Skip to main content

slint_interpreter/
api.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4// cSpell: ignore theproperty underscoresanddashespreserved xreadonly
5use i_slint_compiler::langtype::Type as LangType;
6use i_slint_core::PathData;
7use i_slint_core::component_factory::ComponentFactory;
8#[cfg(feature = "internal")]
9use i_slint_core::component_factory::FactoryContext;
10use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
11use i_slint_core::items::*;
12use i_slint_core::model::{Model, ModelExt, ModelRc};
13use i_slint_core::styled_text::StyledText;
14#[cfg(feature = "internal")]
15use i_slint_core::window::WindowInner;
16use smol_str::SmolStr;
17use std::collections::HashMap;
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::rc::Rc;
21#[cfg(test)]
22use std::sync::Arc;
23
24#[doc(inline)]
25pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
26
27pub use i_slint_backend_selector::api::*;
28pub use i_slint_core::api::*;
29
30/// Argument of [`Compiler::set_default_translation_context()`]
31///
32pub use i_slint_compiler::DefaultTranslationContext;
33
34/// This enum represents the different public variants of the [`Value`] enum, without
35/// the contained values.
36#[derive(Debug, Copy, Clone, PartialEq)]
37#[repr(i8)]
38#[non_exhaustive]
39pub enum ValueType {
40    /// The variant that expresses the non-type. This is the default.
41    Void,
42    /// An `int` or a `float` (this is also used for unit based type such as `length` or `angle`)
43    Number,
44    /// Correspond to the `string` type in .slint
45    String,
46    /// Correspond to the `bool` type in .slint
47    Bool,
48    /// A model (that includes array in .slint)
49    Model,
50    /// An object
51    Struct,
52    /// Correspond to `brush` or `color` type in .slint.  For color, this is then a [`Brush::SolidColor`]
53    Brush,
54    /// Correspond to `image` type in .slint.
55    Image,
56    /// The type is not a public type but something internal.
57    #[doc(hidden)]
58    Other = -1,
59}
60
61impl From<LangType> for ValueType {
62    fn from(ty: LangType) -> Self {
63        match ty {
64            LangType::Float32
65            | LangType::Int32
66            | LangType::Duration
67            | LangType::Angle
68            | LangType::PhysicalLength
69            | LangType::LogicalLength
70            | LangType::Percent
71            | LangType::UnitProduct(_) => Self::Number,
72            LangType::String => Self::String,
73            LangType::Color => Self::Brush,
74            LangType::Brush => Self::Brush,
75            LangType::Array(_) => Self::Model,
76            LangType::Bool => Self::Bool,
77            LangType::Struct { .. } => Self::Struct,
78            LangType::Void => Self::Void,
79            LangType::Image => Self::Image,
80            _ => Self::Other,
81        }
82    }
83}
84
85/// This is a dynamically typed value used in the Slint interpreter.
86/// It can hold a value of different types, and you should use the
87/// [`From`] or [`TryFrom`] traits to access the value.
88///
89/// ```
90/// # use slint_interpreter::*;
91/// use core::convert::TryInto;
92/// // create a value containing an integer
93/// let v = Value::from(100u32);
94/// assert_eq!(v.try_into(), Ok(100u32));
95/// ```
96#[derive(Clone, Default)]
97#[non_exhaustive]
98#[repr(u8)]
99pub enum Value {
100    /// There is nothing in this value. That's the default.
101    /// For example, a function that does not return a result would return a Value::Void
102    #[default]
103    Void = 0,
104    /// An `int` or a `float` (this is also used for unit based type such as `length` or `angle`)
105    Number(f64) = 1,
106    /// Correspond to the `string` type in .slint
107    String(SharedString) = 2,
108    /// Correspond to the `bool` type in .slint
109    Bool(bool) = 3,
110    /// Correspond to the `image` type in .slint
111    Image(Image) = 4,
112    /// A model (that includes array in .slint)
113    Model(ModelRc<Value>) = 5,
114    /// An object
115    Struct(Struct) = 6,
116    /// Correspond to `brush` or `color` type in .slint.  For color, this is then a [`Brush::SolidColor`]
117    Brush(Brush) = 7,
118    #[doc(hidden)]
119    /// The elements of a path
120    PathData(PathData) = 8,
121    #[doc(hidden)]
122    /// An easing curve
123    EasingCurve(i_slint_core::animations::EasingCurve) = 9,
124    #[doc(hidden)]
125    /// An enumeration, like `TextHorizontalAlignment::align_center`, represented by `("TextHorizontalAlignment", "align_center")`.
126    /// FIXME: consider representing that with a number?
127    EnumerationValue(String, String) = 10,
128    #[doc(hidden)]
129    LayoutCache(SharedVector<f32>) = 11,
130    #[doc(hidden)]
131    /// Correspond to the `component-factory` type in .slint
132    ComponentFactory(ComponentFactory) = 12,
133    #[doc(hidden)] // make visible when we make StyledText public
134    /// Correspond to the `styled-text` type in .slint
135    StyledText(StyledText) = 13,
136    #[doc(hidden)]
137    ArrayOfU16(SharedVector<u16>) = 14,
138    /// Correspond to the `keys` type in .slint
139    Keys(Keys) = 15,
140    /// Correspond to the `data-transfer` type in .slint
141    DataTransfer(DataTransfer) = 16,
142    #[doc(hidden)]
143    /// A mouse cursor.
144    MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
145}
146
147impl Value {
148    /// Returns the type variant that this value holds without the containing value.
149    pub fn value_type(&self) -> ValueType {
150        match self {
151            Value::Void => ValueType::Void,
152            Value::Number(_) => ValueType::Number,
153            Value::String(_) => ValueType::String,
154            Value::Bool(_) => ValueType::Bool,
155            Value::Model(_) => ValueType::Model,
156            Value::Struct(_) => ValueType::Struct,
157            Value::Brush(_) => ValueType::Brush,
158            Value::Image(_) => ValueType::Image,
159            _ => ValueType::Other,
160        }
161    }
162}
163
164impl i_slint_core::rtti::ValueType for Value {}
165
166impl PartialEq for Value {
167    fn eq(&self, other: &Self) -> bool {
168        match self {
169            Value::Void => matches!(other, Value::Void),
170            Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
171            Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
172            Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
173            Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
174            Value::Model(lhs) => {
175                if let Value::Model(rhs) = other {
176                    lhs == rhs
177                } else {
178                    false
179                }
180            }
181            Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
182            Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
183            Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
184            Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
185            Value::EnumerationValue(lhs_name, lhs_value) => {
186                matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
187            }
188            Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
189            Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
190            Value::ComponentFactory(lhs) => {
191                matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
192            }
193            Value::StyledText(lhs) => {
194                matches!(other, Value::StyledText(rhs) if lhs == rhs)
195            }
196            Value::Keys(lhs) => {
197                matches!(other, Value::Keys(rhs) if lhs == rhs)
198            }
199            Value::DataTransfer(lhs) => {
200                matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
201            }
202            Value::MouseCursorInner(lhs) => {
203                matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
204            }
205        }
206    }
207}
208
209impl std::fmt::Debug for Value {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        match self {
212            Value::Void => write!(f, "Value::Void"),
213            Value::Number(n) => write!(f, "Value::Number({n:?})"),
214            Value::String(s) => write!(f, "Value::String({s:?})"),
215            Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
216            Value::Image(i) => write!(f, "Value::Image({i:?})"),
217            Value::Model(m) => {
218                write!(f, "Value::Model(")?;
219                f.debug_list().entries(m.iter()).finish()?;
220                write!(f, "])")
221            }
222            Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
223            Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
224            Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
225            Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
226            Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
227            Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
228            Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
229            Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
230            Value::ArrayOfU16(data) => {
231                write!(f, "Value::ArrayOfU16({data:?})")
232            }
233            Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
234            Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
235            Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
236        }
237    }
238}
239
240/// Helper macro to implement the From / TryFrom for Value
241///
242/// For example
243/// `declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64] );`
244/// means that `Value::Number` can be converted to / from each of the said rust types
245///
246/// For `Value::Object` mapping to a rust `struct`, one can use [`declare_value_struct_conversion!`]
247/// And for `Value::EnumerationValue` which maps to a rust `enum`, one can use [`declare_value_enum_conversion!`]
248macro_rules! declare_value_conversion {
249    ( $value:ident => [$($ty:ty),*] ) => {
250        $(
251            impl From<$ty> for Value {
252                fn from(v: $ty) -> Self {
253                    Value::$value(v as _)
254                }
255            }
256            impl TryFrom<Value> for $ty {
257                type Error = Value;
258                fn try_from(v: Value) -> Result<$ty, Self::Error> {
259                    match v {
260                        Value::$value(x) => Ok(x as _),
261                        _ => Err(v)
262                    }
263                }
264            }
265        )*
266    };
267}
268declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
269declare_value_conversion!(String => [SharedString] );
270declare_value_conversion!(Bool => [bool] );
271declare_value_conversion!(Image => [Image] );
272declare_value_conversion!(Struct => [Struct] );
273declare_value_conversion!(Brush => [Brush] );
274declare_value_conversion!(PathData => [PathData]);
275declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
276declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
277declare_value_conversion!(ComponentFactory => [ComponentFactory] );
278declare_value_conversion!(StyledText => [StyledText] );
279declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
280declare_value_conversion!(Keys => [Keys]);
281declare_value_conversion!(DataTransfer => [DataTransfer]);
282declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
283
284/// Implement From / TryFrom for Value that convert a `struct` to/from `Value::Struct`
285macro_rules! declare_value_struct_conversion {
286    (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
287        impl From<$name> for Value {
288            fn from($name { $($field),* , .. }: $name) -> Self {
289                let mut struct_ = Struct::default();
290                $(struct_.set_field(stringify!($field).into(), $field.into());)*
291                Value::Struct(struct_)
292            }
293        }
294        impl TryFrom<Value> for $name {
295            type Error = ();
296            fn try_from(v: Value) -> Result<$name, Self::Error> {
297                #[allow(clippy::field_reassign_with_default)]
298                match v {
299                    Value::Struct(x) => {
300                        type Ty = $name;
301                        #[allow(unused)]
302                        let mut res: Ty = Ty::default();
303                        $(let mut res: Ty = $extra;)?
304                        $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
305                        Ok(res)
306                    }
307                    _ => Err(()),
308                }
309            }
310        }
311    };
312    ($(
313        $(#[$struct_attr:meta])*
314        $vis:vis struct $Name:ident {
315            $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
316        }
317    )*) => {
318        $(
319            impl From<$Name> for Value {
320                fn from(item: $Name) -> Self {
321                    let mut struct_ = Struct::default();
322                    $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
323                    Value::Struct(struct_)
324                }
325            }
326            impl TryFrom<Value> for $Name {
327                type Error = ();
328                fn try_from(v: Value) -> Result<$Name, Self::Error> {
329                    #[allow(clippy::field_reassign_with_default)]
330                    match v {
331                        Value::Struct(x) => {
332                            type Ty = $Name;
333                            #[allow(unused)]
334                            let mut res: Ty = Ty::default();
335                            // Every field is required and overwritten, so declared field
336                            // defaults do not apply to this conversion
337                            $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
338                            Ok(res)
339                        }
340                        _ => Err(()),
341                    }
342                }
343            }
344        )*
345    };
346}
347
348declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
349declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
350declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
351declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
352declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
353
354i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
355
356/// Implement From / TryFrom for Value that convert an `enum` to/from `Value::EnumerationValue`
357///
358/// The `enum` must derive `Display` and `FromStr`
359/// (can be done with `strum_macros::EnumString`, `strum_macros::Display` derive macro)
360macro_rules! declare_value_enum_conversion {
361    ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
362        impl From<i_slint_core::items::$Name> for Value {
363            fn from(v: i_slint_core::items::$Name) -> Self {
364                Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
365            }
366        }
367        impl TryFrom<Value> for i_slint_core::items::$Name {
368            type Error = ();
369            fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
370                use std::str::FromStr;
371                match v {
372                    Value::EnumerationValue(enumeration, value) => {
373                        if enumeration != stringify!($Name) {
374                            return Err(());
375                        }
376                        i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
377                    }
378                    _ => Err(()),
379                }
380            }
381        }
382    )*};
383}
384
385i_slint_common::for_each_enums!(declare_value_enum_conversion);
386
387impl From<i_slint_core::animations::Instant> for Value {
388    fn from(value: i_slint_core::animations::Instant) -> Self {
389        Value::Number(value.0 as _)
390    }
391}
392impl TryFrom<Value> for i_slint_core::animations::Instant {
393    type Error = ();
394    fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
395        match v {
396            Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
397            _ => Err(()),
398        }
399    }
400}
401
402impl From<()> for Value {
403    #[inline]
404    fn from(_: ()) -> Self {
405        Value::Void
406    }
407}
408impl TryFrom<Value> for () {
409    type Error = ();
410    #[inline]
411    fn try_from(_: Value) -> Result<(), Self::Error> {
412        Ok(())
413    }
414}
415
416impl From<Color> for Value {
417    #[inline]
418    fn from(c: Color) -> Self {
419        Value::Brush(Brush::SolidColor(c))
420    }
421}
422impl TryFrom<Value> for Color {
423    type Error = Value;
424    #[inline]
425    fn try_from(v: Value) -> Result<Color, Self::Error> {
426        match v {
427            Value::Brush(Brush::SolidColor(c)) => Ok(c),
428            _ => Err(v),
429        }
430    }
431}
432
433impl From<i_slint_core::lengths::LogicalLength> for Value {
434    #[inline]
435    fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
436        Value::Number(l.get() as _)
437    }
438}
439impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
440    type Error = Value;
441    #[inline]
442    fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
443        match v {
444            Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
445            _ => Err(v),
446        }
447    }
448}
449
450impl From<i_slint_core::lengths::LogicalPoint> for Value {
451    #[inline]
452    fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
453        Value::Struct(Struct::from_iter([
454            ("x".to_owned(), Value::Number(pt.x as _)),
455            ("y".to_owned(), Value::Number(pt.y as _)),
456        ]))
457    }
458}
459impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
460    type Error = Value;
461    #[inline]
462    fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
463        match v {
464            Value::Struct(s) => {
465                let x = s
466                    .get_field("x")
467                    .cloned()
468                    .unwrap_or_else(|| Value::Number(0 as _))
469                    .try_into()?;
470                let y = s
471                    .get_field("y")
472                    .cloned()
473                    .unwrap_or_else(|| Value::Number(0 as _))
474                    .try_into()?;
475                Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
476            }
477            _ => Err(v),
478        }
479    }
480}
481
482impl From<i_slint_core::lengths::LogicalSize> for Value {
483    #[inline]
484    fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
485        Value::Struct(Struct::from_iter([
486            ("width".to_owned(), Value::Number(s.width as _)),
487            ("height".to_owned(), Value::Number(s.height as _)),
488        ]))
489    }
490}
491impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
492    type Error = Value;
493    #[inline]
494    fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
495        match v {
496            Value::Struct(s) => {
497                let width = s
498                    .get_field("width")
499                    .cloned()
500                    .unwrap_or_else(|| Value::Number(0 as _))
501                    .try_into()?;
502                let height = s
503                    .get_field("height")
504                    .cloned()
505                    .unwrap_or_else(|| Value::Number(0 as _))
506                    .try_into()?;
507                Ok(i_slint_core::lengths::LogicalSize::new(width, height))
508            }
509            _ => Err(v),
510        }
511    }
512}
513
514impl From<i_slint_core::lengths::LogicalEdges> for Value {
515    #[inline]
516    fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
517        Value::Struct(Struct::from_iter([
518            ("left".to_owned(), Value::Number(s.left as _)),
519            ("right".to_owned(), Value::Number(s.right as _)),
520            ("top".to_owned(), Value::Number(s.top as _)),
521            ("bottom".to_owned(), Value::Number(s.bottom as _)),
522        ]))
523    }
524}
525impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
526    type Error = Value;
527    #[inline]
528    fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
529        match v {
530            Value::Struct(s) => {
531                let left = s
532                    .get_field("left")
533                    .cloned()
534                    .unwrap_or_else(|| Value::Number(0 as _))
535                    .try_into()?;
536                let right = s
537                    .get_field("right")
538                    .cloned()
539                    .unwrap_or_else(|| Value::Number(0 as _))
540                    .try_into()?;
541                let top = s
542                    .get_field("top")
543                    .cloned()
544                    .unwrap_or_else(|| Value::Number(0 as _))
545                    .try_into()?;
546                let bottom = s
547                    .get_field("bottom")
548                    .cloned()
549                    .unwrap_or_else(|| Value::Number(0 as _))
550                    .try_into()?;
551                Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
552            }
553            _ => Err(v),
554        }
555    }
556}
557
558impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
559    fn from(m: ModelRc<T>) -> Self {
560        if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
561            Value::Model(v.clone())
562        } else {
563            Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
564        }
565    }
566}
567impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
568    type Error = Value;
569    #[inline]
570    fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
571        match v {
572            Value::Model(m) => {
573                if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
574                    Ok(v.clone())
575                } else if let Some(v) =
576                    m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
577                {
578                    Ok(v.0.clone())
579                } else {
580                    Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
581                }
582            }
583            _ => Err(v),
584        }
585    }
586}
587
588#[test]
589fn value_model_conversion() {
590    use i_slint_core::model::*;
591    let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
592    let v = Value::from(m.clone());
593    assert_eq!(v, Value::Model(m.clone()));
594    let m2: ModelRc<Value> = v.clone().try_into().unwrap();
595    assert_eq!(m2, m);
596
597    let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
598    assert_eq!(int_model.row_count(), 2);
599    assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
600
601    let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
602    assert_eq!(m3.row_count(), 2);
603    assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
604
605    let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
606    assert_eq!(str_model.row_count(), 2);
607    // Value::Int doesn't convert to string, but since the mapping can't report error, we get the default constructed string
608    assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
609
610    let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
611    assert!(err.is_err());
612
613    let model =
614        Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
615
616    let value: Value = ModelRc::from(model.clone()).into();
617    let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
618    assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
619    value_model.set_row_data(1, Value::String("qux".into()));
620    value_model.set_row_data(0, Value::Bool(true));
621    assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
622    // This is backed by a string model, so changing to bool has no effect
623    assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
624
625    // The original values are changed
626    assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
627    assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
628
629    let the_model: ModelRc<SharedString> = value.try_into().unwrap();
630    assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
631    assert_eq!(
632        model.as_ref() as *const VecModel<SharedString>,
633        the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
634            as *const VecModel<SharedString>
635    );
636}
637
638pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
639    i_slint_compiler::parser::normalize_identifier(ident)
640}
641
642/// This type represents a runtime instance of structure in `.slint`.
643///
644/// This can either be an instance of a name structure introduced
645/// with the `struct` keyword in the .slint file, or an anonymous struct
646/// written with the `{ key: value, }`  notation.
647///
648/// It can be constructed with the [`FromIterator`] trait, and converted
649/// into or from a [`Value`] with the [`From`], [`TryFrom`] trait
650///
651///
652/// ```
653/// # use slint_interpreter::*;
654/// use core::convert::TryInto;
655/// // Construct a value from a key/value iterator
656/// let value : Value = [("foo".into(), 45u32.into()), ("bar".into(), true.into())]
657///     .iter().cloned().collect::<Struct>().into();
658///
659/// // get the properties of a `{ foo: 45, bar: true }`
660/// let s : Struct = value.try_into().unwrap();
661/// assert_eq!(s.get_field("foo").cloned().unwrap().try_into(), Ok(45u32));
662/// ```
663#[derive(Clone, PartialEq, Debug, Default)]
664pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
665impl Struct {
666    /// Get the value for a given struct field
667    pub fn get_field(&self, name: &str) -> Option<&Value> {
668        if i_slint_compiler::parser::is_identifier_normalized(name) {
669            self.0.get(name)
670        } else {
671            self.0.get(&*normalize_identifier(name))
672        }
673    }
674    /// Set the value of a given struct field
675    pub fn set_field(&mut self, name: String, value: Value) {
676        self.0.insert(normalize_identifier(&name), value);
677    }
678
679    /// Iterate over all the fields in this struct
680    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
681        self.0.iter().map(|(a, b)| (a.as_str(), b))
682    }
683}
684
685impl FromIterator<(String, Value)> for Struct {
686    fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
687        Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
688    }
689}
690
691#[test]
692fn struct_field_name_normalization() {
693    let mut s = Struct::default();
694    s.set_field("foo_bar".into(), Value::Number(1.));
695    // A real field name longer than SmolStr's 23-byte inline limit (25 bytes)
696    s.set_field("cross-axis-self-alignment".into(), Value::Number(2.));
697    assert_eq!(s.get_field("foo-bar"), Some(&Value::Number(1.)));
698    assert_eq!(s.get_field("foo_bar"), Some(&Value::Number(1.)));
699    assert_eq!(s.get_field("cross-axis-self-alignment"), Some(&Value::Number(2.)));
700    assert_eq!(s.get_field("cross_axis_self_alignment"), Some(&Value::Number(2.)));
701}
702
703/// ComponentCompiler is deprecated, use [`Compiler`] instead
704#[deprecated(note = "Use slint_interpreter::Compiler instead")]
705pub struct ComponentCompiler {
706    config: i_slint_compiler::CompilerConfiguration,
707    diagnostics: Vec<Diagnostic>,
708}
709
710#[allow(deprecated)]
711impl Default for ComponentCompiler {
712    fn default() -> Self {
713        let mut config = i_slint_compiler::CompilerConfiguration::new(
714            i_slint_compiler::generator::OutputFormat::Interpreter,
715        );
716        config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
717        Self { config, diagnostics: Vec::new() }
718    }
719}
720
721#[allow(deprecated)]
722impl ComponentCompiler {
723    /// Returns a new ComponentCompiler.
724    pub fn new() -> Self {
725        Self::default()
726    }
727
728    /// Allow access to the underlying `CompilerConfiguration`
729    ///
730    /// This is an internal function without and ABI or API stability guarantees.
731    #[doc(hidden)]
732    #[cfg(feature = "internal")]
733    pub fn compiler_configuration(
734        &mut self,
735        _: i_slint_core::InternalToken,
736    ) -> &mut i_slint_compiler::CompilerConfiguration {
737        &mut self.config
738    }
739
740    /// Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
741    pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
742        self.config.include_paths = include_paths;
743    }
744
745    /// Returns the include paths the component compiler is currently configured with.
746    pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
747        &self.config.include_paths
748    }
749
750    /// Sets the library paths used for looking up `@library` imports to the specified map of library names to paths.
751    pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
752        self.config.library_paths = library_paths;
753    }
754
755    /// Returns the library paths the component compiler is currently configured with.
756    pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
757        &self.config.library_paths
758    }
759
760    /// Sets the style to be used for widgets.
761    ///
762    /// Use the "material" style as widget style when compiling:
763    /// ```rust
764    /// use slint_interpreter::{ComponentDefinition, ComponentCompiler, ComponentHandle};
765    ///
766    /// let mut compiler = ComponentCompiler::default();
767    /// compiler.set_style("material".into());
768    /// let definition =
769    ///     spin_on::spin_on(compiler.build_from_path("hello.slint"));
770    /// ```
771    pub fn set_style(&mut self, style: String) {
772        self.config.style = Some(style);
773    }
774
775    /// Returns the widget style the compiler is currently using when compiling .slint files.
776    pub fn style(&self) -> Option<&String> {
777        self.config.style.as_ref()
778    }
779
780    /// The domain used for translations
781    pub fn set_translation_domain(&mut self, domain: String) {
782        self.config.translation_domain = Some(domain);
783    }
784
785    /// Sets the callback that will be invoked when loading imported .slint files. The specified
786    /// `file_loader_callback` parameter will be called with a canonical file path as argument
787    /// and is expected to return a future that, when resolved, provides the source code of the
788    /// .slint file to be imported as a string.
789    /// If an error is returned, then the build will abort with that error.
790    /// If None is returned, it means the normal resolution algorithm will proceed as if the hook
791    /// was not in place (i.e: load from the file system following the include paths)
792    pub fn set_file_loader(
793        &mut self,
794        file_loader_fallback: impl Fn(
795            &Path,
796        ) -> core::pin::Pin<
797            Box<dyn Future<Output = Option<std::io::Result<String>>>>,
798        > + 'static,
799    ) {
800        self.config.open_import_callback =
801            Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
802    }
803
804    /// Returns the diagnostics that were produced in the last call to [`Self::build_from_path`] or [`Self::build_from_source`].
805    pub fn diagnostics(&self) -> &Vec<Diagnostic> {
806        &self.diagnostics
807    }
808
809    /// Compile a .slint file into a ComponentDefinition
810    ///
811    /// Returns the compiled `ComponentDefinition` if there were no errors.
812    ///
813    /// Any diagnostics produced during the compilation, such as warnings or errors, are collected
814    /// in this ComponentCompiler and can be retrieved after the call using the [`Self::diagnostics()`]
815    /// function. The [`print_diagnostics`] function can be used to display the diagnostics
816    /// to the users.
817    ///
818    /// Diagnostics from previous calls are cleared when calling this function.
819    ///
820    /// If the path is `"-"`, the file will be read from stdin.
821    /// If the extension of the file .rs, the first `slint!` macro from a rust file will be extracted
822    ///
823    /// This function is `async` but in practice, this is only asynchronous if
824    /// [`Self::set_file_loader`] was called and its future is actually asynchronous.
825    /// If that is not used, then it is fine to use a very simple executor, such as the one
826    /// provided by the `spin_on` crate
827    pub async fn build_from_path<P: AsRef<Path>>(
828        &mut self,
829        path: P,
830    ) -> Option<ComponentDefinition> {
831        let path = path.as_ref();
832        let source = match i_slint_compiler::diagnostics::load_from_path(path) {
833            Ok(s) => s,
834            Err(d) => {
835                self.diagnostics = vec![d];
836                return None;
837            }
838        };
839
840        let r = build_compilation_result(source, path.into(), self.config.clone()).await;
841        self.diagnostics = r.diagnostics.into_iter().collect();
842        r.components.into_values().next()
843    }
844
845    /// Compile some .slint code into a ComponentDefinition
846    ///
847    /// The `path` argument will be used for diagnostics and to compute relative
848    /// paths while importing.
849    ///
850    /// Any diagnostics produced during the compilation, such as warnings or errors, are collected
851    /// in this ComponentCompiler and can be retrieved after the call using the [`Self::diagnostics()`]
852    /// function. The [`print_diagnostics`] function can be used to display the diagnostics
853    /// to the users.
854    ///
855    /// Diagnostics from previous calls are cleared when calling this function.
856    ///
857    /// This function is `async` but in practice, this is only asynchronous if
858    /// [`Self::set_file_loader`] is set and its future is actually asynchronous.
859    /// If that is not used, then it is fine to use a very simple executor, such as the one
860    /// provided by the `spin_on` crate
861    pub async fn build_from_source(
862        &mut self,
863        source_code: String,
864        path: PathBuf,
865    ) -> Option<ComponentDefinition> {
866        let r = build_compilation_result(source_code, path, self.config.clone()).await;
867        self.diagnostics = r.diagnostics.into_iter().collect();
868        r.components.into_values().next()
869    }
870}
871
872/// This is the entry point of the crate, it can be used to load a `.slint` file and
873/// compile it into a [`CompilationResult`].
874pub struct Compiler {
875    config: i_slint_compiler::CompilerConfiguration,
876}
877
878impl Default for Compiler {
879    fn default() -> Self {
880        let config = i_slint_compiler::CompilerConfiguration::new(
881            i_slint_compiler::generator::OutputFormat::Interpreter,
882        );
883        Self { config }
884    }
885}
886
887impl Compiler {
888    /// Returns a new Compiler.
889    pub fn new() -> Self {
890        Self::default()
891    }
892
893    #[doc(hidden)]
894    #[cfg(feature = "internal")]
895    pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
896        self.config.embed_resources = embed_resources;
897    }
898
899    /// Allow access to the underlying `CompilerConfiguration`
900    ///
901    /// This is an internal function without and ABI or API stability guarantees.
902    #[doc(hidden)]
903    #[cfg(feature = "internal")]
904    pub fn compiler_configuration(
905        &mut self,
906        _: i_slint_core::InternalToken,
907    ) -> &mut i_slint_compiler::CompilerConfiguration {
908        &mut self.config
909    }
910
911    /// Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
912    pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
913        self.config.include_paths = include_paths;
914    }
915
916    /// Returns the include paths the component compiler is currently configured with.
917    pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
918        &self.config.include_paths
919    }
920
921    /// Sets the library paths used for looking up `@library` imports to the specified map of library names to paths.
922    pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
923        self.config.library_paths = library_paths;
924    }
925
926    /// Returns the library paths the component compiler is currently configured with.
927    pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
928        &self.config.library_paths
929    }
930
931    /// Sets the style to be used for widgets.
932    ///
933    /// Use the "material" style as widget style when compiling:
934    /// ```rust
935    /// use slint_interpreter::{ComponentDefinition, Compiler, ComponentHandle};
936    ///
937    /// let mut compiler = Compiler::default();
938    /// compiler.set_style("material".into());
939    /// let result = spin_on::spin_on(compiler.build_from_path("hello.slint"));
940    /// ```
941    pub fn set_style(&mut self, style: String) {
942        self.config.style = Some(style);
943    }
944
945    /// Returns the widget style the compiler is currently using when compiling .slint files.
946    pub fn style(&self) -> Option<&String> {
947        self.config.style.as_ref()
948    }
949
950    /// The domain used for translations
951    pub fn set_translation_domain(&mut self, domain: String) {
952        self.config.translation_domain = Some(domain);
953    }
954
955    /// Unless explicitly specified with the `@tr("context" => ...)`, the default translation context is the component name.
956    /// Use this option with [`DefaultTranslationContext::None`] to disable the default translation context.
957    ///
958    /// The translation file must also not have context
959    /// (`--no-default-translation-context` argument of `slint-tr-extractor`)
960    pub fn set_default_translation_context(
961        &mut self,
962        default_translation_context: DefaultTranslationContext,
963    ) {
964        self.config.default_translation_context = default_translation_context;
965    }
966
967    /// Sets the callback that will be invoked when loading imported .slint files. The specified
968    /// `file_loader_callback` parameter will be called with a canonical file path as argument
969    /// and is expected to return a future that, when resolved, provides the source code of the
970    /// .slint file to be imported as a string.
971    /// If an error is returned, then the build will abort with that error.
972    /// If None is returned, it means the normal resolution algorithm will proceed as if the hook
973    /// was not in place (i.e: load from the file system following the include paths)
974    pub fn set_file_loader(
975        &mut self,
976        file_loader_fallback: impl Fn(
977            &Path,
978        ) -> core::pin::Pin<
979            Box<dyn Future<Output = Option<std::io::Result<String>>>>,
980        > + 'static,
981    ) {
982        self.config.open_import_callback =
983            Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
984    }
985
986    /// Compile a .slint file
987    ///
988    /// Returns a structure that holds the diagnostics and the compiled components.
989    ///
990    /// Any diagnostics produced during the compilation, such as warnings or errors, can be retrieved
991    /// after the call using [`CompilationResult::diagnostics()`].
992    ///
993    /// If the file was compiled without error, the list of component names can be obtained with
994    /// [`CompilationResult::component_names`], and the compiled components themselves with
995    /// [`CompilationResult::component()`].
996    ///
997    /// If the path is `"-"`, the file will be read from stdin.
998    /// If the extension of the file .rs, the first `slint!` macro from a rust file will be extracted
999    ///
1000    /// This function is `async` but in practice, this is only asynchronous if
1001    /// [`Self::set_file_loader`] was called and its future is actually asynchronous.
1002    /// If that is not used, then it is fine to use a very simple executor, such as the one
1003    /// provided by the `spin_on` crate
1004    pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
1005        let path = path.as_ref();
1006        let source = match i_slint_compiler::diagnostics::load_from_path(path) {
1007            Ok(s) => s,
1008            Err(d) => {
1009                let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1010                diagnostics.push_compiler_error(d);
1011                return CompilationResult {
1012                    components: HashMap::new(),
1013                    diagnostics: diagnostics.into_iter().collect(),
1014                    #[cfg(feature = "internal")]
1015                    watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
1016                    #[cfg(feature = "internal")]
1017                    structs_and_enums: Vec::new(),
1018                };
1019            }
1020        };
1021
1022        build_compilation_result(source, path.into(), self.config.clone()).await
1023    }
1024
1025    /// Compile some .slint code
1026    ///
1027    /// The `path` argument will be used for diagnostics and to compute relative
1028    /// paths while importing.
1029    ///
1030    /// Any diagnostics produced during the compilation, such as warnings or errors, can be retrieved
1031    /// after the call using [`CompilationResult::diagnostics()`].
1032    ///
1033    /// This function is `async` but in practice, this is only asynchronous if
1034    /// [`Self::set_file_loader`] is set and its future is actually asynchronous.
1035    /// If that is not used, then it is fine to use a very simple executor, such as the one
1036    /// provided by the `spin_on` crate
1037    pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1038        build_compilation_result(source_code, path, self.config.clone()).await
1039    }
1040}
1041
1042async fn build_compilation_result(
1043    source_code: String,
1044    path: PathBuf,
1045    config: i_slint_compiler::CompilerConfiguration,
1046) -> CompilationResult {
1047    let result = crate::component::build_from_source(source_code, path, config).await;
1048    let components = result
1049        .components
1050        .into_iter()
1051        .map(|(name, def)| (name, ComponentDefinition { inner: std::rc::Rc::new(def) }))
1052        .collect::<HashMap<String, ComponentDefinition>>();
1053    CompilationResult {
1054        components,
1055        diagnostics: result.diagnostics,
1056        #[cfg(feature = "internal")]
1057        watch_paths: result.watch_paths,
1058        #[cfg(feature = "internal")]
1059        structs_and_enums: result.structs_and_enums,
1060    }
1061}
1062
1063/// The result of a compilation
1064///
1065/// If [`Self::has_errors()`] is true, then the compilation failed.
1066/// The [`Self::diagnostics()`] function can be used to retrieve the diagnostics (errors and/or warnings)
1067/// or [`Self::print_diagnostics()`] can be used to print them to stderr.
1068/// The components can be retrieved using [`Self::components()`]
1069#[derive(Clone)]
1070pub struct CompilationResult {
1071    pub(crate) components: HashMap<String, ComponentDefinition>,
1072    pub(crate) diagnostics: Vec<Diagnostic>,
1073    #[cfg(feature = "internal")]
1074    pub(crate) watch_paths: Vec<PathBuf>,
1075    #[cfg(feature = "internal")]
1076    pub(crate) structs_and_enums: Vec<LangType>,
1077}
1078
1079impl core::fmt::Debug for CompilationResult {
1080    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1081        f.debug_struct("CompilationResult")
1082            .field("components", &self.components.keys())
1083            .field("diagnostics", &self.diagnostics)
1084            .finish()
1085    }
1086}
1087
1088impl CompilationResult {
1089    /// Returns true if the compilation failed.
1090    /// The errors can be retrieved using the [`Self::diagnostics()`] function.
1091    pub fn has_errors(&self) -> bool {
1092        self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1093    }
1094
1095    /// Return an iterator over the diagnostics.
1096    ///
1097    /// You can also call [`Self::print_diagnostics()`] to output the diagnostics to stderr
1098    pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1099        self.diagnostics.iter().cloned()
1100    }
1101
1102    /// Print the diagnostics to stderr
1103    ///
1104    /// The diagnostics are printed in the same style as rustc errors
1105    ///
1106    /// This function is available when the `display-diagnostics` is enabled.
1107    #[cfg(feature = "display-diagnostics")]
1108    pub fn print_diagnostics(&self) {
1109        print_diagnostics(&self.diagnostics)
1110    }
1111
1112    /// Returns an iterator over the compiled components.
1113    pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1114        self.components.values().cloned()
1115    }
1116
1117    /// Returns the names of the components that were compiled.
1118    pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1119        self.components.keys().map(|s| s.as_str())
1120    }
1121
1122    /// Return the component definition for the given name.
1123    /// If the component does not exist, then `None` is returned.
1124    pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1125        self.components.get(name).cloned()
1126    }
1127
1128    /// This is an internal function without API stability guarantees.
1129    #[doc(hidden)]
1130    #[cfg(feature = "internal")]
1131    pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1132        &self.watch_paths
1133    }
1134
1135    /// This is an internal function without API stability guarantees.
1136    #[doc(hidden)]
1137    #[cfg(feature = "internal")]
1138    pub fn structs_and_enums(
1139        &self,
1140        _: i_slint_core::InternalToken,
1141    ) -> impl Iterator<Item = &LangType> {
1142        self.structs_and_enums.iter()
1143    }
1144
1145    /// This is an internal function without API stability guarantees.
1146    /// The lowered compilation unit, or `None` when the compilation failed.
1147    #[doc(hidden)]
1148    #[cfg(feature = "internal")]
1149    pub fn compilation_unit(
1150        &self,
1151        _: i_slint_core::InternalToken,
1152    ) -> Option<&i_slint_compiler::llr::CompilationUnit> {
1153        self.components.values().next().map(|d| &*d.inner.compilation_unit)
1154    }
1155}
1156
1157/// ComponentDefinition is a representation of a compiled component from .slint markup.
1158///
1159/// It can be constructed from a .slint file using the [`Compiler::build_from_path`] or [`Compiler::build_from_source`] functions.
1160/// And then it can be instantiated with the [`Self::create`] function.
1161///
1162/// The ComponentDefinition acts as a factory to create new instances. When you've finished
1163/// creating the instances it is safe to drop the ComponentDefinition.
1164#[derive(Clone)]
1165pub struct ComponentDefinition {
1166    pub(crate) inner: std::rc::Rc<crate::component::ComponentDefinitionInner>,
1167}
1168
1169impl ComponentDefinition {
1170    /// Creates a new instance of the component and returns a shared handle to it.
1171    pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1172        let instance = self.create_with_options(Default::default())?;
1173        // SystemTrayIcon-rooted components don't have a real WindowAdapter.
1174        // Skip the eager window creation and tree instantiation for them.
1175        if !instance.is_system_tray_rooted() {
1176            // Make sure the window adapter is created so call to `window()` do not panic later.
1177            instance.inner.window_adapter_ref()?;
1178            // Eagerly instantiate repeaters and conditionals so that layout
1179            // bindings can see all instances without calling ensure_updated.
1180            i_slint_core::window::WindowInner::from_pub(instance.window())
1181                .ensure_tree_instantiated();
1182        }
1183        Ok(instance)
1184    }
1185
1186    /// Creates a new instance of the component and returns a shared handle to it.
1187    #[doc(hidden)]
1188    #[cfg(feature = "internal")]
1189    pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1190        self.create_with_options(WindowOptions::Embed {
1191            parent_item_tree: ctx.parent_item_tree,
1192            parent_item_tree_index: ctx.parent_item_tree_index,
1193        })
1194    }
1195
1196    /// Instantiate the component using an existing window.
1197    #[doc(hidden)]
1198    #[cfg(feature = "internal")]
1199    pub fn create_with_existing_window(
1200        &self,
1201        window: &Window,
1202    ) -> Result<ComponentInstance, PlatformError> {
1203        self.create_with_options(WindowOptions::UseExistingWindow(
1204            WindowInner::from_pub(window).window_adapter(),
1205        ))
1206    }
1207
1208    /// Private implementation of create
1209    pub(crate) fn create_with_options(
1210        &self,
1211        options: WindowOptions,
1212    ) -> Result<ComponentInstance, PlatformError> {
1213        let instance = match options {
1214            WindowOptions::CreateNewWindow => self.inner.create(),
1215            WindowOptions::UseExistingWindow(adapter) => {
1216                self.inner.create_with_existing_window(adapter)
1217            }
1218            WindowOptions::Embed { parent_item_tree, parent_item_tree_index } => {
1219                self.inner.create_embedded(parent_item_tree, parent_item_tree_index)
1220            }
1221        };
1222        Ok(ComponentInstance { inner: instance })
1223    }
1224}
1225
1226/// Controls how a [`ComponentInstance`] obtains its window on creation.
1227///
1228/// Live preview passes `UseExistingWindow` with the previous instance's
1229/// adapter so reloads keep the same window frame.
1230#[allow(dead_code)]
1231#[derive(Default)]
1232pub(crate) enum WindowOptions {
1233    #[default]
1234    CreateNewWindow,
1235    UseExistingWindow(i_slint_core::window::WindowAdapterRc),
1236    Embed {
1237        parent_item_tree: i_slint_core::item_tree::ItemTreeWeak,
1238        parent_item_tree_index: u32,
1239    },
1240}
1241
1242impl ComponentDefinition {
1243    /// List of publicly declared properties or callback.
1244    ///
1245    /// This is internal because it exposes the `Type` from compilerlib.
1246    #[doc(hidden)]
1247    #[cfg(feature = "internal")]
1248    pub fn properties_and_callbacks(
1249        &self,
1250    ) -> impl Iterator<
1251        Item = (
1252            String,
1253            (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1254        ),
1255    > + '_ {
1256        self.inner
1257            .properties_and_callbacks()
1258            .map(|(n, t, v)| (n.to_string(), (t, v)))
1259            .collect::<Vec<_>>()
1260            .into_iter()
1261    }
1262
1263    /// Returns an iterator over all publicly declared properties. Each iterator item is a tuple of property name
1264    /// and property type for each of them.
1265    pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1266        self.inner
1267            .properties()
1268            .map(|(n, t)| (n.to_string(), t.into()))
1269            .collect::<Vec<_>>()
1270            .into_iter()
1271    }
1272
1273    /// Returns the names of all publicly declared callbacks.
1274    pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1275        self.inner.callbacks().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1276    }
1277
1278    /// Returns the names of all publicly declared functions.
1279    pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1280        self.inner.functions().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1281    }
1282
1283    /// Returns the names of all exported global singletons
1284    ///
1285    /// **Note:** Only globals that are exported or re-exported from the main .slint file will
1286    /// be exposed in the API
1287    pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1288        self.inner.globals().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1289    }
1290
1291    /// List of publicly declared properties or callback in the exported global singleton specified by its name.
1292    ///
1293    /// This is internal because it exposes the `Type` from compilerlib.
1294    #[doc(hidden)]
1295    #[cfg(feature = "internal")]
1296    pub fn global_properties_and_callbacks(
1297        &self,
1298        global_name: &str,
1299    ) -> Option<
1300        impl Iterator<
1301            Item = (
1302                String,
1303                (
1304                    i_slint_compiler::langtype::Type,
1305                    i_slint_compiler::object_tree::PropertyVisibility,
1306                ),
1307            ),
1308        > + '_,
1309    > {
1310        Some(
1311            self.inner
1312                .global_properties_and_callbacks(global_name)?
1313                .map(|(n, t, v)| (n.to_string(), (t, v)))
1314                .collect::<Vec<_>>()
1315                .into_iter(),
1316        )
1317    }
1318
1319    /// List of publicly declared properties in the exported global singleton specified by its name.
1320    pub fn global_properties(
1321        &self,
1322        global_name: &str,
1323    ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1324        Some(
1325            self.inner
1326                .global_properties(global_name)?
1327                .map(|(n, t)| (n.to_string(), t.into()))
1328                .collect::<Vec<_>>()
1329                .into_iter(),
1330        )
1331    }
1332
1333    /// List of publicly declared callbacks in the exported global singleton specified by its name.
1334    pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1335        Some(
1336            self.inner
1337                .global_callbacks(global_name)?
1338                .map(|s| s.to_string())
1339                .collect::<Vec<_>>()
1340                .into_iter(),
1341        )
1342    }
1343
1344    /// List of publicly declared functions in the exported global singleton specified by its name.
1345    pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1346        Some(
1347            self.inner
1348                .global_functions(global_name)?
1349                .map(|s| s.to_string())
1350                .collect::<Vec<_>>()
1351                .into_iter(),
1352        )
1353    }
1354
1355    /// The name of this Component as written in the .slint file
1356    pub fn name(&self) -> &str {
1357        self.inner.name()
1358    }
1359
1360    /// True if instances of this component expose a `slint::Window`-shaped API
1361    /// (i.e. calling [`ComponentInstance::window`] is meaningful). False for
1362    /// non-windowed roots such as `SystemTrayIcon`, where `window()` would panic.
1363    #[doc(hidden)]
1364    #[cfg(feature = "internal")]
1365    pub fn is_window(&self) -> bool {
1366        self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::Window
1367    }
1368
1369    /// This gives access to the tree of Elements.
1370    #[cfg(feature = "internal")]
1371    #[doc(hidden)]
1372    pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1373        self.inner
1374            .type_loaders
1375            .originals
1376            .get(self.inner.public_index)
1377            .expect("root_component() called on a definition built without compiler state")
1378            .clone()
1379    }
1380
1381    /// Return the `TypeLoader` used when parsing the code in the interpreter.
1382    ///
1383    /// WARNING: this is not part of the public API
1384    #[cfg(feature = "internal-highlight")]
1385    pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1386        self.inner.type_loaders.type_loader.clone().expect(
1387            "TypeLoader was not retained for this ComponentDefinition (reconstructed from an instance)",
1388        )
1389    }
1390
1391    /// Return the `TypeLoader` used when parsing the code in the interpreter in
1392    /// a state before most passes were applied by the compiler.
1393    ///
1394    /// Each returned type loader is a deep copy of the entire state connected to it,
1395    /// so this is a fairly expensive function!
1396    ///
1397    /// WARNING: this is not part of the public API
1398    #[cfg(feature = "internal-highlight")]
1399    pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1400        self.inner
1401            .type_loaders
1402            .raw_type_loader
1403            .as_ref()
1404            .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1405    }
1406}
1407
1408/// Print the diagnostics to stderr
1409///
1410/// The diagnostics are printed in the same style as rustc errors
1411///
1412/// This function is available when the `display-diagnostics` is enabled.
1413#[cfg(feature = "display-diagnostics")]
1414pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1415    let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1416    for d in diagnostics {
1417        build_diagnostics.push_compiler_error(d.clone())
1418    }
1419    build_diagnostics.print();
1420}
1421
1422/// This represents an instance of a dynamic component
1423///
1424/// You can create an instance with the [`ComponentDefinition::create`] function.
1425///
1426/// Properties and callback can be accessed using the associated functions.
1427///
1428/// An instance can be put on screen with the [`ComponentInstance::run`] function.
1429#[repr(C)]
1430pub struct ComponentInstance {
1431    pub(crate) inner: crate::component::ComponentInstanceInner,
1432}
1433
1434impl ComponentInstance {
1435    /// Return the [`ComponentDefinition`] that was used to create this instance.
1436    pub fn definition(&self) -> ComponentDefinition {
1437        ComponentDefinition { inner: std::rc::Rc::new(self.inner.definition()) }
1438    }
1439
1440    fn is_system_tray_rooted(&self) -> bool {
1441        self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::SystemTrayIcon
1442    }
1443
1444    /// Set `visible` directly on the root SystemTrayIcon native item, mirroring
1445    /// what the Rust/C++ generators emit for tray-rooted public components:
1446    /// the change-tracker on the item dispatches the value to the platform handle.
1447    fn set_tray_icon_visible(&self, visible: bool) {
1448        // The native SystemTrayIcon is item 0 of the root sub-component.
1449        let item_rc = ItemRc::new(vtable::VRc::into_dyn(self.inner.vrc().clone()), 0);
1450        let tray = item_rc
1451            .downcast::<SystemTrayIcon>()
1452            .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1453        tray.as_pin_ref().visible.set(visible);
1454    }
1455
1456    /// Return the value for a public property of this component.
1457    ///
1458    /// ## Examples
1459    ///
1460    /// ```
1461    /// # i_slint_backend_testing::init_no_event_loop();
1462    /// use slint_interpreter::{ComponentDefinition, Compiler, Value, SharedString};
1463    /// let code = r#"
1464    ///     export component MyWin inherits Window {
1465    ///         in-out property <int> my_property: 42;
1466    ///     }
1467    /// "#;
1468    /// let mut compiler = Compiler::default();
1469    /// let result = spin_on::spin_on(
1470    ///     compiler.build_from_source(code.into(), Default::default()));
1471    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1472    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1473    /// assert_eq!(instance.get_property("my_property").unwrap(), Value::from(42));
1474    /// ```
1475    pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1476        self.inner.get_property(name).ok_or(GetPropertyError::NoSuchProperty)
1477    }
1478
1479    /// Set the value for a public property of this component.
1480    pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1481        self.inner.set_property(name, value)
1482    }
1483
1484    /// Set a handler for the callback with the given name. A callback with that
1485    /// name must be defined in the document otherwise an error will be returned.
1486    ///
1487    /// Note: Since the [`ComponentInstance`] holds the handler, the handler itself should not
1488    /// contain a strong reference to the instance. So if you need to capture the instance,
1489    /// you should use [`Self::as_weak`] to create a weak reference.
1490    ///
1491    /// ## Examples
1492    ///
1493    /// ```
1494    /// # i_slint_backend_testing::init_no_event_loop();
1495    /// use slint_interpreter::{Compiler, Value, SharedString, ComponentHandle};
1496    /// use core::convert::TryInto;
1497    /// let code = r#"
1498    ///     export component MyWin inherits Window {
1499    ///         callback foo(int) -> int;
1500    ///         in-out property <int> my_prop: 12;
1501    ///     }
1502    /// "#;
1503    /// let result = spin_on::spin_on(
1504    ///     Compiler::default().build_from_source(code.into(), Default::default()));
1505    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1506    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1507    /// let instance_weak = instance.as_weak();
1508    /// instance.set_callback("foo", move |args: &[Value]| -> Value {
1509    ///     let arg: u32 = args[0].clone().try_into().unwrap();
1510    ///     let my_prop = instance_weak.unwrap().get_property("my_prop").unwrap();
1511    ///     let my_prop : u32 = my_prop.try_into().unwrap();
1512    ///     Value::from(arg + my_prop)
1513    /// }).unwrap();
1514    ///
1515    /// let res = instance.invoke("foo", &[Value::from(500)]).unwrap();
1516    /// assert_eq!(res, Value::from(500+12));
1517    /// ```
1518    pub fn set_callback(
1519        &self,
1520        name: &str,
1521        callback: impl Fn(&[Value]) -> Value + 'static,
1522    ) -> Result<(), SetCallbackError> {
1523        self.inner.set_callback(name, callback).map_err(|()| SetCallbackError::NoSuchCallback)
1524    }
1525
1526    /// Call the given callback or function with the arguments
1527    ///
1528    /// ## Examples
1529    /// See the documentation of [`Self::set_callback`] for an example
1530    pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1531        self.inner.invoke(name, args).ok_or(InvokeError::NoSuchCallable)
1532    }
1533
1534    /// Return the value for a property within an exported global singleton used by this component.
1535    ///
1536    /// The `global` parameter is the exported name of the global singleton. The `property` argument
1537    /// is the name of the property
1538    ///
1539    /// ## Examples
1540    ///
1541    /// ```
1542    /// # i_slint_backend_testing::init_no_event_loop();
1543    /// use slint_interpreter::{Compiler, Value, SharedString};
1544    /// let code = r#"
1545    ///     global Glob {
1546    ///         in-out property <int> my_property: 42;
1547    ///     }
1548    ///     export { Glob as TheGlobal }
1549    ///     export component MyWin inherits Window {
1550    ///     }
1551    /// "#;
1552    /// let mut compiler = Compiler::default();
1553    /// let result = spin_on::spin_on(compiler.build_from_source(code.into(), Default::default()));
1554    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1555    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1556    /// assert_eq!(instance.get_global_property("TheGlobal", "my_property").unwrap(), Value::from(42));
1557    /// ```
1558    pub fn get_global_property(
1559        &self,
1560        global: &str,
1561        property: &str,
1562    ) -> Result<Value, GetPropertyError> {
1563        self.inner.get_global_property(global, property).ok_or(GetPropertyError::NoSuchProperty)
1564    }
1565
1566    /// Set the value for a property within an exported global singleton used by this component.
1567    pub fn set_global_property(
1568        &self,
1569        global: &str,
1570        property: &str,
1571        value: Value,
1572    ) -> Result<(), SetPropertyError> {
1573        self.inner.set_global_property(global, property, value)
1574    }
1575
1576    /// Set a handler for the callback in the exported global singleton. A callback with that
1577    /// name must be defined in the specified global and the global must be exported from the
1578    /// main document otherwise an error will be returned.
1579    ///
1580    /// ## Examples
1581    ///
1582    /// ```
1583    /// # i_slint_backend_testing::init_no_event_loop();
1584    /// use slint_interpreter::{Compiler, Value, SharedString};
1585    /// use core::convert::TryInto;
1586    /// let code = r#"
1587    ///     export global Logic {
1588    ///         pure callback to_uppercase(string) -> string;
1589    ///     }
1590    ///     export component MyWin inherits Window {
1591    ///         out property <string> hello: Logic.to_uppercase("world");
1592    ///     }
1593    /// "#;
1594    /// let result = spin_on::spin_on(
1595    ///     Compiler::default().build_from_source(code.into(), Default::default()));
1596    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1597    /// instance.set_global_callback("Logic", "to_uppercase", |args: &[Value]| -> Value {
1598    ///     let arg: SharedString = args[0].clone().try_into().unwrap();
1599    ///     Value::from(SharedString::from(arg.to_uppercase()))
1600    /// }).unwrap();
1601    ///
1602    /// let res = instance.get_property("hello").unwrap();
1603    /// assert_eq!(res, Value::from(SharedString::from("WORLD")));
1604    ///
1605    /// let abc = instance.invoke_global("Logic", "to_uppercase", &[
1606    ///     SharedString::from("abc").into()
1607    /// ]).unwrap();
1608    /// assert_eq!(abc, Value::from(SharedString::from("ABC")));
1609    /// ```
1610    pub fn set_global_callback(
1611        &self,
1612        global: &str,
1613        name: &str,
1614        callback: impl Fn(&[Value]) -> Value + 'static,
1615    ) -> Result<(), SetCallbackError> {
1616        self.inner
1617            .set_global_callback(global, name, callback)
1618            .map_err(|()| SetCallbackError::NoSuchCallback)
1619    }
1620
1621    /// Call the given callback or function within a global singleton with the arguments
1622    ///
1623    /// ## Examples
1624    /// See the documentation of [`Self::set_global_callback`] for an example
1625    pub fn invoke_global(
1626        &self,
1627        global: &str,
1628        callable_name: &str,
1629        args: &[Value],
1630    ) -> Result<Value, InvokeError> {
1631        self.inner.invoke_global(global, callable_name, args).ok_or(InvokeError::NoSuchCallable)
1632    }
1633
1634    /// Find all positions of the components which are pointed by a given source location.
1635    ///
1636    /// WARNING: this is not part of the public API
1637    #[cfg(feature = "internal-highlight")]
1638    pub fn component_positions(
1639        &self,
1640        path: &Path,
1641        offset: u32,
1642    ) -> Vec<crate::highlight::HighlightedRect> {
1643        crate::highlight::component_positions(self.inner.vrc(), path, offset)
1644    }
1645
1646    /// Find the position of the `element`.
1647    ///
1648    /// WARNING: this is not part of the public API
1649    #[cfg(feature = "internal-highlight")]
1650    pub fn element_positions(
1651        &self,
1652        element: &i_slint_compiler::object_tree::ElementRc,
1653    ) -> Vec<crate::highlight::HighlightedRect> {
1654        crate::highlight::element_positions(
1655            self.inner.vrc(),
1656            element,
1657            crate::highlight::ElementPositionFilter::IncludeClipped,
1658        )
1659    }
1660
1661    /// Find the `element` that was defined at the text position.
1662    ///
1663    /// WARNING: this is not part of the public API
1664    #[cfg(feature = "internal-highlight")]
1665    pub fn element_node_at_source_code_position(
1666        &self,
1667        path: &Path,
1668        offset: u32,
1669    ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1670        crate::highlight::element_node_at_source_code_position(self.inner.vrc(), path, offset)
1671    }
1672
1673    /// Set a callback triggered by `Expression::DebugHook`.
1674    #[cfg(feature = "internal")]
1675    pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1676        crate::debug_hook::set_debug_hook_callback(self.inner.vrc(), callback);
1677    }
1678}
1679
1680impl StrongHandle for ComponentInstance {
1681    type WeakInner = vtable::VWeak<ItemTreeVTable, crate::instance::Instance>;
1682
1683    fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1684        Some(Self { inner: crate::component::ComponentInstanceInner(inner.upgrade()?) })
1685    }
1686}
1687
1688impl ComponentHandle for ComponentInstance {
1689    fn as_weak(&self) -> Weak<Self>
1690    where
1691        Self: Sized,
1692    {
1693        Weak::new(vtable::VRc::downgrade(self.inner.vrc()))
1694    }
1695
1696    fn clone_strong(&self) -> Self {
1697        Self { inner: self.inner.clone() }
1698    }
1699
1700    fn show(&self) -> Result<(), PlatformError> {
1701        if self.is_system_tray_rooted() {
1702            self.set_tray_icon_visible(true);
1703            return Ok(());
1704        }
1705        let adapter = self.inner.window_adapter_ref()?;
1706        // Link the window adapter back to this item tree. Must happen from
1707        // a lifecycle call site rather than from inside binding evaluation
1708        // so `set_component` can touch window-item property trackers safely.
1709        self.inner.0.attach_to_window();
1710        adapter.window().show()
1711    }
1712
1713    fn hide(&self) -> Result<(), PlatformError> {
1714        if self.is_system_tray_rooted() {
1715            self.set_tray_icon_visible(false);
1716            return Ok(());
1717        }
1718        self.inner.window_adapter_ref()?.window().hide()
1719    }
1720
1721    fn run(&self) -> Result<(), PlatformError> {
1722        self.show()?;
1723        run_event_loop()?;
1724        self.hide()
1725    }
1726
1727    fn window(&self) -> &Window {
1728        let adapter = self.inner.window_adapter_ref().unwrap();
1729        // `window()` is always called from the public API, never from inside
1730        // a property binding evaluation, so it's safe to attach the item
1731        // tree to the window here. This lets test helpers (e.g.
1732        // `send_mouse_click`) dispatch events even when the caller never
1733        // called `show()`.
1734        self.inner.0.attach_to_window();
1735        adapter.window()
1736    }
1737
1738    fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1739    where
1740        Self: Sized,
1741    {
1742        unreachable!()
1743    }
1744}
1745
1746impl From<ComponentInstance>
1747    for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>
1748{
1749    fn from(value: ComponentInstance) -> Self {
1750        value.inner.0
1751    }
1752}
1753
1754/// Error returned by [`ComponentInstance::get_property`]
1755#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1756#[non_exhaustive]
1757pub enum GetPropertyError {
1758    /// There is no property with the given name
1759    #[display("no such property")]
1760    NoSuchProperty,
1761}
1762
1763/// Error returned by [`ComponentInstance::set_property`]
1764#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1765#[non_exhaustive]
1766pub enum SetPropertyError {
1767    /// There is no property with the given name.
1768    #[display("no such property")]
1769    NoSuchProperty,
1770    /// The property exists but does not have a type matching the dynamic value.
1771    ///
1772    /// This happens for example when assigning a source struct value to a target
1773    /// struct property, where the source doesn't have all the fields the target struct
1774    /// requires.
1775    #[display("wrong type")]
1776    WrongType,
1777    /// Attempt to set an output property.
1778    #[display("access denied")]
1779    AccessDenied,
1780}
1781
1782/// Error returned by [`ComponentInstance::set_callback`]
1783#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1784#[non_exhaustive]
1785pub enum SetCallbackError {
1786    /// There is no callback with the given name
1787    #[display("no such callback")]
1788    NoSuchCallback,
1789}
1790
1791/// Error returned by [`ComponentInstance::invoke`]
1792#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1793#[non_exhaustive]
1794pub enum InvokeError {
1795    /// There is no callback or function with the given name
1796    #[display("no such callback or function")]
1797    NoSuchCallable,
1798}
1799
1800/// Enters the main event loop. This is necessary in order to receive
1801/// events from the windowing system in order to render to the screen
1802/// and react to user input.
1803pub fn run_event_loop() -> Result<(), PlatformError> {
1804    i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1805}
1806
1807/// Spawns a [`Future`] to execute in the Slint event loop.
1808///
1809/// See the documentation of `slint::spawn_local()` for more info
1810pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1811    i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1812        .map_err(|_| EventLoopError::NoEventLoopProvider)?
1813}
1814
1815#[test]
1816fn component_definition_properties() {
1817    i_slint_backend_testing::init_no_event_loop();
1818    let mut compiler = Compiler::default();
1819    compiler.set_style("fluent".into());
1820    let comp_def = spin_on::spin_on(
1821        compiler.build_from_source(
1822            r#"
1823    export component Dummy {
1824        in-out property <string> test;
1825        in-out property <int> underscores-and-dashes_preserved: 44;
1826        callback hello;
1827    }"#
1828            .into(),
1829            "".into(),
1830        ),
1831    )
1832    .component("Dummy")
1833    .unwrap();
1834
1835    let props = comp_def.properties().collect::<Vec<(_, _)>>();
1836
1837    assert_eq!(props.len(), 2);
1838    assert_eq!(props[0].0, "test");
1839    assert_eq!(props[0].1, ValueType::String);
1840    assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1841    assert_eq!(props[1].1, ValueType::Number);
1842
1843    let instance = comp_def.create().unwrap();
1844    assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1845    assert_eq!(
1846        instance.get_property("underscoresanddashespreserved"),
1847        Err(GetPropertyError::NoSuchProperty)
1848    );
1849    assert_eq!(
1850        instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1851        Ok(())
1852    );
1853    assert_eq!(
1854        instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1855        Err(SetPropertyError::NoSuchProperty)
1856    );
1857    assert_eq!(
1858        instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1859        Err(SetPropertyError::WrongType)
1860    );
1861    assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1862}
1863
1864#[test]
1865fn component_definition_properties2() {
1866    i_slint_backend_testing::init_no_event_loop();
1867    let mut compiler = Compiler::default();
1868    compiler.set_style("fluent".into());
1869    let comp_def = spin_on::spin_on(
1870        compiler.build_from_source(
1871            r#"
1872    export component Dummy {
1873        in-out property <string> sub-text <=> sub.text;
1874        sub := Text { property <int> private-not-exported; }
1875        out property <string> xreadonly: "the value";
1876        private property <string> xx: sub.text;
1877        callback hello;
1878    }"#
1879            .into(),
1880            "".into(),
1881        ),
1882    )
1883    .component("Dummy")
1884    .unwrap();
1885
1886    let props = comp_def.properties().collect::<Vec<(_, _)>>();
1887
1888    assert_eq!(props.len(), 2);
1889    assert_eq!(props[0].0, "sub-text");
1890    assert_eq!(props[0].1, ValueType::String);
1891    assert_eq!(props[1].0, "xreadonly");
1892
1893    let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1894    assert_eq!(callbacks.len(), 1);
1895    assert_eq!(callbacks[0], "hello");
1896
1897    let instance = comp_def.create().unwrap();
1898    assert_eq!(
1899        instance.set_property("xreadonly", SharedString::from("XXX").into()),
1900        Err(SetPropertyError::AccessDenied)
1901    );
1902    assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1903    assert_eq!(
1904        instance.set_property("xx", SharedString::from("XXX").into()),
1905        Err(SetPropertyError::NoSuchProperty)
1906    );
1907    assert_eq!(
1908        instance.set_property("background", Value::default()),
1909        Err(SetPropertyError::NoSuchProperty)
1910    );
1911
1912    assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1913    assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1914}
1915
1916#[test]
1917fn globals() {
1918    i_slint_backend_testing::init_no_event_loop();
1919    let mut compiler = Compiler::default();
1920    compiler.set_style("fluent".into());
1921    let definition = spin_on::spin_on(
1922        compiler.build_from_source(
1923            r#"
1924    export global My-Super_Global {
1925        in-out property <int> the-property : 21;
1926        callback my-callback();
1927        callback int-callback() -> int;
1928    }
1929    export { My-Super_Global as AliasedGlobal }
1930    export component Dummy {
1931        callback alias <=> My-Super_Global.my-callback;
1932    }"#
1933            .into(),
1934            "".into(),
1935        ),
1936    )
1937    .component("Dummy")
1938    .unwrap();
1939
1940    assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1941
1942    assert!(definition.global_properties("not-there").is_none());
1943    {
1944        let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1945        let expected_callbacks = vec!["int-callback".to_string(), "my-callback".to_string()];
1946
1947        let assert_properties_and_callbacks = |global_name| {
1948            assert_eq!(
1949                definition
1950                    .global_properties(global_name)
1951                    .map(|props| props.collect::<Vec<_>>())
1952                    .as_ref(),
1953                Some(&expected_properties)
1954            );
1955            assert_eq!(
1956                definition
1957                    .global_callbacks(global_name)
1958                    .map(|props| props.collect::<Vec<_>>())
1959                    .as_ref(),
1960                Some(&expected_callbacks)
1961            );
1962        };
1963
1964        assert_properties_and_callbacks("My-Super-Global");
1965        assert_properties_and_callbacks("My_Super-Global");
1966        assert_properties_and_callbacks("AliasedGlobal");
1967    }
1968
1969    let instance = definition.create().unwrap();
1970    assert_eq!(
1971        instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
1972        Ok(())
1973    );
1974    assert_eq!(
1975        instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
1976        Ok(())
1977    );
1978    assert_eq!(
1979        instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
1980        Err(SetPropertyError::NoSuchProperty)
1981    );
1982
1983    assert_eq!(
1984        instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
1985        Err(SetPropertyError::NoSuchProperty)
1986    );
1987    assert_eq!(
1988        instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
1989        Err(SetPropertyError::NoSuchProperty)
1990    );
1991    assert_eq!(
1992        instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
1993        Err(SetPropertyError::WrongType)
1994    );
1995    assert_eq!(
1996        instance.get_global_property("My-Super_Global", "yoyo"),
1997        Err(GetPropertyError::NoSuchProperty)
1998    );
1999    assert_eq!(
2000        instance.get_global_property("My-Super_Global", "the-property"),
2001        Ok(Value::Number(44.))
2002    );
2003
2004    assert_eq!(
2005        instance.set_property("the-property", Value::Void),
2006        Err(SetPropertyError::NoSuchProperty)
2007    );
2008    assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2009
2010    assert_eq!(
2011        instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2012        Err(SetCallbackError::NoSuchCallback)
2013    );
2014    assert_eq!(
2015        instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2016        Err(SetCallbackError::NoSuchCallback)
2017    );
2018    assert_eq!(
2019        instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2020        Err(SetCallbackError::NoSuchCallback)
2021    );
2022
2023    assert_eq!(
2024        instance.invoke_global("DontExist", "the-property", &[]),
2025        Err(InvokeError::NoSuchCallable)
2026    );
2027    assert_eq!(
2028        instance.invoke_global("My_Super_Global", "the-property", &[]),
2029        Err(InvokeError::NoSuchCallable)
2030    );
2031    assert_eq!(
2032        instance.invoke_global("My_Super_Global", "yoyo", &[]),
2033        Err(InvokeError::NoSuchCallable)
2034    );
2035
2036    // Alias to global don't crash (#8238)
2037    assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2038
2039    // Invoking a callback without a handler returns the return type's default
2040    assert_eq!(
2041        instance.invoke_global("My_Super_Global", "int-callback", &[]),
2042        Ok(Value::Number(0.))
2043    );
2044}
2045
2046#[test]
2047fn call_functions() {
2048    i_slint_backend_testing::init_no_event_loop();
2049    let mut compiler = Compiler::default();
2050    compiler.set_style("fluent".into());
2051    let definition = spin_on::spin_on(
2052        compiler.build_from_source(
2053            r#"
2054    export global Gl {
2055        out property<string> q;
2056        public function foo-bar(a-a: string, b-b:int) -> string {
2057            q = a-a;
2058            return a-a + b-b;
2059        }
2060    }
2061    export component Test {
2062        out property<int> p;
2063        public function foo-bar(a: int, b:int) -> int {
2064            p = a;
2065            return a + b;
2066        }
2067    }"#
2068            .into(),
2069            "".into(),
2070        ),
2071    )
2072    .component("Test")
2073    .unwrap();
2074
2075    assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2076    assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2077
2078    let instance = definition.create().unwrap();
2079
2080    assert_eq!(
2081        instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2082        Ok(Value::Number(7.))
2083    );
2084    assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2085    assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2086
2087    assert_eq!(
2088        instance.invoke_global(
2089            "Gl",
2090            "foo_bar",
2091            &[Value::String("Hello".into()), Value::Number(10.)]
2092        ),
2093        Ok(Value::String("Hello10".into()))
2094    );
2095    assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2096}
2097
2098#[test]
2099fn component_definition_struct_properties() {
2100    i_slint_backend_testing::init_no_event_loop();
2101    let mut compiler = Compiler::default();
2102    compiler.set_style("fluent".into());
2103    let comp_def = spin_on::spin_on(
2104        compiler.build_from_source(
2105            r#"
2106    export struct Settings {
2107        string_value: string,
2108    }
2109    export component Dummy {
2110        in-out property <Settings> test;
2111    }"#
2112            .into(),
2113            "".into(),
2114        ),
2115    )
2116    .component("Dummy")
2117    .unwrap();
2118
2119    let props = comp_def.properties().collect::<Vec<(_, _)>>();
2120
2121    assert_eq!(props.len(), 1);
2122    assert_eq!(props[0].0, "test");
2123    assert_eq!(props[0].1, ValueType::Struct);
2124
2125    let instance = comp_def.create().unwrap();
2126
2127    let valid_struct: Struct =
2128        [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2129
2130    assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2131    assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2132
2133    assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2134
2135    let mut invalid_struct = valid_struct.clone();
2136    invalid_struct.set_field("other".into(), Value::Number(44.));
2137    assert_eq!(
2138        instance.set_property("test", Value::Struct(invalid_struct)),
2139        Err(SetPropertyError::WrongType)
2140    );
2141    let mut invalid_struct = valid_struct;
2142    invalid_struct.set_field("string_value".into(), Value::Number(44.));
2143    assert_eq!(
2144        instance.set_property("test", Value::Struct(invalid_struct)),
2145        Err(SetPropertyError::WrongType)
2146    );
2147}
2148
2149#[test]
2150fn component_definition_model_properties() {
2151    use i_slint_core::model::*;
2152    i_slint_backend_testing::init_no_event_loop();
2153    let mut compiler = Compiler::default();
2154    compiler.set_style("fluent".into());
2155    let comp_def = spin_on::spin_on(compiler.build_from_source(
2156        "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2157        "".into(),
2158    ))
2159    .component("Dummy")
2160    .unwrap();
2161
2162    let props = comp_def.properties().collect::<Vec<(_, _)>>();
2163    assert_eq!(props.len(), 1);
2164    assert_eq!(props[0].0, "prop");
2165    assert_eq!(props[0].1, ValueType::Model);
2166
2167    let instance = comp_def.create().unwrap();
2168
2169    let int_model =
2170        Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2171    let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2172    let model_with_string = Value::Model(VecModel::from_slice(&[
2173        Value::Number(1000.),
2174        Value::String("foo".into()),
2175        Value::Number(1111.),
2176    ]));
2177
2178    #[track_caller]
2179    fn check_model(val: Value, r: &[f64]) {
2180        if let Value::Model(m) = val {
2181            assert_eq!(r.len(), m.row_count());
2182            for (i, v) in r.iter().enumerate() {
2183                assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2184            }
2185        } else {
2186            panic!("{val:?} not a model");
2187        }
2188    }
2189
2190    assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2191    check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2192
2193    instance.set_property("prop", int_model).unwrap();
2194    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2195
2196    assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2197    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2198    assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2199    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2200
2201    assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2202    check_model(instance.get_property("prop").unwrap(), &[]);
2203}
2204
2205#[test]
2206fn lang_type_to_value_type() {
2207    use i_slint_compiler::langtype::Struct as LangStruct;
2208    use std::collections::BTreeMap;
2209
2210    assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2211    assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2212    assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2213    assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2214    assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2215    assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2216    assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2217    assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2218    assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2219    assert_eq!(ValueType::from(LangType::String), ValueType::String);
2220    assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2221    assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2222    assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2223    assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2224    assert_eq!(
2225        ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2226            BTreeMap::default(),
2227            i_slint_compiler::langtype::StructName::None
2228        )))),
2229        ValueType::Struct
2230    );
2231    assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2232}
2233
2234#[test]
2235fn test_multi_components() {
2236    i_slint_backend_testing::init_no_event_loop();
2237    let result = spin_on::spin_on(
2238        Compiler::default().build_from_source(
2239            r#"
2240        export struct Settings {
2241            string_value: string,
2242        }
2243        export global ExpGlo { in-out property <int> test: 42; }
2244        component Common {
2245            in-out property <Settings> settings: { string_value: "Hello", };
2246        }
2247        export component Xyz inherits Window {
2248            in-out property <int> aaa: 8;
2249        }
2250        export component Foo {
2251
2252            in-out property <int> test: 42;
2253            c := Common {}
2254        }
2255        export component Bar inherits Window {
2256            in-out property <int> blah: 78;
2257            c := Common {}
2258        }
2259        "#
2260            .into(),
2261            PathBuf::from("hello.slint"),
2262        ),
2263    );
2264
2265    assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2266    let mut components = result.component_names().collect::<Vec<_>>();
2267    components.sort();
2268    assert_eq!(components, vec!["Bar", "Xyz"]);
2269    let diag = result.diagnostics().collect::<Vec<_>>();
2270    assert_eq!(diag.len(), 1);
2271    assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2272    assert_eq!(
2273        diag[0].message(),
2274        "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2275    );
2276
2277    let comp1 = result.component("Xyz").unwrap();
2278    assert_eq!(comp1.name(), "Xyz");
2279    let instance1a = comp1.create().unwrap();
2280    let comp2 = result.component("Bar").unwrap();
2281    let instance2 = comp2.create().unwrap();
2282    let instance1b = comp1.create().unwrap();
2283
2284    // globals are not shared between instances
2285    assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2286    assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2287    assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2288    assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2289    assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2290
2291    assert!(result.component("Settings").is_none());
2292    assert!(result.component("Foo").is_none());
2293    assert!(result.component("Common").is_none());
2294    assert!(result.component("ExpGlo").is_none());
2295    assert!(result.component("xyz").is_none());
2296}
2297
2298#[cfg(all(test, feature = "internal-highlight"))]
2299fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2300    i_slint_backend_testing::init_no_event_loop();
2301    let mut compiler = Compiler::default();
2302    compiler.set_style("fluent".into());
2303    let path = PathBuf::from("/tmp/test.slint");
2304
2305    let compile_result =
2306        spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2307
2308    for d in &compile_result.diagnostics {
2309        eprintln!("{d}");
2310    }
2311
2312    assert!(!compile_result.has_errors());
2313
2314    let definition = compile_result.components().next().unwrap();
2315    let instance = definition.create().unwrap();
2316
2317    (instance, path)
2318}
2319
2320#[cfg(feature = "internal-highlight")]
2321#[test]
2322fn test_element_node_at_source_code_position() {
2323    let code = r#"
2324component Bar1 {}
2325
2326component Foo1 {
2327}
2328
2329export component Foo2 inherits Window  {
2330    Bar1 {}
2331    Foo1   {}
2332}"#;
2333
2334    let (handle, path) = compile(code);
2335
2336    for i in 0..code.len() as u32 {
2337        let elements = handle.element_node_at_source_code_position(&path, i);
2338        eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2339        match i {
2340            16 => assert_eq!(elements.len(), 1),       // Bar1 (def)
2341            35 => assert_eq!(elements.len(), 1),       // Foo1 (def)
2342            71..=78 => assert_eq!(elements.len(), 1),  // Window + WS (from Foo2)
2343            85..=89 => assert_eq!(elements.len(), 1),  // Bar1 + WS (use)
2344            97..=103 => assert_eq!(elements.len(), 1), // Foo1 + WS (use)
2345            _ => assert!(elements.is_empty()),
2346        }
2347    }
2348}
2349
2350/// `element_positions` must return one rect per *instantiation*: a component
2351/// used twice yields only the queried use site's rect, and elements inside a
2352/// `for` yield one rect per row.
2353#[cfg(feature = "internal-highlight")]
2354#[test]
2355fn test_element_positions_instances_and_repeaters() {
2356    use i_slint_core::graphics::euclid;
2357    let code = r#"
2358component MyBox inherits Rectangle {
2359    width: 50px;
2360    height: 50px;
2361}
2362
2363export component Foo3 inherits Window {
2364    width: 400px;
2365    height: 400px;
2366    b1 := MyBox { x: 0px; y: 0px; }
2367    b2 := MyBox { x: 200px; y: 200px; }
2368    for xo in [0, 1, 2]: Rectangle {
2369        x: xo * 10px;
2370        y: 300px;
2371        width: 10px;
2372        height: 10px;
2373    }
2374}"#;
2375
2376    let (handle, path) = compile(code);
2377
2378    let element_at = |pattern: &str| {
2379        let offset = code.find(pattern).unwrap() as u32;
2380        let elements = handle.element_node_at_source_code_position(&path, offset);
2381        assert_eq!(elements.len(), 1, "expected one element at {pattern:?}");
2382        elements.into_iter().next().unwrap().0
2383    };
2384
2385    // Each MyBox use highlights only its own instance.
2386    let b1_rects = handle.element_positions(&element_at("MyBox { x: 0px"));
2387    assert_eq!(b1_rects.len(), 1, "{b1_rects:?}");
2388    assert_eq!(b1_rects[0].rect.origin, euclid::point2(0., 0.));
2389
2390    let b2_rects = handle.element_positions(&element_at("MyBox { x: 200px"));
2391    assert_eq!(b2_rects.len(), 1, "{b2_rects:?}");
2392    assert_eq!(b2_rects[0].rect.origin, euclid::point2(200., 200.));
2393
2394    // An element inside the component's definition maps to both uses.
2395    let def_rects = handle.element_positions(&element_at("Rectangle {\n    width: 50px"));
2396    assert_eq!(def_rects.len(), 2, "{def_rects:?}");
2397
2398    // A repeated element yields one rect per row, in root coordinates.
2399    let repeated = element_at("Rectangle {\n        x: xo");
2400    let mut row_rects = handle.element_positions(&repeated);
2401    row_rects.sort_by(|a, b| a.rect.origin.x.total_cmp(&b.rect.origin.x));
2402    assert_eq!(row_rects.len(), 3, "{row_rects:?}");
2403    for (i, r) in row_rects.iter().enumerate() {
2404        assert_eq!(r.rect.origin, euclid::point2(i as f32 * 10., 300.));
2405        assert_eq!(r.rect.size, euclid::size2(10., 10.));
2406    }
2407
2408    // component_positions covers the same shapes, and an offset outside any
2409    // element matches nothing.
2410    let offset = code.find("Rectangle {\n        x: xo").unwrap() as u32;
2411    assert_eq!(handle.component_positions(&path, offset).len(), 3);
2412    assert!(handle.component_positions(&path, code.len() as u32 - 1).is_empty());
2413}