1use i_slint_compiler::langtype::Type as LangType;
6use i_slint_compiler::source_path::SourcePath;
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;
24use std::time::Duration;
25
26#[doc(inline)]
27pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
28
29pub use i_slint_backend_selector::api::*;
30pub use i_slint_core::api::*;
31
32pub use i_slint_compiler::DefaultTranslationContext;
35
36#[derive(Debug, Copy, Clone, PartialEq)]
39#[repr(i8)]
40#[non_exhaustive]
41pub enum ValueType {
42 Void,
44 Number,
46 String,
48 Bool,
50 Model,
52 Struct,
54 Brush,
56 Image,
58 #[doc(hidden)]
60 Other = -1,
61}
62
63impl From<LangType> for ValueType {
64 fn from(ty: LangType) -> Self {
65 match ty {
66 LangType::Float32
67 | LangType::Int32
68 | LangType::Duration
69 | LangType::Angle
70 | LangType::PhysicalLength
71 | LangType::LogicalLength
72 | LangType::Percent
73 | LangType::UnitProduct(_) => Self::Number,
74 LangType::String => Self::String,
75 LangType::Color => Self::Brush,
76 LangType::Brush => Self::Brush,
77 LangType::Array(_) => Self::Model,
78 LangType::Bool => Self::Bool,
79 LangType::Struct { .. } => Self::Struct,
80 LangType::Void => Self::Void,
81 LangType::Image => Self::Image,
82 _ => Self::Other,
83 }
84 }
85}
86
87#[derive(Clone, Default)]
99#[non_exhaustive]
100#[repr(u8)]
101pub enum Value {
102 #[default]
105 Void = 0,
106 Number(f64) = 1,
108 String(SharedString) = 2,
110 Bool(bool) = 3,
112 Image(Image) = 4,
114 Model(ModelRc<Value>) = 5,
116 Struct(Struct) = 6,
118 Brush(Brush) = 7,
120 #[doc(hidden)]
121 PathData(PathData) = 8,
123 #[doc(hidden)]
124 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
126 #[doc(hidden)]
127 EnumerationValue(String, String) = 10,
130 #[doc(hidden)]
131 LayoutCache(SharedVector<f32>) = 11,
132 #[doc(hidden)]
133 ComponentFactory(ComponentFactory) = 12,
135 #[doc(hidden)] StyledText(StyledText) = 13,
138 #[doc(hidden)]
139 ArrayOfU16(SharedVector<u16>) = 14,
140 Keys(Keys) = 15,
142 DataTransfer(DataTransfer) = 16,
144 #[doc(hidden)]
145 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
147}
148
149impl Value {
150 pub fn value_type(&self) -> ValueType {
152 match self {
153 Value::Void => ValueType::Void,
154 Value::Number(_) => ValueType::Number,
155 Value::String(_) => ValueType::String,
156 Value::Bool(_) => ValueType::Bool,
157 Value::Model(_) => ValueType::Model,
158 Value::Struct(_) => ValueType::Struct,
159 Value::Brush(_) => ValueType::Brush,
160 Value::Image(_) => ValueType::Image,
161 _ => ValueType::Other,
162 }
163 }
164}
165
166impl i_slint_core::rtti::ValueType for Value {}
167
168impl PartialEq for Value {
169 fn eq(&self, other: &Self) -> bool {
170 match self {
171 Value::Void => matches!(other, Value::Void),
172 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
173 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
174 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
175 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
176 Value::Model(lhs) => {
177 if let Value::Model(rhs) = other {
178 lhs == rhs
179 } else {
180 false
181 }
182 }
183 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
184 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
185 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
186 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
187 Value::EnumerationValue(lhs_name, lhs_value) => {
188 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
189 }
190 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
191 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
192 Value::ComponentFactory(lhs) => {
193 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
194 }
195 Value::StyledText(lhs) => {
196 matches!(other, Value::StyledText(rhs) if lhs == rhs)
197 }
198 Value::Keys(lhs) => {
199 matches!(other, Value::Keys(rhs) if lhs == rhs)
200 }
201 Value::DataTransfer(lhs) => {
202 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
203 }
204 Value::MouseCursorInner(lhs) => {
205 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
206 }
207 }
208 }
209}
210
211impl std::fmt::Debug for Value {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 match self {
214 Value::Void => write!(f, "Value::Void"),
215 Value::Number(n) => write!(f, "Value::Number({n:?})"),
216 Value::String(s) => write!(f, "Value::String({s:?})"),
217 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
218 Value::Image(i) => write!(f, "Value::Image({i:?})"),
219 Value::Model(m) => {
220 write!(f, "Value::Model(")?;
221 f.debug_list().entries(m.iter()).finish()?;
222 write!(f, "])")
223 }
224 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
225 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
226 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
227 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
228 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
229 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
230 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
231 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
232 Value::ArrayOfU16(data) => {
233 write!(f, "Value::ArrayOfU16({data:?})")
234 }
235 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
236 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
237 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
238 }
239 }
240}
241
242macro_rules! declare_value_conversion {
251 ( $value:ident => [$($ty:ty),*] ) => {
252 $(
253 impl From<$ty> for Value {
254 fn from(v: $ty) -> Self {
255 Value::$value(v as _)
256 }
257 }
258 impl TryFrom<Value> for $ty {
259 type Error = Value;
260 fn try_from(v: Value) -> Result<$ty, Self::Error> {
261 match v {
262 Value::$value(x) => Ok(x as _),
263 _ => Err(v)
264 }
265 }
266 }
267 )*
268 };
269}
270declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
271declare_value_conversion!(String => [SharedString] );
272declare_value_conversion!(Bool => [bool] );
273declare_value_conversion!(Image => [Image] );
274declare_value_conversion!(Struct => [Struct] );
275declare_value_conversion!(Brush => [Brush] );
276declare_value_conversion!(PathData => [PathData]);
277declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
278declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
279declare_value_conversion!(ComponentFactory => [ComponentFactory] );
280declare_value_conversion!(StyledText => [StyledText] );
281declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
282declare_value_conversion!(Keys => [Keys]);
283declare_value_conversion!(DataTransfer => [DataTransfer]);
284declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
285
286macro_rules! declare_value_struct_conversion {
288 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
289 impl From<$name> for Value {
290 fn from($name { $($field),* , .. }: $name) -> Self {
291 let mut struct_ = Struct::default();
292 $(struct_.set_field(stringify!($field).into(), $field.into());)*
293 Value::Struct(struct_)
294 }
295 }
296 impl TryFrom<Value> for $name {
297 type Error = ();
298 fn try_from(v: Value) -> Result<$name, Self::Error> {
299 #[allow(clippy::field_reassign_with_default)]
300 match v {
301 Value::Struct(x) => {
302 type Ty = $name;
303 #[allow(unused)]
304 let mut res: Ty = Ty::default();
305 $(let mut res: Ty = $extra;)?
306 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
307 Ok(res)
308 }
309 _ => Err(()),
310 }
311 }
312 }
313 };
314 ($(
315 $(#[$struct_attr:meta])*
316 $vis:vis struct $Name:ident {
317 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
318 }
319 )*) => {
320 $(
321 impl From<$Name> for Value {
322 fn from(item: $Name) -> Self {
323 let mut struct_ = Struct::default();
324 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
325 Value::Struct(struct_)
326 }
327 }
328 impl TryFrom<Value> for $Name {
329 type Error = ();
330 fn try_from(v: Value) -> Result<$Name, Self::Error> {
331 #[allow(clippy::field_reassign_with_default)]
332 match v {
333 Value::Struct(x) => {
334 type Ty = $Name;
335 #[allow(unused)]
336 let mut res: Ty = Ty::default();
337 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
340 Ok(res)
341 }
342 _ => Err(()),
343 }
344 }
345 }
346 )*
347 };
348}
349
350declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
351declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
352declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
353declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
354declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
355
356i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
357
358macro_rules! declare_value_enum_conversion {
363 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
364 impl From<i_slint_core::items::$Name> for Value {
365 fn from(v: i_slint_core::items::$Name) -> Self {
366 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
367 }
368 }
369 impl TryFrom<Value> for i_slint_core::items::$Name {
370 type Error = ();
371 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
372 use std::str::FromStr;
373 match v {
374 Value::EnumerationValue(enumeration, value) => {
375 if enumeration != stringify!($Name) {
376 return Err(());
377 }
378 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
379 }
380 _ => Err(()),
381 }
382 }
383 }
384 )*};
385}
386
387i_slint_common::for_each_enums!(declare_value_enum_conversion);
388
389impl From<i_slint_core::animations::Instant> for Value {
390 fn from(value: i_slint_core::animations::Instant) -> Self {
391 Value::Number(value.as_millis() as f64)
392 }
393}
394impl TryFrom<Value> for i_slint_core::animations::Instant {
395 type Error = ();
396 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
397 match v {
398 Value::Number(x) => Ok(Duration::from_millis(x as u64).into()),
399 _ => Err(()),
400 }
401 }
402}
403
404impl From<()> for Value {
405 #[inline]
406 fn from(_: ()) -> Self {
407 Value::Void
408 }
409}
410impl TryFrom<Value> for () {
411 type Error = ();
412 #[inline]
413 fn try_from(_: Value) -> Result<(), Self::Error> {
414 Ok(())
415 }
416}
417
418impl From<Color> for Value {
419 #[inline]
420 fn from(c: Color) -> Self {
421 Value::Brush(Brush::SolidColor(c))
422 }
423}
424impl TryFrom<Value> for Color {
425 type Error = Value;
426 #[inline]
427 fn try_from(v: Value) -> Result<Color, Self::Error> {
428 match v {
429 Value::Brush(Brush::SolidColor(c)) => Ok(c),
430 _ => Err(v),
431 }
432 }
433}
434
435impl From<i_slint_core::lengths::LogicalLength> for Value {
436 #[inline]
437 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
438 Value::Number(l.get() as _)
439 }
440}
441impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
442 type Error = Value;
443 #[inline]
444 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
445 match v {
446 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
447 _ => Err(v),
448 }
449 }
450}
451
452impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
453 fn from(m: ModelRc<T>) -> Self {
454 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
455 Value::Model(v.clone())
456 } else {
457 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
458 }
459 }
460}
461impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
462 type Error = Value;
463 #[inline]
464 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
465 match v {
466 Value::Model(m) => {
467 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
468 Ok(v.clone())
469 } else if let Some(v) =
470 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
471 {
472 Ok(v.0.clone())
473 } else {
474 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
475 }
476 }
477 _ => Err(v),
478 }
479 }
480}
481
482#[test]
483fn value_model_conversion() {
484 use i_slint_core::model::*;
485 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
486 let v = Value::from(m.clone());
487 assert_eq!(v, Value::Model(m.clone()));
488 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
489 assert_eq!(m2, m);
490
491 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
492 assert_eq!(int_model.row_count(), 2);
493 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
494
495 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
496 assert_eq!(m3.row_count(), 2);
497 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
498
499 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
500 assert_eq!(str_model.row_count(), 2);
501 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
503
504 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
505 assert!(err.is_err());
506
507 let model =
508 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
509
510 let value: Value = ModelRc::from(model.clone()).into();
511 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
512 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
513 value_model.set_row_data(1, Value::String("qux".into()));
514 value_model.set_row_data(0, Value::Bool(true));
515 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
516 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
518
519 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
521 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
522
523 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
524 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
525 assert_eq!(
526 model.as_ref() as *const VecModel<SharedString>,
527 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
528 as *const VecModel<SharedString>
529 );
530}
531
532pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
533 i_slint_compiler::parser::normalize_identifier(ident)
534}
535
536#[derive(Clone, PartialEq, Debug, Default)]
558pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
559impl Struct {
560 pub fn get_field(&self, name: &str) -> Option<&Value> {
562 if i_slint_compiler::parser::is_identifier_normalized(name) {
563 self.0.get(name)
564 } else {
565 self.0.get(&*normalize_identifier(name))
566 }
567 }
568 pub fn set_field(&mut self, name: String, value: Value) {
570 self.0.insert(normalize_identifier(&name), value);
571 }
572
573 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
575 self.0.iter().map(|(a, b)| (a.as_str(), b))
576 }
577}
578
579impl FromIterator<(String, Value)> for Struct {
580 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
581 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
582 }
583}
584
585#[test]
586fn struct_field_name_normalization() {
587 let mut s = Struct::default();
588 s.set_field("foo_bar".into(), Value::Number(1.));
589 s.set_field("cross-axis-self-alignment".into(), Value::Number(2.));
591 assert_eq!(s.get_field("foo-bar"), Some(&Value::Number(1.)));
592 assert_eq!(s.get_field("foo_bar"), Some(&Value::Number(1.)));
593 assert_eq!(s.get_field("cross-axis-self-alignment"), Some(&Value::Number(2.)));
594 assert_eq!(s.get_field("cross_axis_self_alignment"), Some(&Value::Number(2.)));
595}
596
597#[deprecated(note = "Use slint_interpreter::Compiler instead")]
599pub struct ComponentCompiler {
600 config: i_slint_compiler::CompilerConfiguration,
601 diagnostics: Vec<Diagnostic>,
602}
603
604#[allow(deprecated)]
605impl Default for ComponentCompiler {
606 fn default() -> Self {
607 let mut config = i_slint_compiler::CompilerConfiguration::new(
608 i_slint_compiler::generator::OutputFormat::Interpreter,
609 );
610 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
611 Self { config, diagnostics: Vec::new() }
612 }
613}
614
615#[allow(deprecated)]
616impl ComponentCompiler {
617 pub fn new() -> Self {
619 Self::default()
620 }
621
622 #[doc(hidden)]
626 #[cfg(feature = "internal")]
627 pub fn compiler_configuration(
628 &mut self,
629 _: i_slint_core::InternalToken,
630 ) -> &mut i_slint_compiler::CompilerConfiguration {
631 &mut self.config
632 }
633
634 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
636 self.config.include_paths = include_paths;
637 }
638
639 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
641 &self.config.include_paths
642 }
643
644 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
646 self.config.library_paths = library_paths;
647 }
648
649 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
651 &self.config.library_paths
652 }
653
654 pub fn set_style(&mut self, style: String) {
666 self.config.style = Some(style);
667 }
668
669 pub fn style(&self) -> Option<&String> {
671 self.config.style.as_ref()
672 }
673
674 pub fn set_translation_domain(&mut self, domain: String) {
676 self.config.translation_domain = Some(domain);
677 }
678
679 pub fn set_file_loader(
687 &mut self,
688 file_loader_fallback: impl Fn(
689 &Path,
690 ) -> core::pin::Pin<
691 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
692 > + 'static,
693 ) {
694 #[expect(deprecated)]
695 let open_import_callback: i_slint_compiler::OpenImportCallback =
696 Rc::new(move |path| file_loader_fallback(&path.to_legacy_path()));
697 self.config.open_import_callback = Some(open_import_callback);
698 }
699
700 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
702 &self.diagnostics
703 }
704
705 pub async fn build_from_path<P: AsRef<Path>>(
724 &mut self,
725 path: P,
726 ) -> Option<ComponentDefinition> {
727 let path = path.as_ref();
728 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
729 Ok(s) => s,
730 Err(d) => {
731 self.diagnostics = vec![d];
732 return None;
733 }
734 };
735
736 let r = build_compilation_result(
737 source,
738 SourcePath::new(path),
739 self.config.clone(),
740 AnimationMode::Running,
741 )
742 .await;
743 self.diagnostics = r.diagnostics.into_iter().collect();
744 r.components.into_values().next()
745 }
746
747 pub async fn build_from_source(
764 &mut self,
765 source_code: String,
766 path: PathBuf,
767 ) -> Option<ComponentDefinition> {
768 let r = build_compilation_result(
769 source_code,
770 SourcePath::new(path),
771 self.config.clone(),
772 AnimationMode::Running,
773 )
774 .await;
775 self.diagnostics = r.diagnostics.into_iter().collect();
776 r.components.into_values().next()
777 }
778}
779
780pub struct Compiler {
783 config: i_slint_compiler::CompilerConfiguration,
784}
785
786impl Default for Compiler {
787 fn default() -> Self {
788 let config = i_slint_compiler::CompilerConfiguration::new(
789 i_slint_compiler::generator::OutputFormat::Interpreter,
790 );
791 Self { config }
792 }
793}
794
795impl Compiler {
796 pub fn new() -> Self {
798 Self::default()
799 }
800
801 #[doc(hidden)]
802 #[cfg(feature = "internal")]
803 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
804 self.config.embed_resources = embed_resources;
805 }
806
807 #[doc(hidden)]
811 #[cfg(feature = "internal")]
812 pub fn compiler_configuration(
813 &mut self,
814 _: i_slint_core::InternalToken,
815 ) -> &mut i_slint_compiler::CompilerConfiguration {
816 &mut self.config
817 }
818
819 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
821 self.config.include_paths = include_paths;
822 }
823
824 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
826 &self.config.include_paths
827 }
828
829 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
831 self.config.library_paths = library_paths;
832 }
833
834 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
836 &self.config.library_paths
837 }
838
839 pub fn set_style(&mut self, style: String) {
850 self.config.style = Some(style);
851 }
852
853 pub fn style(&self) -> Option<&String> {
855 self.config.style.as_ref()
856 }
857
858 pub fn set_translation_domain(&mut self, domain: String) {
860 self.config.translation_domain = Some(domain);
861 }
862
863 pub fn set_default_translation_context(
869 &mut self,
870 default_translation_context: DefaultTranslationContext,
871 ) {
872 self.config.default_translation_context = default_translation_context;
873 }
874
875 #[cfg(feature = "bundle-translations")]
882 pub fn set_bundled_translations_path(&mut self, path: PathBuf) {
883 self.config.bundled_translations_path = Some(path);
884 }
885
886 pub fn set_file_loader(
894 &mut self,
895 file_loader_fallback: impl Fn(
896 &Path,
897 ) -> core::pin::Pin<
898 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
899 > + 'static,
900 ) {
901 #[expect(deprecated)]
902 let open_import_callback: i_slint_compiler::OpenImportCallback =
903 Rc::new(move |path| file_loader_fallback(&path.to_legacy_path()));
904 self.config.open_import_callback = Some(open_import_callback);
905 }
906
907 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
926 let path = path.as_ref();
927 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
928 Ok(s) => s,
929 Err(d) => {
930 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
931 diagnostics.push_compiler_error(d);
932 return CompilationResult {
933 components: HashMap::new(),
934 diagnostics: diagnostics.into_iter().collect(),
935 #[cfg(feature = "internal")]
936 watch_paths: vec![SourcePath::new(path)],
937 #[cfg(feature = "internal")]
938 structs_and_enums: Vec::new(),
939 };
940 }
941 };
942
943 build_compilation_result(
944 source,
945 SourcePath::new(path),
946 self.config.clone(),
947 AnimationMode::Running,
948 )
949 .await
950 }
951
952 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
965 let path = SourcePath::new(path);
966 build_compilation_result(source_code, path, self.config.clone(), AnimationMode::Running)
967 .await
968 }
969
970 #[doc(hidden)]
974 #[cfg(any(feature = "internal", feature = "internal-highlight"))]
975 pub async fn build_from_source_path(
976 &self,
977 source_code: String,
978 path: SourcePath,
979 _: i_slint_core::InternalToken,
980 ) -> CompilationResult {
981 build_compilation_result(source_code, path, self.config.clone(), AnimationMode::Running)
982 .await
983 }
984
985 #[doc(hidden)]
987 #[cfg(feature = "internal")]
988 pub async fn build_static_from_source(
989 &self,
990 source_code: String,
991 path: SourcePath,
992 _: i_slint_core::InternalToken,
993 ) -> CompilationResult {
994 build_compilation_result(source_code, path, self.config.clone(), AnimationMode::Static)
995 .await
996 }
997}
998
999pub(crate) enum AnimationMode {
1000 #[cfg_attr(not(feature = "internal"), allow(dead_code))]
1003 Static,
1004 Running,
1005}
1006
1007async fn build_compilation_result(
1008 source_code: String,
1009 path: SourcePath,
1010 config: i_slint_compiler::CompilerConfiguration,
1011 animation_mode: AnimationMode,
1012) -> CompilationResult {
1013 let result =
1014 crate::component::build_from_source(source_code, path, config, animation_mode).await;
1015 let components = result
1016 .components
1017 .into_iter()
1018 .map(|(name, def)| (name, ComponentDefinition { inner: std::rc::Rc::new(def) }))
1019 .collect::<HashMap<String, ComponentDefinition>>();
1020 CompilationResult {
1021 components,
1022 diagnostics: result.diagnostics,
1023 #[cfg(feature = "internal")]
1024 watch_paths: result.watch_paths,
1025 #[cfg(feature = "internal")]
1026 structs_and_enums: result.structs_and_enums,
1027 }
1028}
1029
1030pub struct CompilationResultSend {
1053 compilation_unit: Option<i_slint_compiler::llr::CompilationUnit>,
1055 components: HashMap<String, i_slint_compiler::llr::PublicComponentIdx>,
1057 diagnostics: Vec<Diagnostic>,
1058 #[cfg(feature = "internal")]
1059 watch_paths: Vec<SourcePath>,
1060 #[cfg(feature = "internal")]
1061 structs_and_enums: Vec<LangType>,
1062}
1063
1064const _: () = {
1065 const fn assert_send<T: Send>() {}
1066 assert_send::<CompilationResultSend>();
1067};
1068
1069impl CompilationResultSend {
1070 pub fn has_errors(&self) -> bool {
1072 self.diagnostics.iter().any(|d| d.level() == DiagnosticLevel::Error)
1073 }
1074
1075 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1077 self.diagnostics.iter().cloned()
1078 }
1079
1080 #[cfg(feature = "display-diagnostics")]
1082 pub fn print_diagnostics(&self) {
1083 print_diagnostics(&self.diagnostics)
1084 }
1085}
1086
1087impl From<CompilationResultSend> for CompilationResult {
1088 fn from(sent: CompilationResultSend) -> Self {
1089 let CompilationResultSend {
1090 compilation_unit,
1091 components,
1092 diagnostics,
1093 #[cfg(feature = "internal")]
1094 watch_paths,
1095 #[cfg(feature = "internal")]
1096 structs_and_enums,
1097 } = sent;
1098 let compilation_unit = compilation_unit.map(std::rc::Rc::new);
1099 let components = components
1100 .into_iter()
1101 .filter_map(|(name, public_index)| {
1102 let inner = std::rc::Rc::new(crate::component::ComponentDefinitionInner {
1103 compilation_unit: compilation_unit.clone()?,
1104 public_index,
1105 type_loaders: Default::default(),
1106 });
1107 Some((name, ComponentDefinition { inner }))
1108 })
1109 .collect();
1110 Self {
1111 components,
1112 diagnostics,
1113 #[cfg(feature = "internal")]
1114 watch_paths,
1115 #[cfg(feature = "internal")]
1116 structs_and_enums,
1117 }
1118 }
1119}
1120
1121#[derive(Clone)]
1128pub struct CompilationResult {
1129 pub(crate) components: HashMap<String, ComponentDefinition>,
1130 pub(crate) diagnostics: Vec<Diagnostic>,
1131 #[cfg(feature = "internal")]
1132 pub(crate) watch_paths: Vec<SourcePath>,
1133 #[cfg(feature = "internal")]
1134 pub(crate) structs_and_enums: Vec<LangType>,
1135}
1136
1137impl core::fmt::Debug for CompilationResult {
1138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1139 f.debug_struct("CompilationResult")
1140 .field("components", &self.components.keys())
1141 .field("diagnostics", &self.diagnostics)
1142 .finish()
1143 }
1144}
1145
1146impl CompilationResult {
1147 pub fn has_errors(&self) -> bool {
1150 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1151 }
1152
1153 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1157 self.diagnostics.iter().cloned()
1158 }
1159
1160 #[cfg(feature = "display-diagnostics")]
1166 pub fn print_diagnostics(&self) {
1167 print_diagnostics(&self.diagnostics)
1168 }
1169
1170 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1172 self.components.values().cloned()
1173 }
1174
1175 pub fn into_send(self) -> CompilationResultSend {
1177 let Self {
1178 components,
1179 diagnostics,
1180 #[cfg(feature = "internal")]
1181 watch_paths,
1182 #[cfg(feature = "internal")]
1183 structs_and_enums,
1184 } = self;
1185
1186 let mut unit = None::<std::rc::Rc<i_slint_compiler::llr::CompilationUnit>>;
1188 let components = components
1189 .into_iter()
1190 .map(|(name, definition)| {
1191 let public_index = definition.inner.public_index;
1192 match &unit {
1193 Some(u) => {
1194 debug_assert!(std::rc::Rc::ptr_eq(u, &definition.inner.compilation_unit))
1195 }
1196 None => unit = Some(definition.inner.compilation_unit.clone()),
1197 }
1198 (name, public_index)
1199 })
1200 .collect();
1201 let compilation_unit = unit.map(std::rc::Rc::unwrap_or_clone);
1204
1205 CompilationResultSend {
1206 compilation_unit,
1207 components,
1208 diagnostics,
1209 #[cfg(feature = "internal")]
1210 watch_paths,
1211 #[cfg(feature = "internal")]
1212 structs_and_enums,
1213 }
1214 }
1215
1216 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1218 self.components.keys().map(|s| s.as_str())
1219 }
1220
1221 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1224 self.components.get(name).cloned()
1225 }
1226
1227 #[doc(hidden)]
1229 #[cfg(feature = "internal")]
1230 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[SourcePath] {
1231 &self.watch_paths
1232 }
1233
1234 #[doc(hidden)]
1236 #[cfg(feature = "internal")]
1237 pub fn structs_and_enums(
1238 &self,
1239 _: i_slint_core::InternalToken,
1240 ) -> impl Iterator<Item = &LangType> {
1241 self.structs_and_enums.iter()
1242 }
1243
1244 #[doc(hidden)]
1247 #[cfg(feature = "internal")]
1248 pub fn compilation_unit(
1249 &self,
1250 _: i_slint_core::InternalToken,
1251 ) -> Option<&i_slint_compiler::llr::CompilationUnit> {
1252 self.components.values().next().map(|d| &*d.inner.compilation_unit)
1253 }
1254}
1255
1256#[derive(Clone)]
1264pub struct ComponentDefinition {
1265 pub(crate) inner: std::rc::Rc<crate::component::ComponentDefinitionInner>,
1266}
1267
1268impl ComponentDefinition {
1269 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1271 let instance = self.create_with_options(Default::default())?;
1272 instance.finish_creation()?;
1273 Ok(instance)
1274 }
1275
1276 #[doc(hidden)]
1278 #[cfg(feature = "internal")]
1279 pub fn create_with_context(
1280 &self,
1281 context: i_slint_core::SlintContext,
1282 ) -> Result<ComponentInstance, PlatformError> {
1283 let instance = self.create_with_options(WindowOptions::WithContext(context))?;
1284 instance.finish_creation()?;
1285 Ok(instance)
1286 }
1287
1288 #[doc(hidden)]
1290 #[cfg(feature = "internal")]
1291 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1292 self.create_with_options(WindowOptions::Embed {
1293 parent_item_tree: ctx.parent_item_tree,
1294 parent_item_tree_index: ctx.parent_item_tree_index,
1295 })
1296 }
1297
1298 #[doc(hidden)]
1300 #[cfg(feature = "internal")]
1301 pub fn create_with_existing_window(
1302 &self,
1303 window: &Window,
1304 ) -> Result<ComponentInstance, PlatformError> {
1305 self.create_with_options(WindowOptions::UseExistingWindow(
1306 WindowInner::from_pub(window).window_adapter(),
1307 ))
1308 }
1309
1310 #[doc(hidden)]
1312 #[cfg(feature = "internal")]
1313 pub fn create_detached_with_existing_window(
1314 &self,
1315 window: &Window,
1316 _: i_slint_core::InternalToken,
1317 ) -> Result<ComponentInstance, PlatformError> {
1318 let adapter = WindowInner::from_pub(window).window_adapter();
1319 Ok(ComponentInstance { inner: self.inner.create_detached_with_existing_window(adapter) })
1320 }
1321
1322 pub(crate) fn create_with_options(
1324 &self,
1325 options: WindowOptions,
1326 ) -> Result<ComponentInstance, PlatformError> {
1327 let instance = match options {
1328 WindowOptions::CreateNewWindow => self
1329 .inner
1330 .create_with_context(i_slint_backend_selector::with_global_context(Clone::clone)?),
1331 WindowOptions::UseExistingWindow(adapter) => {
1332 self.inner.create_with_existing_window(adapter)
1333 }
1334 WindowOptions::Embed { parent_item_tree, parent_item_tree_index } => {
1335 self.inner.create_embedded(parent_item_tree, parent_item_tree_index)
1336 }
1337 WindowOptions::WithContext(context) => self.inner.create_with_context(context),
1338 };
1339 Ok(ComponentInstance { inner: instance })
1340 }
1341}
1342
1343#[allow(dead_code)]
1348#[derive(Default)]
1349pub(crate) enum WindowOptions {
1350 #[default]
1351 CreateNewWindow,
1352 UseExistingWindow(i_slint_core::window::WindowAdapterRc),
1353 Embed {
1354 parent_item_tree: i_slint_core::item_tree::ItemTreeWeak,
1355 parent_item_tree_index: u32,
1356 },
1357 WithContext(i_slint_core::SlintContext),
1358}
1359
1360impl ComponentDefinition {
1361 #[doc(hidden)]
1365 #[cfg(feature = "internal")]
1366 pub fn properties_and_callbacks(
1367 &self,
1368 ) -> impl Iterator<
1369 Item = (
1370 String,
1371 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1372 ),
1373 > + '_ {
1374 self.inner
1375 .properties_and_callbacks()
1376 .map(|(n, t, v)| (n.to_string(), (t, v)))
1377 .collect::<Vec<_>>()
1378 .into_iter()
1379 }
1380
1381 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1384 self.inner
1385 .properties()
1386 .map(|(n, t)| (n.to_string(), t.into()))
1387 .collect::<Vec<_>>()
1388 .into_iter()
1389 }
1390
1391 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1393 self.inner.callbacks().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1394 }
1395
1396 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1398 self.inner.functions().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1399 }
1400
1401 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1406 self.inner.globals().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1407 }
1408
1409 #[doc(hidden)]
1413 #[cfg(feature = "internal")]
1414 pub fn global_properties_and_callbacks(
1415 &self,
1416 global_name: &str,
1417 ) -> Option<
1418 impl Iterator<
1419 Item = (
1420 String,
1421 (
1422 i_slint_compiler::langtype::Type,
1423 i_slint_compiler::object_tree::PropertyVisibility,
1424 ),
1425 ),
1426 > + '_,
1427 > {
1428 Some(
1429 self.inner
1430 .global_properties_and_callbacks(global_name)?
1431 .map(|(n, t, v)| (n.to_string(), (t, v)))
1432 .collect::<Vec<_>>()
1433 .into_iter(),
1434 )
1435 }
1436
1437 pub fn global_properties(
1439 &self,
1440 global_name: &str,
1441 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1442 Some(
1443 self.inner
1444 .global_properties(global_name)?
1445 .map(|(n, t)| (n.to_string(), t.into()))
1446 .collect::<Vec<_>>()
1447 .into_iter(),
1448 )
1449 }
1450
1451 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1453 Some(
1454 self.inner
1455 .global_callbacks(global_name)?
1456 .map(|s| s.to_string())
1457 .collect::<Vec<_>>()
1458 .into_iter(),
1459 )
1460 }
1461
1462 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1464 Some(
1465 self.inner
1466 .global_functions(global_name)?
1467 .map(|s| s.to_string())
1468 .collect::<Vec<_>>()
1469 .into_iter(),
1470 )
1471 }
1472
1473 pub fn name(&self) -> &str {
1475 self.inner.name()
1476 }
1477
1478 #[doc(hidden)]
1482 #[cfg(feature = "internal")]
1483 pub fn is_window(&self) -> bool {
1484 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::Window
1485 }
1486
1487 #[cfg(feature = "internal")]
1489 #[doc(hidden)]
1490 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1491 self.inner
1492 .type_loaders
1493 .originals
1494 .get(self.inner.public_index)
1495 .expect("root_component() called on a definition built without compiler state")
1496 .clone()
1497 }
1498
1499 #[cfg(feature = "internal-highlight")]
1503 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1504 self.inner.type_loaders.type_loader.clone().expect(
1505 "TypeLoader was not retained for this ComponentDefinition (reconstructed from an instance)",
1506 )
1507 }
1508
1509 #[cfg(feature = "internal-highlight")]
1517 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1518 self.inner
1519 .type_loaders
1520 .raw_type_loader
1521 .as_ref()
1522 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1523 }
1524}
1525
1526#[cfg(feature = "display-diagnostics")]
1532pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1533 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1534 for d in diagnostics {
1535 build_diagnostics.push_compiler_error(d.clone())
1536 }
1537 build_diagnostics.print();
1538}
1539
1540#[repr(C)]
1548pub struct ComponentInstance {
1549 pub(crate) inner: crate::component::ComponentInstanceInner,
1550}
1551
1552impl ComponentInstance {
1553 pub fn definition(&self) -> ComponentDefinition {
1555 ComponentDefinition { inner: std::rc::Rc::new(self.inner.definition()) }
1556 }
1557
1558 fn finish_creation(&self) -> Result<(), PlatformError> {
1560 if !self.is_system_tray_rooted() {
1563 self.inner.window_adapter_ref()?;
1565 i_slint_core::window::WindowInner::from_pub(self.window()).ensure_tree_instantiated();
1568 }
1569 Ok(())
1570 }
1571
1572 #[doc(hidden)]
1574 #[cfg(feature = "internal")]
1575 pub fn as_item_tree(
1576 &self,
1577 _: i_slint_core::InternalToken,
1578 ) -> i_slint_core::item_tree::ItemTreeRc {
1579 vtable::VRc::into_dyn(self.inner.vrc().clone())
1580 }
1581
1582 fn is_system_tray_rooted(&self) -> bool {
1583 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::SystemTrayIcon
1584 }
1585
1586 fn set_tray_icon_visible(&self, visible: bool) {
1590 let item_rc = ItemRc::new(vtable::VRc::into_dyn(self.inner.vrc().clone()), 0);
1592 let tray = item_rc
1593 .downcast::<SystemTrayIcon>()
1594 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1595 tray.as_pin_ref().visible.set(visible);
1596 }
1597
1598 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1618 self.inner.get_property(name).ok_or(GetPropertyError::NoSuchProperty)
1619 }
1620
1621 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1623 self.inner.set_property(name, value)
1624 }
1625
1626 pub fn set_callback(
1661 &self,
1662 name: &str,
1663 callback: impl Fn(&[Value]) -> Value + 'static,
1664 ) -> Result<(), SetCallbackError> {
1665 self.inner.set_callback(name, callback).map_err(|()| SetCallbackError::NoSuchCallback)
1666 }
1667
1668 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1673 self.inner.invoke(name, args).ok_or(InvokeError::NoSuchCallable)
1674 }
1675
1676 pub fn get_global_property(
1701 &self,
1702 global: &str,
1703 property: &str,
1704 ) -> Result<Value, GetPropertyError> {
1705 self.inner.get_global_property(global, property).ok_or(GetPropertyError::NoSuchProperty)
1706 }
1707
1708 pub fn set_global_property(
1710 &self,
1711 global: &str,
1712 property: &str,
1713 value: Value,
1714 ) -> Result<(), SetPropertyError> {
1715 self.inner.set_global_property(global, property, value)
1716 }
1717
1718 pub fn set_global_callback(
1753 &self,
1754 global: &str,
1755 name: &str,
1756 callback: impl Fn(&[Value]) -> Value + 'static,
1757 ) -> Result<(), SetCallbackError> {
1758 self.inner
1759 .set_global_callback(global, name, callback)
1760 .map_err(|()| SetCallbackError::NoSuchCallback)
1761 }
1762
1763 pub fn invoke_global(
1768 &self,
1769 global: &str,
1770 callable_name: &str,
1771 args: &[Value],
1772 ) -> Result<Value, InvokeError> {
1773 self.inner.invoke_global(global, callable_name, args).ok_or(InvokeError::NoSuchCallable)
1774 }
1775
1776 #[cfg(feature = "internal-highlight")]
1780 pub fn component_positions(
1781 &self,
1782 path: &SourcePath,
1783 offset: u32,
1784 ) -> Vec<crate::highlight::HighlightedRect> {
1785 crate::highlight::component_positions(self.inner.vrc(), path, offset)
1786 }
1787
1788 #[cfg(feature = "internal-highlight")]
1792 pub fn element_candidates_at(
1793 &self,
1794 position: i_slint_core::lengths::LogicalPoint,
1795 ) -> Vec<crate::highlight::ElementCandidate> {
1796 crate::highlight::element_candidates_at(self.inner.vrc(), position)
1797 }
1798
1799 #[cfg(feature = "internal-highlight")]
1803 pub fn element_node_at_source_code_position(
1804 &self,
1805 path: &SourcePath,
1806 offset: u32,
1807 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1808 crate::highlight::element_node_at_source_code_position(self.inner.vrc(), path, offset)
1809 }
1810
1811 #[cfg(feature = "internal")]
1813 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1814 crate::debug_hook::set_debug_hook_callback(self.inner.vrc(), callback);
1815 }
1816}
1817
1818impl StrongHandle for ComponentInstance {
1819 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::instance::Instance>;
1820
1821 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1822 Some(Self { inner: crate::component::ComponentInstanceInner(inner.upgrade()?) })
1823 }
1824}
1825
1826impl ComponentHandle for ComponentInstance {
1827 fn as_weak(&self) -> Weak<Self>
1828 where
1829 Self: Sized,
1830 {
1831 Weak::new(vtable::VRc::downgrade(self.inner.vrc()))
1832 }
1833
1834 fn clone_strong(&self) -> Self {
1835 Self { inner: self.inner.clone() }
1836 }
1837
1838 fn show(&self) -> Result<(), PlatformError> {
1839 if self.is_system_tray_rooted() {
1840 self.set_tray_icon_visible(true);
1841 return Ok(());
1842 }
1843 let adapter = self.inner.window_adapter_ref()?;
1844 self.inner.0.attach_to_window();
1848 adapter.window().show()
1849 }
1850
1851 fn hide(&self) -> Result<(), PlatformError> {
1852 if self.is_system_tray_rooted() {
1853 self.set_tray_icon_visible(false);
1854 return Ok(());
1855 }
1856 self.inner.window_adapter_ref()?.window().hide()
1857 }
1858
1859 fn run(&self) -> Result<(), PlatformError> {
1860 self.show()?;
1861 run_event_loop()?;
1862 self.hide()
1863 }
1864
1865 fn window(&self) -> &Window {
1866 let adapter = self.inner.window_adapter_ref().unwrap();
1867 self.inner.0.attach_to_window();
1873 adapter.window()
1874 }
1875
1876 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1877 where
1878 Self: Sized,
1879 {
1880 unreachable!()
1881 }
1882}
1883
1884impl From<ComponentInstance>
1885 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>
1886{
1887 fn from(value: ComponentInstance) -> Self {
1888 value.inner.0
1889 }
1890}
1891
1892#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1894#[non_exhaustive]
1895pub enum GetPropertyError {
1896 #[display("no such property")]
1898 NoSuchProperty,
1899}
1900
1901#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1903#[non_exhaustive]
1904pub enum SetPropertyError {
1905 #[display("no such property")]
1907 NoSuchProperty,
1908 #[display("wrong type")]
1914 WrongType,
1915 #[display("access denied")]
1917 AccessDenied,
1918}
1919
1920#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1922#[non_exhaustive]
1923pub enum SetCallbackError {
1924 #[display("no such callback")]
1926 NoSuchCallback,
1927}
1928
1929#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1931#[non_exhaustive]
1932pub enum InvokeError {
1933 #[display("no such callback or function")]
1935 NoSuchCallable,
1936}
1937
1938pub fn run_event_loop() -> Result<(), PlatformError> {
1942 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1943}
1944
1945pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1949 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1950 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1951}
1952
1953#[test]
1954fn component_definition_properties() {
1955 i_slint_backend_testing::init_no_event_loop();
1956 let mut compiler = Compiler::default();
1957 compiler.set_style("fluent".into());
1958 let comp_def = spin_on::spin_on(
1959 compiler.build_from_source(
1960 r#"
1961 export component Dummy {
1962 in-out property <string> test;
1963 in-out property <int> underscores-and-dashes_preserved: 44;
1964 callback hello;
1965 }"#
1966 .into(),
1967 "".into(),
1968 ),
1969 )
1970 .component("Dummy")
1971 .unwrap();
1972
1973 let props = comp_def.properties().collect::<Vec<(_, _)>>();
1974
1975 assert_eq!(props.len(), 2);
1976 assert_eq!(props[0].0, "test");
1977 assert_eq!(props[0].1, ValueType::String);
1978 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
1979 assert_eq!(props[1].1, ValueType::Number);
1980
1981 let instance = comp_def.create().unwrap();
1982 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
1983 assert_eq!(
1984 instance.get_property("underscoresanddashespreserved"),
1985 Err(GetPropertyError::NoSuchProperty)
1986 );
1987 assert_eq!(
1988 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
1989 Ok(())
1990 );
1991 assert_eq!(
1992 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
1993 Err(SetPropertyError::NoSuchProperty)
1994 );
1995 assert_eq!(
1996 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
1997 Err(SetPropertyError::WrongType)
1998 );
1999 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
2000}
2001
2002#[test]
2003fn component_definition_properties2() {
2004 i_slint_backend_testing::init_no_event_loop();
2005 let mut compiler = Compiler::default();
2006 compiler.set_style("fluent".into());
2007 let comp_def = spin_on::spin_on(
2008 compiler.build_from_source(
2009 r#"
2010 export component Dummy {
2011 in-out property <string> sub-text <=> sub.text;
2012 sub := Text { property <int> private-not-exported; }
2013 out property <string> xreadonly: "the value";
2014 private property <string> xx: sub.text;
2015 callback hello;
2016 }"#
2017 .into(),
2018 "".into(),
2019 ),
2020 )
2021 .component("Dummy")
2022 .unwrap();
2023
2024 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2025
2026 assert_eq!(props.len(), 2);
2027 assert_eq!(props[0].0, "sub-text");
2028 assert_eq!(props[0].1, ValueType::String);
2029 assert_eq!(props[1].0, "xreadonly");
2030
2031 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
2032 assert_eq!(callbacks.len(), 1);
2033 assert_eq!(callbacks[0], "hello");
2034
2035 let instance = comp_def.create().unwrap();
2036 assert_eq!(
2037 instance.set_property("xreadonly", SharedString::from("XXX").into()),
2038 Err(SetPropertyError::AccessDenied)
2039 );
2040 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
2041 assert_eq!(
2042 instance.set_property("xx", SharedString::from("XXX").into()),
2043 Err(SetPropertyError::NoSuchProperty)
2044 );
2045 assert_eq!(
2046 instance.set_property("background", Value::default()),
2047 Err(SetPropertyError::NoSuchProperty)
2048 );
2049
2050 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
2051 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
2052}
2053
2054#[test]
2055fn globals() {
2056 i_slint_backend_testing::init_no_event_loop();
2057 let mut compiler = Compiler::default();
2058 compiler.set_style("fluent".into());
2059 let definition = spin_on::spin_on(
2060 compiler.build_from_source(
2061 r#"
2062 export global My-Super_Global {
2063 in-out property <int> the-property : 21;
2064 callback my-callback();
2065 callback int-callback() -> int;
2066 }
2067 export { My-Super_Global as AliasedGlobal }
2068 export component Dummy {
2069 callback alias <=> My-Super_Global.my-callback;
2070 }"#
2071 .into(),
2072 "".into(),
2073 ),
2074 )
2075 .component("Dummy")
2076 .unwrap();
2077
2078 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
2079
2080 assert!(definition.global_properties("not-there").is_none());
2081 {
2082 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
2083 let expected_callbacks = vec!["int-callback".to_string(), "my-callback".to_string()];
2084
2085 let assert_properties_and_callbacks = |global_name| {
2086 assert_eq!(
2087 definition
2088 .global_properties(global_name)
2089 .map(|props| props.collect::<Vec<_>>())
2090 .as_ref(),
2091 Some(&expected_properties)
2092 );
2093 assert_eq!(
2094 definition
2095 .global_callbacks(global_name)
2096 .map(|props| props.collect::<Vec<_>>())
2097 .as_ref(),
2098 Some(&expected_callbacks)
2099 );
2100 };
2101
2102 assert_properties_and_callbacks("My-Super-Global");
2103 assert_properties_and_callbacks("My_Super-Global");
2104 assert_properties_and_callbacks("AliasedGlobal");
2105 }
2106
2107 let instance = definition.create().unwrap();
2108 assert_eq!(
2109 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
2110 Ok(())
2111 );
2112 assert_eq!(
2113 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2114 Ok(())
2115 );
2116 assert_eq!(
2117 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2118 Err(SetPropertyError::NoSuchProperty)
2119 );
2120
2121 assert_eq!(
2122 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2123 Err(SetPropertyError::NoSuchProperty)
2124 );
2125 assert_eq!(
2126 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2127 Err(SetPropertyError::NoSuchProperty)
2128 );
2129 assert_eq!(
2130 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2131 Err(SetPropertyError::WrongType)
2132 );
2133 assert_eq!(
2134 instance.get_global_property("My-Super_Global", "yoyo"),
2135 Err(GetPropertyError::NoSuchProperty)
2136 );
2137 assert_eq!(
2138 instance.get_global_property("My-Super_Global", "the-property"),
2139 Ok(Value::Number(44.))
2140 );
2141
2142 assert_eq!(
2143 instance.set_property("the-property", Value::Void),
2144 Err(SetPropertyError::NoSuchProperty)
2145 );
2146 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2147
2148 assert_eq!(
2149 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2150 Err(SetCallbackError::NoSuchCallback)
2151 );
2152 assert_eq!(
2153 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2154 Err(SetCallbackError::NoSuchCallback)
2155 );
2156 assert_eq!(
2157 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2158 Err(SetCallbackError::NoSuchCallback)
2159 );
2160
2161 assert_eq!(
2162 instance.invoke_global("DontExist", "the-property", &[]),
2163 Err(InvokeError::NoSuchCallable)
2164 );
2165 assert_eq!(
2166 instance.invoke_global("My_Super_Global", "the-property", &[]),
2167 Err(InvokeError::NoSuchCallable)
2168 );
2169 assert_eq!(
2170 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2171 Err(InvokeError::NoSuchCallable)
2172 );
2173
2174 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2176
2177 assert_eq!(
2179 instance.invoke_global("My_Super_Global", "int-callback", &[]),
2180 Ok(Value::Number(0.))
2181 );
2182}
2183
2184#[test]
2185fn call_functions() {
2186 i_slint_backend_testing::init_no_event_loop();
2187 let mut compiler = Compiler::default();
2188 compiler.set_style("fluent".into());
2189 let definition = spin_on::spin_on(
2190 compiler.build_from_source(
2191 r#"
2192 export global Gl {
2193 out property<string> q;
2194 public function foo-bar(a-a: string, b-b:int) -> string {
2195 q = a-a;
2196 return a-a + b-b;
2197 }
2198 }
2199 export component Test {
2200 out property<int> p;
2201 public function foo-bar(a: int, b:int) -> int {
2202 p = a;
2203 return a + b;
2204 }
2205 }"#
2206 .into(),
2207 "".into(),
2208 ),
2209 )
2210 .component("Test")
2211 .unwrap();
2212
2213 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2214 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2215
2216 let instance = definition.create().unwrap();
2217
2218 assert_eq!(
2219 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2220 Ok(Value::Number(7.))
2221 );
2222 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2223 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2224
2225 assert_eq!(
2226 instance.invoke_global(
2227 "Gl",
2228 "foo_bar",
2229 &[Value::String("Hello".into()), Value::Number(10.)]
2230 ),
2231 Ok(Value::String("Hello10".into()))
2232 );
2233 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2234}
2235
2236#[test]
2237fn component_definition_struct_properties() {
2238 i_slint_backend_testing::init_no_event_loop();
2239 let mut compiler = Compiler::default();
2240 compiler.set_style("fluent".into());
2241 let comp_def = spin_on::spin_on(
2242 compiler.build_from_source(
2243 r#"
2244 export struct Settings {
2245 string_value: string,
2246 }
2247 export component Dummy {
2248 in-out property <Settings> test;
2249 }"#
2250 .into(),
2251 "".into(),
2252 ),
2253 )
2254 .component("Dummy")
2255 .unwrap();
2256
2257 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2258
2259 assert_eq!(props.len(), 1);
2260 assert_eq!(props[0].0, "test");
2261 assert_eq!(props[0].1, ValueType::Struct);
2262
2263 let instance = comp_def.create().unwrap();
2264
2265 let valid_struct: Struct =
2266 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2267
2268 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2269 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2270
2271 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2272
2273 let mut invalid_struct = valid_struct.clone();
2274 invalid_struct.set_field("other".into(), Value::Number(44.));
2275 assert_eq!(
2276 instance.set_property("test", Value::Struct(invalid_struct)),
2277 Err(SetPropertyError::WrongType)
2278 );
2279 let mut invalid_struct = valid_struct;
2280 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2281 assert_eq!(
2282 instance.set_property("test", Value::Struct(invalid_struct)),
2283 Err(SetPropertyError::WrongType)
2284 );
2285}
2286
2287#[test]
2288fn component_definition_model_properties() {
2289 use i_slint_core::model::*;
2290 i_slint_backend_testing::init_no_event_loop();
2291 let mut compiler = Compiler::default();
2292 compiler.set_style("fluent".into());
2293 let comp_def = spin_on::spin_on(compiler.build_from_source(
2294 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2295 "".into(),
2296 ))
2297 .component("Dummy")
2298 .unwrap();
2299
2300 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2301 assert_eq!(props.len(), 1);
2302 assert_eq!(props[0].0, "prop");
2303 assert_eq!(props[0].1, ValueType::Model);
2304
2305 let instance = comp_def.create().unwrap();
2306
2307 let int_model =
2308 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2309 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2310 let model_with_string = Value::Model(VecModel::from_slice(&[
2311 Value::Number(1000.),
2312 Value::String("foo".into()),
2313 Value::Number(1111.),
2314 ]));
2315
2316 #[track_caller]
2317 fn check_model(val: Value, r: &[f64]) {
2318 if let Value::Model(m) = val {
2319 assert_eq!(r.len(), m.row_count());
2320 for (i, v) in r.iter().enumerate() {
2321 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2322 }
2323 } else {
2324 panic!("{val:?} not a model");
2325 }
2326 }
2327
2328 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2329 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2330
2331 instance.set_property("prop", int_model).unwrap();
2332 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2333
2334 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2335 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2336 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2337 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2338
2339 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2340 check_model(instance.get_property("prop").unwrap(), &[]);
2341}
2342
2343#[test]
2344fn lang_type_to_value_type() {
2345 use i_slint_compiler::langtype::Struct as LangStruct;
2346 use std::collections::BTreeMap;
2347
2348 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2349 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2350 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2351 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2352 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2353 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2354 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2355 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2356 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2357 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2358 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2359 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2360 assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2361 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2362 assert_eq!(
2363 ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2364 BTreeMap::default(),
2365 i_slint_compiler::langtype::StructName::None
2366 )))),
2367 ValueType::Struct
2368 );
2369 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2370}
2371
2372#[test]
2373fn test_multi_components() {
2374 i_slint_backend_testing::init_no_event_loop();
2375 let result = spin_on::spin_on(
2376 Compiler::default().build_from_source(
2377 r#"
2378 export struct Settings {
2379 string_value: string,
2380 }
2381 export global ExpGlo { in-out property <int> test: 42; }
2382 component Common {
2383 in-out property <Settings> settings: { string_value: "Hello", };
2384 }
2385 export component Xyz inherits Window {
2386 in-out property <int> aaa: 8;
2387 }
2388 export component Foo {
2389
2390 in-out property <int> test: 42;
2391 c := Common {}
2392 }
2393 export component Bar inherits Window {
2394 in-out property <int> blah: 78;
2395 c := Common {}
2396 }
2397 "#
2398 .into(),
2399 PathBuf::from("hello.slint"),
2400 ),
2401 );
2402
2403 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2404 let mut components = result.component_names().collect::<Vec<_>>();
2405 components.sort();
2406 assert_eq!(components, vec!["Bar", "Xyz"]);
2407 let diag = result.diagnostics().collect::<Vec<_>>();
2408 assert_eq!(diag.len(), 1);
2409 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2410 assert_eq!(
2411 diag[0].message(),
2412 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2413 );
2414
2415 let comp1 = result.component("Xyz").unwrap();
2416 assert_eq!(comp1.name(), "Xyz");
2417 let instance1a = comp1.create().unwrap();
2418 let comp2 = result.component("Bar").unwrap();
2419 let instance2 = comp2.create().unwrap();
2420 let instance1b = comp1.create().unwrap();
2421
2422 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2424 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2425 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2426 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2427 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2428
2429 assert!(result.component("Settings").is_none());
2430 assert!(result.component("Foo").is_none());
2431 assert!(result.component("Common").is_none());
2432 assert!(result.component("ExpGlo").is_none());
2433 assert!(result.component("xyz").is_none());
2434}
2435
2436#[cfg(all(test, feature = "internal-highlight"))]
2437fn compile(code: &str) -> (ComponentInstance, SourcePath) {
2438 i_slint_backend_testing::init_no_event_loop();
2439 let mut compiler = Compiler::default();
2440 compiler.set_style("fluent".into());
2441 let path = SourcePath::new("/tmp/test.slint");
2442
2443 let compile_result = spin_on::spin_on(compiler.build_from_source_path(
2444 code.to_string(),
2445 path.clone(),
2446 i_slint_core::InternalToken,
2447 ));
2448
2449 for d in &compile_result.diagnostics {
2450 eprintln!("{d}");
2451 }
2452
2453 assert!(!compile_result.has_errors());
2454
2455 let definition = compile_result.components().next().unwrap();
2456 let instance = definition.create().unwrap();
2457
2458 (instance, path)
2459}
2460
2461#[cfg(feature = "internal-highlight")]
2462#[test]
2463fn test_element_node_at_source_code_position() {
2464 let code = r#"
2465component Bar1 {}
2466
2467component Foo1 {
2468}
2469
2470export component Foo2 inherits Window {
2471 Bar1 {}
2472 Foo1 {}
2473}"#;
2474
2475 let (handle, path) = compile(code);
2476
2477 for i in 0..code.len() as u32 {
2478 let elements = handle.element_node_at_source_code_position(&path, i);
2479 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2480 match i {
2481 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()),
2487 }
2488 }
2489}
2490
2491#[cfg(feature = "internal-highlight")]
2495#[test]
2496fn test_component_positions_instances_and_repeaters() {
2497 use i_slint_core::graphics::euclid;
2498 let code = r#"
2499component MyBox inherits Rectangle {
2500 width: 50px;
2501 height: 50px;
2502}
2503
2504export component Foo3 inherits Window {
2505 width: 400px;
2506 height: 400px;
2507 b1 := MyBox { x: 0px; y: 0px; }
2508 b2 := MyBox { x: 200px; y: 200px; }
2509 for xo in [0, 1, 2]: Rectangle {
2510 x: xo * 10px;
2511 y: 300px;
2512 width: 10px;
2513 height: 10px;
2514 }
2515}"#;
2516
2517 let (handle, path) = compile(code);
2518
2519 let positions_at =
2520 |pattern: &str| handle.component_positions(&path, code.find(pattern).unwrap() as u32);
2521
2522 let b1_rects = positions_at("MyBox { x: 0px");
2524 assert_eq!(b1_rects.len(), 1, "{b1_rects:?}");
2525 assert_eq!(b1_rects[0].rect.origin, euclid::point2(0., 0.));
2526
2527 let b2_rects = positions_at("MyBox { x: 200px");
2528 assert_eq!(b2_rects.len(), 1, "{b2_rects:?}");
2529 assert_eq!(b2_rects[0].rect.origin, euclid::point2(200., 200.));
2530
2531 let def_rects = positions_at("Rectangle {\n width: 50px");
2533 assert_eq!(def_rects.len(), 2, "{def_rects:?}");
2534
2535 let mut row_rects = positions_at("Rectangle {\n x: xo");
2537 row_rects.sort_by(|a, b| a.rect.origin.x.total_cmp(&b.rect.origin.x));
2538 assert_eq!(row_rects.len(), 3, "{row_rects:?}");
2539 for (i, r) in row_rects.iter().enumerate() {
2540 assert_eq!(r.rect.origin, euclid::point2(i as f32 * 10., 300.));
2541 assert_eq!(r.rect.size, euclid::size2(10., 10.));
2542 }
2543
2544 let offset = code.find("Rectangle {\n x: xo").unwrap() as u32;
2547 assert_eq!(handle.component_positions(&path, offset).len(), 3);
2548 assert!(handle.component_positions(&path, code.len() as u32 - 1).is_empty());
2549}
2550
2551#[cfg(feature = "internal-highlight")]
2552#[test]
2553fn component_positions_survive_compilation_result_round_trip() {
2554 use i_slint_core::graphics::euclid;
2555
2556 i_slint_backend_testing::init_no_event_loop();
2557 let code = r#"
2558component Base inherits Rectangle {
2559 width: 50px;
2560 height: 40px;
2561}
2562
2563component Derived inherits Base { }
2564
2565export component App inherits Window {
2566 width: 400px;
2567 height: 300px;
2568 in property <bool> show-conditional: true;
2569 first := Derived { x: 10px; y: 20px; }
2570 second := Derived { x: 200px; y: 100px; }
2571 if root.show-conditional: conditional := Rectangle {
2572 x: 100px;
2573 y: 200px;
2574 width: 20px;
2575 height: 30px;
2576 }
2577 optimized := Rectangle {
2578 x: 300px;
2579 y: 10px;
2580 width: 30px;
2581 height: 20px;
2582 background: red;
2583 redundant := Rectangle { }
2584 }
2585 for column in [0, 1]: Derived {
2586 x: column * 60px;
2587 y: 250px;
2588 }
2589 for column in [0, 1]: Derived {
2590 x: 150px + column * 60px;
2591 y: 250px;
2592 }
2593}
2594"#;
2595 let path = PathBuf::from("/virtual/round-trip.slint");
2596 let result = spin_on::spin_on(Compiler::default().build_from_source(code.into(), path.clone()));
2597 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
2598 let result = CompilationResult::from(result.into_send());
2599 let instance = result.component("App").unwrap().create().unwrap();
2600
2601 let positions_at = |pattern: &str, inside_pattern: usize| {
2602 let offset = code.find(pattern).unwrap() + inside_pattern;
2603 instance.component_positions(&SourcePath::new(&path), offset as u32)
2604 };
2605
2606 let first = positions_at("Derived { x: 10px", 2);
2607 assert_eq!(first.len(), 1, "{first:?}");
2608 assert_eq!(first[0].rect.origin, euclid::point2(10., 20.));
2609 let second = positions_at("Derived { x: 200px", 2);
2610 assert_eq!(second.len(), 1, "{second:?}");
2611 assert_eq!(second[0].rect.origin, euclid::point2(200., 100.));
2612
2613 let definition = positions_at("Rectangle {\n width: 50px", 3);
2614 assert_eq!(definition.len(), 6, "{definition:?}");
2615
2616 let conditional_offset = code.find("Rectangle {\n x: 100px").unwrap() as u32 + 4;
2617 let conditional = instance.component_positions(&SourcePath::new(&path), conditional_offset);
2618 assert_eq!(conditional.len(), 1, "{conditional:?}");
2619 assert_eq!(conditional[0].rect.origin, euclid::point2(100., 200.));
2620
2621 let optimized = positions_at("Rectangle {\n x: 300px", 3);
2622 let redundant = positions_at("Rectangle { }", 3);
2623 assert_eq!(optimized.len(), 1, "{optimized:?}");
2624 assert_eq!(redundant.len(), 1, "{redundant:?}");
2625 assert_eq!(redundant[0].rect, optimized[0].rect);
2626
2627 let assert_repeated_positions = |mut positions: Vec<crate::highlight::HighlightedRect>,
2628 expected_x_positions| {
2629 positions.sort_by(|left, right| left.rect.origin.x.total_cmp(&right.rect.origin.x));
2630 assert_eq!(positions.len(), 2, "{positions:?}");
2631 for (geometry, expected_x) in positions.iter().zip(expected_x_positions) {
2632 assert_eq!(geometry.rect.origin, euclid::point2(expected_x, 250.));
2633 }
2634 };
2635 for (pattern, expected_x_positions) in
2636 [("Derived {\n x: column", [0., 60.]), ("Derived {\n x: 150px", [150., 210.])]
2637 {
2638 assert_repeated_positions(positions_at(pattern, 2), expected_x_positions);
2639 }
2640}
2641
2642#[cfg(feature = "internal-highlight")]
2643#[test]
2644fn component_positions_resolve_imported_sources_after_round_trip() {
2645 use i_slint_core::graphics::euclid;
2646
2647 i_slint_backend_testing::init_no_event_loop();
2648 let imported_code = r#"
2649export component Imported inherits Rectangle {
2650 width: 40px;
2651 height: 30px;
2652}
2653"#;
2654 let main_code = r#"
2655import { Imported } from "lib.slint";
2656
2657export component App inherits Window {
2658 width: 200px;
2659 height: 200px;
2660 Imported { x: 25px; y: 35px; }
2661}
2662"#;
2663 let main_path = PathBuf::from("/virtual/main.slint");
2664 let imported_path = PathBuf::from("/virtual/lib.slint");
2665 let mut compiler = Compiler::default();
2666 compiler.set_file_loader({
2667 let imported_path = imported_path.clone();
2668 move |path| {
2669 let source = (path == imported_path).then(|| Ok(imported_code.to_owned()));
2670 Box::pin(std::future::ready(source))
2671 }
2672 });
2673 let result = spin_on::spin_on(compiler.build_from_source(main_code.into(), main_path.clone()));
2674 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
2675 let result = CompilationResult::from(result.into_send());
2676 let instance = result.component("App").unwrap().create().unwrap();
2677
2678 for (path, code, pattern) in [
2679 (&main_path, main_code, "Imported { x: 25px"),
2680 (&imported_path, imported_code, "Rectangle"),
2681 ] {
2682 let offset = code.find(pattern).unwrap() as u32;
2683 let positions = instance.component_positions(&SourcePath::new(path), offset);
2684 assert_eq!(positions.len(), 1, "{positions:?}");
2685 assert_eq!(positions[0].rect.origin, euclid::point2(25., 35.));
2686 assert_eq!(positions[0].rect.size, euclid::size2(40., 30.));
2687 }
2688}
2689
2690#[cfg(feature = "internal-highlight")]
2691#[test]
2692fn inlined_repeated_source_resolves_each_repeater_once() {
2693 use i_slint_compiler::diagnostics::BuildDiagnostics;
2694 use i_slint_compiler::generator::OutputFormat;
2695 use i_slint_core::graphics::euclid;
2696
2697 i_slint_backend_testing::init_no_event_loop();
2698 let code = r#"
2699component RepeatedBox inherits Rectangle {
2700 width: 60px;
2701 height: 20px;
2702 for value in [0, 1]: Rectangle {
2703 x: value * 20px;
2704 y: 0px;
2705 width: 10px;
2706 height: 10px;
2707 }
2708}
2709
2710export component App inherits Window {
2711 width: 200px;
2712 height: 100px;
2713 first := RepeatedBox { x: 10px; y: 20px; }
2714 second := RepeatedBox { x: 100px; y: 20px; }
2715}
2716"#;
2717 let path = SourcePath::new("/virtual/inlined-repeaters.slint");
2718 let mut diagnostics = BuildDiagnostics::default();
2719 let syntax_node =
2720 i_slint_compiler::parser::parse(code.into(), Some(path.clone()), &mut diagnostics);
2721 let mut compiler_configuration =
2722 i_slint_compiler::CompilerConfiguration::new(OutputFormat::Interpreter);
2723 compiler_configuration.debug_info = true;
2724 compiler_configuration.inline_all_elements = true;
2725 let (document, diagnostics, _) = spin_on::spin_on(i_slint_compiler::compile_syntax_node(
2726 syntax_node,
2727 diagnostics,
2728 compiler_configuration.clone(),
2729 ));
2730 assert!(!diagnostics.has_errors(), "{:?}", diagnostics.to_string_vec());
2731 let definition = crate::component::build_from_document(
2732 &document,
2733 &compiler_configuration,
2734 Default::default(),
2735 AnimationMode::Running,
2736 )
2737 .into_iter()
2738 .next()
2739 .expect("component definition");
2740 let definition = ComponentDefinition { inner: std::rc::Rc::new(definition) };
2741
2742 let repeated_offset = code.find("Rectangle {\n x: value").unwrap();
2743 let matching_repeated_elements = definition
2744 .inner
2745 .compilation_unit
2746 .sub_components
2747 .iter()
2748 .flat_map(|sub_component| sub_component.debug_info.iter())
2749 .flat_map(|debug_info| debug_info.repeated_elements.iter())
2750 .filter(|source_location| {
2751 source_location
2752 .source_file
2753 .as_ref()
2754 .is_some_and(|source_file| source_file.path() == &path)
2755 && source_location.span.offset == repeated_offset
2756 })
2757 .count();
2758 assert_eq!(matching_repeated_elements, 2);
2759
2760 let instance = definition.create().unwrap();
2761 let mut positions = instance.component_positions(&path, repeated_offset as u32 + 3);
2762 positions.sort_by(|left, right| left.rect.origin.x.total_cmp(&right.rect.origin.x));
2763 assert_eq!(positions.len(), 4, "{positions:?}");
2764 for (geometry, expected_x) in positions.iter().zip([10., 30., 100., 120.]) {
2765 assert_eq!(geometry.rect.origin, euclid::point2(expected_x, 20.));
2766 }
2767}