Skip to main content

slint_interpreter/
api.rs

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