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