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#[cfg(test)]
23use std::sync::Arc;
24
25#[doc(inline)]
26pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
27
28pub use i_slint_backend_selector::api::*;
29pub use i_slint_core::api::*;
30
31pub use i_slint_compiler::DefaultTranslationContext;
34
35#[derive(Debug, Copy, Clone, PartialEq)]
38#[repr(i8)]
39#[non_exhaustive]
40pub enum ValueType {
41 Void,
43 Number,
45 String,
47 Bool,
49 Model,
51 Struct,
53 Brush,
55 Image,
57 #[doc(hidden)]
59 Other = -1,
60}
61
62impl From<LangType> for ValueType {
63 fn from(ty: LangType) -> Self {
64 match ty {
65 LangType::Float32
66 | LangType::Int32
67 | LangType::Duration
68 | LangType::Angle
69 | LangType::PhysicalLength
70 | LangType::LogicalLength
71 | LangType::Percent
72 | LangType::UnitProduct(_) => Self::Number,
73 LangType::String => Self::String,
74 LangType::Color => Self::Brush,
75 LangType::Brush => Self::Brush,
76 LangType::Array(_) => Self::Model,
77 LangType::Bool => Self::Bool,
78 LangType::Struct { .. } => Self::Struct,
79 LangType::Void => Self::Void,
80 LangType::Image => Self::Image,
81 _ => Self::Other,
82 }
83 }
84}
85
86#[derive(Clone, Default)]
98#[non_exhaustive]
99#[repr(u8)]
100pub enum Value {
101 #[default]
104 Void = 0,
105 Number(f64) = 1,
107 String(SharedString) = 2,
109 Bool(bool) = 3,
111 Image(Image) = 4,
113 Model(ModelRc<Value>) = 5,
115 Struct(Struct) = 6,
117 Brush(Brush) = 7,
119 #[doc(hidden)]
120 PathData(PathData) = 8,
122 #[doc(hidden)]
123 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
125 #[doc(hidden)]
126 EnumerationValue(String, String) = 10,
129 #[doc(hidden)]
130 LayoutCache(SharedVector<f32>) = 11,
131 #[doc(hidden)]
132 ComponentFactory(ComponentFactory) = 12,
134 #[doc(hidden)] StyledText(StyledText) = 13,
137 #[doc(hidden)]
138 ArrayOfU16(SharedVector<u16>) = 14,
139 Keys(Keys) = 15,
141 DataTransfer(DataTransfer) = 16,
143 #[doc(hidden)]
144 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
146}
147
148impl Value {
149 pub fn value_type(&self) -> ValueType {
151 match self {
152 Value::Void => ValueType::Void,
153 Value::Number(_) => ValueType::Number,
154 Value::String(_) => ValueType::String,
155 Value::Bool(_) => ValueType::Bool,
156 Value::Model(_) => ValueType::Model,
157 Value::Struct(_) => ValueType::Struct,
158 Value::Brush(_) => ValueType::Brush,
159 Value::Image(_) => ValueType::Image,
160 _ => ValueType::Other,
161 }
162 }
163}
164
165impl PartialEq for Value {
166 fn eq(&self, other: &Self) -> bool {
167 match self {
168 Value::Void => matches!(other, Value::Void),
169 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
170 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
171 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
172 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
173 Value::Model(lhs) => {
174 if let Value::Model(rhs) = other {
175 lhs == rhs
176 } else {
177 false
178 }
179 }
180 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
181 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
182 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
183 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
184 Value::EnumerationValue(lhs_name, lhs_value) => {
185 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
186 }
187 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
188 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
189 Value::ComponentFactory(lhs) => {
190 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
191 }
192 Value::StyledText(lhs) => {
193 matches!(other, Value::StyledText(rhs) if lhs == rhs)
194 }
195 Value::Keys(lhs) => {
196 matches!(other, Value::Keys(rhs) if lhs == rhs)
197 }
198 Value::DataTransfer(lhs) => {
199 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
200 }
201 Value::MouseCursorInner(lhs) => {
202 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
203 }
204 }
205 }
206}
207
208impl std::fmt::Debug for Value {
209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210 match self {
211 Value::Void => write!(f, "Value::Void"),
212 Value::Number(n) => write!(f, "Value::Number({n:?})"),
213 Value::String(s) => write!(f, "Value::String({s:?})"),
214 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
215 Value::Image(i) => write!(f, "Value::Image({i:?})"),
216 Value::Model(m) => {
217 write!(f, "Value::Model(")?;
218 f.debug_list().entries(m.iter()).finish()?;
219 write!(f, "])")
220 }
221 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
222 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
223 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
224 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
225 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
226 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
227 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
228 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
229 Value::ArrayOfU16(data) => {
230 write!(f, "Value::ArrayOfU16({data:?})")
231 }
232 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
233 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
234 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
235 }
236 }
237}
238
239macro_rules! declare_value_conversion {
248 ( $value:ident => [$($ty:ty),*] ) => {
249 $(
250 impl From<$ty> for Value {
251 fn from(v: $ty) -> Self {
252 Value::$value(v as _)
253 }
254 }
255 impl TryFrom<Value> for $ty {
256 type Error = Value;
257 fn try_from(v: Value) -> Result<$ty, Self::Error> {
258 match v {
259 Value::$value(x) => Ok(x as _),
260 _ => Err(v)
261 }
262 }
263 }
264 )*
265 };
266}
267declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
268declare_value_conversion!(String => [SharedString] );
269declare_value_conversion!(Bool => [bool] );
270declare_value_conversion!(Image => [Image] );
271declare_value_conversion!(Struct => [Struct] );
272declare_value_conversion!(Brush => [Brush] );
273declare_value_conversion!(PathData => [PathData]);
274declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
275declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
276declare_value_conversion!(ComponentFactory => [ComponentFactory] );
277declare_value_conversion!(StyledText => [StyledText] );
278declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
279declare_value_conversion!(Keys => [Keys]);
280declare_value_conversion!(DataTransfer => [DataTransfer]);
281declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
282
283macro_rules! declare_value_struct_conversion {
285 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
286 impl From<$name> for Value {
287 fn from($name { $($field),* , .. }: $name) -> Self {
288 let mut struct_ = Struct::default();
289 $(struct_.set_field(stringify!($field).into(), $field.into());)*
290 Value::Struct(struct_)
291 }
292 }
293 impl TryFrom<Value> for $name {
294 type Error = ();
295 fn try_from(v: Value) -> Result<$name, Self::Error> {
296 #[allow(clippy::field_reassign_with_default)]
297 match v {
298 Value::Struct(x) => {
299 type Ty = $name;
300 #[allow(unused)]
301 let mut res: Ty = Ty::default();
302 $(let mut res: Ty = $extra;)?
303 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
304 Ok(res)
305 }
306 _ => Err(()),
307 }
308 }
309 }
310 };
311 ($(
312 $(#[$struct_attr:meta])*
313 $vis:vis struct $Name:ident {
314 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
315 }
316 )*) => {
317 $(
318 impl From<$Name> for Value {
319 fn from(item: $Name) -> Self {
320 let mut struct_ = Struct::default();
321 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
322 Value::Struct(struct_)
323 }
324 }
325 impl TryFrom<Value> for $Name {
326 type Error = ();
327 fn try_from(v: Value) -> Result<$Name, Self::Error> {
328 #[allow(clippy::field_reassign_with_default)]
329 match v {
330 Value::Struct(x) => {
331 type Ty = $Name;
332 #[allow(unused)]
333 let mut res: Ty = Ty::default();
334 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
337 Ok(res)
338 }
339 _ => Err(()),
340 }
341 }
342 }
343 )*
344 };
345}
346
347declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
348declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
349declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
350declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
351declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
352
353i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
354
355macro_rules! declare_value_enum_conversion {
360 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
361 impl From<i_slint_core::items::$Name> for Value {
362 fn from(v: i_slint_core::items::$Name) -> Self {
363 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
364 }
365 }
366 impl TryFrom<Value> for i_slint_core::items::$Name {
367 type Error = ();
368 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
369 use std::str::FromStr;
370 match v {
371 Value::EnumerationValue(enumeration, value) => {
372 if enumeration != stringify!($Name) {
373 return Err(());
374 }
375 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
376 }
377 _ => Err(()),
378 }
379 }
380 }
381 )*};
382}
383
384i_slint_common::for_each_enums!(declare_value_enum_conversion);
385
386impl From<i_slint_core::animations::Instant> for Value {
387 fn from(value: i_slint_core::animations::Instant) -> Self {
388 Value::Number(value.0 as _)
389 }
390}
391impl TryFrom<Value> for i_slint_core::animations::Instant {
392 type Error = ();
393 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
394 match v {
395 Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
396 _ => Err(()),
397 }
398 }
399}
400
401impl From<()> for Value {
402 #[inline]
403 fn from(_: ()) -> Self {
404 Value::Void
405 }
406}
407impl TryFrom<Value> for () {
408 type Error = ();
409 #[inline]
410 fn try_from(_: Value) -> Result<(), Self::Error> {
411 Ok(())
412 }
413}
414
415impl From<Color> for Value {
416 #[inline]
417 fn from(c: Color) -> Self {
418 Value::Brush(Brush::SolidColor(c))
419 }
420}
421impl TryFrom<Value> for Color {
422 type Error = Value;
423 #[inline]
424 fn try_from(v: Value) -> Result<Color, Self::Error> {
425 match v {
426 Value::Brush(Brush::SolidColor(c)) => Ok(c),
427 _ => Err(v),
428 }
429 }
430}
431
432impl From<i_slint_core::lengths::LogicalLength> for Value {
433 #[inline]
434 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
435 Value::Number(l.get() as _)
436 }
437}
438impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
439 type Error = Value;
440 #[inline]
441 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
442 match v {
443 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
444 _ => Err(v),
445 }
446 }
447}
448
449impl From<i_slint_core::lengths::LogicalPoint> for Value {
450 #[inline]
451 fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
452 Value::Struct(Struct::from_iter([
453 ("x".to_owned(), Value::Number(pt.x as _)),
454 ("y".to_owned(), Value::Number(pt.y as _)),
455 ]))
456 }
457}
458impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
459 type Error = Value;
460 #[inline]
461 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
462 match v {
463 Value::Struct(s) => {
464 let x = s
465 .get_field("x")
466 .cloned()
467 .unwrap_or_else(|| Value::Number(0 as _))
468 .try_into()?;
469 let y = s
470 .get_field("y")
471 .cloned()
472 .unwrap_or_else(|| Value::Number(0 as _))
473 .try_into()?;
474 Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
475 }
476 _ => Err(v),
477 }
478 }
479}
480
481impl From<i_slint_core::lengths::LogicalSize> for Value {
482 #[inline]
483 fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
484 Value::Struct(Struct::from_iter([
485 ("width".to_owned(), Value::Number(s.width as _)),
486 ("height".to_owned(), Value::Number(s.height as _)),
487 ]))
488 }
489}
490impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
491 type Error = Value;
492 #[inline]
493 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
494 match v {
495 Value::Struct(s) => {
496 let width = s
497 .get_field("width")
498 .cloned()
499 .unwrap_or_else(|| Value::Number(0 as _))
500 .try_into()?;
501 let height = s
502 .get_field("height")
503 .cloned()
504 .unwrap_or_else(|| Value::Number(0 as _))
505 .try_into()?;
506 Ok(i_slint_core::lengths::LogicalSize::new(width, height))
507 }
508 _ => Err(v),
509 }
510 }
511}
512
513impl From<i_slint_core::lengths::LogicalEdges> for Value {
514 #[inline]
515 fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
516 Value::Struct(Struct::from_iter([
517 ("left".to_owned(), Value::Number(s.left as _)),
518 ("right".to_owned(), Value::Number(s.right as _)),
519 ("top".to_owned(), Value::Number(s.top as _)),
520 ("bottom".to_owned(), Value::Number(s.bottom as _)),
521 ]))
522 }
523}
524impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
525 type Error = Value;
526 #[inline]
527 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
528 match v {
529 Value::Struct(s) => {
530 let left = s
531 .get_field("left")
532 .cloned()
533 .unwrap_or_else(|| Value::Number(0 as _))
534 .try_into()?;
535 let right = s
536 .get_field("right")
537 .cloned()
538 .unwrap_or_else(|| Value::Number(0 as _))
539 .try_into()?;
540 let top = s
541 .get_field("top")
542 .cloned()
543 .unwrap_or_else(|| Value::Number(0 as _))
544 .try_into()?;
545 let bottom = s
546 .get_field("bottom")
547 .cloned()
548 .unwrap_or_else(|| Value::Number(0 as _))
549 .try_into()?;
550 Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
551 }
552 _ => Err(v),
553 }
554 }
555}
556
557impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
558 fn from(m: ModelRc<T>) -> Self {
559 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
560 Value::Model(v.clone())
561 } else {
562 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
563 }
564 }
565}
566impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
567 type Error = Value;
568 #[inline]
569 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
570 match v {
571 Value::Model(m) => {
572 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
573 Ok(v.clone())
574 } else if let Some(v) =
575 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
576 {
577 Ok(v.0.clone())
578 } else {
579 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
580 }
581 }
582 _ => Err(v),
583 }
584 }
585}
586
587#[test]
588fn value_model_conversion() {
589 use i_slint_core::model::*;
590 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
591 let v = Value::from(m.clone());
592 assert_eq!(v, Value::Model(m.clone()));
593 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
594 assert_eq!(m2, m);
595
596 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
597 assert_eq!(int_model.row_count(), 2);
598 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
599
600 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
601 assert_eq!(m3.row_count(), 2);
602 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
603
604 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
605 assert_eq!(str_model.row_count(), 2);
606 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
608
609 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
610 assert!(err.is_err());
611
612 let model =
613 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
614
615 let value: Value = ModelRc::from(model.clone()).into();
616 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
617 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
618 value_model.set_row_data(1, Value::String("qux".into()));
619 value_model.set_row_data(0, Value::Bool(true));
620 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
621 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
623
624 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
626 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
627
628 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
629 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
630 assert_eq!(
631 model.as_ref() as *const VecModel<SharedString>,
632 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
633 as *const VecModel<SharedString>
634 );
635}
636
637pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
638 i_slint_compiler::parser::normalize_identifier(ident)
639}
640
641#[derive(Clone, PartialEq, Debug, Default)]
663pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
664impl Struct {
665 pub fn get_field(&self, name: &str) -> Option<&Value> {
667 self.0.get(&*normalize_identifier(name))
668 }
669 pub fn set_field(&mut self, name: String, value: Value) {
671 self.0.insert(normalize_identifier(&name), value);
672 }
673
674 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
676 self.0.iter().map(|(a, b)| (a.as_str(), b))
677 }
678}
679
680impl FromIterator<(String, Value)> for Struct {
681 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
682 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
683 }
684}
685
686#[deprecated(note = "Use slint_interpreter::Compiler instead")]
688pub struct ComponentCompiler {
689 config: i_slint_compiler::CompilerConfiguration,
690 diagnostics: Vec<Diagnostic>,
691}
692
693#[allow(deprecated)]
694impl Default for ComponentCompiler {
695 fn default() -> Self {
696 let mut config = i_slint_compiler::CompilerConfiguration::new(
697 i_slint_compiler::generator::OutputFormat::Interpreter,
698 );
699 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
700 Self { config, diagnostics: Vec::new() }
701 }
702}
703
704#[allow(deprecated)]
705impl ComponentCompiler {
706 pub fn new() -> Self {
708 Self::default()
709 }
710
711 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
713 self.config.include_paths = include_paths;
714 }
715
716 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
718 &self.config.include_paths
719 }
720
721 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
723 self.config.library_paths = library_paths;
724 }
725
726 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
728 &self.config.library_paths
729 }
730
731 pub fn set_style(&mut self, style: String) {
743 self.config.style = Some(style);
744 }
745
746 pub fn style(&self) -> Option<&String> {
748 self.config.style.as_ref()
749 }
750
751 pub fn set_translation_domain(&mut self, domain: String) {
753 self.config.translation_domain = Some(domain);
754 }
755
756 pub fn set_file_loader(
764 &mut self,
765 file_loader_fallback: impl Fn(
766 &Path,
767 ) -> core::pin::Pin<
768 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
769 > + 'static,
770 ) {
771 self.config.open_import_callback =
772 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
773 }
774
775 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
777 &self.diagnostics
778 }
779
780 pub async fn build_from_path<P: AsRef<Path>>(
799 &mut self,
800 path: P,
801 ) -> Option<ComponentDefinition> {
802 let path = path.as_ref();
803 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
804 Ok(s) => s,
805 Err(d) => {
806 self.diagnostics = vec![d];
807 return None;
808 }
809 };
810
811 let r = crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await;
812 self.diagnostics = r.diagnostics.into_iter().collect();
813 r.components.into_values().next()
814 }
815
816 pub async fn build_from_source(
833 &mut self,
834 source_code: String,
835 path: PathBuf,
836 ) -> Option<ComponentDefinition> {
837 let r = crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await;
838 self.diagnostics = r.diagnostics.into_iter().collect();
839 r.components.into_values().next()
840 }
841}
842
843pub struct Compiler {
846 config: i_slint_compiler::CompilerConfiguration,
847}
848
849impl Default for Compiler {
850 fn default() -> Self {
851 let config = i_slint_compiler::CompilerConfiguration::new(
852 i_slint_compiler::generator::OutputFormat::Interpreter,
853 );
854 Self { config }
855 }
856}
857
858impl Compiler {
859 pub fn new() -> Self {
861 Self::default()
862 }
863
864 #[doc(hidden)]
865 #[cfg(feature = "internal")]
866 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
867 self.config.embed_resources = embed_resources;
868 }
869
870 #[doc(hidden)]
874 #[cfg(feature = "internal")]
875 pub fn compiler_configuration(
876 &mut self,
877 _: i_slint_core::InternalToken,
878 ) -> &mut i_slint_compiler::CompilerConfiguration {
879 &mut self.config
880 }
881
882 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
884 self.config.include_paths = include_paths;
885 }
886
887 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
889 &self.config.include_paths
890 }
891
892 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
894 self.config.library_paths = library_paths;
895 }
896
897 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
899 &self.config.library_paths
900 }
901
902 pub fn set_style(&mut self, style: String) {
913 self.config.style = Some(style);
914 }
915
916 pub fn style(&self) -> Option<&String> {
918 self.config.style.as_ref()
919 }
920
921 pub fn set_translation_domain(&mut self, domain: String) {
923 self.config.translation_domain = Some(domain);
924 }
925
926 pub fn set_default_translation_context(
932 &mut self,
933 default_translation_context: DefaultTranslationContext,
934 ) {
935 self.config.default_translation_context = default_translation_context;
936 }
937
938 pub fn set_file_loader(
946 &mut self,
947 file_loader_fallback: impl Fn(
948 &Path,
949 ) -> core::pin::Pin<
950 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
951 > + 'static,
952 ) {
953 self.config.open_import_callback =
954 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
955 }
956
957 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
976 let path = path.as_ref();
977 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
978 Ok(s) => s,
979 Err(d) => {
980 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
981 diagnostics.push_compiler_error(d);
982 return CompilationResult {
983 components: HashMap::new(),
984 diagnostics: diagnostics.into_iter().collect(),
985 #[cfg(feature = "internal")]
986 watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
987 #[cfg(feature = "internal")]
988 structs_and_enums: Vec::new(),
989 #[cfg(feature = "internal")]
990 named_exports: Vec::new(),
991 };
992 }
993 };
994
995 crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await
996 }
997
998 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1011 crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await
1012 }
1013}
1014
1015#[derive(Clone)]
1022pub struct CompilationResult {
1023 pub(crate) components: HashMap<String, ComponentDefinition>,
1024 pub(crate) diagnostics: Vec<Diagnostic>,
1025 #[cfg(feature = "internal")]
1026 pub(crate) watch_paths: Vec<PathBuf>,
1027 #[cfg(feature = "internal")]
1028 pub(crate) structs_and_enums: Vec<LangType>,
1029 #[cfg(feature = "internal")]
1031 pub(crate) named_exports: Vec<(String, String)>,
1032}
1033
1034impl core::fmt::Debug for CompilationResult {
1035 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1036 f.debug_struct("CompilationResult")
1037 .field("components", &self.components.keys())
1038 .field("diagnostics", &self.diagnostics)
1039 .finish()
1040 }
1041}
1042
1043impl CompilationResult {
1044 pub fn has_errors(&self) -> bool {
1047 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1048 }
1049
1050 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1054 self.diagnostics.iter().cloned()
1055 }
1056
1057 #[cfg(feature = "display-diagnostics")]
1063 pub fn print_diagnostics(&self) {
1064 print_diagnostics(&self.diagnostics)
1065 }
1066
1067 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1069 self.components.values().cloned()
1070 }
1071
1072 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1074 self.components.keys().map(|s| s.as_str())
1075 }
1076
1077 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1080 self.components.get(name).cloned()
1081 }
1082
1083 #[doc(hidden)]
1085 #[cfg(feature = "internal")]
1086 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1087 &self.watch_paths
1088 }
1089
1090 #[doc(hidden)]
1092 #[cfg(feature = "internal")]
1093 pub fn structs_and_enums(
1094 &self,
1095 _: i_slint_core::InternalToken,
1096 ) -> impl Iterator<Item = &LangType> {
1097 self.structs_and_enums.iter()
1098 }
1099
1100 #[doc(hidden)]
1103 #[cfg(feature = "internal")]
1104 pub fn named_exports(
1105 &self,
1106 _: i_slint_core::InternalToken,
1107 ) -> impl Iterator<Item = &(String, String)> {
1108 self.named_exports.iter()
1109 }
1110}
1111
1112#[derive(Clone)]
1120pub struct ComponentDefinition {
1121 pub(crate) inner: crate::dynamic_item_tree::ErasedItemTreeDescription,
1122}
1123
1124impl ComponentDefinition {
1125 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1127 let instance = self.create_with_options(Default::default())?;
1128 if !instance.is_system_tray_rooted() {
1131 instance.inner.window_adapter_ref()?;
1133 i_slint_core::window::WindowInner::from_pub(instance.window())
1136 .ensure_tree_instantiated();
1137 }
1138 Ok(instance)
1139 }
1140
1141 #[doc(hidden)]
1143 #[cfg(feature = "internal")]
1144 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1145 self.create_with_options(WindowOptions::Embed {
1146 parent_item_tree: ctx.parent_item_tree,
1147 parent_item_tree_index: ctx.parent_item_tree_index,
1148 })
1149 }
1150
1151 #[doc(hidden)]
1153 #[cfg(feature = "internal")]
1154 pub fn create_with_existing_window(
1155 &self,
1156 window: &Window,
1157 ) -> Result<ComponentInstance, PlatformError> {
1158 self.create_with_options(WindowOptions::UseExistingWindow(
1159 WindowInner::from_pub(window).window_adapter(),
1160 ))
1161 }
1162
1163 pub(crate) fn create_with_options(
1165 &self,
1166 options: WindowOptions,
1167 ) -> Result<ComponentInstance, PlatformError> {
1168 generativity::make_guard!(guard);
1169 Ok(ComponentInstance { inner: self.inner.unerase(guard).clone().create(options)? })
1170 }
1171
1172 #[doc(hidden)]
1176 #[cfg(feature = "internal")]
1177 pub fn properties_and_callbacks(
1178 &self,
1179 ) -> impl Iterator<
1180 Item = (
1181 String,
1182 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1183 ),
1184 > + '_ {
1185 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1188 self.inner.unerase(guard).properties().map(|(s, t, v)| (s.to_string(), (t, v)))
1189 }
1190
1191 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1194 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1197 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1198 if prop_type.is_property_type() {
1199 Some((prop_name.to_string(), prop_type.into()))
1200 } else {
1201 None
1202 }
1203 })
1204 }
1205
1206 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1208 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1211 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1212 if matches!(prop_type, LangType::Callback { .. }) {
1213 Some(prop_name.to_string())
1214 } else {
1215 None
1216 }
1217 })
1218 }
1219
1220 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1222 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1225 self.inner.unerase(guard).properties().filter_map(|(prop_name, prop_type, _)| {
1226 if matches!(prop_type, LangType::Function { .. }) {
1227 Some(prop_name.to_string())
1228 } else {
1229 None
1230 }
1231 })
1232 }
1233
1234 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1239 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1242 self.inner.unerase(guard).global_names().map(|s| s.to_string())
1243 }
1244
1245 #[doc(hidden)]
1249 #[cfg(feature = "internal")]
1250 pub fn global_properties_and_callbacks(
1251 &self,
1252 global_name: &str,
1253 ) -> Option<
1254 impl Iterator<
1255 Item = (
1256 String,
1257 (
1258 i_slint_compiler::langtype::Type,
1259 i_slint_compiler::object_tree::PropertyVisibility,
1260 ),
1261 ),
1262 > + '_,
1263 > {
1264 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1267 self.inner
1268 .unerase(guard)
1269 .global_properties(global_name)
1270 .map(|o| o.map(|(s, t, v)| (s.to_string(), (t, v))))
1271 }
1272
1273 pub fn global_properties(
1275 &self,
1276 global_name: &str,
1277 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1278 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1281 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1282 iter.filter_map(|(prop_name, prop_type, _)| {
1283 if prop_type.is_property_type() {
1284 Some((prop_name.to_string(), prop_type.into()))
1285 } else {
1286 None
1287 }
1288 })
1289 })
1290 }
1291
1292 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1294 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1297 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1298 iter.filter_map(|(prop_name, prop_type, _)| {
1299 if matches!(prop_type, LangType::Callback { .. }) {
1300 Some(prop_name.to_string())
1301 } else {
1302 None
1303 }
1304 })
1305 })
1306 }
1307
1308 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1310 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1313 self.inner.unerase(guard).global_properties(global_name).map(|iter| {
1314 iter.filter_map(|(prop_name, prop_type, _)| {
1315 if matches!(prop_type, LangType::Function { .. }) {
1316 Some(prop_name.to_string())
1317 } else {
1318 None
1319 }
1320 })
1321 })
1322 }
1323
1324 pub fn name(&self) -> &str {
1326 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1329 self.inner.unerase(guard).id()
1330 }
1331
1332 #[doc(hidden)]
1336 #[cfg(feature = "internal")]
1337 pub fn is_window(&self) -> bool {
1338 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1339 !self.inner.unerase(guard).original.inherits_system_tray_icon()
1340 }
1341
1342 #[cfg(feature = "internal")]
1344 #[doc(hidden)]
1345 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1346 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1347 self.inner.unerase(guard).original.clone()
1348 }
1349
1350 #[cfg(feature = "internal-highlight")]
1354 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1355 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1356 self.inner.unerase(guard).type_loader.get().unwrap().clone()
1357 }
1358
1359 #[cfg(feature = "internal-highlight")]
1367 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1368 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1369 self.inner
1370 .unerase(guard)
1371 .raw_type_loader
1372 .get()
1373 .unwrap()
1374 .as_ref()
1375 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1376 }
1377}
1378
1379#[cfg(feature = "display-diagnostics")]
1385pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1386 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1387 for d in diagnostics {
1388 build_diagnostics.push_compiler_error(d.clone())
1389 }
1390 build_diagnostics.print();
1391}
1392
1393#[repr(C)]
1401pub struct ComponentInstance {
1402 pub(crate) inner: crate::dynamic_item_tree::DynamicComponentVRc,
1403}
1404
1405impl ComponentInstance {
1406 pub fn definition(&self) -> ComponentDefinition {
1408 generativity::make_guard!(guard);
1409 ComponentDefinition { inner: self.inner.unerase(guard).description().into() }
1410 }
1411
1412 fn is_system_tray_rooted(&self) -> bool {
1413 let guard = unsafe { generativity::Guard::new(generativity::Id::new()) };
1414 self.inner.unerase(guard).description().original.inherits_system_tray_icon()
1415 }
1416
1417 fn set_tray_icon_visible(&self, visible: bool) {
1421 generativity::make_guard!(guard);
1422 let description = self.inner.unerase(guard).description();
1423 let item_info = &description.items[description.original.root_element.borrow().id.as_str()];
1424 let item_rc =
1425 ItemRc::new(vtable::VRc::into_dyn(self.inner.clone()), item_info.item_index());
1426 let tray = item_rc
1427 .downcast::<SystemTrayIcon>()
1428 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1429 tray.as_pin_ref().visible.set(visible);
1430 }
1431
1432 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1452 generativity::make_guard!(guard);
1453 let comp = self.inner.unerase(guard);
1454 let name = normalize_identifier(name);
1455
1456 if comp
1457 .description()
1458 .original
1459 .root_element
1460 .borrow()
1461 .property_declarations
1462 .get(&name)
1463 .is_none_or(|d| !d.expose_in_public_api)
1464 {
1465 return Err(GetPropertyError::NoSuchProperty);
1466 }
1467
1468 comp.description()
1469 .get_property(comp.borrow(), &name)
1470 .map_err(|()| GetPropertyError::NoSuchProperty)
1471 }
1472
1473 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1475 let name = normalize_identifier(name);
1476 generativity::make_guard!(guard);
1477 let comp = self.inner.unerase(guard);
1478 let d = comp.description();
1479 let elem = d.original.root_element.borrow();
1480 let decl = elem.property_declarations.get(&name).ok_or(SetPropertyError::NoSuchProperty)?;
1481
1482 if !decl.expose_in_public_api {
1483 return Err(SetPropertyError::NoSuchProperty);
1484 } else if decl.visibility == i_slint_compiler::object_tree::PropertyVisibility::Output {
1485 return Err(SetPropertyError::AccessDenied);
1486 }
1487
1488 d.set_property(comp.borrow(), &name, value)
1489 }
1490
1491 pub fn set_callback(
1526 &self,
1527 name: &str,
1528 callback: impl Fn(&[Value]) -> Value + 'static,
1529 ) -> Result<(), SetCallbackError> {
1530 generativity::make_guard!(guard);
1531 let comp = self.inner.unerase(guard);
1532 comp.description()
1533 .set_callback_handler(comp.borrow(), &normalize_identifier(name), Box::new(callback))
1534 .map_err(|()| SetCallbackError::NoSuchCallback)
1535 }
1536
1537 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1542 generativity::make_guard!(guard);
1543 let comp = self.inner.unerase(guard);
1544 comp.description()
1545 .invoke(comp.borrow(), &normalize_identifier(name), args)
1546 .map_err(|()| InvokeError::NoSuchCallable)
1547 }
1548
1549 pub fn get_global_property(
1574 &self,
1575 global: &str,
1576 property: &str,
1577 ) -> Result<Value, GetPropertyError> {
1578 generativity::make_guard!(guard);
1579 let comp = self.inner.unerase(guard);
1580 comp.description()
1581 .get_global(comp.borrow(), &normalize_identifier(global))
1582 .map_err(|()| GetPropertyError::NoSuchProperty)? .as_ref()
1584 .get_property(&normalize_identifier(property))
1585 .map_err(|()| GetPropertyError::NoSuchProperty)
1586 }
1587
1588 pub fn set_global_property(
1590 &self,
1591 global: &str,
1592 property: &str,
1593 value: Value,
1594 ) -> Result<(), SetPropertyError> {
1595 generativity::make_guard!(guard);
1596 let comp = self.inner.unerase(guard);
1597 comp.description()
1598 .get_global(comp.borrow(), &normalize_identifier(global))
1599 .map_err(|()| SetPropertyError::NoSuchProperty)? .as_ref()
1601 .set_property(&normalize_identifier(property), value)
1602 }
1603
1604 pub fn set_global_callback(
1639 &self,
1640 global: &str,
1641 name: &str,
1642 callback: impl Fn(&[Value]) -> Value + 'static,
1643 ) -> Result<(), SetCallbackError> {
1644 generativity::make_guard!(guard);
1645 let comp = self.inner.unerase(guard);
1646 comp.description()
1647 .get_global(comp.borrow(), &normalize_identifier(global))
1648 .map_err(|()| SetCallbackError::NoSuchCallback)? .as_ref()
1650 .set_callback_handler(&normalize_identifier(name), Box::new(callback))
1651 .map_err(|()| SetCallbackError::NoSuchCallback)
1652 }
1653
1654 pub fn invoke_global(
1659 &self,
1660 global: &str,
1661 callable_name: &str,
1662 args: &[Value],
1663 ) -> Result<Value, InvokeError> {
1664 generativity::make_guard!(guard);
1665 let comp = self.inner.unerase(guard);
1666 let g = comp
1667 .description()
1668 .get_global(comp.borrow(), &normalize_identifier(global))
1669 .map_err(|()| InvokeError::NoSuchCallable)?; let callable_name = normalize_identifier(callable_name);
1671 if matches!(
1672 comp.description()
1673 .original
1674 .root_element
1675 .borrow()
1676 .lookup_property(&callable_name)
1677 .property_type,
1678 LangType::Function { .. }
1679 ) {
1680 g.as_ref()
1681 .eval_function(&callable_name, args.to_vec())
1682 .map_err(|()| InvokeError::NoSuchCallable)
1683 } else {
1684 g.as_ref()
1685 .invoke_callback(&callable_name, args)
1686 .map_err(|()| InvokeError::NoSuchCallable)
1687 }
1688 }
1689
1690 #[cfg(feature = "internal-highlight")]
1694 pub fn component_positions(
1695 &self,
1696 path: &Path,
1697 offset: u32,
1698 ) -> Vec<crate::highlight::HighlightedRect> {
1699 crate::highlight::component_positions(&self.inner, path, offset)
1700 }
1701
1702 #[cfg(feature = "internal-highlight")]
1706 pub fn element_positions(
1707 &self,
1708 element: &i_slint_compiler::object_tree::ElementRc,
1709 ) -> Vec<crate::highlight::HighlightedRect> {
1710 crate::highlight::element_positions(
1711 &self.inner,
1712 element,
1713 crate::highlight::ElementPositionFilter::IncludeClipped,
1714 )
1715 }
1716
1717 #[cfg(feature = "internal-highlight")]
1721 pub fn element_node_at_source_code_position(
1722 &self,
1723 path: &Path,
1724 offset: u32,
1725 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1726 crate::highlight::element_node_at_source_code_position(&self.inner, path, offset)
1727 }
1728
1729 #[cfg(feature = "internal")]
1731 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1732 generativity::make_guard!(guard);
1733 let comp = self.inner.unerase(guard);
1734 crate::debug_hook::set_debug_hook_callback(comp, callback);
1735 }
1736}
1737
1738impl StrongHandle for ComponentInstance {
1739 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::dynamic_item_tree::ErasedItemTreeBox>;
1740
1741 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1742 Some(Self { inner: inner.upgrade()? })
1743 }
1744}
1745
1746impl ComponentHandle for ComponentInstance {
1747 fn as_weak(&self) -> Weak<Self>
1748 where
1749 Self: Sized,
1750 {
1751 Weak::new(vtable::VRc::downgrade(&self.inner))
1752 }
1753
1754 fn clone_strong(&self) -> Self {
1755 Self { inner: self.inner.clone() }
1756 }
1757
1758 fn show(&self) -> Result<(), PlatformError> {
1759 if self.is_system_tray_rooted() {
1760 self.set_tray_icon_visible(true);
1761 return Ok(());
1762 }
1763 self.inner.window_adapter_ref()?.window().show()
1764 }
1765
1766 fn hide(&self) -> Result<(), PlatformError> {
1767 if self.is_system_tray_rooted() {
1768 self.set_tray_icon_visible(false);
1769 return Ok(());
1770 }
1771 self.inner.window_adapter_ref()?.window().hide()
1772 }
1773
1774 fn run(&self) -> Result<(), PlatformError> {
1775 self.show()?;
1776 run_event_loop()?;
1777 self.hide()
1778 }
1779
1780 fn window(&self) -> &Window {
1781 self.inner.window_adapter_ref().unwrap().window()
1782 }
1783
1784 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1785 where
1786 Self: Sized,
1787 {
1788 unreachable!()
1789 }
1790}
1791
1792impl From<ComponentInstance>
1793 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, ErasedItemTreeBox>
1794{
1795 fn from(value: ComponentInstance) -> Self {
1796 value.inner
1797 }
1798}
1799
1800#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1802#[non_exhaustive]
1803pub enum GetPropertyError {
1804 #[display("no such property")]
1806 NoSuchProperty,
1807}
1808
1809#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1811#[non_exhaustive]
1812pub enum SetPropertyError {
1813 #[display("no such property")]
1815 NoSuchProperty,
1816 #[display("wrong type")]
1822 WrongType,
1823 #[display("access denied")]
1825 AccessDenied,
1826}
1827
1828#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1830#[non_exhaustive]
1831pub enum SetCallbackError {
1832 #[display("no such callback")]
1834 NoSuchCallback,
1835}
1836
1837#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1839#[non_exhaustive]
1840pub enum InvokeError {
1841 #[display("no such callback or function")]
1843 NoSuchCallable,
1844}
1845
1846pub fn run_event_loop() -> Result<(), PlatformError> {
1850 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1851}
1852
1853pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1857 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1858 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1859}
1860
1861#[test]
1862fn component_definition_properties() {
1863 i_slint_backend_testing::init_no_event_loop();
1864 let mut compiler = Compiler::default();
1865 compiler.set_style("fluent".into());
1866 let comp_def = spin_on::spin_on(
1867 compiler.build_from_source(
1868 r#"
1869 export component Dummy {
1870 in-out property <string> test;
1871 in-out property <int> underscores-and-dashes_preserved: 44;
1872 callback hello;
1873 }"#
1874 .into(),
1875 "".into(),
1876 ),
1877 )
1878 .component("Dummy")
1879 .unwrap();
1880
1881 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1882
1883 assert_eq!(props.len(), 2);
1884 assert_eq!(props[0].0, "test");
1885 assert_eq!(props[0].1, ValueType::String);
1886 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1887 assert_eq!(props[1].1, ValueType::Number);
1888
1889 let instance = comp_def.create().unwrap();
1890 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1891 assert_eq!(
1892 instance.get_property("underscoresanddashespreserved"),
1893 Err(GetPropertyError::NoSuchProperty)
1894 );
1895 assert_eq!(
1896 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1897 Ok(())
1898 );
1899 assert_eq!(
1900 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1901 Err(SetPropertyError::NoSuchProperty)
1902 );
1903 assert_eq!(
1904 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1905 Err(SetPropertyError::WrongType)
1906 );
1907 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1908}
1909
1910#[test]
1911fn component_definition_properties2() {
1912 i_slint_backend_testing::init_no_event_loop();
1913 let mut compiler = Compiler::default();
1914 compiler.set_style("fluent".into());
1915 let comp_def = spin_on::spin_on(
1916 compiler.build_from_source(
1917 r#"
1918 export component Dummy {
1919 in-out property <string> sub-text <=> sub.text;
1920 sub := Text { property <int> private-not-exported; }
1921 out property <string> xreadonly: "the value";
1922 private property <string> xx: sub.text;
1923 callback hello;
1924 }"#
1925 .into(),
1926 "".into(),
1927 ),
1928 )
1929 .component("Dummy")
1930 .unwrap();
1931
1932 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1933
1934 assert_eq!(props.len(), 2);
1935 assert_eq!(props[0].0, "sub-text");
1936 assert_eq!(props[0].1, ValueType::String);
1937 assert_eq!(props[1].0, "xreadonly");
1938
1939 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1940 assert_eq!(callbacks.len(), 1);
1941 assert_eq!(callbacks[0], "hello");
1942
1943 let instance = comp_def.create().unwrap();
1944 assert_eq!(
1945 instance.set_property("xreadonly", SharedString::from("XXX").into()),
1946 Err(SetPropertyError::AccessDenied)
1947 );
1948 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1949 assert_eq!(
1950 instance.set_property("xx", SharedString::from("XXX").into()),
1951 Err(SetPropertyError::NoSuchProperty)
1952 );
1953 assert_eq!(
1954 instance.set_property("background", Value::default()),
1955 Err(SetPropertyError::NoSuchProperty)
1956 );
1957
1958 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1959 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1960}
1961
1962#[test]
1963fn globals() {
1964 i_slint_backend_testing::init_no_event_loop();
1965 let mut compiler = Compiler::default();
1966 compiler.set_style("fluent".into());
1967 let definition = spin_on::spin_on(
1968 compiler.build_from_source(
1969 r#"
1970 export global My-Super_Global {
1971 in-out property <int> the-property : 21;
1972 callback my-callback();
1973 }
1974 export { My-Super_Global as AliasedGlobal }
1975 export component Dummy {
1976 callback alias <=> My-Super_Global.my-callback;
1977 }"#
1978 .into(),
1979 "".into(),
1980 ),
1981 )
1982 .component("Dummy")
1983 .unwrap();
1984
1985 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1986
1987 assert!(definition.global_properties("not-there").is_none());
1988 {
1989 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1990 let expected_callbacks = vec!["my-callback".to_string()];
1991
1992 let assert_properties_and_callbacks = |global_name| {
1993 assert_eq!(
1994 definition
1995 .global_properties(global_name)
1996 .map(|props| props.collect::<Vec<_>>())
1997 .as_ref(),
1998 Some(&expected_properties)
1999 );
2000 assert_eq!(
2001 definition
2002 .global_callbacks(global_name)
2003 .map(|props| props.collect::<Vec<_>>())
2004 .as_ref(),
2005 Some(&expected_callbacks)
2006 );
2007 };
2008
2009 assert_properties_and_callbacks("My-Super-Global");
2010 assert_properties_and_callbacks("My_Super-Global");
2011 assert_properties_and_callbacks("AliasedGlobal");
2012 }
2013
2014 let instance = definition.create().unwrap();
2015 assert_eq!(
2016 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
2017 Ok(())
2018 );
2019 assert_eq!(
2020 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2021 Ok(())
2022 );
2023 assert_eq!(
2024 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2025 Err(SetPropertyError::NoSuchProperty)
2026 );
2027
2028 assert_eq!(
2029 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2030 Err(SetPropertyError::NoSuchProperty)
2031 );
2032 assert_eq!(
2033 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2034 Err(SetPropertyError::NoSuchProperty)
2035 );
2036 assert_eq!(
2037 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2038 Err(SetPropertyError::WrongType)
2039 );
2040 assert_eq!(
2041 instance.get_global_property("My-Super_Global", "yoyo"),
2042 Err(GetPropertyError::NoSuchProperty)
2043 );
2044 assert_eq!(
2045 instance.get_global_property("My-Super_Global", "the-property"),
2046 Ok(Value::Number(44.))
2047 );
2048
2049 assert_eq!(
2050 instance.set_property("the-property", Value::Void),
2051 Err(SetPropertyError::NoSuchProperty)
2052 );
2053 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2054
2055 assert_eq!(
2056 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2057 Err(SetCallbackError::NoSuchCallback)
2058 );
2059 assert_eq!(
2060 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2061 Err(SetCallbackError::NoSuchCallback)
2062 );
2063 assert_eq!(
2064 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2065 Err(SetCallbackError::NoSuchCallback)
2066 );
2067
2068 assert_eq!(
2069 instance.invoke_global("DontExist", "the-property", &[]),
2070 Err(InvokeError::NoSuchCallable)
2071 );
2072 assert_eq!(
2073 instance.invoke_global("My_Super_Global", "the-property", &[]),
2074 Err(InvokeError::NoSuchCallable)
2075 );
2076 assert_eq!(
2077 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2078 Err(InvokeError::NoSuchCallable)
2079 );
2080
2081 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2083}
2084
2085#[test]
2086fn call_functions() {
2087 i_slint_backend_testing::init_no_event_loop();
2088 let mut compiler = Compiler::default();
2089 compiler.set_style("fluent".into());
2090 let definition = spin_on::spin_on(
2091 compiler.build_from_source(
2092 r#"
2093 export global Gl {
2094 out property<string> q;
2095 public function foo-bar(a-a: string, b-b:int) -> string {
2096 q = a-a;
2097 return a-a + b-b;
2098 }
2099 }
2100 export component Test {
2101 out property<int> p;
2102 public function foo-bar(a: int, b:int) -> int {
2103 p = a;
2104 return a + b;
2105 }
2106 }"#
2107 .into(),
2108 "".into(),
2109 ),
2110 )
2111 .component("Test")
2112 .unwrap();
2113
2114 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2115 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2116
2117 let instance = definition.create().unwrap();
2118
2119 assert_eq!(
2120 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2121 Ok(Value::Number(7.))
2122 );
2123 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2124 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2125
2126 assert_eq!(
2127 instance.invoke_global(
2128 "Gl",
2129 "foo_bar",
2130 &[Value::String("Hello".into()), Value::Number(10.)]
2131 ),
2132 Ok(Value::String("Hello10".into()))
2133 );
2134 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2135}
2136
2137#[test]
2138fn component_definition_struct_properties() {
2139 i_slint_backend_testing::init_no_event_loop();
2140 let mut compiler = Compiler::default();
2141 compiler.set_style("fluent".into());
2142 let comp_def = spin_on::spin_on(
2143 compiler.build_from_source(
2144 r#"
2145 export struct Settings {
2146 string_value: string,
2147 }
2148 export component Dummy {
2149 in-out property <Settings> test;
2150 }"#
2151 .into(),
2152 "".into(),
2153 ),
2154 )
2155 .component("Dummy")
2156 .unwrap();
2157
2158 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2159
2160 assert_eq!(props.len(), 1);
2161 assert_eq!(props[0].0, "test");
2162 assert_eq!(props[0].1, ValueType::Struct);
2163
2164 let instance = comp_def.create().unwrap();
2165
2166 let valid_struct: Struct =
2167 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2168
2169 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2170 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2171
2172 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2173
2174 let mut invalid_struct = valid_struct.clone();
2175 invalid_struct.set_field("other".into(), Value::Number(44.));
2176 assert_eq!(
2177 instance.set_property("test", Value::Struct(invalid_struct)),
2178 Err(SetPropertyError::WrongType)
2179 );
2180 let mut invalid_struct = valid_struct;
2181 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2182 assert_eq!(
2183 instance.set_property("test", Value::Struct(invalid_struct)),
2184 Err(SetPropertyError::WrongType)
2185 );
2186}
2187
2188#[test]
2189fn component_definition_model_properties() {
2190 use i_slint_core::model::*;
2191 i_slint_backend_testing::init_no_event_loop();
2192 let mut compiler = Compiler::default();
2193 compiler.set_style("fluent".into());
2194 let comp_def = spin_on::spin_on(compiler.build_from_source(
2195 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2196 "".into(),
2197 ))
2198 .component("Dummy")
2199 .unwrap();
2200
2201 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2202 assert_eq!(props.len(), 1);
2203 assert_eq!(props[0].0, "prop");
2204 assert_eq!(props[0].1, ValueType::Model);
2205
2206 let instance = comp_def.create().unwrap();
2207
2208 let int_model =
2209 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2210 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2211 let model_with_string = Value::Model(VecModel::from_slice(&[
2212 Value::Number(1000.),
2213 Value::String("foo".into()),
2214 Value::Number(1111.),
2215 ]));
2216
2217 #[track_caller]
2218 fn check_model(val: Value, r: &[f64]) {
2219 if let Value::Model(m) = val {
2220 assert_eq!(r.len(), m.row_count());
2221 for (i, v) in r.iter().enumerate() {
2222 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2223 }
2224 } else {
2225 panic!("{val:?} not a model");
2226 }
2227 }
2228
2229 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2230 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2231
2232 instance.set_property("prop", int_model).unwrap();
2233 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2234
2235 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2236 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2237 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2238 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2239
2240 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2241 check_model(instance.get_property("prop").unwrap(), &[]);
2242}
2243
2244#[test]
2245fn lang_type_to_value_type() {
2246 use i_slint_compiler::langtype::Struct as LangStruct;
2247 use std::collections::BTreeMap;
2248
2249 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2250 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2251 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2252 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2253 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2254 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2255 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2256 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2257 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2258 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2259 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2260 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2261 assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2262 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2263 assert_eq!(
2264 ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2265 BTreeMap::default(),
2266 i_slint_compiler::langtype::StructName::None
2267 )))),
2268 ValueType::Struct
2269 );
2270 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2271}
2272
2273#[test]
2274fn test_multi_components() {
2275 i_slint_backend_testing::init_no_event_loop();
2276 let result = spin_on::spin_on(
2277 Compiler::default().build_from_source(
2278 r#"
2279 export struct Settings {
2280 string_value: string,
2281 }
2282 export global ExpGlo { in-out property <int> test: 42; }
2283 component Common {
2284 in-out property <Settings> settings: { string_value: "Hello", };
2285 }
2286 export component Xyz inherits Window {
2287 in-out property <int> aaa: 8;
2288 }
2289 export component Foo {
2290
2291 in-out property <int> test: 42;
2292 c := Common {}
2293 }
2294 export component Bar inherits Window {
2295 in-out property <int> blah: 78;
2296 c := Common {}
2297 }
2298 "#
2299 .into(),
2300 PathBuf::from("hello.slint"),
2301 ),
2302 );
2303
2304 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2305 let mut components = result.component_names().collect::<Vec<_>>();
2306 components.sort();
2307 assert_eq!(components, vec!["Bar", "Xyz"]);
2308 let diag = result.diagnostics().collect::<Vec<_>>();
2309 assert_eq!(diag.len(), 1);
2310 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2311 assert_eq!(
2312 diag[0].message(),
2313 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2314 );
2315
2316 let comp1 = result.component("Xyz").unwrap();
2317 assert_eq!(comp1.name(), "Xyz");
2318 let instance1a = comp1.create().unwrap();
2319 let comp2 = result.component("Bar").unwrap();
2320 let instance2 = comp2.create().unwrap();
2321 let instance1b = comp1.create().unwrap();
2322
2323 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2325 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2326 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2327 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2328 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2329
2330 assert!(result.component("Settings").is_none());
2331 assert!(result.component("Foo").is_none());
2332 assert!(result.component("Common").is_none());
2333 assert!(result.component("ExpGlo").is_none());
2334 assert!(result.component("xyz").is_none());
2335}
2336
2337#[cfg(all(test, feature = "internal-highlight"))]
2338fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2339 i_slint_backend_testing::init_no_event_loop();
2340 let mut compiler = Compiler::default();
2341 compiler.set_style("fluent".into());
2342 let path = PathBuf::from("/tmp/test.slint");
2343
2344 let compile_result =
2345 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2346
2347 for d in &compile_result.diagnostics {
2348 eprintln!("{d}");
2349 }
2350
2351 assert!(!compile_result.has_errors());
2352
2353 let definition = compile_result.components().next().unwrap();
2354 let instance = definition.create().unwrap();
2355
2356 (instance, path)
2357}
2358
2359#[cfg(feature = "internal-highlight")]
2360#[test]
2361fn test_element_node_at_source_code_position() {
2362 let code = r#"
2363component Bar1 {}
2364
2365component Foo1 {
2366}
2367
2368export component Foo2 inherits Window {
2369 Bar1 {}
2370 Foo1 {}
2371}"#;
2372
2373 let (handle, path) = compile(code);
2374
2375 for i in 0..code.len() as u32 {
2376 let elements = handle.element_node_at_source_code_position(&path, i);
2377 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2378 match i {
2379 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()),
2385 }
2386 }
2387}