Skip to main content

slint_interpreter/
api.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4// cSpell: ignore theproperty underscoresanddashespreserved xreadonly
5use 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    /// Return the value for a public property of this component.
1414    ///
1415    /// ## Examples
1416    ///
1417    /// ```
1418    /// # i_slint_backend_testing::init_no_event_loop();
1419    /// use slint_interpreter::{ComponentDefinition, Compiler, Value, SharedString};
1420    /// let code = r#"
1421    ///     export component MyWin inherits Window {
1422    ///         in-out property <int> my_property: 42;
1423    ///     }
1424    /// "#;
1425    /// let mut compiler = Compiler::default();
1426    /// let result = spin_on::spin_on(
1427    ///     compiler.build_from_source(code.into(), Default::default()));
1428    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1429    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1430    /// assert_eq!(instance.get_property("my_property").unwrap(), Value::from(42));
1431    /// ```
1432    pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1433        generativity::make_guard!(guard);
1434        let comp = self.inner.unerase(guard);
1435        let name = normalize_identifier(name);
1436
1437        if comp
1438            .description()
1439            .original
1440            .root_element
1441            .borrow()
1442            .property_declarations
1443            .get(&name)
1444            .is_none_or(|d| !d.expose_in_public_api)
1445        {
1446            return Err(GetPropertyError::NoSuchProperty);
1447        }
1448
1449        comp.description()
1450            .get_property(comp.borrow(), &name)
1451            .map_err(|()| GetPropertyError::NoSuchProperty)
1452    }
1453
1454    /// Set the value for a public property of this component.
1455    pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1456        let name = normalize_identifier(name);
1457        generativity::make_guard!(guard);
1458        let comp = self.inner.unerase(guard);
1459        let d = comp.description();
1460        let elem = d.original.root_element.borrow();
1461        let decl = elem.property_declarations.get(&name).ok_or(SetPropertyError::NoSuchProperty)?;
1462
1463        if !decl.expose_in_public_api {
1464            return Err(SetPropertyError::NoSuchProperty);
1465        } else if decl.visibility == i_slint_compiler::object_tree::PropertyVisibility::Output {
1466            return Err(SetPropertyError::AccessDenied);
1467        }
1468
1469        d.set_property(comp.borrow(), &name, value)
1470    }
1471
1472    /// Set a handler for the callback with the given name. A callback with that
1473    /// name must be defined in the document otherwise an error will be returned.
1474    ///
1475    /// Note: Since the [`ComponentInstance`] holds the handler, the handler itself should not
1476    /// contain a strong reference to the instance. So if you need to capture the instance,
1477    /// you should use [`Self::as_weak`] to create a weak reference.
1478    ///
1479    /// ## Examples
1480    ///
1481    /// ```
1482    /// # i_slint_backend_testing::init_no_event_loop();
1483    /// use slint_interpreter::{Compiler, Value, SharedString, ComponentHandle};
1484    /// use core::convert::TryInto;
1485    /// let code = r#"
1486    ///     export component MyWin inherits Window {
1487    ///         callback foo(int) -> int;
1488    ///         in-out property <int> my_prop: 12;
1489    ///     }
1490    /// "#;
1491    /// let result = spin_on::spin_on(
1492    ///     Compiler::default().build_from_source(code.into(), Default::default()));
1493    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1494    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1495    /// let instance_weak = instance.as_weak();
1496    /// instance.set_callback("foo", move |args: &[Value]| -> Value {
1497    ///     let arg: u32 = args[0].clone().try_into().unwrap();
1498    ///     let my_prop = instance_weak.unwrap().get_property("my_prop").unwrap();
1499    ///     let my_prop : u32 = my_prop.try_into().unwrap();
1500    ///     Value::from(arg + my_prop)
1501    /// }).unwrap();
1502    ///
1503    /// let res = instance.invoke("foo", &[Value::from(500)]).unwrap();
1504    /// assert_eq!(res, Value::from(500+12));
1505    /// ```
1506    pub fn set_callback(
1507        &self,
1508        name: &str,
1509        callback: impl Fn(&[Value]) -> Value + 'static,
1510    ) -> Result<(), SetCallbackError> {
1511        generativity::make_guard!(guard);
1512        let comp = self.inner.unerase(guard);
1513        comp.description()
1514            .set_callback_handler(comp.borrow(), &normalize_identifier(name), Box::new(callback))
1515            .map_err(|()| SetCallbackError::NoSuchCallback)
1516    }
1517
1518    /// Call the given callback or function with the arguments
1519    ///
1520    /// ## Examples
1521    /// See the documentation of [`Self::set_callback`] for an example
1522    pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1523        generativity::make_guard!(guard);
1524        let comp = self.inner.unerase(guard);
1525        comp.description()
1526            .invoke(comp.borrow(), &normalize_identifier(name), args)
1527            .map_err(|()| InvokeError::NoSuchCallable)
1528    }
1529
1530    /// Return the value for a property within an exported global singleton used by this component.
1531    ///
1532    /// The `global` parameter is the exported name of the global singleton. The `property` argument
1533    /// is the name of the property
1534    ///
1535    /// ## Examples
1536    ///
1537    /// ```
1538    /// # i_slint_backend_testing::init_no_event_loop();
1539    /// use slint_interpreter::{Compiler, Value, SharedString};
1540    /// let code = r#"
1541    ///     global Glob {
1542    ///         in-out property <int> my_property: 42;
1543    ///     }
1544    ///     export { Glob as TheGlobal }
1545    ///     export component MyWin inherits Window {
1546    ///     }
1547    /// "#;
1548    /// let mut compiler = Compiler::default();
1549    /// let result = spin_on::spin_on(compiler.build_from_source(code.into(), Default::default()));
1550    /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::<Vec<_>>());
1551    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1552    /// assert_eq!(instance.get_global_property("TheGlobal", "my_property").unwrap(), Value::from(42));
1553    /// ```
1554    pub fn get_global_property(
1555        &self,
1556        global: &str,
1557        property: &str,
1558    ) -> Result<Value, GetPropertyError> {
1559        generativity::make_guard!(guard);
1560        let comp = self.inner.unerase(guard);
1561        comp.description()
1562            .get_global(comp.borrow(), &normalize_identifier(global))
1563            .map_err(|()| GetPropertyError::NoSuchProperty)? // FIXME: should there be a NoSuchGlobal error?
1564            .as_ref()
1565            .get_property(&normalize_identifier(property))
1566            .map_err(|()| GetPropertyError::NoSuchProperty)
1567    }
1568
1569    /// Set the value for a property within an exported global singleton used by this component.
1570    pub fn set_global_property(
1571        &self,
1572        global: &str,
1573        property: &str,
1574        value: Value,
1575    ) -> Result<(), SetPropertyError> {
1576        generativity::make_guard!(guard);
1577        let comp = self.inner.unerase(guard);
1578        comp.description()
1579            .get_global(comp.borrow(), &normalize_identifier(global))
1580            .map_err(|()| SetPropertyError::NoSuchProperty)? // FIXME: should there be a NoSuchGlobal error?
1581            .as_ref()
1582            .set_property(&normalize_identifier(property), value)
1583    }
1584
1585    /// Set a handler for the callback in the exported global singleton. A callback with that
1586    /// name must be defined in the specified global and the global must be exported from the
1587    /// main document otherwise an error will be returned.
1588    ///
1589    /// ## Examples
1590    ///
1591    /// ```
1592    /// # i_slint_backend_testing::init_no_event_loop();
1593    /// use slint_interpreter::{Compiler, Value, SharedString};
1594    /// use core::convert::TryInto;
1595    /// let code = r#"
1596    ///     export global Logic {
1597    ///         pure callback to_uppercase(string) -> string;
1598    ///     }
1599    ///     export component MyWin inherits Window {
1600    ///         out property <string> hello: Logic.to_uppercase("world");
1601    ///     }
1602    /// "#;
1603    /// let result = spin_on::spin_on(
1604    ///     Compiler::default().build_from_source(code.into(), Default::default()));
1605    /// let instance = result.component("MyWin").unwrap().create().unwrap();
1606    /// instance.set_global_callback("Logic", "to_uppercase", |args: &[Value]| -> Value {
1607    ///     let arg: SharedString = args[0].clone().try_into().unwrap();
1608    ///     Value::from(SharedString::from(arg.to_uppercase()))
1609    /// }).unwrap();
1610    ///
1611    /// let res = instance.get_property("hello").unwrap();
1612    /// assert_eq!(res, Value::from(SharedString::from("WORLD")));
1613    ///
1614    /// let abc = instance.invoke_global("Logic", "to_uppercase", &[
1615    ///     SharedString::from("abc").into()
1616    /// ]).unwrap();
1617    /// assert_eq!(abc, Value::from(SharedString::from("ABC")));
1618    /// ```
1619    pub fn set_global_callback(
1620        &self,
1621        global: &str,
1622        name: &str,
1623        callback: impl Fn(&[Value]) -> Value + 'static,
1624    ) -> Result<(), SetCallbackError> {
1625        generativity::make_guard!(guard);
1626        let comp = self.inner.unerase(guard);
1627        comp.description()
1628            .get_global(comp.borrow(), &normalize_identifier(global))
1629            .map_err(|()| SetCallbackError::NoSuchCallback)? // FIXME: should there be a NoSuchGlobal error?
1630            .as_ref()
1631            .set_callback_handler(&normalize_identifier(name), Box::new(callback))
1632            .map_err(|()| SetCallbackError::NoSuchCallback)
1633    }
1634
1635    /// Call the given callback or function within a global singleton with the arguments
1636    ///
1637    /// ## Examples
1638    /// See the documentation of [`Self::set_global_callback`] for an example
1639    pub fn invoke_global(
1640        &self,
1641        global: &str,
1642        callable_name: &str,
1643        args: &[Value],
1644    ) -> Result<Value, InvokeError> {
1645        generativity::make_guard!(guard);
1646        let comp = self.inner.unerase(guard);
1647        let g = comp
1648            .description()
1649            .get_global(comp.borrow(), &normalize_identifier(global))
1650            .map_err(|()| InvokeError::NoSuchCallable)?; // FIXME: should there be a NoSuchGlobal error?
1651        let callable_name = normalize_identifier(callable_name);
1652        if matches!(
1653            comp.description()
1654                .original
1655                .root_element
1656                .borrow()
1657                .lookup_property(&callable_name)
1658                .property_type,
1659            LangType::Function { .. }
1660        ) {
1661            g.as_ref()
1662                .eval_function(&callable_name, args.to_vec())
1663                .map_err(|()| InvokeError::NoSuchCallable)
1664        } else {
1665            g.as_ref()
1666                .invoke_callback(&callable_name, args)
1667                .map_err(|()| InvokeError::NoSuchCallable)
1668        }
1669    }
1670
1671    /// Find all positions of the components which are pointed by a given source location.
1672    ///
1673    /// WARNING: this is not part of the public API
1674    #[cfg(feature = "internal-highlight")]
1675    pub fn component_positions(
1676        &self,
1677        path: &Path,
1678        offset: u32,
1679    ) -> Vec<crate::highlight::HighlightedRect> {
1680        crate::highlight::component_positions(&self.inner, path, offset)
1681    }
1682
1683    /// Find the position of the `element`.
1684    ///
1685    /// WARNING: this is not part of the public API
1686    #[cfg(feature = "internal-highlight")]
1687    pub fn element_positions(
1688        &self,
1689        element: &i_slint_compiler::object_tree::ElementRc,
1690    ) -> Vec<crate::highlight::HighlightedRect> {
1691        crate::highlight::element_positions(
1692            &self.inner,
1693            element,
1694            crate::highlight::ElementPositionFilter::IncludeClipped,
1695        )
1696    }
1697
1698    /// Find the `element` that was defined at the text position.
1699    ///
1700    /// WARNING: this is not part of the public API
1701    #[cfg(feature = "internal-highlight")]
1702    pub fn element_node_at_source_code_position(
1703        &self,
1704        path: &Path,
1705        offset: u32,
1706    ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1707        crate::highlight::element_node_at_source_code_position(&self.inner, path, offset)
1708    }
1709}
1710
1711impl StrongHandle for ComponentInstance {
1712    type WeakInner = vtable::VWeak<ItemTreeVTable, crate::dynamic_item_tree::ErasedItemTreeBox>;
1713
1714    fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1715        Some(Self { inner: inner.upgrade()? })
1716    }
1717}
1718
1719impl ComponentHandle for ComponentInstance {
1720    fn as_weak(&self) -> Weak<Self>
1721    where
1722        Self: Sized,
1723    {
1724        Weak::new(vtable::VRc::downgrade(&self.inner))
1725    }
1726
1727    fn clone_strong(&self) -> Self {
1728        Self { inner: self.inner.clone() }
1729    }
1730
1731    fn show(&self) -> Result<(), PlatformError> {
1732        if self.is_system_tray_rooted() {
1733            // Mirror what the Rust/C++ generators emit for tray-rooted public
1734            // components: toggle the `visible` property; the change-tracker on
1735            // the SystemTrayIcon native item dispatches to the platform handle.
1736            self.set_property("visible", Value::Bool(true)).expect(
1737                "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1738            );
1739            return Ok(());
1740        }
1741        self.inner.window_adapter_ref()?.window().show()
1742    }
1743
1744    fn hide(&self) -> Result<(), PlatformError> {
1745        if self.is_system_tray_rooted() {
1746            self.set_property("visible", Value::Bool(false)).expect(
1747                "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1748            );
1749            return Ok(());
1750        }
1751        self.inner.window_adapter_ref()?.window().hide()
1752    }
1753
1754    fn run(&self) -> Result<(), PlatformError> {
1755        self.show()?;
1756        run_event_loop()?;
1757        self.hide()
1758    }
1759
1760    fn window(&self) -> &Window {
1761        self.inner.window_adapter_ref().unwrap().window()
1762    }
1763
1764    fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1765    where
1766        Self: Sized,
1767    {
1768        unreachable!()
1769    }
1770}
1771
1772impl From<ComponentInstance>
1773    for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, ErasedItemTreeBox>
1774{
1775    fn from(value: ComponentInstance) -> Self {
1776        value.inner
1777    }
1778}
1779
1780/// Error returned by [`ComponentInstance::get_property`]
1781#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1782#[non_exhaustive]
1783pub enum GetPropertyError {
1784    /// There is no property with the given name
1785    #[display("no such property")]
1786    NoSuchProperty,
1787}
1788
1789/// Error returned by [`ComponentInstance::set_property`]
1790#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1791#[non_exhaustive]
1792pub enum SetPropertyError {
1793    /// There is no property with the given name.
1794    #[display("no such property")]
1795    NoSuchProperty,
1796    /// The property exists but does not have a type matching the dynamic value.
1797    ///
1798    /// This happens for example when assigning a source struct value to a target
1799    /// struct property, where the source doesn't have all the fields the target struct
1800    /// requires.
1801    #[display("wrong type")]
1802    WrongType,
1803    /// Attempt to set an output property.
1804    #[display("access denied")]
1805    AccessDenied,
1806}
1807
1808/// Error returned by [`ComponentInstance::set_callback`]
1809#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1810#[non_exhaustive]
1811pub enum SetCallbackError {
1812    /// There is no callback with the given name
1813    #[display("no such callback")]
1814    NoSuchCallback,
1815}
1816
1817/// Error returned by [`ComponentInstance::invoke`]
1818#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1819#[non_exhaustive]
1820pub enum InvokeError {
1821    /// There is no callback or function with the given name
1822    #[display("no such callback or function")]
1823    NoSuchCallable,
1824}
1825
1826/// Enters the main event loop. This is necessary in order to receive
1827/// events from the windowing system in order to render to the screen
1828/// and react to user input.
1829pub fn run_event_loop() -> Result<(), PlatformError> {
1830    i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1831}
1832
1833/// Spawns a [`Future`] to execute in the Slint event loop.
1834///
1835/// See the documentation of `slint::spawn_local()` for more info
1836pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1837    i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1838        .map_err(|_| EventLoopError::NoEventLoopProvider)?
1839}
1840
1841#[test]
1842fn component_definition_properties() {
1843    i_slint_backend_testing::init_no_event_loop();
1844    let mut compiler = Compiler::default();
1845    compiler.set_style("fluent".into());
1846    let comp_def = spin_on::spin_on(
1847        compiler.build_from_source(
1848            r#"
1849    export component Dummy {
1850        in-out property <string> test;
1851        in-out property <int> underscores-and-dashes_preserved: 44;
1852        callback hello;
1853    }"#
1854            .into(),
1855            "".into(),
1856        ),
1857    )
1858    .component("Dummy")
1859    .unwrap();
1860
1861    let props = comp_def.properties().collect::<Vec<(_, _)>>();
1862
1863    assert_eq!(props.len(), 2);
1864    assert_eq!(props[0].0, "test");
1865    assert_eq!(props[0].1, ValueType::String);
1866    assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1867    assert_eq!(props[1].1, ValueType::Number);
1868
1869    let instance = comp_def.create().unwrap();
1870    assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1871    assert_eq!(
1872        instance.get_property("underscoresanddashespreserved"),
1873        Err(GetPropertyError::NoSuchProperty)
1874    );
1875    assert_eq!(
1876        instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1877        Ok(())
1878    );
1879    assert_eq!(
1880        instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1881        Err(SetPropertyError::NoSuchProperty)
1882    );
1883    assert_eq!(
1884        instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1885        Err(SetPropertyError::WrongType)
1886    );
1887    assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1888}
1889
1890#[test]
1891fn component_definition_properties2() {
1892    i_slint_backend_testing::init_no_event_loop();
1893    let mut compiler = Compiler::default();
1894    compiler.set_style("fluent".into());
1895    let comp_def = spin_on::spin_on(
1896        compiler.build_from_source(
1897            r#"
1898    export component Dummy {
1899        in-out property <string> sub-text <=> sub.text;
1900        sub := Text { property <int> private-not-exported; }
1901        out property <string> xreadonly: "the value";
1902        private property <string> xx: sub.text;
1903        callback hello;
1904    }"#
1905            .into(),
1906            "".into(),
1907        ),
1908    )
1909    .component("Dummy")
1910    .unwrap();
1911
1912    let props = comp_def.properties().collect::<Vec<(_, _)>>();
1913
1914    assert_eq!(props.len(), 2);
1915    assert_eq!(props[0].0, "sub-text");
1916    assert_eq!(props[0].1, ValueType::String);
1917    assert_eq!(props[1].0, "xreadonly");
1918
1919    let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1920    assert_eq!(callbacks.len(), 1);
1921    assert_eq!(callbacks[0], "hello");
1922
1923    let instance = comp_def.create().unwrap();
1924    assert_eq!(
1925        instance.set_property("xreadonly", SharedString::from("XXX").into()),
1926        Err(SetPropertyError::AccessDenied)
1927    );
1928    assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1929    assert_eq!(
1930        instance.set_property("xx", SharedString::from("XXX").into()),
1931        Err(SetPropertyError::NoSuchProperty)
1932    );
1933    assert_eq!(
1934        instance.set_property("background", Value::default()),
1935        Err(SetPropertyError::NoSuchProperty)
1936    );
1937
1938    assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1939    assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1940}
1941
1942#[test]
1943fn globals() {
1944    i_slint_backend_testing::init_no_event_loop();
1945    let mut compiler = Compiler::default();
1946    compiler.set_style("fluent".into());
1947    let definition = spin_on::spin_on(
1948        compiler.build_from_source(
1949            r#"
1950    export global My-Super_Global {
1951        in-out property <int> the-property : 21;
1952        callback my-callback();
1953    }
1954    export { My-Super_Global as AliasedGlobal }
1955    export component Dummy {
1956        callback alias <=> My-Super_Global.my-callback;
1957    }"#
1958            .into(),
1959            "".into(),
1960        ),
1961    )
1962    .component("Dummy")
1963    .unwrap();
1964
1965    assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1966
1967    assert!(definition.global_properties("not-there").is_none());
1968    {
1969        let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1970        let expected_callbacks = vec!["my-callback".to_string()];
1971
1972        let assert_properties_and_callbacks = |global_name| {
1973            assert_eq!(
1974                definition
1975                    .global_properties(global_name)
1976                    .map(|props| props.collect::<Vec<_>>())
1977                    .as_ref(),
1978                Some(&expected_properties)
1979            );
1980            assert_eq!(
1981                definition
1982                    .global_callbacks(global_name)
1983                    .map(|props| props.collect::<Vec<_>>())
1984                    .as_ref(),
1985                Some(&expected_callbacks)
1986            );
1987        };
1988
1989        assert_properties_and_callbacks("My-Super-Global");
1990        assert_properties_and_callbacks("My_Super-Global");
1991        assert_properties_and_callbacks("AliasedGlobal");
1992    }
1993
1994    let instance = definition.create().unwrap();
1995    assert_eq!(
1996        instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
1997        Ok(())
1998    );
1999    assert_eq!(
2000        instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2001        Ok(())
2002    );
2003    assert_eq!(
2004        instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2005        Err(SetPropertyError::NoSuchProperty)
2006    );
2007
2008    assert_eq!(
2009        instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2010        Err(SetPropertyError::NoSuchProperty)
2011    );
2012    assert_eq!(
2013        instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2014        Err(SetPropertyError::NoSuchProperty)
2015    );
2016    assert_eq!(
2017        instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2018        Err(SetPropertyError::WrongType)
2019    );
2020    assert_eq!(
2021        instance.get_global_property("My-Super_Global", "yoyo"),
2022        Err(GetPropertyError::NoSuchProperty)
2023    );
2024    assert_eq!(
2025        instance.get_global_property("My-Super_Global", "the-property"),
2026        Ok(Value::Number(44.))
2027    );
2028
2029    assert_eq!(
2030        instance.set_property("the-property", Value::Void),
2031        Err(SetPropertyError::NoSuchProperty)
2032    );
2033    assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2034
2035    assert_eq!(
2036        instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2037        Err(SetCallbackError::NoSuchCallback)
2038    );
2039    assert_eq!(
2040        instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2041        Err(SetCallbackError::NoSuchCallback)
2042    );
2043    assert_eq!(
2044        instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2045        Err(SetCallbackError::NoSuchCallback)
2046    );
2047
2048    assert_eq!(
2049        instance.invoke_global("DontExist", "the-property", &[]),
2050        Err(InvokeError::NoSuchCallable)
2051    );
2052    assert_eq!(
2053        instance.invoke_global("My_Super_Global", "the-property", &[]),
2054        Err(InvokeError::NoSuchCallable)
2055    );
2056    assert_eq!(
2057        instance.invoke_global("My_Super_Global", "yoyo", &[]),
2058        Err(InvokeError::NoSuchCallable)
2059    );
2060
2061    // Alias to global don't crash (#8238)
2062    assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2063}
2064
2065#[test]
2066fn call_functions() {
2067    i_slint_backend_testing::init_no_event_loop();
2068    let mut compiler = Compiler::default();
2069    compiler.set_style("fluent".into());
2070    let definition = spin_on::spin_on(
2071        compiler.build_from_source(
2072            r#"
2073    export global Gl {
2074        out property<string> q;
2075        public function foo-bar(a-a: string, b-b:int) -> string {
2076            q = a-a;
2077            return a-a + b-b;
2078        }
2079    }
2080    export component Test {
2081        out property<int> p;
2082        public function foo-bar(a: int, b:int) -> int {
2083            p = a;
2084            return a + b;
2085        }
2086    }"#
2087            .into(),
2088            "".into(),
2089        ),
2090    )
2091    .component("Test")
2092    .unwrap();
2093
2094    assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2095    assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2096
2097    let instance = definition.create().unwrap();
2098
2099    assert_eq!(
2100        instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2101        Ok(Value::Number(7.))
2102    );
2103    assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2104    assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2105
2106    assert_eq!(
2107        instance.invoke_global(
2108            "Gl",
2109            "foo_bar",
2110            &[Value::String("Hello".into()), Value::Number(10.)]
2111        ),
2112        Ok(Value::String("Hello10".into()))
2113    );
2114    assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2115}
2116
2117#[test]
2118fn component_definition_struct_properties() {
2119    i_slint_backend_testing::init_no_event_loop();
2120    let mut compiler = Compiler::default();
2121    compiler.set_style("fluent".into());
2122    let comp_def = spin_on::spin_on(
2123        compiler.build_from_source(
2124            r#"
2125    export struct Settings {
2126        string_value: string,
2127    }
2128    export component Dummy {
2129        in-out property <Settings> test;
2130    }"#
2131            .into(),
2132            "".into(),
2133        ),
2134    )
2135    .component("Dummy")
2136    .unwrap();
2137
2138    let props = comp_def.properties().collect::<Vec<(_, _)>>();
2139
2140    assert_eq!(props.len(), 1);
2141    assert_eq!(props[0].0, "test");
2142    assert_eq!(props[0].1, ValueType::Struct);
2143
2144    let instance = comp_def.create().unwrap();
2145
2146    let valid_struct: Struct =
2147        [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2148
2149    assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2150    assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2151
2152    assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2153
2154    let mut invalid_struct = valid_struct.clone();
2155    invalid_struct.set_field("other".into(), Value::Number(44.));
2156    assert_eq!(
2157        instance.set_property("test", Value::Struct(invalid_struct)),
2158        Err(SetPropertyError::WrongType)
2159    );
2160    let mut invalid_struct = valid_struct;
2161    invalid_struct.set_field("string_value".into(), Value::Number(44.));
2162    assert_eq!(
2163        instance.set_property("test", Value::Struct(invalid_struct)),
2164        Err(SetPropertyError::WrongType)
2165    );
2166}
2167
2168#[test]
2169fn component_definition_model_properties() {
2170    use i_slint_core::model::*;
2171    i_slint_backend_testing::init_no_event_loop();
2172    let mut compiler = Compiler::default();
2173    compiler.set_style("fluent".into());
2174    let comp_def = spin_on::spin_on(compiler.build_from_source(
2175        "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2176        "".into(),
2177    ))
2178    .component("Dummy")
2179    .unwrap();
2180
2181    let props = comp_def.properties().collect::<Vec<(_, _)>>();
2182    assert_eq!(props.len(), 1);
2183    assert_eq!(props[0].0, "prop");
2184    assert_eq!(props[0].1, ValueType::Model);
2185
2186    let instance = comp_def.create().unwrap();
2187
2188    let int_model =
2189        Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2190    let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2191    let model_with_string = Value::Model(VecModel::from_slice(&[
2192        Value::Number(1000.),
2193        Value::String("foo".into()),
2194        Value::Number(1111.),
2195    ]));
2196
2197    #[track_caller]
2198    fn check_model(val: Value, r: &[f64]) {
2199        if let Value::Model(m) = val {
2200            assert_eq!(r.len(), m.row_count());
2201            for (i, v) in r.iter().enumerate() {
2202                assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2203            }
2204        } else {
2205            panic!("{val:?} not a model");
2206        }
2207    }
2208
2209    assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2210    check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2211
2212    instance.set_property("prop", int_model).unwrap();
2213    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2214
2215    assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2216    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2217    assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2218    check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2219
2220    assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2221    check_model(instance.get_property("prop").unwrap(), &[]);
2222}
2223
2224#[test]
2225fn lang_type_to_value_type() {
2226    use i_slint_compiler::langtype::Struct as LangStruct;
2227    use std::collections::BTreeMap;
2228
2229    assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2230    assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2231    assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2232    assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2233    assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2234    assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2235    assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2236    assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2237    assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2238    assert_eq!(ValueType::from(LangType::String), ValueType::String);
2239    assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2240    assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2241    assert_eq!(ValueType::from(LangType::Array(Rc::new(LangType::Void))), ValueType::Model);
2242    assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2243    assert_eq!(
2244        ValueType::from(LangType::Struct(Rc::new(LangStruct::new(
2245            BTreeMap::default(),
2246            i_slint_compiler::langtype::StructName::None
2247        )))),
2248        ValueType::Struct
2249    );
2250    assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2251}
2252
2253#[test]
2254fn test_multi_components() {
2255    i_slint_backend_testing::init_no_event_loop();
2256    let result = spin_on::spin_on(
2257        Compiler::default().build_from_source(
2258            r#"
2259        export struct Settings {
2260            string_value: string,
2261        }
2262        export global ExpGlo { in-out property <int> test: 42; }
2263        component Common {
2264            in-out property <Settings> settings: { string_value: "Hello", };
2265        }
2266        export component Xyz inherits Window {
2267            in-out property <int> aaa: 8;
2268        }
2269        export component Foo {
2270
2271            in-out property <int> test: 42;
2272            c := Common {}
2273        }
2274        export component Bar inherits Window {
2275            in-out property <int> blah: 78;
2276            c := Common {}
2277        }
2278        "#
2279            .into(),
2280            PathBuf::from("hello.slint"),
2281        ),
2282    );
2283
2284    assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2285    let mut components = result.component_names().collect::<Vec<_>>();
2286    components.sort();
2287    assert_eq!(components, vec!["Bar", "Xyz"]);
2288    let diag = result.diagnostics().collect::<Vec<_>>();
2289    assert_eq!(diag.len(), 1);
2290    assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2291    assert_eq!(
2292        diag[0].message(),
2293        "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2294    );
2295
2296    let comp1 = result.component("Xyz").unwrap();
2297    assert_eq!(comp1.name(), "Xyz");
2298    let instance1a = comp1.create().unwrap();
2299    let comp2 = result.component("Bar").unwrap();
2300    let instance2 = comp2.create().unwrap();
2301    let instance1b = comp1.create().unwrap();
2302
2303    // globals are not shared between instances
2304    assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2305    assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2306    assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2307    assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2308    assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2309
2310    assert!(result.component("Settings").is_none());
2311    assert!(result.component("Foo").is_none());
2312    assert!(result.component("Common").is_none());
2313    assert!(result.component("ExpGlo").is_none());
2314    assert!(result.component("xyz").is_none());
2315}
2316
2317#[cfg(all(test, feature = "internal-highlight"))]
2318fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2319    i_slint_backend_testing::init_no_event_loop();
2320    let mut compiler = Compiler::default();
2321    compiler.set_style("fluent".into());
2322    let path = PathBuf::from("/tmp/test.slint");
2323
2324    let compile_result =
2325        spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2326
2327    for d in &compile_result.diagnostics {
2328        eprintln!("{d}");
2329    }
2330
2331    assert!(!compile_result.has_errors());
2332
2333    let definition = compile_result.components().next().unwrap();
2334    let instance = definition.create().unwrap();
2335
2336    (instance, path)
2337}
2338
2339#[cfg(feature = "internal-highlight")]
2340#[test]
2341fn test_element_node_at_source_code_position() {
2342    let code = r#"
2343component Bar1 {}
2344
2345component Foo1 {
2346}
2347
2348export component Foo2 inherits Window  {
2349    Bar1 {}
2350    Foo1   {}
2351}"#;
2352
2353    let (handle, path) = compile(code);
2354
2355    for i in 0..code.len() as u32 {
2356        let elements = handle.element_node_at_source_code_position(&path, i);
2357        eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2358        match i {
2359            16 => assert_eq!(elements.len(), 1),       // Bar1 (def)
2360            35 => assert_eq!(elements.len(), 1),       // Foo1 (def)
2361            71..=78 => assert_eq!(elements.len(), 1),  // Window + WS (from Foo2)
2362            85..=89 => assert_eq!(elements.len(), 1),  // Bar1 + WS (use)
2363            97..=103 => assert_eq!(elements.len(), 1), // Foo1 + WS (use)
2364            _ => assert!(elements.is_empty()),
2365        }
2366    }
2367}