1use i_slint_compiler::langtype::Type as LangType;
6use i_slint_core::PathData;
7use i_slint_core::component_factory::ComponentFactory;
8#[cfg(feature = "internal")]
9use i_slint_core::component_factory::FactoryContext;
10use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
11use i_slint_core::items::*;
12use i_slint_core::model::{Model, ModelExt, ModelRc};
13use i_slint_core::styled_text::StyledText;
14#[cfg(feature = "internal")]
15use i_slint_core::window::WindowInner;
16use smol_str::SmolStr;
17use std::collections::HashMap;
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::rc::Rc;
21#[cfg(test)]
22use std::sync::Arc;
23
24#[doc(inline)]
25pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
26
27pub use i_slint_backend_selector::api::*;
28pub use i_slint_core::api::*;
29
30pub use i_slint_compiler::DefaultTranslationContext;
33
34#[derive(Debug, Copy, Clone, PartialEq)]
37#[repr(i8)]
38#[non_exhaustive]
39pub enum ValueType {
40 Void,
42 Number,
44 String,
46 Bool,
48 Model,
50 Struct,
52 Brush,
54 Image,
56 #[doc(hidden)]
58 Other = -1,
59}
60
61impl From<LangType> for ValueType {
62 fn from(ty: LangType) -> Self {
63 match ty {
64 LangType::Float32
65 | LangType::Int32
66 | LangType::Duration
67 | LangType::Angle
68 | LangType::PhysicalLength
69 | LangType::LogicalLength
70 | LangType::Percent
71 | LangType::UnitProduct(_) => Self::Number,
72 LangType::String => Self::String,
73 LangType::Color => Self::Brush,
74 LangType::Brush => Self::Brush,
75 LangType::Array(_) => Self::Model,
76 LangType::Bool => Self::Bool,
77 LangType::Struct { .. } => Self::Struct,
78 LangType::Void => Self::Void,
79 LangType::Image => Self::Image,
80 _ => Self::Other,
81 }
82 }
83}
84
85#[derive(Clone, Default)]
97#[non_exhaustive]
98#[repr(u8)]
99pub enum Value {
100 #[default]
103 Void = 0,
104 Number(f64) = 1,
106 String(SharedString) = 2,
108 Bool(bool) = 3,
110 Image(Image) = 4,
112 Model(ModelRc<Value>) = 5,
114 Struct(Struct) = 6,
116 Brush(Brush) = 7,
118 #[doc(hidden)]
119 PathData(PathData) = 8,
121 #[doc(hidden)]
122 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
124 #[doc(hidden)]
125 EnumerationValue(String, String) = 10,
128 #[doc(hidden)]
129 LayoutCache(SharedVector<f32>) = 11,
130 #[doc(hidden)]
131 ComponentFactory(ComponentFactory) = 12,
133 #[doc(hidden)] StyledText(StyledText) = 13,
136 #[doc(hidden)]
137 ArrayOfU16(SharedVector<u16>) = 14,
138 Keys(Keys) = 15,
140 DataTransfer(DataTransfer) = 16,
142 #[doc(hidden)]
143 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
145}
146
147impl Value {
148 pub fn value_type(&self) -> ValueType {
150 match self {
151 Value::Void => ValueType::Void,
152 Value::Number(_) => ValueType::Number,
153 Value::String(_) => ValueType::String,
154 Value::Bool(_) => ValueType::Bool,
155 Value::Model(_) => ValueType::Model,
156 Value::Struct(_) => ValueType::Struct,
157 Value::Brush(_) => ValueType::Brush,
158 Value::Image(_) => ValueType::Image,
159 _ => ValueType::Other,
160 }
161 }
162}
163
164impl i_slint_core::rtti::ValueType for Value {}
165
166impl PartialEq for Value {
167 fn eq(&self, other: &Self) -> bool {
168 match self {
169 Value::Void => matches!(other, Value::Void),
170 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
171 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
172 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
173 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
174 Value::Model(lhs) => {
175 if let Value::Model(rhs) = other {
176 lhs == rhs
177 } else {
178 false
179 }
180 }
181 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
182 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
183 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
184 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
185 Value::EnumerationValue(lhs_name, lhs_value) => {
186 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
187 }
188 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
189 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
190 Value::ComponentFactory(lhs) => {
191 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
192 }
193 Value::StyledText(lhs) => {
194 matches!(other, Value::StyledText(rhs) if lhs == rhs)
195 }
196 Value::Keys(lhs) => {
197 matches!(other, Value::Keys(rhs) if lhs == rhs)
198 }
199 Value::DataTransfer(lhs) => {
200 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
201 }
202 Value::MouseCursorInner(lhs) => {
203 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
204 }
205 }
206 }
207}
208
209impl std::fmt::Debug for Value {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 match self {
212 Value::Void => write!(f, "Value::Void"),
213 Value::Number(n) => write!(f, "Value::Number({n:?})"),
214 Value::String(s) => write!(f, "Value::String({s:?})"),
215 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
216 Value::Image(i) => write!(f, "Value::Image({i:?})"),
217 Value::Model(m) => {
218 write!(f, "Value::Model(")?;
219 f.debug_list().entries(m.iter()).finish()?;
220 write!(f, "])")
221 }
222 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
223 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
224 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
225 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
226 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
227 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
228 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
229 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
230 Value::ArrayOfU16(data) => {
231 write!(f, "Value::ArrayOfU16({data:?})")
232 }
233 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
234 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
235 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
236 }
237 }
238}
239
240macro_rules! declare_value_conversion {
249 ( $value:ident => [$($ty:ty),*] ) => {
250 $(
251 impl From<$ty> for Value {
252 fn from(v: $ty) -> Self {
253 Value::$value(v as _)
254 }
255 }
256 impl TryFrom<Value> for $ty {
257 type Error = Value;
258 fn try_from(v: Value) -> Result<$ty, Self::Error> {
259 match v {
260 Value::$value(x) => Ok(x as _),
261 _ => Err(v)
262 }
263 }
264 }
265 )*
266 };
267}
268declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
269declare_value_conversion!(String => [SharedString] );
270declare_value_conversion!(Bool => [bool] );
271declare_value_conversion!(Image => [Image] );
272declare_value_conversion!(Struct => [Struct] );
273declare_value_conversion!(Brush => [Brush] );
274declare_value_conversion!(PathData => [PathData]);
275declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
276declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
277declare_value_conversion!(ComponentFactory => [ComponentFactory] );
278declare_value_conversion!(StyledText => [StyledText] );
279declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
280declare_value_conversion!(Keys => [Keys]);
281declare_value_conversion!(DataTransfer => [DataTransfer]);
282declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
283
284macro_rules! declare_value_struct_conversion {
286 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
287 impl From<$name> for Value {
288 fn from($name { $($field),* , .. }: $name) -> Self {
289 let mut struct_ = Struct::default();
290 $(struct_.set_field(stringify!($field).into(), $field.into());)*
291 Value::Struct(struct_)
292 }
293 }
294 impl TryFrom<Value> for $name {
295 type Error = ();
296 fn try_from(v: Value) -> Result<$name, Self::Error> {
297 #[allow(clippy::field_reassign_with_default)]
298 match v {
299 Value::Struct(x) => {
300 type Ty = $name;
301 #[allow(unused)]
302 let mut res: Ty = Ty::default();
303 $(let mut res: Ty = $extra;)?
304 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
305 Ok(res)
306 }
307 _ => Err(()),
308 }
309 }
310 }
311 };
312 ($(
313 $(#[$struct_attr:meta])*
314 $vis:vis struct $Name:ident {
315 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
316 }
317 )*) => {
318 $(
319 impl From<$Name> for Value {
320 fn from(item: $Name) -> Self {
321 let mut struct_ = Struct::default();
322 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
323 Value::Struct(struct_)
324 }
325 }
326 impl TryFrom<Value> for $Name {
327 type Error = ();
328 fn try_from(v: Value) -> Result<$Name, Self::Error> {
329 #[allow(clippy::field_reassign_with_default)]
330 match v {
331 Value::Struct(x) => {
332 type Ty = $Name;
333 #[allow(unused)]
334 let mut res: Ty = Ty::default();
335 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
338 Ok(res)
339 }
340 _ => Err(()),
341 }
342 }
343 }
344 )*
345 };
346}
347
348declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
349declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
350declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
351declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
352declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
353
354i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
355
356macro_rules! declare_value_enum_conversion {
361 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
362 impl From<i_slint_core::items::$Name> for Value {
363 fn from(v: i_slint_core::items::$Name) -> Self {
364 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
365 }
366 }
367 impl TryFrom<Value> for i_slint_core::items::$Name {
368 type Error = ();
369 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
370 use std::str::FromStr;
371 match v {
372 Value::EnumerationValue(enumeration, value) => {
373 if enumeration != stringify!($Name) {
374 return Err(());
375 }
376 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
377 }
378 _ => Err(()),
379 }
380 }
381 }
382 )*};
383}
384
385i_slint_common::for_each_enums!(declare_value_enum_conversion);
386
387impl From<i_slint_core::animations::Instant> for Value {
388 fn from(value: i_slint_core::animations::Instant) -> Self {
389 Value::Number(value.0 as _)
390 }
391}
392impl TryFrom<Value> for i_slint_core::animations::Instant {
393 type Error = ();
394 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
395 match v {
396 Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
397 _ => Err(()),
398 }
399 }
400}
401
402impl From<()> for Value {
403 #[inline]
404 fn from(_: ()) -> Self {
405 Value::Void
406 }
407}
408impl TryFrom<Value> for () {
409 type Error = ();
410 #[inline]
411 fn try_from(_: Value) -> Result<(), Self::Error> {
412 Ok(())
413 }
414}
415
416impl From<Color> for Value {
417 #[inline]
418 fn from(c: Color) -> Self {
419 Value::Brush(Brush::SolidColor(c))
420 }
421}
422impl TryFrom<Value> for Color {
423 type Error = Value;
424 #[inline]
425 fn try_from(v: Value) -> Result<Color, Self::Error> {
426 match v {
427 Value::Brush(Brush::SolidColor(c)) => Ok(c),
428 _ => Err(v),
429 }
430 }
431}
432
433impl From<i_slint_core::lengths::LogicalLength> for Value {
434 #[inline]
435 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
436 Value::Number(l.get() as _)
437 }
438}
439impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
440 type Error = Value;
441 #[inline]
442 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
443 match v {
444 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
445 _ => Err(v),
446 }
447 }
448}
449
450impl From<i_slint_core::lengths::LogicalPoint> for Value {
451 #[inline]
452 fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
453 Value::Struct(Struct::from_iter([
454 ("x".to_owned(), Value::Number(pt.x as _)),
455 ("y".to_owned(), Value::Number(pt.y as _)),
456 ]))
457 }
458}
459impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
460 type Error = Value;
461 #[inline]
462 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
463 match v {
464 Value::Struct(s) => {
465 let x = s
466 .get_field("x")
467 .cloned()
468 .unwrap_or_else(|| Value::Number(0 as _))
469 .try_into()?;
470 let y = s
471 .get_field("y")
472 .cloned()
473 .unwrap_or_else(|| Value::Number(0 as _))
474 .try_into()?;
475 Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
476 }
477 _ => Err(v),
478 }
479 }
480}
481
482impl From<i_slint_core::lengths::LogicalSize> for Value {
483 #[inline]
484 fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
485 Value::Struct(Struct::from_iter([
486 ("width".to_owned(), Value::Number(s.width as _)),
487 ("height".to_owned(), Value::Number(s.height as _)),
488 ]))
489 }
490}
491impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
492 type Error = Value;
493 #[inline]
494 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
495 match v {
496 Value::Struct(s) => {
497 let width = s
498 .get_field("width")
499 .cloned()
500 .unwrap_or_else(|| Value::Number(0 as _))
501 .try_into()?;
502 let height = s
503 .get_field("height")
504 .cloned()
505 .unwrap_or_else(|| Value::Number(0 as _))
506 .try_into()?;
507 Ok(i_slint_core::lengths::LogicalSize::new(width, height))
508 }
509 _ => Err(v),
510 }
511 }
512}
513
514impl From<i_slint_core::lengths::LogicalEdges> for Value {
515 #[inline]
516 fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
517 Value::Struct(Struct::from_iter([
518 ("left".to_owned(), Value::Number(s.left as _)),
519 ("right".to_owned(), Value::Number(s.right as _)),
520 ("top".to_owned(), Value::Number(s.top as _)),
521 ("bottom".to_owned(), Value::Number(s.bottom as _)),
522 ]))
523 }
524}
525impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
526 type Error = Value;
527 #[inline]
528 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
529 match v {
530 Value::Struct(s) => {
531 let left = s
532 .get_field("left")
533 .cloned()
534 .unwrap_or_else(|| Value::Number(0 as _))
535 .try_into()?;
536 let right = s
537 .get_field("right")
538 .cloned()
539 .unwrap_or_else(|| Value::Number(0 as _))
540 .try_into()?;
541 let top = s
542 .get_field("top")
543 .cloned()
544 .unwrap_or_else(|| Value::Number(0 as _))
545 .try_into()?;
546 let bottom = s
547 .get_field("bottom")
548 .cloned()
549 .unwrap_or_else(|| Value::Number(0 as _))
550 .try_into()?;
551 Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
552 }
553 _ => Err(v),
554 }
555 }
556}
557
558impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
559 fn from(m: ModelRc<T>) -> Self {
560 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
561 Value::Model(v.clone())
562 } else {
563 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
564 }
565 }
566}
567impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
568 type Error = Value;
569 #[inline]
570 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
571 match v {
572 Value::Model(m) => {
573 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
574 Ok(v.clone())
575 } else if let Some(v) =
576 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
577 {
578 Ok(v.0.clone())
579 } else {
580 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
581 }
582 }
583 _ => Err(v),
584 }
585 }
586}
587
588#[test]
589fn value_model_conversion() {
590 use i_slint_core::model::*;
591 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
592 let v = Value::from(m.clone());
593 assert_eq!(v, Value::Model(m.clone()));
594 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
595 assert_eq!(m2, m);
596
597 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
598 assert_eq!(int_model.row_count(), 2);
599 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
600
601 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
602 assert_eq!(m3.row_count(), 2);
603 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
604
605 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
606 assert_eq!(str_model.row_count(), 2);
607 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
609
610 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
611 assert!(err.is_err());
612
613 let model =
614 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
615
616 let value: Value = ModelRc::from(model.clone()).into();
617 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
618 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
619 value_model.set_row_data(1, Value::String("qux".into()));
620 value_model.set_row_data(0, Value::Bool(true));
621 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
622 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
624
625 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
627 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
628
629 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
630 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
631 assert_eq!(
632 model.as_ref() as *const VecModel<SharedString>,
633 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
634 as *const VecModel<SharedString>
635 );
636}
637
638pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
639 i_slint_compiler::parser::normalize_identifier(ident)
640}
641
642#[derive(Clone, PartialEq, Debug, Default)]
664pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
665impl Struct {
666 pub fn get_field(&self, name: &str) -> Option<&Value> {
668 if i_slint_compiler::parser::is_identifier_normalized(name) {
669 self.0.get(name)
670 } else {
671 self.0.get(&*normalize_identifier(name))
672 }
673 }
674 pub fn set_field(&mut self, name: String, value: Value) {
676 self.0.insert(normalize_identifier(&name), value);
677 }
678
679 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
681 self.0.iter().map(|(a, b)| (a.as_str(), b))
682 }
683}
684
685impl FromIterator<(String, Value)> for Struct {
686 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
687 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
688 }
689}
690
691#[test]
692fn struct_field_name_normalization() {
693 let mut s = Struct::default();
694 s.set_field("foo_bar".into(), Value::Number(1.));
695 s.set_field("cross-axis-self-alignment".into(), Value::Number(2.));
697 assert_eq!(s.get_field("foo-bar"), Some(&Value::Number(1.)));
698 assert_eq!(s.get_field("foo_bar"), Some(&Value::Number(1.)));
699 assert_eq!(s.get_field("cross-axis-self-alignment"), Some(&Value::Number(2.)));
700 assert_eq!(s.get_field("cross_axis_self_alignment"), Some(&Value::Number(2.)));
701}
702
703#[deprecated(note = "Use slint_interpreter::Compiler instead")]
705pub struct ComponentCompiler {
706 config: i_slint_compiler::CompilerConfiguration,
707 diagnostics: Vec<Diagnostic>,
708}
709
710#[allow(deprecated)]
711impl Default for ComponentCompiler {
712 fn default() -> Self {
713 let mut config = i_slint_compiler::CompilerConfiguration::new(
714 i_slint_compiler::generator::OutputFormat::Interpreter,
715 );
716 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
717 Self { config, diagnostics: Vec::new() }
718 }
719}
720
721#[allow(deprecated)]
722impl ComponentCompiler {
723 pub fn new() -> Self {
725 Self::default()
726 }
727
728 #[doc(hidden)]
732 #[cfg(feature = "internal")]
733 pub fn compiler_configuration(
734 &mut self,
735 _: i_slint_core::InternalToken,
736 ) -> &mut i_slint_compiler::CompilerConfiguration {
737 &mut self.config
738 }
739
740 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
742 self.config.include_paths = include_paths;
743 }
744
745 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
747 &self.config.include_paths
748 }
749
750 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
752 self.config.library_paths = library_paths;
753 }
754
755 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
757 &self.config.library_paths
758 }
759
760 pub fn set_style(&mut self, style: String) {
772 self.config.style = Some(style);
773 }
774
775 pub fn style(&self) -> Option<&String> {
777 self.config.style.as_ref()
778 }
779
780 pub fn set_translation_domain(&mut self, domain: String) {
782 self.config.translation_domain = Some(domain);
783 }
784
785 pub fn set_file_loader(
793 &mut self,
794 file_loader_fallback: impl Fn(
795 &Path,
796 ) -> core::pin::Pin<
797 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
798 > + 'static,
799 ) {
800 self.config.open_import_callback =
801 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
802 }
803
804 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
806 &self.diagnostics
807 }
808
809 pub async fn build_from_path<P: AsRef<Path>>(
828 &mut self,
829 path: P,
830 ) -> Option<ComponentDefinition> {
831 let path = path.as_ref();
832 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
833 Ok(s) => s,
834 Err(d) => {
835 self.diagnostics = vec![d];
836 return None;
837 }
838 };
839
840 let r = build_compilation_result(source, path.into(), self.config.clone()).await;
841 self.diagnostics = r.diagnostics.into_iter().collect();
842 r.components.into_values().next()
843 }
844
845 pub async fn build_from_source(
862 &mut self,
863 source_code: String,
864 path: PathBuf,
865 ) -> Option<ComponentDefinition> {
866 let r = build_compilation_result(source_code, path, self.config.clone()).await;
867 self.diagnostics = r.diagnostics.into_iter().collect();
868 r.components.into_values().next()
869 }
870}
871
872pub struct Compiler {
875 config: i_slint_compiler::CompilerConfiguration,
876}
877
878impl Default for Compiler {
879 fn default() -> Self {
880 let config = i_slint_compiler::CompilerConfiguration::new(
881 i_slint_compiler::generator::OutputFormat::Interpreter,
882 );
883 Self { config }
884 }
885}
886
887impl Compiler {
888 pub fn new() -> Self {
890 Self::default()
891 }
892
893 #[doc(hidden)]
894 #[cfg(feature = "internal")]
895 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
896 self.config.embed_resources = embed_resources;
897 }
898
899 #[doc(hidden)]
903 #[cfg(feature = "internal")]
904 pub fn compiler_configuration(
905 &mut self,
906 _: i_slint_core::InternalToken,
907 ) -> &mut i_slint_compiler::CompilerConfiguration {
908 &mut self.config
909 }
910
911 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
913 self.config.include_paths = include_paths;
914 }
915
916 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
918 &self.config.include_paths
919 }
920
921 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
923 self.config.library_paths = library_paths;
924 }
925
926 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
928 &self.config.library_paths
929 }
930
931 pub fn set_style(&mut self, style: String) {
942 self.config.style = Some(style);
943 }
944
945 pub fn style(&self) -> Option<&String> {
947 self.config.style.as_ref()
948 }
949
950 pub fn set_translation_domain(&mut self, domain: String) {
952 self.config.translation_domain = Some(domain);
953 }
954
955 pub fn set_default_translation_context(
961 &mut self,
962 default_translation_context: DefaultTranslationContext,
963 ) {
964 self.config.default_translation_context = default_translation_context;
965 }
966
967 pub fn set_file_loader(
975 &mut self,
976 file_loader_fallback: impl Fn(
977 &Path,
978 ) -> core::pin::Pin<
979 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
980 > + 'static,
981 ) {
982 self.config.open_import_callback =
983 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
984 }
985
986 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
1005 let path = path.as_ref();
1006 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
1007 Ok(s) => s,
1008 Err(d) => {
1009 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1010 diagnostics.push_compiler_error(d);
1011 return CompilationResult {
1012 components: HashMap::new(),
1013 diagnostics: diagnostics.into_iter().collect(),
1014 #[cfg(feature = "internal")]
1015 watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
1016 #[cfg(feature = "internal")]
1017 structs_and_enums: Vec::new(),
1018 #[cfg(feature = "internal")]
1019 named_exports: Vec::new(),
1020 };
1021 }
1022 };
1023
1024 build_compilation_result(source, path.into(), self.config.clone()).await
1025 }
1026
1027 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1040 build_compilation_result(source_code, path, self.config.clone()).await
1041 }
1042}
1043
1044async fn build_compilation_result(
1045 source_code: String,
1046 path: PathBuf,
1047 config: i_slint_compiler::CompilerConfiguration,
1048) -> CompilationResult {
1049 let result = crate::component::build_from_source(source_code, path, config).await;
1050 let components = result
1051 .components
1052 .into_iter()
1053 .map(|(name, def)| (name, ComponentDefinition { inner: std::rc::Rc::new(def) }))
1054 .collect::<HashMap<String, ComponentDefinition>>();
1055 CompilationResult {
1056 components,
1057 diagnostics: result.diagnostics,
1058 #[cfg(feature = "internal")]
1059 watch_paths: result.watch_paths,
1060 #[cfg(feature = "internal")]
1061 structs_and_enums: result.structs_and_enums,
1062 #[cfg(feature = "internal")]
1063 named_exports: result.named_exports,
1064 }
1065}
1066
1067#[derive(Clone)]
1074pub struct CompilationResult {
1075 pub(crate) components: HashMap<String, ComponentDefinition>,
1076 pub(crate) diagnostics: Vec<Diagnostic>,
1077 #[cfg(feature = "internal")]
1078 pub(crate) watch_paths: Vec<PathBuf>,
1079 #[cfg(feature = "internal")]
1080 pub(crate) structs_and_enums: Vec<LangType>,
1081 #[cfg(feature = "internal")]
1083 pub(crate) named_exports: Vec<(String, String)>,
1084}
1085
1086impl core::fmt::Debug for CompilationResult {
1087 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1088 f.debug_struct("CompilationResult")
1089 .field("components", &self.components.keys())
1090 .field("diagnostics", &self.diagnostics)
1091 .finish()
1092 }
1093}
1094
1095impl CompilationResult {
1096 pub fn has_errors(&self) -> bool {
1099 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1100 }
1101
1102 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1106 self.diagnostics.iter().cloned()
1107 }
1108
1109 #[cfg(feature = "display-diagnostics")]
1115 pub fn print_diagnostics(&self) {
1116 print_diagnostics(&self.diagnostics)
1117 }
1118
1119 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1121 self.components.values().cloned()
1122 }
1123
1124 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1126 self.components.keys().map(|s| s.as_str())
1127 }
1128
1129 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1132 self.components.get(name).cloned()
1133 }
1134
1135 #[doc(hidden)]
1137 #[cfg(feature = "internal")]
1138 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1139 &self.watch_paths
1140 }
1141
1142 #[doc(hidden)]
1144 #[cfg(feature = "internal")]
1145 pub fn structs_and_enums(
1146 &self,
1147 _: i_slint_core::InternalToken,
1148 ) -> impl Iterator<Item = &LangType> {
1149 self.structs_and_enums.iter()
1150 }
1151
1152 #[doc(hidden)]
1155 #[cfg(feature = "internal")]
1156 pub fn named_exports(
1157 &self,
1158 _: i_slint_core::InternalToken,
1159 ) -> impl Iterator<Item = &(String, String)> {
1160 self.named_exports.iter()
1161 }
1162}
1163
1164#[derive(Clone)]
1172pub struct ComponentDefinition {
1173 pub(crate) inner: std::rc::Rc<crate::component::ComponentDefinitionInner>,
1174}
1175
1176impl ComponentDefinition {
1177 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1179 let instance = self.create_with_options(Default::default())?;
1180 if !instance.is_system_tray_rooted() {
1183 instance.inner.window_adapter_ref()?;
1185 i_slint_core::window::WindowInner::from_pub(instance.window())
1188 .ensure_tree_instantiated();
1189 }
1190 Ok(instance)
1191 }
1192
1193 #[doc(hidden)]
1195 #[cfg(feature = "internal")]
1196 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1197 self.create_with_options(WindowOptions::Embed {
1198 parent_item_tree: ctx.parent_item_tree,
1199 parent_item_tree_index: ctx.parent_item_tree_index,
1200 })
1201 }
1202
1203 #[doc(hidden)]
1205 #[cfg(feature = "internal")]
1206 pub fn create_with_existing_window(
1207 &self,
1208 window: &Window,
1209 ) -> Result<ComponentInstance, PlatformError> {
1210 self.create_with_options(WindowOptions::UseExistingWindow(
1211 WindowInner::from_pub(window).window_adapter(),
1212 ))
1213 }
1214
1215 pub(crate) fn create_with_options(
1217 &self,
1218 options: WindowOptions,
1219 ) -> Result<ComponentInstance, PlatformError> {
1220 let instance = match options {
1221 WindowOptions::CreateNewWindow => self.inner.create(),
1222 WindowOptions::UseExistingWindow(adapter) => {
1223 self.inner.create_with_existing_window(adapter)
1224 }
1225 WindowOptions::Embed { parent_item_tree, parent_item_tree_index } => {
1226 self.inner.create_embedded(parent_item_tree, parent_item_tree_index)
1227 }
1228 };
1229 Ok(ComponentInstance { inner: instance })
1230 }
1231}
1232
1233#[allow(dead_code)]
1238#[derive(Default)]
1239pub(crate) enum WindowOptions {
1240 #[default]
1241 CreateNewWindow,
1242 UseExistingWindow(i_slint_core::window::WindowAdapterRc),
1243 Embed {
1244 parent_item_tree: i_slint_core::item_tree::ItemTreeWeak,
1245 parent_item_tree_index: u32,
1246 },
1247}
1248
1249impl ComponentDefinition {
1250 #[doc(hidden)]
1254 #[cfg(feature = "internal")]
1255 pub fn properties_and_callbacks(
1256 &self,
1257 ) -> impl Iterator<
1258 Item = (
1259 String,
1260 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1261 ),
1262 > + '_ {
1263 self.inner
1264 .properties_and_callbacks()
1265 .map(|(n, t, v)| (n.to_string(), (t, v)))
1266 .collect::<Vec<_>>()
1267 .into_iter()
1268 }
1269
1270 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1273 self.inner
1274 .properties()
1275 .map(|(n, t)| (n.to_string(), t.into()))
1276 .collect::<Vec<_>>()
1277 .into_iter()
1278 }
1279
1280 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1282 self.inner.callbacks().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1283 }
1284
1285 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1287 self.inner.functions().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1288 }
1289
1290 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1295 self.inner.globals().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1296 }
1297
1298 #[doc(hidden)]
1302 #[cfg(feature = "internal")]
1303 pub fn global_properties_and_callbacks(
1304 &self,
1305 global_name: &str,
1306 ) -> Option<
1307 impl Iterator<
1308 Item = (
1309 String,
1310 (
1311 i_slint_compiler::langtype::Type,
1312 i_slint_compiler::object_tree::PropertyVisibility,
1313 ),
1314 ),
1315 > + '_,
1316 > {
1317 Some(
1318 self.inner
1319 .global_properties_and_callbacks(global_name)?
1320 .map(|(n, t, v)| (n.to_string(), (t, v)))
1321 .collect::<Vec<_>>()
1322 .into_iter(),
1323 )
1324 }
1325
1326 pub fn global_properties(
1328 &self,
1329 global_name: &str,
1330 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1331 Some(
1332 self.inner
1333 .global_properties(global_name)?
1334 .map(|(n, t)| (n.to_string(), t.into()))
1335 .collect::<Vec<_>>()
1336 .into_iter(),
1337 )
1338 }
1339
1340 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1342 Some(
1343 self.inner
1344 .global_callbacks(global_name)?
1345 .map(|s| s.to_string())
1346 .collect::<Vec<_>>()
1347 .into_iter(),
1348 )
1349 }
1350
1351 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1353 Some(
1354 self.inner
1355 .global_functions(global_name)?
1356 .map(|s| s.to_string())
1357 .collect::<Vec<_>>()
1358 .into_iter(),
1359 )
1360 }
1361
1362 pub fn name(&self) -> &str {
1364 self.inner.name()
1365 }
1366
1367 #[doc(hidden)]
1371 #[cfg(feature = "internal")]
1372 pub fn is_window(&self) -> bool {
1373 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::Window
1374 }
1375
1376 #[cfg(feature = "internal")]
1378 #[doc(hidden)]
1379 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1380 self.inner
1381 .type_loaders
1382 .originals
1383 .get(self.inner.public_index)
1384 .expect("root_component() called on a definition built without compiler state")
1385 .clone()
1386 }
1387
1388 #[cfg(feature = "internal-highlight")]
1392 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1393 self.inner.type_loaders.type_loader.clone().expect(
1394 "TypeLoader was not retained for this ComponentDefinition (reconstructed from an instance)",
1395 )
1396 }
1397
1398 #[cfg(feature = "internal-highlight")]
1406 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1407 self.inner
1408 .type_loaders
1409 .raw_type_loader
1410 .as_ref()
1411 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1412 }
1413}
1414
1415#[cfg(feature = "display-diagnostics")]
1421pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1422 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1423 for d in diagnostics {
1424 build_diagnostics.push_compiler_error(d.clone())
1425 }
1426 build_diagnostics.print();
1427}
1428
1429#[repr(C)]
1437pub struct ComponentInstance {
1438 pub(crate) inner: crate::component::ComponentInstanceInner,
1439}
1440
1441impl ComponentInstance {
1442 pub fn definition(&self) -> ComponentDefinition {
1444 ComponentDefinition { inner: std::rc::Rc::new(self.inner.definition()) }
1445 }
1446
1447 fn is_system_tray_rooted(&self) -> bool {
1448 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::SystemTrayIcon
1449 }
1450
1451 fn set_tray_icon_visible(&self, visible: bool) {
1455 let item_rc = ItemRc::new(vtable::VRc::into_dyn(self.inner.vrc().clone()), 0);
1457 let tray = item_rc
1458 .downcast::<SystemTrayIcon>()
1459 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1460 tray.as_pin_ref().visible.set(visible);
1461 }
1462
1463 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1483 self.inner.get_property(name).ok_or(GetPropertyError::NoSuchProperty)
1484 }
1485
1486 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1488 self.inner.set_property(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 self.inner.set_callback(name, callback).map_err(|()| SetCallbackError::NoSuchCallback)
1531 }
1532
1533 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1538 self.inner.invoke(name, args).ok_or(InvokeError::NoSuchCallable)
1539 }
1540
1541 pub fn get_global_property(
1566 &self,
1567 global: &str,
1568 property: &str,
1569 ) -> Result<Value, GetPropertyError> {
1570 self.inner.get_global_property(global, property).ok_or(GetPropertyError::NoSuchProperty)
1571 }
1572
1573 pub fn set_global_property(
1575 &self,
1576 global: &str,
1577 property: &str,
1578 value: Value,
1579 ) -> Result<(), SetPropertyError> {
1580 self.inner.set_global_property(global, property, value)
1581 }
1582
1583 pub fn set_global_callback(
1618 &self,
1619 global: &str,
1620 name: &str,
1621 callback: impl Fn(&[Value]) -> Value + 'static,
1622 ) -> Result<(), SetCallbackError> {
1623 self.inner
1624 .set_global_callback(global, name, callback)
1625 .map_err(|()| SetCallbackError::NoSuchCallback)
1626 }
1627
1628 pub fn invoke_global(
1633 &self,
1634 global: &str,
1635 callable_name: &str,
1636 args: &[Value],
1637 ) -> Result<Value, InvokeError> {
1638 self.inner.invoke_global(global, callable_name, args).ok_or(InvokeError::NoSuchCallable)
1639 }
1640
1641 #[cfg(feature = "internal-highlight")]
1645 pub fn component_positions(
1646 &self,
1647 path: &Path,
1648 offset: u32,
1649 ) -> Vec<crate::highlight::HighlightedRect> {
1650 crate::highlight::component_positions(self.inner.vrc(), path, offset)
1651 }
1652
1653 #[cfg(feature = "internal-highlight")]
1657 pub fn element_positions(
1658 &self,
1659 element: &i_slint_compiler::object_tree::ElementRc,
1660 ) -> Vec<crate::highlight::HighlightedRect> {
1661 crate::highlight::element_positions(
1662 self.inner.vrc(),
1663 element,
1664 crate::highlight::ElementPositionFilter::IncludeClipped,
1665 )
1666 }
1667
1668 #[cfg(feature = "internal-highlight")]
1672 pub fn element_node_at_source_code_position(
1673 &self,
1674 path: &Path,
1675 offset: u32,
1676 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1677 crate::highlight::element_node_at_source_code_position(self.inner.vrc(), path, offset)
1678 }
1679
1680 #[cfg(feature = "internal")]
1682 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1683 crate::debug_hook::set_debug_hook_callback(self.inner.vrc(), callback);
1684 }
1685}
1686
1687impl StrongHandle for ComponentInstance {
1688 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::instance::Instance>;
1689
1690 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1691 Some(Self { inner: crate::component::ComponentInstanceInner(inner.upgrade()?) })
1692 }
1693}
1694
1695impl ComponentHandle for ComponentInstance {
1696 fn as_weak(&self) -> Weak<Self>
1697 where
1698 Self: Sized,
1699 {
1700 Weak::new(vtable::VRc::downgrade(self.inner.vrc()))
1701 }
1702
1703 fn clone_strong(&self) -> Self {
1704 Self { inner: self.inner.clone() }
1705 }
1706
1707 fn show(&self) -> Result<(), PlatformError> {
1708 if self.is_system_tray_rooted() {
1709 self.set_tray_icon_visible(true);
1710 return Ok(());
1711 }
1712 let adapter = self.inner.window_adapter_ref()?;
1713 self.inner.0.attach_to_window();
1717 adapter.window().show()
1718 }
1719
1720 fn hide(&self) -> Result<(), PlatformError> {
1721 if self.is_system_tray_rooted() {
1722 self.set_tray_icon_visible(false);
1723 return Ok(());
1724 }
1725 self.inner.window_adapter_ref()?.window().hide()
1726 }
1727
1728 fn run(&self) -> Result<(), PlatformError> {
1729 self.show()?;
1730 run_event_loop()?;
1731 self.hide()
1732 }
1733
1734 fn window(&self) -> &Window {
1735 let adapter = self.inner.window_adapter_ref().unwrap();
1736 self.inner.0.attach_to_window();
1742 adapter.window()
1743 }
1744
1745 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1746 where
1747 Self: Sized,
1748 {
1749 unreachable!()
1750 }
1751}
1752
1753impl From<ComponentInstance>
1754 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>
1755{
1756 fn from(value: ComponentInstance) -> Self {
1757 value.inner.0
1758 }
1759}
1760
1761#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1763#[non_exhaustive]
1764pub enum GetPropertyError {
1765 #[display("no such property")]
1767 NoSuchProperty,
1768}
1769
1770#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1772#[non_exhaustive]
1773pub enum SetPropertyError {
1774 #[display("no such property")]
1776 NoSuchProperty,
1777 #[display("wrong type")]
1783 WrongType,
1784 #[display("access denied")]
1786 AccessDenied,
1787}
1788
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1791#[non_exhaustive]
1792pub enum SetCallbackError {
1793 #[display("no such callback")]
1795 NoSuchCallback,
1796}
1797
1798#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1800#[non_exhaustive]
1801pub enum InvokeError {
1802 #[display("no such callback or function")]
1804 NoSuchCallable,
1805}
1806
1807pub fn run_event_loop() -> Result<(), PlatformError> {
1811 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1812}
1813
1814pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1818 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1819 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1820}
1821
1822#[test]
1823fn component_definition_properties() {
1824 i_slint_backend_testing::init_no_event_loop();
1825 let mut compiler = Compiler::default();
1826 compiler.set_style("fluent".into());
1827 let comp_def = spin_on::spin_on(
1828 compiler.build_from_source(
1829 r#"
1830 export component Dummy {
1831 in-out property <string> test;
1832 in-out property <int> underscores-and-dashes_preserved: 44;
1833 callback hello;
1834 }"#
1835 .into(),
1836 "".into(),
1837 ),
1838 )
1839 .component("Dummy")
1840 .unwrap();
1841
1842 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1843
1844 assert_eq!(props.len(), 2);
1845 assert_eq!(props[0].0, "test");
1846 assert_eq!(props[0].1, ValueType::String);
1847 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1848 assert_eq!(props[1].1, ValueType::Number);
1849
1850 let instance = comp_def.create().unwrap();
1851 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1852 assert_eq!(
1853 instance.get_property("underscoresanddashespreserved"),
1854 Err(GetPropertyError::NoSuchProperty)
1855 );
1856 assert_eq!(
1857 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1858 Ok(())
1859 );
1860 assert_eq!(
1861 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1862 Err(SetPropertyError::NoSuchProperty)
1863 );
1864 assert_eq!(
1865 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1866 Err(SetPropertyError::WrongType)
1867 );
1868 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
1869}
1870
1871#[test]
1872fn component_definition_properties2() {
1873 i_slint_backend_testing::init_no_event_loop();
1874 let mut compiler = Compiler::default();
1875 compiler.set_style("fluent".into());
1876 let comp_def = spin_on::spin_on(
1877 compiler.build_from_source(
1878 r#"
1879 export component Dummy {
1880 in-out property <string> sub-text <=> sub.text;
1881 sub := Text { property <int> private-not-exported; }
1882 out property <string> xreadonly: "the value";
1883 private property <string> xx: sub.text;
1884 callback hello;
1885 }"#
1886 .into(),
1887 "".into(),
1888 ),
1889 )
1890 .component("Dummy")
1891 .unwrap();
1892
1893 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1894
1895 assert_eq!(props.len(), 2);
1896 assert_eq!(props[0].0, "sub-text");
1897 assert_eq!(props[0].1, ValueType::String);
1898 assert_eq!(props[1].0, "xreadonly");
1899
1900 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
1901 assert_eq!(callbacks.len(), 1);
1902 assert_eq!(callbacks[0], "hello");
1903
1904 let instance = comp_def.create().unwrap();
1905 assert_eq!(
1906 instance.set_property("xreadonly", SharedString::from("XXX").into()),
1907 Err(SetPropertyError::AccessDenied)
1908 );
1909 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
1910 assert_eq!(
1911 instance.set_property("xx", SharedString::from("XXX").into()),
1912 Err(SetPropertyError::NoSuchProperty)
1913 );
1914 assert_eq!(
1915 instance.set_property("background", Value::default()),
1916 Err(SetPropertyError::NoSuchProperty)
1917 );
1918
1919 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
1920 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
1921}
1922
1923#[test]
1924fn globals() {
1925 i_slint_backend_testing::init_no_event_loop();
1926 let mut compiler = Compiler::default();
1927 compiler.set_style("fluent".into());
1928 let definition = spin_on::spin_on(
1929 compiler.build_from_source(
1930 r#"
1931 export global My-Super_Global {
1932 in-out property <int> the-property : 21;
1933 callback my-callback();
1934 callback int-callback() -> int;
1935 }
1936 export { My-Super_Global as AliasedGlobal }
1937 export component Dummy {
1938 callback alias <=> My-Super_Global.my-callback;
1939 }"#
1940 .into(),
1941 "".into(),
1942 ),
1943 )
1944 .component("Dummy")
1945 .unwrap();
1946
1947 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
1948
1949 assert!(definition.global_properties("not-there").is_none());
1950 {
1951 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
1952 let expected_callbacks = vec!["int-callback".to_string(), "my-callback".to_string()];
1953
1954 let assert_properties_and_callbacks = |global_name| {
1955 assert_eq!(
1956 definition
1957 .global_properties(global_name)
1958 .map(|props| props.collect::<Vec<_>>())
1959 .as_ref(),
1960 Some(&expected_properties)
1961 );
1962 assert_eq!(
1963 definition
1964 .global_callbacks(global_name)
1965 .map(|props| props.collect::<Vec<_>>())
1966 .as_ref(),
1967 Some(&expected_callbacks)
1968 );
1969 };
1970
1971 assert_properties_and_callbacks("My-Super-Global");
1972 assert_properties_and_callbacks("My_Super-Global");
1973 assert_properties_and_callbacks("AliasedGlobal");
1974 }
1975
1976 let instance = definition.create().unwrap();
1977 assert_eq!(
1978 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
1979 Ok(())
1980 );
1981 assert_eq!(
1982 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
1983 Ok(())
1984 );
1985 assert_eq!(
1986 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
1987 Err(SetPropertyError::NoSuchProperty)
1988 );
1989
1990 assert_eq!(
1991 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
1992 Err(SetPropertyError::NoSuchProperty)
1993 );
1994 assert_eq!(
1995 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
1996 Err(SetPropertyError::NoSuchProperty)
1997 );
1998 assert_eq!(
1999 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2000 Err(SetPropertyError::WrongType)
2001 );
2002 assert_eq!(
2003 instance.get_global_property("My-Super_Global", "yoyo"),
2004 Err(GetPropertyError::NoSuchProperty)
2005 );
2006 assert_eq!(
2007 instance.get_global_property("My-Super_Global", "the-property"),
2008 Ok(Value::Number(44.))
2009 );
2010
2011 assert_eq!(
2012 instance.set_property("the-property", Value::Void),
2013 Err(SetPropertyError::NoSuchProperty)
2014 );
2015 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2016
2017 assert_eq!(
2018 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2019 Err(SetCallbackError::NoSuchCallback)
2020 );
2021 assert_eq!(
2022 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2023 Err(SetCallbackError::NoSuchCallback)
2024 );
2025 assert_eq!(
2026 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2027 Err(SetCallbackError::NoSuchCallback)
2028 );
2029
2030 assert_eq!(
2031 instance.invoke_global("DontExist", "the-property", &[]),
2032 Err(InvokeError::NoSuchCallable)
2033 );
2034 assert_eq!(
2035 instance.invoke_global("My_Super_Global", "the-property", &[]),
2036 Err(InvokeError::NoSuchCallable)
2037 );
2038 assert_eq!(
2039 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2040 Err(InvokeError::NoSuchCallable)
2041 );
2042
2043 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2045
2046 assert_eq!(
2048 instance.invoke_global("My_Super_Global", "int-callback", &[]),
2049 Ok(Value::Number(0.))
2050 );
2051}
2052
2053#[test]
2054fn call_functions() {
2055 i_slint_backend_testing::init_no_event_loop();
2056 let mut compiler = Compiler::default();
2057 compiler.set_style("fluent".into());
2058 let definition = spin_on::spin_on(
2059 compiler.build_from_source(
2060 r#"
2061 export global Gl {
2062 out property<string> q;
2063 public function foo-bar(a-a: string, b-b:int) -> string {
2064 q = a-a;
2065 return a-a + b-b;
2066 }
2067 }
2068 export component Test {
2069 out property<int> p;
2070 public function foo-bar(a: int, b:int) -> int {
2071 p = a;
2072 return a + b;
2073 }
2074 }"#
2075 .into(),
2076 "".into(),
2077 ),
2078 )
2079 .component("Test")
2080 .unwrap();
2081
2082 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2083 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2084
2085 let instance = definition.create().unwrap();
2086
2087 assert_eq!(
2088 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2089 Ok(Value::Number(7.))
2090 );
2091 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2092 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2093
2094 assert_eq!(
2095 instance.invoke_global(
2096 "Gl",
2097 "foo_bar",
2098 &[Value::String("Hello".into()), Value::Number(10.)]
2099 ),
2100 Ok(Value::String("Hello10".into()))
2101 );
2102 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2103}
2104
2105#[test]
2106fn component_definition_struct_properties() {
2107 i_slint_backend_testing::init_no_event_loop();
2108 let mut compiler = Compiler::default();
2109 compiler.set_style("fluent".into());
2110 let comp_def = spin_on::spin_on(
2111 compiler.build_from_source(
2112 r#"
2113 export struct Settings {
2114 string_value: string,
2115 }
2116 export component Dummy {
2117 in-out property <Settings> test;
2118 }"#
2119 .into(),
2120 "".into(),
2121 ),
2122 )
2123 .component("Dummy")
2124 .unwrap();
2125
2126 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2127
2128 assert_eq!(props.len(), 1);
2129 assert_eq!(props[0].0, "test");
2130 assert_eq!(props[0].1, ValueType::Struct);
2131
2132 let instance = comp_def.create().unwrap();
2133
2134 let valid_struct: Struct =
2135 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2136
2137 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2138 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2139
2140 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2141
2142 let mut invalid_struct = valid_struct.clone();
2143 invalid_struct.set_field("other".into(), Value::Number(44.));
2144 assert_eq!(
2145 instance.set_property("test", Value::Struct(invalid_struct)),
2146 Err(SetPropertyError::WrongType)
2147 );
2148 let mut invalid_struct = valid_struct;
2149 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2150 assert_eq!(
2151 instance.set_property("test", Value::Struct(invalid_struct)),
2152 Err(SetPropertyError::WrongType)
2153 );
2154}
2155
2156#[test]
2157fn component_definition_model_properties() {
2158 use i_slint_core::model::*;
2159 i_slint_backend_testing::init_no_event_loop();
2160 let mut compiler = Compiler::default();
2161 compiler.set_style("fluent".into());
2162 let comp_def = spin_on::spin_on(compiler.build_from_source(
2163 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2164 "".into(),
2165 ))
2166 .component("Dummy")
2167 .unwrap();
2168
2169 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2170 assert_eq!(props.len(), 1);
2171 assert_eq!(props[0].0, "prop");
2172 assert_eq!(props[0].1, ValueType::Model);
2173
2174 let instance = comp_def.create().unwrap();
2175
2176 let int_model =
2177 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2178 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2179 let model_with_string = Value::Model(VecModel::from_slice(&[
2180 Value::Number(1000.),
2181 Value::String("foo".into()),
2182 Value::Number(1111.),
2183 ]));
2184
2185 #[track_caller]
2186 fn check_model(val: Value, r: &[f64]) {
2187 if let Value::Model(m) = val {
2188 assert_eq!(r.len(), m.row_count());
2189 for (i, v) in r.iter().enumerate() {
2190 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2191 }
2192 } else {
2193 panic!("{val:?} not a model");
2194 }
2195 }
2196
2197 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2198 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2199
2200 instance.set_property("prop", int_model).unwrap();
2201 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2202
2203 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2204 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2205 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2206 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2207
2208 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2209 check_model(instance.get_property("prop").unwrap(), &[]);
2210}
2211
2212#[test]
2213fn lang_type_to_value_type() {
2214 use i_slint_compiler::langtype::Struct as LangStruct;
2215 use std::collections::BTreeMap;
2216
2217 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2218 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2219 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2220 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2221 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2222 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2223 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2224 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2225 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2226 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2227 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2228 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2229 assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2230 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2231 assert_eq!(
2232 ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2233 BTreeMap::default(),
2234 i_slint_compiler::langtype::StructName::None
2235 )))),
2236 ValueType::Struct
2237 );
2238 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2239}
2240
2241#[test]
2242fn test_multi_components() {
2243 i_slint_backend_testing::init_no_event_loop();
2244 let result = spin_on::spin_on(
2245 Compiler::default().build_from_source(
2246 r#"
2247 export struct Settings {
2248 string_value: string,
2249 }
2250 export global ExpGlo { in-out property <int> test: 42; }
2251 component Common {
2252 in-out property <Settings> settings: { string_value: "Hello", };
2253 }
2254 export component Xyz inherits Window {
2255 in-out property <int> aaa: 8;
2256 }
2257 export component Foo {
2258
2259 in-out property <int> test: 42;
2260 c := Common {}
2261 }
2262 export component Bar inherits Window {
2263 in-out property <int> blah: 78;
2264 c := Common {}
2265 }
2266 "#
2267 .into(),
2268 PathBuf::from("hello.slint"),
2269 ),
2270 );
2271
2272 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2273 let mut components = result.component_names().collect::<Vec<_>>();
2274 components.sort();
2275 assert_eq!(components, vec!["Bar", "Xyz"]);
2276 let diag = result.diagnostics().collect::<Vec<_>>();
2277 assert_eq!(diag.len(), 1);
2278 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2279 assert_eq!(
2280 diag[0].message(),
2281 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2282 );
2283
2284 let comp1 = result.component("Xyz").unwrap();
2285 assert_eq!(comp1.name(), "Xyz");
2286 let instance1a = comp1.create().unwrap();
2287 let comp2 = result.component("Bar").unwrap();
2288 let instance2 = comp2.create().unwrap();
2289 let instance1b = comp1.create().unwrap();
2290
2291 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2293 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2294 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2295 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2296 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2297
2298 assert!(result.component("Settings").is_none());
2299 assert!(result.component("Foo").is_none());
2300 assert!(result.component("Common").is_none());
2301 assert!(result.component("ExpGlo").is_none());
2302 assert!(result.component("xyz").is_none());
2303}
2304
2305#[cfg(all(test, feature = "internal-highlight"))]
2306fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2307 i_slint_backend_testing::init_no_event_loop();
2308 let mut compiler = Compiler::default();
2309 compiler.set_style("fluent".into());
2310 let path = PathBuf::from("/tmp/test.slint");
2311
2312 let compile_result =
2313 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2314
2315 for d in &compile_result.diagnostics {
2316 eprintln!("{d}");
2317 }
2318
2319 assert!(!compile_result.has_errors());
2320
2321 let definition = compile_result.components().next().unwrap();
2322 let instance = definition.create().unwrap();
2323
2324 (instance, path)
2325}
2326
2327#[cfg(feature = "internal-highlight")]
2328#[test]
2329fn test_element_node_at_source_code_position() {
2330 let code = r#"
2331component Bar1 {}
2332
2333component Foo1 {
2334}
2335
2336export component Foo2 inherits Window {
2337 Bar1 {}
2338 Foo1 {}
2339}"#;
2340
2341 let (handle, path) = compile(code);
2342
2343 for i in 0..code.len() as u32 {
2344 let elements = handle.element_node_at_source_code_position(&path, i);
2345 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2346 match i {
2347 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()),
2353 }
2354 }
2355}
2356
2357#[cfg(feature = "internal-highlight")]
2361#[test]
2362fn test_element_positions_instances_and_repeaters() {
2363 use i_slint_core::graphics::euclid;
2364 let code = r#"
2365component MyBox inherits Rectangle {
2366 width: 50px;
2367 height: 50px;
2368}
2369
2370export component Foo3 inherits Window {
2371 width: 400px;
2372 height: 400px;
2373 b1 := MyBox { x: 0px; y: 0px; }
2374 b2 := MyBox { x: 200px; y: 200px; }
2375 for xo in [0, 1, 2]: Rectangle {
2376 x: xo * 10px;
2377 y: 300px;
2378 width: 10px;
2379 height: 10px;
2380 }
2381}"#;
2382
2383 let (handle, path) = compile(code);
2384
2385 let element_at = |pattern: &str| {
2386 let offset = code.find(pattern).unwrap() as u32;
2387 let elements = handle.element_node_at_source_code_position(&path, offset);
2388 assert_eq!(elements.len(), 1, "expected one element at {pattern:?}");
2389 elements.into_iter().next().unwrap().0
2390 };
2391
2392 let b1_rects = handle.element_positions(&element_at("MyBox { x: 0px"));
2394 assert_eq!(b1_rects.len(), 1, "{b1_rects:?}");
2395 assert_eq!(b1_rects[0].rect.origin, euclid::point2(0., 0.));
2396
2397 let b2_rects = handle.element_positions(&element_at("MyBox { x: 200px"));
2398 assert_eq!(b2_rects.len(), 1, "{b2_rects:?}");
2399 assert_eq!(b2_rects[0].rect.origin, euclid::point2(200., 200.));
2400
2401 let def_rects = handle.element_positions(&element_at("Rectangle {\n width: 50px"));
2403 assert_eq!(def_rects.len(), 2, "{def_rects:?}");
2404
2405 let repeated = element_at("Rectangle {\n x: xo");
2407 let mut row_rects = handle.element_positions(&repeated);
2408 row_rects.sort_by(|a, b| a.rect.origin.x.total_cmp(&b.rect.origin.x));
2409 assert_eq!(row_rects.len(), 3, "{row_rects:?}");
2410 for (i, r) in row_rects.iter().enumerate() {
2411 assert_eq!(r.rect.origin, euclid::point2(i as f32 * 10., 300.));
2412 assert_eq!(r.rect.size, euclid::size2(10., 10.));
2413 }
2414
2415 let offset = code.find("Rectangle {\n x: xo").unwrap() as u32;
2418 assert_eq!(handle.component_positions(&path, offset).len(), 3);
2419 assert!(handle.component_positions(&path, code.len() as u32 - 1).is_empty());
2420}