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