1use crate::dynamic_item_tree::{ErasedItemTreeBox, WindowOptions};
6use i_slint_compiler::langtype::Type as LangType;
7use i_slint_core::PathData;
8use i_slint_core::component_factory::ComponentFactory;
9#[cfg(feature = "internal")]
10use i_slint_core::component_factory::FactoryContext;
11use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
12use i_slint_core::items::*;
13use i_slint_core::model::{Model, ModelExt, ModelRc};
14use i_slint_core::styled_text::StyledText;
15#[cfg(feature = "internal")]
16use i_slint_core::window::WindowInner;
17use smol_str::SmolStr;
18use std::collections::HashMap;
19use std::future::Future;
20use std::path::{Path, PathBuf};
21use std::rc::Rc;
22
23#[doc(inline)]
24pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
25
26pub use i_slint_backend_selector::api::*;
27pub use i_slint_core::api::*;
28
29pub use i_slint_compiler::DefaultTranslationContext;
32
33#[derive(Debug, Copy, Clone, PartialEq)]
36#[repr(i8)]
37#[non_exhaustive]
38pub enum ValueType {
39 Void,
41 Number,
43 String,
45 Bool,
47 Model,
49 Struct,
51 Brush,
53 Image,
55 #[doc(hidden)]
57 Other = -1,
58}
59
60impl From<LangType> for ValueType {
61 fn from(ty: LangType) -> Self {
62 match ty {
63 LangType::Float32
64 | LangType::Int32
65 | LangType::Duration
66 | LangType::Angle
67 | LangType::PhysicalLength
68 | LangType::LogicalLength
69 | LangType::Percent
70 | LangType::UnitProduct(_) => Self::Number,
71 LangType::String => Self::String,
72 LangType::Color => Self::Brush,
73 LangType::Brush => Self::Brush,
74 LangType::Array(_) => Self::Model,
75 LangType::Bool => Self::Bool,
76 LangType::Struct { .. } => Self::Struct,
77 LangType::Void => Self::Void,
78 LangType::Image => Self::Image,
79 _ => Self::Other,
80 }
81 }
82}
83
84#[derive(Clone, Default)]
96#[non_exhaustive]
97#[repr(u8)]
98pub enum Value {
99 #[default]
102 Void = 0,
103 Number(f64) = 1,
105 String(SharedString) = 2,
107 Bool(bool) = 3,
109 Image(Image) = 4,
111 Model(ModelRc<Value>) = 5,
113 Struct(Struct) = 6,
115 Brush(Brush) = 7,
117 #[doc(hidden)]
118 PathData(PathData) = 8,
120 #[doc(hidden)]
121 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
123 #[doc(hidden)]
124 EnumerationValue(String, String) = 10,
127 #[doc(hidden)]
128 LayoutCache(SharedVector<f32>) = 11,
129 #[doc(hidden)]
130 ComponentFactory(ComponentFactory) = 12,
132 #[doc(hidden)] StyledText(StyledText) = 13,
135 #[doc(hidden)]
136 ArrayOfU16(SharedVector<u16>) = 14,
137 Keys(Keys) = 15,
139 DataTransfer(DataTransfer) = 16,
141 #[doc(hidden)]
142 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
144}
145
146impl Value {
147 pub fn value_type(&self) -> ValueType {
149 match self {
150 Value::Void => ValueType::Void,
151 Value::Number(_) => ValueType::Number,
152 Value::String(_) => ValueType::String,
153 Value::Bool(_) => ValueType::Bool,
154 Value::Model(_) => ValueType::Model,
155 Value::Struct(_) => ValueType::Struct,
156 Value::Brush(_) => ValueType::Brush,
157 Value::Image(_) => ValueType::Image,
158 _ => ValueType::Other,
159 }
160 }
161}
162
163impl PartialEq for Value {
164 fn eq(&self, other: &Self) -> bool {
165 match self {
166 Value::Void => matches!(other, Value::Void),
167 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
168 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
169 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
170 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
171 Value::Model(lhs) => {
172 if let Value::Model(rhs) = other {
173 lhs == rhs
174 } else {
175 false
176 }
177 }
178 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
179 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
180 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
181 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
182 Value::EnumerationValue(lhs_name, lhs_value) => {
183 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
184 }
185 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
186 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
187 Value::ComponentFactory(lhs) => {
188 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
189 }
190 Value::StyledText(lhs) => {
191 matches!(other, Value::StyledText(rhs) if lhs == rhs)
192 }
193 Value::Keys(lhs) => {
194 matches!(other, Value::Keys(rhs) if lhs == rhs)
195 }
196 Value::DataTransfer(lhs) => {
197 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
198 }
199 Value::MouseCursorInner(lhs) => {
200 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
201 }
202 }
203 }
204}
205
206impl std::fmt::Debug for Value {
207 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 match self {
209 Value::Void => write!(f, "Value::Void"),
210 Value::Number(n) => write!(f, "Value::Number({n:?})"),
211 Value::String(s) => write!(f, "Value::String({s:?})"),
212 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
213 Value::Image(i) => write!(f, "Value::Image({i:?})"),
214 Value::Model(m) => {
215 write!(f, "Value::Model(")?;
216 f.debug_list().entries(m.iter()).finish()?;
217 write!(f, "])")
218 }
219 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
220 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
221 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
222 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
223 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
224 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
225 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
226 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
227 Value::ArrayOfU16(data) => {
228 write!(f, "Value::ArrayOfU16({data:?})")
229 }
230 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
231 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
232 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
233 }
234 }
235}
236
237macro_rules! declare_value_conversion {
246 ( $value:ident => [$($ty:ty),*] ) => {
247 $(
248 impl From<$ty> for Value {
249 fn from(v: $ty) -> Self {
250 Value::$value(v as _)
251 }
252 }
253 impl TryFrom<Value> for $ty {
254 type Error = Value;
255 fn try_from(v: Value) -> Result<$ty, Self::Error> {
256 match v {
257 Value::$value(x) => Ok(x as _),
258 _ => Err(v)
259 }
260 }
261 }
262 )*
263 };
264}
265declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
266declare_value_conversion!(String => [SharedString] );
267declare_value_conversion!(Bool => [bool] );
268declare_value_conversion!(Image => [Image] );
269declare_value_conversion!(Struct => [Struct] );
270declare_value_conversion!(Brush => [Brush] );
271declare_value_conversion!(PathData => [PathData]);
272declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
273declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
274declare_value_conversion!(ComponentFactory => [ComponentFactory] );
275declare_value_conversion!(StyledText => [StyledText] );
276declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
277declare_value_conversion!(Keys => [Keys]);
278declare_value_conversion!(DataTransfer => [DataTransfer]);
279declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
280
281macro_rules! declare_value_struct_conversion {
283 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
284 impl From<$name> for Value {
285 fn from($name { $($field),* , .. }: $name) -> Self {
286 let mut struct_ = Struct::default();
287 $(struct_.set_field(stringify!($field).into(), $field.into());)*
288 Value::Struct(struct_)
289 }
290 }
291 impl TryFrom<Value> for $name {
292 type Error = ();
293 fn try_from(v: Value) -> Result<$name, Self::Error> {
294 #[allow(clippy::field_reassign_with_default)]
295 match v {
296 Value::Struct(x) => {
297 type Ty = $name;
298 #[allow(unused)]
299 let mut res: Ty = Ty::default();
300 $(let mut res: Ty = $extra;)?
301 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
302 Ok(res)
303 }
304 _ => Err(()),
305 }
306 }
307 }
308 };
309 ($(
310 $(#[$struct_attr:meta])*
311 $vis:vis struct $Name:ident {
312 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty, )*
313 }
314 )*) => {
315 $(
316 impl From<$Name> for Value {
317 fn from(item: $Name) -> Self {
318 let mut struct_ = Struct::default();
319 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
320 Value::Struct(struct_)
321 }
322 }
323 impl TryFrom<Value> for $Name {
324 type Error = ();
325 fn try_from(v: Value) -> Result<$Name, Self::Error> {
326 #[allow(clippy::field_reassign_with_default)]
327 match v {
328 Value::Struct(x) => {
329 type Ty = $Name;
330 #[allow(unused)]
331 let mut res: Ty = Ty::default();
332 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
333 Ok(res)
334 }
335 _ => Err(()),
336 }
337 }
338 }
339 )*
340 };
341}
342
343declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
344declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
345declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
346declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
347declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
348
349i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
350
351macro_rules! declare_value_enum_conversion {
356 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
357 impl From<i_slint_core::items::$Name> for Value {
358 fn from(v: i_slint_core::items::$Name) -> Self {
359 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
360 }
361 }
362 impl TryFrom<Value> for i_slint_core::items::$Name {
363 type Error = ();
364 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
365 use std::str::FromStr;
366 match v {
367 Value::EnumerationValue(enumeration, value) => {
368 if enumeration != stringify!($Name) {
369 return Err(());
370 }
371 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
372 }
373 _ => Err(()),
374 }
375 }
376 }
377 )*};
378}
379
380i_slint_common::for_each_enums!(declare_value_enum_conversion);
381
382impl From<i_slint_core::animations::Instant> for Value {
383 fn from(value: i_slint_core::animations::Instant) -> Self {
384 Value::Number(value.0 as _)
385 }
386}
387impl TryFrom<Value> for i_slint_core::animations::Instant {
388 type Error = ();
389 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
390 match v {
391 Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
392 _ => Err(()),
393 }
394 }
395}
396
397impl From<()> for Value {
398 #[inline]
399 fn from(_: ()) -> Self {
400 Value::Void
401 }
402}
403impl TryFrom<Value> for () {
404 type Error = ();
405 #[inline]
406 fn try_from(_: Value) -> Result<(), Self::Error> {
407 Ok(())
408 }
409}
410
411impl From<Color> for Value {
412 #[inline]
413 fn from(c: Color) -> Self {
414 Value::Brush(Brush::SolidColor(c))
415 }
416}
417impl TryFrom<Value> for Color {
418 type Error = Value;
419 #[inline]
420 fn try_from(v: Value) -> Result<Color, Self::Error> {
421 match v {
422 Value::Brush(Brush::SolidColor(c)) => Ok(c),
423 _ => Err(v),
424 }
425 }
426}
427
428impl From<i_slint_core::lengths::LogicalLength> for Value {
429 #[inline]
430 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
431 Value::Number(l.get() as _)
432 }
433}
434impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
435 type Error = Value;
436 #[inline]
437 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
438 match v {
439 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
440 _ => Err(v),
441 }
442 }
443}
444
445impl From<i_slint_core::lengths::LogicalPoint> for Value {
446 #[inline]
447 fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
448 Value::Struct(Struct::from_iter([
449 ("x".to_owned(), Value::Number(pt.x as _)),
450 ("y".to_owned(), Value::Number(pt.y as _)),
451 ]))
452 }
453}
454impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
455 type Error = Value;
456 #[inline]
457 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
458 match v {
459 Value::Struct(s) => {
460 let x = s
461 .get_field("x")
462 .cloned()
463 .unwrap_or_else(|| Value::Number(0 as _))
464 .try_into()?;
465 let y = s
466 .get_field("y")
467 .cloned()
468 .unwrap_or_else(|| Value::Number(0 as _))
469 .try_into()?;
470 Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
471 }
472 _ => Err(v),
473 }
474 }
475}
476
477impl From<i_slint_core::lengths::LogicalSize> for Value {
478 #[inline]
479 fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
480 Value::Struct(Struct::from_iter([
481 ("width".to_owned(), Value::Number(s.width as _)),
482 ("height".to_owned(), Value::Number(s.height as _)),
483 ]))
484 }
485}
486impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
487 type Error = Value;
488 #[inline]
489 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
490 match v {
491 Value::Struct(s) => {
492 let width = s
493 .get_field("width")
494 .cloned()
495 .unwrap_or_else(|| Value::Number(0 as _))
496 .try_into()?;
497 let height = s
498 .get_field("height")
499 .cloned()
500 .unwrap_or_else(|| Value::Number(0 as _))
501 .try_into()?;
502 Ok(i_slint_core::lengths::LogicalSize::new(width, height))
503 }
504 _ => Err(v),
505 }
506 }
507}
508
509impl From<i_slint_core::lengths::LogicalEdges> for Value {
510 #[inline]
511 fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
512 Value::Struct(Struct::from_iter([
513 ("left".to_owned(), Value::Number(s.left as _)),
514 ("right".to_owned(), Value::Number(s.right as _)),
515 ("top".to_owned(), Value::Number(s.top as _)),
516 ("bottom".to_owned(), Value::Number(s.bottom as _)),
517 ]))
518 }
519}
520impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
521 type Error = Value;
522 #[inline]
523 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
524 match v {
525 Value::Struct(s) => {
526 let left = s
527 .get_field("left")
528 .cloned()
529 .unwrap_or_else(|| Value::Number(0 as _))
530 .try_into()?;
531 let right = s
532 .get_field("right")
533 .cloned()
534 .unwrap_or_else(|| Value::Number(0 as _))
535 .try_into()?;
536 let top = s
537 .get_field("top")
538 .cloned()
539 .unwrap_or_else(|| Value::Number(0 as _))
540 .try_into()?;
541 let bottom = s
542 .get_field("bottom")
543 .cloned()
544 .unwrap_or_else(|| Value::Number(0 as _))
545 .try_into()?;
546 Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
547 }
548 _ => Err(v),
549 }
550 }
551}
552
553impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
554 fn from(m: ModelRc<T>) -> Self {
555 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
556 Value::Model(v.clone())
557 } else {
558 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
559 }
560 }
561}
562impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
563 type Error = Value;
564 #[inline]
565 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
566 match v {
567 Value::Model(m) => {
568 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
569 Ok(v.clone())
570 } else if let Some(v) =
571 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
572 {
573 Ok(v.0.clone())
574 } else {
575 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
576 }
577 }
578 _ => Err(v),
579 }
580 }
581}
582
583#[test]
584fn value_model_conversion() {
585 use i_slint_core::model::*;
586 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
587 let v = Value::from(m.clone());
588 assert_eq!(v, Value::Model(m.clone()));
589 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
590 assert_eq!(m2, m);
591
592 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
593 assert_eq!(int_model.row_count(), 2);
594 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
595
596 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
597 assert_eq!(m3.row_count(), 2);
598 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
599
600 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
601 assert_eq!(str_model.row_count(), 2);
602 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
604
605 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
606 assert!(err.is_err());
607
608 let model =
609 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
610
611 let value: Value = ModelRc::from(model.clone()).into();
612 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
613 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
614 value_model.set_row_data(1, Value::String("qux".into()));
615 value_model.set_row_data(0, Value::Bool(true));
616 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
617 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
619
620 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
622 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
623
624 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
625 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
626 assert_eq!(
627 model.as_ref() as *const VecModel<SharedString>,
628 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
629 as *const VecModel<SharedString>
630 );
631}
632
633pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
634 i_slint_compiler::parser::normalize_identifier(ident)
635}
636
637#[derive(Clone, PartialEq, Debug, Default)]
659pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
660impl Struct {
661 pub fn get_field(&self, name: &str) -> Option<&Value> {
663 self.0.get(&*normalize_identifier(name))
664 }
665 pub fn set_field(&mut self, name: String, value: Value) {
667 self.0.insert(normalize_identifier(&name), value);
668 }
669
670 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
672 self.0.iter().map(|(a, b)| (a.as_str(), b))
673 }
674}
675
676impl FromIterator<(String, Value)> for Struct {
677 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
678 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
679 }
680}
681
682#[deprecated(note = "Use slint_interpreter::Compiler instead")]
684pub struct ComponentCompiler {
685 config: i_slint_compiler::CompilerConfiguration,
686 diagnostics: Vec<Diagnostic>,
687}
688
689#[allow(deprecated)]
690impl Default for ComponentCompiler {
691 fn default() -> Self {
692 let mut config = i_slint_compiler::CompilerConfiguration::new(
693 i_slint_compiler::generator::OutputFormat::Interpreter,
694 );
695 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
696 Self { config, diagnostics: Vec::new() }
697 }
698}
699
700#[allow(deprecated)]
701impl ComponentCompiler {
702 pub fn new() -> Self {
704 Self::default()
705 }
706
707 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
709 self.config.include_paths = include_paths;
710 }
711
712 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
714 &self.config.include_paths
715 }
716
717 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
719 self.config.library_paths = library_paths;
720 }
721
722 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
724 &self.config.library_paths
725 }
726
727 pub fn set_style(&mut self, style: String) {
739 self.config.style = Some(style);
740 }
741
742 pub fn style(&self) -> Option<&String> {
744 self.config.style.as_ref()
745 }
746
747 pub fn set_translation_domain(&mut self, domain: String) {
749 self.config.translation_domain = Some(domain);
750 }
751
752 pub fn set_file_loader(
760 &mut self,
761 file_loader_fallback: impl Fn(
762 &Path,
763 ) -> core::pin::Pin<
764 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
765 > + 'static,
766 ) {
767 self.config.open_import_callback =
768 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
769 }
770
771 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
773 &self.diagnostics
774 }
775
776 pub async fn build_from_path<P: AsRef<Path>>(
795 &mut self,
796 path: P,
797 ) -> Option<ComponentDefinition> {
798 let path = path.as_ref();
799 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
800 Ok(s) => s,
801 Err(d) => {
802 self.diagnostics = vec![d];
803 return None;
804 }
805 };
806
807 let r = crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await;
808 self.diagnostics = r.diagnostics.into_iter().collect();
809 r.components.into_values().next()
810 }
811
812 pub async fn build_from_source(
829 &mut self,
830 source_code: String,
831 path: PathBuf,
832 ) -> Option<ComponentDefinition> {
833 let r = crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await;
834 self.diagnostics = r.diagnostics.into_iter().collect();
835 r.components.into_values().next()
836 }
837}
838
839pub struct Compiler {
842 config: i_slint_compiler::CompilerConfiguration,
843}
844
845impl Default for Compiler {
846 fn default() -> Self {
847 let config = i_slint_compiler::CompilerConfiguration::new(
848 i_slint_compiler::generator::OutputFormat::Interpreter,
849 );
850 Self { config }
851 }
852}
853
854impl Compiler {
855 pub fn new() -> Self {
857 Self::default()
858 }
859
860 #[doc(hidden)]
861 #[cfg(feature = "internal")]
862 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
863 self.config.embed_resources = embed_resources;
864 }
865
866 #[doc(hidden)]
870 #[cfg(feature = "internal")]
871 pub fn compiler_configuration(
872 &mut self,
873 _: i_slint_core::InternalToken,
874 ) -> &mut i_slint_compiler::CompilerConfiguration {
875 &mut self.config
876 }
877
878 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
880 self.config.include_paths = include_paths;
881 }
882
883 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
885 &self.config.include_paths
886 }
887
888 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
890 self.config.library_paths = library_paths;
891 }
892
893 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
895 &self.config.library_paths
896 }
897
898 pub fn set_style(&mut self, style: String) {
909 self.config.style = Some(style);
910 }
911
912 pub fn style(&self) -> Option<&String> {
914 self.config.style.as_ref()
915 }
916
917 pub fn set_translation_domain(&mut self, domain: String) {
919 self.config.translation_domain = Some(domain);
920 }
921
922 pub fn set_default_translation_context(
928 &mut self,
929 default_translation_context: DefaultTranslationContext,
930 ) {
931 self.config.default_translation_context = default_translation_context;
932 }
933
934 pub fn set_file_loader(
942 &mut self,
943 file_loader_fallback: impl Fn(
944 &Path,
945 ) -> core::pin::Pin<
946 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
947 > + 'static,
948 ) {
949 self.config.open_import_callback =
950 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
951 }
952
953 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
972 let path = path.as_ref();
973 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
974 Ok(s) => s,
975 Err(d) => {
976 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
977 diagnostics.push_compiler_error(d);
978 return CompilationResult {
979 components: HashMap::new(),
980 diagnostics: diagnostics.into_iter().collect(),
981 #[cfg(feature = "internal")]
982 watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
983 #[cfg(feature = "internal")]
984 structs_and_enums: Vec::new(),
985 #[cfg(feature = "internal")]
986 named_exports: Vec::new(),
987 };
988 }
989 };
990
991 crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await
992 }
993
994 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1007 crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await
1008 }
1009}
1010
1011#[derive(Clone)]
1018pub struct CompilationResult {
1019 pub(crate) components: HashMap<String, ComponentDefinition>,
1020 pub(crate) diagnostics: Vec<Diagnostic>,
1021 #[cfg(feature = "internal")]
1022 pub(crate) watch_paths: Vec<PathBuf>,
1023 #[cfg(feature = "internal")]
1024 pub(crate) structs_and_enums: Vec<LangType>,
1025 #[cfg(feature = "internal")]
1027 pub(crate) named_exports: Vec<(String, String)>,
1028}
1029
1030impl core::fmt::Debug for CompilationResult {
1031 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1032 f.debug_struct("CompilationResult")
1033 .field("components", &self.components.keys())
1034 .field("diagnostics", &self.diagnostics)
1035 .finish()
1036 }
1037}
1038
1039impl CompilationResult {
1040 pub fn has_errors(&self) -> bool {
1043 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1044 }
1045
1046 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1050 self.diagnostics.iter().cloned()
1051 }
1052
1053 #[cfg(feature = "display-diagnostics")]
1059 pub fn print_diagnostics(&self) {
1060 print_diagnostics(&self.diagnostics)
1061 }
1062
1063 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1065 self.components.values().cloned()
1066 }
1067
1068 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1070 self.components.keys().map(|s| s.as_str())
1071 }
1072
1073 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1076 self.components.get(name).cloned()
1077 }
1078
1079 #[doc(hidden)]
1081 #[cfg(feature = "internal")]
1082 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1083 &self.watch_paths
1084 }
1085
1086 #[doc(hidden)]
1088 #[cfg(feature = "internal")]
1089 pub fn structs_and_enums(
1090 &self,
1091 _: i_slint_core::InternalToken,
1092 ) -> impl Iterator<Item = &LangType> {
1093 self.structs_and_enums.iter()
1094 }
1095
1096 #[doc(hidden)]
1099 #[cfg(feature = "internal")]
1100 pub fn named_exports(
1101 &self,
1102 _: i_slint_core::InternalToken,
1103 ) -> impl Iterator<Item = &(String, String)> {
1104 self.named_exports.iter()
1105 }
1106}
1107
1108#[derive(Clone)]
1116pub struct ComponentDefinition {
1117 pub(crate) inner: crate::dynamic_item_tree::ErasedItemTreeDescription,
1118}
1119
1120impl ComponentDefinition {
1121 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1123 let instance = self.create_with_options(Default::default())?;
1124 if !instance.is_system_tray_rooted() {
1127 instance.inner.window_adapter_ref()?;
1129 i_slint_core::window::WindowInner::from_pub(instance.window())
1132 .ensure_tree_instantiated();
1133 }
1134 Ok(instance)
1135 }
1136
1137 #[doc(hidden)]
1139 #[cfg(feature = "internal")]
1140 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1141 self.create_with_options(WindowOptions::Embed {
1142 parent_item_tree: ctx.parent_item_tree,
1143 parent_item_tree_index: ctx.parent_item_tree_index,
1144 })
1145 }
1146
1147 #[doc(hidden)]
1149 #[cfg(feature = "internal")]
1150 pub fn create_with_existing_window(
1151 &self,
1152 window: &Window,
1153 ) -> Result<ComponentInstance, PlatformError> {
1154 self.create_with_options(WindowOptions::UseExistingWindow(
1155 WindowInner::from_pub(window).window_adapter(),
1156 ))
1157 }
1158
1159 pub(crate) fn create_with_options(
1161 &self,
1162 options: WindowOptions,
1163 ) -> Result<ComponentInstance, PlatformError> {
1164 generativity::make_guard!(guard);
1165 Ok(ComponentInstance { inner: self.inner.unerase(guard).clone().create(options)? })
1166 }
1167
1168 #[doc(hidden)]
1172 #[cfg(feature = "internal")]
1173 pub fn properties_and_callbacks(
1174 &self,
1175 ) -> impl Iterator<
1176 Item = (
1177 String,
1178 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1179 ),
1180 > + '_ {
1181 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1184 self.inner.unerase(guard).properties().map(|(s, t, v)| (s.to_string(), (t, v)))
1185 }
1186
1187 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1190 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1193 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1194 if prop_type.is_property_type() {
1195 Some((prop_name.to_string(), prop_type.into()))
1196 } else {
1197 None
1198 }
1199 })
1200 }
1201
1202 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1204 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1207 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1208 if matches!(prop_type, LangType::Callback { .. }) {
1209 Some(prop_name.to_string())
1210 } else {
1211 None
1212 }
1213 })
1214 }
1215
1216 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1218 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1221 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1222 if matches!(prop_type, LangType::Function { .. }) {
1223 Some(prop_name.to_string())
1224 } else {
1225 None
1226 }
1227 })
1228 }
1229
1230 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1235 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1238 self.inner.unerase(guard).global_names().map(|s| s.to_string())
1239 }
1240
1241 #[doc(hidden)]
1245 #[cfg(feature = "internal")]
1246 pub fn global_properties_and_callbacks(
1247 &self,
1248 global_name: &str,
1249 ) -> Option<
1250 impl Iterator<
1251 Item = (
1252 String,
1253 (
1254 i_slint_compiler::langtype::Type,
1255 i_slint_compiler::object_tree::PropertyVisibility,
1256 ),
1257 ),
1258 > + '_,
1259 > {
1260 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1263 self.inner
1264 .unerase(guard)
1265 .global_properties(global_name)
1266 .map(|o| o.map(|(s, t, v)| (s.to_string(), (t, v))))
1267 }
1268
1269 pub fn global_properties(
1271 &self,
1272 global_name: &str,
1273 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1274 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1277 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1278 iter.filter_map(|(prop_name, prop_type, _)| {
1279 if prop_type.is_property_type() {
1280 Some((prop_name.to_string(), prop_type.into()))
1281 } else {
1282 None
1283 }
1284 })
1285 })
1286 }
1287
1288 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1290 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1293 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1294 iter.filter_map(|(prop_name, prop_type, _)| {
1295 if matches!(prop_type, LangType::Callback { .. }) {
1296 Some(prop_name.to_string())
1297 } else {
1298 None
1299 }
1300 })
1301 })
1302 }
1303
1304 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1306 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1309 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1310 iter.filter_map(|(prop_name, prop_type, _)| {
1311 if matches!(prop_type, LangType::Function { .. }) {
1312 Some(prop_name.to_string())
1313 } else {
1314 None
1315 }
1316 })
1317 })
1318 }
1319
1320 pub fn name(&self) -> &str {
1322 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1325 self.inner.unerase(guard).id()
1326 }
1327
1328 #[doc(hidden)]
1332 #[cfg(feature = "internal")]
1333 pub fn is_window(&self) -> bool {
1334 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1335 !self.inner.unerase(guard).original.inherits_system_tray_icon()
1336 }
1337
1338 #[cfg(feature = "internal")]
1340 #[doc(hidden)]
1341 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1342 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1343 self.inner.unerase(guard).original.clone()
1344 }
1345
1346 #[cfg(feature = "internal-highlight")]
1350 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1351 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1352 self.inner.unerase(guard).type_loader.get().unwrap().clone()
1353 }
1354
1355 #[cfg(feature = "internal-highlight")]
1363 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1364 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1365 self.inner
1366 .unerase(guard)
1367 .raw_type_loader
1368 .get()
1369 .unwrap()
1370 .as_ref()
1371 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1372 }
1373}
1374
1375#[cfg(feature = "display-diagnostics")]
1381pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1382 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1383 for d in diagnostics {
1384 build_diagnostics.push_compiler_error(d.clone())
1385 }
1386 build_diagnostics.print();
1387}
1388
1389#[repr(C)]
1397pub struct ComponentInstance {
1398 pub(crate) inner: crate::dynamic_item_tree::DynamicComponentVRc,
1399}
1400
1401impl ComponentInstance {
1402 pub fn definition(&self) -> ComponentDefinition {
1404 generativity::make_guard!(guard);
1405 ComponentDefinition { inner: self.inner.unerase(guard).description().into() }
1406 }
1407
1408 fn is_system_tray_rooted(&self) -> bool {
1409 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1410 self.inner.unerase(guard).description().original.inherits_system_tray_icon()
1411 }
1412
1413 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1433 generativity::make_guard!(guard);
1434 let comp = self.inner.unerase(guard);
1435 let name = normalize_identifier(name);
1436
1437 if comp
1438 .description()
1439 .original
1440 .root_element
1441 .borrow()
1442 .property_declarations
1443 .get(&name)
1444 .is_none_or(|d| !d.expose_in_public_api)
1445 {
1446 return Err(GetPropertyError::NoSuchProperty);
1447 }
1448
1449 comp.description()
1450 .get_property(comp.borrow(), &name)
1451 .map_err(|()| GetPropertyError::NoSuchProperty)
1452 }
1453
1454 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1456 let name = normalize_identifier(name);
1457 generativity::make_guard!(guard);
1458 let comp = self.inner.unerase(guard);
1459 let d = comp.description();
1460 let elem = d.original.root_element.borrow();
1461 let decl = elem.property_declarations.get(&name).ok_or(SetPropertyError::NoSuchProperty)?;
1462
1463 if !decl.expose_in_public_api {
1464 return Err(SetPropertyError::NoSuchProperty);
1465 } else if decl.visibility == i_slint_compiler::object_tree::PropertyVisibility::Output {
1466 return Err(SetPropertyError::AccessDenied);
1467 }
1468
1469 d.set_property(comp.borrow(), &name, value)
1470 }
1471
1472 pub fn set_callback(
1507 &self,
1508 name: &str,
1509 callback: impl Fn(&[Value]) -> Value + 'static,
1510 ) -> Result<(), SetCallbackError> {
1511 generativity::make_guard!(guard);
1512 let comp = self.inner.unerase(guard);
1513 comp.description()
1514 .set_callback_handler(comp.borrow(), &normalize_identifier(name), Box::new(callback))
1515 .map_err(|()| SetCallbackError::NoSuchCallback)
1516 }
1517
1518 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1523 generativity::make_guard!(guard);
1524 let comp = self.inner.unerase(guard);
1525 comp.description()
1526 .invoke(comp.borrow(), &normalize_identifier(name), args)
1527 .map_err(|()| InvokeError::NoSuchCallable)
1528 }
1529
1530 pub fn get_global_property(
1555 &self,
1556 global: &str,
1557 property: &str,
1558 ) -> Result<Value, GetPropertyError> {
1559 generativity::make_guard!(guard);
1560 let comp = self.inner.unerase(guard);
1561 comp.description()
1562 .get_global(comp.borrow(), &normalize_identifier(global))
1563 .map_err(|()| GetPropertyError::NoSuchProperty)? .as_ref()
1565 .get_property(&normalize_identifier(property))
1566 .map_err(|()| GetPropertyError::NoSuchProperty)
1567 }
1568
1569 pub fn set_global_property(
1571 &self,
1572 global: &str,
1573 property: &str,
1574 value: Value,
1575 ) -> Result<(), SetPropertyError> {
1576 generativity::make_guard!(guard);
1577 let comp = self.inner.unerase(guard);
1578 comp.description()
1579 .get_global(comp.borrow(), &normalize_identifier(global))
1580 .map_err(|()| SetPropertyError::NoSuchProperty)? .as_ref()
1582 .set_property(&normalize_identifier(property), value)
1583 }
1584
1585 pub fn set_global_callback(
1620 &self,
1621 global: &str,
1622 name: &str,
1623 callback: impl Fn(&[Value]) -> Value + 'static,
1624 ) -> Result<(), SetCallbackError> {
1625 generativity::make_guard!(guard);
1626 let comp = self.inner.unerase(guard);
1627 comp.description()
1628 .get_global(comp.borrow(), &normalize_identifier(global))
1629 .map_err(|()| SetCallbackError::NoSuchCallback)? .as_ref()
1631 .set_callback_handler(&normalize_identifier(name), Box::new(callback))
1632 .map_err(|()| SetCallbackError::NoSuchCallback)
1633 }
1634
1635 pub fn invoke_global(
1640 &self,
1641 global: &str,
1642 callable_name: &str,
1643 args: &[Value],
1644 ) -> Result<Value, InvokeError> {
1645 generativity::make_guard!(guard);
1646 let comp = self.inner.unerase(guard);
1647 let g = comp
1648 .description()
1649 .get_global(comp.borrow(), &normalize_identifier(global))
1650 .map_err(|()| InvokeError::NoSuchCallable)?; let callable_name = normalize_identifier(callable_name);
1652 if matches!(
1653 comp.description()
1654 .original
1655 .root_element
1656 .borrow()
1657 .lookup_property(&callable_name)
1658 .property_type,
1659 LangType::Function { .. }
1660 ) {
1661 g.as_ref()
1662 .eval_function(&callable_name, args.to_vec())
1663 .map_err(|()| InvokeError::NoSuchCallable)
1664 } else {
1665 g.as_ref()
1666 .invoke_callback(&callable_name, args)
1667 .map_err(|()| InvokeError::NoSuchCallable)
1668 }
1669 }
1670
1671 #[cfg(feature = "internal-highlight")]
1675 pub fn component_positions(
1676 &self,
1677 path: &Path,
1678 offset: u32,
1679 ) -> Vec<crate::highlight::HighlightedRect> {
1680 crate::highlight::component_positions(&self.inner, path, offset)
1681 }
1682
1683 #[cfg(feature = "internal-highlight")]
1687 pub fn element_positions(
1688 &self,
1689 element: &i_slint_compiler::object_tree::ElementRc,
1690 ) -> Vec<crate::highlight::HighlightedRect> {
1691 crate::highlight::element_positions(
1692 &self.inner,
1693 element,
1694 crate::highlight::ElementPositionFilter::IncludeClipped,
1695 )
1696 }
1697
1698 #[cfg(feature = "internal-highlight")]
1702 pub fn element_node_at_source_code_position(
1703 &self,
1704 path: &Path,
1705 offset: u32,
1706 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1707 crate::highlight::element_node_at_source_code_position(&self.inner, path, offset)
1708 }
1709}
1710
1711impl StrongHandle for ComponentInstance {
1712 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::dynamic_item_tree::ErasedItemTreeBox>;
1713
1714 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1715 Some(Self { inner: inner.upgrade()? })
1716 }
1717}
1718
1719impl ComponentHandle for ComponentInstance {
1720 fn as_weak(&self) -> Weak<Self>
1721 where
1722 Self: Sized,
1723 {
1724 Weak::new(vtable::VRc::downgrade(&self.inner))
1725 }
1726
1727 fn clone_strong(&self) -> Self {
1728 Self { inner: self.inner.clone() }
1729 }
1730
1731 fn show(&self) -> Result<(), PlatformError> {
1732 if self.is_system_tray_rooted() {
1733 self.set_property("visible", Value::Bool(true)).expect(
1737 "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1738 );
1739 return Ok(());
1740 }
1741 self.inner.window_adapter_ref()?.window().show()
1742 }
1743
1744 fn hide(&self) -> Result<(), PlatformError> {
1745 if self.is_system_tray_rooted() {
1746 self.set_property("visible", Value::Bool(false)).expect(
1747 "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1748 );
1749 return Ok(());
1750 }
1751 self.inner.window_adapter_ref()?.window().hide()
1752 }
1753
1754 fn run(&self) -> Result<(), PlatformError> {
1755 self.show()?;
1756 run_event_loop()?;
1757 self.hide()
1758 }
1759
1760 fn window(&self) -> &Window {
1761 self.inner.window_adapter_ref().unwrap().window()
1762 }
1763
1764 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1765 where
1766 Self: Sized,
1767 {
1768 unreachable!()
1769 }
1770}
1771
1772impl From<ComponentInstance>
1773 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, ErasedItemTreeBox>
1774{
1775 fn from(value: ComponentInstance) -> Self {
1776 value.inner
1777 }
1778}
1779
1780#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1782#[non_exhaustive]
1783pub enum GetPropertyError {
1784 #[display("no such property")]
1786 NoSuchProperty,
1787}
1788
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1791#[non_exhaustive]
1792pub enum SetPropertyError {
1793 #[display("no such property")]
1795 NoSuchProperty,
1796 #[display("wrong type")]
1802 WrongType,
1803 #[display("access denied")]
1805 AccessDenied,
1806}
1807
1808#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1810#[non_exhaustive]
1811pub enum SetCallbackError {
1812 #[display("no such callback")]
1814 NoSuchCallback,
1815}
1816
1817#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1819#[non_exhaustive]
1820pub enum InvokeError {
1821 #[display("no such callback or function")]
1823 NoSuchCallable,
1824}
1825
1826pub fn run_event_loop() -> Result<(), PlatformError> {
1830 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1831}
1832
1833pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1837 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1838 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1839}
1840
1841#[test]
1842fn component_definition_properties() {
1843 i_slint_backend_testing::init_no_event_loop();
1844 let mut compiler = Compiler::default();
1845 compiler.set_style("fluent".into());
1846 let comp_def = spin_on::spin_on(
1847 compiler.build_from_source(
1848 r#"
1849 export component Dummy {
1850 in-out property <string> test;
1851 in-out property <int> underscores-and-dashes_preserved: 44;
1852 callback hello;
1853 }"#
1854 .into(),
1855 "".into(),
1856 ),
1857 )
1858 .component("Dummy")
1859 .unwrap();
1860
1861 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1862
1863 assert_eq!(props.len(), 2);
1864 assert_eq!(props[0].0, "test");
1865 assert_eq!(props[0].1, ValueType::String);
1866 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1867 assert_eq!(props[1].1, ValueType::Number);
1868
1869 let instance = comp_def.create().unwrap();
1870 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1871 assert_eq!(
1872 instance.get_property("underscoresanddashespreserved"),
1873 Err(GetPropertyError::NoSuchProperty)
1874 );
1875 assert_eq!(
1876 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1877 Ok(())
1878 );
1879 assert_eq!(
1880 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1881 Err(SetPropertyError::NoSuchProperty)
1882 );
1883 assert_eq!(
1884 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1885 Err(SetPropertyError::WrongType)
1886 );
1887 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1888}
1889
1890#[test]
1891fn component_definition_properties2() {
1892 i_slint_backend_testing::init_no_event_loop();
1893 let mut compiler = Compiler::default();
1894 compiler.set_style("fluent".into());
1895 let comp_def = spin_on::spin_on(
1896 compiler.build_from_source(
1897 r#"
1898 export component Dummy {
1899 in-out property <string> sub-text <=> sub.text;
1900 sub := Text { property <int> private-not-exported; }
1901 out property <string> xreadonly: "the value";
1902 private property <string> xx: sub.text;
1903 callback hello;
1904 }"#
1905 .into(),
1906 "".into(),
1907 ),
1908 )
1909 .component("Dummy")
1910 .unwrap();
1911
1912 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1913
1914 assert_eq!(props.len(), 2);
1915 assert_eq!(props[0].0, "sub-text");
1916 assert_eq!(props[0].1, ValueType::String);
1917 assert_eq!(props[1].0, "xreadonly");
1918
1919 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1920 assert_eq!(callbacks.len(), 1);
1921 assert_eq!(callbacks[0], "hello");
1922
1923 let instance = comp_def.create().unwrap();
1924 assert_eq!(
1925 instance.set_property("xreadonly", SharedString::from("XXX").into()),
1926 Err(SetPropertyError::AccessDenied)
1927 );
1928 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1929 assert_eq!(
1930 instance.set_property("xx", SharedString::from("XXX").into()),
1931 Err(SetPropertyError::NoSuchProperty)
1932 );
1933 assert_eq!(
1934 instance.set_property("background", Value::default()),
1935 Err(SetPropertyError::NoSuchProperty)
1936 );
1937
1938 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1939 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1940}
1941
1942#[test]
1943fn globals() {
1944 i_slint_backend_testing::init_no_event_loop();
1945 let mut compiler = Compiler::default();
1946 compiler.set_style("fluent".into());
1947 let definition = spin_on::spin_on(
1948 compiler.build_from_source(
1949 r#"
1950 export global My-Super_Global {
1951 in-out property <int> the-property : 21;
1952 callback my-callback();
1953 }
1954 export { My-Super_Global as AliasedGlobal }
1955 export component Dummy {
1956 callback alias <=> My-Super_Global.my-callback;
1957 }"#
1958 .into(),
1959 "".into(),
1960 ),
1961 )
1962 .component("Dummy")
1963 .unwrap();
1964
1965 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1966
1967 assert!(definition.global_properties("not-there").is_none());
1968 {
1969 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1970 let expected_callbacks = vec!["my-callback".to_string()];
1971
1972 let assert_properties_and_callbacks = |global_name| {
1973 assert_eq!(
1974 definition
1975 .global_properties(global_name)
1976 .map(|props| props.collect::<Vec<_>>())
1977 .as_ref(),
1978 Some(&expected_properties)
1979 );
1980 assert_eq!(
1981 definition
1982 .global_callbacks(global_name)
1983 .map(|props| props.collect::<Vec<_>>())
1984 .as_ref(),
1985 Some(&expected_callbacks)
1986 );
1987 };
1988
1989 assert_properties_and_callbacks("My-Super-Global");
1990 assert_properties_and_callbacks("My_Super-Global");
1991 assert_properties_and_callbacks("AliasedGlobal");
1992 }
1993
1994 let instance = definition.create().unwrap();
1995 assert_eq!(
1996 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
1997 Ok(())
1998 );
1999 assert_eq!(
2000 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2001 Ok(())
2002 );
2003 assert_eq!(
2004 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2005 Err(SetPropertyError::NoSuchProperty)
2006 );
2007
2008 assert_eq!(
2009 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2010 Err(SetPropertyError::NoSuchProperty)
2011 );
2012 assert_eq!(
2013 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2014 Err(SetPropertyError::NoSuchProperty)
2015 );
2016 assert_eq!(
2017 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2018 Err(SetPropertyError::WrongType)
2019 );
2020 assert_eq!(
2021 instance.get_global_property("My-Super_Global", "yoyo"),
2022 Err(GetPropertyError::NoSuchProperty)
2023 );
2024 assert_eq!(
2025 instance.get_global_property("My-Super_Global", "the-property"),
2026 Ok(Value::Number(44.))
2027 );
2028
2029 assert_eq!(
2030 instance.set_property("the-property", Value::Void),
2031 Err(SetPropertyError::NoSuchProperty)
2032 );
2033 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2034
2035 assert_eq!(
2036 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2037 Err(SetCallbackError::NoSuchCallback)
2038 );
2039 assert_eq!(
2040 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2041 Err(SetCallbackError::NoSuchCallback)
2042 );
2043 assert_eq!(
2044 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2045 Err(SetCallbackError::NoSuchCallback)
2046 );
2047
2048 assert_eq!(
2049 instance.invoke_global("DontExist", "the-property", &[]),
2050 Err(InvokeError::NoSuchCallable)
2051 );
2052 assert_eq!(
2053 instance.invoke_global("My_Super_Global", "the-property", &[]),
2054 Err(InvokeError::NoSuchCallable)
2055 );
2056 assert_eq!(
2057 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2058 Err(InvokeError::NoSuchCallable)
2059 );
2060
2061 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2063}
2064
2065#[test]
2066fn call_functions() {
2067 i_slint_backend_testing::init_no_event_loop();
2068 let mut compiler = Compiler::default();
2069 compiler.set_style("fluent".into());
2070 let definition = spin_on::spin_on(
2071 compiler.build_from_source(
2072 r#"
2073 export global Gl {
2074 out property<string> q;
2075 public function foo-bar(a-a: string, b-b:int) -> string {
2076 q = a-a;
2077 return a-a + b-b;
2078 }
2079 }
2080 export component Test {
2081 out property<int> p;
2082 public function foo-bar(a: int, b:int) -> int {
2083 p = a;
2084 return a + b;
2085 }
2086 }"#
2087 .into(),
2088 "".into(),
2089 ),
2090 )
2091 .component("Test")
2092 .unwrap();
2093
2094 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2095 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2096
2097 let instance = definition.create().unwrap();
2098
2099 assert_eq!(
2100 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2101 Ok(Value::Number(7.))
2102 );
2103 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2104 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2105
2106 assert_eq!(
2107 instance.invoke_global(
2108 "Gl",
2109 "foo_bar",
2110 &[Value::String("Hello".into()), Value::Number(10.)]
2111 ),
2112 Ok(Value::String("Hello10".into()))
2113 );
2114 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2115}
2116
2117#[test]
2118fn component_definition_struct_properties() {
2119 i_slint_backend_testing::init_no_event_loop();
2120 let mut compiler = Compiler::default();
2121 compiler.set_style("fluent".into());
2122 let comp_def = spin_on::spin_on(
2123 compiler.build_from_source(
2124 r#"
2125 export struct Settings {
2126 string_value: string,
2127 }
2128 export component Dummy {
2129 in-out property <Settings> test;
2130 }"#
2131 .into(),
2132 "".into(),
2133 ),
2134 )
2135 .component("Dummy")
2136 .unwrap();
2137
2138 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2139
2140 assert_eq!(props.len(), 1);
2141 assert_eq!(props[0].0, "test");
2142 assert_eq!(props[0].1, ValueType::Struct);
2143
2144 let instance = comp_def.create().unwrap();
2145
2146 let valid_struct: Struct =
2147 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2148
2149 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2150 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2151
2152 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2153
2154 let mut invalid_struct = valid_struct.clone();
2155 invalid_struct.set_field("other".into(), Value::Number(44.));
2156 assert_eq!(
2157 instance.set_property("test", Value::Struct(invalid_struct)),
2158 Err(SetPropertyError::WrongType)
2159 );
2160 let mut invalid_struct = valid_struct;
2161 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2162 assert_eq!(
2163 instance.set_property("test", Value::Struct(invalid_struct)),
2164 Err(SetPropertyError::WrongType)
2165 );
2166}
2167
2168#[test]
2169fn component_definition_model_properties() {
2170 use i_slint_core::model::*;
2171 i_slint_backend_testing::init_no_event_loop();
2172 let mut compiler = Compiler::default();
2173 compiler.set_style("fluent".into());
2174 let comp_def = spin_on::spin_on(compiler.build_from_source(
2175 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2176 "".into(),
2177 ))
2178 .component("Dummy")
2179 .unwrap();
2180
2181 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2182 assert_eq!(props.len(), 1);
2183 assert_eq!(props[0].0, "prop");
2184 assert_eq!(props[0].1, ValueType::Model);
2185
2186 let instance = comp_def.create().unwrap();
2187
2188 let int_model =
2189 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2190 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2191 let model_with_string = Value::Model(VecModel::from_slice(&[
2192 Value::Number(1000.),
2193 Value::String("foo".into()),
2194 Value::Number(1111.),
2195 ]));
2196
2197 #[track_caller]
2198 fn check_model(val: Value, r: &[f64]) {
2199 if let Value::Model(m) = val {
2200 assert_eq!(r.len(), m.row_count());
2201 for (i, v) in r.iter().enumerate() {
2202 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2203 }
2204 } else {
2205 panic!("{val:?} not a model");
2206 }
2207 }
2208
2209 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2210 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2211
2212 instance.set_property("prop", int_model).unwrap();
2213 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2214
2215 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2216 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2217 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2218 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2219
2220 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2221 check_model(instance.get_property("prop").unwrap(), &[]);
2222}
2223
2224#[test]
2225fn lang_type_to_value_type() {
2226 use i_slint_compiler::langtype::Struct as LangStruct;
2227 use std::collections::BTreeMap;
2228
2229 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2230 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2231 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2232 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2233 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2234 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2235 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2236 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2237 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2238 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2239 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2240 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2241 assert_eq!(ValueType::from(LangType::Array(Rc::new(LangType::Void))), ValueType::Model);
2242 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2243 assert_eq!(
2244 ValueType::from(LangType::Struct(Rc::new(LangStruct::new(
2245 BTreeMap::default(),
2246 i_slint_compiler::langtype::StructName::None
2247 )))),
2248 ValueType::Struct
2249 );
2250 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2251}
2252
2253#[test]
2254fn test_multi_components() {
2255 i_slint_backend_testing::init_no_event_loop();
2256 let result = spin_on::spin_on(
2257 Compiler::default().build_from_source(
2258 r#"
2259 export struct Settings {
2260 string_value: string,
2261 }
2262 export global ExpGlo { in-out property <int> test: 42; }
2263 component Common {
2264 in-out property <Settings> settings: { string_value: "Hello", };
2265 }
2266 export component Xyz inherits Window {
2267 in-out property <int> aaa: 8;
2268 }
2269 export component Foo {
2270
2271 in-out property <int> test: 42;
2272 c := Common {}
2273 }
2274 export component Bar inherits Window {
2275 in-out property <int> blah: 78;
2276 c := Common {}
2277 }
2278 "#
2279 .into(),
2280 PathBuf::from("hello.slint"),
2281 ),
2282 );
2283
2284 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2285 let mut components = result.component_names().collect::<Vec<_>>();
2286 components.sort();
2287 assert_eq!(components, vec!["Bar", "Xyz"]);
2288 let diag = result.diagnostics().collect::<Vec<_>>();
2289 assert_eq!(diag.len(), 1);
2290 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2291 assert_eq!(
2292 diag[0].message(),
2293 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2294 );
2295
2296 let comp1 = result.component("Xyz").unwrap();
2297 assert_eq!(comp1.name(), "Xyz");
2298 let instance1a = comp1.create().unwrap();
2299 let comp2 = result.component("Bar").unwrap();
2300 let instance2 = comp2.create().unwrap();
2301 let instance1b = comp1.create().unwrap();
2302
2303 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2305 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2306 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2307 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2308 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2309
2310 assert!(result.component("Settings").is_none());
2311 assert!(result.component("Foo").is_none());
2312 assert!(result.component("Common").is_none());
2313 assert!(result.component("ExpGlo").is_none());
2314 assert!(result.component("xyz").is_none());
2315}
2316
2317#[cfg(all(test, feature = "internal-highlight"))]
2318fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2319 i_slint_backend_testing::init_no_event_loop();
2320 let mut compiler = Compiler::default();
2321 compiler.set_style("fluent".into());
2322 let path = PathBuf::from("/tmp/test.slint");
2323
2324 let compile_result =
2325 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2326
2327 for d in &compile_result.diagnostics {
2328 eprintln!("{d}");
2329 }
2330
2331 assert!(!compile_result.has_errors());
2332
2333 let definition = compile_result.components().next().unwrap();
2334 let instance = definition.create().unwrap();
2335
2336 (instance, path)
2337}
2338
2339#[cfg(feature = "internal-highlight")]
2340#[test]
2341fn test_element_node_at_source_code_position() {
2342 let code = r#"
2343component Bar1 {}
2344
2345component Foo1 {
2346}
2347
2348export component Foo2 inherits Window {
2349 Bar1 {}
2350 Foo1 {}
2351}"#;
2352
2353 let (handle, path) = compile(code);
2354
2355 for i in 0..code.len() as u32 {
2356 let elements = handle.element_node_at_source_code_position(&path, i);
2357 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2358 match i {
2359 16 => assert_eq!(elements.len(), 1), 35 => assert_eq!(elements.len(), 1), 71..=78 => assert_eq!(elements.len(), 1), 85..=89 => assert_eq!(elements.len(), 1), 97..=103 => assert_eq!(elements.len(), 1), _ => assert!(elements.is_empty()),
2365 }
2366 }
2367}