1use 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 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 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
155pub struct EvalLocalContext<'a, 'id> {
157 local_variables: HashMap<SmolStr, Value>,
158 function_arguments: Vec<Value>,
159 pub(crate) component_instance: InstanceRef<'a, 'id>,
160 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 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
188fn 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
197pub 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 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 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 #[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 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 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 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 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 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(s.replace(from.as_str(), to.as_str()).into())
1372 } else {
1373 panic!("Not all arguments are strings");
1374 }
1375 }
1376 BuiltinFunction::KeysToString => {
1377 if arguments.len() != 1 {
1378 panic!("internal error: incorrect argument count to KeysToString")
1379 }
1380 let Value::Keys(keys) = eval_expression(&arguments[0], local_context) else {
1381 panic!("Argument is not of type keys");
1382 };
1383 Value::String(ToSharedString::to_shared_string(&keys))
1384 }
1385 BuiltinFunction::ColorRgbaStruct => {
1386 if arguments.len() != 1 {
1387 panic!("internal error: incorrect argument count to ColorRGBAComponents")
1388 }
1389 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1390 let color = brush.color();
1391 let values = IntoIterator::into_iter([
1392 ("red".to_string(), Value::Number(color.red().into())),
1393 ("green".to_string(), Value::Number(color.green().into())),
1394 ("blue".to_string(), Value::Number(color.blue().into())),
1395 ("alpha".to_string(), Value::Number(color.alpha().into())),
1396 ])
1397 .collect();
1398 Value::Struct(values)
1399 } else {
1400 panic!("First argument not a color");
1401 }
1402 }
1403 BuiltinFunction::ColorHsvaStruct => {
1404 if arguments.len() != 1 {
1405 panic!("internal error: incorrect argument count to ColorHSVAComponents")
1406 }
1407 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1408 let color = brush.color().to_hsva();
1409 let values = IntoIterator::into_iter([
1410 ("hue".to_string(), Value::Number(color.hue.into())),
1411 ("saturation".to_string(), Value::Number(color.saturation.into())),
1412 ("value".to_string(), Value::Number(color.value.into())),
1413 ("alpha".to_string(), Value::Number(color.alpha.into())),
1414 ])
1415 .collect();
1416 Value::Struct(values)
1417 } else {
1418 panic!("First argument not a color");
1419 }
1420 }
1421 BuiltinFunction::ColorOklchStruct => {
1422 if arguments.len() != 1 {
1423 panic!("internal error: incorrect argument count to ColorOklchStruct")
1424 }
1425 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1426 let color = brush.color().to_oklch();
1427 let values = IntoIterator::into_iter([
1428 ("lightness".to_string(), Value::Number(color.lightness.into())),
1429 ("chroma".to_string(), Value::Number(color.chroma.into())),
1430 ("hue".to_string(), Value::Number(color.hue.into())),
1431 ("alpha".to_string(), Value::Number(color.alpha.into())),
1432 ])
1433 .collect();
1434 Value::Struct(values)
1435 } else {
1436 panic!("First argument not a color");
1437 }
1438 }
1439 BuiltinFunction::ColorBrighter => {
1440 if arguments.len() != 2 {
1441 panic!("internal error: incorrect argument count to ColorBrighter")
1442 }
1443 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1444 if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1445 brush.brighter(factor as _).into()
1446 } else {
1447 panic!("Second argument not a number");
1448 }
1449 } else {
1450 panic!("First argument not a color");
1451 }
1452 }
1453 BuiltinFunction::ColorDarker => {
1454 if arguments.len() != 2 {
1455 panic!("internal error: incorrect argument count to ColorDarker")
1456 }
1457 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1458 if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1459 brush.darker(factor as _).into()
1460 } else {
1461 panic!("Second argument not a number");
1462 }
1463 } else {
1464 panic!("First argument not a color");
1465 }
1466 }
1467 BuiltinFunction::ColorTransparentize => {
1468 if arguments.len() != 2 {
1469 panic!("internal error: incorrect argument count to ColorFaded")
1470 }
1471 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1472 if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1473 brush.transparentize(factor as _).into()
1474 } else {
1475 panic!("Second argument not a number");
1476 }
1477 } else {
1478 panic!("First argument not a color");
1479 }
1480 }
1481 BuiltinFunction::ColorMix => {
1482 if arguments.len() != 3 {
1483 panic!("internal error: incorrect argument count to ColorMix")
1484 }
1485
1486 let arg0 = eval_expression(&arguments[0], local_context);
1487 let arg1 = eval_expression(&arguments[1], local_context);
1488 let arg2 = eval_expression(&arguments[2], local_context);
1489
1490 if !matches!(arg0, Value::Brush(Brush::SolidColor(_))) {
1491 panic!("First argument not a color");
1492 }
1493 if !matches!(arg1, Value::Brush(Brush::SolidColor(_))) {
1494 panic!("Second argument not a color");
1495 }
1496 if !matches!(arg2, Value::Number(_)) {
1497 panic!("Third argument not a number");
1498 }
1499
1500 let (
1501 Value::Brush(Brush::SolidColor(color_a)),
1502 Value::Brush(Brush::SolidColor(color_b)),
1503 Value::Number(factor),
1504 ) = (arg0, arg1, arg2)
1505 else {
1506 unreachable!()
1507 };
1508
1509 color_a.mix(&color_b, factor as _).into()
1510 }
1511 BuiltinFunction::ColorWithAlpha => {
1512 if arguments.len() != 2 {
1513 panic!("internal error: incorrect argument count to ColorWithAlpha")
1514 }
1515 if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1516 if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1517 brush.with_alpha(factor as _).into()
1518 } else {
1519 panic!("Second argument not a number");
1520 }
1521 } else {
1522 panic!("First argument not a color");
1523 }
1524 }
1525 BuiltinFunction::ImageSize => {
1526 if arguments.len() != 1 {
1527 panic!("internal error: incorrect argument count to ImageSize")
1528 }
1529 if let Value::Image(img) = eval_expression(&arguments[0], local_context) {
1530 let size = img.size();
1531 let values = IntoIterator::into_iter([
1532 ("width".to_string(), Value::Number(size.width as f64)),
1533 ("height".to_string(), Value::Number(size.height as f64)),
1534 ])
1535 .collect();
1536 Value::Struct(values)
1537 } else {
1538 panic!("First argument not an image");
1539 }
1540 }
1541 BuiltinFunction::ArrayLength => {
1542 if arguments.len() != 1 {
1543 panic!("internal error: incorrect argument count to ArrayLength")
1544 }
1545 match eval_expression(&arguments[0], local_context) {
1546 Value::Model(model) => {
1547 model.model_tracker().track_row_count_changes();
1548 Value::Number(model.row_count() as f64)
1549 }
1550 _ => {
1551 panic!("First argument not an array: {:?}", arguments[0]);
1552 }
1553 }
1554 }
1555 BuiltinFunction::ArrayPush => {
1556 if arguments.len() != 2 {
1557 panic!("internal error: incorrect argument count to ArrayPush")
1558 }
1559
1560 let model = match eval_expression(&arguments[0], local_context) {
1561 Value::Model(m) => m,
1562 _ => panic!("First argument not an array: {:?}", arguments[0]),
1563 };
1564 let value = eval_expression(&arguments[1], local_context);
1565
1566 model.push_row(value);
1567
1568 Value::Void
1569 }
1570 BuiltinFunction::ArrayRemove => {
1571 if arguments.len() != 2 {
1572 panic!("internal error: incorrect argument count to ArrayRemove")
1573 }
1574
1575 let model = match eval_expression(&arguments[0], local_context) {
1576 Value::Model(m) => m,
1577 _ => panic!("First argument not an array: {:?}", arguments[0]),
1578 };
1579 let index = match eval_expression(&arguments[1], local_context) {
1580 Value::Number(i) => i,
1581 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1582 };
1583
1584 model.remove_row(index as isize);
1585
1586 Value::Void
1587 }
1588
1589 BuiltinFunction::ArrayInsert => {
1590 if arguments.len() != 3 {
1591 panic!("internal error: incorrect argument count to ArrayInsert")
1592 }
1593
1594 let model = match eval_expression(&arguments[0], local_context) {
1595 Value::Model(m) => m,
1596 _ => panic!("First argument not an array: {:?}", arguments[0]),
1597 };
1598 let index = match eval_expression(&arguments[1], local_context) {
1599 Value::Number(i) => i,
1600 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1601 };
1602
1603 let value = eval_expression(&arguments[2], local_context);
1604 model.insert_row(index as isize, value);
1605
1606 Value::Void
1607 }
1608 BuiltinFunction::Rgb => {
1609 let r: i32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1610 let g: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1611 let b: i32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1612 let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1613 let r: u8 = r.clamp(0, 255) as u8;
1614 let g: u8 = g.clamp(0, 255) as u8;
1615 let b: u8 = b.clamp(0, 255) as u8;
1616 let a: u8 = (255. * a).clamp(0., 255.) as u8;
1617 Value::Brush(Brush::SolidColor(Color::from_argb_u8(a, r, g, b)))
1618 }
1619 BuiltinFunction::Hsv => {
1620 let h: f32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1621 let s: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1622 let v: f32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1623 let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1624 let a = (1. * a).clamp(0., 1.);
1625 Value::Brush(Brush::SolidColor(Color::from_hsva(h, s, v, a)))
1626 }
1627 BuiltinFunction::Oklch => {
1628 let l: f32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1629 let c: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1630 let h: f32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1631 let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1632 let l = l.clamp(0., 1.);
1633 let c = c.max(0.);
1634 let a = a.clamp(0., 1.);
1635 Value::Brush(Brush::SolidColor(Color::from_oklch(l, c, h, a)))
1636 }
1637 BuiltinFunction::ColorScheme => {
1638 let root_weak =
1639 vtable::VWeak::into_dyn(local_context.component_instance.root_weak().clone());
1640 let root = root_weak.upgrade().unwrap();
1641 corelib::window::context_for_root(&root)
1642 .map_or(corelib::items::ColorScheme::Unknown, |ctx| ctx.color_scheme(Some(&root)))
1643 .into()
1644 }
1645 BuiltinFunction::AccentColor => {
1646 let root_weak =
1647 vtable::VWeak::into_dyn(local_context.component_instance.root_weak().clone());
1648 let root = root_weak.upgrade().unwrap();
1649 Value::Brush(corelib::Brush::SolidColor(corelib::window::accent_color(&root)))
1650 }
1651 BuiltinFunction::SupportsNativeMenuBar => local_context
1652 .component_instance
1653 .window_adapter()
1654 .internal(corelib::InternalToken)
1655 .is_some_and(|x| x.supports_native_menu_bar())
1656 .into(),
1657 BuiltinFunction::SetupMenuBar => {
1658 let component = local_context.component_instance;
1659 let [
1660 Expression::PropertyReference(entries_nr),
1661 Expression::PropertyReference(sub_menu_nr),
1662 Expression::PropertyReference(activated_nr),
1663 Expression::ElementReference(item_tree_root),
1664 Expression::BoolLiteral(no_native),
1665 condition,
1666 visible,
1667 ..,
1668 ] = arguments
1669 else {
1670 panic!("internal error: incorrect argument count to SetupMenuBar")
1671 };
1672
1673 let menu_item_tree =
1674 item_tree_root.upgrade().unwrap().borrow().enclosing_component.upgrade().unwrap();
1675 let menu_item_tree = crate::dynamic_item_tree::make_menu_item_tree(
1676 &menu_item_tree,
1677 &component,
1678 Some(condition),
1679 Some(visible),
1680 );
1681
1682 let window_adapter = component.window_adapter();
1683 let window_inner = WindowInner::from_pub(window_adapter.window());
1684 let menubar = vtable::VRc::into_dyn(vtable::VRc::clone(&menu_item_tree));
1685 window_inner.setup_menubar_shortcuts(vtable::VRc::clone(&menubar));
1686
1687 if !no_native && window_inner.supports_native_menu_bar() {
1688 window_inner.setup_menubar(menubar);
1689 return Value::Void;
1690 }
1691
1692 let (entries, sub_menu, activated) = menu_item_tree_properties(menu_item_tree);
1693
1694 assert_eq!(
1695 entries_nr.element().borrow().id,
1696 component.description.original.root_element.borrow().id,
1697 "entries need to be in the main element"
1698 );
1699 local_context
1700 .component_instance
1701 .description
1702 .set_binding(component.borrow(), entries_nr.name(), entries)
1703 .unwrap();
1704 let i = &ComponentInstance::InstanceRef(local_context.component_instance);
1705 set_callback_handler(i, &sub_menu_nr.element(), sub_menu_nr.name(), sub_menu).unwrap();
1706 set_callback_handler(i, &activated_nr.element(), activated_nr.name(), activated)
1707 .unwrap();
1708
1709 Value::Void
1710 }
1711 BuiltinFunction::SetupSystemTrayIcon => {
1712 let [
1713 Expression::ElementReference(system_tray_elem),
1714 Expression::ElementReference(item_tree_root),
1715 rest @ ..,
1716 ] = arguments
1717 else {
1718 panic!("internal error: incorrect argument count to SetupSystemTrayIcon")
1719 };
1720
1721 let component = local_context.component_instance;
1722 let elem = system_tray_elem.upgrade().unwrap();
1723 generativity::make_guard!(guard);
1724 let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1725 let description = enclosing_component.description;
1726 let item_info = &description.items[elem.borrow().id.as_str()];
1727 let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1728 let item_tree = vtable::VRc::into_dyn(item_comp);
1729 let item_rc = corelib::items::ItemRc::new(item_tree.clone(), item_info.item_index());
1730
1731 let menu_item_tree_component =
1732 item_tree_root.upgrade().unwrap().borrow().enclosing_component.upgrade().unwrap();
1733 let menu_vrc = crate::dynamic_item_tree::make_menu_item_tree(
1734 &menu_item_tree_component,
1735 &enclosing_component,
1736 rest.first(),
1737 None,
1738 );
1739
1740 let system_tray =
1741 item_rc.downcast::<corelib::items::SystemTrayIcon>().expect("SystemTrayIcon item");
1742 system_tray.as_pin_ref().set_menu(&item_rc, vtable::VRc::into_dyn(menu_vrc));
1743
1744 Value::Void
1745 }
1746 BuiltinFunction::MonthDayCount => {
1747 let m: u32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1748 let y: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1749 Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
1750 }
1751 BuiltinFunction::MonthOffset => {
1752 let m: u32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1753 let y: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1754
1755 Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
1756 }
1757 BuiltinFunction::FormatDate => {
1758 let f: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1759 let d: u32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1760 let m: u32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1761 let y: i32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1762
1763 Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
1764 }
1765 BuiltinFunction::DateNow => Value::Model(ModelRc::new(VecModel::from(
1766 i_slint_core::date_time::date_now()
1767 .into_iter()
1768 .map(|x| Value::Number(x as f64))
1769 .collect::<Vec<_>>(),
1770 ))),
1771 BuiltinFunction::ValidDate => {
1772 let d: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1773 let f: SharedString = eval_expression(&arguments[1], local_context).try_into().unwrap();
1774 Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
1775 }
1776 BuiltinFunction::ParseDate => {
1777 let d: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1778 let f: SharedString = eval_expression(&arguments[1], local_context).try_into().unwrap();
1779
1780 Value::Model(ModelRc::new(
1781 i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
1782 .map(|x| {
1783 VecModel::from(
1784 x.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>(),
1785 )
1786 })
1787 .unwrap_or_default(),
1788 ))
1789 }
1790 BuiltinFunction::TextInputFocused => Value::Bool(
1791 local_context.component_instance.access_window(|window| window.text_input_focused())
1792 as _,
1793 ),
1794 BuiltinFunction::SetTextInputFocused => {
1795 local_context.component_instance.access_window(|window| {
1796 window.set_text_input_focused(
1797 eval_expression(&arguments[0], local_context).try_into().unwrap(),
1798 )
1799 });
1800 Value::Void
1801 }
1802 BuiltinFunction::ImplicitLayoutInfo(orient) => {
1803 let component = local_context.component_instance;
1804 if let [Expression::ElementReference(item), constraint_expr] = arguments {
1805 generativity::make_guard!(guard);
1806
1807 let constraint: f32 =
1808 eval_expression(constraint_expr, local_context).try_into().unwrap_or(-1.);
1809
1810 let item = item.upgrade().unwrap();
1811 let enclosing_component = enclosing_component_for_element(&item, component, guard);
1812 let description = enclosing_component.description;
1813 let item_info = &description.items[item.borrow().id.as_str()];
1814 let item_ref =
1815 unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1816 let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1817 let window_adapter = component.window_adapter();
1818 item_ref
1819 .as_ref()
1820 .layout_info(
1821 crate::eval_layout::to_runtime(orient),
1822 constraint,
1823 &window_adapter,
1824 &ItemRc::new(vtable::VRc::into_dyn(item_comp), item_info.item_index()),
1825 )
1826 .into()
1827 } else {
1828 panic!("internal error: incorrect arguments to ImplicitLayoutInfo {arguments:?}");
1829 }
1830 }
1831 BuiltinFunction::ItemAbsolutePosition => {
1832 if arguments.len() != 1 {
1833 panic!("internal error: incorrect argument count to ItemAbsolutePosition")
1834 }
1835
1836 let component = local_context.component_instance;
1837
1838 if let Expression::ElementReference(item) = &arguments[0] {
1839 let item_rc = item_rc_for_element(item, component);
1840
1841 item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into()
1844 } else {
1845 panic!("internal error: argument to SetFocusItem must be an element")
1846 }
1847 }
1848 BuiltinFunction::RegisterCustomFontByPath => {
1849 if arguments.len() != 1 {
1850 panic!("internal error: incorrect argument count to RegisterCustomFontByPath")
1851 }
1852 let component = local_context.component_instance;
1853 if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1854 let result = component.try_window_adapter().map_err(|e| e.to_string()).and_then(
1858 |window_adapter| {
1859 window_adapter
1860 .renderer()
1861 .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
1862 .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
1863 },
1864 );
1865 if let Err(err) = result {
1866 corelib::debug_log!("{err}");
1867 }
1868 Value::Void
1869 } else {
1870 panic!("Argument not a string");
1871 }
1872 }
1873 BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
1874 unimplemented!()
1875 }
1876 BuiltinFunction::Translate => {
1877 let original: SharedString =
1878 eval_expression(&arguments[0], local_context).try_into().unwrap();
1879 let context: SharedString =
1880 eval_expression(&arguments[1], local_context).try_into().unwrap();
1881 let domain: SharedString =
1882 eval_expression(&arguments[2], local_context).try_into().unwrap();
1883 let args = eval_expression(&arguments[3], local_context);
1884 let Value::Model(args) = args else { panic!("Args to translate not a model {args:?}") };
1885 struct StringModelWrapper(ModelRc<Value>);
1886 impl corelib::translations::FormatArgs for StringModelWrapper {
1887 type Output<'a> = SharedString;
1888 fn from_index(&self, index: usize) -> Option<SharedString> {
1889 self.0.row_data(index).map(|x| x.try_into().unwrap())
1890 }
1891 }
1892 Value::String(corelib::translations::translate(
1893 &original,
1894 &context,
1895 &domain,
1896 &StringModelWrapper(args),
1897 eval_expression(&arguments[4], local_context).try_into().unwrap(),
1898 &SharedString::try_from(eval_expression(&arguments[5], local_context)).unwrap(),
1899 ))
1900 }
1901 BuiltinFunction::Use24HourFormat => Value::Bool(corelib::date_time::use_24_hour_format()),
1902 BuiltinFunction::UpdateTimers => {
1903 crate::dynamic_item_tree::update_timers(local_context.component_instance);
1904 Value::Void
1905 }
1906 BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
1907 BuiltinFunction::StartTimer => unreachable!(),
1909 BuiltinFunction::StopTimer => unreachable!(),
1910 BuiltinFunction::RestartTimer => {
1911 if let [Expression::ElementReference(timer_element)] = arguments {
1912 crate::dynamic_item_tree::restart_timer(
1913 timer_element.clone(),
1914 local_context.component_instance,
1915 );
1916
1917 Value::Void
1918 } else {
1919 panic!("internal error: argument to RestartTimer must be an element")
1920 }
1921 }
1922 BuiltinFunction::OpenUrl => {
1923 let url: SharedString =
1924 eval_expression(&arguments[0], local_context).try_into().unwrap();
1925 let window_adapter = local_context.component_instance.window_adapter();
1926 Value::Bool(corelib::open_url(&url, window_adapter.window()).is_ok())
1927 }
1928 BuiltinFunction::MacosBringAllWindowsToFront => {
1929 corelib::macos_bring_all_windows_to_front();
1930 Value::Void
1931 }
1932 BuiltinFunction::ParseMarkdown => {
1933 let format_string: SharedString =
1934 eval_expression(&arguments[0], local_context).try_into().unwrap();
1935 let args: ModelRc<corelib::styled_text::StyledText> =
1936 eval_expression(&arguments[1], local_context).try_into().unwrap();
1937 Value::StyledText(corelib::styled_text::parse_markdown(
1938 &format_string,
1939 &args.iter().collect::<Vec<_>>(),
1940 ))
1941 }
1942 BuiltinFunction::StringToStyledText => {
1943 let string: SharedString =
1944 eval_expression(&arguments[0], local_context).try_into().unwrap();
1945 Value::StyledText(corelib::styled_text::string_to_styled_text(string.to_string()))
1946 }
1947 BuiltinFunction::ColorToStyledText => {
1948 let color: corelib::Color =
1949 eval_expression(&arguments[0], local_context).try_into().unwrap();
1950 Value::StyledText(corelib::styled_text::color_to_styled_text(color))
1951 }
1952 BuiltinFunction::PathPointAt => {
1953 let component = local_context.component_instance;
1954
1955 if let Expression::ElementReference(item) = &arguments[0] {
1956 let item_rc = item_rc_for_element(item, component);
1957
1958 let t: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1959
1960 item_rc
1961 .downcast::<corelib::items::Path>()
1962 .unwrap()
1963 .as_pin_ref()
1964 .point_at(&item_rc, t)
1965 .to_untyped()
1966 .into()
1967 } else {
1968 panic!("internal error: argument to PathPointAt must be an element")
1969 }
1970 }
1971 BuiltinFunction::PathAngleAt => {
1972 let component = local_context.component_instance;
1973
1974 if let Expression::ElementReference(item) = &arguments[0] {
1975 let item_rc = item_rc_for_element(item, component);
1976
1977 let t: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1978
1979 item_rc
1980 .downcast::<corelib::items::Path>()
1981 .unwrap()
1982 .as_pin_ref()
1983 .angle_at(&item_rc, t)
1984 .into()
1985 } else {
1986 panic!("internal error: argument to PathAngleAt must be an element")
1987 }
1988 }
1989 BuiltinFunction::ArrayAny | BuiltinFunction::ArrayAll => {
1990 let is_all = matches!(f, BuiltinFunction::ArrayAll);
1991 let model: ModelRc<Value> =
1992 eval_expression(&arguments[0], local_context).try_into().unwrap();
1993 let Expression::Closure { arg_name, expression } = &arguments[1] else {
1994 panic!("internal error: Array.any/all expects a closure as second argument")
1995 };
1996 model.model_tracker().track_row_count_changes();
1997 for row in 0..model.row_count() {
1998 let x = model.row_data_tracked(row).unwrap_or_default();
1999 let previous = local_context.local_variables.insert(arg_name.clone(), x);
2000 let result: bool = eval_expression(expression, local_context).try_into().unwrap();
2001 match previous {
2002 Some(prev) => {
2003 local_context.local_variables.insert(arg_name.clone(), prev);
2004 }
2005 None => {
2006 local_context.local_variables.remove(arg_name);
2007 }
2008 }
2009 if result != is_all {
2011 return Value::Bool(!is_all);
2012 }
2013 }
2014 Value::Bool(is_all)
2015 }
2016 }
2017}
2018
2019fn item_rc_for_element(
2020 item: &Weak<RefCell<Element>>,
2021 component: InstanceRef,
2022) -> corelib::items::ItemRc {
2023 generativity::make_guard!(guard);
2024 let item = item.upgrade().unwrap();
2025 let enclosing_component = enclosing_component_for_element(&item, component, guard);
2026 let description = enclosing_component.description;
2027
2028 let item_info = &description.items[item.borrow().id.as_str()];
2029
2030 let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
2031
2032 corelib::items::ItemRc::new(vtable::VRc::into_dyn(item_comp), item_info.item_index())
2033}
2034
2035fn call_item_member_function(nr: &NamedReference, local_context: &mut EvalLocalContext) -> Value {
2036 let component = local_context.component_instance;
2037 let elem = nr.element();
2038 let name = nr.name().as_str();
2039 generativity::make_guard!(guard);
2040 let enclosing_component = enclosing_component_for_element(&elem, component, guard);
2041 let description = enclosing_component.description;
2042 let item_info = &description.items[elem.borrow().id.as_str()];
2043 let item_ref = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2044
2045 let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
2046 let item_rc =
2047 corelib::items::ItemRc::new(vtable::VRc::into_dyn(item_comp), item_info.item_index());
2048
2049 let window_adapter = component.window_adapter();
2050
2051 if let Some(textinput) = ItemRef::downcast_pin::<corelib::items::TextInput>(item_ref) {
2053 match name {
2054 "select-all" => textinput.select_all(&window_adapter, &item_rc),
2055 "clear-selection" => textinput.clear_selection(&window_adapter, &item_rc),
2056 "cut" => textinput.cut(&window_adapter, &item_rc),
2057 "copy" => textinput.copy(&window_adapter, &item_rc),
2058 "paste" => textinput.paste(&window_adapter, &item_rc),
2059 "undo" => textinput.undo(&window_adapter, &item_rc),
2060 "redo" => textinput.redo(&window_adapter, &item_rc),
2061 _ => panic!("internal: Unknown member function {name} called on TextInput"),
2062 }
2063 } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::SwipeGestureHandler>(item_ref) {
2064 match name {
2065 "cancel" => s.cancel(&window_adapter, &item_rc),
2066 _ => panic!("internal: Unknown member function {name} called on SwipeGestureHandler"),
2067 }
2068 } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::ContextMenu>(item_ref) {
2069 match name {
2070 "close" => s.close(&window_adapter, &item_rc),
2071 "is-open" => return Value::Bool(s.is_open(&window_adapter, &item_rc)),
2072 _ => {
2073 panic!("internal: Unknown member function {name} called on ContextMenu")
2074 }
2075 }
2076 } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::WindowItem>(item_ref) {
2077 match name {
2078 "hide" => s.hide(&window_adapter, &item_rc),
2079 "close" => return Value::Bool(s.close(&window_adapter, &item_rc)),
2080 _ => {
2081 panic!("internal: Unknown member function {name} called on WindowItem")
2082 }
2083 }
2084 } else {
2085 panic!(
2086 "internal error: member function {name} called on element that doesn't have it: {}",
2087 elem.borrow().original_name()
2088 )
2089 }
2090
2091 Value::Void
2092}
2093
2094fn eval_assignment(lhs: &Expression, op: char, rhs: Value, local_context: &mut EvalLocalContext) {
2095 let eval = |lhs| match (lhs, &rhs, op) {
2096 (Value::String(ref mut a), Value::String(b), '+') => {
2097 a.push_str(b.as_str());
2098 Value::String(a.clone())
2099 }
2100 (Value::Number(a), Value::Number(b), '+') => Value::Number(a + b),
2101 (Value::Number(a), Value::Number(b), '-') => Value::Number(a - b),
2102 (Value::Number(a), Value::Number(b), '/') => Value::Number(a / b),
2103 (Value::Number(a), Value::Number(b), '*') => Value::Number(a * b),
2104 (lhs, rhs, op) => panic!("unsupported {lhs:?} {op} {rhs:?}"),
2105 };
2106 match lhs {
2107 Expression::PropertyReference(nr) => {
2108 let element = nr.element();
2109 generativity::make_guard!(guard);
2110 let enclosing_component = enclosing_component_instance_for_element(
2111 &element,
2112 &ComponentInstance::InstanceRef(local_context.component_instance),
2113 guard,
2114 );
2115
2116 match enclosing_component {
2117 ComponentInstance::InstanceRef(enclosing_component) => {
2118 let value = if op == '=' {
2121 rhs
2122 } else {
2123 eval(load_property(enclosing_component, &element, nr.name()).unwrap())
2124 };
2125 store_property(enclosing_component, &element, nr.name(), value).unwrap();
2126 }
2127 ComponentInstance::GlobalComponent(global) => {
2128 let val = if op == '=' {
2129 rhs
2130 } else {
2131 eval(global.as_ref().get_property(nr.name()).unwrap())
2132 };
2133 global.as_ref().set_property(nr.name(), val).unwrap();
2134 }
2135 }
2136 }
2137 Expression::StructFieldAccess { base, name } => {
2138 if let Value::Struct(mut o) = eval_expression(base, local_context) {
2139 let mut r = o.get_field(name).unwrap().clone();
2140 r = if op == '=' { rhs } else { eval(std::mem::take(&mut r)) };
2141 o.set_field(name.to_string(), r);
2142 eval_assignment(base, '=', Value::Struct(o), local_context)
2143 }
2144 }
2145 Expression::RepeaterModelReference { element } => {
2146 let element = element.upgrade().unwrap();
2147 let component_instance = local_context.component_instance;
2148 generativity::make_guard!(g1);
2149 let enclosing_component =
2150 enclosing_component_for_element(&element, component_instance, g1);
2151 let static_guard =
2154 unsafe { generativity::Guard::new(generativity::Id::<'static>::new()) };
2155 let repeater = crate::dynamic_item_tree::get_repeater_by_name(
2156 enclosing_component,
2157 element.borrow().id.as_str(),
2158 static_guard,
2159 );
2160 repeater.0.model_set_row_data(
2161 eval_expression(
2162 &Expression::RepeaterIndexReference { element: Rc::downgrade(&element) },
2163 local_context,
2164 )
2165 .try_into()
2166 .unwrap(),
2167 if op == '=' {
2168 rhs
2169 } else {
2170 eval(eval_expression(
2171 &Expression::RepeaterModelReference { element: Rc::downgrade(&element) },
2172 local_context,
2173 ))
2174 },
2175 )
2176 }
2177 Expression::ArrayIndex { array, index } => {
2178 let array = eval_expression(array, local_context);
2179 let index = eval_expression(index, local_context);
2180 match (array, index) {
2181 (Value::Model(model), Value::Number(index)) => {
2182 if index >= 0. && (index as usize) < model.row_count() {
2183 let index = index as usize;
2184 if op == '=' {
2185 model.set_row_data(index, rhs);
2186 } else {
2187 model.set_row_data(
2188 index,
2189 eval(
2190 model
2191 .row_data(index)
2192 .unwrap_or_else(|| default_value_for_type(&lhs.ty())),
2193 ),
2194 );
2195 }
2196 }
2197 }
2198 _ => {
2199 eprintln!("Attempting to write into an array that cannot be written");
2200 }
2201 }
2202 }
2203 _ => panic!("typechecking should make sure this was a PropertyReference"),
2204 }
2205}
2206
2207pub fn load_property(component: InstanceRef, element: &ElementRc, name: &str) -> Result<Value, ()> {
2208 load_property_helper(&ComponentInstance::InstanceRef(component), element, name)
2209}
2210
2211fn load_property_helper(
2212 component_instance: &ComponentInstance,
2213 element: &ElementRc,
2214 name: &str,
2215) -> Result<Value, ()> {
2216 generativity::make_guard!(guard);
2217 match enclosing_component_instance_for_element(element, component_instance, guard) {
2218 ComponentInstance::InstanceRef(enclosing_component) => {
2219 let element = element.borrow();
2220 if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2221 {
2222 if let Some(x) = enclosing_component.description.custom_properties.get(name) {
2223 return unsafe {
2224 x.prop.get(Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset)))
2225 };
2226 } else if enclosing_component.description.original.is_global() {
2227 return Err(());
2228 }
2229 };
2230 let item_info = enclosing_component
2231 .description
2232 .items
2233 .get(element.id.as_str())
2234 .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, name));
2235 core::mem::drop(element);
2236 let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2237 Ok(item_info.rtti.properties.get(name).ok_or(())?.get(item))
2238 }
2239 ComponentInstance::GlobalComponent(glob) => glob.as_ref().get_property(name),
2240 }
2241}
2242
2243pub fn store_property(
2244 component_instance: InstanceRef,
2245 element: &ElementRc,
2246 name: &str,
2247 mut value: Value,
2248) -> Result<(), SetPropertyError> {
2249 generativity::make_guard!(guard);
2250 match enclosing_component_instance_for_element(
2251 element,
2252 &ComponentInstance::InstanceRef(component_instance),
2253 guard,
2254 ) {
2255 ComponentInstance::InstanceRef(enclosing_component) => {
2256 let maybe_animation = match element.borrow().binding_cell_including_synthetic(name) {
2257 Some(b) => crate::dynamic_item_tree::animation_for_property(
2258 enclosing_component,
2259 &b.borrow().animation,
2260 ),
2261 None => {
2262 crate::dynamic_item_tree::animation_for_property(enclosing_component, &None)
2263 }
2264 };
2265
2266 let component = element.borrow().enclosing_component.upgrade().unwrap();
2267 if element.borrow().id == component.root_element.borrow().id {
2268 if let Some(x) = enclosing_component.description.custom_properties.get(name) {
2269 if let Some(orig_decl) = enclosing_component
2270 .description
2271 .original
2272 .root_element
2273 .borrow()
2274 .property_declarations
2275 .get(name)
2276 {
2277 if !check_value_type(&mut value, &orig_decl.property_type) {
2279 return Err(SetPropertyError::WrongType);
2280 }
2281 }
2282 unsafe {
2283 let p = Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset));
2284 return x
2285 .prop
2286 .set(p, value, maybe_animation.as_animation())
2287 .map_err(|()| SetPropertyError::WrongType);
2288 }
2289 } else if enclosing_component.description.original.is_global() {
2290 return Err(SetPropertyError::NoSuchProperty);
2291 }
2292 };
2293 let item_info = &enclosing_component.description.items[element.borrow().id.as_str()];
2294 let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2295 let p = &item_info.rtti.properties.get(name).ok_or(SetPropertyError::NoSuchProperty)?;
2296 p.set(item, value, maybe_animation.as_animation())
2297 .map_err(|()| SetPropertyError::WrongType)?;
2298 }
2299 ComponentInstance::GlobalComponent(glob) => {
2300 glob.as_ref().set_property(name, value)?;
2301 }
2302 }
2303 Ok(())
2304}
2305
2306fn check_value_type(value: &mut Value, ty: &Type) -> bool {
2308 match ty {
2309 Type::Void => true,
2310 Type::Invalid
2311 | Type::InferredProperty
2312 | Type::InferredCallback
2313 | Type::Callback { .. }
2314 | Type::Function { .. }
2315 | Type::ElementReference
2316 | Type::Closure => panic!("not valid property type"),
2317 Type::Float32 => matches!(value, Value::Number(_)),
2318 Type::Int32 => matches!(value, Value::Number(_)),
2319 Type::String => matches!(value, Value::String(_)),
2320 Type::Color => matches!(value, Value::Brush(_)),
2321 Type::UnitProduct(_)
2322 | Type::Duration
2323 | Type::PhysicalLength
2324 | Type::LogicalLength
2325 | Type::Rem
2326 | Type::Angle
2327 | Type::Percent => matches!(value, Value::Number(_)),
2328 Type::Image => matches!(value, Value::Image(_)),
2329 Type::Bool => matches!(value, Value::Bool(_)),
2330 Type::Model => {
2331 matches!(value, Value::Model(_) | Value::Bool(_) | Value::Number(_))
2332 }
2333 Type::PathData => matches!(value, Value::PathData(_)),
2334 Type::Easing => matches!(value, Value::EasingCurve(_)),
2335 Type::MouseCursor => matches!(value, Value::MouseCursorInner(_)),
2336 Type::Brush => matches!(value, Value::Brush(_)),
2337 Type::Array(inner) => {
2338 matches!(value, Value::Model(m) if m.iter().all(|mut v| check_value_type(&mut v, inner)))
2339 }
2340 Type::Struct(s) => {
2341 let Value::Struct(str) = value else { return false };
2342 if !str
2343 .0
2344 .iter_mut()
2345 .all(|(k, v)| s.fields.get(k).is_some_and(|ty| check_value_type(v, ty)))
2346 {
2347 return false;
2348 }
2349 for k in s.fields.keys() {
2350 str.0.entry(k.clone()).or_insert_with(|| default_value_for_struct_field(s, k));
2351 }
2352 true
2353 }
2354 Type::Enumeration(en) => {
2355 matches!(value, Value::EnumerationValue(name, _) if name == en.name.as_str())
2356 }
2357 Type::Keys => matches!(value, Value::Keys(_)),
2358 Type::LayoutCache => matches!(value, Value::LayoutCache(_)),
2359 Type::ArrayOfU16 => matches!(value, Value::ArrayOfU16(_)),
2360 Type::ComponentFactory => matches!(value, Value::ComponentFactory(_)),
2361 Type::StyledText => matches!(value, Value::StyledText(_)),
2362 Type::DataTransfer => matches!(value, Value::DataTransfer(_)),
2363 }
2364}
2365
2366pub(crate) fn invoke_callback(
2367 component_instance: &ComponentInstance,
2368 element: &ElementRc,
2369 callback_name: &SmolStr,
2370 args: &[Value],
2371) -> Option<Value> {
2372 generativity::make_guard!(guard);
2373 match enclosing_component_instance_for_element(element, component_instance, guard) {
2374 ComponentInstance::InstanceRef(enclosing_component) => {
2375 let _component_guard = enclosing_component
2378 .self_weak()
2379 .get()
2380 .expect("component self weak must be initialized before invoking callbacks")
2381 .upgrade()
2382 .expect("component must be alive while invoking callbacks");
2383 let description = enclosing_component.description;
2384 let element = element.borrow();
2385 if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2386 {
2387 if let Some(callback_offset) = description.custom_callbacks.get(callback_name) {
2388 if let Some(tracker_offset) = description.callback_trackers.get(callback_name) {
2389 tracker_offset.apply_pin(enclosing_component.instance).get();
2390 }
2391 let callback = callback_offset.apply(&*enclosing_component.instance);
2392 let res = callback.call(args);
2393 return Some(if res != Value::Void {
2394 res
2395 } else if let Some(Type::Callback(callback)) = description
2396 .original
2397 .root_element
2398 .borrow()
2399 .property_declarations
2400 .get(callback_name)
2401 .map(|d| &d.property_type)
2402 {
2403 default_value_for_type(&callback.return_type)
2407 } else {
2408 res
2409 });
2410 } else if enclosing_component.description.original.is_global() {
2411 return None;
2412 }
2413 };
2414 let item_info = &description.items[element.id.as_str()];
2415 let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2416 item_info
2417 .rtti
2418 .callbacks
2419 .get(callback_name.as_str())
2420 .map(|callback| callback.call(item, args))
2421 }
2422 ComponentInstance::GlobalComponent(global) => {
2423 Some(global.as_ref().invoke_callback(callback_name, args).unwrap())
2424 }
2425 }
2426}
2427
2428pub(crate) fn set_callback_handler(
2429 component_instance: &ComponentInstance,
2430 element: &ElementRc,
2431 callback_name: &str,
2432 handler: CallbackHandler,
2433) -> Result<(), ()> {
2434 generativity::make_guard!(guard);
2435 match enclosing_component_instance_for_element(element, component_instance, guard) {
2436 ComponentInstance::InstanceRef(enclosing_component) => {
2437 let description = enclosing_component.description;
2438 let element = element.borrow();
2439 if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2440 {
2441 if let Some(callback_offset) = description.custom_callbacks.get(callback_name) {
2442 let callback = callback_offset.apply(&*enclosing_component.instance);
2443 callback.set_handler(handler);
2444 if let Some(tracker_offset) = description.callback_trackers.get(callback_name) {
2445 tracker_offset.apply_pin(enclosing_component.instance).mark_dirty();
2446 }
2447 return Ok(());
2448 } else if enclosing_component.description.original.is_global() {
2449 return Err(());
2450 }
2451 };
2452 let item_info = &description.items[element.id.as_str()];
2453 let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2454 if let Some(callback) = item_info.rtti.callbacks.get(callback_name) {
2455 callback.set_handler(item, handler);
2456 Ok(())
2457 } else {
2458 Err(())
2459 }
2460 }
2461 ComponentInstance::GlobalComponent(global) => {
2462 global.as_ref().set_callback_handler(callback_name, handler)
2463 }
2464 }
2465}
2466
2467pub(crate) fn call_function(
2471 component_instance: &ComponentInstance,
2472 element: &ElementRc,
2473 function_name: &str,
2474 args: Vec<Value>,
2475) -> Option<Value> {
2476 generativity::make_guard!(guard);
2477 match enclosing_component_instance_for_element(element, component_instance, guard) {
2478 ComponentInstance::InstanceRef(c) => {
2479 let _component_guard = c
2482 .self_weak()
2483 .get()
2484 .expect("component self weak must be initialized before invoking functions")
2485 .upgrade()
2486 .expect("component must be alive while invoking functions");
2487 let mut ctx = EvalLocalContext::from_function_arguments(c, args);
2488 eval_expression(
2489 &element
2490 .borrow()
2491 .binding_cell_including_synthetic(function_name)?
2492 .borrow()
2493 .expression,
2494 &mut ctx,
2495 )
2496 .into()
2497 }
2498 ComponentInstance::GlobalComponent(g) => g.as_ref().eval_function(function_name, args).ok(),
2499 }
2500}
2501
2502pub fn enclosing_component_for_element<'a, 'old_id, 'new_id>(
2505 element: &'a ElementRc,
2506 component: InstanceRef<'a, 'old_id>,
2507 _guard: generativity::Guard<'new_id>,
2508) -> InstanceRef<'a, 'new_id> {
2509 let enclosing = &element.borrow().enclosing_component.upgrade().unwrap();
2510 if Rc::ptr_eq(enclosing, &component.description.original) {
2511 unsafe {
2513 std::mem::transmute::<InstanceRef<'a, 'old_id>, InstanceRef<'a, 'new_id>>(component)
2514 }
2515 } else {
2516 assert!(!enclosing.is_global());
2517 let static_guard = unsafe { generativity::Guard::new(generativity::Id::<'static>::new()) };
2521
2522 let parent_instance = component
2523 .parent_instance(static_guard)
2524 .expect("accessing deleted parent (issue #6426)");
2525 enclosing_component_for_element(element, parent_instance, _guard)
2526 }
2527}
2528
2529pub(crate) fn enclosing_component_instance_for_element<'a, 'new_id>(
2532 element: &'a ElementRc,
2533 component_instance: &ComponentInstance<'a, '_>,
2534 guard: generativity::Guard<'new_id>,
2535) -> ComponentInstance<'a, 'new_id> {
2536 let enclosing = &element.borrow().enclosing_component.upgrade().unwrap();
2537 match component_instance {
2538 ComponentInstance::InstanceRef(component) => {
2539 if enclosing.is_global() && !Rc::ptr_eq(enclosing, &component.description.original) {
2540 ComponentInstance::GlobalComponent(
2541 component
2542 .description
2543 .extra_data_offset
2544 .apply(component.instance.get_ref())
2545 .globals
2546 .get()
2547 .unwrap()
2548 .get(enclosing.root_element.borrow().id.as_str())
2549 .unwrap(),
2550 )
2551 } else {
2552 ComponentInstance::InstanceRef(enclosing_component_for_element(
2553 element, *component, guard,
2554 ))
2555 }
2556 }
2557 ComponentInstance::GlobalComponent(global) => {
2558 ComponentInstance::GlobalComponent(global.clone())
2560 }
2561 }
2562}
2563
2564pub(crate) trait BindingLookup {
2568 fn lookup_binding(
2569 &self,
2570 name: &str,
2571 ) -> Option<&std::cell::RefCell<i_slint_compiler::expression_tree::BindingExpression>>;
2572}
2573impl BindingLookup for i_slint_compiler::object_tree::BindingsMap {
2574 fn lookup_binding(
2575 &self,
2576 name: &str,
2577 ) -> Option<&std::cell::RefCell<i_slint_compiler::expression_tree::BindingExpression>> {
2578 self.get(name)
2579 }
2580}
2581impl BindingLookup for i_slint_compiler::object_tree::Bindings {
2582 fn lookup_binding(
2583 &self,
2584 name: &str,
2585 ) -> Option<&std::cell::RefCell<i_slint_compiler::expression_tree::BindingExpression>> {
2586 self.binding_cell_including_synthetic(name)
2587 }
2588}
2589
2590pub fn new_struct_with_bindings<ElementType: 'static + Default + corelib::rtti::BuiltinItem>(
2591 bindings: &impl BindingLookup,
2592 local_context: &mut EvalLocalContext,
2593) -> ElementType {
2594 let mut element = ElementType::default();
2595 for (prop, info) in ElementType::fields::<Value>().into_iter() {
2596 if let Some(binding) = bindings.lookup_binding(prop) {
2597 let value = eval_expression(&binding.borrow(), local_context);
2598 info.set_field(&mut element, value).unwrap();
2599 }
2600 }
2601 element
2602}
2603
2604fn convert_from_lyon_path<'a>(
2605 events_it: impl IntoIterator<Item = &'a i_slint_compiler::expression_tree::Expression>,
2606 points_it: impl IntoIterator<Item = &'a i_slint_compiler::expression_tree::Expression>,
2607 local_context: &mut EvalLocalContext,
2608) -> PathData {
2609 let events = events_it
2610 .into_iter()
2611 .map(|event_expr| eval_expression(event_expr, local_context).try_into().unwrap())
2612 .collect::<SharedVector<_>>();
2613
2614 let points = points_it
2615 .into_iter()
2616 .map(|point_expr| {
2617 let point_value = eval_expression(point_expr, local_context);
2618 let point_struct: Struct = point_value.try_into().unwrap();
2619 let mut point = i_slint_core::graphics::Point::default();
2620 let x: f64 = point_struct.get_field("x").unwrap().clone().try_into().unwrap();
2621 let y: f64 = point_struct.get_field("y").unwrap().clone().try_into().unwrap();
2622 point.x = x as _;
2623 point.y = y as _;
2624 point
2625 })
2626 .collect::<SharedVector<_>>();
2627
2628 PathData::Events(events, points)
2629}
2630
2631pub fn convert_path(path: &ExprPath, local_context: &mut EvalLocalContext) -> PathData {
2632 match path {
2633 ExprPath::Elements(elements) => PathData::Elements(
2634 elements
2635 .iter()
2636 .map(|element| convert_path_element(element, local_context))
2637 .collect::<SharedVector<PathElement>>(),
2638 ),
2639 ExprPath::Events(events, points) => {
2640 convert_from_lyon_path(events.iter(), points.iter(), local_context)
2641 }
2642 ExprPath::Commands(commands) => {
2643 if let Value::String(commands) = eval_expression(commands, local_context) {
2644 PathData::Commands(commands)
2645 } else {
2646 panic!("binding to path commands does not evaluate to string");
2647 }
2648 }
2649 }
2650}
2651
2652fn convert_path_element(
2653 expr_element: &ExprPathElement,
2654 local_context: &mut EvalLocalContext,
2655) -> PathElement {
2656 match expr_element.element_type.native_class.class_name.as_str() {
2657 "MoveTo" => {
2658 PathElement::MoveTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2659 }
2660 "LineTo" => {
2661 PathElement::LineTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2662 }
2663 "ArcTo" => {
2664 PathElement::ArcTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2665 }
2666 "CubicTo" => {
2667 PathElement::CubicTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2668 }
2669 "QuadraticTo" => PathElement::QuadraticTo(new_struct_with_bindings(
2670 &expr_element.bindings,
2671 local_context,
2672 )),
2673 "Close" => PathElement::Close,
2674 _ => panic!(
2675 "Cannot create unsupported path element {}",
2676 expr_element.element_type.native_class.class_name
2677 ),
2678 }
2679}
2680
2681pub fn default_value_for_type(ty: &Type) -> Value {
2683 match ty {
2684 Type::Float32 | Type::Int32 => Value::Number(0.),
2685 Type::String => Value::String(Default::default()),
2686 Type::Color | Type::Brush => Value::Brush(Default::default()),
2687 Type::Duration | Type::Angle | Type::PhysicalLength | Type::LogicalLength | Type::Rem => {
2688 Value::Number(0.)
2689 }
2690 Type::Image => Value::Image(Default::default()),
2691 Type::Bool => Value::Bool(false),
2692 Type::Callback { .. } => Value::Void,
2693 Type::Struct(s) => Value::Struct(
2694 s.fields
2695 .keys()
2696 .map(|n| (n.to_string(), default_value_for_struct_field(s, n)))
2697 .collect::<Struct>(),
2698 ),
2699 Type::Array(_) | Type::Model => Value::Model(Default::default()),
2700 Type::Percent => Value::Number(0.),
2701 Type::Enumeration(e) => Value::EnumerationValue(
2702 e.name.to_string(),
2703 e.values.get(e.default_value).unwrap().to_string(),
2704 ),
2705 Type::Keys => Value::Keys(Default::default()),
2706 Type::DataTransfer => Value::DataTransfer(Default::default()),
2707 Type::Easing => Value::EasingCurve(Default::default()),
2708 Type::MouseCursor => Value::MouseCursorInner(Default::default()),
2709 Type::Void | Type::Invalid => Value::Void,
2710 Type::UnitProduct(_) => Value::Number(0.),
2711 Type::PathData => Value::PathData(Default::default()),
2712 Type::LayoutCache => Value::LayoutCache(Default::default()),
2713 Type::ArrayOfU16 => Value::ArrayOfU16(Default::default()),
2714 Type::ComponentFactory => Value::ComponentFactory(Default::default()),
2715 Type::InferredProperty
2716 | Type::InferredCallback
2717 | Type::ElementReference
2718 | Type::Function { .. }
2719 | Type::Closure => {
2720 panic!("There can't be such property")
2721 }
2722 Type::StyledText => Value::StyledText(Default::default()),
2723 }
2724}
2725
2726pub fn default_value_for_struct_field(
2730 s: &i_slint_compiler::langtype::Struct,
2731 field_name: &str,
2732) -> Value {
2733 match s.field_defaults.get(field_name) {
2734 Some(expr) => eval_constant_expression(expr),
2735 None => default_value_for_type(
2736 s.fields.get(field_name).expect("default value requested for unknown struct field"),
2737 ),
2738 }
2739}
2740
2741fn cast_value(value: Value, to: &Type) -> Value {
2743 match (value, to) {
2744 (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
2745 (Value::Number(n), Type::String) => {
2746 Value::String(i_slint_core::string::shared_string_from_number(n))
2747 }
2748 (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
2749 (Value::Brush(brush), Type::Color) => brush.color().into(),
2750 (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
2751 (v, _) => v,
2752 }
2753}
2754
2755fn eval_unary_op(sub: Value, op: char) -> Result<Value, Value> {
2758 match (sub, op) {
2759 (Value::Number(a), '+') => Ok(Value::Number(a)),
2760 (Value::Number(a), '-') => Ok(Value::Number(-a)),
2761 (Value::Bool(a), '!') => Ok(Value::Bool(!a)),
2762 (sub, _) => Err(sub),
2763 }
2764}
2765
2766fn eval_constant_expression(expr: &ConstantExpression) -> Value {
2770 match expr {
2771 ConstantExpression::StringLiteral(s) => Value::String(s.as_str().into()),
2772 ConstantExpression::NumberLiteral(n, _unit) => Value::Number(*n),
2773 ConstantExpression::BoolLiteral(b) => Value::Bool(*b),
2774 ConstantExpression::EnumerationValue(value) => {
2775 Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
2776 }
2777 ConstantExpression::Cast { from, to } => cast_value(eval_constant_expression(from), to),
2778 ConstantExpression::UnaryOp { sub, op } => {
2779 eval_unary_op(eval_constant_expression(sub), *op)
2781 .unwrap_or_else(|sub| panic!("unsupported {op} {sub:?}"))
2782 }
2783 ConstantExpression::Struct { values, .. } => Value::Struct(
2784 values
2785 .iter()
2786 .map(|(k, v)| (k.to_string(), eval_constant_expression(v)))
2787 .collect::<Struct>(),
2788 ),
2789 ConstantExpression::Array { values, .. } => {
2790 Value::Model(ModelRc::new(corelib::model::SharedVectorModel::from(
2791 values.iter().map(eval_constant_expression).collect::<SharedVector<_>>(),
2792 )))
2793 }
2794 }
2795}
2796
2797fn menu_item_tree_properties(
2798 context_menu_item_tree: vtable::VRc<i_slint_core::menus::MenuVTable, MenuFromItemTree>,
2799) -> (Box<dyn Fn() -> Value>, CallbackHandler, CallbackHandler) {
2800 let context_menu_item_tree_ = context_menu_item_tree.clone();
2801 let entries = Box::new(move || {
2802 let mut entries = SharedVector::default();
2803 context_menu_item_tree_.sub_menu(None, &mut entries);
2804 Value::Model(ModelRc::new(VecModel::from(
2805 entries.into_iter().map(Value::from).collect::<Vec<_>>(),
2806 )))
2807 });
2808 let context_menu_item_tree_ = context_menu_item_tree.clone();
2809 let sub_menu = Box::new(move |args: &[Value]| -> Value {
2810 let mut entries = SharedVector::default();
2811 context_menu_item_tree_.sub_menu(Some(&args[0].clone().try_into().unwrap()), &mut entries);
2812 Value::Model(ModelRc::new(VecModel::from(
2813 entries.into_iter().map(Value::from).collect::<Vec<_>>(),
2814 )))
2815 });
2816 let activated = Box::new(move |args: &[Value]| -> Value {
2817 context_menu_item_tree.activate(&args[0].clone().try_into().unwrap());
2818 Value::Void
2819 });
2820 (entries, sub_menu, activated)
2821}