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(
1346 "cross_axis_self_alignment".to_string(),
1347 Value::EnumerationValue(
1348 "CrossAxisSelfAlignment".to_string(),
1349 format!("{:?}", props.cross_axis_self_alignment).to_lowercase(),
1350 ),
1351 );
1352 s.set_field("flex_order".to_string(), Value::Number(props.flex_order as f64));
1353 Value::Struct(s)
1354}
1355
1356fn with_grid_input_data(
1357 ctx: &mut EvalContext,
1358 cells_variable: &str,
1359 elements: &[itertools::Either<Expression, i_slint_compiler::llr::GridLayoutRepeatedElement>],
1360 sub_expression: &Expression,
1361) -> Value {
1362 let saved_new_row = ctx.locals.remove("new_row");
1369 let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1370 let mut repeated_indices: Vec<u32> = Vec::new();
1371 let mut repeater_steps: Vec<u32> = Vec::new();
1372
1373 for el in elements {
1374 match el {
1375 itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1376 itertools::Either::Right(repeater) => {
1377 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(repeater.new_row));
1378 let offset = cells.len() as u32;
1379 let is_row_repeater = repeater.row_child_templates.is_some();
1380 let (instances, step) = push_repeater_grid_input_data(
1381 ctx,
1382 repeater.repeater_index,
1383 repeater.new_row,
1384 repeater.row_child_templates.as_deref(),
1385 &mut cells,
1386 );
1387 if !is_row_repeater && instances > 0 {
1388 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(false));
1389 }
1390 repeated_indices.push(offset);
1391 repeated_indices.push(instances);
1392 repeater_steps.push(step);
1393 }
1394 }
1395 }
1396 restore_local(ctx, "new_row", saved_new_row);
1397
1398 let prev_cells =
1399 ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1400 let prev_ri = ctx.locals.insert(
1401 SmolStr::new_static("repeated_indices"),
1402 Value::Model(model_from_vec(
1403 repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1404 )),
1405 );
1406 let prev_rs = ctx.locals.insert(
1407 SmolStr::new_static("repeater_steps"),
1408 Value::Model(model_from_vec(
1409 repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1410 )),
1411 );
1412
1413 let result = eval_expression(ctx, sub_expression);
1414
1415 restore_local(ctx, cells_variable, prev_cells);
1416 restore_local(ctx, "repeated_indices", prev_ri);
1417 restore_local(ctx, "repeater_steps", prev_rs);
1418 result
1419}
1420
1421pub(crate) fn restore_local(ctx: &mut EvalContext, name: &str, prev: Option<Value>) {
1422 if let Some(prev) = prev {
1423 ctx.locals.insert(SmolStr::from(name), prev);
1424 } else {
1425 ctx.locals.remove(name);
1426 }
1427}
1428
1429fn push_repeater_grid_input_data(
1430 ctx: &mut EvalContext,
1431 repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1432 new_row: bool,
1433 row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1434 cells: &mut Vec<Value>,
1435) -> (u32, u32) {
1436 use i_slint_compiler::llr::RowChildTemplateInfo;
1437 use i_slint_core::model::VecModel;
1438 use std::rc::Rc;
1439 let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1440 let repeater = ¤t.repeaters[repeater_idx];
1441 repeater.track_instance_changes();
1442
1443 let is_row_repeater = row_child_templates.is_some();
1444 let static_count =
1445 row_child_templates.map(i_slint_compiler::llr::static_child_count).unwrap_or(1);
1446
1447 let instances = repeater.instances_vec();
1448 let instance_count = instances.len() as u32;
1449
1450 let step = if let Some(templates) = row_child_templates {
1454 instances
1455 .iter()
1456 .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1457 .max()
1458 .unwrap_or(static_count)
1459 } else {
1460 1
1461 };
1462
1463 let mut current_new_row = new_row;
1464
1465 for instance in &instances {
1466 let inner_sub = instance.root_sub_component.clone();
1467 let cu = inner_sub.compilation_unit.clone();
1468 let sc = &cu.sub_components[inner_sub.sub_component_idx];
1469
1470 let mut statics: Vec<Value> = vec![Value::Void; static_count];
1474 if let Some(expr) = &sc.grid_layout_input_for_repeated {
1475 let expr = expr.borrow();
1476 let mut inner_ctx = EvalContext::new(inner_sub.clone());
1477 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1478 for _ in 0..static_count {
1479 result_model.push(Value::Void);
1480 }
1481 inner_ctx.locals.insert(
1482 SmolStr::new_static("result"),
1483 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1484 );
1485 inner_ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(current_new_row));
1486 eval_expression(&mut inner_ctx, &expr);
1487 for (slot, i) in statics.iter_mut().zip(0..result_model.row_count()) {
1488 if let Some(v) = result_model.row_data(i) {
1489 *slot = v;
1490 }
1491 }
1492 }
1493
1494 if let Some(templates) = row_child_templates {
1495 let mut written = 0usize;
1499 let mut static_idx = 0usize;
1500 for entry in templates {
1501 if written >= step {
1502 break;
1503 }
1504 match entry {
1505 RowChildTemplateInfo::Static { .. } => {
1506 let mut v = statics.get(static_idx).cloned().unwrap_or(Value::Void);
1507 static_idx += 1;
1508 override_new_row(&mut v, written == 0 && current_new_row);
1509 cells.push(v);
1510 written += 1;
1511 }
1512 RowChildTemplateInfo::Repeated { repeater_index } => {
1513 let inner_rep = &inner_sub.repeaters[*repeater_index];
1514 inner_rep.track_instance_changes();
1515 for inner_inst in inner_rep.instances_vec() {
1519 if written >= step {
1520 break;
1521 }
1522 for mut v in eval_grid_input_for_repeated(
1523 &inner_inst.root_sub_component,
1524 written == 0 && current_new_row,
1525 ) {
1526 if written >= step {
1527 break;
1528 }
1529 override_new_row(&mut v, written == 0 && current_new_row);
1530 cells.push(v);
1531 written += 1;
1532 }
1533 }
1534 }
1535 }
1536 }
1537 while written < step {
1538 cells.push(auto_grid_input_data());
1539 written += 1;
1540 }
1541 } else {
1542 cells.push(statics.pop().unwrap_or_else(auto_grid_input_data));
1544 }
1545
1546 if !is_row_repeater {
1547 current_new_row = false;
1548 }
1549 }
1550 (instance_count, step as u32)
1551}
1552
1553fn eval_grid_input_for_repeated(
1558 sub: &Pin<Rc<crate::instance::SubComponentInstance>>,
1559 new_row: bool,
1560) -> Vec<Value> {
1561 use i_slint_core::model::{Model, VecModel};
1562 let cu = sub.compilation_unit.clone();
1563 let sc = &cu.sub_components[sub.sub_component_idx];
1564 let count = sc
1565 .row_child_templates
1566 .as_ref()
1567 .map(|t| i_slint_compiler::llr::static_child_count(t))
1568 .unwrap_or(1)
1569 .max(1);
1570 let Some(expr) = &sc.grid_layout_input_for_repeated else {
1571 return vec![auto_grid_input_data()];
1572 };
1573 let expr = expr.borrow();
1574 let mut ctx = EvalContext::new(sub.clone());
1575 let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1576 for _ in 0..count {
1577 result_model.push(Value::Void);
1578 }
1579 ctx.locals.insert(
1580 SmolStr::new_static("result"),
1581 Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1582 );
1583 ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(new_row));
1584 eval_expression(&mut ctx, &expr);
1585 (0..result_model.row_count())
1586 .map(|i| result_model.row_data(i).unwrap_or_else(auto_grid_input_data))
1587 .collect()
1588}
1589
1590fn auto_grid_input_data() -> Value {
1593 let mut s = crate::api::Struct::default();
1594 s.set_field("new_row".into(), Value::Bool(false));
1595 s.set_field("row".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1596 s.set_field("col".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1597 s.set_field("rowspan".into(), Value::Number(1.0));
1598 s.set_field("colspan".into(), Value::Number(1.0));
1599 Value::Struct(s)
1600}
1601
1602fn override_new_row(v: &mut Value, new_row: bool) {
1603 if let Value::Struct(s) = v {
1604 s.set_field("new_row".into(), Value::Bool(new_row));
1605 }
1606}
1607
1608fn model_from_vec(values: Vec<Value>) -> ModelRc<Value> {
1609 ModelRc::new(SharedVectorModel::from(values.into_iter().collect::<SharedVector<_>>()))
1610}
1611
1612fn binary_op(op: char, lhs: Value, rhs: Value) -> Value {
1613 let (lhs, rhs) = match (lhs, rhs) {
1616 (Value::Void, Value::Number(b)) => (Value::Number(0.), Value::Number(b)),
1617 (Value::Number(a), Value::Void) => (Value::Number(a), Value::Number(0.)),
1618 (Value::Void, Value::Bool(b)) => (Value::Bool(false), Value::Bool(b)),
1619 (Value::Bool(a), Value::Void) => (Value::Bool(a), Value::Bool(false)),
1620 (Value::Void, Value::String(b)) => (Value::String(Default::default()), Value::String(b)),
1621 (Value::String(a), Value::Void) => (Value::String(a), Value::String(Default::default())),
1622 (a, b) => (a, b),
1623 };
1624 match (op, lhs, rhs) {
1625 ('+', Value::String(mut a), Value::String(b)) => {
1626 a.push_str(b.as_str());
1627 Value::String(a)
1628 }
1629 ('+', Value::Number(a), Value::Number(b)) => Value::Number(a + b),
1630 ('+', a @ Value::Struct(_), b @ Value::Struct(_)) => {
1631 let la: Option<i_slint_core::layout::LayoutInfo> = a.try_into().ok();
1632 let lb: Option<i_slint_core::layout::LayoutInfo> = b.try_into().ok();
1633 if let (Some(a), Some(b)) = (la, lb) {
1634 a.merge(&b).into()
1635 } else {
1636 panic!("unsupported struct + struct");
1637 }
1638 }
1639 ('-', Value::Number(a), Value::Number(b)) => Value::Number(a - b),
1640 ('/', Value::Number(a), Value::Number(b)) => Value::Number(a / b),
1641 ('*', Value::Number(a), Value::Number(b)) => Value::Number(a * b),
1642 ('<', Value::Number(a), Value::Number(b)) => Value::Bool(a < b),
1643 ('>', Value::Number(a), Value::Number(b)) => Value::Bool(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::String(a), Value::String(b)) => Value::Bool(a < b),
1647 ('>', Value::String(a), Value::String(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 ('=', a, b) => Value::Bool(a == b),
1651 ('!', a, b) => Value::Bool(a != b),
1652 ('&', Value::Bool(a), Value::Bool(b)) => Value::Bool(a && b),
1653 ('|', Value::Bool(a), Value::Bool(b)) => Value::Bool(a || b),
1654 (op, a, b) => panic!("unsupported {a:?} {op} {b:?}"),
1655 }
1656}
1657
1658fn eval_stops(ctx: &mut EvalContext, stops: &[(Expression, Expression)]) -> Vec<GradientStop> {
1659 stops
1660 .iter()
1661 .map(|(color, stop)| GradientStop {
1662 color: eval_expression(ctx, color).try_into().unwrap_or_default(),
1663 position: eval_expression(ctx, stop).try_into().unwrap_or_default(),
1664 })
1665 .collect()
1666}
1667
1668fn load_image_reference(
1669 resource_ref: &i_slint_compiler::expression_tree::ImageReference,
1670) -> i_slint_core::graphics::Image {
1671 use i_slint_compiler::expression_tree::ImageReference as Ref;
1672 let image = match resource_ref {
1673 Ref::None => Ok(Default::default()),
1674 Ref::DataUri(data_uri) => i_slint_compiler::data_uri::decode_data_uri(data_uri)
1675 .ok()
1676 .and_then(|(data, extension)| {
1677 i_slint_core::graphics::load_image_from_data_uri(data_uri, &data, &extension).ok()
1678 })
1679 .ok_or_else(Default::default),
1680 Ref::Url(url) if url.scheme() == "builtin" => {
1681 let path = std::path::Path::new(url.as_str());
1685 i_slint_compiler::fileaccess::load_file(path)
1686 .and_then(|virtual_file| virtual_file.builtin_contents)
1687 .map(|contents| {
1688 let extension = path.extension().unwrap().to_str().unwrap();
1689 i_slint_core::graphics::load_image_from_embedded_data(
1690 i_slint_core::slice::Slice::from_slice(contents),
1691 i_slint_core::slice::Slice::from_slice(extension.as_bytes()),
1692 )
1693 })
1694 .ok_or_else(Default::default)
1695 }
1696 Ref::Path(path) => {
1697 i_slint_core::graphics::Image::load_from_path(std::path::Path::new(path.as_str()))
1698 }
1699 Ref::Url(url) => {
1700 #[cfg(target_arch = "wasm32")]
1701 {
1702 i_slint_core::graphics::load_as_html_image(url.as_str())
1703 }
1704 #[cfg(not(target_arch = "wasm32"))]
1706 {
1707 let _ = url;
1708 Err(Default::default())
1709 }
1710 }
1711 Ref::EmbeddedData { .. } | Ref::EmbeddedTexture { .. } => Ok(Default::default()),
1712 };
1713 image.unwrap_or_else(|_| {
1714 eprintln!("Could not load image {resource_ref:?}");
1715 Default::default()
1716 })
1717}
1718
1719fn layout_cache_access(
1720 ctx: &mut EvalContext,
1721 cache: Value,
1722 index: usize,
1723 repeater_index: Option<&Expression>,
1724 entries_per_item: usize,
1725) -> Value {
1726 match cache {
1727 Value::LayoutCache(cache) => {
1728 if let Some(ri) = repeater_index {
1729 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1730 Value::Number(
1731 cache
1732 .get((cache[index] as usize) + offset * entries_per_item)
1733 .copied()
1734 .unwrap_or(0.)
1735 .into(),
1736 )
1737 } else {
1738 Value::Number(cache[index].into())
1739 }
1740 }
1741 Value::ArrayOfU16(cache) => {
1742 if let Some(ri) = repeater_index {
1743 let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1744 Value::Number(
1745 cache
1746 .get((cache[index] as usize) + offset * entries_per_item)
1747 .copied()
1748 .unwrap_or(0)
1749 .into(),
1750 )
1751 } else {
1752 Value::Number(cache[index].into())
1753 }
1754 }
1755 _ => Value::Number(0.),
1756 }
1757}
1758
1759fn grid_repeater_cache_access(
1764 cache: Value,
1765 index: usize,
1766 repeater_index: usize,
1767 stride: usize,
1768 child_offset: usize,
1769 inner_offset: usize,
1770) -> Value {
1771 let get = |data_idx: usize, slice_len: usize, read: &dyn Fn(usize) -> f64| {
1772 if data_idx < slice_len { Value::Number(read(data_idx)) } else { Value::Number(0.) }
1773 };
1774 match cache {
1775 Value::LayoutCache(cache) => {
1776 let base = cache.get(index).copied().unwrap_or(0.) as usize;
1777 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1778 get(data_idx, cache.len(), &|i| cache[i] as f64)
1779 }
1780 Value::ArrayOfU16(cache) => {
1781 let base = cache.get(index).copied().unwrap_or(0) as usize;
1782 let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1783 get(data_idx, cache.len(), &|i| cache[i] as f64)
1784 }
1785 _ => Value::Number(0.),
1786 }
1787}
1788
1789fn call_builtin_function(
1791 ctx: &mut EvalContext,
1792 f: BuiltinFunction,
1793 arguments: &[Expression],
1794) -> Value {
1795 let to_num = |ctx: &mut EvalContext, e: &Expression| -> f64 {
1796 eval_expression(ctx, e).try_into().unwrap_or_default()
1797 };
1798 let to_string = |ctx: &mut EvalContext, e: &Expression| -> SharedString {
1799 eval_expression(ctx, e).try_into().unwrap_or_default()
1800 };
1801
1802 match f {
1803 BuiltinFunction::Mod => {
1804 Value::Number(to_num(ctx, &arguments[0]).rem_euclid(to_num(ctx, &arguments[1])))
1805 }
1806 BuiltinFunction::Round => Value::Number(to_num(ctx, &arguments[0]).round()),
1807 BuiltinFunction::Ceil => Value::Number(to_num(ctx, &arguments[0]).ceil()),
1808 BuiltinFunction::Floor => Value::Number(to_num(ctx, &arguments[0]).floor()),
1809 BuiltinFunction::Sqrt => Value::Number(to_num(ctx, &arguments[0]).sqrt()),
1810 BuiltinFunction::Abs => Value::Number(to_num(ctx, &arguments[0]).abs()),
1811 BuiltinFunction::Sin => Value::Number(to_num(ctx, &arguments[0]).to_radians().sin()),
1812 BuiltinFunction::Cos => Value::Number(to_num(ctx, &arguments[0]).to_radians().cos()),
1813 BuiltinFunction::Tan => Value::Number(to_num(ctx, &arguments[0]).to_radians().tan()),
1814 BuiltinFunction::ASin => Value::Number(to_num(ctx, &arguments[0]).asin().to_degrees()),
1815 BuiltinFunction::ACos => Value::Number(to_num(ctx, &arguments[0]).acos().to_degrees()),
1816 BuiltinFunction::ATan => Value::Number(to_num(ctx, &arguments[0]).atan().to_degrees()),
1817 BuiltinFunction::ATan2 => {
1818 Value::Number(to_num(ctx, &arguments[0]).atan2(to_num(ctx, &arguments[1])).to_degrees())
1819 }
1820 BuiltinFunction::Log => {
1821 Value::Number(to_num(ctx, &arguments[0]).log(to_num(ctx, &arguments[1])))
1822 }
1823 BuiltinFunction::Ln => Value::Number(to_num(ctx, &arguments[0]).ln()),
1824 BuiltinFunction::Pow => {
1825 Value::Number(to_num(ctx, &arguments[0]).powf(to_num(ctx, &arguments[1])))
1826 }
1827 BuiltinFunction::Exp => Value::Number(to_num(ctx, &arguments[0]).exp()),
1828 BuiltinFunction::ToFixed => {
1829 let n = to_num(ctx, &arguments[0]);
1830 let digits: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1831 Value::String(i_slint_core::string::shared_string_from_number_fixed(
1832 n,
1833 digits.max(0) as usize,
1834 ))
1835 }
1836 BuiltinFunction::ToPrecision => {
1837 let n = to_num(ctx, &arguments[0]);
1838 let p: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1839 Value::String(i_slint_core::string::shared_string_from_number_precision(
1840 n,
1841 p.max(0) as usize,
1842 ))
1843 }
1844 BuiltinFunction::StringStartsWith => Value::Bool(
1845 to_string(ctx, &arguments[0])
1846 .as_str()
1847 .starts_with(to_string(ctx, &arguments[1]).as_str()),
1848 ),
1849 BuiltinFunction::StringEndsWith => Value::Bool(
1850 to_string(ctx, &arguments[0])
1851 .as_str()
1852 .ends_with(to_string(ctx, &arguments[1]).as_str()),
1853 ),
1854 BuiltinFunction::ToStringUnlocalized => {
1855 let n = to_num(ctx, &arguments[0]);
1856 Value::String(i_slint_core::string::shared_string_from_number_unlocalized(n))
1857 }
1858 BuiltinFunction::DecimalSeparator => Value::String(
1859 find_window_adapter(ctx)
1860 .map(|adapter| {
1861 i_slint_core::window::WindowInner::from_pub(adapter.window())
1862 .context()
1863 .locale_decimal_separator()
1864 })
1865 .unwrap_or_default()
1866 .into(),
1867 ),
1868 BuiltinFunction::MacosBringAllWindowsToFront => {
1869 i_slint_core::macos_bring_all_windows_to_front();
1870 Value::Void
1871 }
1872 BuiltinFunction::ColorToStyledText => {
1873 let color: i_slint_core::Color =
1874 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
1875 Value::StyledText(i_slint_core::styled_text::color_to_styled_text(color))
1876 }
1877 BuiltinFunction::SetupSystemTrayIcon => {
1878 crate::popup::setup_system_tray_icon(ctx, arguments)
1879 }
1880 BuiltinFunction::StringIsFloat => Value::Bool(
1881 <f64 as core::str::FromStr>::from_str(to_string(ctx, &arguments[0]).as_str()).is_ok(),
1882 ),
1883 BuiltinFunction::StringToFloat => Value::Number(
1884 core::str::FromStr::from_str(to_string(ctx, &arguments[0]).as_str()).unwrap_or(0.),
1885 ),
1886 BuiltinFunction::StringIsEmpty => Value::Bool(to_string(ctx, &arguments[0]).is_empty()),
1887 BuiltinFunction::StringCharacterCount => Value::Number(
1888 unicode_segmentation::UnicodeSegmentation::graphemes(
1889 to_string(ctx, &arguments[0]).as_str(),
1890 true,
1891 )
1892 .count() as f64,
1893 ),
1894 BuiltinFunction::StringToLowercase => {
1895 Value::String(to_string(ctx, &arguments[0]).to_lowercase().into())
1896 }
1897 BuiltinFunction::StringToUppercase => {
1898 Value::String(to_string(ctx, &arguments[0]).to_uppercase().into())
1899 }
1900 BuiltinFunction::StringReplaceAll => {
1901 if arguments.len() != 3 {
1902 panic!("internal error: incorrect argument count to StringReplaceAll")
1903 }
1904
1905 if let (Value::String(s), Value::String(from), Value::String(to)) = (
1906 eval_expression(ctx, &arguments[0]),
1907 eval_expression(ctx, &arguments[1]),
1908 eval_expression(ctx, &arguments[2]),
1909 ) {
1910 Value::String(i_slint_core::string::shared_string_replace_all(
1911 &s,
1912 from.as_str(),
1913 to.as_str(),
1914 ))
1915 } else {
1916 panic!("Not all arguments are strings");
1917 }
1918 }
1919 BuiltinFunction::ColorRgbaStruct => {
1920 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1921 let color = brush.color();
1922 let values = [
1923 ("red".to_string(), Value::Number(color.red().into())),
1924 ("green".to_string(), Value::Number(color.green().into())),
1925 ("blue".to_string(), Value::Number(color.blue().into())),
1926 ("alpha".to_string(), Value::Number(color.alpha().into())),
1927 ]
1928 .into_iter()
1929 .collect();
1930 Value::Struct(values)
1931 } else {
1932 Value::Void
1933 }
1934 }
1935 BuiltinFunction::ColorHsvaStruct => {
1936 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1937 let color = brush.color().to_hsva();
1938 let values = [
1939 ("hue".to_string(), Value::Number(color.hue.into())),
1940 ("saturation".to_string(), Value::Number(color.saturation.into())),
1941 ("value".to_string(), Value::Number(color.value.into())),
1942 ("alpha".to_string(), Value::Number(color.alpha.into())),
1943 ]
1944 .into_iter()
1945 .collect();
1946 Value::Struct(values)
1947 } else {
1948 Value::Void
1949 }
1950 }
1951 BuiltinFunction::ColorOklchStruct => {
1952 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1953 let color = brush.color().to_oklch();
1954 let values = [
1955 ("lightness".to_string(), Value::Number(color.lightness.into())),
1956 ("chroma".to_string(), Value::Number(color.chroma.into())),
1957 ("hue".to_string(), Value::Number(color.hue.into())),
1958 ("alpha".to_string(), Value::Number(color.alpha.into())),
1959 ]
1960 .into_iter()
1961 .collect();
1962 Value::Struct(values)
1963 } else {
1964 Value::Void
1965 }
1966 }
1967 BuiltinFunction::ColorBrighter => {
1968 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1969 brush.brighter(to_num(ctx, &arguments[1]) as f32).into()
1970 } else {
1971 Value::Void
1972 }
1973 }
1974 BuiltinFunction::ColorDarker => {
1975 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1976 brush.darker(to_num(ctx, &arguments[1]) as f32).into()
1977 } else {
1978 Value::Void
1979 }
1980 }
1981 BuiltinFunction::ColorTransparentize => {
1982 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1983 brush.transparentize(to_num(ctx, &arguments[1]) as f32).into()
1984 } else {
1985 Value::Void
1986 }
1987 }
1988 BuiltinFunction::ColorWithAlpha => {
1989 if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1990 brush.with_alpha(to_num(ctx, &arguments[1]) as f32).into()
1991 } else {
1992 Value::Void
1993 }
1994 }
1995 BuiltinFunction::ColorMix => {
1996 let a = eval_expression(ctx, &arguments[0]);
1997 let b = eval_expression(ctx, &arguments[1]);
1998 let factor = to_num(ctx, &arguments[2]) as f32;
1999 if let (
2000 Value::Brush(i_slint_core::Brush::SolidColor(ca)),
2001 Value::Brush(i_slint_core::Brush::SolidColor(cb)),
2002 ) = (a, b)
2003 {
2004 ca.mix(&cb, factor).into()
2005 } else {
2006 Value::Void
2007 }
2008 }
2009 BuiltinFunction::ArrayPush => {
2010 if arguments.len() != 2 {
2011 panic!("internal error: incorrect argument count to ArrayPush")
2012 }
2013
2014 let model = match eval_expression(ctx, &arguments[0]) {
2015 Value::Model(m) => m,
2016 _ => panic!("First argument not an array: {:?}", arguments[0]),
2017 };
2018 let value = eval_expression(ctx, &arguments[1]);
2019
2020 model.push_row(value);
2021
2022 Value::Void
2023 }
2024 BuiltinFunction::ArrayRemove => {
2025 if arguments.len() != 2 {
2026 panic!("internal error: incorrect argument count to ArrayRemove")
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 index = match eval_expression(ctx, &arguments[1]) {
2034 Value::Number(i) => i,
2035 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
2036 };
2037
2038 model.remove_row(index as isize);
2039
2040 Value::Void
2041 }
2042
2043 BuiltinFunction::ArrayInsert => {
2044 if arguments.len() != 3 {
2045 panic!("internal error: incorrect argument count to ArrayInsert")
2046 }
2047
2048 let model = match eval_expression(ctx, &arguments[0]) {
2049 Value::Model(m) => m,
2050 _ => panic!("First argument not an array: {:?}", arguments[0]),
2051 };
2052 let index = match eval_expression(ctx, &arguments[1]) {
2053 Value::Number(i) => i,
2054 _ => panic!("Second argument not an integer: {:?}", arguments[1]),
2055 };
2056
2057 let value = eval_expression(ctx, &arguments[2]);
2058 model.insert_row(index as isize, value);
2059
2060 Value::Void
2061 }
2062 BuiltinFunction::Rgb => {
2063 let r: i32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2064 let g: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2065 let b: i32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2066 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2067 let r: u8 = r.clamp(0, 255) as u8;
2068 let g: u8 = g.clamp(0, 255) as u8;
2069 let b: u8 = b.clamp(0, 255) as u8;
2070 let a: u8 = (255. * a).clamp(0., 255.) as u8;
2071 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_argb_u8(
2072 a, r, g, b,
2073 )))
2074 }
2075 BuiltinFunction::Hsv => {
2076 let h: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2077 let s: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2078 let v: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2079 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2080 let a = a.clamp(0., 1.);
2081 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_hsva(
2082 h, s, v, a,
2083 )))
2084 }
2085 BuiltinFunction::Oklch => {
2086 let l: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2087 let c: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2088 let h: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2089 let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2090 Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_oklch(
2091 l.clamp(0.0, 1.0),
2092 c,
2093 h,
2094 a.clamp(0.0, 1.0),
2095 )))
2096 }
2097 BuiltinFunction::AnimationTick => {
2098 Value::Number(i_slint_core::animations::animation_tick() as f64)
2099 }
2100 BuiltinFunction::GetWindowScaleFactor => {
2101 let factor = root_instance(ctx)
2102 .and_then(|inst| inst.window_adapter_or_default())
2103 .map(|adapter| {
2104 i_slint_core::window::WindowInner::from_pub(adapter.window()).scale_factor()
2105 as f64
2106 })
2107 .unwrap_or(1.0);
2108 Value::Number(factor)
2109 }
2110 BuiltinFunction::GetWindowDefaultFontSize => {
2111 let size = root_instance(ctx)
2117 .map(|inst| {
2118 i_slint_core::items::WindowItem::resolved_default_font_size(
2119 vtable::VRc::into_dyn(inst),
2120 )
2121 .get() as f64
2122 })
2123 .unwrap_or(12.0);
2124 Value::Number(size)
2125 }
2126 BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
2127 BuiltinFunction::Use24HourFormat => {
2128 Value::Bool(i_slint_core::date_time::use_24_hour_format())
2129 }
2130 BuiltinFunction::ColorScheme => {
2131 let scheme = root_instance(ctx)
2132 .map(vtable::VRc::into_dyn)
2133 .and_then(|root| {
2134 i_slint_core::window::context_for_root(&root)
2135 .map(|ctx| ctx.color_scheme(Some(&root)))
2136 })
2137 .unwrap_or(i_slint_core::items::ColorScheme::Unknown);
2138 scheme.into()
2139 }
2140 BuiltinFunction::AccentColor => {
2141 let color = root_instance(ctx)
2142 .map(vtable::VRc::into_dyn)
2143 .map(|root| i_slint_core::window::accent_color(&root))
2144 .unwrap_or_default();
2145 Value::Brush(i_slint_core::Brush::SolidColor(color))
2146 }
2147 BuiltinFunction::SupportsNativeMenuBar => {
2148 let supports = find_window_adapter(ctx).is_some_and(|a| {
2149 a.internal(i_slint_core::InternalToken)
2150 .is_some_and(|x| x.supports_native_menu_bar())
2151 });
2152 Value::Bool(supports)
2153 }
2154 BuiltinFunction::TextInputFocused => {
2155 let focused = ctx
2156 .current
2157 .as_ref()
2158 .and_then(|c| c.root.get())
2159 .and_then(|w| w.upgrade())
2160 .and_then(|inst| inst.window_adapter_or_default())
2161 .map(|adapter| {
2162 i_slint_core::window::WindowInner::from_pub(adapter.window())
2163 .text_input_focused()
2164 })
2165 .unwrap_or(false);
2166 Value::Bool(focused)
2167 }
2168 BuiltinFunction::SetTextInputFocused => {
2169 let value = arguments
2170 .first()
2171 .map(|e| eval_expression(ctx, e))
2172 .and_then(|v| bool::try_from(v).ok())
2173 .unwrap_or(false);
2174 if let Some(adapter) = ctx
2175 .current
2176 .as_ref()
2177 .and_then(|c| c.root.get())
2178 .and_then(|w| w.upgrade())
2179 .and_then(|inst| inst.window_adapter_or_default())
2180 {
2181 i_slint_core::window::WindowInner::from_pub(adapter.window())
2182 .set_text_input_focused(value);
2183 }
2184 Value::Void
2185 }
2186 BuiltinFunction::UpdateTimers => {
2187 Value::Void
2190 }
2191 BuiltinFunction::RestartTimer => {
2192 if let [
2197 Expression::PropertyReference(MemberReference::Relative {
2198 parent_level,
2199 local_reference,
2200 }),
2201 ] = arguments
2202 && let LocalMemberIndex::Timer(timer_idx) = &local_reference.reference
2203 && ctx.current.is_some()
2204 {
2205 let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2206 if let Some(timer) = instance.timers.get(usize::from(*timer_idx)) {
2207 timer.restart();
2208 }
2209 }
2210 Value::Void
2211 }
2212 BuiltinFunction::KeysToString => {
2213 let v = arguments.first().map(|e| eval_expression(ctx, e));
2214 if let Some(Value::Keys(keys)) = v {
2215 Value::String(keys.to_string().into())
2216 } else {
2217 Value::String(Default::default())
2218 }
2219 }
2220 BuiltinFunction::SetSelectionOffsets => {
2221 use i_slint_core::items::TextInput;
2223 let [Expression::PropertyReference(mr), start_expr, end_expr] = arguments else {
2224 return Value::Void;
2225 };
2226 let start: i32 = eval_expression(ctx, start_expr).try_into().unwrap_or(0);
2227 let end: i32 = eval_expression(ctx, end_expr).try_into().unwrap_or(0);
2228 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr) else {
2229 return Value::Void;
2230 };
2231 let Some(adapter) = parent_inst.window_adapter_or_default() else {
2232 return Value::Void;
2233 };
2234 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2235 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2236 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_rc.borrow()) {
2237 text_input.set_selection_offsets(&adapter, &item_rc, start, end);
2238 }
2239 Value::Void
2240 }
2241 BuiltinFunction::RegisterCustomFontByPath => {
2242 if let Value::String(s) = eval_expression(ctx, &arguments[0])
2243 && let Some(root) = find_root_instance(ctx)
2244 {
2245 let result =
2248 root.try_window_adapter().map_err(|e| e.to_string()).and_then(|adapter| {
2249 adapter
2250 .renderer()
2251 .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
2252 .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
2253 });
2254 if let Err(err) = result {
2255 i_slint_core::debug_log!("{err}");
2256 }
2257 }
2258 Value::Void
2259 }
2260 BuiltinFunction::SetupMenuBar => crate::popup::setup_menubar(ctx, arguments),
2261 BuiltinFunction::ItemFontMetrics => {
2262 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2263 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2264 && let Some(adapter) = inst.window_adapter_or_default()
2265 {
2266 let item_rc =
2267 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2268 let metrics = i_slint_core::items::slint_text_item_fontmetrics(
2269 &adapter,
2270 item_rc.borrow(),
2271 &item_rc,
2272 );
2273 return metrics.into();
2274 }
2275 i_slint_core::items::FontMetrics::default().into()
2276 }
2277 BuiltinFunction::ItemAbsolutePosition => {
2278 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2279 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2280 {
2281 let item_rc =
2282 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2283 return item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into();
2287 }
2288 i_slint_core::api::LogicalPosition::default().into()
2289 }
2290 BuiltinFunction::PathPointAt => {
2291 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2292 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2293 {
2294 let item_rc =
2295 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2296 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2297 return item_rc
2298 .downcast::<i_slint_core::items::Path>()
2299 .unwrap()
2300 .as_pin_ref()
2301 .point_at(&item_rc, t)
2302 .to_untyped()
2303 .into();
2304 }
2305 panic!("internal error: argument to PathPointAt must be an element")
2306 }
2307 BuiltinFunction::PathAngleAt => {
2308 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2309 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2310 {
2311 let item_rc =
2312 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2313 let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2314 return item_rc
2315 .downcast::<i_slint_core::items::Path>()
2316 .unwrap()
2317 .as_pin_ref()
2318 .angle_at(&item_rc, t)
2319 .into();
2320 }
2321 panic!("internal error: argument to PathAngleAt must be an element")
2322 }
2323 BuiltinFunction::ArrayAny | BuiltinFunction::ArrayAll => {
2324 let is_all = matches!(f, BuiltinFunction::ArrayAll);
2325 let model: i_slint_core::model::ModelRc<Value> =
2326 eval_expression(ctx, &arguments[0]).try_into().unwrap();
2327 let Expression::Closure { arg_name, expression } = &arguments[1] else {
2328 panic!("internal error: Array.any/all expects a closure as second argument")
2329 };
2330 let mut predicate =
2331 |row_value| eval_array_row_predicate(arg_name, expression, ctx, row_value);
2332 Value::Bool(if is_all {
2333 i_slint_core::model::model_all(&model, &mut predicate)
2334 } else {
2335 i_slint_core::model::model_any(&model, &mut predicate)
2336 })
2337 }
2338 BuiltinFunction::ArrayFindIndex => {
2339 let model: i_slint_core::model::ModelRc<Value> =
2340 eval_expression(ctx, &arguments[0]).try_into().unwrap();
2341 let Expression::Closure { arg_name, expression } = &arguments[1] else {
2342 panic!("internal error: Array.find-index expects a closure as second argument")
2343 };
2344 Value::Number(i_slint_core::model::model_find_index(&model, |row_value| {
2345 eval_array_row_predicate(arg_name, expression, ctx, row_value)
2346 }) as f64)
2347 }
2348 BuiltinFunction::ImplicitLayoutInfo(orient) => {
2349 let constraint: f32 = arguments
2353 .get(1)
2354 .map(|e| eval_expression(ctx, e).try_into().unwrap_or(-1.))
2355 .unwrap_or(-1.);
2356 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2357 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2358 && let Some(adapter) = inst.window_adapter_or_default()
2359 {
2360 let item_rc =
2361 i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2362 return item_rc
2363 .borrow()
2364 .as_ref()
2365 .layout_info(
2366 llr_to_core_orientation(orient),
2367 constraint as _,
2368 &adapter,
2369 &item_rc,
2370 )
2371 .into();
2372 }
2373 i_slint_core::layout::LayoutInfo::default().into()
2374 }
2375 BuiltinFunction::Debug => {
2376 use i_slint_core::debug_log::*;
2377 let msg = to_string(ctx, &arguments[0]);
2378 let root = ctx
2379 .current
2380 .as_ref()
2381 .and_then(|c| c.root.get())
2382 .and_then(|w| w.upgrade())
2383 .map(vtable::VRc::into_dyn);
2384 if let Some(context) = root.as_ref().and_then(i_slint_core::window::context_for_root) {
2385 context.dispatch_log_message(LogMessage::new(
2386 LogMessageSource::SlintCode,
2387 None,
2388 format_args!("{msg}"),
2389 ));
2390 } else {
2391 log_message(LogMessage::new(
2392 LogMessageSource::SlintCode,
2393 None,
2394 format_args!("{msg}"),
2395 ));
2396 }
2397 Value::Void
2398 }
2399 BuiltinFunction::ArrayLength => match eval_expression(ctx, &arguments[0]) {
2400 Value::Model(m) => {
2403 m.model_tracker().track_row_count_changes();
2404 Value::Number(m.row_count() as f64)
2405 }
2406 _ => Value::Number(0.),
2407 },
2408 BuiltinFunction::ImageSize => {
2409 if let Value::Image(img) = eval_expression(ctx, &arguments[0]) {
2410 let size = img.size();
2411 let mut s = crate::api::Struct::default();
2412 s.set_field("width".to_string(), Value::Number(size.width as f64));
2413 s.set_field("height".to_string(), Value::Number(size.height as f64));
2414 Value::Struct(s)
2415 } else {
2416 Value::Void
2417 }
2418 }
2419 BuiltinFunction::ParseMarkdown => {
2420 let format_string: SharedString =
2421 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2422 let args = eval_expression(ctx, &arguments[1]);
2423 let args: Vec<i_slint_core::styled_text::StyledText> = if let Value::Model(m) = args {
2424 (0..m.row_count())
2425 .filter_map(|i| match m.row_data(i)? {
2426 Value::StyledText(t) => Some(t),
2427 _ => None,
2428 })
2429 .collect()
2430 } else {
2431 Vec::new()
2432 };
2433 Value::StyledText(i_slint_core::styled_text::parse_markdown(&format_string, &args))
2434 }
2435 BuiltinFunction::StringToStyledText => {
2436 let string: SharedString =
2437 eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2438 Value::StyledText(i_slint_core::styled_text::string_to_styled_text(string.to_string()))
2439 }
2440 BuiltinFunction::Translate => {
2441 let original: SharedString = to_string(ctx, &arguments[0]);
2442 let context: SharedString = to_string(ctx, &arguments[1]);
2443 let domain: SharedString = to_string(ctx, &arguments[2]);
2444 let args = eval_expression(ctx, &arguments[3]);
2445 let Value::Model(args) = args else {
2446 return Value::String(original);
2447 };
2448 struct StringModelWrapper(ModelRc<Value>);
2449 impl i_slint_core::translations::FormatArgs for StringModelWrapper {
2450 type Output<'a> = SharedString;
2451 fn from_index(&self, index: usize) -> Option<SharedString> {
2452 self.0.row_data(index).and_then(|v| v.try_into().ok())
2453 }
2454 }
2455 let n: i32 = eval_expression(ctx, &arguments[4]).try_into().unwrap_or(0);
2456 let plural: SharedString = to_string(ctx, &arguments[5]);
2457 Value::String(i_slint_core::translations::translate(
2458 &original,
2459 &context,
2460 &domain,
2461 &StringModelWrapper(args),
2462 n,
2463 &plural,
2464 ))
2465 }
2466 BuiltinFunction::ShowPopupWindow => crate::popup::show_popup_window(ctx, arguments),
2467 BuiltinFunction::ClosePopupWindow => crate::popup::close_popup_window(ctx, arguments),
2468 BuiltinFunction::SetFocusItem => {
2469 if let Some(Expression::PropertyReference(mr)) = arguments.first()
2470 && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2471 && let Some(adapter) = find_window_adapter(ctx)
2472 {
2473 let dyn_rc = vtable::VRc::into_dyn(inst);
2474 let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2475 i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2476 &item_rc,
2477 true,
2478 i_slint_core::input::FocusReason::Programmatic,
2479 );
2480 }
2481 Value::Void
2482 }
2483 BuiltinFunction::ClearFocusItem => {
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 false,
2493 i_slint_core::input::FocusReason::Programmatic,
2494 );
2495 }
2496 Value::Void
2497 }
2498 BuiltinFunction::MonthDayCount => {
2499 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2500 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2501 Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
2502 }
2503 BuiltinFunction::MonthOffset => {
2504 let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2505 let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2506 Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
2507 }
2508 BuiltinFunction::FormatDate => {
2509 let f: SharedString = to_string(ctx, &arguments[0]);
2510 let d: u32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2511 let m: u32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2512 let y: i32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(0);
2513 Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
2514 }
2515 BuiltinFunction::DateNow => {
2516 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2517 i_slint_core::date_time::date_now()
2518 .into_iter()
2519 .map(|x| Value::Number(x as f64))
2520 .collect::<Vec<_>>(),
2521 )))
2522 }
2523 BuiltinFunction::ValidDate => {
2524 let d: SharedString = to_string(ctx, &arguments[0]);
2525 let f: SharedString = to_string(ctx, &arguments[1]);
2526 Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
2527 }
2528 BuiltinFunction::ParseDate => {
2529 let d: SharedString = to_string(ctx, &arguments[0]);
2530 let f: SharedString = to_string(ctx, &arguments[1]);
2531 Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2532 i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
2533 .map(|v| v.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>())
2534 .unwrap_or_default(),
2535 )))
2536 }
2537 BuiltinFunction::ShowPopupMenu | BuiltinFunction::ShowPopupMenuInternal => {
2538 crate::popup::show_popup_menu(ctx, arguments)
2539 }
2540 BuiltinFunction::OpenUrl => {
2541 let url = to_string(ctx, &arguments[0]);
2542 let result = find_window_adapter(ctx)
2543 .map(|adapter| i_slint_core::open_url(&url, adapter.window()).is_ok())
2544 .unwrap_or(false);
2545 Value::Bool(result)
2546 }
2547 BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
2548 Value::Void
2550 }
2551 BuiltinFunction::StartTimer | BuiltinFunction::StopTimer => {
2552 Value::Void
2554 }
2555 }
2556}
2557
2558pub(crate) fn resolve_item_rc_from_ref(
2562 ctx: &EvalContext,
2563 mr: &MemberReference,
2564) -> Option<(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>, usize)>
2565{
2566 let MemberReference::Relative { parent_level, local_reference } = mr else { return None };
2567 let LocalMemberIndex::Native { item_index, .. } = &local_reference.reference else {
2568 return None;
2569 };
2570 let owner = try_walk_to(ctx, *parent_level, &local_reference.sub_component_path)?;
2571 let parent_inst = owner.root.get().and_then(|w| w.upgrade())?;
2572 let full_path = crate::item_tree_vtable::sub_component_path_of(&owner, &parent_inst);
2573 let flat_idx = find_flat_item_index(&parent_inst.item_table, &full_path, *item_index)?;
2574 Some((parent_inst, flat_idx))
2575}
2576
2577pub(crate) fn find_root_instance(
2581 ctx: &EvalContext,
2582) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
2583 let current = ctx.current.as_ref()?;
2584 let mut sub = current.clone();
2585 loop {
2586 if let Some(root) = sub.root.get()
2587 && let Some(inst) = root.upgrade()
2588 && inst.public_component_index.is_some()
2589 {
2590 return Some(inst);
2591 }
2592 let parent = sub.parent.upgrade()?;
2593 sub = Pin::new(parent);
2594 }
2595}
2596
2597pub(crate) fn find_window_adapter(
2599 ctx: &EvalContext,
2600) -> Option<i_slint_core::window::WindowAdapterRc> {
2601 find_root_instance(ctx)?.window_adapter_or_default()
2602}
2603
2604fn call_item_member_function(ctx: &EvalContext, function: &MemberReference) -> Value {
2608 use i_slint_core::items::{ContextMenu, SwipeGestureHandler, TextInput, WindowItem};
2609 let MemberReference::Relative { local_reference, .. } = function else {
2610 return Value::Void;
2611 };
2612 let LocalMemberIndex::Native { prop_name, .. } = &local_reference.reference else {
2613 return Value::Void;
2614 };
2615 let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, function) else {
2616 return Value::Void;
2617 };
2618 let Some(adapter) = parent_inst.window_adapter_or_default() else { return Value::Void };
2619 let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2620 let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2621 let item_ref = item_rc.borrow();
2622
2623 macro_rules! dispatch {
2626 ($item:expr, $name:expr; $($slint_name:literal => $rust_method:ident $(=> $into:ty)?),* $(,)?) => {
2627 match $name {
2628 $(
2629 $slint_name => {
2630 let res = $item.$rust_method(&adapter, &item_rc);
2631 $(let res: $into = res.into();)?
2632 return res.into();
2633 }
2634 )*
2635 _ => {}
2636 }
2637 };
2638 }
2639
2640 if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_ref) {
2641 dispatch!(text_input, prop_name.as_str();
2642 "select-all" => select_all => (),
2643 "clear-selection" => clear_selection => (),
2644 "select-word" => select_word => (),
2645 "cut" => cut => (),
2646 "copy" => copy => (),
2647 "paste" => paste => (),
2648 "undo" => undo => (),
2649 "redo" => redo => (),
2650 );
2651 }
2652 if let Some(swipe) = vtable::VRef::downcast_pin::<SwipeGestureHandler>(item_rc.borrow()) {
2653 dispatch!(swipe, prop_name.as_str();
2654 "cancel" => cancel => (),
2655 );
2656 }
2657 if let Some(menu) = vtable::VRef::downcast_pin::<ContextMenu>(item_rc.borrow()) {
2658 dispatch!(menu, prop_name.as_str();
2659 "close" => close => (),
2660 "is-open" => is_open,
2661 );
2662 }
2663 if let Some(window) = vtable::VRef::downcast_pin::<WindowItem>(item_rc.borrow()) {
2664 match prop_name.as_str() {
2665 "hide" => {
2666 window.hide(&adapter, &item_rc);
2667 return Value::Void;
2668 }
2669 "close" => return Value::Bool(window.close(&adapter, &item_rc)),
2670 _ => {}
2671 }
2672 }
2673 unimplemented!("ItemMemberFunctionCall `{prop_name}`")
2674}