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}
142
143impl Value {
144 pub fn value_type(&self) -> ValueType {
146 match self {
147 Value::Void => ValueType::Void,
148 Value::Number(_) => ValueType::Number,
149 Value::String(_) => ValueType::String,
150 Value::Bool(_) => ValueType::Bool,
151 Value::Model(_) => ValueType::Model,
152 Value::Struct(_) => ValueType::Struct,
153 Value::Brush(_) => ValueType::Brush,
154 Value::Image(_) => ValueType::Image,
155 _ => ValueType::Other,
156 }
157 }
158}
159
160impl PartialEq for Value {
161 fn eq(&self, other: &Self) -> bool {
162 match self {
163 Value::Void => matches!(other, Value::Void),
164 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
165 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
166 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
167 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
168 Value::Model(lhs) => {
169 if let Value::Model(rhs) = other {
170 lhs == rhs
171 } else {
172 false
173 }
174 }
175 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
176 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
177 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
178 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
179 Value::EnumerationValue(lhs_name, lhs_value) => {
180 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
181 }
182 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
183 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
184 Value::ComponentFactory(lhs) => {
185 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
186 }
187 Value::StyledText(lhs) => {
188 matches!(other, Value::StyledText(rhs) if lhs == rhs)
189 }
190 Value::Keys(lhs) => {
191 matches!(other, Value::Keys(rhs) if lhs == rhs)
192 }
193 Value::DataTransfer(lhs) => {
194 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
195 }
196 }
197 }
198}
199
200impl std::fmt::Debug for Value {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 match self {
203 Value::Void => write!(f, "Value::Void"),
204 Value::Number(n) => write!(f, "Value::Number({n:?})"),
205 Value::String(s) => write!(f, "Value::String({s:?})"),
206 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
207 Value::Image(i) => write!(f, "Value::Image({i:?})"),
208 Value::Model(m) => {
209 write!(f, "Value::Model(")?;
210 f.debug_list().entries(m.iter()).finish()?;
211 write!(f, "])")
212 }
213 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
214 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
215 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
216 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
217 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
218 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
219 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
220 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
221 Value::ArrayOfU16(data) => {
222 write!(f, "Value::ArrayOfU16({data:?})")
223 }
224 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
225 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
226 }
227 }
228}
229
230macro_rules! declare_value_conversion {
239 ( $value:ident => [$($ty:ty),*] ) => {
240 $(
241 impl From<$ty> for Value {
242 fn from(v: $ty) -> Self {
243 Value::$value(v as _)
244 }
245 }
246 impl TryFrom<Value> for $ty {
247 type Error = Value;
248 fn try_from(v: Value) -> Result<$ty, Self::Error> {
249 match v {
250 Value::$value(x) => Ok(x as _),
251 _ => Err(v)
252 }
253 }
254 }
255 )*
256 };
257}
258declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
259declare_value_conversion!(String => [SharedString] );
260declare_value_conversion!(Bool => [bool] );
261declare_value_conversion!(Image => [Image] );
262declare_value_conversion!(Struct => [Struct] );
263declare_value_conversion!(Brush => [Brush] );
264declare_value_conversion!(PathData => [PathData]);
265declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
266declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
267declare_value_conversion!(ComponentFactory => [ComponentFactory] );
268declare_value_conversion!(StyledText => [StyledText] );
269declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
270declare_value_conversion!(Keys => [Keys]);
271declare_value_conversion!(DataTransfer => [DataTransfer]);
272
273macro_rules! declare_value_struct_conversion {
275 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
276 impl From<$name> for Value {
277 fn from($name { $($field),* , .. }: $name) -> Self {
278 let mut struct_ = Struct::default();
279 $(struct_.set_field(stringify!($field).into(), $field.into());)*
280 Value::Struct(struct_)
281 }
282 }
283 impl TryFrom<Value> for $name {
284 type Error = ();
285 fn try_from(v: Value) -> Result<$name, Self::Error> {
286 #[allow(clippy::field_reassign_with_default)]
287 match v {
288 Value::Struct(x) => {
289 type Ty = $name;
290 #[allow(unused)]
291 let mut res: Ty = Ty::default();
292 $(let mut res: Ty = $extra;)?
293 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
294 Ok(res)
295 }
296 _ => Err(()),
297 }
298 }
299 }
300 };
301 ($(
302 $(#[$struct_attr:meta])*
303 $vis:vis struct $Name:ident {
304 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty, )*
305 }
306 )*) => {
307 $(
308 impl From<$Name> for Value {
309 fn from(item: $Name) -> Self {
310 let mut struct_ = Struct::default();
311 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
312 Value::Struct(struct_)
313 }
314 }
315 impl TryFrom<Value> for $Name {
316 type Error = ();
317 fn try_from(v: Value) -> Result<$Name, Self::Error> {
318 #[allow(clippy::field_reassign_with_default)]
319 match v {
320 Value::Struct(x) => {
321 type Ty = $Name;
322 #[allow(unused)]
323 let mut res: Ty = Ty::default();
324 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
325 Ok(res)
326 }
327 _ => Err(()),
328 }
329 }
330 }
331 )*
332 };
333}
334
335declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
336declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
337declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
338declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
339declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
340
341i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
342
343macro_rules! declare_value_enum_conversion {
348 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
349 impl From<i_slint_core::items::$Name> for Value {
350 fn from(v: i_slint_core::items::$Name) -> Self {
351 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
352 }
353 }
354 impl TryFrom<Value> for i_slint_core::items::$Name {
355 type Error = ();
356 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
357 use std::str::FromStr;
358 match v {
359 Value::EnumerationValue(enumeration, value) => {
360 if enumeration != stringify!($Name) {
361 return Err(());
362 }
363 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
364 }
365 _ => Err(()),
366 }
367 }
368 }
369 )*};
370}
371
372i_slint_common::for_each_enums!(declare_value_enum_conversion);
373
374impl From<i_slint_core::animations::Instant> for Value {
375 fn from(value: i_slint_core::animations::Instant) -> Self {
376 Value::Number(value.0 as _)
377 }
378}
379impl TryFrom<Value> for i_slint_core::animations::Instant {
380 type Error = ();
381 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
382 match v {
383 Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
384 _ => Err(()),
385 }
386 }
387}
388
389impl From<()> for Value {
390 #[inline]
391 fn from(_: ()) -> Self {
392 Value::Void
393 }
394}
395impl TryFrom<Value> for () {
396 type Error = ();
397 #[inline]
398 fn try_from(_: Value) -> Result<(), Self::Error> {
399 Ok(())
400 }
401}
402
403impl From<Color> for Value {
404 #[inline]
405 fn from(c: Color) -> Self {
406 Value::Brush(Brush::SolidColor(c))
407 }
408}
409impl TryFrom<Value> for Color {
410 type Error = Value;
411 #[inline]
412 fn try_from(v: Value) -> Result<Color, Self::Error> {
413 match v {
414 Value::Brush(Brush::SolidColor(c)) => Ok(c),
415 _ => Err(v),
416 }
417 }
418}
419
420impl From<i_slint_core::lengths::LogicalLength> for Value {
421 #[inline]
422 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
423 Value::Number(l.get() as _)
424 }
425}
426impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
427 type Error = Value;
428 #[inline]
429 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
430 match v {
431 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
432 _ => Err(v),
433 }
434 }
435}
436
437impl From<i_slint_core::lengths::LogicalPoint> for Value {
438 #[inline]
439 fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
440 Value::Struct(Struct::from_iter([
441 ("x".to_owned(), Value::Number(pt.x as _)),
442 ("y".to_owned(), Value::Number(pt.y as _)),
443 ]))
444 }
445}
446impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
447 type Error = Value;
448 #[inline]
449 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
450 match v {
451 Value::Struct(s) => {
452 let x = s
453 .get_field("x")
454 .cloned()
455 .unwrap_or_else(|| Value::Number(0 as _))
456 .try_into()?;
457 let y = s
458 .get_field("y")
459 .cloned()
460 .unwrap_or_else(|| Value::Number(0 as _))
461 .try_into()?;
462 Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
463 }
464 _ => Err(v),
465 }
466 }
467}
468
469impl From<i_slint_core::lengths::LogicalSize> for Value {
470 #[inline]
471 fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
472 Value::Struct(Struct::from_iter([
473 ("width".to_owned(), Value::Number(s.width as _)),
474 ("height".to_owned(), Value::Number(s.height as _)),
475 ]))
476 }
477}
478impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
479 type Error = Value;
480 #[inline]
481 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
482 match v {
483 Value::Struct(s) => {
484 let width = s
485 .get_field("width")
486 .cloned()
487 .unwrap_or_else(|| Value::Number(0 as _))
488 .try_into()?;
489 let height = s
490 .get_field("height")
491 .cloned()
492 .unwrap_or_else(|| Value::Number(0 as _))
493 .try_into()?;
494 Ok(i_slint_core::lengths::LogicalSize::new(width, height))
495 }
496 _ => Err(v),
497 }
498 }
499}
500
501impl From<i_slint_core::lengths::LogicalEdges> for Value {
502 #[inline]
503 fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
504 Value::Struct(Struct::from_iter([
505 ("left".to_owned(), Value::Number(s.left as _)),
506 ("right".to_owned(), Value::Number(s.right as _)),
507 ("top".to_owned(), Value::Number(s.top as _)),
508 ("bottom".to_owned(), Value::Number(s.bottom as _)),
509 ]))
510 }
511}
512impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
513 type Error = Value;
514 #[inline]
515 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
516 match v {
517 Value::Struct(s) => {
518 let left = s
519 .get_field("left")
520 .cloned()
521 .unwrap_or_else(|| Value::Number(0 as _))
522 .try_into()?;
523 let right = s
524 .get_field("right")
525 .cloned()
526 .unwrap_or_else(|| Value::Number(0 as _))
527 .try_into()?;
528 let top = s
529 .get_field("top")
530 .cloned()
531 .unwrap_or_else(|| Value::Number(0 as _))
532 .try_into()?;
533 let bottom = s
534 .get_field("bottom")
535 .cloned()
536 .unwrap_or_else(|| Value::Number(0 as _))
537 .try_into()?;
538 Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
539 }
540 _ => Err(v),
541 }
542 }
543}
544
545impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
546 fn from(m: ModelRc<T>) -> Self {
547 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
548 Value::Model(v.clone())
549 } else {
550 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
551 }
552 }
553}
554impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
555 type Error = Value;
556 #[inline]
557 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
558 match v {
559 Value::Model(m) => {
560 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
561 Ok(v.clone())
562 } else if let Some(v) =
563 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
564 {
565 Ok(v.0.clone())
566 } else {
567 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
568 }
569 }
570 _ => Err(v),
571 }
572 }
573}
574
575#[test]
576fn value_model_conversion() {
577 use i_slint_core::model::*;
578 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
579 let v = Value::from(m.clone());
580 assert_eq!(v, Value::Model(m.clone()));
581 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
582 assert_eq!(m2, m);
583
584 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
585 assert_eq!(int_model.row_count(), 2);
586 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
587
588 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
589 assert_eq!(m3.row_count(), 2);
590 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
591
592 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
593 assert_eq!(str_model.row_count(), 2);
594 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
596
597 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
598 assert!(err.is_err());
599
600 let model =
601 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
602
603 let value: Value = ModelRc::from(model.clone()).into();
604 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
605 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
606 value_model.set_row_data(1, Value::String("qux".into()));
607 value_model.set_row_data(0, Value::Bool(true));
608 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
609 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
611
612 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
614 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
615
616 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
617 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
618 assert_eq!(
619 model.as_ref() as *const VecModel<SharedString>,
620 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
621 as *const VecModel<SharedString>
622 );
623}
624
625pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
626 i_slint_compiler::parser::normalize_identifier(ident)
627}
628
629#[derive(Clone, PartialEq, Debug, Default)]
651pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
652impl Struct {
653 pub fn get_field(&self, name: &str) -> Option<&Value> {
655 self.0.get(&*normalize_identifier(name))
656 }
657 pub fn set_field(&mut self, name: String, value: Value) {
659 self.0.insert(normalize_identifier(&name), value);
660 }
661
662 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
664 self.0.iter().map(|(a, b)| (a.as_str(), b))
665 }
666}
667
668impl FromIterator<(String, Value)> for Struct {
669 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
670 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
671 }
672}
673
674#[deprecated(note = "Use slint_interpreter::Compiler instead")]
676pub struct ComponentCompiler {
677 config: i_slint_compiler::CompilerConfiguration,
678 diagnostics: Vec<Diagnostic>,
679}
680
681#[allow(deprecated)]
682impl Default for ComponentCompiler {
683 fn default() -> Self {
684 let mut config = i_slint_compiler::CompilerConfiguration::new(
685 i_slint_compiler::generator::OutputFormat::Interpreter,
686 );
687 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
688 Self { config, diagnostics: Vec::new() }
689 }
690}
691
692#[allow(deprecated)]
693impl ComponentCompiler {
694 pub fn new() -> Self {
696 Self::default()
697 }
698
699 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
701 self.config.include_paths = include_paths;
702 }
703
704 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
706 &self.config.include_paths
707 }
708
709 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
711 self.config.library_paths = library_paths;
712 }
713
714 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
716 &self.config.library_paths
717 }
718
719 pub fn set_style(&mut self, style: String) {
731 self.config.style = Some(style);
732 }
733
734 pub fn style(&self) -> Option<&String> {
736 self.config.style.as_ref()
737 }
738
739 pub fn set_translation_domain(&mut self, domain: String) {
741 self.config.translation_domain = Some(domain);
742 }
743
744 pub fn set_file_loader(
752 &mut self,
753 file_loader_fallback: impl Fn(
754 &Path,
755 ) -> core::pin::Pin<
756 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
757 > + 'static,
758 ) {
759 self.config.open_import_callback =
760 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
761 }
762
763 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
765 &self.diagnostics
766 }
767
768 pub async fn build_from_path<P: AsRef<Path>>(
787 &mut self,
788 path: P,
789 ) -> Option<ComponentDefinition> {
790 let path = path.as_ref();
791 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
792 Ok(s) => s,
793 Err(d) => {
794 self.diagnostics = vec![d];
795 return None;
796 }
797 };
798
799 let r = crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await;
800 self.diagnostics = r.diagnostics.into_iter().collect();
801 r.components.into_values().next()
802 }
803
804 pub async fn build_from_source(
821 &mut self,
822 source_code: String,
823 path: PathBuf,
824 ) -> Option<ComponentDefinition> {
825 let r = crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await;
826 self.diagnostics = r.diagnostics.into_iter().collect();
827 r.components.into_values().next()
828 }
829}
830
831pub struct Compiler {
834 config: i_slint_compiler::CompilerConfiguration,
835}
836
837impl Default for Compiler {
838 fn default() -> Self {
839 let config = i_slint_compiler::CompilerConfiguration::new(
840 i_slint_compiler::generator::OutputFormat::Interpreter,
841 );
842 Self { config }
843 }
844}
845
846impl Compiler {
847 pub fn new() -> Self {
849 Self::default()
850 }
851
852 #[doc(hidden)]
853 #[cfg(feature = "internal")]
854 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
855 self.config.embed_resources = embed_resources;
856 }
857
858 #[doc(hidden)]
862 #[cfg(feature = "internal")]
863 pub fn compiler_configuration(
864 &mut self,
865 _: i_slint_core::InternalToken,
866 ) -> &mut i_slint_compiler::CompilerConfiguration {
867 &mut self.config
868 }
869
870 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
872 self.config.include_paths = include_paths;
873 }
874
875 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
877 &self.config.include_paths
878 }
879
880 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
882 self.config.library_paths = library_paths;
883 }
884
885 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
887 &self.config.library_paths
888 }
889
890 pub fn set_style(&mut self, style: String) {
901 self.config.style = Some(style);
902 }
903
904 pub fn style(&self) -> Option<&String> {
906 self.config.style.as_ref()
907 }
908
909 pub fn set_translation_domain(&mut self, domain: String) {
911 self.config.translation_domain = Some(domain);
912 }
913
914 pub fn set_default_translation_context(
920 &mut self,
921 default_translation_context: DefaultTranslationContext,
922 ) {
923 self.config.default_translation_context = default_translation_context;
924 }
925
926 pub fn set_file_loader(
934 &mut self,
935 file_loader_fallback: impl Fn(
936 &Path,
937 ) -> core::pin::Pin<
938 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
939 > + 'static,
940 ) {
941 self.config.open_import_callback =
942 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
943 }
944
945 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
964 let path = path.as_ref();
965 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
966 Ok(s) => s,
967 Err(d) => {
968 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
969 diagnostics.push_compiler_error(d);
970 return CompilationResult {
971 components: HashMap::new(),
972 diagnostics: diagnostics.into_iter().collect(),
973 #[cfg(feature = "internal")]
974 watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
975 #[cfg(feature = "internal")]
976 structs_and_enums: Vec::new(),
977 #[cfg(feature = "internal")]
978 named_exports: Vec::new(),
979 };
980 }
981 };
982
983 crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await
984 }
985
986 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
999 crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await
1000 }
1001}
1002
1003#[derive(Clone)]
1010pub struct CompilationResult {
1011 pub(crate) components: HashMap<String, ComponentDefinition>,
1012 pub(crate) diagnostics: Vec<Diagnostic>,
1013 #[cfg(feature = "internal")]
1014 pub(crate) watch_paths: Vec<PathBuf>,
1015 #[cfg(feature = "internal")]
1016 pub(crate) structs_and_enums: Vec<LangType>,
1017 #[cfg(feature = "internal")]
1019 pub(crate) named_exports: Vec<(String, String)>,
1020}
1021
1022impl core::fmt::Debug for CompilationResult {
1023 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1024 f.debug_struct("CompilationResult")
1025 .field("components", &self.components.keys())
1026 .field("diagnostics", &self.diagnostics)
1027 .finish()
1028 }
1029}
1030
1031impl CompilationResult {
1032 pub fn has_errors(&self) -> bool {
1035 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1036 }
1037
1038 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1042 self.diagnostics.iter().cloned()
1043 }
1044
1045 #[cfg(feature = "display-diagnostics")]
1051 pub fn print_diagnostics(&self) {
1052 print_diagnostics(&self.diagnostics)
1053 }
1054
1055 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1057 self.components.values().cloned()
1058 }
1059
1060 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1062 self.components.keys().map(|s| s.as_str())
1063 }
1064
1065 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1068 self.components.get(name).cloned()
1069 }
1070
1071 #[doc(hidden)]
1073 #[cfg(feature = "internal")]
1074 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1075 &self.watch_paths
1076 }
1077
1078 #[doc(hidden)]
1080 #[cfg(feature = "internal")]
1081 pub fn structs_and_enums(
1082 &self,
1083 _: i_slint_core::InternalToken,
1084 ) -> impl Iterator<Item = &LangType> {
1085 self.structs_and_enums.iter()
1086 }
1087
1088 #[doc(hidden)]
1091 #[cfg(feature = "internal")]
1092 pub fn named_exports(
1093 &self,
1094 _: i_slint_core::InternalToken,
1095 ) -> impl Iterator<Item = &(String, String)> {
1096 self.named_exports.iter()
1097 }
1098}
1099
1100#[derive(Clone)]
1108pub struct ComponentDefinition {
1109 pub(crate) inner: crate::dynamic_item_tree::ErasedItemTreeDescription,
1110}
1111
1112impl ComponentDefinition {
1113 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1115 let instance = self.create_with_options(Default::default())?;
1116 if !instance.is_system_tray_rooted() {
1119 instance.inner.window_adapter_ref()?;
1121 i_slint_core::window::WindowInner::from_pub(instance.window())
1124 .ensure_tree_instantiated();
1125 }
1126 Ok(instance)
1127 }
1128
1129 #[doc(hidden)]
1131 #[cfg(feature = "internal")]
1132 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1133 self.create_with_options(WindowOptions::Embed {
1134 parent_item_tree: ctx.parent_item_tree,
1135 parent_item_tree_index: ctx.parent_item_tree_index,
1136 })
1137 }
1138
1139 #[doc(hidden)]
1141 #[cfg(feature = "internal")]
1142 pub fn create_with_existing_window(
1143 &self,
1144 window: &Window,
1145 ) -> Result<ComponentInstance, PlatformError> {
1146 self.create_with_options(WindowOptions::UseExistingWindow(
1147 WindowInner::from_pub(window).window_adapter(),
1148 ))
1149 }
1150
1151 pub(crate) fn create_with_options(
1153 &self,
1154 options: WindowOptions,
1155 ) -> Result<ComponentInstance, PlatformError> {
1156 generativity::make_guard!(guard);
1157 Ok(ComponentInstance { inner: self.inner.unerase(guard).clone().create(options)? })
1158 }
1159
1160 #[doc(hidden)]
1164 #[cfg(feature = "internal")]
1165 pub fn properties_and_callbacks(
1166 &self,
1167 ) -> impl Iterator<
1168 Item = (
1169 String,
1170 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1171 ),
1172 > + '_ {
1173 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1176 self.inner.unerase(guard).properties().map(|(s, t, v)| (s.to_string(), (t, v)))
1177 }
1178
1179 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1182 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1185 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1186 if prop_type.is_property_type() {
1187 Some((prop_name.to_string(), prop_type.into()))
1188 } else {
1189 None
1190 }
1191 })
1192 }
1193
1194 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1196 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1199 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1200 if matches!(prop_type, LangType::Callback { .. }) {
1201 Some(prop_name.to_string())
1202 } else {
1203 None
1204 }
1205 })
1206 }
1207
1208 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1210 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1213 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1214 if matches!(prop_type, LangType::Function { .. }) {
1215 Some(prop_name.to_string())
1216 } else {
1217 None
1218 }
1219 })
1220 }
1221
1222 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1227 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1230 self.inner.unerase(guard).global_names().map(|s| s.to_string())
1231 }
1232
1233 #[doc(hidden)]
1237 #[cfg(feature = "internal")]
1238 pub fn global_properties_and_callbacks(
1239 &self,
1240 global_name: &str,
1241 ) -> Option<
1242 impl Iterator<
1243 Item = (
1244 String,
1245 (
1246 i_slint_compiler::langtype::Type,
1247 i_slint_compiler::object_tree::PropertyVisibility,
1248 ),
1249 ),
1250 > + '_,
1251 > {
1252 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1255 self.inner
1256 .unerase(guard)
1257 .global_properties(global_name)
1258 .map(|o| o.map(|(s, t, v)| (s.to_string(), (t, v))))
1259 }
1260
1261 pub fn global_properties(
1263 &self,
1264 global_name: &str,
1265 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1266 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1269 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1270 iter.filter_map(|(prop_name, prop_type, _)| {
1271 if prop_type.is_property_type() {
1272 Some((prop_name.to_string(), prop_type.into()))
1273 } else {
1274 None
1275 }
1276 })
1277 })
1278 }
1279
1280 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1282 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1285 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1286 iter.filter_map(|(prop_name, prop_type, _)| {
1287 if matches!(prop_type, LangType::Callback { .. }) {
1288 Some(prop_name.to_string())
1289 } else {
1290 None
1291 }
1292 })
1293 })
1294 }
1295
1296 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1298 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1301 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1302 iter.filter_map(|(prop_name, prop_type, _)| {
1303 if matches!(prop_type, LangType::Function { .. }) {
1304 Some(prop_name.to_string())
1305 } else {
1306 None
1307 }
1308 })
1309 })
1310 }
1311
1312 pub fn name(&self) -> &str {
1314 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1317 self.inner.unerase(guard).id()
1318 }
1319
1320 #[doc(hidden)]
1324 #[cfg(feature = "internal")]
1325 pub fn is_window(&self) -> bool {
1326 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1327 !self.inner.unerase(guard).original.inherits_system_tray_icon()
1328 }
1329
1330 #[cfg(feature = "internal")]
1332 #[doc(hidden)]
1333 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1334 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1335 self.inner.unerase(guard).original.clone()
1336 }
1337
1338 #[cfg(feature = "internal-highlight")]
1342 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1343 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1344 self.inner.unerase(guard).type_loader.get().unwrap().clone()
1345 }
1346
1347 #[cfg(feature = "internal-highlight")]
1355 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1356 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1357 self.inner
1358 .unerase(guard)
1359 .raw_type_loader
1360 .get()
1361 .unwrap()
1362 .as_ref()
1363 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1364 }
1365}
1366
1367#[cfg(feature = "display-diagnostics")]
1373pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1374 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1375 for d in diagnostics {
1376 build_diagnostics.push_compiler_error(d.clone())
1377 }
1378 build_diagnostics.print();
1379}
1380
1381#[repr(C)]
1389pub struct ComponentInstance {
1390 pub(crate) inner: crate::dynamic_item_tree::DynamicComponentVRc,
1391}
1392
1393impl ComponentInstance {
1394 pub fn definition(&self) -> ComponentDefinition {
1396 generativity::make_guard!(guard);
1397 ComponentDefinition { inner: self.inner.unerase(guard).description().into() }
1398 }
1399
1400 fn is_system_tray_rooted(&self) -> bool {
1401 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1402 self.inner.unerase(guard).description().original.inherits_system_tray_icon()
1403 }
1404
1405 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1425 generativity::make_guard!(guard);
1426 let comp = self.inner.unerase(guard);
1427 let name = normalize_identifier(name);
1428
1429 if comp
1430 .description()
1431 .original
1432 .root_element
1433 .borrow()
1434 .property_declarations
1435 .get(&name)
1436 .is_none_or(|d| !d.expose_in_public_api)
1437 {
1438 return Err(GetPropertyError::NoSuchProperty);
1439 }
1440
1441 comp.description()
1442 .get_property(comp.borrow(), &name)
1443 .map_err(|()| GetPropertyError::NoSuchProperty)
1444 }
1445
1446 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1448 let name = normalize_identifier(name);
1449 generativity::make_guard!(guard);
1450 let comp = self.inner.unerase(guard);
1451 let d = comp.description();
1452 let elem = d.original.root_element.borrow();
1453 let decl = elem.property_declarations.get(&name).ok_or(SetPropertyError::NoSuchProperty)?;
1454
1455 if !decl.expose_in_public_api {
1456 return Err(SetPropertyError::NoSuchProperty);
1457 } else if decl.visibility == i_slint_compiler::object_tree::PropertyVisibility::Output {
1458 return Err(SetPropertyError::AccessDenied);
1459 }
1460
1461 d.set_property(comp.borrow(), &name, value)
1462 }
1463
1464 pub fn set_callback(
1499 &self,
1500 name: &str,
1501 callback: impl Fn(&[Value]) -> Value + 'static,
1502 ) -> Result<(), SetCallbackError> {
1503 generativity::make_guard!(guard);
1504 let comp = self.inner.unerase(guard);
1505 comp.description()
1506 .set_callback_handler(comp.borrow(), &normalize_identifier(name), Box::new(callback))
1507 .map_err(|()| SetCallbackError::NoSuchCallback)
1508 }
1509
1510 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1515 generativity::make_guard!(guard);
1516 let comp = self.inner.unerase(guard);
1517 comp.description()
1518 .invoke(comp.borrow(), &normalize_identifier(name), args)
1519 .map_err(|()| InvokeError::NoSuchCallable)
1520 }
1521
1522 pub fn get_global_property(
1547 &self,
1548 global: &str,
1549 property: &str,
1550 ) -> Result<Value, GetPropertyError> {
1551 generativity::make_guard!(guard);
1552 let comp = self.inner.unerase(guard);
1553 comp.description()
1554 .get_global(comp.borrow(), &normalize_identifier(global))
1555 .map_err(|()| GetPropertyError::NoSuchProperty)? .as_ref()
1557 .get_property(&normalize_identifier(property))
1558 .map_err(|()| GetPropertyError::NoSuchProperty)
1559 }
1560
1561 pub fn set_global_property(
1563 &self,
1564 global: &str,
1565 property: &str,
1566 value: Value,
1567 ) -> Result<(), SetPropertyError> {
1568 generativity::make_guard!(guard);
1569 let comp = self.inner.unerase(guard);
1570 comp.description()
1571 .get_global(comp.borrow(), &normalize_identifier(global))
1572 .map_err(|()| SetPropertyError::NoSuchProperty)? .as_ref()
1574 .set_property(&normalize_identifier(property), value)
1575 }
1576
1577 pub fn set_global_callback(
1612 &self,
1613 global: &str,
1614 name: &str,
1615 callback: impl Fn(&[Value]) -> Value + 'static,
1616 ) -> Result<(), SetCallbackError> {
1617 generativity::make_guard!(guard);
1618 let comp = self.inner.unerase(guard);
1619 comp.description()
1620 .get_global(comp.borrow(), &normalize_identifier(global))
1621 .map_err(|()| SetCallbackError::NoSuchCallback)? .as_ref()
1623 .set_callback_handler(&normalize_identifier(name), Box::new(callback))
1624 .map_err(|()| SetCallbackError::NoSuchCallback)
1625 }
1626
1627 pub fn invoke_global(
1632 &self,
1633 global: &str,
1634 callable_name: &str,
1635 args: &[Value],
1636 ) -> Result<Value, InvokeError> {
1637 generativity::make_guard!(guard);
1638 let comp = self.inner.unerase(guard);
1639 let g = comp
1640 .description()
1641 .get_global(comp.borrow(), &normalize_identifier(global))
1642 .map_err(|()| InvokeError::NoSuchCallable)?; let callable_name = normalize_identifier(callable_name);
1644 if matches!(
1645 comp.description()
1646 .original
1647 .root_element
1648 .borrow()
1649 .lookup_property(&callable_name)
1650 .property_type,
1651 LangType::Function { .. }
1652 ) {
1653 g.as_ref()
1654 .eval_function(&callable_name, args.to_vec())
1655 .map_err(|()| InvokeError::NoSuchCallable)
1656 } else {
1657 g.as_ref()
1658 .invoke_callback(&callable_name, args)
1659 .map_err(|()| InvokeError::NoSuchCallable)
1660 }
1661 }
1662
1663 #[cfg(feature = "internal-highlight")]
1667 pub fn component_positions(
1668 &self,
1669 path: &Path,
1670 offset: u32,
1671 ) -> Vec<crate::highlight::HighlightedRect> {
1672 crate::highlight::component_positions(&self.inner, path, offset)
1673 }
1674
1675 #[cfg(feature = "internal-highlight")]
1679 pub fn element_positions(
1680 &self,
1681 element: &i_slint_compiler::object_tree::ElementRc,
1682 ) -> Vec<crate::highlight::HighlightedRect> {
1683 crate::highlight::element_positions(
1684 &self.inner,
1685 element,
1686 crate::highlight::ElementPositionFilter::IncludeClipped,
1687 )
1688 }
1689
1690 #[cfg(feature = "internal-highlight")]
1694 pub fn element_node_at_source_code_position(
1695 &self,
1696 path: &Path,
1697 offset: u32,
1698 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1699 crate::highlight::element_node_at_source_code_position(&self.inner, path, offset)
1700 }
1701}
1702
1703impl StrongHandle for ComponentInstance {
1704 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::dynamic_item_tree::ErasedItemTreeBox>;
1705
1706 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1707 Some(Self { inner: inner.upgrade()? })
1708 }
1709}
1710
1711impl ComponentHandle for ComponentInstance {
1712 fn as_weak(&self) -> Weak<Self>
1713 where
1714 Self: Sized,
1715 {
1716 Weak::new(vtable::VRc::downgrade(&self.inner))
1717 }
1718
1719 fn clone_strong(&self) -> Self {
1720 Self { inner: self.inner.clone() }
1721 }
1722
1723 fn show(&self) -> Result<(), PlatformError> {
1724 if self.is_system_tray_rooted() {
1725 self.set_property("visible", Value::Bool(true)).expect(
1729 "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1730 );
1731 return Ok(());
1732 }
1733 self.inner.window_adapter_ref()?.window().show()
1734 }
1735
1736 fn hide(&self) -> Result<(), PlatformError> {
1737 if self.is_system_tray_rooted() {
1738 self.set_property("visible", Value::Bool(false)).expect(
1739 "setting `visible` on a SystemTrayIcon-rooted component should always succeed",
1740 );
1741 return Ok(());
1742 }
1743 self.inner.window_adapter_ref()?.window().hide()
1744 }
1745
1746 fn run(&self) -> Result<(), PlatformError> {
1747 self.show()?;
1748 run_event_loop()?;
1749 self.hide()
1750 }
1751
1752 fn window(&self) -> &Window {
1753 self.inner.window_adapter_ref().unwrap().window()
1754 }
1755
1756 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1757 where
1758 Self: Sized,
1759 {
1760 unreachable!()
1761 }
1762}
1763
1764impl From<ComponentInstance>
1765 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, ErasedItemTreeBox>
1766{
1767 fn from(value: ComponentInstance) -> Self {
1768 value.inner
1769 }
1770}
1771
1772#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1774#[non_exhaustive]
1775pub enum GetPropertyError {
1776 #[display("no such property")]
1778 NoSuchProperty,
1779}
1780
1781#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1783#[non_exhaustive]
1784pub enum SetPropertyError {
1785 #[display("no such property")]
1787 NoSuchProperty,
1788 #[display("wrong type")]
1794 WrongType,
1795 #[display("access denied")]
1797 AccessDenied,
1798}
1799
1800#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1802#[non_exhaustive]
1803pub enum SetCallbackError {
1804 #[display("no such callback")]
1806 NoSuchCallback,
1807}
1808
1809#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1811#[non_exhaustive]
1812pub enum InvokeError {
1813 #[display("no such callback or function")]
1815 NoSuchCallable,
1816}
1817
1818pub fn run_event_loop() -> Result<(), PlatformError> {
1822 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1823}
1824
1825pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1829 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1830 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1831}
1832
1833#[test]
1834fn component_definition_properties() {
1835 i_slint_backend_testing::init_no_event_loop();
1836 let mut compiler = Compiler::default();
1837 compiler.set_style("fluent".into());
1838 let comp_def = spin_on::spin_on(
1839 compiler.build_from_source(
1840 r#"
1841 export component Dummy {
1842 in-out property <string> test;
1843 in-out property <int> underscores-and-dashes_preserved: 44;
1844 callback hello;
1845 }"#
1846 .into(),
1847 "".into(),
1848 ),
1849 )
1850 .component("Dummy")
1851 .unwrap();
1852
1853 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1854
1855 assert_eq!(props.len(), 2);
1856 assert_eq!(props[0].0, "test");
1857 assert_eq!(props[0].1, ValueType::String);
1858 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1859 assert_eq!(props[1].1, ValueType::Number);
1860
1861 let instance = comp_def.create().unwrap();
1862 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1863 assert_eq!(
1864 instance.get_property("underscoresanddashespreserved"),
1865 Err(GetPropertyError::NoSuchProperty)
1866 );
1867 assert_eq!(
1868 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1869 Ok(())
1870 );
1871 assert_eq!(
1872 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1873 Err(SetPropertyError::NoSuchProperty)
1874 );
1875 assert_eq!(
1876 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1877 Err(SetPropertyError::WrongType)
1878 );
1879 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1880}
1881
1882#[test]
1883fn component_definition_properties2() {
1884 i_slint_backend_testing::init_no_event_loop();
1885 let mut compiler = Compiler::default();
1886 compiler.set_style("fluent".into());
1887 let comp_def = spin_on::spin_on(
1888 compiler.build_from_source(
1889 r#"
1890 export component Dummy {
1891 in-out property <string> sub-text <=> sub.text;
1892 sub := Text { property <int> private-not-exported; }
1893 out property <string> xreadonly: "the value";
1894 private property <string> xx: sub.text;
1895 callback hello;
1896 }"#
1897 .into(),
1898 "".into(),
1899 ),
1900 )
1901 .component("Dummy")
1902 .unwrap();
1903
1904 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1905
1906 assert_eq!(props.len(), 2);
1907 assert_eq!(props[0].0, "sub-text");
1908 assert_eq!(props[0].1, ValueType::String);
1909 assert_eq!(props[1].0, "xreadonly");
1910
1911 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1912 assert_eq!(callbacks.len(), 1);
1913 assert_eq!(callbacks[0], "hello");
1914
1915 let instance = comp_def.create().unwrap();
1916 assert_eq!(
1917 instance.set_property("xreadonly", SharedString::from("XXX").into()),
1918 Err(SetPropertyError::AccessDenied)
1919 );
1920 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1921 assert_eq!(
1922 instance.set_property("xx", SharedString::from("XXX").into()),
1923 Err(SetPropertyError::NoSuchProperty)
1924 );
1925 assert_eq!(
1926 instance.set_property("background", Value::default()),
1927 Err(SetPropertyError::NoSuchProperty)
1928 );
1929
1930 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1931 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1932}
1933
1934#[test]
1935fn globals() {
1936 i_slint_backend_testing::init_no_event_loop();
1937 let mut compiler = Compiler::default();
1938 compiler.set_style("fluent".into());
1939 let definition = spin_on::spin_on(
1940 compiler.build_from_source(
1941 r#"
1942 export global My-Super_Global {
1943 in-out property <int> the-property : 21;
1944 callback my-callback();
1945 }
1946 export { My-Super_Global as AliasedGlobal }
1947 export component Dummy {
1948 callback alias <=> My-Super_Global.my-callback;
1949 }"#
1950 .into(),
1951 "".into(),
1952 ),
1953 )
1954 .component("Dummy")
1955 .unwrap();
1956
1957 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1958
1959 assert!(definition.global_properties("not-there").is_none());
1960 {
1961 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1962 let expected_callbacks = vec!["my-callback".to_string()];
1963
1964 let assert_properties_and_callbacks = |global_name| {
1965 assert_eq!(
1966 definition
1967 .global_properties(global_name)
1968 .map(|props| props.collect::<Vec<_>>())
1969 .as_ref(),
1970 Some(&expected_properties)
1971 );
1972 assert_eq!(
1973 definition
1974 .global_callbacks(global_name)
1975 .map(|props| props.collect::<Vec<_>>())
1976 .as_ref(),
1977 Some(&expected_callbacks)
1978 );
1979 };
1980
1981 assert_properties_and_callbacks("My-Super-Global");
1982 assert_properties_and_callbacks("My_Super-Global");
1983 assert_properties_and_callbacks("AliasedGlobal");
1984 }
1985
1986 let instance = definition.create().unwrap();
1987 assert_eq!(
1988 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
1989 Ok(())
1990 );
1991 assert_eq!(
1992 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
1993 Ok(())
1994 );
1995 assert_eq!(
1996 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
1997 Err(SetPropertyError::NoSuchProperty)
1998 );
1999
2000 assert_eq!(
2001 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2002 Err(SetPropertyError::NoSuchProperty)
2003 );
2004 assert_eq!(
2005 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2006 Err(SetPropertyError::NoSuchProperty)
2007 );
2008 assert_eq!(
2009 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2010 Err(SetPropertyError::WrongType)
2011 );
2012 assert_eq!(
2013 instance.get_global_property("My-Super_Global", "yoyo"),
2014 Err(GetPropertyError::NoSuchProperty)
2015 );
2016 assert_eq!(
2017 instance.get_global_property("My-Super_Global", "the-property"),
2018 Ok(Value::Number(44.))
2019 );
2020
2021 assert_eq!(
2022 instance.set_property("the-property", Value::Void),
2023 Err(SetPropertyError::NoSuchProperty)
2024 );
2025 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2026
2027 assert_eq!(
2028 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2029 Err(SetCallbackError::NoSuchCallback)
2030 );
2031 assert_eq!(
2032 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2033 Err(SetCallbackError::NoSuchCallback)
2034 );
2035 assert_eq!(
2036 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2037 Err(SetCallbackError::NoSuchCallback)
2038 );
2039
2040 assert_eq!(
2041 instance.invoke_global("DontExist", "the-property", &[]),
2042 Err(InvokeError::NoSuchCallable)
2043 );
2044 assert_eq!(
2045 instance.invoke_global("My_Super_Global", "the-property", &[]),
2046 Err(InvokeError::NoSuchCallable)
2047 );
2048 assert_eq!(
2049 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2050 Err(InvokeError::NoSuchCallable)
2051 );
2052
2053 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2055}
2056
2057#[test]
2058fn call_functions() {
2059 i_slint_backend_testing::init_no_event_loop();
2060 let mut compiler = Compiler::default();
2061 compiler.set_style("fluent".into());
2062 let definition = spin_on::spin_on(
2063 compiler.build_from_source(
2064 r#"
2065 export global Gl {
2066 out property<string> q;
2067 public function foo-bar(a-a: string, b-b:int) -> string {
2068 q = a-a;
2069 return a-a + b-b;
2070 }
2071 }
2072 export component Test {
2073 out property<int> p;
2074 public function foo-bar(a: int, b:int) -> int {
2075 p = a;
2076 return a + b;
2077 }
2078 }"#
2079 .into(),
2080 "".into(),
2081 ),
2082 )
2083 .component("Test")
2084 .unwrap();
2085
2086 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2087 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2088
2089 let instance = definition.create().unwrap();
2090
2091 assert_eq!(
2092 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2093 Ok(Value::Number(7.))
2094 );
2095 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2096 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2097
2098 assert_eq!(
2099 instance.invoke_global(
2100 "Gl",
2101 "foo_bar",
2102 &[Value::String("Hello".into()), Value::Number(10.)]
2103 ),
2104 Ok(Value::String("Hello10".into()))
2105 );
2106 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2107}
2108
2109#[test]
2110fn component_definition_struct_properties() {
2111 i_slint_backend_testing::init_no_event_loop();
2112 let mut compiler = Compiler::default();
2113 compiler.set_style("fluent".into());
2114 let comp_def = spin_on::spin_on(
2115 compiler.build_from_source(
2116 r#"
2117 export struct Settings {
2118 string_value: string,
2119 }
2120 export component Dummy {
2121 in-out property <Settings> test;
2122 }"#
2123 .into(),
2124 "".into(),
2125 ),
2126 )
2127 .component("Dummy")
2128 .unwrap();
2129
2130 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2131
2132 assert_eq!(props.len(), 1);
2133 assert_eq!(props[0].0, "test");
2134 assert_eq!(props[0].1, ValueType::Struct);
2135
2136 let instance = comp_def.create().unwrap();
2137
2138 let valid_struct: Struct =
2139 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2140
2141 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2142 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2143
2144 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2145
2146 let mut invalid_struct = valid_struct.clone();
2147 invalid_struct.set_field("other".into(), Value::Number(44.));
2148 assert_eq!(
2149 instance.set_property("test", Value::Struct(invalid_struct)),
2150 Err(SetPropertyError::WrongType)
2151 );
2152 let mut invalid_struct = valid_struct;
2153 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2154 assert_eq!(
2155 instance.set_property("test", Value::Struct(invalid_struct)),
2156 Err(SetPropertyError::WrongType)
2157 );
2158}
2159
2160#[test]
2161fn component_definition_model_properties() {
2162 use i_slint_core::model::*;
2163 i_slint_backend_testing::init_no_event_loop();
2164 let mut compiler = Compiler::default();
2165 compiler.set_style("fluent".into());
2166 let comp_def = spin_on::spin_on(compiler.build_from_source(
2167 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2168 "".into(),
2169 ))
2170 .component("Dummy")
2171 .unwrap();
2172
2173 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2174 assert_eq!(props.len(), 1);
2175 assert_eq!(props[0].0, "prop");
2176 assert_eq!(props[0].1, ValueType::Model);
2177
2178 let instance = comp_def.create().unwrap();
2179
2180 let int_model =
2181 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2182 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2183 let model_with_string = Value::Model(VecModel::from_slice(&[
2184 Value::Number(1000.),
2185 Value::String("foo".into()),
2186 Value::Number(1111.),
2187 ]));
2188
2189 #[track_caller]
2190 fn check_model(val: Value, r: &[f64]) {
2191 if let Value::Model(m) = val {
2192 assert_eq!(r.len(), m.row_count());
2193 for (i, v) in r.iter().enumerate() {
2194 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2195 }
2196 } else {
2197 panic!("{val:?} not a model");
2198 }
2199 }
2200
2201 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2202 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2203
2204 instance.set_property("prop", int_model).unwrap();
2205 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2206
2207 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2208 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2209 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2210 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2211
2212 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2213 check_model(instance.get_property("prop").unwrap(), &[]);
2214}
2215
2216#[test]
2217fn lang_type_to_value_type() {
2218 use i_slint_compiler::langtype::Struct as LangStruct;
2219 use std::collections::BTreeMap;
2220
2221 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2222 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2223 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2224 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2225 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2226 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2227 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2228 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2229 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2230 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2231 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2232 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2233 assert_eq!(ValueType::from(LangType::Array(Rc::new(LangType::Void))), ValueType::Model);
2234 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2235 assert_eq!(
2236 ValueType::from(LangType::Struct(Rc::new(LangStruct {
2237 fields: BTreeMap::default(),
2238 name: i_slint_compiler::langtype::StructName::None,
2239 }))),
2240 ValueType::Struct
2241 );
2242 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2243}
2244
2245#[test]
2246fn test_multi_components() {
2247 i_slint_backend_testing::init_no_event_loop();
2248 let result = spin_on::spin_on(
2249 Compiler::default().build_from_source(
2250 r#"
2251 export struct Settings {
2252 string_value: string,
2253 }
2254 export global ExpGlo { in-out property <int> test: 42; }
2255 component Common {
2256 in-out property <Settings> settings: { string_value: "Hello", };
2257 }
2258 export component Xyz inherits Window {
2259 in-out property <int> aaa: 8;
2260 }
2261 export component Foo {
2262
2263 in-out property <int> test: 42;
2264 c := Common {}
2265 }
2266 export component Bar inherits Window {
2267 in-out property <int> blah: 78;
2268 c := Common {}
2269 }
2270 "#
2271 .into(),
2272 PathBuf::from("hello.slint"),
2273 ),
2274 );
2275
2276 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2277 let mut components = result.component_names().collect::<Vec<_>>();
2278 components.sort();
2279 assert_eq!(components, vec!["Bar", "Xyz"]);
2280 let diag = result.diagnostics().collect::<Vec<_>>();
2281 assert_eq!(diag.len(), 1);
2282 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2283 assert_eq!(
2284 diag[0].message(),
2285 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2286 );
2287
2288 let comp1 = result.component("Xyz").unwrap();
2289 assert_eq!(comp1.name(), "Xyz");
2290 let instance1a = comp1.create().unwrap();
2291 let comp2 = result.component("Bar").unwrap();
2292 let instance2 = comp2.create().unwrap();
2293 let instance1b = comp1.create().unwrap();
2294
2295 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2297 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2298 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2299 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2300 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2301
2302 assert!(result.component("Settings").is_none());
2303 assert!(result.component("Foo").is_none());
2304 assert!(result.component("Common").is_none());
2305 assert!(result.component("ExpGlo").is_none());
2306 assert!(result.component("xyz").is_none());
2307}
2308
2309#[cfg(all(test, feature = "internal-highlight"))]
2310fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2311 i_slint_backend_testing::init_no_event_loop();
2312 let mut compiler = Compiler::default();
2313 compiler.set_style("fluent".into());
2314 let path = PathBuf::from("/tmp/test.slint");
2315
2316 let compile_result =
2317 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2318
2319 for d in &compile_result.diagnostics {
2320 eprintln!("{d}");
2321 }
2322
2323 assert!(!compile_result.has_errors());
2324
2325 let definition = compile_result.components().next().unwrap();
2326 let instance = definition.create().unwrap();
2327
2328 (instance, path)
2329}
2330
2331#[cfg(feature = "internal-highlight")]
2332#[test]
2333fn test_element_node_at_source_code_position() {
2334 let code = r#"
2335component Bar1 {}
2336
2337component Foo1 {
2338}
2339
2340export component Foo2 inherits Window {
2341 Bar1 {}
2342 Foo1 {}
2343}"#;
2344
2345 let (handle, path) = compile(code);
2346
2347 for i in 0..code.len() as u32 {
2348 let elements = handle.element_node_at_source_code_position(&path, i);
2349 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2350 match i {
2351 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()),
2357 }
2358 }
2359}
2360
2361#[cfg(feature = "ffi")]
2362#[doc(hidden)]
2363#[allow(missing_docs)]
2364#[path = "ffi.rs"]
2365pub mod ffi;