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