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 fn set_tray_icon_visible(&self, visible: bool) {
1417 generativity::make_guard!(guard);
1418 let description = self.inner.unerase(guard).description();
1419 let item_info = &description.items[description.original.root_element.borrow().id.as_str()];
1420 let item_rc =
1421 ItemRc::new(vtable::VRc::into_dyn(self.inner.clone()), item_info.item_index());
1422 let tray = item_rc
1423 .downcast::<SystemTrayIcon>()
1424 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1425 tray.as_pin_ref().visible.set(visible);
1426 }
1427
1428 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1448 generativity::make_guard!(guard);
1449 let comp = self.inner.unerase(guard);
1450 let name = normalize_identifier(name);
1451
1452 if comp
1453 .description()
1454 .original
1455 .root_element
1456 .borrow()
1457 .property_declarations
1458 .get(&name)
1459 .is_none_or(|d| !d.expose_in_public_api)
1460 {
1461 return Err(GetPropertyError::NoSuchProperty);
1462 }
1463
1464 comp.description()
1465 .get_property(comp.borrow(), &name)
1466 .map_err(|()| GetPropertyError::NoSuchProperty)
1467 }
1468
1469 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1471 let name = normalize_identifier(name);
1472 generativity::make_guard!(guard);
1473 let comp = self.inner.unerase(guard);
1474 let d = comp.description();
1475 let elem = d.original.root_element.borrow();
1476 let decl = elem.property_declarations.get(&name).ok_or(SetPropertyError::NoSuchProperty)?;
1477
1478 if !decl.expose_in_public_api {
1479 return Err(SetPropertyError::NoSuchProperty);
1480 } else if decl.visibility == i_slint_compiler::object_tree::PropertyVisibility::Output {
1481 return Err(SetPropertyError::AccessDenied);
1482 }
1483
1484 d.set_property(comp.borrow(), &name, value)
1485 }
1486
1487 pub fn set_callback(
1522 &self,
1523 name: &str,
1524 callback: impl Fn(&[Value]) -> Value + 'static,
1525 ) -> Result<(), SetCallbackError> {
1526 generativity::make_guard!(guard);
1527 let comp = self.inner.unerase(guard);
1528 comp.description()
1529 .set_callback_handler(comp.borrow(), &normalize_identifier(name), Box::new(callback))
1530 .map_err(|()| SetCallbackError::NoSuchCallback)
1531 }
1532
1533 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1538 generativity::make_guard!(guard);
1539 let comp = self.inner.unerase(guard);
1540 comp.description()
1541 .invoke(comp.borrow(), &normalize_identifier(name), args)
1542 .map_err(|()| InvokeError::NoSuchCallable)
1543 }
1544
1545 pub fn get_global_property(
1570 &self,
1571 global: &str,
1572 property: &str,
1573 ) -> Result<Value, GetPropertyError> {
1574 generativity::make_guard!(guard);
1575 let comp = self.inner.unerase(guard);
1576 comp.description()
1577 .get_global(comp.borrow(), &normalize_identifier(global))
1578 .map_err(|()| GetPropertyError::NoSuchProperty)? .as_ref()
1580 .get_property(&normalize_identifier(property))
1581 .map_err(|()| GetPropertyError::NoSuchProperty)
1582 }
1583
1584 pub fn set_global_property(
1586 &self,
1587 global: &str,
1588 property: &str,
1589 value: Value,
1590 ) -> Result<(), SetPropertyError> {
1591 generativity::make_guard!(guard);
1592 let comp = self.inner.unerase(guard);
1593 comp.description()
1594 .get_global(comp.borrow(), &normalize_identifier(global))
1595 .map_err(|()| SetPropertyError::NoSuchProperty)? .as_ref()
1597 .set_property(&normalize_identifier(property), value)
1598 }
1599
1600 pub fn set_global_callback(
1635 &self,
1636 global: &str,
1637 name: &str,
1638 callback: impl Fn(&[Value]) -> Value + 'static,
1639 ) -> Result<(), SetCallbackError> {
1640 generativity::make_guard!(guard);
1641 let comp = self.inner.unerase(guard);
1642 comp.description()
1643 .get_global(comp.borrow(), &normalize_identifier(global))
1644 .map_err(|()| SetCallbackError::NoSuchCallback)? .as_ref()
1646 .set_callback_handler(&normalize_identifier(name), Box::new(callback))
1647 .map_err(|()| SetCallbackError::NoSuchCallback)
1648 }
1649
1650 pub fn invoke_global(
1655 &self,
1656 global: &str,
1657 callable_name: &str,
1658 args: &[Value],
1659 ) -> Result<Value, InvokeError> {
1660 generativity::make_guard!(guard);
1661 let comp = self.inner.unerase(guard);
1662 let g = comp
1663 .description()
1664 .get_global(comp.borrow(), &normalize_identifier(global))
1665 .map_err(|()| InvokeError::NoSuchCallable)?; let callable_name = normalize_identifier(callable_name);
1667 if matches!(
1668 comp.description()
1669 .original
1670 .root_element
1671 .borrow()
1672 .lookup_property(&callable_name)
1673 .property_type,
1674 LangType::Function { .. }
1675 ) {
1676 g.as_ref()
1677 .eval_function(&callable_name, args.to_vec())
1678 .map_err(|()| InvokeError::NoSuchCallable)
1679 } else {
1680 g.as_ref()
1681 .invoke_callback(&callable_name, args)
1682 .map_err(|()| InvokeError::NoSuchCallable)
1683 }
1684 }
1685
1686 #[cfg(feature = "internal-highlight")]
1690 pub fn component_positions(
1691 &self,
1692 path: &Path,
1693 offset: u32,
1694 ) -> Vec<crate::highlight::HighlightedRect> {
1695 crate::highlight::component_positions(&self.inner, path, offset)
1696 }
1697
1698 #[cfg(feature = "internal-highlight")]
1702 pub fn element_positions(
1703 &self,
1704 element: &i_slint_compiler::object_tree::ElementRc,
1705 ) -> Vec<crate::highlight::HighlightedRect> {
1706 crate::highlight::element_positions(
1707 &self.inner,
1708 element,
1709 crate::highlight::ElementPositionFilter::IncludeClipped,
1710 )
1711 }
1712
1713 #[cfg(feature = "internal-highlight")]
1717 pub fn element_node_at_source_code_position(
1718 &self,
1719 path: &Path,
1720 offset: u32,
1721 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1722 crate::highlight::element_node_at_source_code_position(&self.inner, path, offset)
1723 }
1724
1725 #[cfg(feature = "internal")]
1727 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1728 generativity::make_guard!(guard);
1729 let comp = self.inner.unerase(guard);
1730 crate::debug_hook::set_debug_hook_callback(comp, callback);
1731 }
1732}
1733
1734impl StrongHandle for ComponentInstance {
1735 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::dynamic_item_tree::ErasedItemTreeBox>;
1736
1737 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1738 Some(Self { inner: inner.upgrade()? })
1739 }
1740}
1741
1742impl ComponentHandle for ComponentInstance {
1743 fn as_weak(&self) -> Weak<Self>
1744 where
1745 Self: Sized,
1746 {
1747 Weak::new(vtable::VRc::downgrade(&self.inner))
1748 }
1749
1750 fn clone_strong(&self) -> Self {
1751 Self { inner: self.inner.clone() }
1752 }
1753
1754 fn show(&self) -> Result<(), PlatformError> {
1755 if self.is_system_tray_rooted() {
1756 self.set_tray_icon_visible(true);
1757 return Ok(());
1758 }
1759 self.inner.window_adapter_ref()?.window().show()
1760 }
1761
1762 fn hide(&self) -> Result<(), PlatformError> {
1763 if self.is_system_tray_rooted() {
1764 self.set_tray_icon_visible(false);
1765 return Ok(());
1766 }
1767 self.inner.window_adapter_ref()?.window().hide()
1768 }
1769
1770 fn run(&self) -> Result<(), PlatformError> {
1771 self.show()?;
1772 run_event_loop()?;
1773 self.hide()
1774 }
1775
1776 fn window(&self) -> &Window {
1777 self.inner.window_adapter_ref().unwrap().window()
1778 }
1779
1780 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1781 where
1782 Self: Sized,
1783 {
1784 unreachable!()
1785 }
1786}
1787
1788impl From<ComponentInstance>
1789 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, ErasedItemTreeBox>
1790{
1791 fn from(value: ComponentInstance) -> Self {
1792 value.inner
1793 }
1794}
1795
1796#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1798#[non_exhaustive]
1799pub enum GetPropertyError {
1800 #[display("no such property")]
1802 NoSuchProperty,
1803}
1804
1805#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1807#[non_exhaustive]
1808pub enum SetPropertyError {
1809 #[display("no such property")]
1811 NoSuchProperty,
1812 #[display("wrong type")]
1818 WrongType,
1819 #[display("access denied")]
1821 AccessDenied,
1822}
1823
1824#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1826#[non_exhaustive]
1827pub enum SetCallbackError {
1828 #[display("no such callback")]
1830 NoSuchCallback,
1831}
1832
1833#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1835#[non_exhaustive]
1836pub enum InvokeError {
1837 #[display("no such callback or function")]
1839 NoSuchCallable,
1840}
1841
1842pub fn run_event_loop() -> Result<(), PlatformError> {
1846 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1847}
1848
1849pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1853 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1854 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1855}
1856
1857#[test]
1858fn component_definition_properties() {
1859 i_slint_backend_testing::init_no_event_loop();
1860 let mut compiler = Compiler::default();
1861 compiler.set_style("fluent".into());
1862 let comp_def = spin_on::spin_on(
1863 compiler.build_from_source(
1864 r#"
1865 export component Dummy {
1866 in-out property <string> test;
1867 in-out property <int> underscores-and-dashes_preserved: 44;
1868 callback hello;
1869 }"#
1870 .into(),
1871 "".into(),
1872 ),
1873 )
1874 .component("Dummy")
1875 .unwrap();
1876
1877 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1878
1879 assert_eq!(props.len(), 2);
1880 assert_eq!(props[0].0, "test");
1881 assert_eq!(props[0].1, ValueType::String);
1882 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1883 assert_eq!(props[1].1, ValueType::Number);
1884
1885 let instance = comp_def.create().unwrap();
1886 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1887 assert_eq!(
1888 instance.get_property("underscoresanddashespreserved"),
1889 Err(GetPropertyError::NoSuchProperty)
1890 );
1891 assert_eq!(
1892 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1893 Ok(())
1894 );
1895 assert_eq!(
1896 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1897 Err(SetPropertyError::NoSuchProperty)
1898 );
1899 assert_eq!(
1900 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1901 Err(SetPropertyError::WrongType)
1902 );
1903 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1904}
1905
1906#[test]
1907fn component_definition_properties2() {
1908 i_slint_backend_testing::init_no_event_loop();
1909 let mut compiler = Compiler::default();
1910 compiler.set_style("fluent".into());
1911 let comp_def = spin_on::spin_on(
1912 compiler.build_from_source(
1913 r#"
1914 export component Dummy {
1915 in-out property <string> sub-text <=> sub.text;
1916 sub := Text { property <int> private-not-exported; }
1917 out property <string> xreadonly: "the value";
1918 private property <string> xx: sub.text;
1919 callback hello;
1920 }"#
1921 .into(),
1922 "".into(),
1923 ),
1924 )
1925 .component("Dummy")
1926 .unwrap();
1927
1928 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1929
1930 assert_eq!(props.len(), 2);
1931 assert_eq!(props[0].0, "sub-text");
1932 assert_eq!(props[0].1, ValueType::String);
1933 assert_eq!(props[1].0, "xreadonly");
1934
1935 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1936 assert_eq!(callbacks.len(), 1);
1937 assert_eq!(callbacks[0], "hello");
1938
1939 let instance = comp_def.create().unwrap();
1940 assert_eq!(
1941 instance.set_property("xreadonly", SharedString::from("XXX").into()),
1942 Err(SetPropertyError::AccessDenied)
1943 );
1944 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1945 assert_eq!(
1946 instance.set_property("xx", SharedString::from("XXX").into()),
1947 Err(SetPropertyError::NoSuchProperty)
1948 );
1949 assert_eq!(
1950 instance.set_property("background", Value::default()),
1951 Err(SetPropertyError::NoSuchProperty)
1952 );
1953
1954 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1955 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1956}
1957
1958#[test]
1959fn globals() {
1960 i_slint_backend_testing::init_no_event_loop();
1961 let mut compiler = Compiler::default();
1962 compiler.set_style("fluent".into());
1963 let definition = spin_on::spin_on(
1964 compiler.build_from_source(
1965 r#"
1966 export global My-Super_Global {
1967 in-out property <int> the-property : 21;
1968 callback my-callback();
1969 }
1970 export { My-Super_Global as AliasedGlobal }
1971 export component Dummy {
1972 callback alias <=> My-Super_Global.my-callback;
1973 }"#
1974 .into(),
1975 "".into(),
1976 ),
1977 )
1978 .component("Dummy")
1979 .unwrap();
1980
1981 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1982
1983 assert!(definition.global_properties("not-there").is_none());
1984 {
1985 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1986 let expected_callbacks = vec!["my-callback".to_string()];
1987
1988 let assert_properties_and_callbacks = |global_name| {
1989 assert_eq!(
1990 definition
1991 .global_properties(global_name)
1992 .map(|props| props.collect::<Vec<_>>())
1993 .as_ref(),
1994 Some(&expected_properties)
1995 );
1996 assert_eq!(
1997 definition
1998 .global_callbacks(global_name)
1999 .map(|props| props.collect::<Vec<_>>())
2000 .as_ref(),
2001 Some(&expected_callbacks)
2002 );
2003 };
2004
2005 assert_properties_and_callbacks("My-Super-Global");
2006 assert_properties_and_callbacks("My_Super-Global");
2007 assert_properties_and_callbacks("AliasedGlobal");
2008 }
2009
2010 let instance = definition.create().unwrap();
2011 assert_eq!(
2012 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
2013 Ok(())
2014 );
2015 assert_eq!(
2016 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2017 Ok(())
2018 );
2019 assert_eq!(
2020 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2021 Err(SetPropertyError::NoSuchProperty)
2022 );
2023
2024 assert_eq!(
2025 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2026 Err(SetPropertyError::NoSuchProperty)
2027 );
2028 assert_eq!(
2029 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2030 Err(SetPropertyError::NoSuchProperty)
2031 );
2032 assert_eq!(
2033 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2034 Err(SetPropertyError::WrongType)
2035 );
2036 assert_eq!(
2037 instance.get_global_property("My-Super_Global", "yoyo"),
2038 Err(GetPropertyError::NoSuchProperty)
2039 );
2040 assert_eq!(
2041 instance.get_global_property("My-Super_Global", "the-property"),
2042 Ok(Value::Number(44.))
2043 );
2044
2045 assert_eq!(
2046 instance.set_property("the-property", Value::Void),
2047 Err(SetPropertyError::NoSuchProperty)
2048 );
2049 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2050
2051 assert_eq!(
2052 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2053 Err(SetCallbackError::NoSuchCallback)
2054 );
2055 assert_eq!(
2056 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2057 Err(SetCallbackError::NoSuchCallback)
2058 );
2059 assert_eq!(
2060 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2061 Err(SetCallbackError::NoSuchCallback)
2062 );
2063
2064 assert_eq!(
2065 instance.invoke_global("DontExist", "the-property", &[]),
2066 Err(InvokeError::NoSuchCallable)
2067 );
2068 assert_eq!(
2069 instance.invoke_global("My_Super_Global", "the-property", &[]),
2070 Err(InvokeError::NoSuchCallable)
2071 );
2072 assert_eq!(
2073 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2074 Err(InvokeError::NoSuchCallable)
2075 );
2076
2077 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2079}
2080
2081#[test]
2082fn call_functions() {
2083 i_slint_backend_testing::init_no_event_loop();
2084 let mut compiler = Compiler::default();
2085 compiler.set_style("fluent".into());
2086 let definition = spin_on::spin_on(
2087 compiler.build_from_source(
2088 r#"
2089 export global Gl {
2090 out property<string> q;
2091 public function foo-bar(a-a: string, b-b:int) -> string {
2092 q = a-a;
2093 return a-a + b-b;
2094 }
2095 }
2096 export component Test {
2097 out property<int> p;
2098 public function foo-bar(a: int, b:int) -> int {
2099 p = a;
2100 return a + b;
2101 }
2102 }"#
2103 .into(),
2104 "".into(),
2105 ),
2106 )
2107 .component("Test")
2108 .unwrap();
2109
2110 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2111 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2112
2113 let instance = definition.create().unwrap();
2114
2115 assert_eq!(
2116 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2117 Ok(Value::Number(7.))
2118 );
2119 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2120 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2121
2122 assert_eq!(
2123 instance.invoke_global(
2124 "Gl",
2125 "foo_bar",
2126 &[Value::String("Hello".into()), Value::Number(10.)]
2127 ),
2128 Ok(Value::String("Hello10".into()))
2129 );
2130 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2131}
2132
2133#[test]
2134fn component_definition_struct_properties() {
2135 i_slint_backend_testing::init_no_event_loop();
2136 let mut compiler = Compiler::default();
2137 compiler.set_style("fluent".into());
2138 let comp_def = spin_on::spin_on(
2139 compiler.build_from_source(
2140 r#"
2141 export struct Settings {
2142 string_value: string,
2143 }
2144 export component Dummy {
2145 in-out property <Settings> test;
2146 }"#
2147 .into(),
2148 "".into(),
2149 ),
2150 )
2151 .component("Dummy")
2152 .unwrap();
2153
2154 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2155
2156 assert_eq!(props.len(), 1);
2157 assert_eq!(props[0].0, "test");
2158 assert_eq!(props[0].1, ValueType::Struct);
2159
2160 let instance = comp_def.create().unwrap();
2161
2162 let valid_struct: Struct =
2163 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2164
2165 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2166 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2167
2168 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2169
2170 let mut invalid_struct = valid_struct.clone();
2171 invalid_struct.set_field("other".into(), Value::Number(44.));
2172 assert_eq!(
2173 instance.set_property("test", Value::Struct(invalid_struct)),
2174 Err(SetPropertyError::WrongType)
2175 );
2176 let mut invalid_struct = valid_struct;
2177 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2178 assert_eq!(
2179 instance.set_property("test", Value::Struct(invalid_struct)),
2180 Err(SetPropertyError::WrongType)
2181 );
2182}
2183
2184#[test]
2185fn component_definition_model_properties() {
2186 use i_slint_core::model::*;
2187 i_slint_backend_testing::init_no_event_loop();
2188 let mut compiler = Compiler::default();
2189 compiler.set_style("fluent".into());
2190 let comp_def = spin_on::spin_on(compiler.build_from_source(
2191 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2192 "".into(),
2193 ))
2194 .component("Dummy")
2195 .unwrap();
2196
2197 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2198 assert_eq!(props.len(), 1);
2199 assert_eq!(props[0].0, "prop");
2200 assert_eq!(props[0].1, ValueType::Model);
2201
2202 let instance = comp_def.create().unwrap();
2203
2204 let int_model =
2205 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2206 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2207 let model_with_string = Value::Model(VecModel::from_slice(&[
2208 Value::Number(1000.),
2209 Value::String("foo".into()),
2210 Value::Number(1111.),
2211 ]));
2212
2213 #[track_caller]
2214 fn check_model(val: Value, r: &[f64]) {
2215 if let Value::Model(m) = val {
2216 assert_eq!(r.len(), m.row_count());
2217 for (i, v) in r.iter().enumerate() {
2218 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2219 }
2220 } else {
2221 panic!("{val:?} not a model");
2222 }
2223 }
2224
2225 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2226 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2227
2228 instance.set_property("prop", int_model).unwrap();
2229 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2230
2231 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2232 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2233 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2234 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2235
2236 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2237 check_model(instance.get_property("prop").unwrap(), &[]);
2238}
2239
2240#[test]
2241fn lang_type_to_value_type() {
2242 use i_slint_compiler::langtype::Struct as LangStruct;
2243 use std::collections::BTreeMap;
2244
2245 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2246 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2247 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2248 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2249 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2250 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2251 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2252 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2253 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2254 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2255 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2256 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2257 assert_eq!(ValueType::from(LangType::Array(Rc::new(LangType::Void))), ValueType::Model);
2258 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2259 assert_eq!(
2260 ValueType::from(LangType::Struct(Rc::new(LangStruct::new(
2261 BTreeMap::default(),
2262 i_slint_compiler::langtype::StructName::None
2263 )))),
2264 ValueType::Struct
2265 );
2266 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2267}
2268
2269#[test]
2270fn test_multi_components() {
2271 i_slint_backend_testing::init_no_event_loop();
2272 let result = spin_on::spin_on(
2273 Compiler::default().build_from_source(
2274 r#"
2275 export struct Settings {
2276 string_value: string,
2277 }
2278 export global ExpGlo { in-out property <int> test: 42; }
2279 component Common {
2280 in-out property <Settings> settings: { string_value: "Hello", };
2281 }
2282 export component Xyz inherits Window {
2283 in-out property <int> aaa: 8;
2284 }
2285 export component Foo {
2286
2287 in-out property <int> test: 42;
2288 c := Common {}
2289 }
2290 export component Bar inherits Window {
2291 in-out property <int> blah: 78;
2292 c := Common {}
2293 }
2294 "#
2295 .into(),
2296 PathBuf::from("hello.slint"),
2297 ),
2298 );
2299
2300 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2301 let mut components = result.component_names().collect::<Vec<_>>();
2302 components.sort();
2303 assert_eq!(components, vec!["Bar", "Xyz"]);
2304 let diag = result.diagnostics().collect::<Vec<_>>();
2305 assert_eq!(diag.len(), 1);
2306 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2307 assert_eq!(
2308 diag[0].message(),
2309 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2310 );
2311
2312 let comp1 = result.component("Xyz").unwrap();
2313 assert_eq!(comp1.name(), "Xyz");
2314 let instance1a = comp1.create().unwrap();
2315 let comp2 = result.component("Bar").unwrap();
2316 let instance2 = comp2.create().unwrap();
2317 let instance1b = comp1.create().unwrap();
2318
2319 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2321 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2322 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2323 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2324 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2325
2326 assert!(result.component("Settings").is_none());
2327 assert!(result.component("Foo").is_none());
2328 assert!(result.component("Common").is_none());
2329 assert!(result.component("ExpGlo").is_none());
2330 assert!(result.component("xyz").is_none());
2331}
2332
2333#[cfg(all(test, feature = "internal-highlight"))]
2334fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2335 i_slint_backend_testing::init_no_event_loop();
2336 let mut compiler = Compiler::default();
2337 compiler.set_style("fluent".into());
2338 let path = PathBuf::from("/tmp/test.slint");
2339
2340 let compile_result =
2341 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2342
2343 for d in &compile_result.diagnostics {
2344 eprintln!("{d}");
2345 }
2346
2347 assert!(!compile_result.has_errors());
2348
2349 let definition = compile_result.components().next().unwrap();
2350 let instance = definition.create().unwrap();
2351
2352 (instance, path)
2353}
2354
2355#[cfg(feature = "internal-highlight")]
2356#[test]
2357fn test_element_node_at_source_code_position() {
2358 let code = r#"
2359component Bar1 {}
2360
2361component Foo1 {
2362}
2363
2364export component Foo2 inherits Window {
2365 Bar1 {}
2366 Foo1 {}
2367}"#;
2368
2369 let (handle, path) = compile(code);
2370
2371 for i in 0..code.len() as u32 {
2372 let elements = handle.element_node_at_source_code_position(&path, i);
2373 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2374 match i {
2375 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()),
2381 }
2382 }
2383}