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