1use crate::Value;
11use crate::globals::{GlobalInstance, GlobalStorage};
12use crate::instance::SubComponentInstance;
13use i_slint_compiler::expression_tree::{BuiltinFunction, MinMaxOp};
14use i_slint_compiler::langtype::{ConstantExpression, Type};
15use i_slint_compiler::llr::{self, Expression, LocalMemberIndex, MemberReference};
16use i_slint_core::graphics::{
17 Brush, ConicGradientBrush, GradientStop, LinearGradientBrush, RadialGradientBrush,
18};
19use i_slint_core::model::{Model, ModelExt, ModelRc, SharedVectorModel};
20use i_slint_core::{Color, SharedString, SharedVector};
21use smol_str::SmolStr;
22use std::collections::HashMap;
23use std::pin::Pin;
24use std::rc::{Rc, Weak};
25
26pub struct EvalContext {
28 pub current: Option<Pin<Rc<SubComponentInstance>>>,
31 pub compilation_unit: Rc<llr::CompilationUnit>,
34 pub globals: Weak<GlobalStorage>,
36 pub locals: HashMap<SmolStr, Value>,
38 pub function_arguments: Vec<Value>,
40 pub function_arg_types: Vec<Type>,
43 pub return_value: Option<Value>,
45}
46
47impl EvalContext {
48 pub fn new(current: Pin<Rc<SubComponentInstance>>) -> Self {
51 let globals = current
52 .root
53 .get()
54 .and_then(|w| w.upgrade())
55 .map(|inst| Rc::downgrade(&inst.globals))
56 .unwrap_or_default();
57 Self {
58 compilation_unit: current.compilation_unit.clone(),
59 current: Some(current),
60 globals,
61 locals: HashMap::new(),
62 function_arguments: Vec::new(),
63 function_arg_types: Vec::new(),
64 return_value: None,
65 }
66 }
67
68 pub fn for_global(globals: Weak<GlobalStorage>, cu: Rc<llr::CompilationUnit>) -> Self {
70 Self {
71 current: None,
72 compilation_unit: cu,
73 globals,
74 locals: HashMap::new(),
75 function_arguments: Vec::new(),
76 function_arg_types: Vec::new(),
77 return_value: None,
78 }
79 }
80
81 pub fn with_arguments(current: Pin<Rc<SubComponentInstance>>, args: Vec<Value>) -> Self {
82 let mut ctx = Self::new(current);
83 ctx.function_arguments = args;
84 ctx
85 }
86}
87
88fn root_instance(
91 ctx: &EvalContext,
92) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
93 match ctx.current.as_ref() {
94 Some(c) => c.root.get()?.upgrade(),
95 None => ctx.globals.upgrade()?.root.get()?.upgrade(),
96 }
97}
98
99pub(crate) fn walk_parent(
101 start: &Pin<Rc<SubComponentInstance>>,
102 level: usize,
103) -> Pin<Rc<SubComponentInstance>> {
104 let mut current = start.clone();
105 for _ in 0..level {
106 let parent = current.parent.upgrade().expect("parent vanished during evaluation");
107 current = Pin::new(parent);
108 }
109 current
110}
111
112impl i_slint_compiler::llr::TypeResolutionContext for EvalContext {
113 fn property_ty(&self, mr: &MemberReference) -> &Type {
114 let cu = &self.compilation_unit;
115 match mr {
116 MemberReference::Global { global_index, member } => {
117 let g = &cu.globals[*global_index];
118 match member {
119 LocalMemberIndex::Property(idx) => &g.properties[*idx].ty,
120 LocalMemberIndex::Function(idx) => &g.functions[*idx].ret_ty,
121 LocalMemberIndex::Callback(idx) => &g.callbacks[*idx].ty,
124 LocalMemberIndex::Native { .. } | LocalMemberIndex::Timer(_) => &Type::Invalid,
125 }
126 }
127 MemberReference::Relative { parent_level, local_reference } => {
128 let current =
129 self.current.as_ref().expect("property_ty needs a sub-component context");
130 let sub = walk_parent(current, *parent_level);
134 let mut sc_idx = sub.sub_component_idx;
135 for i in &local_reference.sub_component_path {
136 sc_idx = cu.sub_components[sc_idx].sub_components[*i].ty;
137 }
138 let sc = &cu.sub_components[sc_idx];
139 match &local_reference.reference {
140 LocalMemberIndex::Property(idx) => &sc.properties[*idx].ty,
141 LocalMemberIndex::Function(idx) => &sc.functions[*idx].ret_ty,
142 LocalMemberIndex::Callback(idx) => &sc.callbacks[*idx].ty,
143 LocalMemberIndex::Timer(_) => &Type::Invalid,
145 LocalMemberIndex::Native { item_index, prop_name, .. } => {
146 if prop_name == "elements" {
147 return &Type::PathData;
149 }
150 sc.items[*item_index]
151 .ty
152 .lookup_property(prop_name)
153 .unwrap_or(&Type::Invalid)
154 }
155 }
156 }
157 }
158 }
159
160 fn arg_type(&self, index: usize) -> &Type {
161 self.function_arg_types.get(index).unwrap_or(&Type::Invalid)
162 }
163}
164
165pub(crate) fn walk_sub_path(
167 mut current: Pin<Rc<SubComponentInstance>>,
168 path: &[llr::SubComponentInstanceIdx],
169) -> Pin<Rc<SubComponentInstance>> {
170 for &idx in path {
171 let next = current.sub_components[idx].clone();
172 current = next;
173 }
174 current
175}
176
177pub(crate) fn walk_to(
181 ctx: &EvalContext,
182 parent_level: usize,
183 path: &[llr::SubComponentInstanceIdx],
184) -> Pin<Rc<SubComponentInstance>> {
185 let start = ctx.current.as_ref().expect("relative member reference without a sub-component");
186 walk_sub_path(walk_parent(start, parent_level), path)
187}
188
189pub(crate) fn find_flat_item_index(
191 item_table: &[Option<(
192 Box<[i_slint_compiler::llr::SubComponentInstanceIdx]>,
193 i_slint_compiler::llr::ItemInstanceIdx,
194 )>],
195 path: &[i_slint_compiler::llr::SubComponentInstanceIdx],
196 item_index: i_slint_compiler::llr::ItemInstanceIdx,
197) -> Option<usize> {
198 item_table.iter().position(|entry| {
199 entry.as_ref().is_some_and(|(p, i)| p.as_ref() == path && *i == item_index)
200 })
201}
202
203fn load_local(instance: &SubComponentInstance, member: &LocalMemberIndex) -> Value {
204 match member {
205 LocalMemberIndex::Property(idx) => Pin::as_ref(&instance.properties[*idx]).get(),
206 LocalMemberIndex::Native { item_index, prop_name, .. } => {
207 Pin::as_ref(&instance.items[*item_index]).get_property(prop_name).unwrap_or(Value::Void)
208 }
209 LocalMemberIndex::Callback(_)
210 | LocalMemberIndex::Function(_)
211 | LocalMemberIndex::Timer(_) => {
212 panic!("load_local called on callback/function/timer reference")
213 }
214 }
215}
216
217fn set_maybe_animated(
219 prop: Pin<&i_slint_core::Property<Value>>,
220 ty: &Type,
221 value: Value,
222 animation: Option<i_slint_core::items::PropertyAnimation>,
223) {
224 match animation {
225 Some(anim) => match crate::bindings::animated_value_map(ty) {
226 Some(map) => prop.set_animated_value_with_map(value, anim, map),
227 None => prop.set_animated_value(value, anim),
228 },
229 None => prop.set(value),
230 }
231}
232
233fn store_local(
234 instance: &SubComponentInstance,
235 member: &LocalMemberIndex,
236 value: Value,
237 animation: Option<i_slint_core::items::PropertyAnimation>,
238) {
239 match member {
240 LocalMemberIndex::Property(idx) => {
241 let sc = &instance.compilation_unit.sub_components[instance.sub_component_idx];
242 set_maybe_animated(
243 Pin::as_ref(&instance.properties[*idx]),
244 &sc.properties[*idx].ty,
245 value,
246 animation,
247 );
248 }
249 LocalMemberIndex::Native { item_index, prop_name, .. } => {
250 let _ =
251 Pin::as_ref(&instance.items[*item_index]).set_property(prop_name, value, animation);
252 }
253 LocalMemberIndex::Callback(_)
254 | LocalMemberIndex::Function(_)
255 | LocalMemberIndex::Timer(_) => {
256 panic!("store_local called on callback/function/timer reference")
257 }
258 }
259}
260
261fn walk_to_target_with_animation(
268 start: Pin<Rc<SubComponentInstance>>,
269 local_reference: &llr::LocalMemberReference,
270) -> (Pin<Rc<SubComponentInstance>>, Option<i_slint_core::items::PropertyAnimation>) {
271 let cu = start.compilation_unit.clone();
272 let path = &local_reference.sub_component_path;
273 let mut animation = None;
274 let mut owner = start;
275 for depth in 0..=path.len() {
276 if animation.is_none() {
277 let sc = &cu.sub_components[owner.sub_component_idx];
278 if !sc.animations.is_empty() {
279 let key = llr::LocalMemberReference {
280 sub_component_path: path[depth..].to_vec(),
281 reference: local_reference.reference.clone(),
282 };
283 if let Some(expr) = sc.animations.get(&key) {
284 animation = Some((owner.clone(), expr.clone()));
285 }
286 }
287 }
288 if let Some(&idx) = path.get(depth) {
289 let next = owner.sub_components[idx].clone();
290 owner = next;
291 }
292 }
293 let animation = animation.map(|(scope, expr)| {
294 let mut ctx = EvalContext::new(scope);
295 crate::bindings::value_to_property_animation(eval_expression(&mut ctx, &expr))
296 });
297 (owner, animation)
298}
299
300pub fn load_property(ctx: &EvalContext, mr: &MemberReference) -> Value {
301 match mr {
302 MemberReference::Global { global_index, member } => {
303 let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
304 let Some(global) = storage.get(*global_index) else { return Value::Void };
305 load_global(global, member)
306 }
307 MemberReference::Relative { parent_level, local_reference } => {
308 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
309 load_local(&instance, &local_reference.reference)
310 }
311 }
312}
313
314pub fn store_property(ctx: &EvalContext, mr: &MemberReference, value: Value) {
315 match mr {
316 MemberReference::Global { global_index, member } => {
317 let Some(storage) = ctx.globals.upgrade() else { return };
318 let Some(global) = storage.get(*global_index) else { return };
319 store_global(global, member, value);
320 }
321 MemberReference::Relative { parent_level, local_reference } => {
322 let start =
323 ctx.current.as_ref().expect("relative member reference without a sub-component");
324 let (instance, animation) =
325 walk_to_target_with_animation(walk_parent(start, *parent_level), local_reference);
326 store_local(&instance, &local_reference.reference, value, animation);
327 }
328 }
329}
330
331pub fn invoke_callback(ctx: &EvalContext, mr: &MemberReference, args: &[Value]) -> Value {
332 match mr {
333 MemberReference::Global { global_index, member } => {
334 let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
335 let Some(global) = storage.get(*global_index) else { return Value::Void };
336 let LocalMemberIndex::Callback(idx) = member else {
337 panic!("invoke_callback on non-callback global reference")
338 };
339 let cb = &global.compilation_unit.globals[global.global_idx].callbacks[*idx];
340 if let Some(native) = &global.native {
341 let res = native.as_ref().invoke_callback(&cb.name, args).unwrap_or(Value::Void);
342 return ensure_typed_default(res, &cb.ret_ty);
343 }
344 if let Some(tracker) = global.callback_trackers[*idx].as_ref() {
347 Pin::as_ref(tracker).get();
348 }
349 let res = Pin::as_ref(&global.callbacks[*idx]).call(args);
350 ensure_typed_default(res, &cb.ret_ty)
351 }
352 MemberReference::Relative { parent_level, local_reference } => {
353 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
354 match &local_reference.reference {
355 LocalMemberIndex::Callback(idx) => {
356 if let Some(tracker) = instance.callback_trackers[*idx].as_ref() {
360 Pin::as_ref(tracker).get();
361 }
362 let res = Pin::as_ref(&instance.callbacks[*idx]).call(args);
363 let ret_ty = instance.compilation_unit.sub_components
364 [instance.sub_component_idx]
365 .callbacks[*idx]
366 .ret_ty
367 .clone();
368 ensure_typed_default(res, &ret_ty)
369 }
370 LocalMemberIndex::Native { item_index, prop_name, .. } => {
371 Pin::as_ref(&instance.items[*item_index])
372 .call_callback(prop_name, args)
373 .unwrap_or(Value::Void)
374 }
375 _ => panic!("invoke_callback on non-callback reference: {mr:?}"),
376 }
377 }
378 }
379}
380
381pub(crate) fn ensure_typed_default(value: Value, ret_ty: &Type) -> Value {
384 if matches!(value, Value::Void) { default_value_for_type(ret_ty) } else { value }
385}
386
387pub fn invoke_function(ctx: &EvalContext, mr: &MemberReference, args: Vec<Value>) -> Value {
388 match mr {
389 MemberReference::Global { global_index, member } => {
390 let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
391 let Some(global) = storage.get(*global_index) else { return Value::Void };
392 let LocalMemberIndex::Function(idx) = member else {
393 panic!("invoke_function on non-function global reference")
394 };
395 let function = &global.compilation_unit.globals[global.global_idx].functions[*idx];
396 let code = function.code.borrow().clone();
397 let mut inner_ctx =
398 EvalContext::for_global(ctx.globals.clone(), global.compilation_unit.clone());
399 inner_ctx.function_arg_types = function.args.clone();
400 inner_ctx.function_arguments = args;
401 eval_expression(&mut inner_ctx, &code)
402 }
403 MemberReference::Relative { parent_level, local_reference } => {
404 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
405 let LocalMemberIndex::Function(idx) = &local_reference.reference else {
406 panic!("invoke_function on non-function reference")
407 };
408 let sc = &instance.compilation_unit.sub_components[instance.sub_component_idx];
409 let function = &sc.functions[*idx];
410 let code = function.code.borrow().clone();
411 let mut inner_ctx = EvalContext::with_arguments(instance.clone(), args);
412 inner_ctx.function_arg_types = function.args.clone();
413 eval_expression(&mut inner_ctx, &code)
414 }
415 }
416}
417
418fn load_global(global: &Rc<GlobalInstance>, member: &LocalMemberIndex) -> Value {
419 match member {
420 LocalMemberIndex::Property(idx) => {
421 if let Some(native) = &global.native {
422 let g = &global.compilation_unit.globals[global.global_idx];
423 return native
424 .as_ref()
425 .get_property(&g.properties[*idx].name)
426 .unwrap_or(Value::Void);
427 }
428 Pin::as_ref(&global.properties[*idx]).get()
429 }
430 _ => panic!("load_global called on non-property"),
431 }
432}
433
434pub(crate) fn store_global(global: &Rc<GlobalInstance>, member: &LocalMemberIndex, value: Value) {
435 if let LocalMemberIndex::Property(idx) = member {
436 let g = &global.compilation_unit.globals[global.global_idx];
437 if let Some(native) = &global.native {
439 let _ = native.as_ref().set_property(&g.properties[*idx].name, value, None);
440 return;
441 }
442 set_maybe_animated(
443 Pin::as_ref(&global.properties[*idx]),
444 &g.properties[*idx].ty,
445 value,
446 None,
447 );
448 }
449}
450
451fn cast_to_path_data(ctx: &mut EvalContext, from: &Expression) -> Value {
461 use i_slint_core::graphics::PathData;
462 use i_slint_core::items::PathEvent;
463
464 match from {
465 Expression::Array { values, .. } => {
466 let elements: SharedVector<i_slint_core::graphics::PathElement> =
467 values.iter().filter_map(|e| path_element_from_expression(ctx, e)).collect();
468 Value::PathData(PathData::Elements(elements))
469 }
470 Expression::Struct { values, .. }
471 if values.contains_key("events") && values.contains_key("points") =>
472 {
473 let events_value = eval_expression(ctx, &values["events"]);
474 let points_value = eval_expression(ctx, &values["points"]);
475 let events: SharedVector<PathEvent> = match events_value {
480 Value::Model(m) => {
481 (0..m.row_count()).filter_map(|i| m.row_data(i)?.try_into().ok()).collect()
482 }
483 _ => SharedVector::default(),
484 };
485 let points: SharedVector<lyon_path::math::Point> = match points_value {
486 Value::Model(m) => {
487 (0..m.row_count()).filter_map(|i| m.row_data(i)?.try_into().ok()).collect()
488 }
489 _ => SharedVector::default(),
490 };
491 Value::PathData(PathData::Events(events, points))
492 }
493 _ => match eval_expression(ctx, from) {
494 Value::String(s) => Value::PathData(PathData::Commands(s)),
495 _ => Value::PathData(PathData::None),
496 },
497 }
498}
499
500fn path_element_from_expression(
504 ctx: &mut EvalContext,
505 expr: &Expression,
506) -> Option<i_slint_core::graphics::PathElement> {
507 use i_slint_compiler::langtype::{BuiltinStruct, StructName};
508 use i_slint_core::graphics::{
509 PathArcTo, PathCubicTo, PathElement, PathLineTo, PathMoveTo, PathQuadraticTo,
510 };
511 let Expression::Struct { ty, values } = expr else { return None };
512 let StructName::Builtin(bs) = &ty.name else { return None };
513 let get_f32 = |field: &str, ctx: &mut EvalContext| -> f32 {
514 values
515 .get(field)
516 .map(|e| eval_expression(ctx, e))
517 .and_then(|v| f64::try_from(v).ok())
518 .unwrap_or(0.0) as f32
519 };
520 let get_bool = |field: &str, ctx: &mut EvalContext| -> bool {
521 values
522 .get(field)
523 .map(|e| eval_expression(ctx, e))
524 .map(|v| matches!(v, Value::Bool(true)))
525 .unwrap_or(false)
526 };
527 Some(match bs {
528 BuiltinStruct::PathMoveTo => {
529 PathElement::MoveTo(PathMoveTo { x: get_f32("x", ctx), y: get_f32("y", ctx) })
530 }
531 BuiltinStruct::PathLineTo => {
532 PathElement::LineTo(PathLineTo { x: get_f32("x", ctx), y: get_f32("y", ctx) })
533 }
534 BuiltinStruct::PathArcTo => PathElement::ArcTo(PathArcTo {
535 x: get_f32("x", ctx),
536 y: get_f32("y", ctx),
537 radius_x: get_f32("radius-x", ctx),
538 radius_y: get_f32("radius-y", ctx),
539 x_rotation: get_f32("x-rotation", ctx),
540 large_arc: get_bool("large-arc", ctx),
541 sweep: get_bool("sweep", ctx),
542 }),
543 BuiltinStruct::PathCubicTo => PathElement::CubicTo(PathCubicTo {
544 x: get_f32("x", ctx),
545 y: get_f32("y", ctx),
546 control_1_x: get_f32("control-1-x", ctx),
547 control_1_y: get_f32("control-1-y", ctx),
548 control_2_x: get_f32("control-2-x", ctx),
549 control_2_y: get_f32("control-2-y", ctx),
550 }),
551 BuiltinStruct::PathQuadraticTo => PathElement::QuadraticTo(PathQuadraticTo {
552 x: get_f32("x", ctx),
553 y: get_f32("y", ctx),
554 control_x: get_f32("control-x", ctx),
555 control_y: get_f32("control-y", ctx),
556 }),
557 BuiltinStruct::PathClose => PathElement::Close,
558 _ => return None,
559 })
560}
561
562pub fn default_value_for_type(ty: &Type) -> Value {
565 match ty {
566 Type::Float32
567 | Type::Int32
568 | Type::Duration
569 | Type::Angle
570 | Type::PhysicalLength
571 | Type::LogicalLength
572 | Type::Rem
573 | Type::Percent
574 | Type::UnitProduct(_) => Value::Number(0.),
575 Type::String => Value::String(Default::default()),
576 Type::Color | Type::Brush => Value::Brush(Brush::default()),
577 Type::Bool => Value::Bool(false),
578 Type::Image => Value::Image(Default::default()),
579 Type::Struct(s) => Value::Struct(
580 s.fields
581 .keys()
582 .map(|k| (k.to_string(), default_value_for_struct_field(s, k)))
583 .collect(),
584 ),
585 Type::Array(_) | Type::Model => Value::Model(ModelRc::default()),
586 Type::Keys => Value::Keys(Default::default()),
587 Type::DataTransfer => Value::DataTransfer(Default::default()),
588 Type::StyledText => Value::StyledText(Default::default()),
589 Type::Enumeration(en) => {
590 let default = en.clone().default_value();
591 Value::EnumerationValue(en.name.to_string(), default.to_string())
592 }
593 _ => Value::Void,
594 }
595}
596
597pub fn default_value_for_struct_field(
601 s: &i_slint_compiler::langtype::Struct,
602 field_name: &str,
603) -> Value {
604 match s.field_defaults.get(field_name) {
605 Some(expr) => eval_constant_expression(expr),
606 None => default_value_for_type(
607 s.fields.get(field_name).expect("default value requested for unknown struct field"),
608 ),
609 }
610}
611
612fn eval_constant_expression(expr: &ConstantExpression) -> Value {
615 match expr {
616 ConstantExpression::StringLiteral(s) => Value::String(s.as_str().into()),
617 ConstantExpression::NumberLiteral(n, _unit) => Value::Number(*n),
618 ConstantExpression::BoolLiteral(b) => Value::Bool(*b),
619 ConstantExpression::EnumerationValue(value) => {
620 Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
621 }
622 ConstantExpression::Cast { from, to } => {
623 cast_constant_value(eval_constant_expression(from), to)
624 }
625 ConstantExpression::UnaryOp { sub, op } => {
626 match (eval_constant_expression(sub), op) {
628 (Value::Number(a), '+') => Value::Number(a),
629 (Value::Number(a), '-') => Value::Number(-a),
630 (Value::Bool(a), '!') => Value::Bool(!a),
631 (sub, _) => panic!("unsupported {op} {sub:?}"),
632 }
633 }
634 ConstantExpression::Struct { values, .. } => Value::Struct(
635 values
636 .iter()
637 .map(|(k, v)| (k.to_string(), eval_constant_expression(v)))
638 .collect::<crate::api::Struct>(),
639 ),
640 ConstantExpression::Array { values, .. } => {
641 Value::Model(ModelRc::new(SharedVectorModel::from(
642 values.iter().map(eval_constant_expression).collect::<SharedVector<_>>(),
643 )))
644 }
645 }
646}
647
648fn cast_constant_value(value: Value, to: &Type) -> Value {
650 match (value, to) {
651 (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
652 (Value::Number(n), Type::String) => {
653 Value::String(i_slint_core::string::shared_string_from_number(n))
654 }
655 (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
656 (Value::Brush(brush), Type::Color) => brush.color().into(),
657 (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
658 (v, _) => v,
659 }
660}
661
662pub fn eval_expression(ctx: &mut EvalContext, expression: &Expression) -> Value {
663 if let Some(r) = &ctx.return_value {
664 return r.clone();
665 }
666 match expression {
667 Expression::StringLiteral(s) => Value::String(s.as_str().into()),
668 Expression::NumberLiteral(n) => Value::Number(*n),
669 Expression::BoolLiteral(b) => Value::Bool(*b),
670 Expression::KeysLiteral(ks) => Value::Keys({
671 let mut modifiers = i_slint_core::input::KeyboardModifiers::default();
672 modifiers.alt = ks.modifiers.alt;
673 modifiers.control = ks.modifiers.control;
674 modifiers.shift = ks.modifiers.shift;
675 modifiers.meta = ks.modifiers.meta;
676 i_slint_core::input::make_keys(
677 SharedString::from(&*ks.key),
678 modifiers,
679 ks.ignore_shift,
680 ks.ignore_alt,
681 )
682 }),
683 Expression::PropertyReference(mr) => load_property(ctx, mr),
684 Expression::FunctionParameterReference { index } => ctx.function_arguments[*index].clone(),
685 Expression::StoreLocalVariable { name, value } => {
686 let v = eval_expression(ctx, value);
687 ctx.locals.insert(name.clone(), v);
688 Value::Void
689 }
690 Expression::ReadLocalVariable { name, .. } => {
691 ctx.locals.get(name).cloned().unwrap_or(Value::Void)
692 }
693 Expression::StructFieldAccess { base, name } => {
694 if let Value::Struct(s) = eval_expression(ctx, base) {
695 s.get_field(name).cloned().unwrap_or(Value::Void)
696 } else {
697 Value::Void
698 }
699 }
700 Expression::ArrayIndex { array, index } => {
701 let array_v = eval_expression(ctx, array);
702 let index = eval_expression(ctx, index);
703 match (array_v, index) {
704 (Value::Model(m), Value::Number(i)) => {
705 let idx = i as isize as usize;
706 m.row_data_tracked(idx).unwrap_or_else(|| {
707 default_value_for_type(&expression.ty(&*ctx))
710 })
711 }
712 _ => Value::Void,
713 }
714 }
715 Expression::Cast { from, to } => {
716 if matches!(to, Type::PathData) {
720 return cast_to_path_data(ctx, from);
721 }
722 let v = eval_expression(ctx, from);
723 match (v, to) {
724 (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
725 (Value::Number(n), Type::String) => {
726 Value::String(i_slint_core::string::shared_string_from_number(n))
727 }
728 (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
729 (Value::Brush(brush), Type::Color) => brush.color().into(),
730 (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
731 (v, _) => v,
732 }
733 }
734 Expression::CodeBlock(sub) => {
735 let mut v = Value::Void;
736 for e in sub {
737 v = eval_expression(ctx, e);
738 if let Some(r) = &ctx.return_value {
739 return r.clone();
740 }
741 }
742 v
743 }
744 Expression::BuiltinFunctionCall { function, arguments } => {
745 call_builtin_function(ctx, function.clone(), arguments)
746 }
747 Expression::CallBackCall { callback, arguments } => {
748 let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
749 invoke_callback(ctx, callback, &args)
750 }
751 Expression::FunctionCall { function, arguments } => {
752 let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
753 invoke_function(ctx, function, args)
754 }
755 Expression::ItemMemberFunctionCall { function } => call_item_member_function(ctx, function),
756 Expression::ExtraBuiltinFunctionCall { function, arguments, .. } => {
757 crate::eval_layout::call_extra_builtin(ctx, function, arguments)
758 }
759 Expression::PropertyAssignment { property, value } => {
760 let v = eval_expression(ctx, value);
761 store_property(ctx, property, v);
762 Value::Void
763 }
764 Expression::ModelDataAssignment { level, value } => {
765 let new_value = eval_expression(ctx, value);
766 if let Some(current) = ctx.current.as_ref() {
767 let mut walker = current.clone();
768 for _ in 0..*level {
769 let parent = walker.parent.upgrade().expect("parent vanished");
770 walker = std::pin::Pin::new(parent);
771 }
772 if let Some((parent_weak, repeater_idx)) = walker.repeated_in.get()
773 && let Some(parent) = parent_weak.upgrade()
774 {
775 let row = walker.compilation_unit.sub_components[walker.sub_component_idx]
778 .properties
779 .iter_enumerated()
780 .find(|(_, p)| p.name.as_str() == "model_index")
781 .map(|(idx, _)| {
782 let v = std::pin::Pin::as_ref(&walker.properties[idx]).get();
783 f64::try_from(v).unwrap_or(0.) as usize
784 })
785 .unwrap_or(0);
786 let parent_pinned = std::pin::Pin::new(parent);
787 let repeater = &parent_pinned.repeaters[*repeater_idx];
788 repeater.model_set_row_data(row, new_value);
789 }
790 }
791 Value::Void
792 }
793 Expression::ArrayIndexAssignment { array, index, value } => {
794 let value = eval_expression(ctx, value);
795 let array = eval_expression(ctx, array);
796 let index = eval_expression(ctx, index);
797 if let (Value::Model(m), Value::Number(i)) = (array, index)
798 && i >= 0.0
799 {
800 let i = i.trunc() as usize;
801 if i < m.row_count() {
802 m.set_row_data(i, value);
803 }
804 }
805 Value::Void
806 }
807 Expression::SliceIndexAssignment { slice_name, index, value } => {
808 let value = eval_expression(ctx, value);
809 match ctx.locals.get_mut(slice_name.as_str()) {
810 Some(Value::ArrayOfU16(vec)) => {
811 if let Value::Number(n) = value
812 && *index < vec.len()
813 {
814 vec.make_mut_slice()[*index] = n as u16;
815 }
816 }
817 Some(Value::Model(m)) if *index < m.row_count() => {
818 m.set_row_data(*index, value);
819 }
820 _ => {}
821 }
822 Value::Void
823 }
824 Expression::BinaryExpression { lhs, rhs, op } => {
825 let lhs = eval_expression(ctx, lhs);
826 match (op, &lhs) {
829 ('&', Value::Bool(false)) => return Value::Bool(false),
830 ('|', Value::Bool(true)) => return Value::Bool(true),
831 _ => {}
832 }
833 let rhs = eval_expression(ctx, rhs);
834 binary_op(*op, lhs, rhs)
835 }
836 Expression::UnaryOp { sub, op } => {
837 let sub = eval_expression(ctx, sub);
838 match (sub, op) {
839 (Value::Number(a), '+') => Value::Number(a),
840 (Value::Number(a), '-') => Value::Number(-a),
841 (Value::Bool(a), '!') => Value::Bool(!a),
842 (Value::Void, '+' | '-') => Value::Number(0.0),
845 (Value::Void, '!') => Value::Bool(true),
846 (s, o) => panic!("unsupported {o} {s:?}"),
847 }
848 }
849 Expression::ImageReference { resource_ref, nine_slice } => {
850 let mut image = load_image_reference(resource_ref);
851 if let Some(n) = nine_slice {
852 image.set_nine_slice_edges(n[0], n[1], n[2], n[3]);
853 }
854 Value::Image(image)
855 }
856 Expression::Condition { condition, true_expr, false_expr } => {
857 match eval_expression(ctx, condition) {
858 Value::Bool(true) => eval_expression(ctx, true_expr),
859 Value::Bool(false) => eval_expression(ctx, false_expr),
860 _ => Value::Void,
861 }
862 }
863 Expression::Array { values, .. } => Value::Model(ModelRc::new(SharedVectorModel::from(
864 values.iter().map(|e| eval_expression(ctx, e)).collect::<SharedVector<_>>(),
865 ))),
866 Expression::Struct { values, .. } => Value::Struct(
867 values.iter().map(|(k, v)| (k.to_string(), eval_expression(ctx, v))).collect(),
868 ),
869 Expression::EasingCurve(curve) => {
870 use i_slint_compiler::expression_tree::EasingCurve as EC;
871 use i_slint_core::animations::EasingCurve as Core;
872 Value::EasingCurve(match curve {
873 EC::Linear => Core::Linear,
874 EC::EaseInElastic => Core::EaseInElastic,
875 EC::EaseOutElastic => Core::EaseOutElastic,
876 EC::EaseInOutElastic => Core::EaseInOutElastic,
877 EC::EaseInBounce => Core::EaseInBounce,
878 EC::EaseOutBounce => Core::EaseOutBounce,
879 EC::EaseInOutBounce => Core::EaseInOutBounce,
880 EC::CubicBezier(a, b, c, d) => Core::CubicBezier([*a, *b, *c, *d]),
881 })
882 }
883 Expression::MouseCursor(cursor) => {
884 use i_slint_compiler::expression_tree::MouseCursorInner as Expr;
885 use i_slint_core::cursor::MouseCursorInner as Core;
886 Value::MouseCursorInner(match cursor {
887 Expr::BuiltIn(cursor) => {
888 Core::BuiltIn(eval_expression(ctx, cursor).try_into().unwrap_or_default())
889 }
890 Expr::CustomMouseCursor { image, hotspot_x, hotspot_y } => {
891 Core::CustomMouseCursor {
892 image: eval_expression(ctx, image).try_into().unwrap_or_default(),
893 hotspot_x: eval_expression(ctx, hotspot_x).try_into().unwrap_or_default(),
894 hotspot_y: eval_expression(ctx, hotspot_y).try_into().unwrap_or_default(),
895 }
896 }
897 })
898 }
899 Expression::LinearGradient { angle, stops } => {
900 let angle: f32 = eval_expression(ctx, angle).try_into().unwrap_or_default();
901 Value::Brush(Brush::LinearGradient(LinearGradientBrush::new(
902 angle,
903 eval_stops(ctx, stops),
904 )))
905 }
906 Expression::RadialGradient { stops, center, radius } => {
907 let mut g = RadialGradientBrush::new_circle(eval_stops(ctx, stops));
908 if let Some((cx, cy)) = center {
909 let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
910 let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
911 g = g.with_center(cx, cy);
912 }
913 if let Some(r) = radius {
914 let r: f32 = eval_expression(ctx, r).try_into().unwrap_or_default();
915 g = g.with_radius(r);
916 }
917 Value::Brush(Brush::RadialGradient(g))
918 }
919 Expression::ConicGradient { from_angle, stops, center } => {
920 let from_angle: f32 = eval_expression(ctx, from_angle).try_into().unwrap_or_default();
921 let mut g = ConicGradientBrush::new(from_angle, eval_stops(ctx, stops));
922 if let Some((cx, cy)) = center {
923 let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
924 let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
925 g = g.with_center(cx, cy);
926 }
927 Value::Brush(Brush::ConicGradient(g))
928 }
929 Expression::EnumerationValue(value) => {
930 Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
931 }
932 Expression::LayoutCacheAccess {
933 layout_cache_prop,
934 index,
935 repeater_index,
936 entries_per_item,
937 } => {
938 let cache = load_property(ctx, layout_cache_prop);
939 layout_cache_access(ctx, cache, *index, repeater_index.as_deref(), *entries_per_item)
940 }
941 Expression::GridRepeaterCacheAccess {
942 layout_cache_prop,
943 index,
944 repeater_index,
945 stride,
946 child_offset,
947 inner_repeater_index,
948 entries_per_item,
949 } => {
950 let cache = load_property(ctx, layout_cache_prop);
951 let offset: usize = eval_expression(ctx, repeater_index).try_into().unwrap_or_default();
952 let stride_val: usize = eval_expression(ctx, stride).try_into().unwrap_or_default();
953 let inner_offset: usize = inner_repeater_index
954 .as_deref()
955 .map(|e| {
956 let i: usize = eval_expression(ctx, e).try_into().unwrap_or_default();
957 i * *entries_per_item
958 })
959 .unwrap_or(0);
960 grid_repeater_cache_access(
961 cache,
962 *index,
963 offset,
964 stride_val,
965 *child_offset,
966 inner_offset,
967 )
968 }
969 Expression::WithLayoutItemInfo {
970 cells_variable,
971 elements,
972 orientation,
973 sub_expression,
974 ..
975 } => with_layout_item_info(ctx, cells_variable, elements, *orientation, sub_expression),
976 Expression::WithFlexboxLayoutItemInfo {
977 cells_h_variable,
978 cells_v_variable,
979 flex_props_variable,
980 elements,
981 repeated_cross_width,
982 sub_expression,
983 ..
984 } => with_flexbox_layout_item_info(
985 ctx,
986 cells_h_variable,
987 cells_v_variable,
988 flex_props_variable,
989 elements,
990 repeated_cross_width.as_deref(),
991 sub_expression,
992 ),
993 Expression::WithGridInputData { cells_variable, elements, sub_expression, .. } => {
994 with_grid_input_data(ctx, cells_variable, elements, sub_expression)
995 }
996 Expression::MinMax { ty: _, op, lhs, rhs } => {
997 let Value::Number(lhs) = eval_expression(ctx, lhs) else { return Value::Void };
998 let Value::Number(rhs) = eval_expression(ctx, rhs) else { return Value::Void };
999 match op {
1000 MinMaxOp::Min => Value::Number(lhs.min(rhs)),
1001 MinMaxOp::Max => Value::Number(lhs.max(rhs)),
1002 }
1003 }
1004 Expression::EmptyComponentFactory => Value::ComponentFactory(Default::default()),
1005 Expression::EmptyDataTransfer => Value::DataTransfer(Default::default()),
1006 Expression::SolveFlexboxLayoutWithMeasure { .. } => {
1007 crate::eval_layout::solve_flexbox_layout_with_measure(ctx, expression)
1008 }
1009 Expression::TranslationReference { .. } => {
1010 Value::String(Default::default())
1014 }
1015 Expression::Closure { .. } => unreachable!(
1016 "closures are dispatched by their consuming builtin and should not go through eval_expression"
1017 ),
1018 Expression::DebugHook { expression, id } => {
1019 if let Some(hook_value) = crate::debug_hook::trigger_debug_hook(ctx, id) {
1020 return hook_value;
1021 }
1022 eval_expression(ctx, expression)
1023 }
1024 }
1025}
1026
1027fn with_layout_item_info(
1028 ctx: &mut EvalContext,
1029 cells_variable: &str,
1030 elements: &[itertools::Either<Expression, i_slint_compiler::llr::LayoutRepeatedElement>],
1031 orientation: i_slint_compiler::layout::Orientation,
1032 sub_expression: &Expression,
1033) -> Value {
1034 let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1035 let mut repeated_indices: Vec<u32> = Vec::new();
1036 let mut repeater_steps: Vec<u32> = Vec::new();
1037 for el in elements {
1038 match el {
1039 itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1040 itertools::Either::Right(repeater) => {
1041 let offset = cells.len() as u32;
1042 let (instances, step) = push_repeater_layout_items(
1043 ctx,
1044 repeater.repeater_index,
1045 repeater.row_child_templates.as_deref(),
1046 orientation,
1047 &mut cells,
1048 );
1049 repeated_indices.push(offset);
1050 repeated_indices.push(instances);
1051 repeater_steps.push(step);
1052 }
1053 }
1054 }
1055 let prev_cells =
1056 ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1057 let prev_ri = ctx.locals.insert(
1058 SmolStr::new_static("repeated_indices"),
1059 Value::Model(model_from_vec(
1060 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1061 )),
1062 );
1063 let prev_rs = ctx.locals.insert(
1064 SmolStr::new_static("repeater_steps"),
1065 Value::Model(model_from_vec(
1066 repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1067 )),
1068 );
1069 let result = eval_expression(ctx, sub_expression);
1070 restore_local(ctx, cells_variable, prev_cells);
1071 restore_local(ctx, "repeated_indices", prev_ri);
1072 restore_local(ctx, "repeater_steps", prev_rs);
1073 result
1074}
1075
1076fn push_repeater_layout_items(
1077 ctx: &mut EvalContext,
1078 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1079 row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1080 orientation: i_slint_compiler::layout::Orientation,
1081 cells: &mut Vec<Value>,
1082) -> (u32, u32) {
1083 use i_slint_core::model::RepeatedItemTree;
1084 let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1085 let repeater = ¤t.repeaters[repeater_idx];
1086 repeater.track_instance_changes();
1087 let instances = repeater.instances_vec();
1088 let core_orientation = llr_to_core_orientation(orientation);
1089 let push_cell = |cells: &mut Vec<Value>, info: i_slint_core::layout::LayoutItemInfo| {
1090 let mut struct_value = crate::api::Struct::default();
1091 struct_value.set_field("constraint".to_string(), info.constraint.into());
1092 cells.push(Value::Struct(struct_value));
1093 };
1094 let step = match row_child_templates {
1095 None => {
1096 for instance in &instances {
1099 let info = RepeatedItemTree::layout_item_info(
1100 instance.as_pin_ref(),
1101 core_orientation,
1102 None,
1103 );
1104 push_cell(cells, info);
1105 }
1106 1
1107 }
1108 Some(templates) => {
1109 let max_total = instances
1113 .iter()
1114 .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1115 .max()
1116 .unwrap_or(i_slint_compiler::llr::static_child_count(templates));
1117 for instance in &instances {
1118 for child_idx in 0..max_total {
1119 let info = RepeatedItemTree::layout_item_info(
1120 instance.as_pin_ref(),
1121 core_orientation,
1122 Some(child_idx),
1123 );
1124 push_cell(cells, info);
1125 }
1126 }
1127 max_total as u32
1128 }
1129 };
1130 (instances.len() as u32, step)
1131}
1132
1133fn total_row_child_count(
1134 sub: &Pin<std::rc::Rc<crate::instance::SubComponentInstance>>,
1135 templates: &[i_slint_compiler::llr::RowChildTemplateInfo],
1136) -> usize {
1137 use i_slint_compiler::llr::{RowChildTemplateInfo, static_child_count};
1138 let mut total = static_child_count(templates);
1139 for entry in templates {
1140 if let RowChildTemplateInfo::Repeated { repeater_index } = entry {
1141 let repeater = &sub.repeaters[*repeater_index];
1142 repeater.track_instance_changes();
1143 total += repeater.range().len();
1144 }
1145 }
1146 total
1147}
1148
1149fn llr_to_core_orientation(
1150 o: i_slint_compiler::layout::Orientation,
1151) -> i_slint_core::items::Orientation {
1152 match o {
1153 i_slint_compiler::layout::Orientation::Horizontal => {
1154 i_slint_core::items::Orientation::Horizontal
1155 }
1156 i_slint_compiler::layout::Orientation::Vertical => {
1157 i_slint_core::items::Orientation::Vertical
1158 }
1159 }
1160}
1161
1162fn with_flexbox_layout_item_info(
1163 ctx: &mut EvalContext,
1164 cells_h_variable: &str,
1165 cells_v_variable: &str,
1166 flex_props_variable: &str,
1167 elements: &[itertools::Either<
1168 (Expression, Expression, Expression),
1169 i_slint_compiler::llr::LayoutRepeatedElement,
1170 >],
1171 repeated_cross_width: Option<&Expression>,
1172 sub_expression: &Expression,
1173) -> Value {
1174 let cross_width =
1177 repeated_cross_width.map(|e| eval_expression(ctx, e).try_into().unwrap_or_default());
1178 let mut cells_h: Vec<Value> = Vec::with_capacity(elements.len());
1179 let mut cells_v: Vec<Value> = Vec::with_capacity(elements.len());
1180 let mut flex_props: Vec<Value> = Vec::with_capacity(elements.len());
1181 let mut repeated_indices: Vec<u32> = Vec::new();
1182 for el in elements {
1183 match el {
1184 itertools::Either::Left((h, v, props)) => {
1185 cells_h.push(eval_expression(ctx, h));
1186 cells_v.push(eval_expression(ctx, v));
1187 flex_props.push(eval_expression(ctx, props));
1188 }
1189 itertools::Either::Right(repeater) => {
1190 let offset = cells_h.len() as u32;
1191 let instances = push_repeater_flexbox_items(
1192 ctx,
1193 repeater.repeater_index,
1194 cross_width,
1195 &mut cells_h,
1196 &mut cells_v,
1197 &mut flex_props,
1198 );
1199 repeated_indices.push(offset);
1200 repeated_indices.push(instances);
1201 }
1202 }
1203 }
1204 let prev_h =
1205 ctx.locals.insert(SmolStr::from(cells_h_variable), Value::Model(model_from_vec(cells_h)));
1206 let prev_v =
1207 ctx.locals.insert(SmolStr::from(cells_v_variable), Value::Model(model_from_vec(cells_v)));
1208 let prev_fp = ctx
1209 .locals
1210 .insert(SmolStr::from(flex_props_variable), Value::Model(model_from_vec(flex_props)));
1211 let prev_ri = ctx.locals.insert(
1212 SmolStr::new_static("repeated_indices"),
1213 Value::Model(model_from_vec(
1214 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1215 )),
1216 );
1217 let result = eval_expression(ctx, sub_expression);
1218 restore_local(ctx, cells_h_variable, prev_h);
1219 restore_local(ctx, cells_v_variable, prev_v);
1220 restore_local(ctx, flex_props_variable, prev_fp);
1221 restore_local(ctx, "repeated_indices", prev_ri);
1222 result
1223}
1224
1225fn push_repeater_flexbox_items(
1226 ctx: &mut EvalContext,
1227 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1228 cross_width: Option<f32>,
1229 cells_h: &mut Vec<Value>,
1230 cells_v: &mut Vec<Value>,
1231 flex_props: &mut Vec<Value>,
1232) -> u32 {
1233 use i_slint_core::items::Orientation;
1234 use i_slint_core::model::RepeatedItemTree;
1235 let Some(current) = ctx.current.as_ref() else { return 0 };
1236 let repeater = ¤t.repeaters[repeater_idx];
1237 repeater.track_instance_changes();
1238 let instances = repeater.instances_vec();
1239 let instance_count = instances.len() as u32;
1240 for instance in instances {
1241 let info_h = RepeatedItemTree::flexbox_layout_item_info(
1245 instance.as_pin_ref(),
1246 Orientation::Horizontal,
1247 None,
1248 );
1249 let info_v = match cross_width {
1252 Some(w) => instance.as_pin_ref().flexbox_layout_item_info_at_cross_width(w),
1253 None => RepeatedItemTree::flexbox_layout_item_info(
1254 instance.as_pin_ref(),
1255 Orientation::Vertical,
1256 None,
1257 ),
1258 };
1259 flex_props.push(flex_props_to_value(info_h.props));
1262 cells_h.push(layout_item_info_to_value(info_h.constraint));
1263 cells_v.push(layout_item_info_to_value(info_v.constraint));
1264 }
1265 instance_count
1266}
1267
1268fn layout_item_info_to_value(constraint: i_slint_core::layout::LayoutInfo) -> Value {
1269 let mut s = crate::api::Struct::default();
1270 s.set_field("constraint".to_string(), constraint.into());
1271 Value::Struct(s)
1272}
1273
1274fn flex_props_to_value(props: i_slint_core::layout::FlexItemProps) -> Value {
1275 let mut s = crate::api::Struct::default();
1276 s.set_field("flex_grow".to_string(), Value::Number(props.flex_grow as f64));
1277 s.set_field("flex_shrink".to_string(), Value::Number(props.flex_shrink as f64));
1278 s.set_field("flex_basis".to_string(), Value::Number(props.flex_basis as f64));
1279 s.set_field(
1280 "cross_axis_self_alignment".to_string(),
1281 Value::EnumerationValue(
1282 "CrossAxisSelfAlignment".to_string(),
1283 format!("{:?}", props.cross_axis_self_alignment).to_lowercase(),
1284 ),
1285 );
1286 s.set_field("flex_order".to_string(), Value::Number(props.flex_order as f64));
1287 Value::Struct(s)
1288}
1289
1290fn with_grid_input_data(
1291 ctx: &mut EvalContext,
1292 cells_variable: &str,
1293 elements: &[itertools::Either<Expression, i_slint_compiler::llr::GridLayoutRepeatedElement>],
1294 sub_expression: &Expression,
1295) -> Value {
1296 let saved_new_row = ctx.locals.remove("new_row");
1303 let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1304 let mut repeated_indices: Vec<u32> = Vec::new();
1305 let mut repeater_steps: Vec<u32> = Vec::new();
1306
1307 for el in elements {
1308 match el {
1309 itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1310 itertools::Either::Right(repeater) => {
1311 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(repeater.new_row));
1312 let offset = cells.len() as u32;
1313 let is_row_repeater = repeater.row_child_templates.is_some();
1314 let (instances, step) = push_repeater_grid_input_data(
1315 ctx,
1316 repeater.repeater_index,
1317 repeater.new_row,
1318 repeater.row_child_templates.as_deref(),
1319 &mut cells,
1320 );
1321 if !is_row_repeater && instances > 0 {
1322 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(false));
1323 }
1324 repeated_indices.push(offset);
1325 repeated_indices.push(instances);
1326 repeater_steps.push(step);
1327 }
1328 }
1329 }
1330 restore_local(ctx, "new_row", saved_new_row);
1331
1332 let prev_cells =
1333 ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1334 let prev_ri = ctx.locals.insert(
1335 SmolStr::new_static("repeated_indices"),
1336 Value::Model(model_from_vec(
1337 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1338 )),
1339 );
1340 let prev_rs = ctx.locals.insert(
1341 SmolStr::new_static("repeater_steps"),
1342 Value::Model(model_from_vec(
1343 repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1344 )),
1345 );
1346
1347 let result = eval_expression(ctx, sub_expression);
1348
1349 restore_local(ctx, cells_variable, prev_cells);
1350 restore_local(ctx, "repeated_indices", prev_ri);
1351 restore_local(ctx, "repeater_steps", prev_rs);
1352 result
1353}
1354
1355fn restore_local(ctx: &mut EvalContext, name: &str, prev: Option<Value>) {
1356 if let Some(prev) = prev {
1357 ctx.locals.insert(SmolStr::from(name), prev);
1358 } else {
1359 ctx.locals.remove(name);
1360 }
1361}
1362
1363fn push_repeater_grid_input_data(
1364 ctx: &mut EvalContext,
1365 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1366 new_row: bool,
1367 row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1368 cells: &mut Vec<Value>,
1369) -> (u32, u32) {
1370 use i_slint_compiler::llr::RowChildTemplateInfo;
1371 use i_slint_core::model::VecModel;
1372 use std::rc::Rc;
1373 let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1374 let repeater = ¤t.repeaters[repeater_idx];
1375 repeater.track_instance_changes();
1376
1377 let is_row_repeater = row_child_templates.is_some();
1378 let static_count =
1379 row_child_templates.map(i_slint_compiler::llr::static_child_count).unwrap_or(1);
1380
1381 let instances = repeater.instances_vec();
1382 let instance_count = instances.len() as u32;
1383
1384 let step = if let Some(templates) = row_child_templates {
1388 instances
1389 .iter()
1390 .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1391 .max()
1392 .unwrap_or(static_count)
1393 } else {
1394 1
1395 };
1396
1397 let mut current_new_row = new_row;
1398
1399 for instance in &instances {
1400 let inner_sub = instance.root_sub_component.clone();
1401 let cu = inner_sub.compilation_unit.clone();
1402 let sc = &cu.sub_components[inner_sub.sub_component_idx];
1403
1404 let mut statics: Vec<Value> = vec![Value::Void; static_count];
1408 if let Some(expr) = &sc.grid_layout_input_for_repeated {
1409 let expr = expr.borrow();
1410 let mut inner_ctx = EvalContext::new(inner_sub.clone());
1411 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1412 for _ in 0..static_count {
1413 result_model.push(Value::Void);
1414 }
1415 inner_ctx.locals.insert(
1416 SmolStr::new_static("result"),
1417 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1418 );
1419 inner_ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(current_new_row));
1420 eval_expression(&mut inner_ctx, &expr);
1421 for (slot, i) in statics.iter_mut().zip(0..result_model.row_count()) {
1422 if let Some(v) = result_model.row_data(i) {
1423 *slot = v;
1424 }
1425 }
1426 }
1427
1428 if let Some(templates) = row_child_templates {
1429 let mut written = 0usize;
1433 let mut static_idx = 0usize;
1434 for entry in templates {
1435 if written >= step {
1436 break;
1437 }
1438 match entry {
1439 RowChildTemplateInfo::Static { .. } => {
1440 let mut v = statics.get(static_idx).cloned().unwrap_or(Value::Void);
1441 static_idx += 1;
1442 override_new_row(&mut v, written == 0 && current_new_row);
1443 cells.push(v);
1444 written += 1;
1445 }
1446 RowChildTemplateInfo::Repeated { repeater_index } => {
1447 let inner_rep = &inner_sub.repeaters[*repeater_index];
1448 inner_rep.track_instance_changes();
1449 for inner_inst in inner_rep.instances_vec() {
1453 if written >= step {
1454 break;
1455 }
1456 for mut v in eval_grid_input_for_repeated(
1457 &inner_inst.root_sub_component,
1458 written == 0 && current_new_row,
1459 ) {
1460 if written >= step {
1461 break;
1462 }
1463 override_new_row(&mut v, written == 0 && current_new_row);
1464 cells.push(v);
1465 written += 1;
1466 }
1467 }
1468 }
1469 }
1470 }
1471 while written < step {
1472 cells.push(auto_grid_input_data());
1473 written += 1;
1474 }
1475 } else {
1476 cells.push(statics.pop().unwrap_or_else(auto_grid_input_data));
1478 }
1479
1480 if !is_row_repeater {
1481 current_new_row = false;
1482 }
1483 }
1484 (instance_count, step as u32)
1485}
1486
1487fn eval_grid_input_for_repeated(
1492 sub: &Pin<Rc<crate::instance::SubComponentInstance>>,
1493 new_row: bool,
1494) -> Vec<Value> {
1495 use i_slint_core::model::{Model, VecModel};
1496 let cu = sub.compilation_unit.clone();
1497 let sc = &cu.sub_components[sub.sub_component_idx];
1498 let count = sc
1499 .row_child_templates
1500 .as_ref()
1501 .map(|t| i_slint_compiler::llr::static_child_count(t))
1502 .unwrap_or(1)
1503 .max(1);
1504 let Some(expr) = &sc.grid_layout_input_for_repeated else {
1505 return vec![auto_grid_input_data()];
1506 };
1507 let expr = expr.borrow();
1508 let mut ctx = EvalContext::new(sub.clone());
1509 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1510 for _ in 0..count {
1511 result_model.push(Value::Void);
1512 }
1513 ctx.locals.insert(
1514 SmolStr::new_static("result"),
1515 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1516 );
1517 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(new_row));
1518 eval_expression(&mut ctx, &expr);
1519 (0..result_model.row_count())
1520 .map(|i| result_model.row_data(i).unwrap_or_else(auto_grid_input_data))
1521 .collect()
1522}
1523
1524fn auto_grid_input_data() -> Value {
1527 let mut s = crate::api::Struct::default();
1528 s.set_field("new_row".into(), Value::Bool(false));
1529 s.set_field("row".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1530 s.set_field("col".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1531 s.set_field("rowspan".into(), Value::Number(1.0));
1532 s.set_field("colspan".into(), Value::Number(1.0));
1533 Value::Struct(s)
1534}
1535
1536fn override_new_row(v: &mut Value, new_row: bool) {
1537 if let Value::Struct(s) = v {
1538 s.set_field("new_row".into(), Value::Bool(new_row));
1539 }
1540}
1541
1542fn model_from_vec(values: Vec<Value>) -> ModelRc<Value> {
1543 ModelRc::new(SharedVectorModel::from(values.into_iter().collect::<SharedVector<_>>()))
1544}
1545
1546fn binary_op(op: char, lhs: Value, rhs: Value) -> Value {
1547 let (lhs, rhs) = match (lhs, rhs) {
1550 (Value::Void, Value::Number(b)) => (Value::Number(0.), Value::Number(b)),
1551 (Value::Number(a), Value::Void) => (Value::Number(a), Value::Number(0.)),
1552 (Value::Void, Value::Bool(b)) => (Value::Bool(false), Value::Bool(b)),
1553 (Value::Bool(a), Value::Void) => (Value::Bool(a), Value::Bool(false)),
1554 (Value::Void, Value::String(b)) => (Value::String(Default::default()), Value::String(b)),
1555 (Value::String(a), Value::Void) => (Value::String(a), Value::String(Default::default())),
1556 (a, b) => (a, b),
1557 };
1558 match (op, lhs, rhs) {
1559 ('+', Value::String(mut a), Value::String(b)) => {
1560 a.push_str(b.as_str());
1561 Value::String(a)
1562 }
1563 ('+', Value::Number(a), Value::Number(b)) => Value::Number(a + b),
1564 ('+', a @ Value::Struct(_), b @ Value::Struct(_)) => {
1565 let la: Option<i_slint_core::layout::LayoutInfo> = a.try_into().ok();
1566 let lb: Option<i_slint_core::layout::LayoutInfo> = b.try_into().ok();
1567 if let (Some(a), Some(b)) = (la, lb) {
1568 a.merge(&b).into()
1569 } else {
1570 panic!("unsupported struct + struct");
1571 }
1572 }
1573 ('-', Value::Number(a), Value::Number(b)) => Value::Number(a - b),
1574 ('/', Value::Number(a), Value::Number(b)) => Value::Number(a / b),
1575 ('*', Value::Number(a), Value::Number(b)) => Value::Number(a * b),
1576 ('<', Value::Number(a), Value::Number(b)) => Value::Bool(a < b),
1577 ('>', Value::Number(a), Value::Number(b)) => Value::Bool(a > b),
1578 ('≤', Value::Number(a), Value::Number(b)) => Value::Bool(a <= b),
1579 ('≥', Value::Number(a), Value::Number(b)) => Value::Bool(a >= b),
1580 ('<', Value::String(a), Value::String(b)) => Value::Bool(a < b),
1581 ('>', Value::String(a), Value::String(b)) => Value::Bool(a > b),
1582 ('≤', Value::String(a), Value::String(b)) => Value::Bool(a <= b),
1583 ('≥', Value::String(a), Value::String(b)) => Value::Bool(a >= b),
1584 ('=', a, b) => Value::Bool(a == b),
1585 ('!', a, b) => Value::Bool(a != b),
1586 ('&', Value::Bool(a), Value::Bool(b)) => Value::Bool(a && b),
1587 ('|', Value::Bool(a), Value::Bool(b)) => Value::Bool(a || b),
1588 (op, a, b) => panic!("unsupported {a:?} {op} {b:?}"),
1589 }
1590}
1591
1592fn eval_stops(ctx: &mut EvalContext, stops: &[(Expression, Expression)]) -> Vec<GradientStop> {
1593 stops
1594 .iter()
1595 .map(|(color, stop)| GradientStop {
1596 color: eval_expression(ctx, color).try_into().unwrap_or_default(),
1597 position: eval_expression(ctx, stop).try_into().unwrap_or_default(),
1598 })
1599 .collect()
1600}
1601
1602fn load_image_reference(
1603 resource_ref: &i_slint_compiler::expression_tree::ImageReference,
1604) -> i_slint_core::graphics::Image {
1605 use i_slint_compiler::expression_tree::ImageReference as Ref;
1606 let image = match resource_ref {
1607 Ref::None => Ok(Default::default()),
1608 Ref::DataUri(data_uri) => i_slint_compiler::data_uri::decode_data_uri(data_uri)
1609 .ok()
1610 .and_then(|(data, extension)| {
1611 i_slint_core::graphics::load_image_from_data_uri(data_uri, &data, &extension).ok()
1612 })
1613 .ok_or_else(Default::default),
1614 Ref::Url(url) if url.scheme() == "builtin" => {
1615 let path = std::path::Path::new(url.as_str());
1619 i_slint_compiler::fileaccess::load_file(path)
1620 .and_then(|virtual_file| virtual_file.builtin_contents)
1621 .map(|contents| {
1622 let extension = path.extension().unwrap().to_str().unwrap();
1623 i_slint_core::graphics::load_image_from_embedded_data(
1624 i_slint_core::slice::Slice::from_slice(contents),
1625 i_slint_core::slice::Slice::from_slice(extension.as_bytes()),
1626 )
1627 })
1628 .ok_or_else(Default::default)
1629 }
1630 Ref::Path(path) => {
1631 i_slint_core::graphics::Image::load_from_path(std::path::Path::new(path.as_str()))
1632 }
1633 Ref::Url(url) => {
1634 #[cfg(target_arch = "wasm32")]
1635 {
1636 i_slint_core::graphics::load_as_html_image(url.as_str())
1637 }
1638 #[cfg(not(target_arch = "wasm32"))]
1640 {
1641 let _ = url;
1642 Err(Default::default())
1643 }
1644 }
1645 Ref::EmbeddedData { .. } | Ref::EmbeddedTexture { .. } => Ok(Default::default()),
1646 };
1647 image.unwrap_or_else(|_| {
1648 eprintln!("Could not load image {resource_ref:?}");
1649 Default::default()
1650 })
1651}
1652
1653fn layout_cache_access(
1654 ctx: &mut EvalContext,
1655 cache: Value,
1656 index: usize,
1657 repeater_index: Option<&Expression>,
1658 entries_per_item: usize,
1659) -> Value {
1660 match cache {
1661 Value::LayoutCache(cache) => {
1662 if let Some(ri) = repeater_index {
1663 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1664 Value::Number(
1665 cache
1666 .get((cache[index] as usize) + offset * entries_per_item)
1667 .copied()
1668 .unwrap_or(0.)
1669 .into(),
1670 )
1671 } else {
1672 Value::Number(cache[index].into())
1673 }
1674 }
1675 Value::ArrayOfU16(cache) => {
1676 if let Some(ri) = repeater_index {
1677 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1678 Value::Number(
1679 cache
1680 .get((cache[index] as usize) + offset * entries_per_item)
1681 .copied()
1682 .unwrap_or(0)
1683 .into(),
1684 )
1685 } else {
1686 Value::Number(cache[index].into())
1687 }
1688 }
1689 _ => Value::Number(0.),
1690 }
1691}
1692
1693fn grid_repeater_cache_access(
1698 cache: Value,
1699 index: usize,
1700 repeater_index: usize,
1701 stride: usize,
1702 child_offset: usize,
1703 inner_offset: usize,
1704) -> Value {
1705 let get = |data_idx: usize, slice_len: usize, read: &dyn Fn(usize) -> f64| {
1706 if data_idx < slice_len { Value::Number(read(data_idx)) } else { Value::Number(0.) }
1707 };
1708 match cache {
1709 Value::LayoutCache(cache) => {
1710 let base = cache.get(index).copied().unwrap_or(0.) as usize;
1711 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1712 get(data_idx, cache.len(), &|i| cache[i] as f64)
1713 }
1714 Value::ArrayOfU16(cache) => {
1715 let base = cache.get(index).copied().unwrap_or(0) as usize;
1716 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1717 get(data_idx, cache.len(), &|i| cache[i] as f64)
1718 }
1719 _ => Value::Number(0.),
1720 }
1721}
1722
1723fn call_builtin_function(
1725 ctx: &mut EvalContext,
1726 f: BuiltinFunction,
1727 arguments: &[Expression],
1728) -> Value {
1729 let to_num = |ctx: &mut EvalContext, e: &Expression| -> f64 {
1730 eval_expression(ctx, e).try_into().unwrap_or_default()
1731 };
1732 let to_string = |ctx: &mut EvalContext, e: &Expression| -> SharedString {
1733 eval_expression(ctx, e).try_into().unwrap_or_default()
1734 };
1735
1736 match f {
1737 BuiltinFunction::Mod => {
1738 Value::Number(to_num(ctx, &arguments[0]).rem_euclid(to_num(ctx, &arguments[1])))
1739 }
1740 BuiltinFunction::Round => Value::Number(to_num(ctx, &arguments[0]).round()),
1741 BuiltinFunction::Ceil => Value::Number(to_num(ctx, &arguments[0]).ceil()),
1742 BuiltinFunction::Floor => Value::Number(to_num(ctx, &arguments[0]).floor()),
1743 BuiltinFunction::Sqrt => Value::Number(to_num(ctx, &arguments[0]).sqrt()),
1744 BuiltinFunction::Abs => Value::Number(to_num(ctx, &arguments[0]).abs()),
1745 BuiltinFunction::Sin => Value::Number(to_num(ctx, &arguments[0]).to_radians().sin()),
1746 BuiltinFunction::Cos => Value::Number(to_num(ctx, &arguments[0]).to_radians().cos()),
1747 BuiltinFunction::Tan => Value::Number(to_num(ctx, &arguments[0]).to_radians().tan()),
1748 BuiltinFunction::ASin => Value::Number(to_num(ctx, &arguments[0]).asin().to_degrees()),
1749 BuiltinFunction::ACos => Value::Number(to_num(ctx, &arguments[0]).acos().to_degrees()),
1750 BuiltinFunction::ATan => Value::Number(to_num(ctx, &arguments[0]).atan().to_degrees()),
1751 BuiltinFunction::ATan2 => {
1752 Value::Number(to_num(ctx, &arguments[0]).atan2(to_num(ctx, &arguments[1])).to_degrees())
1753 }
1754 BuiltinFunction::Log => {
1755 Value::Number(to_num(ctx, &arguments[0]).log(to_num(ctx, &arguments[1])))
1756 }
1757 BuiltinFunction::Ln => Value::Number(to_num(ctx, &arguments[0]).ln()),
1758 BuiltinFunction::Pow => {
1759 Value::Number(to_num(ctx, &arguments[0]).powf(to_num(ctx, &arguments[1])))
1760 }
1761 BuiltinFunction::Exp => Value::Number(to_num(ctx, &arguments[0]).exp()),
1762 BuiltinFunction::ToFixed => {
1763 let n = to_num(ctx, &arguments[0]);
1764 let digits: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1765 Value::String(i_slint_core::string::shared_string_from_number_fixed(
1766 n,
1767 digits.max(0) as usize,
1768 ))
1769 }
1770 BuiltinFunction::ToPrecision => {
1771 let n = to_num(ctx, &arguments[0]);
1772 let p: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1773 Value::String(i_slint_core::string::shared_string_from_number_precision(
1774 n,
1775 p.max(0) as usize,
1776 ))
1777 }
1778 BuiltinFunction::StringStartsWith => Value::Bool(
1779 to_string(ctx, &arguments[0])
1780 .as_str()
1781 .starts_with(to_string(ctx, &arguments[1]).as_str()),
1782 ),
1783 BuiltinFunction::StringEndsWith => Value::Bool(
1784 to_string(ctx, &arguments[0])
1785 .as_str()
1786 .ends_with(to_string(ctx, &arguments[1]).as_str()),
1787 ),
1788 BuiltinFunction::ToStringUnlocalized => {
1789 let n = to_num(ctx, &arguments[0]);
1790 Value::String(i_slint_core::string::shared_string_from_number_unlocalized(n))
1791 }
1792 BuiltinFunction::DecimalSeparator => Value::String(
1793 find_window_adapter(ctx)
1794 .map(|adapter| {
1795 i_slint_core::window::WindowInner::from_pub(adapter.window())
1796 .context()
1797 .locale_decimal_separator()
1798 })
1799 .unwrap_or_default()
1800 .into(),
1801 ),
1802 BuiltinFunction::MacosBringAllWindowsToFront => {
1803 i_slint_core::macos_bring_all_windows_to_front();
1804 Value::Void
1805 }
1806 BuiltinFunction::ColorToStyledText => {
1807 let color: i_slint_core::Color =
1808 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
1809 Value::StyledText(i_slint_core::styled_text::color_to_styled_text(color))
1810 }
1811 BuiltinFunction::SetupSystemTrayIcon => {
1812 crate::popup::setup_system_tray_icon(ctx, arguments)
1813 }
1814 BuiltinFunction::StringIsFloat => Value::Bool(
1815 <f64 as core::str::FromStr>::from_str(to_string(ctx, &arguments[0]).as_str()).is_ok(),
1816 ),
1817 BuiltinFunction::StringToFloat => Value::Number(
1818 core::str::FromStr::from_str(to_string(ctx, &arguments[0]).as_str()).unwrap_or(0.),
1819 ),
1820 BuiltinFunction::StringIsEmpty => Value::Bool(to_string(ctx, &arguments[0]).is_empty()),
1821 BuiltinFunction::StringCharacterCount => Value::Number(
1822 unicode_segmentation::UnicodeSegmentation::graphemes(
1823 to_string(ctx, &arguments[0]).as_str(),
1824 true,
1825 )
1826 .count() as f64,
1827 ),
1828 BuiltinFunction::StringToLowercase => {
1829 Value::String(to_string(ctx, &arguments[0]).to_lowercase().into())
1830 }
1831 BuiltinFunction::StringToUppercase => {
1832 Value::String(to_string(ctx, &arguments[0]).to_uppercase().into())
1833 }
1834 BuiltinFunction::ColorRgbaStruct => {
1835 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1836 let color = brush.color();
1837 let values = [
1838 ("red".to_string(), Value::Number(color.red().into())),
1839 ("green".to_string(), Value::Number(color.green().into())),
1840 ("blue".to_string(), Value::Number(color.blue().into())),
1841 ("alpha".to_string(), Value::Number(color.alpha().into())),
1842 ]
1843 .into_iter()
1844 .collect();
1845 Value::Struct(values)
1846 } else {
1847 Value::Void
1848 }
1849 }
1850 BuiltinFunction::ColorHsvaStruct => {
1851 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1852 let color = brush.color().to_hsva();
1853 let values = [
1854 ("hue".to_string(), Value::Number(color.hue.into())),
1855 ("saturation".to_string(), Value::Number(color.saturation.into())),
1856 ("value".to_string(), Value::Number(color.value.into())),
1857 ("alpha".to_string(), Value::Number(color.alpha.into())),
1858 ]
1859 .into_iter()
1860 .collect();
1861 Value::Struct(values)
1862 } else {
1863 Value::Void
1864 }
1865 }
1866 BuiltinFunction::ColorOklchStruct => {
1867 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1868 let color = brush.color().to_oklch();
1869 let values = [
1870 ("lightness".to_string(), Value::Number(color.lightness.into())),
1871 ("chroma".to_string(), Value::Number(color.chroma.into())),
1872 ("hue".to_string(), Value::Number(color.hue.into())),
1873 ("alpha".to_string(), Value::Number(color.alpha.into())),
1874 ]
1875 .into_iter()
1876 .collect();
1877 Value::Struct(values)
1878 } else {
1879 Value::Void
1880 }
1881 }
1882 BuiltinFunction::ColorBrighter => {
1883 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1884 brush.brighter(to_num(ctx, &arguments[1]) as f32).into()
1885 } else {
1886 Value::Void
1887 }
1888 }
1889 BuiltinFunction::ColorDarker => {
1890 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1891 brush.darker(to_num(ctx, &arguments[1]) as f32).into()
1892 } else {
1893 Value::Void
1894 }
1895 }
1896 BuiltinFunction::ColorTransparentize => {
1897 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1898 brush.transparentize(to_num(ctx, &arguments[1]) as f32).into()
1899 } else {
1900 Value::Void
1901 }
1902 }
1903 BuiltinFunction::ColorWithAlpha => {
1904 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1905 brush.with_alpha(to_num(ctx, &arguments[1]) as f32).into()
1906 } else {
1907 Value::Void
1908 }
1909 }
1910 BuiltinFunction::ColorMix => {
1911 let a = eval_expression(ctx, &arguments[0]);
1912 let b = eval_expression(ctx, &arguments[1]);
1913 let factor = to_num(ctx, &arguments[2]) as f32;
1914 if let (
1915 Value::Brush(i_slint_core::Brush::SolidColor(ca)),
1916 Value::Brush(i_slint_core::Brush::SolidColor(cb)),
1917 ) = (a, b)
1918 {
1919 ca.mix(&cb, factor).into()
1920 } else {
1921 Value::Void
1922 }
1923 }
1924 BuiltinFunction::ArrayPush => {
1925 if arguments.len() != 2 {
1926 panic!("internal error: incorrect argument count to ArrayPush")
1927 }
1928
1929 let model = match eval_expression(ctx, &arguments[0]) {
1930 Value::Model(m) => m,
1931 _ => panic!("First argument not an array: {:?}", arguments[0]),
1932 };
1933 let value = eval_expression(ctx, &arguments[1]);
1934
1935 model.push_row(value);
1936
1937 Value::Void
1938 }
1939 BuiltinFunction::ArrayRemove => {
1940 if arguments.len() != 2 {
1941 panic!("internal error: incorrect argument count to ArrayRemove")
1942 }
1943
1944 let model = match eval_expression(ctx, &arguments[0]) {
1945 Value::Model(m) => m,
1946 _ => panic!("First argument not an array: {:?}", arguments[0]),
1947 };
1948 let index = match eval_expression(ctx, &arguments[1]) {
1949 Value::Number(i) => i,
1950 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1951 };
1952
1953 model.remove_row(index as isize);
1954
1955 Value::Void
1956 }
1957
1958 BuiltinFunction::ArrayInsert => {
1959 if arguments.len() != 3 {
1960 panic!("internal error: incorrect argument count to ArrayInsert")
1961 }
1962
1963 let model = match eval_expression(ctx, &arguments[0]) {
1964 Value::Model(m) => m,
1965 _ => panic!("First argument not an array: {:?}", arguments[0]),
1966 };
1967 let index = match eval_expression(ctx, &arguments[1]) {
1968 Value::Number(i) => i,
1969 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1970 };
1971
1972 let value = eval_expression(ctx, &arguments[2]);
1973 model.insert_row(index as isize, value);
1974
1975 Value::Void
1976 }
1977 BuiltinFunction::Rgb => {
1978 let r: i32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
1979 let g: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
1980 let b: i32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
1981 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
1982 let r: u8 = r.clamp(0, 255) as u8;
1983 let g: u8 = g.clamp(0, 255) as u8;
1984 let b: u8 = b.clamp(0, 255) as u8;
1985 let a: u8 = (255. * a).clamp(0., 255.) as u8;
1986 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_argb_u8(
1987 a, r, g, b,
1988 )))
1989 }
1990 BuiltinFunction::Hsv => {
1991 let h: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
1992 let s: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
1993 let v: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
1994 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
1995 let a = a.clamp(0., 1.);
1996 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_hsva(
1997 h, s, v, a,
1998 )))
1999 }
2000 BuiltinFunction::Oklch => {
2001 let l: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2002 let c: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2003 let h: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2004 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2005 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_oklch(
2006 l.clamp(0.0, 1.0),
2007 c,
2008 h,
2009 a.clamp(0.0, 1.0),
2010 )))
2011 }
2012 BuiltinFunction::AnimationTick => {
2013 Value::Number(i_slint_core::animations::animation_tick() as f64)
2014 }
2015 BuiltinFunction::GetWindowScaleFactor => {
2016 let factor = root_instance(ctx)
2017 .and_then(|inst| inst.window_adapter_or_default())
2018 .map(|adapter| {
2019 i_slint_core::window::WindowInner::from_pub(adapter.window()).scale_factor()
2020 as f64
2021 })
2022 .unwrap_or(1.0);
2023 Value::Number(factor)
2024 }
2025 BuiltinFunction::GetWindowDefaultFontSize => {
2026 let size = root_instance(ctx)
2032 .map(|inst| {
2033 i_slint_core::items::WindowItem::resolved_default_font_size(
2034 vtable::VRc::into_dyn(inst),
2035 )
2036 .get() as f64
2037 })
2038 .unwrap_or(12.0);
2039 Value::Number(size)
2040 }
2041 BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
2042 BuiltinFunction::Use24HourFormat => {
2043 Value::Bool(i_slint_core::date_time::use_24_hour_format())
2044 }
2045 BuiltinFunction::ColorScheme => {
2046 let scheme = root_instance(ctx)
2047 .map(vtable::VRc::into_dyn)
2048 .and_then(|root| {
2049 i_slint_core::window::context_for_root(&root)
2050 .map(|ctx| ctx.color_scheme(Some(&root)))
2051 })
2052 .unwrap_or(i_slint_core::items::ColorScheme::Unknown);
2053 scheme.into()
2054 }
2055 BuiltinFunction::AccentColor => {
2056 let color = root_instance(ctx)
2057 .map(vtable::VRc::into_dyn)
2058 .map(|root| i_slint_core::window::accent_color(&root))
2059 .unwrap_or_default();
2060 Value::Brush(i_slint_core::Brush::SolidColor(color))
2061 }
2062 BuiltinFunction::SupportsNativeMenuBar => {
2063 let supports = find_window_adapter(ctx).is_some_and(|a| {
2064 a.internal(i_slint_core::InternalToken)
2065 .is_some_and(|x| x.supports_native_menu_bar())
2066 });
2067 Value::Bool(supports)
2068 }
2069 BuiltinFunction::TextInputFocused => {
2070 let focused = ctx
2071 .current
2072 .as_ref()
2073 .and_then(|c| c.root.get())
2074 .and_then(|w| w.upgrade())
2075 .and_then(|inst| inst.window_adapter_or_default())
2076 .map(|adapter| {
2077 i_slint_core::window::WindowInner::from_pub(adapter.window())
2078 .text_input_focused()
2079 })
2080 .unwrap_or(false);
2081 Value::Bool(focused)
2082 }
2083 BuiltinFunction::SetTextInputFocused => {
2084 let value = arguments
2085 .first()
2086 .map(|e| eval_expression(ctx, e))
2087 .and_then(|v| bool::try_from(v).ok())
2088 .unwrap_or(false);
2089 if let Some(adapter) = ctx
2090 .current
2091 .as_ref()
2092 .and_then(|c| c.root.get())
2093 .and_then(|w| w.upgrade())
2094 .and_then(|inst| inst.window_adapter_or_default())
2095 {
2096 i_slint_core::window::WindowInner::from_pub(adapter.window())
2097 .set_text_input_focused(value);
2098 }
2099 Value::Void
2100 }
2101 BuiltinFunction::UpdateTimers => {
2102 Value::Void
2105 }
2106 BuiltinFunction::RestartTimer => {
2107 if let [
2112 Expression::PropertyReference(MemberReference::Relative {
2113 parent_level,
2114 local_reference,
2115 }),
2116 ] = arguments
2117 && let LocalMemberIndex::Timer(timer_idx) = &local_reference.reference
2118 && ctx.current.is_some()
2119 {
2120 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2121 if let Some(timer) = instance.timers.get(usize::from(*timer_idx)) {
2122 timer.restart();
2123 }
2124 }
2125 Value::Void
2126 }
2127 BuiltinFunction::KeysToString => {
2128 let v = arguments.first().map(|e| eval_expression(ctx, e));
2129 if let Some(Value::Keys(keys)) = v {
2130 Value::String(keys.to_string().into())
2131 } else {
2132 Value::String(Default::default())
2133 }
2134 }
2135 BuiltinFunction::SetSelectionOffsets => {
2136 use i_slint_core::items::TextInput;
2138 let [Expression::PropertyReference(mr), start_expr, end_expr] = arguments else {
2139 return Value::Void;
2140 };
2141 let start: i32 = eval_expression(ctx, start_expr).try_into().unwrap_or(0);
2142 let end: i32 = eval_expression(ctx, end_expr).try_into().unwrap_or(0);
2143 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr) else {
2144 return Value::Void;
2145 };
2146 let Some(adapter) = parent_inst.window_adapter_or_default() else {
2147 return Value::Void;
2148 };
2149 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2150 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2151 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_rc.borrow()) {
2152 text_input.set_selection_offsets(&adapter, &item_rc, start, end);
2153 }
2154 Value::Void
2155 }
2156 BuiltinFunction::RegisterCustomFontByPath => {
2157 if let Value::String(s) = eval_expression(ctx, &arguments[0])
2158 && let Some(root) = find_root_instance(ctx)
2159 {
2160 let result =
2163 root.try_window_adapter().map_err(|e| e.to_string()).and_then(|adapter| {
2164 adapter
2165 .renderer()
2166 .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
2167 .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
2168 });
2169 if let Err(err) = result {
2170 i_slint_core::debug_log!("{err}");
2171 }
2172 }
2173 Value::Void
2174 }
2175 BuiltinFunction::SetupMenuBar => crate::popup::setup_menubar(ctx, arguments),
2176 BuiltinFunction::ItemFontMetrics => {
2177 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2178 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2179 && let Some(adapter) = inst.window_adapter_or_default()
2180 {
2181 let item_rc =
2182 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2183 let metrics = i_slint_core::items::slint_text_item_fontmetrics(
2184 &adapter,
2185 item_rc.borrow(),
2186 &item_rc,
2187 );
2188 return metrics.into();
2189 }
2190 i_slint_core::items::FontMetrics::default().into()
2191 }
2192 BuiltinFunction::ItemAbsolutePosition => {
2193 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2194 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2195 {
2196 let item_rc =
2197 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2198 return item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into();
2202 }
2203 i_slint_core::api::LogicalPosition::default().into()
2204 }
2205 BuiltinFunction::PathPointAt => {
2206 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2207 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2208 {
2209 let item_rc =
2210 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2211 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2212 return item_rc
2213 .downcast::<i_slint_core::items::Path>()
2214 .unwrap()
2215 .as_pin_ref()
2216 .point_at(&item_rc, t)
2217 .to_untyped()
2218 .into();
2219 }
2220 panic!("internal error: argument to PathPointAt must be an element")
2221 }
2222 BuiltinFunction::PathAngleAt => {
2223 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2224 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2225 {
2226 let item_rc =
2227 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2228 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2229 return item_rc
2230 .downcast::<i_slint_core::items::Path>()
2231 .unwrap()
2232 .as_pin_ref()
2233 .angle_at(&item_rc, t)
2234 .into();
2235 }
2236 panic!("internal error: argument to PathAngleAt must be an element")
2237 }
2238 BuiltinFunction::ArrayAny | BuiltinFunction::ArrayAll => {
2239 let is_all = matches!(f, BuiltinFunction::ArrayAll);
2240 let model: i_slint_core::model::ModelRc<Value> =
2241 eval_expression(ctx, &arguments[0]).try_into().unwrap();
2242 let Expression::Closure { arg_name, expression } = &arguments[1] else {
2243 panic!("internal error: Array.any/all expects a closure as second argument")
2244 };
2245 let mut predicate = |x: Value| -> bool {
2248 let previous = ctx.locals.insert(arg_name.clone(), x);
2249 let result: bool = eval_expression(ctx, expression).try_into().unwrap();
2250 match previous {
2251 Some(prev) => {
2252 ctx.locals.insert(arg_name.clone(), prev);
2253 }
2254 None => {
2255 ctx.locals.remove(arg_name);
2256 }
2257 }
2258 result
2259 };
2260 Value::Bool(if is_all {
2261 i_slint_core::model::model_all(&model, &mut predicate)
2262 } else {
2263 i_slint_core::model::model_any(&model, &mut predicate)
2264 })
2265 }
2266 BuiltinFunction::ImplicitLayoutInfo(orient) => {
2267 let constraint: f32 = arguments
2271 .get(1)
2272 .map(|e| eval_expression(ctx, e).try_into().unwrap_or(-1.))
2273 .unwrap_or(-1.);
2274 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2275 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2276 && let Some(adapter) = inst.window_adapter_or_default()
2277 {
2278 let item_rc =
2279 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2280 return item_rc
2281 .borrow()
2282 .as_ref()
2283 .layout_info(
2284 llr_to_core_orientation(orient),
2285 constraint as _,
2286 &adapter,
2287 &item_rc,
2288 )
2289 .into();
2290 }
2291 i_slint_core::layout::LayoutInfo::default().into()
2292 }
2293 BuiltinFunction::Debug => {
2294 use i_slint_core::debug_log::*;
2295 let msg = to_string(ctx, &arguments[0]);
2296 let root = ctx
2297 .current
2298 .as_ref()
2299 .and_then(|c| c.root.get())
2300 .and_then(|w| w.upgrade())
2301 .map(vtable::VRc::into_dyn);
2302 if let Some(context) = root.as_ref().and_then(i_slint_core::window::context_for_root) {
2303 context.dispatch_log_message(LogMessage::new(
2304 LogMessageSource::SlintCode,
2305 None,
2306 format_args!("{msg}"),
2307 ));
2308 } else {
2309 log_message(LogMessage::new(
2310 LogMessageSource::SlintCode,
2311 None,
2312 format_args!("{msg}"),
2313 ));
2314 }
2315 Value::Void
2316 }
2317 BuiltinFunction::ArrayLength => match eval_expression(ctx, &arguments[0]) {
2318 Value::Model(m) => {
2321 m.model_tracker().track_row_count_changes();
2322 Value::Number(m.row_count() as f64)
2323 }
2324 _ => Value::Number(0.),
2325 },
2326 BuiltinFunction::ImageSize => {
2327 if let Value::Image(img) = eval_expression(ctx, &arguments[0]) {
2328 let size = img.size();
2329 let mut s = crate::api::Struct::default();
2330 s.set_field("width".to_string(), Value::Number(size.width as f64));
2331 s.set_field("height".to_string(), Value::Number(size.height as f64));
2332 Value::Struct(s)
2333 } else {
2334 Value::Void
2335 }
2336 }
2337 BuiltinFunction::ParseMarkdown => {
2338 let format_string: SharedString =
2339 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2340 let args = eval_expression(ctx, &arguments[1]);
2341 let args: Vec<i_slint_core::styled_text::StyledText> = if let Value::Model(m) = args {
2342 (0..m.row_count())
2343 .filter_map(|i| match m.row_data(i)? {
2344 Value::StyledText(t) => Some(t),
2345 _ => None,
2346 })
2347 .collect()
2348 } else {
2349 Vec::new()
2350 };
2351 Value::StyledText(i_slint_core::styled_text::parse_markdown(&format_string, &args))
2352 }
2353 BuiltinFunction::StringToStyledText => {
2354 let string: SharedString =
2355 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2356 Value::StyledText(i_slint_core::styled_text::string_to_styled_text(string.to_string()))
2357 }
2358 BuiltinFunction::Translate => {
2359 let original: SharedString = to_string(ctx, &arguments[0]);
2360 let context: SharedString = to_string(ctx, &arguments[1]);
2361 let domain: SharedString = to_string(ctx, &arguments[2]);
2362 let args = eval_expression(ctx, &arguments[3]);
2363 let Value::Model(args) = args else {
2364 return Value::String(original);
2365 };
2366 struct StringModelWrapper(ModelRc<Value>);
2367 impl i_slint_core::translations::FormatArgs for StringModelWrapper {
2368 type Output<'a> = SharedString;
2369 fn from_index(&self, index: usize) -> Option<SharedString> {
2370 self.0.row_data(index).and_then(|v| v.try_into().ok())
2371 }
2372 }
2373 let n: i32 = eval_expression(ctx, &arguments[4]).try_into().unwrap_or(0);
2374 let plural: SharedString = to_string(ctx, &arguments[5]);
2375 Value::String(i_slint_core::translations::translate(
2376 &original,
2377 &context,
2378 &domain,
2379 &StringModelWrapper(args),
2380 n,
2381 &plural,
2382 ))
2383 }
2384 BuiltinFunction::ShowPopupWindow => crate::popup::show_popup_window(ctx, arguments),
2385 BuiltinFunction::ClosePopupWindow => crate::popup::close_popup_window(ctx, arguments),
2386 BuiltinFunction::SetFocusItem => {
2387 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2388 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2389 && let Some(adapter) = find_window_adapter(ctx)
2390 {
2391 let dyn_rc = vtable::VRc::into_dyn(inst);
2392 let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2393 i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2394 &item_rc,
2395 true,
2396 i_slint_core::input::FocusReason::Programmatic,
2397 );
2398 }
2399 Value::Void
2400 }
2401 BuiltinFunction::ClearFocusItem => {
2402 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2403 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2404 && let Some(adapter) = find_window_adapter(ctx)
2405 {
2406 let dyn_rc = vtable::VRc::into_dyn(inst);
2407 let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2408 i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2409 &item_rc,
2410 false,
2411 i_slint_core::input::FocusReason::Programmatic,
2412 );
2413 }
2414 Value::Void
2415 }
2416 BuiltinFunction::MonthDayCount => {
2417 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2418 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2419 Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
2420 }
2421 BuiltinFunction::MonthOffset => {
2422 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2423 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2424 Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
2425 }
2426 BuiltinFunction::FormatDate => {
2427 let f: SharedString = to_string(ctx, &arguments[0]);
2428 let d: u32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2429 let m: u32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2430 let y: i32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(0);
2431 Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
2432 }
2433 BuiltinFunction::DateNow => {
2434 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2435 i_slint_core::date_time::date_now()
2436 .into_iter()
2437 .map(|x| Value::Number(x as f64))
2438 .collect::<Vec<_>>(),
2439 )))
2440 }
2441 BuiltinFunction::ValidDate => {
2442 let d: SharedString = to_string(ctx, &arguments[0]);
2443 let f: SharedString = to_string(ctx, &arguments[1]);
2444 Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
2445 }
2446 BuiltinFunction::ParseDate => {
2447 let d: SharedString = to_string(ctx, &arguments[0]);
2448 let f: SharedString = to_string(ctx, &arguments[1]);
2449 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2450 i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
2451 .map(|v| v.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>())
2452 .unwrap_or_default(),
2453 )))
2454 }
2455 BuiltinFunction::ShowPopupMenu | BuiltinFunction::ShowPopupMenuInternal => {
2456 crate::popup::show_popup_menu(ctx, arguments)
2457 }
2458 BuiltinFunction::OpenUrl => {
2459 let url = to_string(ctx, &arguments[0]);
2460 let result = find_window_adapter(ctx)
2461 .map(|adapter| i_slint_core::open_url(&url, adapter.window()).is_ok())
2462 .unwrap_or(false);
2463 Value::Bool(result)
2464 }
2465 BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
2466 Value::Void
2468 }
2469 BuiltinFunction::StartTimer | BuiltinFunction::StopTimer => {
2470 Value::Void
2472 }
2473 }
2474}
2475
2476pub(crate) fn resolve_item_rc_from_ref(
2480 ctx: &EvalContext,
2481 mr: &MemberReference,
2482) -> Option<(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>, usize)>
2483{
2484 let MemberReference::Relative { parent_level, local_reference } = mr else { return None };
2485 let LocalMemberIndex::Native { item_index, .. } = &local_reference.reference else {
2486 return None;
2487 };
2488 let owner = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2489 let parent_inst = owner.root.get().and_then(|w| w.upgrade())?;
2490 let full_path = crate::item_tree_vtable::sub_component_path_of(&owner, &parent_inst);
2491 let flat_idx = find_flat_item_index(&parent_inst.item_table, &full_path, *item_index)?;
2492 Some((parent_inst, flat_idx))
2493}
2494
2495pub(crate) fn find_root_instance(
2499 ctx: &EvalContext,
2500) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
2501 let current = ctx.current.as_ref()?;
2502 let mut sub = current.clone();
2503 loop {
2504 if let Some(root) = sub.root.get()
2505 && let Some(inst) = root.upgrade()
2506 && inst.public_component_index.is_some()
2507 {
2508 return Some(inst);
2509 }
2510 let parent = sub.parent.upgrade()?;
2511 sub = Pin::new(parent);
2512 }
2513}
2514
2515pub(crate) fn find_window_adapter(
2517 ctx: &EvalContext,
2518) -> Option<i_slint_core::window::WindowAdapterRc> {
2519 find_root_instance(ctx)?.window_adapter_or_default()
2520}
2521
2522fn call_item_member_function(ctx: &EvalContext, function: &MemberReference) -> Value {
2526 use i_slint_core::items::{ContextMenu, SwipeGestureHandler, TextInput, WindowItem};
2527 let MemberReference::Relative { local_reference, .. } = function else {
2528 return Value::Void;
2529 };
2530 let LocalMemberIndex::Native { prop_name, .. } = &local_reference.reference else {
2531 return Value::Void;
2532 };
2533 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, function) else {
2534 return Value::Void;
2535 };
2536 let Some(adapter) = parent_inst.window_adapter_or_default() else { return Value::Void };
2537 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2538 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2539 let item_ref = item_rc.borrow();
2540
2541 macro_rules! dispatch {
2544 ($item:expr, $name:expr; $($slint_name:literal => $rust_method:ident $(=> $into:ty)?),* $(,)?) => {
2545 match $name {
2546 $(
2547 $slint_name => {
2548 let res = $item.$rust_method(&adapter, &item_rc);
2549 $(let res: $into = res.into();)?
2550 return res.into();
2551 }
2552 )*
2553 _ => {}
2554 }
2555 };
2556 }
2557
2558 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_ref) {
2559 dispatch!(text_input, prop_name.as_str();
2560 "select-all" => select_all => (),
2561 "clear-selection" => clear_selection => (),
2562 "select-word" => select_word => (),
2563 "cut" => cut => (),
2564 "copy" => copy => (),
2565 "paste" => paste => (),
2566 "undo" => undo => (),
2567 "redo" => redo => (),
2568 );
2569 }
2570 if let Some(swipe) = vtable::VRef::downcast_pin::<SwipeGestureHandler>(item_rc.borrow()) {
2571 dispatch!(swipe, prop_name.as_str();
2572 "cancel" => cancel => (),
2573 );
2574 }
2575 if let Some(menu) = vtable::VRef::downcast_pin::<ContextMenu>(item_rc.borrow()) {
2576 dispatch!(menu, prop_name.as_str();
2577 "close" => close => (),
2578 "is-open" => is_open,
2579 );
2580 }
2581 if let Some(window) = vtable::VRef::downcast_pin::<WindowItem>(item_rc.borrow()) {
2582 match prop_name.as_str() {
2583 "hide" => {
2584 window.hide(&adapter, &item_rc);
2585 return Value::Void;
2586 }
2587 "close" => return Value::Bool(window.close(&adapter, &item_rc)),
2588 _ => {}
2589 }
2590 }
2591 unimplemented!("ItemMemberFunctionCall `{prop_name}`")
2592}