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