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 _ => Value::Void,
640 }
641}
642
643pub fn default_value_for_struct_field(
647 s: &i_slint_compiler::langtype::Struct,
648 field_name: &str,
649) -> Value {
650 match s.field_defaults.get(field_name) {
651 Some(expr) => eval_constant_expression(expr),
652 None => default_value_for_type(
653 s.fields.get(field_name).expect("default value requested for unknown struct field"),
654 ),
655 }
656}
657
658fn eval_constant_expression(expr: &ConstantExpression) -> Value {
661 match expr {
662 ConstantExpression::StringLiteral(s) => Value::String(s.as_str().into()),
663 ConstantExpression::NumberLiteral(n, _unit) => Value::Number(*n),
664 ConstantExpression::BoolLiteral(b) => Value::Bool(*b),
665 ConstantExpression::EnumerationValue(value) => {
666 Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
667 }
668 ConstantExpression::Cast { from, to } => {
669 cast_constant_value(eval_constant_expression(from), to)
670 }
671 ConstantExpression::UnaryOp { sub, op } => {
672 match (eval_constant_expression(sub), op) {
674 (Value::Number(a), '+') => Value::Number(a),
675 (Value::Number(a), '-') => Value::Number(-a),
676 (Value::Bool(a), '!') => Value::Bool(!a),
677 (sub, _) => panic!("unsupported {op} {sub:?}"),
678 }
679 }
680 ConstantExpression::Struct { values, .. } => Value::Struct(
681 values
682 .iter()
683 .map(|(k, v)| (k.to_string(), eval_constant_expression(v)))
684 .collect::<crate::api::Struct>(),
685 ),
686 ConstantExpression::Array { values, .. } => {
687 Value::Model(ModelRc::new(SharedVectorModel::from(
688 values.iter().map(eval_constant_expression).collect::<SharedVector<_>>(),
689 )))
690 }
691 }
692}
693
694fn cast_constant_value(value: Value, to: &Type) -> Value {
696 match (value, to) {
697 (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
698 (Value::Number(n), Type::String) => {
699 Value::String(i_slint_core::string::shared_string_from_number(n))
700 }
701 (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
702 (Value::Brush(brush), Type::Color) => brush.color().into(),
703 (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
704 (v, _) => v,
705 }
706}
707
708pub fn eval_expression(ctx: &mut EvalContext, expression: &Expression) -> Value {
709 if let Some(r) = &ctx.return_value {
710 return r.clone();
711 }
712 match expression {
713 Expression::StringLiteral(s) => Value::String(s.as_str().into()),
714 Expression::NumberLiteral(n) => Value::Number(*n),
715 Expression::BoolLiteral(b) => Value::Bool(*b),
716 Expression::KeysLiteral(ks) => Value::Keys({
717 let mut modifiers = i_slint_core::input::KeyboardModifiers::default();
718 modifiers.alt = ks.modifiers.alt;
719 modifiers.control = ks.modifiers.control;
720 modifiers.shift = ks.modifiers.shift;
721 modifiers.meta = ks.modifiers.meta;
722 i_slint_core::input::make_keys(
723 SharedString::from(&*ks.key),
724 modifiers,
725 ks.ignore_shift,
726 ks.ignore_alt,
727 )
728 }),
729 Expression::PropertyReference(mr) => load_property(ctx, mr),
730 Expression::FunctionParameterReference { index } => ctx.function_arguments[*index].clone(),
731 Expression::StoreLocalVariable { name, value } => {
732 let v = eval_expression(ctx, value);
733 ctx.locals.insert(name.clone(), v);
734 Value::Void
735 }
736 Expression::ReadLocalVariable { name, .. } => {
737 ctx.locals.get(name).cloned().unwrap_or(Value::Void)
738 }
739 Expression::StructFieldAccess { base, name } => {
740 if let Value::Struct(s) = eval_expression(ctx, base) {
741 s.get_field(name).cloned().unwrap_or(Value::Void)
742 } else {
743 Value::Void
744 }
745 }
746 Expression::ArrayIndex { array, index } => {
747 let array_v = eval_expression(ctx, array);
748 let index = eval_expression(ctx, index);
749 match (array_v, index) {
750 (Value::Model(m), Value::Number(i)) => {
751 let idx = i as isize as usize;
752 m.row_data_tracked(idx).unwrap_or_else(|| {
753 default_value_for_type(&expression.ty(&*ctx))
756 })
757 }
758 _ => Value::Void,
759 }
760 }
761 Expression::Cast { from, to } => {
762 if matches!(to, Type::PathData) {
766 return cast_to_path_data(ctx, from);
767 }
768 let v = eval_expression(ctx, from);
769 match (v, to) {
770 (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
771 (Value::Number(n), Type::String) => {
772 Value::String(i_slint_core::string::shared_string_from_number(n))
773 }
774 (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
775 (Value::Brush(brush), Type::Color) => brush.color().into(),
776 (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
777 (v, _) => v,
778 }
779 }
780 Expression::CodeBlock(sub) => {
781 let mut v = Value::Void;
782 for e in sub {
783 v = eval_expression(ctx, e);
784 if let Some(r) = &ctx.return_value {
785 return r.clone();
786 }
787 }
788 v
789 }
790 Expression::BuiltinFunctionCall { function, arguments } => {
791 call_builtin_function(ctx, function.clone(), arguments)
792 }
793 Expression::CallBackCall { callback, arguments } => {
794 let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
795 invoke_callback(ctx, callback, &args)
796 }
797 Expression::FunctionCall { function, arguments } => {
798 let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
799 invoke_function(ctx, function, args)
800 }
801 Expression::ItemMemberFunctionCall { function } => call_item_member_function(ctx, function),
802 Expression::ExtraBuiltinFunctionCall { function, arguments, .. } => {
803 crate::eval_layout::call_extra_builtin(ctx, function, arguments)
804 }
805 Expression::PropertyAssignment { property, value } => {
806 let v = eval_expression(ctx, value);
807 store_property(ctx, property, v);
808 Value::Void
809 }
810 Expression::ModelDataAssignment { level, value } => {
811 let new_value = eval_expression(ctx, value);
812 if let Some(current) = ctx.current.as_ref() {
813 let mut walker = current.clone();
814 for _ in 0..*level {
815 let parent = walker.parent.upgrade().expect("parent vanished");
816 walker = std::pin::Pin::new(parent);
817 }
818 if let Some((parent_weak, repeater_idx)) = walker.repeated_in.get()
819 && let Some(parent) = parent_weak.upgrade()
820 {
821 let row = walker.compilation_unit.sub_components[walker.sub_component_idx]
824 .properties
825 .iter_enumerated()
826 .find(|(_, p)| p.name.as_str() == "model_index")
827 .map(|(idx, _)| {
828 let v = std::pin::Pin::as_ref(&walker.properties[idx]).get();
829 f64::try_from(v).unwrap_or(0.) as usize
830 })
831 .unwrap_or(0);
832 let parent_pinned = std::pin::Pin::new(parent);
833 let repeater = &parent_pinned.repeaters[*repeater_idx];
834 repeater.model_set_row_data(row, new_value);
835 }
836 }
837 Value::Void
838 }
839 Expression::ArrayIndexAssignment { array, index, value } => {
840 let value = eval_expression(ctx, value);
841 let array = eval_expression(ctx, array);
842 let index = eval_expression(ctx, index);
843 if let (Value::Model(m), Value::Number(i)) = (array, index)
844 && i >= 0.0
845 {
846 let i = i.trunc() as usize;
847 if i < m.row_count() {
848 m.set_row_data(i, value);
849 }
850 }
851 Value::Void
852 }
853 Expression::SliceIndexAssignment { slice_name, index, value } => {
854 let value = eval_expression(ctx, value);
855 match ctx.locals.get_mut(slice_name.as_str()) {
856 Some(Value::ArrayOfU16(vec)) => {
857 if let Value::Number(n) = value
858 && *index < vec.len()
859 {
860 vec.make_mut_slice()[*index] = n as u16;
861 }
862 }
863 Some(Value::Model(m)) if *index < m.row_count() => {
864 m.set_row_data(*index, value);
865 }
866 _ => {}
867 }
868 Value::Void
869 }
870 Expression::BinaryExpression { lhs, rhs, op } => {
871 let lhs = eval_expression(ctx, lhs);
872 match (op, &lhs) {
875 ('&', Value::Bool(false)) => return Value::Bool(false),
876 ('|', Value::Bool(true)) => return Value::Bool(true),
877 _ => {}
878 }
879 let rhs = eval_expression(ctx, rhs);
880 binary_op(*op, lhs, rhs)
881 }
882 Expression::UnaryOp { sub, op } => {
883 let sub = eval_expression(ctx, sub);
884 match (sub, op) {
885 (Value::Number(a), '+') => Value::Number(a),
886 (Value::Number(a), '-') => Value::Number(-a),
887 (Value::Bool(a), '!') => Value::Bool(!a),
888 (Value::Void, '+' | '-') => Value::Number(0.0),
891 (Value::Void, '!') => Value::Bool(true),
892 (s, o) => panic!("unsupported {o} {s:?}"),
893 }
894 }
895 Expression::ImageReference { resource_ref, nine_slice } => {
896 let mut image = load_image_reference(resource_ref);
897 if let Some(n) = nine_slice {
898 image.set_nine_slice_edges(n[0], n[1], n[2], n[3]);
899 }
900 Value::Image(image)
901 }
902 Expression::Condition { condition, true_expr, false_expr } => {
903 match eval_expression(ctx, condition) {
904 Value::Bool(true) => eval_expression(ctx, true_expr),
905 Value::Bool(false) => eval_expression(ctx, false_expr),
906 _ => Value::Void,
907 }
908 }
909 Expression::Array { values, .. } => Value::Model(ModelRc::new(SharedVectorModel::from(
910 values.iter().map(|e| eval_expression(ctx, e)).collect::<SharedVector<_>>(),
911 ))),
912 Expression::Struct { values, .. } => Value::Struct(
913 values.iter().map(|(k, v)| (k.to_string(), eval_expression(ctx, v))).collect(),
914 ),
915 Expression::EasingCurve(curve) => {
916 use i_slint_compiler::expression_tree::EasingCurve as EC;
917 use i_slint_core::animations::EasingCurve as Core;
918 Value::EasingCurve(match curve {
919 EC::Linear => Core::Linear,
920 EC::EaseInElastic => Core::EaseInElastic,
921 EC::EaseOutElastic => Core::EaseOutElastic,
922 EC::EaseInOutElastic => Core::EaseInOutElastic,
923 EC::EaseInBounce => Core::EaseInBounce,
924 EC::EaseOutBounce => Core::EaseOutBounce,
925 EC::EaseInOutBounce => Core::EaseInOutBounce,
926 EC::CubicBezier(a, b, c, d) => Core::CubicBezier([*a, *b, *c, *d]),
927 })
928 }
929 Expression::MouseCursor(cursor) => {
930 use i_slint_compiler::expression_tree::MouseCursorInner as Expr;
931 use i_slint_core::cursor::MouseCursorInner as Core;
932 Value::MouseCursorInner(match cursor {
933 Expr::BuiltIn(cursor) => {
934 Core::BuiltIn(eval_expression(ctx, cursor).try_into().unwrap_or_default())
935 }
936 Expr::CustomMouseCursor { image, hotspot_x, hotspot_y } => {
937 Core::CustomMouseCursor {
938 image: eval_expression(ctx, image).try_into().unwrap_or_default(),
939 hotspot_x: eval_expression(ctx, hotspot_x).try_into().unwrap_or_default(),
940 hotspot_y: eval_expression(ctx, hotspot_y).try_into().unwrap_or_default(),
941 }
942 }
943 })
944 }
945 Expression::LinearGradient { angle, stops } => {
946 let angle: f32 = eval_expression(ctx, angle).try_into().unwrap_or_default();
947 Value::Brush(Brush::LinearGradient(LinearGradientBrush::new(
948 angle,
949 eval_stops(ctx, stops),
950 )))
951 }
952 Expression::RadialGradient { stops, center, radius } => {
953 let mut g = RadialGradientBrush::new_circle(eval_stops(ctx, stops));
954 if let Some((cx, cy)) = center {
955 let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
956 let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
957 g = g.with_center(cx, cy);
958 }
959 if let Some(r) = radius {
960 let r: f32 = eval_expression(ctx, r).try_into().unwrap_or_default();
961 g = g.with_radius(r);
962 }
963 Value::Brush(Brush::RadialGradient(g))
964 }
965 Expression::ConicGradient { from_angle, stops, center } => {
966 let from_angle: f32 = eval_expression(ctx, from_angle).try_into().unwrap_or_default();
967 let mut g = ConicGradientBrush::new(from_angle, eval_stops(ctx, stops));
968 if let Some((cx, cy)) = center {
969 let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
970 let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
971 g = g.with_center(cx, cy);
972 }
973 Value::Brush(Brush::ConicGradient(g))
974 }
975 Expression::EnumerationValue(value) => {
976 Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
977 }
978 Expression::LayoutCacheAccess {
979 layout_cache_prop,
980 index,
981 repeater_index,
982 entries_per_item,
983 } => {
984 let cache = load_property(ctx, layout_cache_prop);
985 layout_cache_access(ctx, cache, *index, repeater_index.as_deref(), *entries_per_item)
986 }
987 Expression::GridRepeaterCacheAccess {
988 layout_cache_prop,
989 index,
990 repeater_index,
991 stride,
992 child_offset,
993 inner_repeater_index,
994 entries_per_item,
995 } => {
996 let cache = load_property(ctx, layout_cache_prop);
997 let offset: usize = eval_expression(ctx, repeater_index).try_into().unwrap_or_default();
998 let stride_val: usize = eval_expression(ctx, stride).try_into().unwrap_or_default();
999 let inner_offset: usize = inner_repeater_index
1000 .as_deref()
1001 .map(|e| {
1002 let i: usize = eval_expression(ctx, e).try_into().unwrap_or_default();
1003 i * *entries_per_item
1004 })
1005 .unwrap_or(0);
1006 grid_repeater_cache_access(
1007 cache,
1008 *index,
1009 offset,
1010 stride_val,
1011 *child_offset,
1012 inner_offset,
1013 )
1014 }
1015 Expression::WithLayoutItemInfo {
1016 cells_variable,
1017 elements,
1018 orientation,
1019 sub_expression,
1020 ..
1021 } => with_layout_item_info(ctx, cells_variable, elements, *orientation, sub_expression),
1022 Expression::WithFlexboxLayoutItemInfo {
1023 cells_h_variable,
1024 cells_v_variable,
1025 flex_props_variable,
1026 elements,
1027 repeated_cross_width,
1028 sub_expression,
1029 ..
1030 } => with_flexbox_layout_item_info(
1031 ctx,
1032 cells_h_variable,
1033 cells_v_variable,
1034 flex_props_variable.as_deref(),
1035 elements,
1036 repeated_cross_width.as_deref(),
1037 sub_expression,
1038 ),
1039 Expression::WithGridInputData { cells_variable, elements, sub_expression, .. } => {
1040 with_grid_input_data(ctx, cells_variable, elements, sub_expression)
1041 }
1042 Expression::MinMax { ty: _, op, lhs, rhs } => {
1043 let Value::Number(lhs) = eval_expression(ctx, lhs) else { return Value::Void };
1044 let Value::Number(rhs) = eval_expression(ctx, rhs) else { return Value::Void };
1045 match op {
1046 MinMaxOp::Min => Value::Number(lhs.min(rhs)),
1047 MinMaxOp::Max => Value::Number(lhs.max(rhs)),
1048 }
1049 }
1050 Expression::EmptyComponentFactory => Value::ComponentFactory(Default::default()),
1051 Expression::EmptyDataTransfer => Value::DataTransfer(Default::default()),
1052 Expression::SolveFlexboxLayoutWithMeasure { .. } => {
1053 crate::eval_layout::solve_flexbox_layout_with_measure(ctx, expression)
1054 }
1055 Expression::FlexboxLayoutInfoCrossAxisWithMeasure { .. } => {
1056 crate::eval_layout::flexbox_layout_info_cross_axis_with_measure(ctx, expression)
1057 }
1058 Expression::TranslationReference { .. } => {
1059 Value::String(Default::default())
1063 }
1064 Expression::Closure { .. } => unreachable!(
1065 "closures are dispatched by their consuming builtin and should not go through eval_expression"
1066 ),
1067 Expression::DebugHook { expression, id } => {
1068 if let Some(hook_value) = crate::debug_hook::trigger_debug_hook(ctx, id) {
1069 return hook_value;
1070 }
1071 eval_expression(ctx, expression)
1072 }
1073 }
1074}
1075
1076fn with_layout_item_info(
1077 ctx: &mut EvalContext,
1078 cells_variable: &str,
1079 elements: &[itertools::Either<Expression, i_slint_compiler::llr::LayoutRepeatedElement>],
1080 orientation: i_slint_compiler::layout::Orientation,
1081 sub_expression: &Expression,
1082) -> Value {
1083 let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1084 let mut repeated_indices: Vec<u32> = Vec::new();
1085 let mut repeater_steps: Vec<u32> = Vec::new();
1086 for el in elements {
1087 match el {
1088 itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1089 itertools::Either::Right(repeater) => {
1090 let offset = cells.len() as u32;
1091 let (instances, step) = push_repeater_layout_items(
1092 ctx,
1093 repeater.repeater_index,
1094 repeater.row_child_templates.as_deref(),
1095 orientation,
1096 &mut cells,
1097 );
1098 repeated_indices.push(offset);
1099 repeated_indices.push(instances);
1100 repeater_steps.push(step);
1101 }
1102 }
1103 }
1104 let prev_cells =
1105 ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1106 let prev_ri = ctx.locals.insert(
1107 SmolStr::new_static("repeated_indices"),
1108 Value::Model(model_from_vec(
1109 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1110 )),
1111 );
1112 let prev_rs = ctx.locals.insert(
1113 SmolStr::new_static("repeater_steps"),
1114 Value::Model(model_from_vec(
1115 repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1116 )),
1117 );
1118 let result = eval_expression(ctx, sub_expression);
1119 restore_local(ctx, cells_variable, prev_cells);
1120 restore_local(ctx, "repeated_indices", prev_ri);
1121 restore_local(ctx, "repeater_steps", prev_rs);
1122 result
1123}
1124
1125fn push_repeater_layout_items(
1126 ctx: &mut EvalContext,
1127 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1128 row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1129 orientation: i_slint_compiler::layout::Orientation,
1130 cells: &mut Vec<Value>,
1131) -> (u32, u32) {
1132 use i_slint_core::model::RepeatedItemTree;
1133 let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1134 let repeater = ¤t.repeaters[repeater_idx];
1135 repeater.track_instance_changes();
1136 let instances = repeater.instances_vec();
1137 let core_orientation = llr_to_core_orientation(orientation);
1138 let push_cell = |cells: &mut Vec<Value>, info: i_slint_core::layout::LayoutItemInfo| {
1139 let mut struct_value = crate::api::Struct::default();
1140 struct_value.set_field("constraint".to_string(), info.constraint.into());
1141 if info.cross_axis_self_alignment != i_slint_core::items::CrossAxisSelfAlignment::Auto {
1144 struct_value.set_field(
1145 "cross-axis-self-alignment".to_string(),
1146 Value::EnumerationValue(
1147 "CrossAxisSelfAlignment".to_string(),
1148 info.cross_axis_self_alignment.to_string(),
1149 ),
1150 );
1151 }
1152 cells.push(Value::Struct(struct_value));
1153 };
1154 let step = match row_child_templates {
1155 None => {
1156 for instance in &instances {
1159 let info = RepeatedItemTree::layout_item_info(
1160 instance.as_pin_ref(),
1161 core_orientation,
1162 None,
1163 );
1164 push_cell(cells, info);
1165 }
1166 1
1167 }
1168 Some(templates) => {
1169 let max_total = instances
1173 .iter()
1174 .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1175 .max()
1176 .unwrap_or(i_slint_compiler::llr::static_child_count(templates));
1177 for instance in &instances {
1178 for child_idx in 0..max_total {
1179 let info = RepeatedItemTree::layout_item_info(
1180 instance.as_pin_ref(),
1181 core_orientation,
1182 Some(child_idx),
1183 );
1184 push_cell(cells, info);
1185 }
1186 }
1187 max_total as u32
1188 }
1189 };
1190 (instances.len() as u32, step)
1191}
1192
1193fn total_row_child_count(
1194 sub: &Pin<std::rc::Rc<crate::instance::SubComponentInstance>>,
1195 templates: &[i_slint_compiler::llr::RowChildTemplateInfo],
1196) -> usize {
1197 use i_slint_compiler::llr::{RowChildTemplateInfo, static_child_count};
1198 let mut total = static_child_count(templates);
1199 for entry in templates {
1200 if let RowChildTemplateInfo::Repeated { repeater_index } = entry {
1201 let repeater = &sub.repeaters[*repeater_index];
1202 repeater.track_instance_changes();
1203 total += repeater.range().len();
1204 }
1205 }
1206 total
1207}
1208
1209pub(crate) fn llr_to_core_orientation(
1210 o: i_slint_compiler::layout::Orientation,
1211) -> i_slint_core::items::Orientation {
1212 match o {
1213 i_slint_compiler::layout::Orientation::Horizontal => {
1214 i_slint_core::items::Orientation::Horizontal
1215 }
1216 i_slint_compiler::layout::Orientation::Vertical => {
1217 i_slint_core::items::Orientation::Vertical
1218 }
1219 }
1220}
1221
1222fn with_flexbox_layout_item_info(
1223 ctx: &mut EvalContext,
1224 cells_h_variable: &str,
1225 cells_v_variable: &str,
1226 flex_props_variable: Option<&str>,
1227 elements: &[itertools::Either<
1228 (Expression, Expression, Expression),
1229 i_slint_compiler::llr::LayoutRepeatedElement,
1230 >],
1231 repeated_cross_width: Option<&Expression>,
1232 sub_expression: &Expression,
1233) -> Value {
1234 let cross_width =
1237 repeated_cross_width.map(|e| eval_expression(ctx, e).try_into().unwrap_or_default());
1238 let mut cells_h: Vec<Value> = Vec::with_capacity(elements.len());
1239 let mut cells_v: Vec<Value> = Vec::with_capacity(elements.len());
1240 let mut flex_props: Vec<Value> = Vec::with_capacity(elements.len());
1241 let mut repeated_indices: Vec<u32> = Vec::new();
1242 for el in elements {
1243 match el {
1244 itertools::Either::Left((h, v, props)) => {
1245 cells_h.push(eval_expression(ctx, h));
1246 cells_v.push(eval_expression(ctx, v));
1247 if flex_props_variable.is_some() {
1251 flex_props.push(eval_expression(ctx, props));
1252 }
1253 }
1254 itertools::Either::Right(repeater) => {
1255 let offset = cells_h.len() as u32;
1256 let instances = push_repeater_flexbox_items(
1257 ctx,
1258 repeater.repeater_index,
1259 cross_width,
1260 &mut cells_h,
1261 &mut cells_v,
1262 flex_props_variable.is_some().then_some(&mut flex_props),
1263 );
1264 repeated_indices.push(offset);
1265 repeated_indices.push(instances);
1266 }
1267 }
1268 }
1269 let prev_h =
1270 ctx.locals.insert(SmolStr::from(cells_h_variable), Value::Model(model_from_vec(cells_h)));
1271 let prev_v =
1272 ctx.locals.insert(SmolStr::from(cells_v_variable), Value::Model(model_from_vec(cells_v)));
1273 let prev_fp = flex_props_variable.map(|name| {
1274 ctx.locals.insert(SmolStr::from(name), Value::Model(model_from_vec(flex_props)))
1275 });
1276 let prev_ri = ctx.locals.insert(
1277 SmolStr::new_static("repeated_indices"),
1278 Value::Model(model_from_vec(
1279 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1280 )),
1281 );
1282 let result = eval_expression(ctx, sub_expression);
1283 restore_local(ctx, cells_h_variable, prev_h);
1284 restore_local(ctx, cells_v_variable, prev_v);
1285 if let Some(name) = flex_props_variable {
1286 restore_local(ctx, name, prev_fp.flatten());
1287 }
1288 restore_local(ctx, "repeated_indices", prev_ri);
1289 result
1290}
1291
1292fn push_repeater_flexbox_items(
1293 ctx: &mut EvalContext,
1294 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1295 cross_width: Option<f32>,
1296 cells_h: &mut Vec<Value>,
1297 cells_v: &mut Vec<Value>,
1298 mut flex_props: Option<&mut Vec<Value>>,
1299) -> u32 {
1300 use i_slint_core::items::Orientation;
1301 use i_slint_core::model::RepeatedItemTree;
1302 let Some(current) = ctx.current.as_ref() else { return 0 };
1303 let repeater = ¤t.repeaters[repeater_idx];
1304 repeater.track_instance_changes();
1305 let instances = repeater.instances_vec();
1306 let instance_count = instances.len() as u32;
1307 for instance in instances {
1308 let info_h = RepeatedItemTree::flexbox_layout_item_info(
1312 instance.as_pin_ref(),
1313 Orientation::Horizontal,
1314 None,
1315 );
1316 let info_v = match cross_width {
1319 Some(w) => instance.as_pin_ref().flexbox_layout_item_info_at_cross_width(w),
1320 None => RepeatedItemTree::flexbox_layout_item_info(
1321 instance.as_pin_ref(),
1322 Orientation::Vertical,
1323 None,
1324 ),
1325 };
1326 if let Some(fp) = flex_props.as_mut() {
1329 fp.push(flex_props_to_value(info_h.props));
1330 }
1331 cells_h.push(layout_item_info_to_value(info_h.constraint));
1332 cells_v.push(layout_item_info_to_value(info_v.constraint));
1333 }
1334 instance_count
1335}
1336
1337fn layout_item_info_to_value(constraint: i_slint_core::layout::LayoutInfo) -> Value {
1338 let mut s = crate::api::Struct::default();
1339 s.set_field("constraint".to_string(), constraint.into());
1340 Value::Struct(s)
1341}
1342
1343fn flex_props_to_value(props: i_slint_core::layout::FlexItemProps) -> Value {
1344 let mut s = crate::api::Struct::default();
1345 s.set_field("flex_grow".to_string(), Value::Number(props.flex_grow as f64));
1346 s.set_field("flex_shrink".to_string(), Value::Number(props.flex_shrink as f64));
1347 s.set_field(
1348 "cross_axis_self_alignment".to_string(),
1349 Value::EnumerationValue(
1350 "CrossAxisSelfAlignment".to_string(),
1351 format!("{:?}", props.cross_axis_self_alignment).to_lowercase(),
1352 ),
1353 );
1354 s.set_field("flex_order".to_string(), Value::Number(props.flex_order as f64));
1355 Value::Struct(s)
1356}
1357
1358fn with_grid_input_data(
1359 ctx: &mut EvalContext,
1360 cells_variable: &str,
1361 elements: &[itertools::Either<Expression, i_slint_compiler::llr::GridLayoutRepeatedElement>],
1362 sub_expression: &Expression,
1363) -> Value {
1364 let saved_new_row = ctx.locals.remove("new_row");
1371 let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1372 let mut repeated_indices: Vec<u32> = Vec::new();
1373 let mut repeater_steps: Vec<u32> = Vec::new();
1374
1375 for el in elements {
1376 match el {
1377 itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1378 itertools::Either::Right(repeater) => {
1379 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(repeater.new_row));
1380 let offset = cells.len() as u32;
1381 let is_row_repeater = repeater.row_child_templates.is_some();
1382 let (instances, step) = push_repeater_grid_input_data(
1383 ctx,
1384 repeater.repeater_index,
1385 repeater.new_row,
1386 repeater.row_child_templates.as_deref(),
1387 &mut cells,
1388 );
1389 if !is_row_repeater && instances > 0 {
1390 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(false));
1391 }
1392 repeated_indices.push(offset);
1393 repeated_indices.push(instances);
1394 repeater_steps.push(step);
1395 }
1396 }
1397 }
1398 restore_local(ctx, "new_row", saved_new_row);
1399
1400 let prev_cells =
1401 ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1402 let prev_ri = ctx.locals.insert(
1403 SmolStr::new_static("repeated_indices"),
1404 Value::Model(model_from_vec(
1405 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1406 )),
1407 );
1408 let prev_rs = ctx.locals.insert(
1409 SmolStr::new_static("repeater_steps"),
1410 Value::Model(model_from_vec(
1411 repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1412 )),
1413 );
1414
1415 let result = eval_expression(ctx, sub_expression);
1416
1417 restore_local(ctx, cells_variable, prev_cells);
1418 restore_local(ctx, "repeated_indices", prev_ri);
1419 restore_local(ctx, "repeater_steps", prev_rs);
1420 result
1421}
1422
1423pub(crate) fn restore_local(ctx: &mut EvalContext, name: &str, prev: Option<Value>) {
1424 if let Some(prev) = prev {
1425 ctx.locals.insert(SmolStr::from(name), prev);
1426 } else {
1427 ctx.locals.remove(name);
1428 }
1429}
1430
1431fn push_repeater_grid_input_data(
1432 ctx: &mut EvalContext,
1433 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1434 new_row: bool,
1435 row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1436 cells: &mut Vec<Value>,
1437) -> (u32, u32) {
1438 use i_slint_compiler::llr::RowChildTemplateInfo;
1439 use i_slint_core::model::VecModel;
1440 use std::rc::Rc;
1441 let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1442 let repeater = ¤t.repeaters[repeater_idx];
1443 repeater.track_instance_changes();
1444
1445 let is_row_repeater = row_child_templates.is_some();
1446 let static_count =
1447 row_child_templates.map(i_slint_compiler::llr::static_child_count).unwrap_or(1);
1448
1449 let instances = repeater.instances_vec();
1450 let instance_count = instances.len() as u32;
1451
1452 let step = if let Some(templates) = row_child_templates {
1456 instances
1457 .iter()
1458 .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1459 .max()
1460 .unwrap_or(static_count)
1461 } else {
1462 1
1463 };
1464
1465 let mut current_new_row = new_row;
1466
1467 for instance in &instances {
1468 let inner_sub = instance.root_sub_component.clone();
1469 let cu = inner_sub.compilation_unit.clone();
1470 let sc = &cu.sub_components[inner_sub.sub_component_idx];
1471
1472 let mut statics: Vec<Value> = vec![Value::Void; static_count];
1476 if let Some(expr) = &sc.grid_layout_input_for_repeated {
1477 let expr = expr.borrow();
1478 let mut inner_ctx = EvalContext::new(inner_sub.clone());
1479 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1480 for _ in 0..static_count {
1481 result_model.push(Value::Void);
1482 }
1483 inner_ctx.locals.insert(
1484 SmolStr::new_static("result"),
1485 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1486 );
1487 inner_ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(current_new_row));
1488 eval_expression(&mut inner_ctx, &expr);
1489 for (slot, i) in statics.iter_mut().zip(0..result_model.row_count()) {
1490 if let Some(v) = result_model.row_data(i) {
1491 *slot = v;
1492 }
1493 }
1494 }
1495
1496 if let Some(templates) = row_child_templates {
1497 let mut written = 0usize;
1501 let mut static_idx = 0usize;
1502 for entry in templates {
1503 if written >= step {
1504 break;
1505 }
1506 match entry {
1507 RowChildTemplateInfo::Static { .. } => {
1508 let mut v = statics.get(static_idx).cloned().unwrap_or(Value::Void);
1509 static_idx += 1;
1510 override_new_row(&mut v, written == 0 && current_new_row);
1511 cells.push(v);
1512 written += 1;
1513 }
1514 RowChildTemplateInfo::Repeated { repeater_index } => {
1515 let inner_rep = &inner_sub.repeaters[*repeater_index];
1516 inner_rep.track_instance_changes();
1517 for inner_inst in inner_rep.instances_vec() {
1521 if written >= step {
1522 break;
1523 }
1524 for mut v in eval_grid_input_for_repeated(
1525 &inner_inst.root_sub_component,
1526 written == 0 && current_new_row,
1527 ) {
1528 if written >= step {
1529 break;
1530 }
1531 override_new_row(&mut v, written == 0 && current_new_row);
1532 cells.push(v);
1533 written += 1;
1534 }
1535 }
1536 }
1537 }
1538 }
1539 while written < step {
1540 cells.push(auto_grid_input_data());
1541 written += 1;
1542 }
1543 } else {
1544 cells.push(statics.pop().unwrap_or_else(auto_grid_input_data));
1546 }
1547
1548 if !is_row_repeater {
1549 current_new_row = false;
1550 }
1551 }
1552 (instance_count, step as u32)
1553}
1554
1555fn eval_grid_input_for_repeated(
1560 sub: &Pin<Rc<crate::instance::SubComponentInstance>>,
1561 new_row: bool,
1562) -> Vec<Value> {
1563 use i_slint_core::model::{Model, VecModel};
1564 let cu = sub.compilation_unit.clone();
1565 let sc = &cu.sub_components[sub.sub_component_idx];
1566 let count = sc
1567 .row_child_templates
1568 .as_ref()
1569 .map(|t| i_slint_compiler::llr::static_child_count(t))
1570 .unwrap_or(1)
1571 .max(1);
1572 let Some(expr) = &sc.grid_layout_input_for_repeated else {
1573 return vec![auto_grid_input_data()];
1574 };
1575 let expr = expr.borrow();
1576 let mut ctx = EvalContext::new(sub.clone());
1577 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1578 for _ in 0..count {
1579 result_model.push(Value::Void);
1580 }
1581 ctx.locals.insert(
1582 SmolStr::new_static("result"),
1583 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1584 );
1585 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(new_row));
1586 eval_expression(&mut ctx, &expr);
1587 (0..result_model.row_count())
1588 .map(|i| result_model.row_data(i).unwrap_or_else(auto_grid_input_data))
1589 .collect()
1590}
1591
1592fn auto_grid_input_data() -> Value {
1595 let mut s = crate::api::Struct::default();
1596 s.set_field("new_row".into(), Value::Bool(false));
1597 s.set_field("row".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1598 s.set_field("col".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1599 s.set_field("rowspan".into(), Value::Number(1.0));
1600 s.set_field("colspan".into(), Value::Number(1.0));
1601 Value::Struct(s)
1602}
1603
1604fn override_new_row(v: &mut Value, new_row: bool) {
1605 if let Value::Struct(s) = v {
1606 s.set_field("new_row".into(), Value::Bool(new_row));
1607 }
1608}
1609
1610fn model_from_vec(values: Vec<Value>) -> ModelRc<Value> {
1611 ModelRc::new(SharedVectorModel::from(values.into_iter().collect::<SharedVector<_>>()))
1612}
1613
1614fn binary_op(op: char, lhs: Value, rhs: Value) -> Value {
1615 let (lhs, rhs) = match (lhs, rhs) {
1618 (Value::Void, Value::Number(b)) => (Value::Number(0.), Value::Number(b)),
1619 (Value::Number(a), Value::Void) => (Value::Number(a), Value::Number(0.)),
1620 (Value::Void, Value::Bool(b)) => (Value::Bool(false), Value::Bool(b)),
1621 (Value::Bool(a), Value::Void) => (Value::Bool(a), Value::Bool(false)),
1622 (Value::Void, Value::String(b)) => (Value::String(Default::default()), Value::String(b)),
1623 (Value::String(a), Value::Void) => (Value::String(a), Value::String(Default::default())),
1624 (a, b) => (a, b),
1625 };
1626 match (op, lhs, rhs) {
1627 ('+', Value::String(mut a), Value::String(b)) => {
1628 a.push_str(b.as_str());
1629 Value::String(a)
1630 }
1631 ('+', Value::Number(a), Value::Number(b)) => Value::Number(a + b),
1632 ('+', a @ Value::Struct(_), b @ Value::Struct(_)) => {
1633 let la: Option<i_slint_core::layout::LayoutInfo> = a.try_into().ok();
1634 let lb: Option<i_slint_core::layout::LayoutInfo> = b.try_into().ok();
1635 if let (Some(a), Some(b)) = (la, lb) {
1636 a.merge(&b).into()
1637 } else {
1638 panic!("unsupported struct + struct");
1639 }
1640 }
1641 ('-', Value::Number(a), Value::Number(b)) => Value::Number(a - b),
1642 ('/', Value::Number(a), Value::Number(b)) => Value::Number(a / b),
1643 ('*', Value::Number(a), Value::Number(b)) => Value::Number(a * b),
1644 ('<', Value::Number(a), Value::Number(b)) => Value::Bool(a < b),
1645 ('>', Value::Number(a), Value::Number(b)) => Value::Bool(a > b),
1646 ('≤', Value::Number(a), Value::Number(b)) => Value::Bool(a <= b),
1647 ('≥', Value::Number(a), Value::Number(b)) => Value::Bool(a >= b),
1648 ('<', Value::String(a), Value::String(b)) => Value::Bool(a < b),
1649 ('>', Value::String(a), Value::String(b)) => Value::Bool(a > b),
1650 ('≤', Value::String(a), Value::String(b)) => Value::Bool(a <= b),
1651 ('≥', Value::String(a), Value::String(b)) => Value::Bool(a >= b),
1652 ('=', a, b) => Value::Bool(a == b),
1653 ('!', a, b) => Value::Bool(a != b),
1654 ('&', Value::Bool(a), Value::Bool(b)) => Value::Bool(a && b),
1655 ('|', Value::Bool(a), Value::Bool(b)) => Value::Bool(a || b),
1656 (op, a, b) => panic!("unsupported {a:?} {op} {b:?}"),
1657 }
1658}
1659
1660fn eval_stops(ctx: &mut EvalContext, stops: &[(Expression, Expression)]) -> Vec<GradientStop> {
1661 stops
1662 .iter()
1663 .map(|(color, stop)| GradientStop {
1664 color: eval_expression(ctx, color).try_into().unwrap_or_default(),
1665 position: eval_expression(ctx, stop).try_into().unwrap_or_default(),
1666 })
1667 .collect()
1668}
1669
1670fn load_image_reference(
1671 resource_ref: &i_slint_compiler::expression_tree::ImageReference,
1672) -> i_slint_core::graphics::Image {
1673 use i_slint_compiler::expression_tree::ImageReference as Ref;
1674 let image = match resource_ref {
1675 Ref::None => Ok(Default::default()),
1676 Ref::DataUri(data_uri) => i_slint_compiler::data_uri::decode_data_uri(data_uri)
1677 .ok()
1678 .and_then(|(data, extension)| {
1679 i_slint_core::graphics::load_image_from_data_uri(data_uri, &data, &extension).ok()
1680 })
1681 .ok_or_else(Default::default),
1682 Ref::Url(url) if url.scheme() == "builtin" => {
1683 let path = std::path::Path::new(url.as_str());
1687 i_slint_compiler::fileaccess::load_file(path)
1688 .and_then(|virtual_file| virtual_file.builtin_contents)
1689 .map(|contents| {
1690 let extension = path.extension().unwrap().to_str().unwrap();
1691 i_slint_core::graphics::load_image_from_embedded_data(
1692 i_slint_core::slice::Slice::from_slice(contents),
1693 i_slint_core::slice::Slice::from_slice(extension.as_bytes()),
1694 )
1695 })
1696 .ok_or_else(Default::default)
1697 }
1698 Ref::Path(path) => {
1699 i_slint_core::graphics::Image::load_from_path(std::path::Path::new(path.as_str()))
1700 }
1701 Ref::Url(url) => {
1702 #[cfg(target_arch = "wasm32")]
1703 {
1704 i_slint_core::graphics::load_as_html_image(url.as_str())
1705 }
1706 #[cfg(not(target_arch = "wasm32"))]
1708 {
1709 let _ = url;
1710 Err(Default::default())
1711 }
1712 }
1713 Ref::EmbeddedData { .. } | Ref::EmbeddedTexture { .. } => Ok(Default::default()),
1714 };
1715 image.unwrap_or_else(|_| {
1716 eprintln!("Could not load image {resource_ref:?}");
1717 Default::default()
1718 })
1719}
1720
1721fn layout_cache_access(
1722 ctx: &mut EvalContext,
1723 cache: Value,
1724 index: usize,
1725 repeater_index: Option<&Expression>,
1726 entries_per_item: usize,
1727) -> Value {
1728 match cache {
1729 Value::LayoutCache(cache) => {
1730 if let Some(ri) = repeater_index {
1731 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1732 Value::Number(
1733 cache
1734 .get((cache[index] as usize) + offset * entries_per_item)
1735 .copied()
1736 .unwrap_or(0.)
1737 .into(),
1738 )
1739 } else {
1740 Value::Number(cache[index].into())
1741 }
1742 }
1743 Value::ArrayOfU16(cache) => {
1744 if let Some(ri) = repeater_index {
1745 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1746 Value::Number(
1747 cache
1748 .get((cache[index] as usize) + offset * entries_per_item)
1749 .copied()
1750 .unwrap_or(0)
1751 .into(),
1752 )
1753 } else {
1754 Value::Number(cache[index].into())
1755 }
1756 }
1757 _ => Value::Number(0.),
1758 }
1759}
1760
1761fn grid_repeater_cache_access(
1766 cache: Value,
1767 index: usize,
1768 repeater_index: usize,
1769 stride: usize,
1770 child_offset: usize,
1771 inner_offset: usize,
1772) -> Value {
1773 let get = |data_idx: usize, slice_len: usize, read: &dyn Fn(usize) -> f64| {
1774 if data_idx < slice_len { Value::Number(read(data_idx)) } else { Value::Number(0.) }
1775 };
1776 match cache {
1777 Value::LayoutCache(cache) => {
1778 let base = cache.get(index).copied().unwrap_or(0.) as usize;
1779 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1780 get(data_idx, cache.len(), &|i| cache[i] as f64)
1781 }
1782 Value::ArrayOfU16(cache) => {
1783 let base = cache.get(index).copied().unwrap_or(0) as usize;
1784 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1785 get(data_idx, cache.len(), &|i| cache[i] as f64)
1786 }
1787 _ => Value::Number(0.),
1788 }
1789}
1790
1791fn call_builtin_function(
1793 ctx: &mut EvalContext,
1794 f: BuiltinFunction,
1795 arguments: &[Expression],
1796) -> Value {
1797 let to_num = |ctx: &mut EvalContext, e: &Expression| -> f64 {
1798 eval_expression(ctx, e).try_into().unwrap_or_default()
1799 };
1800 let to_string = |ctx: &mut EvalContext, e: &Expression| -> SharedString {
1801 eval_expression(ctx, e).try_into().unwrap_or_default()
1802 };
1803
1804 match f {
1805 BuiltinFunction::Mod => {
1806 Value::Number(to_num(ctx, &arguments[0]).rem_euclid(to_num(ctx, &arguments[1])))
1807 }
1808 BuiltinFunction::Round => Value::Number(to_num(ctx, &arguments[0]).round()),
1809 BuiltinFunction::Ceil => Value::Number(to_num(ctx, &arguments[0]).ceil()),
1810 BuiltinFunction::Floor => Value::Number(to_num(ctx, &arguments[0]).floor()),
1811 BuiltinFunction::Sqrt => Value::Number(to_num(ctx, &arguments[0]).sqrt()),
1812 BuiltinFunction::Abs => Value::Number(to_num(ctx, &arguments[0]).abs()),
1813 BuiltinFunction::Sin => Value::Number(to_num(ctx, &arguments[0]).to_radians().sin()),
1814 BuiltinFunction::Cos => Value::Number(to_num(ctx, &arguments[0]).to_radians().cos()),
1815 BuiltinFunction::Tan => Value::Number(to_num(ctx, &arguments[0]).to_radians().tan()),
1816 BuiltinFunction::ASin => Value::Number(to_num(ctx, &arguments[0]).asin().to_degrees()),
1817 BuiltinFunction::ACos => Value::Number(to_num(ctx, &arguments[0]).acos().to_degrees()),
1818 BuiltinFunction::ATan => Value::Number(to_num(ctx, &arguments[0]).atan().to_degrees()),
1819 BuiltinFunction::ATan2 => {
1820 Value::Number(to_num(ctx, &arguments[0]).atan2(to_num(ctx, &arguments[1])).to_degrees())
1821 }
1822 BuiltinFunction::Log => {
1823 Value::Number(to_num(ctx, &arguments[0]).log(to_num(ctx, &arguments[1])))
1824 }
1825 BuiltinFunction::Ln => Value::Number(to_num(ctx, &arguments[0]).ln()),
1826 BuiltinFunction::Pow => {
1827 Value::Number(to_num(ctx, &arguments[0]).powf(to_num(ctx, &arguments[1])))
1828 }
1829 BuiltinFunction::Exp => Value::Number(to_num(ctx, &arguments[0]).exp()),
1830 BuiltinFunction::ToFixed => {
1831 let n = to_num(ctx, &arguments[0]);
1832 let digits: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1833 Value::String(i_slint_core::string::shared_string_from_number_fixed(
1834 n,
1835 digits.max(0) as usize,
1836 ))
1837 }
1838 BuiltinFunction::ToPrecision => {
1839 let n = to_num(ctx, &arguments[0]);
1840 let p: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1841 Value::String(i_slint_core::string::shared_string_from_number_precision(
1842 n,
1843 p.max(0) as usize,
1844 ))
1845 }
1846 BuiltinFunction::StringStartsWith => Value::Bool(
1847 to_string(ctx, &arguments[0])
1848 .as_str()
1849 .starts_with(to_string(ctx, &arguments[1]).as_str()),
1850 ),
1851 BuiltinFunction::StringEndsWith => Value::Bool(
1852 to_string(ctx, &arguments[0])
1853 .as_str()
1854 .ends_with(to_string(ctx, &arguments[1]).as_str()),
1855 ),
1856 BuiltinFunction::ToStringUnlocalized => {
1857 let n = to_num(ctx, &arguments[0]);
1858 Value::String(i_slint_core::string::shared_string_from_number_unlocalized(n))
1859 }
1860 BuiltinFunction::DecimalSeparator => Value::String(
1861 find_window_adapter(ctx)
1862 .map(|adapter| {
1863 i_slint_core::window::WindowInner::from_pub(adapter.window())
1864 .context()
1865 .locale_decimal_separator()
1866 })
1867 .unwrap_or_default()
1868 .into(),
1869 ),
1870 BuiltinFunction::MacosBringAllWindowsToFront => {
1871 i_slint_core::macos_bring_all_windows_to_front();
1872 Value::Void
1873 }
1874 BuiltinFunction::ColorToStyledText => {
1875 let color: i_slint_core::Color =
1876 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
1877 Value::StyledText(i_slint_core::styled_text::color_to_styled_text(color))
1878 }
1879 BuiltinFunction::SetupSystemTrayIcon => {
1880 crate::popup::setup_system_tray_icon(ctx, arguments)
1881 }
1882 BuiltinFunction::StringIsFloat => Value::Bool(
1883 <f64 as core::str::FromStr>::from_str(to_string(ctx, &arguments[0]).as_str()).is_ok(),
1884 ),
1885 BuiltinFunction::StringToFloat => Value::Number(
1886 core::str::FromStr::from_str(to_string(ctx, &arguments[0]).as_str()).unwrap_or(0.),
1887 ),
1888 BuiltinFunction::StringIsEmpty => Value::Bool(to_string(ctx, &arguments[0]).is_empty()),
1889 BuiltinFunction::StringCharacterCount => Value::Number(
1890 unicode_segmentation::UnicodeSegmentation::graphemes(
1891 to_string(ctx, &arguments[0]).as_str(),
1892 true,
1893 )
1894 .count() as f64,
1895 ),
1896 BuiltinFunction::StringToLowercase => {
1897 Value::String(to_string(ctx, &arguments[0]).to_lowercase().into())
1898 }
1899 BuiltinFunction::StringToUppercase => {
1900 Value::String(to_string(ctx, &arguments[0]).to_uppercase().into())
1901 }
1902 BuiltinFunction::StringReplaceAll => {
1903 if arguments.len() != 3 {
1904 panic!("internal error: incorrect argument count to StringReplaceAll")
1905 }
1906
1907 if let (Value::String(s), Value::String(from), Value::String(to)) = (
1908 eval_expression(ctx, &arguments[0]),
1909 eval_expression(ctx, &arguments[1]),
1910 eval_expression(ctx, &arguments[2]),
1911 ) {
1912 Value::String(i_slint_core::string::shared_string_replace_all(
1913 &s,
1914 from.as_str(),
1915 to.as_str(),
1916 ))
1917 } else {
1918 panic!("Not all arguments are strings");
1919 }
1920 }
1921 BuiltinFunction::ColorRgbaStruct => {
1922 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1923 let color = brush.color();
1924 let values = [
1925 ("red".to_string(), Value::Number(color.red().into())),
1926 ("green".to_string(), Value::Number(color.green().into())),
1927 ("blue".to_string(), Value::Number(color.blue().into())),
1928 ("alpha".to_string(), Value::Number(color.alpha().into())),
1929 ]
1930 .into_iter()
1931 .collect();
1932 Value::Struct(values)
1933 } else {
1934 Value::Void
1935 }
1936 }
1937 BuiltinFunction::ColorHsvaStruct => {
1938 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1939 let color = brush.color().to_hsva();
1940 let values = [
1941 ("hue".to_string(), Value::Number(color.hue.into())),
1942 ("saturation".to_string(), Value::Number(color.saturation.into())),
1943 ("value".to_string(), Value::Number(color.value.into())),
1944 ("alpha".to_string(), Value::Number(color.alpha.into())),
1945 ]
1946 .into_iter()
1947 .collect();
1948 Value::Struct(values)
1949 } else {
1950 Value::Void
1951 }
1952 }
1953 BuiltinFunction::ColorOklchStruct => {
1954 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1955 let color = brush.color().to_oklch();
1956 let values = [
1957 ("lightness".to_string(), Value::Number(color.lightness.into())),
1958 ("chroma".to_string(), Value::Number(color.chroma.into())),
1959 ("hue".to_string(), Value::Number(color.hue.into())),
1960 ("alpha".to_string(), Value::Number(color.alpha.into())),
1961 ]
1962 .into_iter()
1963 .collect();
1964 Value::Struct(values)
1965 } else {
1966 Value::Void
1967 }
1968 }
1969 BuiltinFunction::ColorBrighter => {
1970 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1971 brush.brighter(to_num(ctx, &arguments[1]) as f32).into()
1972 } else {
1973 Value::Void
1974 }
1975 }
1976 BuiltinFunction::ColorDarker => {
1977 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1978 brush.darker(to_num(ctx, &arguments[1]) as f32).into()
1979 } else {
1980 Value::Void
1981 }
1982 }
1983 BuiltinFunction::ColorTransparentize => {
1984 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1985 brush.transparentize(to_num(ctx, &arguments[1]) as f32).into()
1986 } else {
1987 Value::Void
1988 }
1989 }
1990 BuiltinFunction::ColorWithAlpha => {
1991 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1992 brush.with_alpha(to_num(ctx, &arguments[1]) as f32).into()
1993 } else {
1994 Value::Void
1995 }
1996 }
1997 BuiltinFunction::ColorMix => {
1998 let a = eval_expression(ctx, &arguments[0]);
1999 let b = eval_expression(ctx, &arguments[1]);
2000 let factor = to_num(ctx, &arguments[2]) as f32;
2001 if let (
2002 Value::Brush(i_slint_core::Brush::SolidColor(ca)),
2003 Value::Brush(i_slint_core::Brush::SolidColor(cb)),
2004 ) = (a, b)
2005 {
2006 ca.mix(&cb, factor).into()
2007 } else {
2008 Value::Void
2009 }
2010 }
2011 BuiltinFunction::ArrayPush => {
2012 if arguments.len() != 2 {
2013 panic!("internal error: incorrect argument count to ArrayPush")
2014 }
2015
2016 let model = match eval_expression(ctx, &arguments[0]) {
2017 Value::Model(m) => m,
2018 _ => panic!("First argument not an array: {:?}", arguments[0]),
2019 };
2020 let value = eval_expression(ctx, &arguments[1]);
2021
2022 model.push_row(value);
2023
2024 Value::Void
2025 }
2026 BuiltinFunction::ArrayRemove => {
2027 if arguments.len() != 2 {
2028 panic!("internal error: incorrect argument count to ArrayRemove")
2029 }
2030
2031 let model = match eval_expression(ctx, &arguments[0]) {
2032 Value::Model(m) => m,
2033 _ => panic!("First argument not an array: {:?}", arguments[0]),
2034 };
2035 let index = match eval_expression(ctx, &arguments[1]) {
2036 Value::Number(i) => i,
2037 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
2038 };
2039
2040 model.remove_row(index as isize);
2041
2042 Value::Void
2043 }
2044
2045 BuiltinFunction::ArrayInsert => {
2046 if arguments.len() != 3 {
2047 panic!("internal error: incorrect argument count to ArrayInsert")
2048 }
2049
2050 let model = match eval_expression(ctx, &arguments[0]) {
2051 Value::Model(m) => m,
2052 _ => panic!("First argument not an array: {:?}", arguments[0]),
2053 };
2054 let index = match eval_expression(ctx, &arguments[1]) {
2055 Value::Number(i) => i,
2056 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
2057 };
2058
2059 let value = eval_expression(ctx, &arguments[2]);
2060 model.insert_row(index as isize, value);
2061
2062 Value::Void
2063 }
2064 BuiltinFunction::Rgb => {
2065 let r: i32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2066 let g: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2067 let b: i32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2068 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2069 let r: u8 = r.clamp(0, 255) as u8;
2070 let g: u8 = g.clamp(0, 255) as u8;
2071 let b: u8 = b.clamp(0, 255) as u8;
2072 let a: u8 = (255. * a).clamp(0., 255.) as u8;
2073 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_argb_u8(
2074 a, r, g, b,
2075 )))
2076 }
2077 BuiltinFunction::Hsv => {
2078 let h: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2079 let s: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2080 let v: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2081 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2082 let a = a.clamp(0., 1.);
2083 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_hsva(
2084 h, s, v, a,
2085 )))
2086 }
2087 BuiltinFunction::Oklch => {
2088 let l: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2089 let c: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2090 let h: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2091 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2092 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_oklch(
2093 l.clamp(0.0, 1.0),
2094 c,
2095 h,
2096 a.clamp(0.0, 1.0),
2097 )))
2098 }
2099 BuiltinFunction::AnimationTick => {
2100 Value::Number(i_slint_core::animations::animation_tick() as f64)
2101 }
2102 BuiltinFunction::GetWindowScaleFactor => {
2103 let factor = root_instance(ctx)
2104 .and_then(|inst| inst.window_adapter_or_default())
2105 .map(|adapter| {
2106 i_slint_core::window::WindowInner::from_pub(adapter.window()).scale_factor()
2107 as f64
2108 })
2109 .unwrap_or(1.0);
2110 Value::Number(factor)
2111 }
2112 BuiltinFunction::GetWindowDefaultFontSize => {
2113 let size = root_instance(ctx)
2119 .map(|inst| {
2120 i_slint_core::items::WindowItem::resolved_default_font_size(
2121 vtable::VRc::into_dyn(inst),
2122 )
2123 .get() as f64
2124 })
2125 .unwrap_or(12.0);
2126 Value::Number(size)
2127 }
2128 BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
2129 BuiltinFunction::Use24HourFormat => {
2130 Value::Bool(i_slint_core::date_time::use_24_hour_format())
2131 }
2132 BuiltinFunction::ColorScheme => {
2133 let scheme = root_instance(ctx)
2134 .map(vtable::VRc::into_dyn)
2135 .and_then(|root| {
2136 i_slint_core::window::context_for_root(&root)
2137 .map(|ctx| ctx.color_scheme(Some(&root)))
2138 })
2139 .unwrap_or(i_slint_core::items::ColorScheme::Unknown);
2140 scheme.into()
2141 }
2142 BuiltinFunction::AccentColor => {
2143 let color = root_instance(ctx)
2144 .map(vtable::VRc::into_dyn)
2145 .map(|root| i_slint_core::window::accent_color(&root))
2146 .unwrap_or_default();
2147 Value::Brush(i_slint_core::Brush::SolidColor(color))
2148 }
2149 BuiltinFunction::SupportsNativeMenuBar => {
2150 let supports = find_window_adapter(ctx).is_some_and(|a| {
2151 a.internal(i_slint_core::InternalToken)
2152 .is_some_and(|x| x.supports_native_menu_bar())
2153 });
2154 Value::Bool(supports)
2155 }
2156 BuiltinFunction::TextInputFocused => {
2157 let focused = ctx
2158 .current
2159 .as_ref()
2160 .and_then(|c| c.root.get())
2161 .and_then(|w| w.upgrade())
2162 .and_then(|inst| inst.window_adapter_or_default())
2163 .map(|adapter| {
2164 i_slint_core::window::WindowInner::from_pub(adapter.window())
2165 .text_input_focused()
2166 })
2167 .unwrap_or(false);
2168 Value::Bool(focused)
2169 }
2170 BuiltinFunction::SetTextInputFocused => {
2171 let value = arguments
2172 .first()
2173 .map(|e| eval_expression(ctx, e))
2174 .and_then(|v| bool::try_from(v).ok())
2175 .unwrap_or(false);
2176 if let Some(adapter) = ctx
2177 .current
2178 .as_ref()
2179 .and_then(|c| c.root.get())
2180 .and_then(|w| w.upgrade())
2181 .and_then(|inst| inst.window_adapter_or_default())
2182 {
2183 i_slint_core::window::WindowInner::from_pub(adapter.window())
2184 .set_text_input_focused(value);
2185 }
2186 Value::Void
2187 }
2188 BuiltinFunction::UpdateTimers => {
2189 Value::Void
2192 }
2193 BuiltinFunction::RestartTimer => {
2194 if let [
2199 Expression::PropertyReference(MemberReference::Relative {
2200 parent_level,
2201 local_reference,
2202 }),
2203 ] = arguments
2204 && let LocalMemberIndex::Timer(timer_idx) = &local_reference.reference
2205 && ctx.current.is_some()
2206 {
2207 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2208 if let Some(timer) = instance.timers.get(usize::from(*timer_idx)) {
2209 timer.restart();
2210 }
2211 }
2212 Value::Void
2213 }
2214 BuiltinFunction::KeysToString => {
2215 let v = arguments.first().map(|e| eval_expression(ctx, e));
2216 if let Some(Value::Keys(keys)) = v {
2217 Value::String(keys.to_string().into())
2218 } else {
2219 Value::String(Default::default())
2220 }
2221 }
2222 BuiltinFunction::SetSelectionOffsets => {
2223 use i_slint_core::items::TextInput;
2225 let [Expression::PropertyReference(mr), start_expr, end_expr] = arguments else {
2226 return Value::Void;
2227 };
2228 let start: i32 = eval_expression(ctx, start_expr).try_into().unwrap_or(0);
2229 let end: i32 = eval_expression(ctx, end_expr).try_into().unwrap_or(0);
2230 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr) else {
2231 return Value::Void;
2232 };
2233 let Some(adapter) = parent_inst.window_adapter_or_default() else {
2234 return Value::Void;
2235 };
2236 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2237 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2238 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_rc.borrow()) {
2239 text_input.set_selection_offsets(&adapter, &item_rc, start, end);
2240 }
2241 Value::Void
2242 }
2243 BuiltinFunction::RegisterCustomFontByPath => {
2244 if let Value::String(s) = eval_expression(ctx, &arguments[0])
2245 && let Some(root) = find_root_instance(ctx)
2246 {
2247 let result =
2250 root.try_window_adapter().map_err(|e| e.to_string()).and_then(|adapter| {
2251 adapter
2252 .renderer()
2253 .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
2254 .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
2255 });
2256 if let Err(err) = result {
2257 i_slint_core::debug_log!("{err}");
2258 }
2259 }
2260 Value::Void
2261 }
2262 BuiltinFunction::SetupMenuBar => crate::popup::setup_menubar(ctx, arguments),
2263 BuiltinFunction::ItemFontMetrics => {
2264 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2265 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2266 && let Some(adapter) = inst.window_adapter_or_default()
2267 {
2268 let item_rc =
2269 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2270 let metrics = i_slint_core::items::slint_text_item_fontmetrics(
2271 &adapter,
2272 item_rc.borrow(),
2273 &item_rc,
2274 );
2275 return metrics.into();
2276 }
2277 i_slint_core::items::FontMetrics::default().into()
2278 }
2279 BuiltinFunction::ItemAbsolutePosition => {
2280 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2281 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2282 {
2283 let item_rc =
2284 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2285 return item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into();
2289 }
2290 i_slint_core::api::LogicalPosition::default().into()
2291 }
2292 BuiltinFunction::PathPointAt => {
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 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2299 return item_rc
2300 .downcast::<i_slint_core::items::Path>()
2301 .unwrap()
2302 .as_pin_ref()
2303 .point_at(&item_rc, t)
2304 .to_untyped()
2305 .into();
2306 }
2307 panic!("internal error: argument to PathPointAt must be an element")
2308 }
2309 BuiltinFunction::PathAngleAt => {
2310 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2311 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2312 {
2313 let item_rc =
2314 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2315 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2316 return item_rc
2317 .downcast::<i_slint_core::items::Path>()
2318 .unwrap()
2319 .as_pin_ref()
2320 .angle_at(&item_rc, t)
2321 .into();
2322 }
2323 panic!("internal error: argument to PathAngleAt must be an element")
2324 }
2325 BuiltinFunction::ArrayAny | BuiltinFunction::ArrayAll => {
2326 let is_all = matches!(f, BuiltinFunction::ArrayAll);
2327 let model: i_slint_core::model::ModelRc<Value> =
2328 eval_expression(ctx, &arguments[0]).try_into().unwrap();
2329 let Expression::Closure { arg_name, expression } = &arguments[1] else {
2330 panic!("internal error: Array.any/all expects a closure as second argument")
2331 };
2332 let mut predicate =
2333 |row_value| eval_array_row_predicate(arg_name, expression, ctx, row_value);
2334 Value::Bool(if is_all {
2335 i_slint_core::model::model_all(&model, &mut predicate)
2336 } else {
2337 i_slint_core::model::model_any(&model, &mut predicate)
2338 })
2339 }
2340 BuiltinFunction::ArrayFindIndex => {
2341 let model: i_slint_core::model::ModelRc<Value> =
2342 eval_expression(ctx, &arguments[0]).try_into().unwrap();
2343 let Expression::Closure { arg_name, expression } = &arguments[1] else {
2344 panic!("internal error: Array.find-index expects a closure as second argument")
2345 };
2346 Value::Number(i_slint_core::model::model_find_index(&model, |row_value| {
2347 eval_array_row_predicate(arg_name, expression, ctx, row_value)
2348 }) as f64)
2349 }
2350 BuiltinFunction::ImplicitLayoutInfo(orient) => {
2351 let constraint: f32 = arguments
2355 .get(1)
2356 .map(|e| eval_expression(ctx, e).try_into().unwrap_or(-1.))
2357 .unwrap_or(-1.);
2358 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2359 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2360 && let Some(adapter) = inst.window_adapter_or_default()
2361 {
2362 let item_rc =
2363 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2364 return item_rc
2365 .borrow()
2366 .as_ref()
2367 .layout_info(
2368 llr_to_core_orientation(orient),
2369 constraint as _,
2370 &adapter,
2371 &item_rc,
2372 )
2373 .into();
2374 }
2375 i_slint_core::layout::LayoutInfo::default().into()
2376 }
2377 BuiltinFunction::Debug => {
2378 use i_slint_core::debug_log::*;
2379 let msg = to_string(ctx, &arguments[0]);
2380 let root = ctx
2381 .current
2382 .as_ref()
2383 .and_then(|c| c.root.get())
2384 .and_then(|w| w.upgrade())
2385 .map(vtable::VRc::into_dyn);
2386 if let Some(context) = root.as_ref().and_then(i_slint_core::window::context_for_root) {
2387 context.dispatch_log_message(LogMessage::new(
2388 LogMessageSource::SlintCode,
2389 None,
2390 format_args!("{msg}"),
2391 ));
2392 } else {
2393 log_message(LogMessage::new(
2394 LogMessageSource::SlintCode,
2395 None,
2396 format_args!("{msg}"),
2397 ));
2398 }
2399 Value::Void
2400 }
2401 BuiltinFunction::ArrayLength => match eval_expression(ctx, &arguments[0]) {
2402 Value::Model(m) => {
2405 m.model_tracker().track_row_count_changes();
2406 Value::Number(m.row_count() as f64)
2407 }
2408 _ => Value::Number(0.),
2409 },
2410 BuiltinFunction::ImageSize => {
2411 if let Value::Image(img) = eval_expression(ctx, &arguments[0]) {
2412 let size = img.size();
2413 let mut s = crate::api::Struct::default();
2414 s.set_field("width".to_string(), Value::Number(size.width as f64));
2415 s.set_field("height".to_string(), Value::Number(size.height as f64));
2416 Value::Struct(s)
2417 } else {
2418 Value::Void
2419 }
2420 }
2421 BuiltinFunction::ParseMarkdown => {
2422 let format_string: SharedString =
2423 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2424 let args = eval_expression(ctx, &arguments[1]);
2425 let args: Vec<i_slint_core::styled_text::StyledText> = if let Value::Model(m) = args {
2426 (0..m.row_count())
2427 .filter_map(|i| match m.row_data(i)? {
2428 Value::StyledText(t) => Some(t),
2429 _ => None,
2430 })
2431 .collect()
2432 } else {
2433 Vec::new()
2434 };
2435 Value::StyledText(i_slint_core::styled_text::parse_markdown(&format_string, &args))
2436 }
2437 BuiltinFunction::StringToStyledText => {
2438 let string: SharedString =
2439 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2440 Value::StyledText(i_slint_core::styled_text::string_to_styled_text(string.to_string()))
2441 }
2442 BuiltinFunction::Translate => {
2443 let original: SharedString = to_string(ctx, &arguments[0]);
2444 let context: SharedString = to_string(ctx, &arguments[1]);
2445 let domain: SharedString = to_string(ctx, &arguments[2]);
2446 let args = eval_expression(ctx, &arguments[3]);
2447 let Value::Model(args) = args else {
2448 return Value::String(original);
2449 };
2450 struct StringModelWrapper(ModelRc<Value>);
2451 impl i_slint_core::translations::FormatArgs for StringModelWrapper {
2452 type Output<'a> = SharedString;
2453 fn from_index(&self, index: usize) -> Option<SharedString> {
2454 self.0.row_data(index).and_then(|v| v.try_into().ok())
2455 }
2456 }
2457 let n: i32 = eval_expression(ctx, &arguments[4]).try_into().unwrap_or(0);
2458 let plural: SharedString = to_string(ctx, &arguments[5]);
2459 Value::String(i_slint_core::translations::translate(
2460 &original,
2461 &context,
2462 &domain,
2463 &StringModelWrapper(args),
2464 n,
2465 &plural,
2466 ))
2467 }
2468 BuiltinFunction::ShowPopupWindow => crate::popup::show_popup_window(ctx, arguments),
2469 BuiltinFunction::ClosePopupWindow => crate::popup::close_popup_window(ctx, arguments),
2470 BuiltinFunction::SetFocusItem => {
2471 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2472 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2473 && let Some(adapter) = find_window_adapter(ctx)
2474 {
2475 let dyn_rc = vtable::VRc::into_dyn(inst);
2476 let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2477 i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2478 &item_rc,
2479 true,
2480 i_slint_core::input::FocusReason::Programmatic,
2481 );
2482 }
2483 Value::Void
2484 }
2485 BuiltinFunction::ClearFocusItem => {
2486 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2487 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2488 && let Some(adapter) = find_window_adapter(ctx)
2489 {
2490 let dyn_rc = vtable::VRc::into_dyn(inst);
2491 let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2492 i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2493 &item_rc,
2494 false,
2495 i_slint_core::input::FocusReason::Programmatic,
2496 );
2497 }
2498 Value::Void
2499 }
2500 BuiltinFunction::MonthDayCount => {
2501 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2502 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2503 Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
2504 }
2505 BuiltinFunction::MonthOffset => {
2506 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2507 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2508 Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
2509 }
2510 BuiltinFunction::FormatDate => {
2511 let f: SharedString = to_string(ctx, &arguments[0]);
2512 let d: u32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2513 let m: u32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2514 let y: i32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(0);
2515 Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
2516 }
2517 BuiltinFunction::DateNow => {
2518 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2519 i_slint_core::date_time::date_now()
2520 .into_iter()
2521 .map(|x| Value::Number(x as f64))
2522 .collect::<Vec<_>>(),
2523 )))
2524 }
2525 BuiltinFunction::ValidDate => {
2526 let d: SharedString = to_string(ctx, &arguments[0]);
2527 let f: SharedString = to_string(ctx, &arguments[1]);
2528 Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
2529 }
2530 BuiltinFunction::ParseDate => {
2531 let d: SharedString = to_string(ctx, &arguments[0]);
2532 let f: SharedString = to_string(ctx, &arguments[1]);
2533 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2534 i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
2535 .map(|v| v.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>())
2536 .unwrap_or_default(),
2537 )))
2538 }
2539 BuiltinFunction::ShowPopupMenu | BuiltinFunction::ShowPopupMenuInternal => {
2540 crate::popup::show_popup_menu(ctx, arguments)
2541 }
2542 BuiltinFunction::OpenUrl => {
2543 let url = to_string(ctx, &arguments[0]);
2544 let result = find_window_adapter(ctx)
2545 .map(|adapter| i_slint_core::open_url(&url, adapter.window()).is_ok())
2546 .unwrap_or(false);
2547 Value::Bool(result)
2548 }
2549 BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
2550 Value::Void
2552 }
2553 BuiltinFunction::StartTimer | BuiltinFunction::StopTimer => {
2554 Value::Void
2556 }
2557 }
2558}
2559
2560pub(crate) fn resolve_item_rc_from_ref(
2564 ctx: &EvalContext,
2565 mr: &MemberReference,
2566) -> Option<(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>, usize)>
2567{
2568 let MemberReference::Relative { parent_level, local_reference } = mr else { return None };
2569 let LocalMemberIndex::Native { item_index, .. } = &local_reference.reference else {
2570 return None;
2571 };
2572 let owner = try_walk_to(ctx, *parent_level, &local_reference.sub_component_path)?;
2573 let parent_inst = owner.root.get().and_then(|w| w.upgrade())?;
2574 let full_path = crate::item_tree_vtable::sub_component_path_of(&owner, &parent_inst);
2575 let flat_idx = find_flat_item_index(&parent_inst.item_table, &full_path, *item_index)?;
2576 Some((parent_inst, flat_idx))
2577}
2578
2579pub(crate) fn find_root_instance(
2583 ctx: &EvalContext,
2584) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
2585 let current = ctx.current.as_ref()?;
2586 let mut sub = current.clone();
2587 loop {
2588 if let Some(root) = sub.root.get()
2589 && let Some(inst) = root.upgrade()
2590 && inst.public_component_index.is_some()
2591 {
2592 return Some(inst);
2593 }
2594 let parent = sub.parent.upgrade()?;
2595 sub = Pin::new(parent);
2596 }
2597}
2598
2599pub(crate) fn find_window_adapter(
2601 ctx: &EvalContext,
2602) -> Option<i_slint_core::window::WindowAdapterRc> {
2603 find_root_instance(ctx)?.window_adapter_or_default()
2604}
2605
2606fn call_item_member_function(ctx: &EvalContext, function: &MemberReference) -> Value {
2610 use i_slint_core::items::{ContextMenu, SwipeGestureHandler, TextInput, WindowItem};
2611 let MemberReference::Relative { local_reference, .. } = function else {
2612 return Value::Void;
2613 };
2614 let LocalMemberIndex::Native { prop_name, .. } = &local_reference.reference else {
2615 return Value::Void;
2616 };
2617 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, function) else {
2618 return Value::Void;
2619 };
2620 let Some(adapter) = parent_inst.window_adapter_or_default() else { return Value::Void };
2621 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2622 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2623 let item_ref = item_rc.borrow();
2624
2625 macro_rules! dispatch {
2628 ($item:expr, $name:expr; $($slint_name:literal => $rust_method:ident $(=> $into:ty)?),* $(,)?) => {
2629 match $name {
2630 $(
2631 $slint_name => {
2632 let res = $item.$rust_method(&adapter, &item_rc);
2633 $(let res: $into = res.into();)?
2634 return res.into();
2635 }
2636 )*
2637 _ => {}
2638 }
2639 };
2640 }
2641
2642 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_ref) {
2643 dispatch!(text_input, prop_name.as_str();
2644 "select-all" => select_all => (),
2645 "clear-selection" => clear_selection => (),
2646 "select-word" => select_word => (),
2647 "cut" => cut => (),
2648 "copy" => copy => (),
2649 "paste" => paste => (),
2650 "undo" => undo => (),
2651 "redo" => redo => (),
2652 );
2653 }
2654 if let Some(swipe) = vtable::VRef::downcast_pin::<SwipeGestureHandler>(item_rc.borrow()) {
2655 dispatch!(swipe, prop_name.as_str();
2656 "cancel" => cancel => (),
2657 );
2658 }
2659 if let Some(menu) = vtable::VRef::downcast_pin::<ContextMenu>(item_rc.borrow()) {
2660 dispatch!(menu, prop_name.as_str();
2661 "close" => close => (),
2662 "is-open" => is_open,
2663 );
2664 }
2665 if let Some(window) = vtable::VRef::downcast_pin::<WindowItem>(item_rc.borrow()) {
2666 match prop_name.as_str() {
2667 "hide" => {
2668 window.hide(&adapter, &item_rc);
2669 return Value::Void;
2670 }
2671 "close" => return Value::Bool(window.close(&adapter, &item_rc)),
2672 _ => {}
2673 }
2674 }
2675 unimplemented!("ItemMemberFunctionCall `{prop_name}`")
2676}