Skip to main content

slint_interpreter/
api.rs

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