1use crate::prelude::*;
6#[cfg(test)]
7use alloc::sync::Arc;
8use core::future::Future;
9use core::time::Duration;
10use i_slint_compiler::langtype::Type as LangType;
11#[cfg(any(feature = "std", feature = "internal"))]
12use i_slint_compiler::source_path::SourcePath;
13use i_slint_core::Coord;
14use i_slint_core::component_factory::ComponentFactory;
15#[cfg(feature = "internal")]
16use i_slint_core::component_factory::FactoryContext;
17use i_slint_core::graphics::PathData;
18use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
19use i_slint_core::items::*;
20use i_slint_core::model::{Model, ModelExt, ModelRc};
21use i_slint_core::styled_text::StyledText;
22#[cfg(feature = "internal")]
23use i_slint_core::window::WindowInner;
24#[cfg(feature = "std")]
25use std::path::{Path, PathBuf};
26
27#[cfg(feature = "std")]
28#[doc(inline)]
29pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
30
31pub use i_slint_backend_selector::api::*;
32pub use i_slint_core::api::*;
33
34#[cfg(feature = "std")]
37pub use i_slint_compiler::DefaultTranslationContext;
38
39#[doc(hidden)]
40#[cfg(all(feature = "internal", feature = "internal-mcu-interpreter"))]
41pub use crate::static_resources::LoadedResource;
42
43#[derive(Debug, Copy, Clone, PartialEq)]
46#[repr(i8)]
47#[non_exhaustive]
48pub enum ValueType {
49 Void,
51 Number,
53 String,
55 Bool,
57 Model,
59 Struct,
61 Brush,
63 Image,
65 #[doc(hidden)]
67 Other = -1,
68}
69
70impl From<LangType> for ValueType {
71 fn from(ty: LangType) -> Self {
72 match ty {
73 LangType::Float32
74 | LangType::Int32
75 | LangType::Duration
76 | LangType::Angle
77 | LangType::PhysicalLength
78 | LangType::LogicalLength
79 | LangType::Percent
80 | LangType::UnitProduct(_) => Self::Number,
81 LangType::String => Self::String,
82 LangType::Color => Self::Brush,
83 LangType::Brush => Self::Brush,
84 LangType::Array(_) => Self::Model,
85 LangType::Bool => Self::Bool,
86 LangType::Struct { .. } => Self::Struct,
87 LangType::Void => Self::Void,
88 LangType::Image => Self::Image,
89 _ => Self::Other,
90 }
91 }
92}
93
94#[derive(Clone, Default)]
106#[non_exhaustive]
107#[repr(u8)]
108pub enum Value {
109 #[default]
112 Void = 0,
113 Number(f64) = 1,
115 String(SharedString) = 2,
117 Bool(bool) = 3,
119 Image(Image) = 4,
121 Model(ModelRc<Value>) = 5,
123 Struct(Struct) = 6,
125 Brush(Brush) = 7,
127 #[doc(hidden)]
128 PathData(PathData) = 8,
130 #[doc(hidden)]
131 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
133 #[doc(hidden)]
134 EnumerationValue(String, String) = 10,
137 #[doc(hidden)]
138 ArrayOfCoord(SharedVector<Coord>) = 11,
139 #[doc(hidden)]
140 ComponentFactory(ComponentFactory) = 12,
142 #[doc(hidden)] StyledText(StyledText) = 13,
145 #[doc(hidden)]
146 ArrayOfU16(SharedVector<u16>) = 14,
147 Keys(Keys) = 15,
149 DataTransfer(DataTransfer) = 16,
151 #[doc(hidden)]
152 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
154}
155
156impl Value {
157 pub fn value_type(&self) -> ValueType {
159 match self {
160 Value::Void => ValueType::Void,
161 Value::Number(_) => ValueType::Number,
162 Value::String(_) => ValueType::String,
163 Value::Bool(_) => ValueType::Bool,
164 Value::Model(_) => ValueType::Model,
165 Value::Struct(_) => ValueType::Struct,
166 Value::Brush(_) => ValueType::Brush,
167 Value::Image(_) => ValueType::Image,
168 _ => ValueType::Other,
169 }
170 }
171}
172
173impl i_slint_core::rtti::ValueType for Value {}
174
175impl PartialEq for Value {
176 fn eq(&self, other: &Self) -> bool {
177 match self {
178 Value::Void => matches!(other, Value::Void),
179 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
180 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
181 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
182 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
183 Value::Model(lhs) => {
184 if let Value::Model(rhs) = other {
185 lhs == rhs
186 } else {
187 false
188 }
189 }
190 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
191 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
192 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
193 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
194 Value::EnumerationValue(lhs_name, lhs_value) => {
195 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
196 }
197 Value::ArrayOfCoord(lhs) => matches!(other, Value::ArrayOfCoord(rhs) if lhs == rhs),
198 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
199 Value::ComponentFactory(lhs) => {
200 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
201 }
202 Value::StyledText(lhs) => {
203 matches!(other, Value::StyledText(rhs) if lhs == rhs)
204 }
205 Value::Keys(lhs) => {
206 matches!(other, Value::Keys(rhs) if lhs == rhs)
207 }
208 Value::DataTransfer(lhs) => {
209 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
210 }
211 Value::MouseCursorInner(lhs) => {
212 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
213 }
214 }
215 }
216}
217
218impl core::fmt::Debug for Value {
219 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
220 match self {
221 Value::Void => write!(f, "Value::Void"),
222 Value::Number(n) => write!(f, "Value::Number({n:?})"),
223 Value::String(s) => write!(f, "Value::String({s:?})"),
224 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
225 Value::Image(i) => write!(f, "Value::Image({i:?})"),
226 Value::Model(m) => {
227 write!(f, "Value::Model(")?;
228 f.debug_list().entries(m.iter()).finish()?;
229 write!(f, "])")
230 }
231 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
232 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
233 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
234 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
235 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
236 Value::ArrayOfCoord(v) => write!(f, "Value::ArrayOfCoord({v:?})"),
237 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
238 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
239 Value::ArrayOfU16(data) => {
240 write!(f, "Value::ArrayOfU16({data:?})")
241 }
242 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
243 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
244 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
245 }
246 }
247}
248
249macro_rules! declare_value_conversion {
258 ( $value:ident => [$($ty:ty),*] ) => {
259 $(
260 impl From<$ty> for Value {
261 fn from(v: $ty) -> Self {
262 Value::$value(v as _)
263 }
264 }
265 impl TryFrom<Value> for $ty {
266 type Error = Value;
267 fn try_from(v: Value) -> Result<$ty, Self::Error> {
268 match v {
269 Value::$value(x) => Ok(x as _),
270 _ => Err(v)
271 }
272 }
273 }
274 )*
275 };
276}
277declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
278declare_value_conversion!(String => [SharedString] );
279declare_value_conversion!(Bool => [bool] );
280declare_value_conversion!(Image => [Image] );
281declare_value_conversion!(Struct => [Struct] );
282declare_value_conversion!(Brush => [Brush] );
283declare_value_conversion!(PathData => [PathData]);
284declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
285declare_value_conversion!(ArrayOfCoord => [SharedVector<Coord>] );
286declare_value_conversion!(ComponentFactory => [ComponentFactory] );
287declare_value_conversion!(StyledText => [StyledText] );
288declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
289declare_value_conversion!(Keys => [Keys]);
290declare_value_conversion!(DataTransfer => [DataTransfer]);
291declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
292
293macro_rules! declare_value_struct_conversion {
295 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
296 impl From<$name> for Value {
297 fn from($name { $($field),* , .. }: $name) -> Self {
298 let mut struct_ = Struct::default();
299 $(struct_.set_field(stringify!($field).into(), $field.into());)*
300 Value::Struct(struct_)
301 }
302 }
303 impl TryFrom<Value> for $name {
304 type Error = ();
305 fn try_from(v: Value) -> Result<$name, Self::Error> {
306 #[allow(clippy::field_reassign_with_default)]
307 match v {
308 Value::Struct(x) => {
309 type Ty = $name;
310 #[allow(unused)]
311 let mut res: Ty = Ty::default();
312 $(let mut res: Ty = $extra;)?
313 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
314 Ok(res)
315 }
316 _ => Err(()),
317 }
318 }
319 }
320 };
321 ($(
322 $(#[$struct_attr:meta])*
323 $vis:vis struct $Name:ident {
324 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
325 }
326 )*) => {
327 $(
328 impl From<$Name> for Value {
329 fn from(item: $Name) -> Self {
330 let mut struct_ = Struct::default();
331 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
332 Value::Struct(struct_)
333 }
334 }
335 impl TryFrom<Value> for $Name {
336 type Error = ();
337 fn try_from(v: Value) -> Result<$Name, Self::Error> {
338 #[allow(clippy::field_reassign_with_default)]
339 match v {
340 Value::Struct(x) => {
341 type Ty = $Name;
342 #[allow(unused)]
343 let mut res: Ty = Ty::default();
344 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
347 Ok(res)
348 }
349 _ => Err(()),
350 }
351 }
352 }
353 )*
354 };
355}
356
357declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
358declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
359declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
360declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
361declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
362
363i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
364
365macro_rules! declare_value_enum_conversion {
370 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
371 impl From<i_slint_core::items::$Name> for Value {
372 fn from(v: i_slint_core::items::$Name) -> Self {
373 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
374 }
375 }
376 impl TryFrom<Value> for i_slint_core::items::$Name {
377 type Error = ();
378 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
379 use core::str::FromStr;
380 match v {
381 Value::EnumerationValue(enumeration, value) => {
382 if enumeration != stringify!($Name) {
383 return Err(());
384 }
385 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
386 }
387 _ => Err(()),
388 }
389 }
390 }
391 )*};
392}
393
394i_slint_common::for_each_enums!(declare_value_enum_conversion);
395
396impl From<i_slint_core::animations::Instant> for Value {
397 fn from(value: i_slint_core::animations::Instant) -> Self {
398 Value::Number(value.as_millis() as f64)
399 }
400}
401impl TryFrom<Value> for i_slint_core::animations::Instant {
402 type Error = ();
403 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
404 match v {
405 Value::Number(x) => Ok(Duration::from_millis(x as u64).into()),
406 _ => Err(()),
407 }
408 }
409}
410
411impl From<()> for Value {
412 #[inline]
413 fn from(_: ()) -> Self {
414 Value::Void
415 }
416}
417impl TryFrom<Value> for () {
418 type Error = ();
419 #[inline]
420 fn try_from(_: Value) -> Result<(), Self::Error> {
421 Ok(())
422 }
423}
424
425impl From<Color> for Value {
426 #[inline]
427 fn from(c: Color) -> Self {
428 Value::Brush(Brush::SolidColor(c))
429 }
430}
431impl TryFrom<Value> for Color {
432 type Error = Value;
433 #[inline]
434 fn try_from(v: Value) -> Result<Color, Self::Error> {
435 match v {
436 Value::Brush(Brush::SolidColor(c)) => Ok(c),
437 _ => Err(v),
438 }
439 }
440}
441
442impl From<i_slint_core::lengths::LogicalLength> for Value {
443 #[inline]
444 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
445 Value::Number(l.get() as _)
446 }
447}
448impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
449 type Error = Value;
450 #[inline]
451 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
452 match v {
453 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
454 _ => Err(v),
455 }
456 }
457}
458
459impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
460 fn from(m: ModelRc<T>) -> Self {
461 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
462 Value::Model(v.clone())
463 } else {
464 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
465 }
466 }
467}
468impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
469 type Error = Value;
470 #[inline]
471 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
472 match v {
473 Value::Model(m) => {
474 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
475 Ok(v.clone())
476 } else if let Some(v) =
477 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
478 {
479 Ok(v.0.clone())
480 } else {
481 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
482 }
483 }
484 _ => Err(v),
485 }
486 }
487}
488
489#[test]
490fn value_model_conversion() {
491 use i_slint_core::model::*;
492 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
493 let v = Value::from(m.clone());
494 assert_eq!(v, Value::Model(m.clone()));
495 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
496 assert_eq!(m2, m);
497
498 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
499 assert_eq!(int_model.row_count(), 2);
500 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
501
502 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
503 assert_eq!(m3.row_count(), 2);
504 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
505
506 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
507 assert_eq!(str_model.row_count(), 2);
508 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
510
511 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
512 assert!(err.is_err());
513
514 let model =
515 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
516
517 let value: Value = ModelRc::from(model.clone()).into();
518 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
519 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
520 value_model.set_row_data(1, Value::String("qux".into()));
521 value_model.set_row_data(0, Value::Bool(true));
522 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
523 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
525
526 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
528 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
529
530 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
531 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
532 assert_eq!(
533 model.as_ref() as *const VecModel<SharedString>,
534 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
535 as *const VecModel<SharedString>
536 );
537}
538
539pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
540 i_slint_compiler::names::normalize_identifier(ident)
541}
542
543#[derive(Clone, PartialEq, Debug, Default)]
565pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
566impl Struct {
567 pub fn get_field(&self, name: &str) -> Option<&Value> {
569 if i_slint_compiler::names::is_identifier_normalized(name) {
570 self.0.get(name)
571 } else {
572 self.0.get(&*normalize_identifier(name))
573 }
574 }
575 pub fn set_field(&mut self, name: String, value: Value) {
577 self.0.insert(normalize_identifier(&name), value);
578 }
579
580 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
582 self.0.iter().map(|(a, b)| (a.as_str(), b))
583 }
584}
585
586impl FromIterator<(String, Value)> for Struct {
587 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
588 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
589 }
590}
591
592#[test]
593fn struct_field_name_normalization() {
594 let mut s = Struct::default();
595 s.set_field("foo_bar".into(), Value::Number(1.));
596 s.set_field("cross-axis-self-alignment".into(), Value::Number(2.));
598 assert_eq!(s.get_field("foo-bar"), Some(&Value::Number(1.)));
599 assert_eq!(s.get_field("foo_bar"), Some(&Value::Number(1.)));
600 assert_eq!(s.get_field("cross-axis-self-alignment"), Some(&Value::Number(2.)));
601 assert_eq!(s.get_field("cross_axis_self_alignment"), Some(&Value::Number(2.)));
602}
603
604#[cfg(feature = "std")]
605#[deprecated(note = "Use slint_interpreter::Compiler instead")]
607pub struct ComponentCompiler {
608 config: i_slint_compiler::CompilerConfiguration,
609 overrides: i_slint_compiler::project_file::Overrides,
610 diagnostics: Vec<Diagnostic>,
611}
612
613#[cfg(feature = "std")]
614#[allow(deprecated)]
615impl Default for ComponentCompiler {
616 fn default() -> Self {
617 let mut config = i_slint_compiler::CompilerConfiguration::new(
618 i_slint_compiler::generator::OutputFormat::Interpreter,
619 );
620 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
621 Self { config, overrides: Default::default(), diagnostics: Vec::new() }
622 }
623}
624
625#[cfg(feature = "std")]
626#[allow(deprecated)]
627impl ComponentCompiler {
628 pub fn new() -> Self {
630 Self::default()
631 }
632
633 #[doc(hidden)]
637 #[cfg(feature = "internal")]
638 pub fn compiler_configuration(
639 &mut self,
640 _: i_slint_core::InternalToken,
641 ) -> &mut i_slint_compiler::CompilerConfiguration {
642 &mut self.config
643 }
644
645 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
649 self.overrides.project.include_paths = Some(include_paths.clone());
650 self.config.include_paths = include_paths;
651 }
652
653 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
655 &self.config.include_paths
656 }
657
658 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
663 self.overrides.project.library_paths = Some(library_paths.clone());
664 self.config.library_paths = library_paths;
665 }
666
667 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
669 &self.config.library_paths
670 }
671
672 pub fn set_style(&mut self, style: String) {
685 self.overrides.style = Some(style.clone());
686 self.config.style = Some(style);
687 }
688
689 pub fn style(&self) -> Option<&String> {
691 self.config.style.as_ref()
692 }
693
694 pub fn set_translation_domain(&mut self, domain: String) {
696 self.config.translation_domain = Some(domain);
697 }
698
699 pub fn set_file_loader(
707 &mut self,
708 file_loader_fallback: impl Fn(
709 &Path,
710 )
711 -> Pin<Box<dyn Future<Output = Option<std::io::Result<String>>>>>
712 + 'static,
713 ) {
714 #[expect(deprecated)]
715 let open_import_callback: i_slint_compiler::OpenImportCallback =
716 Rc::new(move |path| file_loader_fallback(&path.to_legacy_path()));
717 self.config.open_import_callback = Some(open_import_callback);
718 }
719
720 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
722 &self.diagnostics
723 }
724
725 pub async fn build_from_path<P: AsRef<Path>>(
748 &mut self,
749 path: P,
750 ) -> Option<ComponentDefinition> {
751 let compiler = Compiler {
752 config: self.config.clone(),
753 overrides: self.overrides.clone(),
754 project_file_loader: None,
755 project_root: None,
756 resource_loader: None,
757 };
758 let r = compiler.build_from_path(path).await;
759 self.diagnostics = r.diagnostics.into_iter().collect();
760 r.components.into_values().next()
761 }
762
763 pub async fn build_from_source(
780 &mut self,
781 source_code: String,
782 path: PathBuf,
783 ) -> Option<ComponentDefinition> {
784 let compiler = Compiler {
785 config: self.config.clone(),
786 overrides: self.overrides.clone(),
787 project_file_loader: None,
788 project_root: None,
789 resource_loader: None,
790 };
791 let r = compiler.build_from_source(source_code, path).await;
792 self.diagnostics = r.diagnostics.into_iter().collect();
793 r.components.into_values().next()
794 }
795
796 #[cfg(feature = "ffi")]
798 pub(crate) fn set_error(&mut self, message: &str, path: PathBuf) {
799 use i_slint_compiler::diagnostics::{BuildDiagnostics, SourceFileInner, SourceLocation};
800 let mut diagnostics = BuildDiagnostics::default();
801 diagnostics.push_error_with_span(
802 message.into(),
803 SourceLocation {
804 source_file: Some(SourceFileInner::from_path_only(SourcePath::new(path))),
805 span: Default::default(),
806 },
807 );
808 self.diagnostics = diagnostics.into_iter().collect();
809 }
810}
811
812#[cfg(feature = "std")]
813pub struct Compiler {
816 config: i_slint_compiler::CompilerConfiguration,
817 overrides: i_slint_compiler::project_file::Overrides,
818 project_file_loader: Option<i_slint_compiler::OpenImportCallback>,
819 project_root: Option<SourcePath>,
820 resource_loader: Option<crate::component::ResourceLoader>,
821}
822
823#[cfg(feature = "std")]
824impl Default for Compiler {
825 fn default() -> Self {
826 let config = i_slint_compiler::CompilerConfiguration::new(
827 i_slint_compiler::generator::OutputFormat::Interpreter,
828 );
829 Self {
830 config,
831 overrides: Default::default(),
832 project_file_loader: None,
833 project_root: None,
834 resource_loader: None,
835 }
836 }
837}
838
839#[cfg(feature = "std")]
840impl Compiler {
841 pub fn new() -> Self {
843 Self::default()
844 }
845
846 #[doc(hidden)]
847 #[cfg(feature = "internal")]
848 pub fn set_project_file_loader(
849 &mut self,
850 file_loader: i_slint_compiler::OpenImportCallback,
851 _: i_slint_core::InternalToken,
852 ) {
853 self.project_file_loader = Some(file_loader);
854 }
855
856 #[doc(hidden)]
857 #[cfg(feature = "internal")]
858 pub fn set_project_root(&mut self, root: Option<SourcePath>, _: i_slint_core::InternalToken) {
859 self.project_root = root;
860 }
861
862 #[doc(hidden)]
863 #[cfg(feature = "internal")]
864 pub fn set_overrides(
865 &mut self,
866 overrides: i_slint_compiler::project_file::Overrides,
867 _: i_slint_core::InternalToken,
868 ) {
869 self.overrides = overrides;
870 }
871
872 #[doc(hidden)]
873 #[cfg(feature = "internal")]
874 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
875 self.config.embed_resources = embed_resources;
876 }
877
878 #[doc(hidden)]
882 #[cfg(feature = "internal")]
883 pub fn compiler_configuration(
884 &mut self,
885 _: i_slint_core::InternalToken,
886 ) -> &mut i_slint_compiler::CompilerConfiguration {
887 &mut self.config
888 }
889
890 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
894 self.overrides.project.include_paths = Some(include_paths);
895 }
896
897 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
899 self.overrides.project.include_paths.as_ref().unwrap_or(&self.config.include_paths)
900 }
901
902 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
907 self.overrides.project.library_paths = Some(library_paths);
908 }
909
910 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
912 self.overrides.project.library_paths.as_ref().unwrap_or(&self.config.library_paths)
913 }
914
915 pub fn set_style(&mut self, style: String) {
927 self.overrides.style = Some(style);
928 }
929
930 pub fn style(&self) -> Option<&String> {
932 self.overrides.style.as_ref().or(self.config.style.as_ref())
933 }
934
935 pub fn set_translation_domain(&mut self, domain: String) {
937 self.config.translation_domain = Some(domain);
938 }
939
940 pub fn set_default_translation_context(
946 &mut self,
947 default_translation_context: DefaultTranslationContext,
948 ) {
949 self.config.default_translation_context = default_translation_context;
950 }
951
952 #[cfg(feature = "bundle-translations")]
959 pub fn set_bundled_translations_path(&mut self, path: impl Into<PathBuf>) {
960 self.config.bundled_translations_path = Some(path.into());
961 }
962
963 pub fn set_file_loader(
971 &mut self,
972 file_loader_fallback: impl Fn(
973 &Path,
974 )
975 -> Pin<Box<dyn Future<Output = Option<std::io::Result<String>>>>>
976 + 'static,
977 ) {
978 #[expect(deprecated)]
979 let open_import_callback: i_slint_compiler::OpenImportCallback =
980 Rc::new(move |path| file_loader_fallback(&path.to_legacy_path()));
981 self.config.open_import_callback = Some(open_import_callback);
982 }
983
984 #[doc(hidden)]
991 #[cfg(feature = "internal")]
992 pub fn set_resource_loader(
993 &mut self,
994 resource_loader: impl Fn(SourcePath) -> Pin<Box<dyn Future<Output = std::io::Result<Vec<u8>>>>>
995 + 'static,
996 _: i_slint_core::InternalToken,
997 ) {
998 self.resource_loader = Some(Rc::new(resource_loader));
999 }
1000
1001 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
1024 let input_path = i_slint_compiler::source_path::clean_path(path.as_ref());
1025 self.build(
1026 None,
1027 SourcePath::File(input_path),
1028 AnimationMode::Running,
1029 self.project_root.clone(),
1030 )
1031 .await
1032 }
1033
1034 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1047 self.build(
1048 Some(source_code),
1049 SourcePath::new(path),
1050 AnimationMode::Running,
1051 self.project_root.clone(),
1052 )
1053 .await
1054 }
1055
1056 #[doc(hidden)]
1063 #[cfg(any(feature = "internal", feature = "internal-highlight"))]
1064 pub async fn build_from_source_path(
1065 &self,
1066 source_code: Option<String>,
1067 path: SourcePath,
1068 _: i_slint_core::InternalToken,
1069 ) -> CompilationResult {
1070 self.build(source_code, path, AnimationMode::Running, self.project_root.clone()).await
1071 }
1072
1073 #[doc(hidden)]
1075 #[cfg(feature = "internal")]
1076 pub async fn build_static_from_source(
1077 &self,
1078 source_code: Option<String>,
1079 path: SourcePath,
1080 _: i_slint_core::InternalToken,
1081 ) -> CompilationResult {
1082 self.build(source_code, path, AnimationMode::Static, self.project_root.clone()).await
1083 }
1084
1085 async fn build(
1086 &self,
1087 source_code: Option<String>,
1088 input: SourcePath,
1089 animation_mode: AnimationMode,
1090 project_root: Option<SourcePath>,
1091 ) -> CompilationResult {
1092 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1093 #[cfg_attr(not(feature = "internal"), expect(unused_variables))]
1094 let (loaded, attempted_paths) = i_slint_compiler::project_file::load_input(
1095 &input,
1096 source_code,
1097 project_root,
1098 self.project_file_loader.clone(),
1099 &mut diagnostics,
1100 )
1101 .await;
1102 #[cfg_attr(not(feature = "internal"), allow(unused_mut))]
1103 let mut result = match loaded {
1104 None => CompilationResult {
1105 components: HashMap::new(),
1106 diagnostics: diagnostics.into_iter().collect(),
1107 #[cfg(feature = "internal")]
1108 watch_paths: Vec::new(),
1109 #[cfg(feature = "internal")]
1110 structs_and_enums: Vec::new(),
1111 },
1112 Some(loaded) => {
1113 let mut config = self.config.clone();
1114 self.overrides.apply(loaded.project_file.as_ref(), &mut config);
1115 build_compilation_result(
1116 loaded.source_code,
1117 loaded.source,
1118 config,
1119 animation_mode,
1120 self.resource_loader.clone(),
1121 )
1122 .await
1123 }
1124 };
1125 #[cfg(feature = "internal")]
1126 {
1127 result.watch_paths.push(input);
1128 result.watch_paths.extend(attempted_paths);
1129 result.watch_paths.sort();
1130 result.watch_paths.dedup();
1131 }
1132 result
1133 }
1134}
1135
1136#[cfg(feature = "std")]
1137pub(crate) enum AnimationMode {
1138 #[cfg_attr(not(feature = "internal"), allow(dead_code))]
1141 Static,
1142 Running,
1143}
1144
1145#[cfg(feature = "std")]
1146async fn build_compilation_result(
1147 source_code: String,
1148 path: SourcePath,
1149 config: i_slint_compiler::CompilerConfiguration,
1150 animation_mode: AnimationMode,
1151 resource_loader: Option<crate::component::ResourceLoader>,
1152) -> CompilationResult {
1153 let result = crate::component::build_from_source(
1154 source_code,
1155 path,
1156 config,
1157 animation_mode,
1158 resource_loader,
1159 )
1160 .await;
1161 let components = result
1162 .components
1163 .into_iter()
1164 .map(|(name, def)| (name, ComponentDefinition { inner: Rc::new(def) }))
1165 .collect::<HashMap<String, ComponentDefinition>>();
1166 CompilationResult {
1167 components,
1168 diagnostics: result.diagnostics,
1169 #[cfg(feature = "internal")]
1170 watch_paths: result.watch_paths,
1171 #[cfg(feature = "internal")]
1172 structs_and_enums: result.structs_and_enums,
1173 }
1174}
1175
1176pub struct SendableCompilationResult {
1199 pub(crate) compilation_unit: Option<i_slint_compiler::llr::CompilationUnit>,
1201 components: HashMap<String, i_slint_compiler::llr::PublicComponentIdx>,
1203 font_files: crate::component::FontFiles,
1204 #[cfg(feature = "internal-mcu-interpreter")]
1205 pub(crate) pre_rendered: Vec<Option<i_slint_common::pre_rendered::PreRenderedResource>>,
1206 #[cfg(feature = "std")]
1207 diagnostics: Vec<Diagnostic>,
1208 #[cfg(feature = "internal")]
1209 watch_paths: Vec<SourcePath>,
1210 #[cfg(feature = "internal")]
1211 structs_and_enums: Vec<LangType>,
1212}
1213
1214const _: () = {
1215 const fn assert_send<T: Send>() {}
1216 assert_send::<SendableCompilationResult>();
1217};
1218
1219impl From<SendableCompilationResult> for CompilationResult {
1220 #[cfg_attr(not(feature = "internal-mcu-interpreter"), allow(unused_mut))]
1221 fn from(mut sent: SendableCompilationResult) -> Self {
1222 #[cfg(feature = "internal-mcu-interpreter")]
1223 let pre_rendered = crate::static_resources::PreRendered::from_sendable(core::mem::take(
1224 &mut sent.pre_rendered,
1225 ));
1226 Self::from_sendable(
1227 sent,
1228 #[cfg(feature = "internal-mcu-interpreter")]
1229 pre_rendered,
1230 )
1231 }
1232}
1233
1234impl CompilationResult {
1235 fn from_sendable(
1236 sent: SendableCompilationResult,
1237 #[cfg(feature = "internal-mcu-interpreter")]
1238 pre_rendered: crate::static_resources::PreRendered,
1239 ) -> Self {
1240 let SendableCompilationResult {
1241 compilation_unit,
1242 components,
1243 font_files,
1244 #[cfg(feature = "internal-mcu-interpreter")]
1245 pre_rendered: _,
1246 #[cfg(feature = "std")]
1247 diagnostics,
1248 #[cfg(feature = "internal")]
1249 watch_paths,
1250 #[cfg(feature = "internal")]
1251 structs_and_enums,
1252 } = sent;
1253 let compilation_unit = compilation_unit.map(Rc::new);
1254 let resources = Rc::new(crate::component::Resources {
1255 font_files,
1256 #[cfg(feature = "internal-mcu-interpreter")]
1257 pre_rendered,
1258 });
1259 let components = components
1260 .into_iter()
1261 .filter_map(|(name, public_index)| {
1262 let inner = Rc::new(crate::component::ComponentDefinitionInner {
1263 compilation_unit: compilation_unit.clone()?,
1264 public_index,
1265 type_loaders: Default::default(),
1266 resources: resources.clone(),
1267 });
1268 Some((name, ComponentDefinition { inner }))
1269 })
1270 .collect();
1271 Self {
1272 components,
1273 #[cfg(feature = "std")]
1274 diagnostics,
1275 #[cfg(feature = "internal")]
1276 watch_paths,
1277 #[cfg(feature = "internal")]
1278 structs_and_enums,
1279 }
1280 }
1281}
1282
1283#[derive(Clone)]
1290pub struct CompilationResult {
1291 pub(crate) components: HashMap<String, ComponentDefinition>,
1292 #[cfg(feature = "std")]
1293 pub(crate) diagnostics: Vec<Diagnostic>,
1294 #[cfg(feature = "internal")]
1295 pub(crate) watch_paths: Vec<SourcePath>,
1296 #[cfg(feature = "internal")]
1297 pub(crate) structs_and_enums: Vec<LangType>,
1298}
1299
1300impl core::fmt::Debug for CompilationResult {
1301 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1302 let mut f = f.debug_struct("CompilationResult");
1303 f.field("components", &self.components.keys());
1304 #[cfg(feature = "std")]
1305 f.field("diagnostics", &self.diagnostics);
1306 f.finish()
1307 }
1308}
1309
1310impl CompilationResult {
1311 #[cfg(feature = "std")]
1314 pub fn has_errors(&self) -> bool {
1315 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1316 }
1317
1318 #[cfg(feature = "std")]
1322 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1323 self.diagnostics.iter().cloned()
1324 }
1325
1326 #[cfg(feature = "display-diagnostics")]
1332 pub fn print_diagnostics(&self) {
1333 print_diagnostics(&self.diagnostics)
1334 }
1335
1336 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1338 self.components.values().cloned()
1339 }
1340
1341 #[doc(hidden)]
1345 #[cfg(all(feature = "internal", feature = "internal-mcu-interpreter"))]
1346 pub fn from_compilation_unit(
1347 unit: i_slint_compiler::llr::CompilationUnit,
1348 resources: impl IntoIterator<Item = LoadedResource>,
1349 _: i_slint_core::InternalToken,
1350 ) -> Self {
1351 let components = unit
1352 .public_components
1353 .iter_enumerated()
1354 .map(|(public_index, component)| (component.name.to_string(), public_index))
1355 .collect();
1356 let sent = SendableCompilationResult {
1357 compilation_unit: Some(unit),
1358 components,
1359 font_files: HashMap::new(),
1360 pre_rendered: Vec::new(),
1361 #[cfg(feature = "std")]
1362 diagnostics: Vec::new(),
1363 watch_paths: Vec::new(),
1364 structs_and_enums: Vec::new(),
1365 };
1366 Self::from_sendable(sent, crate::static_resources::PreRendered::from_loaded(resources))
1367 }
1368
1369 pub fn into_send(self) -> SendableCompilationResult {
1371 let Self {
1372 components,
1373 #[cfg(feature = "std")]
1374 diagnostics,
1375 #[cfg(feature = "internal")]
1376 watch_paths,
1377 #[cfg(feature = "internal")]
1378 structs_and_enums,
1379 } = self;
1380
1381 let mut unit = None::<Rc<i_slint_compiler::llr::CompilationUnit>>;
1383 let mut resources = None::<Rc<crate::component::Resources>>;
1384 let components = components
1385 .into_iter()
1386 .map(|(name, definition)| {
1387 let public_index = definition.inner.public_index;
1388 match &unit {
1389 Some(u) => {
1390 debug_assert!(Rc::ptr_eq(u, &definition.inner.compilation_unit))
1391 }
1392 None => {
1393 unit = Some(definition.inner.compilation_unit.clone());
1394 resources = Some(definition.inner.resources.clone());
1395 }
1396 }
1397 (name, public_index)
1398 })
1399 .collect();
1400 let compilation_unit = unit.map(Rc::unwrap_or_clone);
1403 let resources = resources.map(Rc::unwrap_or_clone).unwrap_or_default();
1404
1405 SendableCompilationResult {
1406 compilation_unit,
1407 components,
1408 font_files: resources.font_files,
1409 #[cfg(feature = "internal-mcu-interpreter")]
1410 pre_rendered: resources.pre_rendered.into_sendable(),
1411 #[cfg(feature = "std")]
1412 diagnostics,
1413 #[cfg(feature = "internal")]
1414 watch_paths,
1415 #[cfg(feature = "internal")]
1416 structs_and_enums,
1417 }
1418 }
1419
1420 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1422 self.components.keys().map(|s| s.as_str())
1423 }
1424
1425 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1428 self.components.get(name).cloned()
1429 }
1430
1431 #[doc(hidden)]
1433 #[cfg(feature = "internal")]
1434 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[SourcePath] {
1435 &self.watch_paths
1436 }
1437
1438 #[doc(hidden)]
1440 #[cfg(feature = "internal")]
1441 pub fn structs_and_enums(
1442 &self,
1443 _: i_slint_core::InternalToken,
1444 ) -> impl Iterator<Item = &LangType> {
1445 self.structs_and_enums.iter()
1446 }
1447
1448 #[doc(hidden)]
1451 #[cfg(feature = "internal")]
1452 pub fn compilation_unit(
1453 &self,
1454 _: i_slint_core::InternalToken,
1455 ) -> Option<&i_slint_compiler::llr::CompilationUnit> {
1456 self.components.values().next().map(|d| &*d.inner.compilation_unit)
1457 }
1458}
1459
1460#[derive(Clone)]
1470pub struct ComponentDefinition {
1471 pub(crate) inner: Rc<crate::component::ComponentDefinitionInner>,
1472}
1473
1474impl ComponentDefinition {
1475 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1477 let instance = self.create_with_options(Default::default())?;
1478 instance.finish_creation()?;
1479 Ok(instance)
1480 }
1481
1482 #[doc(hidden)]
1484 #[cfg(feature = "internal")]
1485 pub fn create_with_context(
1486 &self,
1487 context: SlintContext,
1488 ) -> Result<ComponentInstance, PlatformError> {
1489 let instance = self.create_with_options(WindowOptions::WithContext(context))?;
1490 instance.finish_creation()?;
1491 Ok(instance)
1492 }
1493
1494 #[doc(hidden)]
1496 #[cfg(feature = "internal")]
1497 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1498 self.create_with_options(WindowOptions::Embed {
1499 parent_item_tree: ctx.parent_item_tree,
1500 parent_item_tree_index: ctx.parent_item_tree_index,
1501 })
1502 }
1503
1504 #[doc(hidden)]
1506 #[cfg(feature = "internal")]
1507 pub fn create_with_existing_window(
1508 &self,
1509 window: &Window,
1510 ) -> Result<ComponentInstance, PlatformError> {
1511 self.create_with_options(WindowOptions::UseExistingWindow(
1512 WindowInner::from_pub(window).window_adapter(),
1513 ))
1514 }
1515
1516 #[doc(hidden)]
1518 #[cfg(feature = "internal")]
1519 pub fn create_detached_with_existing_window(
1520 &self,
1521 window: &Window,
1522 _: i_slint_core::InternalToken,
1523 ) -> Result<ComponentInstance, PlatformError> {
1524 let adapter = WindowInner::from_pub(window).window_adapter();
1525 Ok(ComponentInstance { inner: self.inner.create_detached_with_existing_window(adapter) })
1526 }
1527
1528 pub(crate) fn create_with_options(
1530 &self,
1531 options: WindowOptions,
1532 ) -> Result<ComponentInstance, PlatformError> {
1533 let instance = match options {
1534 WindowOptions::CreateNewWindow => self
1535 .inner
1536 .create_with_context(i_slint_backend_selector::with_global_context(Clone::clone)?),
1537 WindowOptions::UseExistingWindow(adapter) => {
1538 self.inner.create_with_existing_window(adapter)
1539 }
1540 WindowOptions::Embed { parent_item_tree, parent_item_tree_index } => {
1541 self.inner.create_embedded(parent_item_tree, parent_item_tree_index)
1542 }
1543 WindowOptions::WithContext(context) => self.inner.create_with_context(context),
1544 };
1545 Ok(ComponentInstance { inner: instance })
1546 }
1547}
1548
1549#[allow(dead_code)]
1554#[derive(Default)]
1555pub(crate) enum WindowOptions {
1556 #[default]
1557 CreateNewWindow,
1558 UseExistingWindow(i_slint_core::window::WindowAdapterRc),
1559 Embed {
1560 parent_item_tree: i_slint_core::item_tree::ItemTreeWeak,
1561 parent_item_tree_index: u32,
1562 },
1563 WithContext(SlintContext),
1564}
1565
1566impl ComponentDefinition {
1567 #[doc(hidden)]
1571 #[cfg(feature = "internal")]
1572 pub fn properties_and_callbacks(
1573 &self,
1574 ) -> impl Iterator<
1575 Item = (
1576 String,
1577 (i_slint_compiler::langtype::Type, i_slint_compiler::native_class::PropertyVisibility),
1578 ),
1579 > + '_ {
1580 self.inner
1581 .properties_and_callbacks()
1582 .map(|(n, t, v)| (n.to_string(), (t, v)))
1583 .collect::<Vec<_>>()
1584 .into_iter()
1585 }
1586
1587 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1590 self.inner
1591 .properties()
1592 .map(|(n, t)| (n.to_string(), t.into()))
1593 .collect::<Vec<_>>()
1594 .into_iter()
1595 }
1596
1597 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1599 self.inner.callbacks().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1600 }
1601
1602 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1604 self.inner.functions().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1605 }
1606
1607 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1612 self.inner.globals().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1613 }
1614
1615 #[doc(hidden)]
1619 #[cfg(feature = "internal")]
1620 pub fn global_properties_and_callbacks(
1621 &self,
1622 global_name: &str,
1623 ) -> Option<
1624 impl Iterator<
1625 Item = (
1626 String,
1627 (
1628 i_slint_compiler::langtype::Type,
1629 i_slint_compiler::native_class::PropertyVisibility,
1630 ),
1631 ),
1632 > + '_,
1633 > {
1634 Some(
1635 self.inner
1636 .global_properties_and_callbacks(global_name)?
1637 .map(|(n, t, v)| (n.to_string(), (t, v)))
1638 .collect::<Vec<_>>()
1639 .into_iter(),
1640 )
1641 }
1642
1643 pub fn global_properties(
1645 &self,
1646 global_name: &str,
1647 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1648 Some(
1649 self.inner
1650 .global_properties(global_name)?
1651 .map(|(n, t)| (n.to_string(), t.into()))
1652 .collect::<Vec<_>>()
1653 .into_iter(),
1654 )
1655 }
1656
1657 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1659 Some(
1660 self.inner
1661 .global_callbacks(global_name)?
1662 .map(|s| s.to_string())
1663 .collect::<Vec<_>>()
1664 .into_iter(),
1665 )
1666 }
1667
1668 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1670 Some(
1671 self.inner
1672 .global_functions(global_name)?
1673 .map(|s| s.to_string())
1674 .collect::<Vec<_>>()
1675 .into_iter(),
1676 )
1677 }
1678
1679 pub fn name(&self) -> &str {
1681 self.inner.name()
1682 }
1683
1684 #[doc(hidden)]
1688 #[cfg(feature = "internal")]
1689 pub fn is_window(&self) -> bool {
1690 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::Window
1691 }
1692
1693 #[cfg(all(feature = "internal", feature = "std"))]
1695 #[doc(hidden)]
1696 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1697 self.inner
1698 .type_loaders
1699 .originals
1700 .get(self.inner.public_index)
1701 .expect("root_component() called on a definition built without compiler state")
1702 .clone()
1703 }
1704
1705 #[cfg(feature = "internal-highlight")]
1709 pub fn type_loader(&self) -> Rc<i_slint_compiler::typeloader::TypeLoader> {
1710 self.inner.type_loaders.type_loader.clone().expect(
1711 "TypeLoader was not retained for this ComponentDefinition (reconstructed from an instance)",
1712 )
1713 }
1714
1715 #[cfg(feature = "internal-highlight")]
1723 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1724 self.inner
1725 .type_loaders
1726 .raw_type_loader
1727 .as_ref()
1728 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1729 }
1730}
1731
1732#[cfg(feature = "display-diagnostics")]
1738pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1739 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1740 for d in diagnostics {
1741 build_diagnostics.push_compiler_error(d.clone())
1742 }
1743 build_diagnostics.print_styled_if_terminal();
1744}
1745
1746#[repr(C)]
1754pub struct ComponentInstance {
1755 pub(crate) inner: crate::component::ComponentInstanceInner,
1756}
1757
1758impl ComponentInstance {
1759 pub fn definition(&self) -> ComponentDefinition {
1761 ComponentDefinition { inner: Rc::new(self.inner.definition()) }
1762 }
1763
1764 fn finish_creation(&self) -> Result<(), PlatformError> {
1766 if !self.is_system_tray_rooted() {
1769 self.inner.window_adapter_ref()?;
1771 i_slint_core::window::WindowInner::from_pub(self.window()).ensure_tree_instantiated();
1774 }
1775 Ok(())
1776 }
1777
1778 #[doc(hidden)]
1780 #[cfg(feature = "internal")]
1781 pub fn as_item_tree(
1782 &self,
1783 _: i_slint_core::InternalToken,
1784 ) -> i_slint_core::item_tree::ItemTreeRc {
1785 VRc::into_dyn(self.inner.vrc().clone())
1786 }
1787
1788 fn is_system_tray_rooted(&self) -> bool {
1789 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::SystemTrayIcon
1790 }
1791
1792 fn set_tray_icon_visible(&self, visible: bool) {
1796 let item_rc = ItemRc::new(VRc::into_dyn(self.inner.vrc().clone()), 0);
1798 let tray = item_rc
1799 .downcast::<SystemTrayIcon>()
1800 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1801 tray.as_pin_ref().visible.set(visible);
1802 }
1803
1804 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1824 self.inner.get_property(name).ok_or(GetPropertyError::NoSuchProperty)
1825 }
1826
1827 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1829 self.inner.set_property(name, value)
1830 }
1831
1832 pub fn set_callback(
1867 &self,
1868 name: &str,
1869 callback: impl Fn(&[Value]) -> Value + 'static,
1870 ) -> Result<(), SetCallbackError> {
1871 self.inner.set_callback(name, callback).map_err(|()| SetCallbackError::NoSuchCallback)
1872 }
1873
1874 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1879 self.inner.invoke(name, args).ok_or(InvokeError::NoSuchCallable)
1880 }
1881
1882 pub fn get_global_property(
1907 &self,
1908 global: &str,
1909 property: &str,
1910 ) -> Result<Value, GetPropertyError> {
1911 self.inner.get_global_property(global, property).ok_or(GetPropertyError::NoSuchProperty)
1912 }
1913
1914 pub fn set_global_property(
1916 &self,
1917 global: &str,
1918 property: &str,
1919 value: Value,
1920 ) -> Result<(), SetPropertyError> {
1921 self.inner.set_global_property(global, property, value)
1922 }
1923
1924 pub fn set_global_callback(
1959 &self,
1960 global: &str,
1961 name: &str,
1962 callback: impl Fn(&[Value]) -> Value + 'static,
1963 ) -> Result<(), SetCallbackError> {
1964 self.inner
1965 .set_global_callback(global, name, callback)
1966 .map_err(|()| SetCallbackError::NoSuchCallback)
1967 }
1968
1969 pub fn invoke_global(
1974 &self,
1975 global: &str,
1976 callable_name: &str,
1977 args: &[Value],
1978 ) -> Result<Value, InvokeError> {
1979 self.inner.invoke_global(global, callable_name, args).ok_or(InvokeError::NoSuchCallable)
1980 }
1981
1982 #[cfg(feature = "internal-highlight")]
1986 pub fn component_positions(
1987 &self,
1988 path: &SourcePath,
1989 offset: u32,
1990 ) -> Vec<crate::highlight::HighlightedRect> {
1991 crate::highlight::component_positions(self.inner.vrc(), path, offset)
1992 }
1993
1994 #[doc(hidden)]
1995 #[cfg(all(feature = "internal", feature = "internal-highlight"))]
1996 pub fn component_item(
1997 &self,
1998 path: &SourcePath,
1999 offset: u32,
2000 instance_index: usize,
2001 _: i_slint_core::InternalToken,
2002 ) -> Option<i_slint_core::items::ItemRc> {
2003 crate::highlight::component_item(self.inner.vrc(), path, offset, instance_index)
2004 }
2005
2006 #[doc(hidden)]
2007 #[cfg(all(feature = "internal", feature = "internal-highlight"))]
2008 pub fn item_property(
2009 item: &i_slint_core::items::ItemRc,
2010 property_name: &str,
2011 _: i_slint_core::InternalToken,
2012 ) -> Option<Value> {
2013 let item_tree = VRc::borrow(item.item_tree());
2014 let instance = item_tree.downcast::<Instance>()?;
2015 let (path, local_item_index) = instance.item_table.get(item.index() as usize)?.as_ref()?;
2016 let mut owner = &instance.root_sub_component;
2017 for &component_index in path {
2018 owner = owner.sub_components.get(component_index)?;
2019 }
2020 owner.items.get(*local_item_index)?.as_ref().get_property(property_name).ok()
2021 }
2022
2023 #[cfg(feature = "internal-highlight")]
2027 pub fn element_candidates_at(
2028 &self,
2029 position: i_slint_core::lengths::LogicalPoint,
2030 ) -> Vec<crate::highlight::ElementCandidate> {
2031 crate::highlight::element_candidates_at(self.inner.vrc(), position)
2032 }
2033
2034 #[cfg(feature = "internal-highlight")]
2038 pub fn element_node_at_source_code_position(
2039 &self,
2040 path: &SourcePath,
2041 offset: u32,
2042 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
2043 crate::highlight::element_node_at_source_code_position(self.inner.vrc(), path, offset)
2044 }
2045
2046 #[cfg(feature = "internal")]
2048 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
2049 crate::debug_hook::set_debug_hook_callback(self.inner.vrc(), callback);
2050 }
2051}
2052
2053impl StrongHandle for ComponentInstance {
2054 type WeakInner = vtable::VWeak<ItemTreeVTable, Instance>;
2055
2056 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
2057 Some(Self { inner: crate::component::ComponentInstanceInner(inner.upgrade()?) })
2058 }
2059}
2060
2061impl ComponentHandle for ComponentInstance {
2062 fn as_weak(&self) -> Weak<Self>
2063 where
2064 Self: Sized,
2065 {
2066 Weak::new(VRc::downgrade(self.inner.vrc()))
2067 }
2068
2069 fn clone_strong(&self) -> Self {
2070 Self { inner: self.inner.clone() }
2071 }
2072
2073 fn show(&self) -> Result<(), PlatformError> {
2074 if self.is_system_tray_rooted() {
2075 self.set_tray_icon_visible(true);
2076 return Ok(());
2077 }
2078 let adapter = self.inner.window_adapter_ref()?;
2079 self.inner.0.attach_to_window();
2083 adapter.window().show()
2084 }
2085
2086 fn hide(&self) -> Result<(), PlatformError> {
2087 if self.is_system_tray_rooted() {
2088 self.set_tray_icon_visible(false);
2089 return Ok(());
2090 }
2091 self.inner.window_adapter_ref()?.window().hide()
2092 }
2093
2094 fn run(&self) -> Result<(), PlatformError> {
2095 self.show()?;
2096 run_event_loop()?;
2097 self.hide()
2098 }
2099
2100 fn window(&self) -> &Window {
2101 let adapter = self.inner.window_adapter_ref().unwrap();
2102 self.inner.0.attach_to_window();
2108 adapter.window()
2109 }
2110
2111 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
2112 where
2113 Self: Sized,
2114 {
2115 unreachable!()
2116 }
2117}
2118
2119impl From<ComponentInstance> for VRc<ItemTreeVTable, Instance> {
2120 fn from(value: ComponentInstance) -> Self {
2121 value.inner.0
2122 }
2123}
2124
2125#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
2127#[non_exhaustive]
2128pub enum GetPropertyError {
2129 #[display("no such property")]
2131 NoSuchProperty,
2132}
2133
2134#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
2136#[non_exhaustive]
2137pub enum SetPropertyError {
2138 #[display("no such property")]
2140 NoSuchProperty,
2141 #[display("wrong type")]
2147 WrongType,
2148 #[display("access denied")]
2150 AccessDenied,
2151}
2152
2153#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
2155#[non_exhaustive]
2156pub enum SetCallbackError {
2157 #[display("no such callback")]
2159 NoSuchCallback,
2160}
2161
2162#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
2164#[non_exhaustive]
2165pub enum InvokeError {
2166 #[display("no such callback or function")]
2168 NoSuchCallable,
2169}
2170
2171pub fn run_event_loop() -> Result<(), PlatformError> {
2175 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
2176}
2177
2178pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
2182 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
2183 .map_err(|_| EventLoopError::NoEventLoopProvider)?
2184}
2185
2186#[test]
2187fn component_definition_properties() {
2188 i_slint_backend_testing::init_no_event_loop();
2189 let mut compiler = Compiler::default();
2190 compiler.set_style("fluent".into());
2191 let comp_def = spin_on::spin_on(
2192 compiler.build_from_source(
2193 r#"
2194 export component Dummy {
2195 in-out property <string> test;
2196 in-out property <int> underscores-and-dashes_preserved: 44;
2197 callback hello;
2198 }"#
2199 .into(),
2200 "".into(),
2201 ),
2202 )
2203 .component("Dummy")
2204 .unwrap();
2205
2206 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2207
2208 assert_eq!(props.len(), 2);
2209 assert_eq!(props[0].0, "test");
2210 assert_eq!(props[0].1, ValueType::String);
2211 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
2212 assert_eq!(props[1].1, ValueType::Number);
2213
2214 let instance = comp_def.create().unwrap();
2215 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
2216 assert_eq!(
2217 instance.get_property("underscoresanddashespreserved"),
2218 Err(GetPropertyError::NoSuchProperty)
2219 );
2220 assert_eq!(
2221 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
2222 Ok(())
2223 );
2224 assert_eq!(
2225 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
2226 Err(SetPropertyError::NoSuchProperty)
2227 );
2228 assert_eq!(
2229 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
2230 Err(SetPropertyError::WrongType)
2231 );
2232 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
2233}
2234
2235#[test]
2236fn component_definition_properties2() {
2237 i_slint_backend_testing::init_no_event_loop();
2238 let mut compiler = Compiler::default();
2239 compiler.set_style("fluent".into());
2240 let comp_def = spin_on::spin_on(
2241 compiler.build_from_source(
2242 r#"
2243 export component Dummy {
2244 in-out property <string> sub-text <=> sub.text;
2245 sub := Text { property <int> private-not-exported; }
2246 out property <string> xreadonly: "the value";
2247 private property <string> xx: sub.text;
2248 callback hello;
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(), 2);
2260 assert_eq!(props[0].0, "sub-text");
2261 assert_eq!(props[0].1, ValueType::String);
2262 assert_eq!(props[1].0, "xreadonly");
2263
2264 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
2265 assert_eq!(callbacks.len(), 1);
2266 assert_eq!(callbacks[0], "hello");
2267
2268 let instance = comp_def.create().unwrap();
2269 assert_eq!(
2270 instance.set_property("xreadonly", SharedString::from("XXX").into()),
2271 Err(SetPropertyError::AccessDenied)
2272 );
2273 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
2274 assert_eq!(
2275 instance.set_property("xx", SharedString::from("XXX").into()),
2276 Err(SetPropertyError::NoSuchProperty)
2277 );
2278 assert_eq!(
2279 instance.set_property("background", Value::default()),
2280 Err(SetPropertyError::NoSuchProperty)
2281 );
2282
2283 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
2284 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
2285}
2286
2287#[test]
2288fn globals() {
2289 i_slint_backend_testing::init_no_event_loop();
2290 let mut compiler = Compiler::default();
2291 compiler.set_style("fluent".into());
2292 let definition = spin_on::spin_on(
2293 compiler.build_from_source(
2294 r#"
2295 export global My-Super_Global {
2296 in-out property <int> the-property : 21;
2297 callback my-callback();
2298 callback int-callback() -> int;
2299 }
2300 export { My-Super_Global as AliasedGlobal }
2301 export component Dummy {
2302 callback alias <=> My-Super_Global.my-callback;
2303 }"#
2304 .into(),
2305 "".into(),
2306 ),
2307 )
2308 .component("Dummy")
2309 .unwrap();
2310
2311 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
2312
2313 assert!(definition.global_properties("not-there").is_none());
2314 {
2315 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
2316 let expected_callbacks = vec!["int-callback".to_string(), "my-callback".to_string()];
2317
2318 let assert_properties_and_callbacks = |global_name| {
2319 assert_eq!(
2320 definition
2321 .global_properties(global_name)
2322 .map(|props| props.collect::<Vec<_>>())
2323 .as_ref(),
2324 Some(&expected_properties)
2325 );
2326 assert_eq!(
2327 definition
2328 .global_callbacks(global_name)
2329 .map(|props| props.collect::<Vec<_>>())
2330 .as_ref(),
2331 Some(&expected_callbacks)
2332 );
2333 };
2334
2335 assert_properties_and_callbacks("My-Super-Global");
2336 assert_properties_and_callbacks("My_Super-Global");
2337 assert_properties_and_callbacks("AliasedGlobal");
2338 }
2339
2340 let instance = definition.create().unwrap();
2341 assert_eq!(
2342 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
2343 Ok(())
2344 );
2345 assert_eq!(
2346 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2347 Ok(())
2348 );
2349 assert_eq!(
2350 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2351 Err(SetPropertyError::NoSuchProperty)
2352 );
2353
2354 assert_eq!(
2355 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2356 Err(SetPropertyError::NoSuchProperty)
2357 );
2358 assert_eq!(
2359 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2360 Err(SetPropertyError::NoSuchProperty)
2361 );
2362 assert_eq!(
2363 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2364 Err(SetPropertyError::WrongType)
2365 );
2366 assert_eq!(
2367 instance.get_global_property("My-Super_Global", "yoyo"),
2368 Err(GetPropertyError::NoSuchProperty)
2369 );
2370 assert_eq!(
2371 instance.get_global_property("My-Super_Global", "the-property"),
2372 Ok(Value::Number(44.))
2373 );
2374
2375 assert_eq!(
2376 instance.set_property("the-property", Value::Void),
2377 Err(SetPropertyError::NoSuchProperty)
2378 );
2379 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2380
2381 assert_eq!(
2382 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2383 Err(SetCallbackError::NoSuchCallback)
2384 );
2385 assert_eq!(
2386 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2387 Err(SetCallbackError::NoSuchCallback)
2388 );
2389 assert_eq!(
2390 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2391 Err(SetCallbackError::NoSuchCallback)
2392 );
2393
2394 assert_eq!(
2395 instance.invoke_global("DontExist", "the-property", &[]),
2396 Err(InvokeError::NoSuchCallable)
2397 );
2398 assert_eq!(
2399 instance.invoke_global("My_Super_Global", "the-property", &[]),
2400 Err(InvokeError::NoSuchCallable)
2401 );
2402 assert_eq!(
2403 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2404 Err(InvokeError::NoSuchCallable)
2405 );
2406
2407 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2409
2410 assert_eq!(
2412 instance.invoke_global("My_Super_Global", "int-callback", &[]),
2413 Ok(Value::Number(0.))
2414 );
2415}
2416
2417#[test]
2418fn call_functions() {
2419 i_slint_backend_testing::init_no_event_loop();
2420 let mut compiler = Compiler::default();
2421 compiler.set_style("fluent".into());
2422 let definition = spin_on::spin_on(
2423 compiler.build_from_source(
2424 r#"
2425 export global Gl {
2426 out property<string> q;
2427 public function foo-bar(a-a: string, b-b:int) -> string {
2428 q = a-a;
2429 return a-a + b-b;
2430 }
2431 }
2432 export component Test {
2433 out property<int> p;
2434 public function foo-bar(a: int, b:int) -> int {
2435 p = a;
2436 return a + b;
2437 }
2438 }"#
2439 .into(),
2440 "".into(),
2441 ),
2442 )
2443 .component("Test")
2444 .unwrap();
2445
2446 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2447 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2448
2449 let instance = definition.create().unwrap();
2450
2451 assert_eq!(
2452 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2453 Ok(Value::Number(7.))
2454 );
2455 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2456 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2457
2458 assert_eq!(
2459 instance.invoke_global(
2460 "Gl",
2461 "foo_bar",
2462 &[Value::String("Hello".into()), Value::Number(10.)]
2463 ),
2464 Ok(Value::String("Hello10".into()))
2465 );
2466 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2467}
2468
2469#[test]
2470fn component_definition_struct_properties() {
2471 i_slint_backend_testing::init_no_event_loop();
2472 let mut compiler = Compiler::default();
2473 compiler.set_style("fluent".into());
2474 let comp_def = spin_on::spin_on(
2475 compiler.build_from_source(
2476 r#"
2477 export struct Settings {
2478 string_value: string,
2479 }
2480 export component Dummy {
2481 in-out property <Settings> test;
2482 }"#
2483 .into(),
2484 "".into(),
2485 ),
2486 )
2487 .component("Dummy")
2488 .unwrap();
2489
2490 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2491
2492 assert_eq!(props.len(), 1);
2493 assert_eq!(props[0].0, "test");
2494 assert_eq!(props[0].1, ValueType::Struct);
2495
2496 let instance = comp_def.create().unwrap();
2497
2498 let valid_struct: Struct =
2499 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2500
2501 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2502 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2503
2504 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2505
2506 let mut invalid_struct = valid_struct.clone();
2507 invalid_struct.set_field("other".into(), Value::Number(44.));
2508 assert_eq!(
2509 instance.set_property("test", Value::Struct(invalid_struct)),
2510 Err(SetPropertyError::WrongType)
2511 );
2512 let mut invalid_struct = valid_struct;
2513 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2514 assert_eq!(
2515 instance.set_property("test", Value::Struct(invalid_struct)),
2516 Err(SetPropertyError::WrongType)
2517 );
2518}
2519
2520#[test]
2521fn component_definition_model_properties() {
2522 use i_slint_core::model::*;
2523 i_slint_backend_testing::init_no_event_loop();
2524 let mut compiler = Compiler::default();
2525 compiler.set_style("fluent".into());
2526 let comp_def = spin_on::spin_on(compiler.build_from_source(
2527 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2528 "".into(),
2529 ))
2530 .component("Dummy")
2531 .unwrap();
2532
2533 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2534 assert_eq!(props.len(), 1);
2535 assert_eq!(props[0].0, "prop");
2536 assert_eq!(props[0].1, ValueType::Model);
2537
2538 let instance = comp_def.create().unwrap();
2539
2540 let int_model =
2541 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2542 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2543 let model_with_string = Value::Model(VecModel::from_slice(&[
2544 Value::Number(1000.),
2545 Value::String("foo".into()),
2546 Value::Number(1111.),
2547 ]));
2548
2549 #[track_caller]
2550 fn check_model(val: Value, r: &[f64]) {
2551 if let Value::Model(m) = val {
2552 assert_eq!(r.len(), m.row_count());
2553 for (i, v) in r.iter().enumerate() {
2554 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2555 }
2556 } else {
2557 panic!("{val:?} not a model");
2558 }
2559 }
2560
2561 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2562 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2563
2564 instance.set_property("prop", int_model).unwrap();
2565 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2566
2567 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2568 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2569 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2570 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2571
2572 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2573 check_model(instance.get_property("prop").unwrap(), &[]);
2574}
2575
2576#[test]
2577fn lang_type_to_value_type() {
2578 use alloc::collections::BTreeMap;
2579 use i_slint_compiler::langtype::Struct as LangStruct;
2580
2581 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2582 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2583 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2584 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2585 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2586 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2587 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2588 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2589 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2590 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2591 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2592 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2593 assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2594 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2595 assert_eq!(
2596 ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2597 BTreeMap::default(),
2598 i_slint_compiler::langtype::StructName::None
2599 )))),
2600 ValueType::Struct
2601 );
2602 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2603}
2604
2605#[test]
2606fn test_multi_components() {
2607 i_slint_backend_testing::init_no_event_loop();
2608 let result = spin_on::spin_on(
2609 Compiler::default().build_from_source(
2610 r#"
2611 export struct Settings {
2612 string_value: string,
2613 }
2614 export global ExpGlo { in-out property <int> test: 42; }
2615 component Common {
2616 in-out property <Settings> settings: { string_value: "Hello", };
2617 }
2618 export component Xyz inherits Window {
2619 in-out property <int> aaa: 8;
2620 }
2621 export component Foo {
2622
2623 in-out property <int> test: 42;
2624 c := Common {}
2625 }
2626 export component Bar inherits Window {
2627 in-out property <int> blah: 78;
2628 c := Common {}
2629 }
2630 "#
2631 .into(),
2632 PathBuf::from("hello.slint"),
2633 ),
2634 );
2635
2636 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2637 let mut components = result.component_names().collect::<Vec<_>>();
2638 components.sort();
2639 assert_eq!(components, vec!["Bar", "Xyz"]);
2640 let diag = result.diagnostics().collect::<Vec<_>>();
2641 assert_eq!(diag.len(), 1);
2642 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2643 assert_eq!(
2644 diag[0].message(),
2645 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2646 );
2647
2648 let comp1 = result.component("Xyz").unwrap();
2649 assert_eq!(comp1.name(), "Xyz");
2650 let instance1a = comp1.create().unwrap();
2651 let comp2 = result.component("Bar").unwrap();
2652 let instance2 = comp2.create().unwrap();
2653 let instance1b = comp1.create().unwrap();
2654
2655 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2657 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2658 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2659 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2660 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2661
2662 assert!(result.component("Settings").is_none());
2663 assert!(result.component("Foo").is_none());
2664 assert!(result.component("Common").is_none());
2665 assert!(result.component("ExpGlo").is_none());
2666 assert!(result.component("xyz").is_none());
2667}
2668
2669#[cfg(all(test, feature = "internal-highlight"))]
2670fn compile(code: &str) -> (ComponentInstance, SourcePath) {
2671 i_slint_backend_testing::init_no_event_loop();
2672 let mut compiler = Compiler::default();
2673 compiler.set_style("fluent".into());
2674 let path = SourcePath::new("/tmp/test.slint");
2675
2676 let compile_result = spin_on::spin_on(compiler.build_from_source_path(
2677 Some(code.to_string()),
2678 path.clone(),
2679 i_slint_core::InternalToken,
2680 ));
2681
2682 for d in &compile_result.diagnostics {
2683 eprintln!("{d}");
2684 }
2685
2686 assert!(!compile_result.has_errors());
2687
2688 let definition = compile_result.components().next().unwrap();
2689 let instance = definition.create().unwrap();
2690
2691 (instance, path)
2692}
2693
2694#[cfg(feature = "internal-highlight")]
2695#[test]
2696fn test_element_node_at_source_code_position() {
2697 let code = r#"
2698component Bar1 {}
2699
2700component Foo1 {
2701}
2702
2703export component Foo2 inherits Window {
2704 Bar1 {}
2705 Foo1 {}
2706}"#;
2707
2708 let (handle, path) = compile(code);
2709
2710 for i in 0..code.len() as u32 {
2711 let elements = handle.element_node_at_source_code_position(&path, i);
2712 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2713 match i {
2714 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()),
2720 }
2721 }
2722}
2723
2724#[cfg(feature = "internal-highlight")]
2728#[test]
2729fn test_component_positions_instances_and_repeaters() {
2730 use i_slint_core::graphics::euclid;
2731 let code = r#"
2732component MyBox inherits Rectangle {
2733 width: 50px;
2734 height: 50px;
2735}
2736
2737export component Foo3 inherits Window {
2738 width: 400px;
2739 height: 400px;
2740 b1 := MyBox { x: 0px; y: 0px; }
2741 b2 := MyBox { x: 200px; y: 200px; }
2742 for xo in [0, 1, 2]: Rectangle {
2743 x: xo * 10px;
2744 y: 300px;
2745 width: 10px;
2746 height: 10px;
2747 }
2748}"#;
2749
2750 let (handle, path) = compile(code);
2751
2752 let positions_at =
2753 |pattern: &str| handle.component_positions(&path, code.find(pattern).unwrap() as u32);
2754
2755 let b1_rects = positions_at("MyBox { x: 0px");
2757 assert_eq!(b1_rects.len(), 1, "{b1_rects:?}");
2758 assert_eq!(b1_rects[0].rect.origin, euclid::point2(0., 0.));
2759
2760 let b2_rects = positions_at("MyBox { x: 200px");
2761 assert_eq!(b2_rects.len(), 1, "{b2_rects:?}");
2762 assert_eq!(b2_rects[0].rect.origin, euclid::point2(200., 200.));
2763
2764 let def_rects = positions_at("Rectangle {\n width: 50px");
2766 assert_eq!(def_rects.len(), 2, "{def_rects:?}");
2767
2768 let mut row_rects = positions_at("Rectangle {\n x: xo");
2770 row_rects.sort_by(|a, b| a.rect.origin.x.total_cmp(&b.rect.origin.x));
2771 assert_eq!(row_rects.len(), 3, "{row_rects:?}");
2772 for (i, r) in row_rects.iter().enumerate() {
2773 assert_eq!(r.rect.origin, euclid::point2(i as f32 * 10., 300.));
2774 assert_eq!(r.rect.size, euclid::size2(10., 10.));
2775 }
2776
2777 let offset = code.find("Rectangle {\n x: xo").unwrap() as u32;
2780 assert_eq!(handle.component_positions(&path, offset).len(), 3);
2781 assert!(handle.component_positions(&path, code.len() as u32 - 1).is_empty());
2782}
2783
2784#[cfg(feature = "internal-highlight")]
2785#[test]
2786fn component_positions_survive_compilation_result_round_trip() {
2787 use i_slint_core::graphics::euclid;
2788
2789 i_slint_backend_testing::init_no_event_loop();
2790 let code = r#"
2791component Base inherits Rectangle {
2792 width: 50px;
2793 height: 40px;
2794}
2795
2796component Derived inherits Base { }
2797
2798export component App inherits Window {
2799 width: 400px;
2800 height: 300px;
2801 in property <bool> show-conditional: true;
2802 first := Derived { x: 10px; y: 20px; }
2803 second := Derived { x: 200px; y: 100px; }
2804 if root.show-conditional: conditional := Rectangle {
2805 x: 100px;
2806 y: 200px;
2807 width: 20px;
2808 height: 30px;
2809 }
2810 optimized := Rectangle {
2811 x: 300px;
2812 y: 10px;
2813 width: 30px;
2814 height: 20px;
2815 background: red;
2816 redundant := Rectangle { }
2817 }
2818 for column in [0, 1]: Derived {
2819 x: column * 60px;
2820 y: 250px;
2821 }
2822 for column in [0, 1]: Derived {
2823 x: 150px + column * 60px;
2824 y: 250px;
2825 }
2826}
2827"#;
2828 let path = PathBuf::from("/virtual/round-trip.slint");
2829 let result = spin_on::spin_on(Compiler::default().build_from_source(code.into(), path.clone()));
2830 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
2831 let result = CompilationResult::from(result.into_send());
2832 let instance = result.component("App").unwrap().create().unwrap();
2833
2834 let positions_at = |pattern: &str, inside_pattern: usize| {
2835 let offset = code.find(pattern).unwrap() + inside_pattern;
2836 instance.component_positions(&SourcePath::new(&path), offset as u32)
2837 };
2838
2839 let first = positions_at("Derived { x: 10px", 2);
2840 assert_eq!(first.len(), 1, "{first:?}");
2841 assert_eq!(first[0].rect.origin, euclid::point2(10., 20.));
2842 let second = positions_at("Derived { x: 200px", 2);
2843 assert_eq!(second.len(), 1, "{second:?}");
2844 assert_eq!(second[0].rect.origin, euclid::point2(200., 100.));
2845
2846 let definition = positions_at("Rectangle {\n width: 50px", 3);
2847 assert_eq!(definition.len(), 6, "{definition:?}");
2848
2849 let conditional_offset = code.find("Rectangle {\n x: 100px").unwrap() as u32 + 4;
2850 let conditional = instance.component_positions(&SourcePath::new(&path), conditional_offset);
2851 assert_eq!(conditional.len(), 1, "{conditional:?}");
2852 assert_eq!(conditional[0].rect.origin, euclid::point2(100., 200.));
2853
2854 let optimized = positions_at("Rectangle {\n x: 300px", 3);
2855 let redundant = positions_at("Rectangle { }", 3);
2856 assert_eq!(optimized.len(), 1, "{optimized:?}");
2857 assert_eq!(redundant.len(), 1, "{redundant:?}");
2858 assert_eq!(redundant[0].rect, optimized[0].rect);
2859
2860 let assert_repeated_positions = |mut positions: Vec<crate::highlight::HighlightedRect>,
2861 expected_x_positions| {
2862 positions.sort_by(|left, right| left.rect.origin.x.total_cmp(&right.rect.origin.x));
2863 assert_eq!(positions.len(), 2, "{positions:?}");
2864 for (geometry, expected_x) in positions.iter().zip(expected_x_positions) {
2865 assert_eq!(geometry.rect.origin, euclid::point2(expected_x, 250.));
2866 }
2867 };
2868 for (pattern, expected_x_positions) in
2869 [("Derived {\n x: column", [0., 60.]), ("Derived {\n x: 150px", [150., 210.])]
2870 {
2871 assert_repeated_positions(positions_at(pattern, 2), expected_x_positions);
2872 }
2873}
2874
2875#[cfg(feature = "internal-highlight")]
2876#[test]
2877fn component_positions_resolve_imported_sources_after_round_trip() {
2878 use i_slint_core::graphics::euclid;
2879
2880 i_slint_backend_testing::init_no_event_loop();
2881 let imported_code = r#"
2882export component Imported inherits Rectangle {
2883 width: 40px;
2884 height: 30px;
2885}
2886"#;
2887 let main_code = r#"
2888import { Imported } from "lib.slint";
2889
2890export component App inherits Window {
2891 width: 200px;
2892 height: 200px;
2893 Imported { x: 25px; y: 35px; }
2894}
2895"#;
2896 let main_path = PathBuf::from("/virtual/main.slint");
2897 let imported_path = PathBuf::from("/virtual/lib.slint");
2898 let mut compiler = Compiler::default();
2899 compiler.set_file_loader({
2900 let imported_path = imported_path.clone();
2901 move |path| {
2902 let source = (path == imported_path).then(|| Ok(imported_code.to_owned()));
2903 Box::pin(core::future::ready(source))
2904 }
2905 });
2906 let result = spin_on::spin_on(compiler.build_from_source(main_code.into(), main_path.clone()));
2907 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
2908 let result = CompilationResult::from(result.into_send());
2909 let instance = result.component("App").unwrap().create().unwrap();
2910
2911 for (path, code, pattern) in [
2912 (&main_path, main_code, "Imported { x: 25px"),
2913 (&imported_path, imported_code, "Rectangle"),
2914 ] {
2915 let offset = code.find(pattern).unwrap() as u32;
2916 let positions = instance.component_positions(&SourcePath::new(path), offset);
2917 assert_eq!(positions.len(), 1, "{positions:?}");
2918 assert_eq!(positions[0].rect.origin, euclid::point2(25., 35.));
2919 assert_eq!(positions[0].rect.size, euclid::size2(40., 30.));
2920 }
2921}
2922
2923#[cfg(feature = "internal-highlight")]
2924#[test]
2925fn inlined_repeated_source_resolves_each_repeater_once() {
2926 use i_slint_compiler::diagnostics::BuildDiagnostics;
2927 use i_slint_compiler::generator::OutputFormat;
2928 use i_slint_core::graphics::euclid;
2929
2930 i_slint_backend_testing::init_no_event_loop();
2931 let code = r#"
2932component RepeatedBox inherits Rectangle {
2933 width: 60px;
2934 height: 20px;
2935 for value in [0, 1]: Rectangle {
2936 x: value * 20px;
2937 y: 0px;
2938 width: 10px;
2939 height: 10px;
2940 }
2941}
2942
2943export component App inherits Window {
2944 width: 200px;
2945 height: 100px;
2946 first := RepeatedBox { x: 10px; y: 20px; }
2947 second := RepeatedBox { x: 100px; y: 20px; }
2948}
2949"#;
2950 let path = SourcePath::new("/virtual/inlined-repeaters.slint");
2951 let mut diagnostics = BuildDiagnostics::default();
2952 let syntax_node =
2953 i_slint_compiler::parser::parse(code.into(), Some(path.clone()), &mut diagnostics);
2954 let mut compiler_configuration =
2955 i_slint_compiler::CompilerConfiguration::new(OutputFormat::Interpreter);
2956 compiler_configuration.debug_info = true;
2957 compiler_configuration.inline_all_elements = true;
2958 let (document, diagnostics, _) = spin_on::spin_on(i_slint_compiler::compile_syntax_node(
2959 syntax_node,
2960 diagnostics,
2961 compiler_configuration.clone(),
2962 ));
2963 assert!(!diagnostics.has_errors(), "{:?}", diagnostics.to_string_vec());
2964 let definition = crate::component::build_from_document(
2965 &document,
2966 &compiler_configuration,
2967 Default::default(),
2968 Default::default(),
2969 AnimationMode::Running,
2970 )
2971 .into_iter()
2972 .next()
2973 .expect("component definition");
2974 let definition = ComponentDefinition { inner: Rc::new(definition) };
2975
2976 let repeated_offset = code.find("Rectangle {\n x: value").unwrap();
2977 let matching_repeated_elements = definition
2978 .inner
2979 .compilation_unit
2980 .sub_components
2981 .iter()
2982 .flat_map(|sub_component| sub_component.debug_info.iter())
2983 .flat_map(|debug_info| debug_info.repeated_elements.iter())
2984 .filter(|source_location| {
2985 source_location
2986 .source_file
2987 .as_ref()
2988 .is_some_and(|source_file| source_file.path() == &path)
2989 && source_location.span.offset == repeated_offset
2990 })
2991 .count();
2992 assert_eq!(matching_repeated_elements, 2);
2993
2994 let instance = definition.create().unwrap();
2995 let mut positions = instance.component_positions(&path, repeated_offset as u32 + 3);
2996 positions.sort_by(|left, right| left.rect.origin.x.total_cmp(&right.rect.origin.x));
2997 assert_eq!(positions.len(), 4, "{positions:?}");
2998 for (geometry, expected_x) in positions.iter().zip([10., 30., 100., 120.]) {
2999 assert_eq!(geometry.rect.origin, euclid::point2(expected_x, 20.));
3000 }
3001}
3002
3003#[cfg(test)]
3004mod project_file_tests {
3005
3006 use super::Compiler;
3007 use crate::prelude::*;
3008 use i_slint_compiler::project_file::FILE_NAME;
3009 use std::path::Path;
3010
3011 fn with_project(project: &str, f: impl FnOnce(&Path)) {
3012 let directory = tempfile::TempDir::new().unwrap();
3013 let root = std::fs::canonicalize(directory.path()).unwrap();
3014 std::fs::write(root.join(FILE_NAME), project).unwrap();
3015 f(&root);
3016 }
3017
3018 fn compile(root: &Path, source: &str) -> super::CompilationResult {
3019 let main = root.join("main.slint");
3020 std::fs::write(&main, source).unwrap();
3021 spin_on::spin_on(Compiler::default().build_from_path(root))
3022 }
3023
3024 #[test]
3025 #[allow(deprecated)]
3026 fn missing_source_files_have_no_line_or_column() {
3027 with_project(r#"{"slint-edition":"1.19"}"#, |root| {
3028 let source = root.join("missing.slint");
3029 let result = spin_on::spin_on(Compiler::default().build_from_path(&source));
3030 assert!(result.has_errors());
3031 let mut compiler = super::ComponentCompiler::new();
3032 assert!(spin_on::spin_on(compiler.build_from_path(&source)).is_none());
3033 for diagnostics in
3034 [result.diagnostics().collect::<Vec<_>>(), compiler.diagnostics().clone()]
3035 {
3036 assert_eq!(diagnostics.len(), 1);
3037 assert!(diagnostics[0].message().starts_with("Could not load"));
3038 assert_eq!(diagnostics[0].source_file(), Some(source.as_path()));
3039 assert_eq!(diagnostics[0].line_column(), (0, 0));
3040 }
3041 });
3042 }
3043
3044 #[cfg(feature = "internal")]
3045 fn compile_source(
3046 compiler: &Compiler,
3047 path: super::SourcePath,
3048 static_compilation: bool,
3049 source: &str,
3050 ) -> super::CompilationResult {
3051 let source = source.into();
3052 if static_compilation {
3053 spin_on::spin_on(compiler.build_static_from_source(
3054 Some(source),
3055 path,
3056 i_slint_core::InternalToken,
3057 ))
3058 } else {
3059 spin_on::spin_on(compiler.build_from_source_path(
3060 Some(source),
3061 path,
3062 i_slint_core::InternalToken,
3063 ))
3064 }
3065 }
3066
3067 #[cfg(feature = "internal")]
3068 #[test]
3069 fn public_file_loader_only_receives_imports() {
3070 let directory = tempfile::TempDir::new().unwrap();
3071 let main = directory.path().join("main.slint");
3072 let source =
3073 r#"import { Shared } from "lib.slint"; export component Main inherits Shared {}"#;
3074 std::fs::write(&main, source).unwrap();
3075 std::fs::write(directory.path().join(FILE_NAME), r#"{"slint-edition":"1.19"}"#).unwrap();
3076 for remote in [false, true] {
3077 let calls = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
3078 let loader_calls = calls.clone();
3079 let mut compiler = Compiler::default();
3080 compiler.set_file_loader(move |path| {
3081 loader_calls.borrow_mut().push(path.to_path_buf());
3082 let source = if path.file_name() == Some(std::ffi::OsStr::new("lib.slint")) {
3083 "export component Shared inherits Window {}"
3084 } else {
3085 ""
3086 }
3087 .to_string();
3088 Box::pin(async move { Some(Ok(source)) })
3089 });
3090 let result = if remote {
3091 spin_on::spin_on(compiler.build_from_source_path(
3092 Some(source.into()),
3093 super::SourcePath::new("https://example.invalid/ui/main.slint"),
3094 i_slint_core::InternalToken,
3095 ))
3096 } else {
3097 spin_on::spin_on(compiler.build_from_path(&main))
3098 };
3099 assert!(!result.has_errors(), "{result:?}");
3100 assert!(result.component("Main").is_some());
3101 let calls = calls.borrow();
3102 assert_eq!(calls.len(), 1, "{calls:?}");
3103 assert_eq!(calls[0].file_name(), Some(std::ffi::OsStr::new("lib.slint")));
3104 }
3105 }
3106
3107 #[cfg(feature = "internal")]
3108 #[test]
3109 fn directory_compilation_reads_its_entry_through_the_loader() {
3110 let directory = tempfile::TempDir::new().unwrap();
3111 let manifest = directory.path().join(FILE_NAME);
3112 let entry = directory.path().join("main.slint");
3113 std::fs::write(&manifest, r#"{"slint-edition":"1.19","main":"main.slint"}"#).unwrap();
3114 let loader_entry = entry.clone();
3115 let mut compiler = Compiler::default();
3116 compiler.set_project_file_loader(
3117 std::rc::Rc::new(move |path| {
3118 let contents = if path.as_native_path() == Some(loader_entry.as_path()) {
3119 Ok("export component Main inherits Window {}".into())
3120 } else {
3121 Err(std::io::ErrorKind::NotFound.into())
3122 };
3123 Box::pin(async move { Some(contents) })
3124 }),
3125 i_slint_core::InternalToken,
3126 );
3127 let result = spin_on::spin_on(compiler.build_from_path(directory.path()));
3128 assert!(!result.has_errors(), "{result:?}");
3129 assert!(result.component("Main").is_some());
3130 for dependency in [&manifest, &entry] {
3131 assert!(result.watch_paths.contains(&super::SourcePath::new(dependency)));
3132 }
3133 }
3134
3135 #[cfg(feature = "internal")]
3136 #[test]
3137 fn source_compilers_read_current_loader_settings_and_replace_overrides() {
3138 let source = "export component Main inherits Window { ComponentContainer {} }";
3139 use i_slint_compiler::{project_file::Overrides, source_path::SourcePath};
3140 for path in [
3141 SourcePath::new("/virtual/main.slint"),
3142 SourcePath::new("https://example.invalid/ui/main.slint"),
3143 ] {
3144 for static_compilation in [false, true] {
3145 let manifest = path.parent().join(FILE_NAME).unwrap();
3146 let current_experimental = std::rc::Rc::new(std::cell::RefCell::new("[]"));
3147 let mut compiler = Compiler::default();
3148 compiler.set_project_root(Some(path.parent()), i_slint_core::InternalToken);
3149 let loader_experimental = current_experimental.clone();
3150 let loader_manifest = manifest.clone();
3151 compiler.project_file_loader = Some(std::rc::Rc::new(move |path| {
3152 let contents = if path == loader_manifest {
3153 Ok(format!(
3154 r#"{{"slint-edition":"1.19","experimental-features":{}}}"#,
3155 loader_experimental.borrow()
3156 ))
3157 } else {
3158 Err(std::io::ErrorKind::NotFound.into())
3159 };
3160 Box::pin(async move { Some(contents) })
3161 }));
3162 assert!(
3163 compile_source(&compiler, path.clone(), static_compilation, source)
3164 .has_errors()
3165 );
3166 compiler.set_overrides(
3167 Overrides {
3168 style: Some("fluent".into()),
3169 project: i_slint_compiler::project_file::ProjectFileData {
3170 experimental_features: Some(
3171 i_slint_compiler::ExperimentalFeature::ComponentContainer.into(),
3172 ),
3173 ..Default::default()
3174 },
3175 ..Default::default()
3176 },
3177 i_slint_core::InternalToken,
3178 );
3179 compiler.set_include_paths(vec!["previous-include".into()]);
3180 compiler.set_library_paths(std::collections::HashMap::from([(
3181 "previous".into(),
3182 "previous-library".into(),
3183 )]));
3184 assert!(
3185 !compile_source(&compiler, path.clone(), static_compilation, source)
3186 .has_errors()
3187 );
3188 compiler.set_overrides(Overrides::default(), i_slint_core::InternalToken);
3189 assert!(compiler.style().is_none());
3190 assert!(compiler.include_paths().is_empty());
3191 assert!(compiler.library_paths().is_empty());
3192 assert!(
3193 compile_source(&compiler, path.clone(), static_compilation, source)
3194 .has_errors()
3195 );
3196 *current_experimental.borrow_mut() = r#"["component-container"]"#;
3197 let result = compile_source(&compiler, path.clone(), static_compilation, source);
3198 assert!(!result.has_errors(), "{result:?}");
3199 assert!(result.watch_paths.contains(&manifest));
3200 }
3201 }
3202 }
3203
3204 #[cfg(feature = "internal")]
3205 #[test]
3206 fn attempted_manifests_are_dependencies_even_when_missing_or_invalid() {
3207 let source = "export component Main inherits Window {}";
3208 use super::SourcePath;
3209 let path = SourcePath::new("https://example.invalid/ui/main.slint");
3210 let manifest = path.parent().join(FILE_NAME).unwrap();
3211 for invalid in [false, true] {
3212 for static_compilation in [false, true] {
3213 let mut compiler = Compiler::default();
3214 compiler.set_project_root(Some(path.parent()), i_slint_core::InternalToken);
3215 compiler.project_file_loader = Some(std::rc::Rc::new(move |_| {
3216 Box::pin(async move {
3217 Some(if invalid {
3218 Ok("{".into())
3219 } else {
3220 Err(std::io::ErrorKind::NotFound.into())
3221 })
3222 })
3223 }));
3224 let result = compile_source(&compiler, path.clone(), static_compilation, source);
3225 assert_eq!(result.has_errors(), invalid, "{result:?}");
3226 assert!(result.watch_paths.contains(&manifest));
3227 }
3228 }
3229 }
3230
3231 #[cfg(feature = "internal")]
3232 #[test]
3233 fn native_compilation_does_not_watch_missing_ancestor_manifests() {
3234 let directory = tempfile::TempDir::new().unwrap();
3235 let manifest = directory.path().join(FILE_NAME);
3236 let main = directory.path().join("main.slint");
3237 let compiler = Compiler::default();
3238 let source = "export component Main inherits Window {}";
3239 for contents in [None, Some(r#"{"slint-edition":"1.19"}"#), Some("{")] {
3240 if let Some(contents) = contents {
3241 std::fs::write(&manifest, contents).unwrap();
3242 }
3243 let result = spin_on::spin_on(compiler.build_from_source(source.into(), main.clone()));
3244 assert!(!result.has_errors(), "{result:?}");
3245 let expected_paths = vec![super::SourcePath::new(&main)];
3246 let native_paths = result
3247 .watch_paths
3248 .iter()
3249 .filter(|path| path.as_native_path().is_some())
3250 .collect::<Vec<_>>();
3251 assert_eq!(native_paths.len(), expected_paths.len(), "{native_paths:?}");
3252 for path in expected_paths {
3253 assert!(result.watch_paths.contains(&path));
3254 }
3255 }
3256 }
3257
3258 #[cfg(windows)]
3259 #[test]
3260 fn a_windows_root_relative_manifest_source_is_an_error() {
3261 let result = spin_on::spin_on(
3262 Compiler::default()
3263 .build_from_source("{}".into(), r"\project\slint-project.json".into()),
3264 );
3265 assert!(result.has_errors(), "{result:?}");
3266 assert_eq!(
3267 result
3268 .diagnostics()
3269 .map(|diagnostic| diagnostic.message().to_string())
3270 .collect::<Vec<_>>(),
3271 [format!(
3272 "A `{FILE_NAME}` cannot be compiled directly; pass its directory instead ({})",
3273 Path::new(r"\project\slint-project.json").parent().unwrap().display()
3274 )]
3275 );
3276 assert_eq!(result.components().count(), 0);
3277 }
3278
3279 #[test]
3280 fn a_relative_manifest_source_is_an_error() {
3281 let current_directory = std::env::current_dir().unwrap();
3282 let directory = tempfile::tempdir_in(¤t_directory).unwrap();
3283 let manifest = directory.path().join(FILE_NAME);
3284 std::fs::write(&manifest, "{").unwrap();
3285 let relative_manifest = manifest.strip_prefix(¤t_directory).unwrap().to_path_buf();
3286 let result =
3287 spin_on::spin_on(Compiler::default().build_from_source("{}".into(), relative_manifest));
3288 assert!(result.has_errors(), "{result:?}");
3289 assert_eq!(
3290 result
3291 .diagnostics()
3292 .map(|diagnostic| diagnostic.message().to_string())
3293 .collect::<Vec<_>>(),
3294 [format!(
3295 "A `{FILE_NAME}` cannot be compiled directly; pass its directory instead ({})",
3296 manifest.strip_prefix(¤t_directory).unwrap().parent().unwrap().display()
3297 )]
3298 );
3299 assert_eq!(result.components().count(), 0);
3300 }
3301
3302 #[cfg(feature = "internal")]
3303 #[test]
3304 fn internal_source_compilers_load_only_the_explicit_root() {
3305 use super::SourcePath;
3306 let source = "export component Main inherits Window {}";
3307 for root in [
3308 SourcePath::new("/virtual/project"),
3309 SourcePath::new("https://example.invalid/project/"),
3310 ] {
3311 let main = root.join("ui/main.slint").unwrap();
3312 let manifest = root.join(FILE_NAME).unwrap();
3313 for manifest_contents in
3314 [r#"{"slint-edition":"1.19"}"#, r#"{"slint-edition":"1.19","main":"other.slint"}"#]
3315 {
3316 for static_compilation in [false, true] {
3317 let requested = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
3318 let loader_requested = requested.clone();
3319 let loader_manifest = manifest.clone();
3320 let mut compiler = Compiler::default();
3321 compiler.set_project_root(Some(root.clone()), i_slint_core::InternalToken);
3322 compiler.set_project_file_loader(
3323 std::rc::Rc::new(move |path| {
3324 loader_requested.borrow_mut().push(path.clone());
3325 let contents = if path == loader_manifest {
3326 Ok(manifest_contents.into())
3327 } else {
3328 Ok("{".into())
3329 };
3330 Box::pin(async move { Some(contents) })
3331 }),
3332 i_slint_core::InternalToken,
3333 );
3334 let result =
3335 compile_source(&compiler, main.clone(), static_compilation, source);
3336 assert!(!result.has_errors(), "{result:?}");
3337 assert!(result.component("Main").is_some());
3338 assert!(result.watch_paths.contains(&manifest));
3339 assert_eq!(*requested.borrow(), vec![manifest.clone()]);
3340 }
3341 }
3342 }
3343 }
3344
3345 #[cfg(feature = "internal")]
3346 #[test]
3347 fn explicit_root_switch_and_clear_replace_project_settings() {
3348 let source = "export component Main inherits Window { ComponentContainer {} }";
3349 let main = super::SourcePath::new("https://example.invalid/ui/main.slint");
3350 let disabled_root = super::SourcePath::new("https://example.invalid/disabled/");
3351 let enabled_root = super::SourcePath::new("https://example.invalid/enabled/");
3352 let enabled_manifest = enabled_root.join(FILE_NAME).unwrap();
3353 let mut compiler = Compiler::default();
3354 compiler.set_project_file_loader(
3355 std::rc::Rc::new(move |path| {
3356 let contents = if path == enabled_manifest {
3357 Ok(r#"{"slint-edition":"1.19","experimental-features":["component-container"]}"#.into())
3358 } else {
3359 Ok(r#"{"slint-edition":"1.19","experimental-features":[]}"#.into())
3360 };
3361 Box::pin(async move { Some(contents) })
3362 }),
3363 i_slint_core::InternalToken,
3364 );
3365 for (root, has_errors) in
3366 [(Some(disabled_root), true), (Some(enabled_root), false), (None, true)]
3367 {
3368 compiler.set_project_root(root, i_slint_core::InternalToken);
3369 let result = compile_source(&compiler, main.clone(), false, source);
3370 assert_eq!(result.has_errors(), has_errors, "{result:?}");
3371 }
3372 }
3373
3374 #[test]
3375 fn the_project_file_include_paths_are_used() {
3376 with_project(
3377 r#"{ "slint-edition": "1.19", "main": "main.slint", "include-paths": ["include"] }"#,
3378 |root| {
3379 let include = root.join("include");
3380 std::fs::create_dir_all(&include).unwrap();
3381 std::fs::write(include.join("shared.slint"), "export component Shared { }")
3382 .unwrap();
3383
3384 let result = compile(
3385 root,
3386 r#"import { Shared } from "shared.slint";
3387 export component Main inherits Window { Shared { } }"#,
3388 );
3389 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
3390 },
3391 );
3392 }
3393
3394 #[test]
3395 fn explicit_empty_include_paths_win_for_both_interpreter_compilers() {
3396 with_project(r#"{"slint-edition":"1.19","include-paths":["include"]}"#, |root| {
3397 let include = root.join("include");
3398 std::fs::create_dir_all(&include).unwrap();
3399 std::fs::write(include.join("shared.slint"), "export component Shared {}").unwrap();
3400 let source = r#"import { Shared } from "shared.slint";
3401 export component Main inherits Window { Shared {} }"#;
3402 let main = root.join("main.slint");
3403 std::fs::write(&main, source).unwrap();
3404 let mut compiler = Compiler::default();
3405 compiler.set_include_paths(vec![]);
3406 assert!(compiler.include_paths().is_empty());
3407 let result = spin_on::spin_on(compiler.build_from_path(&main));
3408 assert!(result.has_errors());
3409 assert!(
3410 result
3411 .diagnostics()
3412 .any(|diagnostic| diagnostic.message().contains("shared.slint"))
3413 );
3414
3415 #[allow(deprecated)]
3416 let mut compiler = super::ComponentCompiler::new();
3417 #[allow(deprecated)]
3418 compiler.set_include_paths(vec![]);
3419 #[allow(deprecated)]
3420 let result = spin_on::spin_on(compiler.build_from_path(&main));
3421 assert!(result.is_none());
3422 #[allow(deprecated)]
3423 let missing_import = compiler
3424 .diagnostics()
3425 .iter()
3426 .any(|diagnostic| diagnostic.message().contains("shared.slint"));
3427 assert!(missing_import);
3428 });
3429 }
3430
3431 #[cfg(feature = "internal")]
3432 #[test]
3433 fn explicit_empty_include_paths_apply_to_source_path_compilation() {
3434 with_project(r#"{ "slint-edition": "1.19" }"#, |root| {
3435 let include_directory = root.join("include");
3436 std::fs::create_dir(&include_directory).unwrap();
3437 std::fs::write(include_directory.join("shared.slint"), "export component Shared {}")
3438 .unwrap();
3439 let source =
3440 "import { Shared } from \"shared.slint\"; export component Main inherits Shared {}";
3441 for path in [
3442 super::SourcePath::new(root.join("main.slint")),
3443 super::SourcePath::new("https://example.invalid/main.slint"),
3444 ] {
3445 for static_compilation in [false, true] {
3446 let mut compiler = Compiler::default();
3447 compiler.compiler_configuration(i_slint_core::InternalToken).include_paths =
3448 vec![include_directory.clone()];
3449 compiler.set_include_paths(Vec::new());
3450 let result = if static_compilation {
3451 spin_on::spin_on(compiler.build_static_from_source(
3452 Some(source.into()),
3453 path.clone(),
3454 i_slint_core::InternalToken,
3455 ))
3456 } else {
3457 spin_on::spin_on(compiler.build_from_source_path(
3458 Some(source.into()),
3459 path.clone(),
3460 i_slint_core::InternalToken,
3461 ))
3462 };
3463 assert!(result.has_errors());
3464 assert!(
3465 result
3466 .diagnostics()
3467 .any(|diagnostic| diagnostic.message().contains("shared.slint"))
3468 );
3469 }
3470 }
3471 });
3472 }
3473
3474 #[test]
3475 fn an_invalid_project_file_is_reported() {
3476 with_project("{", |root| {
3477 let result = compile(root, "export component Main inherits Window { }");
3478 assert!(result.has_errors());
3479 let messages =
3480 result.diagnostics().map(|d| d.message().to_string()).collect::<Vec<_>>();
3481 assert!(
3482 messages.iter().any(|message| message.contains(FILE_NAME)),
3483 "expected the project file to be named: {messages:?}"
3484 );
3485 });
3486 }
3487
3488 #[test]
3490 fn the_deprecated_compiler_reads_the_project_file() {
3491 with_project(
3492 r#"{ "slint-edition": "1.19", "main": "main.slint", "include-paths": ["include"] }"#,
3493 |root| {
3494 std::fs::create_dir(root.join("include")).unwrap();
3495 std::fs::write(root.join("include/shared.slint"), "export component Shared {}")
3496 .unwrap();
3497 let main = root.join("main.slint");
3498 std::fs::write(&main, r#"import { Shared } from "shared.slint"; export component Main inherits Window { Shared {} }"#).unwrap();
3499
3500 #[allow(deprecated)]
3501 let mut compiler = super::ComponentCompiler::new();
3502 #[allow(deprecated)]
3503 let definition = spin_on::spin_on(compiler.build_from_path(root));
3504 assert!(definition.is_some());
3505 },
3506 );
3507 }
3508
3509 #[test]
3510 fn a_project_directory_compiles_its_main_file() {
3511 with_project(r#"{ "slint-edition": "1.19", "main": "ui/main.slint" }"#, |root| {
3512 std::fs::create_dir_all(root.join("ui")).unwrap();
3513 std::fs::write(root.join("ui/main.slint"), "export component Main inherits Window { }")
3514 .unwrap();
3515
3516 let result = spin_on::spin_on(Compiler::default().build_from_path(root));
3517 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
3518 assert!(result.component_names().any(|name| name == "Main"));
3519 });
3520 }
3521
3522 #[test]
3523 fn a_project_directory_without_an_entry_is_an_error() {
3524 with_project(r#"{"slint-edition":"1.19"}"#, |root| {
3525 let result = spin_on::spin_on(Compiler::default().build_from_path(root));
3526 assert!(result.has_errors());
3527 assert!(
3528 result
3529 .diagnostics()
3530 .any(|diagnostic| diagnostic.message().contains("has no 'main' to compile"))
3531 );
3532 assert_eq!(result.components().count(), 0);
3533 });
3534 }
3535
3536 #[test]
3537 fn a_project_file_path_is_an_error() {
3538 with_project(r#"{"slint-edition": "1.19", "main":"main.slint"}"#, |root| {
3539 std::fs::write(root.join("main.slint"), "export component Main inherits Window { }")
3540 .unwrap();
3541 let result =
3542 spin_on::spin_on(Compiler::default().build_from_path(root.join(FILE_NAME)));
3543 assert!(result.has_errors());
3544 assert_eq!(
3545 result
3546 .diagnostics()
3547 .map(|diagnostic| diagnostic.message().to_string())
3548 .collect::<Vec<_>>(),
3549 [format!(
3550 "A `{FILE_NAME}` cannot be compiled directly; pass its directory instead ({})",
3551 root.display()
3552 )]
3553 );
3554 });
3555 }
3556
3557 #[test]
3558 fn the_deprecated_compiler_compiles_the_main_file_of_a_project_directory() {
3559 with_project(r#"{ "slint-edition": "1.19", "main": "main.slint" }"#, |root| {
3560 std::fs::write(root.join("main.slint"), "export component Main inherits Window { }")
3561 .unwrap();
3562
3563 #[allow(deprecated)]
3564 let mut compiler = super::ComponentCompiler::new();
3565 #[allow(deprecated)]
3566 let definition = spin_on::spin_on(compiler.build_from_path(root));
3567 assert_eq!(
3568 definition.map(|definition| definition.name().to_string()),
3569 Some("Main".into())
3570 );
3571 });
3572 }
3573
3574 #[test]
3575 fn no_project_file_keeps_the_defaults() {
3576 let directory = tempfile::TempDir::new().unwrap();
3577 let root = std::fs::canonicalize(directory.path()).unwrap();
3578 let main = root.join("main.slint");
3579 std::fs::write(&main, "export component Main inherits Window { }").unwrap();
3580 let result = spin_on::spin_on(Compiler::default().build_from_path(&main));
3581 assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
3582 }
3583
3584 #[test]
3585 fn relative_directory_inputs_compile() {
3586 if std::env::var_os("SLINT_INTERPRETER_PROJECT_ROOT_TEST").is_some() {
3587 for input in [".", "ui/.."] {
3588 let result = spin_on::spin_on(Compiler::default().build_from_path(input));
3589 assert!(!result.has_errors(), "{result:?}");
3590 assert!(result.component("Main").is_some());
3591 }
3592 return;
3593 }
3594
3595 let project_directory = tempfile::TempDir::new().unwrap();
3596 std::fs::create_dir(project_directory.path().join("ui")).unwrap();
3597 std::fs::write(
3598 project_directory.path().join(FILE_NAME),
3599 r#"{"slint-edition":"1.19","main":"main.slint"}"#,
3600 )
3601 .unwrap();
3602 std::fs::write(
3603 project_directory.path().join("main.slint"),
3604 "export component Main inherits Window { }",
3605 )
3606 .unwrap();
3607
3608 let output = std::process::Command::new(std::env::current_exe().unwrap())
3609 .current_dir(project_directory.path())
3610 .env("SLINT_INTERPRETER_PROJECT_ROOT_TEST", "1")
3611 .args(["--exact", "api::project_file_tests::relative_directory_inputs_compile"])
3612 .output()
3613 .unwrap();
3614 assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
3615 }
3616}