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