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