1use i_slint_compiler::langtype::Type as LangType;
6use i_slint_core::PathData;
7use i_slint_core::component_factory::ComponentFactory;
8#[cfg(feature = "internal")]
9use i_slint_core::component_factory::FactoryContext;
10use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
11use i_slint_core::items::*;
12use i_slint_core::model::{Model, ModelExt, ModelRc};
13use i_slint_core::styled_text::StyledText;
14#[cfg(feature = "internal")]
15use i_slint_core::window::WindowInner;
16use smol_str::SmolStr;
17use std::collections::HashMap;
18use std::future::Future;
19use std::path::{Path, PathBuf};
20use std::rc::Rc;
21#[cfg(test)]
22use std::sync::Arc;
23
24#[doc(inline)]
25pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
26
27pub use i_slint_backend_selector::api::*;
28pub use i_slint_core::api::*;
29
30pub use i_slint_compiler::DefaultTranslationContext;
33
34#[derive(Debug, Copy, Clone, PartialEq)]
37#[repr(i8)]
38#[non_exhaustive]
39pub enum ValueType {
40 Void,
42 Number,
44 String,
46 Bool,
48 Model,
50 Struct,
52 Brush,
54 Image,
56 #[doc(hidden)]
58 Other = -1,
59}
60
61impl From<LangType> for ValueType {
62 fn from(ty: LangType) -> Self {
63 match ty {
64 LangType::Float32
65 | LangType::Int32
66 | LangType::Duration
67 | LangType::Angle
68 | LangType::PhysicalLength
69 | LangType::LogicalLength
70 | LangType::Percent
71 | LangType::UnitProduct(_) => Self::Number,
72 LangType::String => Self::String,
73 LangType::Color => Self::Brush,
74 LangType::Brush => Self::Brush,
75 LangType::Array(_) => Self::Model,
76 LangType::Bool => Self::Bool,
77 LangType::Struct { .. } => Self::Struct,
78 LangType::Void => Self::Void,
79 LangType::Image => Self::Image,
80 _ => Self::Other,
81 }
82 }
83}
84
85#[derive(Clone, Default)]
97#[non_exhaustive]
98#[repr(u8)]
99pub enum Value {
100 #[default]
103 Void = 0,
104 Number(f64) = 1,
106 String(SharedString) = 2,
108 Bool(bool) = 3,
110 Image(Image) = 4,
112 Model(ModelRc<Value>) = 5,
114 Struct(Struct) = 6,
116 Brush(Brush) = 7,
118 #[doc(hidden)]
119 PathData(PathData) = 8,
121 #[doc(hidden)]
122 EasingCurve(i_slint_core::animations::EasingCurve) = 9,
124 #[doc(hidden)]
125 EnumerationValue(String, String) = 10,
128 #[doc(hidden)]
129 LayoutCache(SharedVector<f32>) = 11,
130 #[doc(hidden)]
131 ComponentFactory(ComponentFactory) = 12,
133 #[doc(hidden)] StyledText(StyledText) = 13,
136 #[doc(hidden)]
137 ArrayOfU16(SharedVector<u16>) = 14,
138 Keys(Keys) = 15,
140 DataTransfer(DataTransfer) = 16,
142 #[doc(hidden)]
143 MouseCursorInner(i_slint_core::cursor::MouseCursorInner) = 17,
145}
146
147impl Value {
148 pub fn value_type(&self) -> ValueType {
150 match self {
151 Value::Void => ValueType::Void,
152 Value::Number(_) => ValueType::Number,
153 Value::String(_) => ValueType::String,
154 Value::Bool(_) => ValueType::Bool,
155 Value::Model(_) => ValueType::Model,
156 Value::Struct(_) => ValueType::Struct,
157 Value::Brush(_) => ValueType::Brush,
158 Value::Image(_) => ValueType::Image,
159 _ => ValueType::Other,
160 }
161 }
162}
163
164impl i_slint_core::rtti::ValueType for Value {}
165
166impl PartialEq for Value {
167 fn eq(&self, other: &Self) -> bool {
168 match self {
169 Value::Void => matches!(other, Value::Void),
170 Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
171 Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
172 Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
173 Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
174 Value::Model(lhs) => {
175 if let Value::Model(rhs) = other {
176 lhs == rhs
177 } else {
178 false
179 }
180 }
181 Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
182 Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
183 Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
184 Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
185 Value::EnumerationValue(lhs_name, lhs_value) => {
186 matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
187 }
188 Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
189 Value::ArrayOfU16(lhs) => matches!(other, Value::ArrayOfU16(rhs) if lhs == rhs),
190 Value::ComponentFactory(lhs) => {
191 matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
192 }
193 Value::StyledText(lhs) => {
194 matches!(other, Value::StyledText(rhs) if lhs == rhs)
195 }
196 Value::Keys(lhs) => {
197 matches!(other, Value::Keys(rhs) if lhs == rhs)
198 }
199 Value::DataTransfer(lhs) => {
200 matches!(other, Value::DataTransfer(rhs) if lhs == rhs)
201 }
202 Value::MouseCursorInner(lhs) => {
203 matches!(other, Value::MouseCursorInner(rhs) if lhs == rhs)
204 }
205 }
206 }
207}
208
209impl std::fmt::Debug for Value {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 match self {
212 Value::Void => write!(f, "Value::Void"),
213 Value::Number(n) => write!(f, "Value::Number({n:?})"),
214 Value::String(s) => write!(f, "Value::String({s:?})"),
215 Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
216 Value::Image(i) => write!(f, "Value::Image({i:?})"),
217 Value::Model(m) => {
218 write!(f, "Value::Model(")?;
219 f.debug_list().entries(m.iter()).finish()?;
220 write!(f, "])")
221 }
222 Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
223 Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
224 Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
225 Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
226 Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
227 Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
228 Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
229 Value::StyledText(text) => write!(f, "Value::StyledText({text:?})"),
230 Value::ArrayOfU16(data) => {
231 write!(f, "Value::ArrayOfU16({data:?})")
232 }
233 Value::Keys(ks) => write!(f, "Value::Keys({ks:?})"),
234 Value::DataTransfer(cd) => write!(f, "Value::DataTransfer({cd:?})"),
235 Value::MouseCursorInner(m) => write!(f, "Value::MouseCursor({m:?})"),
236 }
237 }
238}
239
240macro_rules! declare_value_conversion {
249 ( $value:ident => [$($ty:ty),*] ) => {
250 $(
251 impl From<$ty> for Value {
252 fn from(v: $ty) -> Self {
253 Value::$value(v as _)
254 }
255 }
256 impl TryFrom<Value> for $ty {
257 type Error = Value;
258 fn try_from(v: Value) -> Result<$ty, Self::Error> {
259 match v {
260 Value::$value(x) => Ok(x as _),
261 _ => Err(v)
262 }
263 }
264 }
265 )*
266 };
267}
268declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
269declare_value_conversion!(String => [SharedString] );
270declare_value_conversion!(Bool => [bool] );
271declare_value_conversion!(Image => [Image] );
272declare_value_conversion!(Struct => [Struct] );
273declare_value_conversion!(Brush => [Brush] );
274declare_value_conversion!(PathData => [PathData]);
275declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
276declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
277declare_value_conversion!(ComponentFactory => [ComponentFactory] );
278declare_value_conversion!(StyledText => [StyledText] );
279declare_value_conversion!(ArrayOfU16 => [SharedVector<u16>] );
280declare_value_conversion!(Keys => [Keys]);
281declare_value_conversion!(DataTransfer => [DataTransfer]);
282declare_value_conversion!(MouseCursorInner => [i_slint_core::cursor::MouseCursorInner]);
283
284macro_rules! declare_value_struct_conversion {
286 (struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
287 impl From<$name> for Value {
288 fn from($name { $($field),* , .. }: $name) -> Self {
289 let mut struct_ = Struct::default();
290 $(struct_.set_field(stringify!($field).into(), $field.into());)*
291 Value::Struct(struct_)
292 }
293 }
294 impl TryFrom<Value> for $name {
295 type Error = ();
296 fn try_from(v: Value) -> Result<$name, Self::Error> {
297 #[allow(clippy::field_reassign_with_default)]
298 match v {
299 Value::Struct(x) => {
300 type Ty = $name;
301 #[allow(unused)]
302 let mut res: Ty = Ty::default();
303 $(let mut res: Ty = $extra;)?
304 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
305 Ok(res)
306 }
307 _ => Err(()),
308 }
309 }
310 }
311 };
312 ($(
313 $(#[$struct_attr:meta])*
314 $vis:vis struct $Name:ident {
315 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
316 }
317 )*) => {
318 $(
319 impl From<$Name> for Value {
320 fn from(item: $Name) -> Self {
321 let mut struct_ = Struct::default();
322 $(struct_.set_field(stringify!($field).into(), item.$field.into());)*
323 Value::Struct(struct_)
324 }
325 }
326 impl TryFrom<Value> for $Name {
327 type Error = ();
328 fn try_from(v: Value) -> Result<$Name, Self::Error> {
329 #[allow(clippy::field_reassign_with_default)]
330 match v {
331 Value::Struct(x) => {
332 type Ty = $Name;
333 #[allow(unused)]
334 let mut res: Ty = Ty::default();
335 $(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
338 Ok(res)
339 }
340 _ => Err(()),
341 }
342 }
343 }
344 )*
345 };
346}
347
348declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
349declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
350declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
351declare_value_struct_conversion!(struct i_slint_core::api::LogicalSize { width, height });
352declare_value_struct_conversion!(struct i_slint_core::properties::StateInfo { current_state, previous_state, change_time });
353
354i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
355
356macro_rules! declare_value_enum_conversion {
361 ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => { $(
362 impl From<i_slint_core::items::$Name> for Value {
363 fn from(v: i_slint_core::items::$Name) -> Self {
364 Value::EnumerationValue(stringify!($Name).to_owned(), v.to_string())
365 }
366 }
367 impl TryFrom<Value> for i_slint_core::items::$Name {
368 type Error = ();
369 fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
370 use std::str::FromStr;
371 match v {
372 Value::EnumerationValue(enumeration, value) => {
373 if enumeration != stringify!($Name) {
374 return Err(());
375 }
376 i_slint_core::items::$Name::from_str(value.as_str()).map_err(|_| ())
377 }
378 _ => Err(()),
379 }
380 }
381 }
382 )*};
383}
384
385i_slint_common::for_each_enums!(declare_value_enum_conversion);
386
387impl From<i_slint_core::animations::Instant> for Value {
388 fn from(value: i_slint_core::animations::Instant) -> Self {
389 Value::Number(value.0 as _)
390 }
391}
392impl TryFrom<Value> for i_slint_core::animations::Instant {
393 type Error = ();
394 fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
395 match v {
396 Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
397 _ => Err(()),
398 }
399 }
400}
401
402impl From<()> for Value {
403 #[inline]
404 fn from(_: ()) -> Self {
405 Value::Void
406 }
407}
408impl TryFrom<Value> for () {
409 type Error = ();
410 #[inline]
411 fn try_from(_: Value) -> Result<(), Self::Error> {
412 Ok(())
413 }
414}
415
416impl From<Color> for Value {
417 #[inline]
418 fn from(c: Color) -> Self {
419 Value::Brush(Brush::SolidColor(c))
420 }
421}
422impl TryFrom<Value> for Color {
423 type Error = Value;
424 #[inline]
425 fn try_from(v: Value) -> Result<Color, Self::Error> {
426 match v {
427 Value::Brush(Brush::SolidColor(c)) => Ok(c),
428 _ => Err(v),
429 }
430 }
431}
432
433impl From<i_slint_core::lengths::LogicalLength> for Value {
434 #[inline]
435 fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
436 Value::Number(l.get() as _)
437 }
438}
439impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
440 type Error = Value;
441 #[inline]
442 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
443 match v {
444 Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
445 _ => Err(v),
446 }
447 }
448}
449
450impl From<i_slint_core::lengths::LogicalPoint> for Value {
451 #[inline]
452 fn from(pt: i_slint_core::lengths::LogicalPoint) -> Self {
453 Value::Struct(Struct::from_iter([
454 ("x".to_owned(), Value::Number(pt.x as _)),
455 ("y".to_owned(), Value::Number(pt.y as _)),
456 ]))
457 }
458}
459impl TryFrom<Value> for i_slint_core::lengths::LogicalPoint {
460 type Error = Value;
461 #[inline]
462 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalPoint, Self::Error> {
463 match v {
464 Value::Struct(s) => {
465 let x = s
466 .get_field("x")
467 .cloned()
468 .unwrap_or_else(|| Value::Number(0 as _))
469 .try_into()?;
470 let y = s
471 .get_field("y")
472 .cloned()
473 .unwrap_or_else(|| Value::Number(0 as _))
474 .try_into()?;
475 Ok(i_slint_core::lengths::LogicalPoint::new(x, y))
476 }
477 _ => Err(v),
478 }
479 }
480}
481
482impl From<i_slint_core::lengths::LogicalSize> for Value {
483 #[inline]
484 fn from(s: i_slint_core::lengths::LogicalSize) -> Self {
485 Value::Struct(Struct::from_iter([
486 ("width".to_owned(), Value::Number(s.width as _)),
487 ("height".to_owned(), Value::Number(s.height as _)),
488 ]))
489 }
490}
491impl TryFrom<Value> for i_slint_core::lengths::LogicalSize {
492 type Error = Value;
493 #[inline]
494 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalSize, Self::Error> {
495 match v {
496 Value::Struct(s) => {
497 let width = s
498 .get_field("width")
499 .cloned()
500 .unwrap_or_else(|| Value::Number(0 as _))
501 .try_into()?;
502 let height = s
503 .get_field("height")
504 .cloned()
505 .unwrap_or_else(|| Value::Number(0 as _))
506 .try_into()?;
507 Ok(i_slint_core::lengths::LogicalSize::new(width, height))
508 }
509 _ => Err(v),
510 }
511 }
512}
513
514impl From<i_slint_core::lengths::LogicalEdges> for Value {
515 #[inline]
516 fn from(s: i_slint_core::lengths::LogicalEdges) -> Self {
517 Value::Struct(Struct::from_iter([
518 ("left".to_owned(), Value::Number(s.left as _)),
519 ("right".to_owned(), Value::Number(s.right as _)),
520 ("top".to_owned(), Value::Number(s.top as _)),
521 ("bottom".to_owned(), Value::Number(s.bottom as _)),
522 ]))
523 }
524}
525impl TryFrom<Value> for i_slint_core::lengths::LogicalEdges {
526 type Error = Value;
527 #[inline]
528 fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalEdges, Self::Error> {
529 match v {
530 Value::Struct(s) => {
531 let left = s
532 .get_field("left")
533 .cloned()
534 .unwrap_or_else(|| Value::Number(0 as _))
535 .try_into()?;
536 let right = s
537 .get_field("right")
538 .cloned()
539 .unwrap_or_else(|| Value::Number(0 as _))
540 .try_into()?;
541 let top = s
542 .get_field("top")
543 .cloned()
544 .unwrap_or_else(|| Value::Number(0 as _))
545 .try_into()?;
546 let bottom = s
547 .get_field("bottom")
548 .cloned()
549 .unwrap_or_else(|| Value::Number(0 as _))
550 .try_into()?;
551 Ok(i_slint_core::lengths::LogicalEdges::new(left, right, top, bottom))
552 }
553 _ => Err(v),
554 }
555 }
556}
557
558impl<T: Into<Value> + TryFrom<Value> + 'static> From<ModelRc<T>> for Value {
559 fn from(m: ModelRc<T>) -> Self {
560 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
561 Value::Model(v.clone())
562 } else {
563 Value::Model(ModelRc::new(crate::value_model::ValueMapModel(m)))
564 }
565 }
566}
567impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
568 type Error = Value;
569 #[inline]
570 fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
571 match v {
572 Value::Model(m) => {
573 if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
574 Ok(v.clone())
575 } else if let Some(v) =
576 m.as_any().downcast_ref::<crate::value_model::ValueMapModel<T>>()
577 {
578 Ok(v.0.clone())
579 } else {
580 Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
581 }
582 }
583 _ => Err(v),
584 }
585 }
586}
587
588#[test]
589fn value_model_conversion() {
590 use i_slint_core::model::*;
591 let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
592 let v = Value::from(m.clone());
593 assert_eq!(v, Value::Model(m.clone()));
594 let m2: ModelRc<Value> = v.clone().try_into().unwrap();
595 assert_eq!(m2, m);
596
597 let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
598 assert_eq!(int_model.row_count(), 2);
599 assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
600
601 let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
602 assert_eq!(m3.row_count(), 2);
603 assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
604
605 let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
606 assert_eq!(str_model.row_count(), 2);
607 assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
609
610 let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
611 assert!(err.is_err());
612
613 let model =
614 Rc::new(VecModel::<SharedString>::from_iter(["foo".into(), "bar".into(), "baz".into()]));
615
616 let value: Value = ModelRc::from(model.clone()).into();
617 let value_model: ModelRc<Value> = value.clone().try_into().unwrap();
618 assert_eq!(value_model.row_data(2).unwrap(), Value::String("baz".into()));
619 value_model.set_row_data(1, Value::String("qux".into()));
620 value_model.set_row_data(0, Value::Bool(true));
621 assert_eq!(value_model.row_data(1).unwrap(), Value::String("qux".into()));
622 assert_eq!(value_model.row_data(0).unwrap(), Value::String("foo".into()));
624
625 assert_eq!(model.row_data(1).unwrap(), SharedString::from("qux"));
627 assert_eq!(model.row_data(0).unwrap(), SharedString::from("foo"));
628
629 let the_model: ModelRc<SharedString> = value.try_into().unwrap();
630 assert_eq!(the_model.row_data(1).unwrap(), SharedString::from("qux"));
631 assert_eq!(
632 model.as_ref() as *const VecModel<SharedString>,
633 the_model.as_any().downcast_ref::<VecModel<SharedString>>().unwrap()
634 as *const VecModel<SharedString>
635 );
636}
637
638pub(crate) fn normalize_identifier(ident: &str) -> SmolStr {
639 i_slint_compiler::parser::normalize_identifier(ident)
640}
641
642#[derive(Clone, PartialEq, Debug, Default)]
664pub struct Struct(pub(crate) HashMap<SmolStr, Value>);
665impl Struct {
666 pub fn get_field(&self, name: &str) -> Option<&Value> {
668 if i_slint_compiler::parser::is_identifier_normalized(name) {
669 self.0.get(name)
670 } else {
671 self.0.get(&*normalize_identifier(name))
672 }
673 }
674 pub fn set_field(&mut self, name: String, value: Value) {
676 self.0.insert(normalize_identifier(&name), value);
677 }
678
679 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
681 self.0.iter().map(|(a, b)| (a.as_str(), b))
682 }
683}
684
685impl FromIterator<(String, Value)> for Struct {
686 fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
687 Self(iter.into_iter().map(|(s, v)| (normalize_identifier(&s), v)).collect())
688 }
689}
690
691#[test]
692fn struct_field_name_normalization() {
693 let mut s = Struct::default();
694 s.set_field("foo_bar".into(), Value::Number(1.));
695 s.set_field("cross-axis-self-alignment".into(), Value::Number(2.));
697 assert_eq!(s.get_field("foo-bar"), Some(&Value::Number(1.)));
698 assert_eq!(s.get_field("foo_bar"), Some(&Value::Number(1.)));
699 assert_eq!(s.get_field("cross-axis-self-alignment"), Some(&Value::Number(2.)));
700 assert_eq!(s.get_field("cross_axis_self_alignment"), Some(&Value::Number(2.)));
701}
702
703#[deprecated(note = "Use slint_interpreter::Compiler instead")]
705pub struct ComponentCompiler {
706 config: i_slint_compiler::CompilerConfiguration,
707 diagnostics: Vec<Diagnostic>,
708}
709
710#[allow(deprecated)]
711impl Default for ComponentCompiler {
712 fn default() -> Self {
713 let mut config = i_slint_compiler::CompilerConfiguration::new(
714 i_slint_compiler::generator::OutputFormat::Interpreter,
715 );
716 config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
717 Self { config, diagnostics: Vec::new() }
718 }
719}
720
721#[allow(deprecated)]
722impl ComponentCompiler {
723 pub fn new() -> Self {
725 Self::default()
726 }
727
728 #[doc(hidden)]
732 #[cfg(feature = "internal")]
733 pub fn compiler_configuration(
734 &mut self,
735 _: i_slint_core::InternalToken,
736 ) -> &mut i_slint_compiler::CompilerConfiguration {
737 &mut self.config
738 }
739
740 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
742 self.config.include_paths = include_paths;
743 }
744
745 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
747 &self.config.include_paths
748 }
749
750 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
752 self.config.library_paths = library_paths;
753 }
754
755 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
757 &self.config.library_paths
758 }
759
760 pub fn set_style(&mut self, style: String) {
772 self.config.style = Some(style);
773 }
774
775 pub fn style(&self) -> Option<&String> {
777 self.config.style.as_ref()
778 }
779
780 pub fn set_translation_domain(&mut self, domain: String) {
782 self.config.translation_domain = Some(domain);
783 }
784
785 pub fn set_file_loader(
793 &mut self,
794 file_loader_fallback: impl Fn(
795 &Path,
796 ) -> core::pin::Pin<
797 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
798 > + 'static,
799 ) {
800 self.config.open_import_callback =
801 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
802 }
803
804 pub fn diagnostics(&self) -> &Vec<Diagnostic> {
806 &self.diagnostics
807 }
808
809 pub async fn build_from_path<P: AsRef<Path>>(
828 &mut self,
829 path: P,
830 ) -> Option<ComponentDefinition> {
831 let path = path.as_ref();
832 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
833 Ok(s) => s,
834 Err(d) => {
835 self.diagnostics = vec![d];
836 return None;
837 }
838 };
839
840 let r = build_compilation_result(
841 source,
842 path.into(),
843 self.config.clone(),
844 AnimationMode::Running,
845 )
846 .await;
847 self.diagnostics = r.diagnostics.into_iter().collect();
848 r.components.into_values().next()
849 }
850
851 pub async fn build_from_source(
868 &mut self,
869 source_code: String,
870 path: PathBuf,
871 ) -> Option<ComponentDefinition> {
872 let r = build_compilation_result(
873 source_code,
874 path,
875 self.config.clone(),
876 AnimationMode::Running,
877 )
878 .await;
879 self.diagnostics = r.diagnostics.into_iter().collect();
880 r.components.into_values().next()
881 }
882}
883
884pub struct Compiler {
887 config: i_slint_compiler::CompilerConfiguration,
888}
889
890impl Default for Compiler {
891 fn default() -> Self {
892 let config = i_slint_compiler::CompilerConfiguration::new(
893 i_slint_compiler::generator::OutputFormat::Interpreter,
894 );
895 Self { config }
896 }
897}
898
899impl Compiler {
900 pub fn new() -> Self {
902 Self::default()
903 }
904
905 #[doc(hidden)]
906 #[cfg(feature = "internal")]
907 pub fn set_embed_resources(&mut self, embed_resources: i_slint_compiler::EmbedResourcesKind) {
908 self.config.embed_resources = embed_resources;
909 }
910
911 #[doc(hidden)]
915 #[cfg(feature = "internal")]
916 pub fn compiler_configuration(
917 &mut self,
918 _: i_slint_core::InternalToken,
919 ) -> &mut i_slint_compiler::CompilerConfiguration {
920 &mut self.config
921 }
922
923 pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
925 self.config.include_paths = include_paths;
926 }
927
928 pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
930 &self.config.include_paths
931 }
932
933 pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
935 self.config.library_paths = library_paths;
936 }
937
938 pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
940 &self.config.library_paths
941 }
942
943 pub fn set_style(&mut self, style: String) {
954 self.config.style = Some(style);
955 }
956
957 pub fn style(&self) -> Option<&String> {
959 self.config.style.as_ref()
960 }
961
962 pub fn set_translation_domain(&mut self, domain: String) {
964 self.config.translation_domain = Some(domain);
965 }
966
967 pub fn set_default_translation_context(
973 &mut self,
974 default_translation_context: DefaultTranslationContext,
975 ) {
976 self.config.default_translation_context = default_translation_context;
977 }
978
979 #[cfg(feature = "bundle-translations")]
986 pub fn set_bundled_translations_path(&mut self, path: PathBuf) {
987 self.config.bundled_translations_path = Some(path);
988 }
989
990 pub fn set_file_loader(
998 &mut self,
999 file_loader_fallback: impl Fn(
1000 &Path,
1001 ) -> core::pin::Pin<
1002 Box<dyn Future<Output = Option<std::io::Result<String>>>>,
1003 > + 'static,
1004 ) {
1005 self.config.open_import_callback =
1006 Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
1007 }
1008
1009 pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
1028 let path = path.as_ref();
1029 let source = match i_slint_compiler::diagnostics::load_from_path(path) {
1030 Ok(s) => s,
1031 Err(d) => {
1032 let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1033 diagnostics.push_compiler_error(d);
1034 return CompilationResult {
1035 components: HashMap::new(),
1036 diagnostics: diagnostics.into_iter().collect(),
1037 #[cfg(feature = "internal")]
1038 watch_paths: vec![i_slint_compiler::pathutils::clean_path(path)],
1039 #[cfg(feature = "internal")]
1040 structs_and_enums: Vec::new(),
1041 };
1042 }
1043 };
1044
1045 build_compilation_result(source, path.into(), self.config.clone(), AnimationMode::Running)
1046 .await
1047 }
1048
1049 pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
1062 build_compilation_result(source_code, path, self.config.clone(), AnimationMode::Running)
1063 .await
1064 }
1065
1066 #[doc(hidden)]
1068 #[cfg(feature = "internal")]
1069 pub async fn build_static_from_source(
1070 &self,
1071 source_code: String,
1072 path: PathBuf,
1073 _: i_slint_core::InternalToken,
1074 ) -> CompilationResult {
1075 build_compilation_result(source_code, path, self.config.clone(), AnimationMode::Static)
1076 .await
1077 }
1078}
1079
1080pub(crate) enum AnimationMode {
1081 #[cfg_attr(not(feature = "internal"), allow(dead_code))]
1084 Static,
1085 Running,
1086}
1087
1088async fn build_compilation_result(
1089 source_code: String,
1090 path: PathBuf,
1091 config: i_slint_compiler::CompilerConfiguration,
1092 animation_mode: AnimationMode,
1093) -> CompilationResult {
1094 let result =
1095 crate::component::build_from_source(source_code, path, config, animation_mode).await;
1096 let components = result
1097 .components
1098 .into_iter()
1099 .map(|(name, def)| (name, ComponentDefinition { inner: std::rc::Rc::new(def) }))
1100 .collect::<HashMap<String, ComponentDefinition>>();
1101 CompilationResult {
1102 components,
1103 diagnostics: result.diagnostics,
1104 #[cfg(feature = "internal")]
1105 watch_paths: result.watch_paths,
1106 #[cfg(feature = "internal")]
1107 structs_and_enums: result.structs_and_enums,
1108 }
1109}
1110
1111pub struct CompilationResultSend {
1134 compilation_unit: Option<i_slint_compiler::llr::CompilationUnit>,
1136 components: HashMap<String, i_slint_compiler::llr::PublicComponentIdx>,
1138 diagnostics: Vec<Diagnostic>,
1139 #[cfg(feature = "internal")]
1140 watch_paths: Vec<PathBuf>,
1141 #[cfg(feature = "internal")]
1142 structs_and_enums: Vec<LangType>,
1143}
1144
1145const _: () = {
1146 const fn assert_send<T: Send>() {}
1147 assert_send::<CompilationResultSend>();
1148};
1149
1150impl CompilationResultSend {
1151 pub fn has_errors(&self) -> bool {
1153 self.diagnostics.iter().any(|d| d.level() == DiagnosticLevel::Error)
1154 }
1155
1156 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1158 self.diagnostics.iter().cloned()
1159 }
1160
1161 #[cfg(feature = "display-diagnostics")]
1163 pub fn print_diagnostics(&self) {
1164 print_diagnostics(&self.diagnostics)
1165 }
1166}
1167
1168impl From<CompilationResultSend> for CompilationResult {
1169 fn from(sent: CompilationResultSend) -> Self {
1170 let CompilationResultSend {
1171 compilation_unit,
1172 components,
1173 diagnostics,
1174 #[cfg(feature = "internal")]
1175 watch_paths,
1176 #[cfg(feature = "internal")]
1177 structs_and_enums,
1178 } = sent;
1179 let compilation_unit = compilation_unit.map(std::rc::Rc::new);
1180 let components = components
1181 .into_iter()
1182 .filter_map(|(name, public_index)| {
1183 let inner = std::rc::Rc::new(crate::component::ComponentDefinitionInner {
1184 compilation_unit: compilation_unit.clone()?,
1185 public_index,
1186 type_loaders: Default::default(),
1187 });
1188 Some((name, ComponentDefinition { inner }))
1189 })
1190 .collect();
1191 Self {
1192 components,
1193 diagnostics,
1194 #[cfg(feature = "internal")]
1195 watch_paths,
1196 #[cfg(feature = "internal")]
1197 structs_and_enums,
1198 }
1199 }
1200}
1201
1202#[derive(Clone)]
1209pub struct CompilationResult {
1210 pub(crate) components: HashMap<String, ComponentDefinition>,
1211 pub(crate) diagnostics: Vec<Diagnostic>,
1212 #[cfg(feature = "internal")]
1213 pub(crate) watch_paths: Vec<PathBuf>,
1214 #[cfg(feature = "internal")]
1215 pub(crate) structs_and_enums: Vec<LangType>,
1216}
1217
1218impl core::fmt::Debug for CompilationResult {
1219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1220 f.debug_struct("CompilationResult")
1221 .field("components", &self.components.keys())
1222 .field("diagnostics", &self.diagnostics)
1223 .finish()
1224 }
1225}
1226
1227impl CompilationResult {
1228 pub fn has_errors(&self) -> bool {
1231 self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
1232 }
1233
1234 pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
1238 self.diagnostics.iter().cloned()
1239 }
1240
1241 #[cfg(feature = "display-diagnostics")]
1247 pub fn print_diagnostics(&self) {
1248 print_diagnostics(&self.diagnostics)
1249 }
1250
1251 pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
1253 self.components.values().cloned()
1254 }
1255
1256 pub fn into_send(self) -> CompilationResultSend {
1258 let Self {
1259 components,
1260 diagnostics,
1261 #[cfg(feature = "internal")]
1262 watch_paths,
1263 #[cfg(feature = "internal")]
1264 structs_and_enums,
1265 } = self;
1266
1267 let mut unit = None::<std::rc::Rc<i_slint_compiler::llr::CompilationUnit>>;
1269 let components = components
1270 .into_iter()
1271 .map(|(name, definition)| {
1272 let public_index = definition.inner.public_index;
1273 match &unit {
1274 Some(u) => {
1275 debug_assert!(std::rc::Rc::ptr_eq(u, &definition.inner.compilation_unit))
1276 }
1277 None => unit = Some(definition.inner.compilation_unit.clone()),
1278 }
1279 (name, public_index)
1280 })
1281 .collect();
1282 let compilation_unit = unit.map(std::rc::Rc::unwrap_or_clone);
1285
1286 CompilationResultSend {
1287 compilation_unit,
1288 components,
1289 diagnostics,
1290 #[cfg(feature = "internal")]
1291 watch_paths,
1292 #[cfg(feature = "internal")]
1293 structs_and_enums,
1294 }
1295 }
1296
1297 pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
1299 self.components.keys().map(|s| s.as_str())
1300 }
1301
1302 pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
1305 self.components.get(name).cloned()
1306 }
1307
1308 #[doc(hidden)]
1310 #[cfg(feature = "internal")]
1311 pub fn watch_paths(&self, _: i_slint_core::InternalToken) -> &[PathBuf] {
1312 &self.watch_paths
1313 }
1314
1315 #[doc(hidden)]
1317 #[cfg(feature = "internal")]
1318 pub fn structs_and_enums(
1319 &self,
1320 _: i_slint_core::InternalToken,
1321 ) -> impl Iterator<Item = &LangType> {
1322 self.structs_and_enums.iter()
1323 }
1324
1325 #[doc(hidden)]
1328 #[cfg(feature = "internal")]
1329 pub fn compilation_unit(
1330 &self,
1331 _: i_slint_core::InternalToken,
1332 ) -> Option<&i_slint_compiler::llr::CompilationUnit> {
1333 self.components.values().next().map(|d| &*d.inner.compilation_unit)
1334 }
1335}
1336
1337#[derive(Clone)]
1345pub struct ComponentDefinition {
1346 pub(crate) inner: std::rc::Rc<crate::component::ComponentDefinitionInner>,
1347}
1348
1349impl ComponentDefinition {
1350 pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
1352 let instance = self.create_with_options(Default::default())?;
1353 if !instance.is_system_tray_rooted() {
1356 instance.inner.window_adapter_ref()?;
1358 i_slint_core::window::WindowInner::from_pub(instance.window())
1361 .ensure_tree_instantiated();
1362 }
1363 Ok(instance)
1364 }
1365
1366 #[doc(hidden)]
1368 #[cfg(feature = "internal")]
1369 pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
1370 self.create_with_options(WindowOptions::Embed {
1371 parent_item_tree: ctx.parent_item_tree,
1372 parent_item_tree_index: ctx.parent_item_tree_index,
1373 })
1374 }
1375
1376 #[doc(hidden)]
1378 #[cfg(feature = "internal")]
1379 pub fn create_with_existing_window(
1380 &self,
1381 window: &Window,
1382 ) -> Result<ComponentInstance, PlatformError> {
1383 self.create_with_options(WindowOptions::UseExistingWindow(
1384 WindowInner::from_pub(window).window_adapter(),
1385 ))
1386 }
1387
1388 pub(crate) fn create_with_options(
1390 &self,
1391 options: WindowOptions,
1392 ) -> Result<ComponentInstance, PlatformError> {
1393 let instance = match options {
1394 WindowOptions::CreateNewWindow => self.inner.create(),
1395 WindowOptions::UseExistingWindow(adapter) => {
1396 self.inner.create_with_existing_window(adapter)
1397 }
1398 WindowOptions::Embed { parent_item_tree, parent_item_tree_index } => {
1399 self.inner.create_embedded(parent_item_tree, parent_item_tree_index)
1400 }
1401 };
1402 Ok(ComponentInstance { inner: instance })
1403 }
1404}
1405
1406#[allow(dead_code)]
1411#[derive(Default)]
1412pub(crate) enum WindowOptions {
1413 #[default]
1414 CreateNewWindow,
1415 UseExistingWindow(i_slint_core::window::WindowAdapterRc),
1416 Embed {
1417 parent_item_tree: i_slint_core::item_tree::ItemTreeWeak,
1418 parent_item_tree_index: u32,
1419 },
1420}
1421
1422impl ComponentDefinition {
1423 #[doc(hidden)]
1427 #[cfg(feature = "internal")]
1428 pub fn properties_and_callbacks(
1429 &self,
1430 ) -> impl Iterator<
1431 Item = (
1432 String,
1433 (i_slint_compiler::langtype::Type, i_slint_compiler::object_tree::PropertyVisibility),
1434 ),
1435 > + '_ {
1436 self.inner
1437 .properties_and_callbacks()
1438 .map(|(n, t, v)| (n.to_string(), (t, v)))
1439 .collect::<Vec<_>>()
1440 .into_iter()
1441 }
1442
1443 pub fn properties(&self) -> impl Iterator<Item = (String, ValueType)> + '_ {
1446 self.inner
1447 .properties()
1448 .map(|(n, t)| (n.to_string(), t.into()))
1449 .collect::<Vec<_>>()
1450 .into_iter()
1451 }
1452
1453 pub fn callbacks(&self) -> impl Iterator<Item = String> + '_ {
1455 self.inner.callbacks().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1456 }
1457
1458 pub fn functions(&self) -> impl Iterator<Item = String> + '_ {
1460 self.inner.functions().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1461 }
1462
1463 pub fn globals(&self) -> impl Iterator<Item = String> + '_ {
1468 self.inner.globals().map(|s| s.to_string()).collect::<Vec<_>>().into_iter()
1469 }
1470
1471 #[doc(hidden)]
1475 #[cfg(feature = "internal")]
1476 pub fn global_properties_and_callbacks(
1477 &self,
1478 global_name: &str,
1479 ) -> Option<
1480 impl Iterator<
1481 Item = (
1482 String,
1483 (
1484 i_slint_compiler::langtype::Type,
1485 i_slint_compiler::object_tree::PropertyVisibility,
1486 ),
1487 ),
1488 > + '_,
1489 > {
1490 Some(
1491 self.inner
1492 .global_properties_and_callbacks(global_name)?
1493 .map(|(n, t, v)| (n.to_string(), (t, v)))
1494 .collect::<Vec<_>>()
1495 .into_iter(),
1496 )
1497 }
1498
1499 pub fn global_properties(
1501 &self,
1502 global_name: &str,
1503 ) -> Option<impl Iterator<Item = (String, ValueType)> + '_> {
1504 Some(
1505 self.inner
1506 .global_properties(global_name)?
1507 .map(|(n, t)| (n.to_string(), t.into()))
1508 .collect::<Vec<_>>()
1509 .into_iter(),
1510 )
1511 }
1512
1513 pub fn global_callbacks(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1515 Some(
1516 self.inner
1517 .global_callbacks(global_name)?
1518 .map(|s| s.to_string())
1519 .collect::<Vec<_>>()
1520 .into_iter(),
1521 )
1522 }
1523
1524 pub fn global_functions(&self, global_name: &str) -> Option<impl Iterator<Item = String> + '_> {
1526 Some(
1527 self.inner
1528 .global_functions(global_name)?
1529 .map(|s| s.to_string())
1530 .collect::<Vec<_>>()
1531 .into_iter(),
1532 )
1533 }
1534
1535 pub fn name(&self) -> &str {
1537 self.inner.name()
1538 }
1539
1540 #[doc(hidden)]
1544 #[cfg(feature = "internal")]
1545 pub fn is_window(&self) -> bool {
1546 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::Window
1547 }
1548
1549 #[cfg(feature = "internal")]
1551 #[doc(hidden)]
1552 pub fn root_component(&self) -> Rc<i_slint_compiler::object_tree::Component> {
1553 self.inner
1554 .type_loaders
1555 .originals
1556 .get(self.inner.public_index)
1557 .expect("root_component() called on a definition built without compiler state")
1558 .clone()
1559 }
1560
1561 #[cfg(feature = "internal-highlight")]
1565 pub fn type_loader(&self) -> std::rc::Rc<i_slint_compiler::typeloader::TypeLoader> {
1566 self.inner.type_loaders.type_loader.clone().expect(
1567 "TypeLoader was not retained for this ComponentDefinition (reconstructed from an instance)",
1568 )
1569 }
1570
1571 #[cfg(feature = "internal-highlight")]
1579 pub fn raw_type_loader(&self) -> Option<i_slint_compiler::typeloader::TypeLoader> {
1580 self.inner
1581 .type_loaders
1582 .raw_type_loader
1583 .as_ref()
1584 .and_then(|tl| i_slint_compiler::typeloader::snapshot(tl))
1585 }
1586}
1587
1588#[cfg(feature = "display-diagnostics")]
1594pub fn print_diagnostics(diagnostics: &[Diagnostic]) {
1595 let mut build_diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
1596 for d in diagnostics {
1597 build_diagnostics.push_compiler_error(d.clone())
1598 }
1599 build_diagnostics.print();
1600}
1601
1602#[repr(C)]
1610pub struct ComponentInstance {
1611 pub(crate) inner: crate::component::ComponentInstanceInner,
1612}
1613
1614impl ComponentInstance {
1615 pub fn definition(&self) -> ComponentDefinition {
1617 ComponentDefinition { inner: std::rc::Rc::new(self.inner.definition()) }
1618 }
1619
1620 fn is_system_tray_rooted(&self) -> bool {
1621 self.inner.top_level_type() == i_slint_compiler::llr::TopLevelComponentType::SystemTrayIcon
1622 }
1623
1624 fn set_tray_icon_visible(&self, visible: bool) {
1628 let item_rc = ItemRc::new(vtable::VRc::into_dyn(self.inner.vrc().clone()), 0);
1630 let tray = item_rc
1631 .downcast::<SystemTrayIcon>()
1632 .expect("the root item of a SystemTrayIcon-rooted component is a SystemTrayIcon");
1633 tray.as_pin_ref().visible.set(visible);
1634 }
1635
1636 pub fn get_property(&self, name: &str) -> Result<Value, GetPropertyError> {
1656 self.inner.get_property(name).ok_or(GetPropertyError::NoSuchProperty)
1657 }
1658
1659 pub fn set_property(&self, name: &str, value: Value) -> Result<(), SetPropertyError> {
1661 self.inner.set_property(name, value)
1662 }
1663
1664 pub fn set_callback(
1699 &self,
1700 name: &str,
1701 callback: impl Fn(&[Value]) -> Value + 'static,
1702 ) -> Result<(), SetCallbackError> {
1703 self.inner.set_callback(name, callback).map_err(|()| SetCallbackError::NoSuchCallback)
1704 }
1705
1706 pub fn invoke(&self, name: &str, args: &[Value]) -> Result<Value, InvokeError> {
1711 self.inner.invoke(name, args).ok_or(InvokeError::NoSuchCallable)
1712 }
1713
1714 pub fn get_global_property(
1739 &self,
1740 global: &str,
1741 property: &str,
1742 ) -> Result<Value, GetPropertyError> {
1743 self.inner.get_global_property(global, property).ok_or(GetPropertyError::NoSuchProperty)
1744 }
1745
1746 pub fn set_global_property(
1748 &self,
1749 global: &str,
1750 property: &str,
1751 value: Value,
1752 ) -> Result<(), SetPropertyError> {
1753 self.inner.set_global_property(global, property, value)
1754 }
1755
1756 pub fn set_global_callback(
1791 &self,
1792 global: &str,
1793 name: &str,
1794 callback: impl Fn(&[Value]) -> Value + 'static,
1795 ) -> Result<(), SetCallbackError> {
1796 self.inner
1797 .set_global_callback(global, name, callback)
1798 .map_err(|()| SetCallbackError::NoSuchCallback)
1799 }
1800
1801 pub fn invoke_global(
1806 &self,
1807 global: &str,
1808 callable_name: &str,
1809 args: &[Value],
1810 ) -> Result<Value, InvokeError> {
1811 self.inner.invoke_global(global, callable_name, args).ok_or(InvokeError::NoSuchCallable)
1812 }
1813
1814 #[cfg(feature = "internal-highlight")]
1818 pub fn component_positions(
1819 &self,
1820 path: &Path,
1821 offset: u32,
1822 ) -> Vec<crate::highlight::HighlightedRect> {
1823 crate::highlight::component_positions(self.inner.vrc(), path, offset)
1824 }
1825
1826 #[cfg(feature = "internal-highlight")]
1830 pub fn element_positions(
1831 &self,
1832 element: &i_slint_compiler::object_tree::ElementRc,
1833 ) -> Vec<crate::highlight::HighlightedRect> {
1834 crate::highlight::element_positions(
1835 self.inner.vrc(),
1836 element,
1837 crate::highlight::ElementPositionFilter::IncludeClipped,
1838 )
1839 }
1840
1841 #[cfg(feature = "internal-highlight")]
1845 pub fn element_node_at_source_code_position(
1846 &self,
1847 path: &Path,
1848 offset: u32,
1849 ) -> Vec<(i_slint_compiler::object_tree::ElementRc, usize)> {
1850 crate::highlight::element_node_at_source_code_position(self.inner.vrc(), path, offset)
1851 }
1852
1853 #[cfg(feature = "internal")]
1855 pub fn set_debug_hook_callback(&self, callback: Option<crate::debug_hook::DebugHookCallback>) {
1856 crate::debug_hook::set_debug_hook_callback(self.inner.vrc(), callback);
1857 }
1858}
1859
1860impl StrongHandle for ComponentInstance {
1861 type WeakInner = vtable::VWeak<ItemTreeVTable, crate::instance::Instance>;
1862
1863 fn upgrade_from_weak_inner(inner: &Self::WeakInner) -> Option<Self> {
1864 Some(Self { inner: crate::component::ComponentInstanceInner(inner.upgrade()?) })
1865 }
1866}
1867
1868impl ComponentHandle for ComponentInstance {
1869 fn as_weak(&self) -> Weak<Self>
1870 where
1871 Self: Sized,
1872 {
1873 Weak::new(vtable::VRc::downgrade(self.inner.vrc()))
1874 }
1875
1876 fn clone_strong(&self) -> Self {
1877 Self { inner: self.inner.clone() }
1878 }
1879
1880 fn show(&self) -> Result<(), PlatformError> {
1881 if self.is_system_tray_rooted() {
1882 self.set_tray_icon_visible(true);
1883 return Ok(());
1884 }
1885 let adapter = self.inner.window_adapter_ref()?;
1886 self.inner.0.attach_to_window();
1890 adapter.window().show()
1891 }
1892
1893 fn hide(&self) -> Result<(), PlatformError> {
1894 if self.is_system_tray_rooted() {
1895 self.set_tray_icon_visible(false);
1896 return Ok(());
1897 }
1898 self.inner.window_adapter_ref()?.window().hide()
1899 }
1900
1901 fn run(&self) -> Result<(), PlatformError> {
1902 self.show()?;
1903 run_event_loop()?;
1904 self.hide()
1905 }
1906
1907 fn window(&self) -> &Window {
1908 let adapter = self.inner.window_adapter_ref().unwrap();
1909 self.inner.0.attach_to_window();
1915 adapter.window()
1916 }
1917
1918 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
1919 where
1920 Self: Sized,
1921 {
1922 unreachable!()
1923 }
1924}
1925
1926impl From<ComponentInstance>
1927 for vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>
1928{
1929 fn from(value: ComponentInstance) -> Self {
1930 value.inner.0
1931 }
1932}
1933
1934#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1936#[non_exhaustive]
1937pub enum GetPropertyError {
1938 #[display("no such property")]
1940 NoSuchProperty,
1941}
1942
1943#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1945#[non_exhaustive]
1946pub enum SetPropertyError {
1947 #[display("no such property")]
1949 NoSuchProperty,
1950 #[display("wrong type")]
1956 WrongType,
1957 #[display("access denied")]
1959 AccessDenied,
1960}
1961
1962#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1964#[non_exhaustive]
1965pub enum SetCallbackError {
1966 #[display("no such callback")]
1968 NoSuchCallback,
1969}
1970
1971#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Error, derive_more::Display)]
1973#[non_exhaustive]
1974pub enum InvokeError {
1975 #[display("no such callback or function")]
1977 NoSuchCallable,
1978}
1979
1980pub fn run_event_loop() -> Result<(), PlatformError> {
1984 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
1985}
1986
1987pub fn spawn_local<F: Future + 'static>(fut: F) -> Result<JoinHandle<F::Output>, EventLoopError> {
1991 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
1992 .map_err(|_| EventLoopError::NoEventLoopProvider)?
1993}
1994
1995#[test]
1996fn component_definition_properties() {
1997 i_slint_backend_testing::init_no_event_loop();
1998 let mut compiler = Compiler::default();
1999 compiler.set_style("fluent".into());
2000 let comp_def = spin_on::spin_on(
2001 compiler.build_from_source(
2002 r#"
2003 export component Dummy {
2004 in-out property <string> test;
2005 in-out property <int> underscores-and-dashes_preserved: 44;
2006 callback hello;
2007 }"#
2008 .into(),
2009 "".into(),
2010 ),
2011 )
2012 .component("Dummy")
2013 .unwrap();
2014
2015 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2016
2017 assert_eq!(props.len(), 2);
2018 assert_eq!(props[0].0, "test");
2019 assert_eq!(props[0].1, ValueType::String);
2020 assert_eq!(props[1].0, "underscores-and-dashes_preserved");
2021 assert_eq!(props[1].1, ValueType::Number);
2022
2023 let instance = comp_def.create().unwrap();
2024 assert_eq!(instance.get_property("underscores_and-dashes-preserved"), Ok(Value::Number(44.)));
2025 assert_eq!(
2026 instance.get_property("underscoresanddashespreserved"),
2027 Err(GetPropertyError::NoSuchProperty)
2028 );
2029 assert_eq!(
2030 instance.set_property("underscores-and_dashes-preserved", Value::Number(88.)),
2031 Ok(())
2032 );
2033 assert_eq!(
2034 instance.set_property("underscoresanddashespreserved", Value::Number(99.)),
2035 Err(SetPropertyError::NoSuchProperty)
2036 );
2037 assert_eq!(
2038 instance.set_property("underscores-and_dashes-preserved", Value::String("99".into())),
2039 Err(SetPropertyError::WrongType)
2040 );
2041 assert_eq!(instance.get_property("underscores-and-dashes-preserved"), Ok(Value::Number(88.)));
2042}
2043
2044#[test]
2045fn component_definition_properties2() {
2046 i_slint_backend_testing::init_no_event_loop();
2047 let mut compiler = Compiler::default();
2048 compiler.set_style("fluent".into());
2049 let comp_def = spin_on::spin_on(
2050 compiler.build_from_source(
2051 r#"
2052 export component Dummy {
2053 in-out property <string> sub-text <=> sub.text;
2054 sub := Text { property <int> private-not-exported; }
2055 out property <string> xreadonly: "the value";
2056 private property <string> xx: sub.text;
2057 callback hello;
2058 }"#
2059 .into(),
2060 "".into(),
2061 ),
2062 )
2063 .component("Dummy")
2064 .unwrap();
2065
2066 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2067
2068 assert_eq!(props.len(), 2);
2069 assert_eq!(props[0].0, "sub-text");
2070 assert_eq!(props[0].1, ValueType::String);
2071 assert_eq!(props[1].0, "xreadonly");
2072
2073 let callbacks = comp_def.callbacks().collect::<Vec<_>>();
2074 assert_eq!(callbacks.len(), 1);
2075 assert_eq!(callbacks[0], "hello");
2076
2077 let instance = comp_def.create().unwrap();
2078 assert_eq!(
2079 instance.set_property("xreadonly", SharedString::from("XXX").into()),
2080 Err(SetPropertyError::AccessDenied)
2081 );
2082 assert_eq!(instance.get_property("xreadonly"), Ok(Value::String("the value".into())));
2083 assert_eq!(
2084 instance.set_property("xx", SharedString::from("XXX").into()),
2085 Err(SetPropertyError::NoSuchProperty)
2086 );
2087 assert_eq!(
2088 instance.set_property("background", Value::default()),
2089 Err(SetPropertyError::NoSuchProperty)
2090 );
2091
2092 assert_eq!(instance.get_property("background"), Err(GetPropertyError::NoSuchProperty));
2093 assert_eq!(instance.get_property("xx"), Err(GetPropertyError::NoSuchProperty));
2094}
2095
2096#[test]
2097fn globals() {
2098 i_slint_backend_testing::init_no_event_loop();
2099 let mut compiler = Compiler::default();
2100 compiler.set_style("fluent".into());
2101 let definition = spin_on::spin_on(
2102 compiler.build_from_source(
2103 r#"
2104 export global My-Super_Global {
2105 in-out property <int> the-property : 21;
2106 callback my-callback();
2107 callback int-callback() -> int;
2108 }
2109 export { My-Super_Global as AliasedGlobal }
2110 export component Dummy {
2111 callback alias <=> My-Super_Global.my-callback;
2112 }"#
2113 .into(),
2114 "".into(),
2115 ),
2116 )
2117 .component("Dummy")
2118 .unwrap();
2119
2120 assert_eq!(definition.globals().collect::<Vec<_>>(), vec!["My-Super_Global", "AliasedGlobal"]);
2121
2122 assert!(definition.global_properties("not-there").is_none());
2123 {
2124 let expected_properties = vec![("the-property".to_string(), ValueType::Number)];
2125 let expected_callbacks = vec!["int-callback".to_string(), "my-callback".to_string()];
2126
2127 let assert_properties_and_callbacks = |global_name| {
2128 assert_eq!(
2129 definition
2130 .global_properties(global_name)
2131 .map(|props| props.collect::<Vec<_>>())
2132 .as_ref(),
2133 Some(&expected_properties)
2134 );
2135 assert_eq!(
2136 definition
2137 .global_callbacks(global_name)
2138 .map(|props| props.collect::<Vec<_>>())
2139 .as_ref(),
2140 Some(&expected_callbacks)
2141 );
2142 };
2143
2144 assert_properties_and_callbacks("My-Super-Global");
2145 assert_properties_and_callbacks("My_Super-Global");
2146 assert_properties_and_callbacks("AliasedGlobal");
2147 }
2148
2149 let instance = definition.create().unwrap();
2150 assert_eq!(
2151 instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)),
2152 Ok(())
2153 );
2154 assert_eq!(
2155 instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)),
2156 Ok(())
2157 );
2158 assert_eq!(
2159 instance.set_global_property("DontExist", "the-property", Value::Number(88.)),
2160 Err(SetPropertyError::NoSuchProperty)
2161 );
2162
2163 assert_eq!(
2164 instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)),
2165 Err(SetPropertyError::NoSuchProperty)
2166 );
2167 assert_eq!(
2168 instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)),
2169 Err(SetPropertyError::NoSuchProperty)
2170 );
2171 assert_eq!(
2172 instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())),
2173 Err(SetPropertyError::WrongType)
2174 );
2175 assert_eq!(
2176 instance.get_global_property("My-Super_Global", "yoyo"),
2177 Err(GetPropertyError::NoSuchProperty)
2178 );
2179 assert_eq!(
2180 instance.get_global_property("My-Super_Global", "the-property"),
2181 Ok(Value::Number(44.))
2182 );
2183
2184 assert_eq!(
2185 instance.set_property("the-property", Value::Void),
2186 Err(SetPropertyError::NoSuchProperty)
2187 );
2188 assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty));
2189
2190 assert_eq!(
2191 instance.set_global_callback("DontExist", "the-property", |_| panic!()),
2192 Err(SetCallbackError::NoSuchCallback)
2193 );
2194 assert_eq!(
2195 instance.set_global_callback("My_Super_Global", "the-property", |_| panic!()),
2196 Err(SetCallbackError::NoSuchCallback)
2197 );
2198 assert_eq!(
2199 instance.set_global_callback("My_Super_Global", "yoyo", |_| panic!()),
2200 Err(SetCallbackError::NoSuchCallback)
2201 );
2202
2203 assert_eq!(
2204 instance.invoke_global("DontExist", "the-property", &[]),
2205 Err(InvokeError::NoSuchCallable)
2206 );
2207 assert_eq!(
2208 instance.invoke_global("My_Super_Global", "the-property", &[]),
2209 Err(InvokeError::NoSuchCallable)
2210 );
2211 assert_eq!(
2212 instance.invoke_global("My_Super_Global", "yoyo", &[]),
2213 Err(InvokeError::NoSuchCallable)
2214 );
2215
2216 assert_eq!(instance.get_property("alias"), Err(GetPropertyError::NoSuchProperty));
2218
2219 assert_eq!(
2221 instance.invoke_global("My_Super_Global", "int-callback", &[]),
2222 Ok(Value::Number(0.))
2223 );
2224}
2225
2226#[test]
2227fn call_functions() {
2228 i_slint_backend_testing::init_no_event_loop();
2229 let mut compiler = Compiler::default();
2230 compiler.set_style("fluent".into());
2231 let definition = spin_on::spin_on(
2232 compiler.build_from_source(
2233 r#"
2234 export global Gl {
2235 out property<string> q;
2236 public function foo-bar(a-a: string, b-b:int) -> string {
2237 q = a-a;
2238 return a-a + b-b;
2239 }
2240 }
2241 export component Test {
2242 out property<int> p;
2243 public function foo-bar(a: int, b:int) -> int {
2244 p = a;
2245 return a + b;
2246 }
2247 }"#
2248 .into(),
2249 "".into(),
2250 ),
2251 )
2252 .component("Test")
2253 .unwrap();
2254
2255 assert_eq!(definition.functions().collect::<Vec<_>>(), ["foo-bar"]);
2256 assert_eq!(definition.global_functions("Gl").unwrap().collect::<Vec<_>>(), ["foo-bar"]);
2257
2258 let instance = definition.create().unwrap();
2259
2260 assert_eq!(
2261 instance.invoke("foo_bar", &[Value::Number(3.), Value::Number(4.)]),
2262 Ok(Value::Number(7.))
2263 );
2264 assert_eq!(instance.invoke("p", &[]), Err(InvokeError::NoSuchCallable));
2265 assert_eq!(instance.get_property("p"), Ok(Value::Number(3.)));
2266
2267 assert_eq!(
2268 instance.invoke_global(
2269 "Gl",
2270 "foo_bar",
2271 &[Value::String("Hello".into()), Value::Number(10.)]
2272 ),
2273 Ok(Value::String("Hello10".into()))
2274 );
2275 assert_eq!(instance.get_global_property("Gl", "q"), Ok(Value::String("Hello".into())));
2276}
2277
2278#[test]
2279fn component_definition_struct_properties() {
2280 i_slint_backend_testing::init_no_event_loop();
2281 let mut compiler = Compiler::default();
2282 compiler.set_style("fluent".into());
2283 let comp_def = spin_on::spin_on(
2284 compiler.build_from_source(
2285 r#"
2286 export struct Settings {
2287 string_value: string,
2288 }
2289 export component Dummy {
2290 in-out property <Settings> test;
2291 }"#
2292 .into(),
2293 "".into(),
2294 ),
2295 )
2296 .component("Dummy")
2297 .unwrap();
2298
2299 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2300
2301 assert_eq!(props.len(), 1);
2302 assert_eq!(props[0].0, "test");
2303 assert_eq!(props[0].1, ValueType::Struct);
2304
2305 let instance = comp_def.create().unwrap();
2306
2307 let valid_struct: Struct =
2308 [("string_value".to_string(), Value::String("hello".into()))].iter().cloned().collect();
2309
2310 assert_eq!(instance.set_property("test", Value::Struct(valid_struct.clone())), Ok(()));
2311 assert_eq!(instance.get_property("test").unwrap().value_type(), ValueType::Struct);
2312
2313 assert_eq!(instance.set_property("test", Value::Number(42.)), Err(SetPropertyError::WrongType));
2314
2315 let mut invalid_struct = valid_struct.clone();
2316 invalid_struct.set_field("other".into(), Value::Number(44.));
2317 assert_eq!(
2318 instance.set_property("test", Value::Struct(invalid_struct)),
2319 Err(SetPropertyError::WrongType)
2320 );
2321 let mut invalid_struct = valid_struct;
2322 invalid_struct.set_field("string_value".into(), Value::Number(44.));
2323 assert_eq!(
2324 instance.set_property("test", Value::Struct(invalid_struct)),
2325 Err(SetPropertyError::WrongType)
2326 );
2327}
2328
2329#[test]
2330fn component_definition_model_properties() {
2331 use i_slint_core::model::*;
2332 i_slint_backend_testing::init_no_event_loop();
2333 let mut compiler = Compiler::default();
2334 compiler.set_style("fluent".into());
2335 let comp_def = spin_on::spin_on(compiler.build_from_source(
2336 "export component Dummy { in-out property <[int]> prop: [42, 12]; }".into(),
2337 "".into(),
2338 ))
2339 .component("Dummy")
2340 .unwrap();
2341
2342 let props = comp_def.properties().collect::<Vec<(_, _)>>();
2343 assert_eq!(props.len(), 1);
2344 assert_eq!(props[0].0, "prop");
2345 assert_eq!(props[0].1, ValueType::Model);
2346
2347 let instance = comp_def.create().unwrap();
2348
2349 let int_model =
2350 Value::Model([Value::Number(14.), Value::Number(15.), Value::Number(16.)].into());
2351 let empty_model = Value::Model(ModelRc::new(VecModel::<Value>::default()));
2352 let model_with_string = Value::Model(VecModel::from_slice(&[
2353 Value::Number(1000.),
2354 Value::String("foo".into()),
2355 Value::Number(1111.),
2356 ]));
2357
2358 #[track_caller]
2359 fn check_model(val: Value, r: &[f64]) {
2360 if let Value::Model(m) = val {
2361 assert_eq!(r.len(), m.row_count());
2362 for (i, v) in r.iter().enumerate() {
2363 assert_eq!(m.row_data(i).unwrap(), Value::Number(*v));
2364 }
2365 } else {
2366 panic!("{val:?} not a model");
2367 }
2368 }
2369
2370 assert_eq!(instance.get_property("prop").unwrap().value_type(), ValueType::Model);
2371 check_model(instance.get_property("prop").unwrap(), &[42., 12.]);
2372
2373 instance.set_property("prop", int_model).unwrap();
2374 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2375
2376 assert_eq!(instance.set_property("prop", Value::Number(42.)), Err(SetPropertyError::WrongType));
2377 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2378 assert_eq!(instance.set_property("prop", model_with_string), Err(SetPropertyError::WrongType));
2379 check_model(instance.get_property("prop").unwrap(), &[14., 15., 16.]);
2380
2381 assert_eq!(instance.set_property("prop", empty_model), Ok(()));
2382 check_model(instance.get_property("prop").unwrap(), &[]);
2383}
2384
2385#[test]
2386fn lang_type_to_value_type() {
2387 use i_slint_compiler::langtype::Struct as LangStruct;
2388 use std::collections::BTreeMap;
2389
2390 assert_eq!(ValueType::from(LangType::Void), ValueType::Void);
2391 assert_eq!(ValueType::from(LangType::Float32), ValueType::Number);
2392 assert_eq!(ValueType::from(LangType::Int32), ValueType::Number);
2393 assert_eq!(ValueType::from(LangType::Duration), ValueType::Number);
2394 assert_eq!(ValueType::from(LangType::Angle), ValueType::Number);
2395 assert_eq!(ValueType::from(LangType::PhysicalLength), ValueType::Number);
2396 assert_eq!(ValueType::from(LangType::LogicalLength), ValueType::Number);
2397 assert_eq!(ValueType::from(LangType::Percent), ValueType::Number);
2398 assert_eq!(ValueType::from(LangType::UnitProduct(Vec::new())), ValueType::Number);
2399 assert_eq!(ValueType::from(LangType::String), ValueType::String);
2400 assert_eq!(ValueType::from(LangType::Color), ValueType::Brush);
2401 assert_eq!(ValueType::from(LangType::Brush), ValueType::Brush);
2402 assert_eq!(ValueType::from(LangType::Array(Arc::new(LangType::Void))), ValueType::Model);
2403 assert_eq!(ValueType::from(LangType::Bool), ValueType::Bool);
2404 assert_eq!(
2405 ValueType::from(LangType::Struct(Arc::new(LangStruct::new(
2406 BTreeMap::default(),
2407 i_slint_compiler::langtype::StructName::None
2408 )))),
2409 ValueType::Struct
2410 );
2411 assert_eq!(ValueType::from(LangType::Image), ValueType::Image);
2412}
2413
2414#[test]
2415fn test_multi_components() {
2416 i_slint_backend_testing::init_no_event_loop();
2417 let result = spin_on::spin_on(
2418 Compiler::default().build_from_source(
2419 r#"
2420 export struct Settings {
2421 string_value: string,
2422 }
2423 export global ExpGlo { in-out property <int> test: 42; }
2424 component Common {
2425 in-out property <Settings> settings: { string_value: "Hello", };
2426 }
2427 export component Xyz inherits Window {
2428 in-out property <int> aaa: 8;
2429 }
2430 export component Foo {
2431
2432 in-out property <int> test: 42;
2433 c := Common {}
2434 }
2435 export component Bar inherits Window {
2436 in-out property <int> blah: 78;
2437 c := Common {}
2438 }
2439 "#
2440 .into(),
2441 PathBuf::from("hello.slint"),
2442 ),
2443 );
2444
2445 assert!(!result.has_errors(), "Error {:?}", result.diagnostics().collect::<Vec<_>>());
2446 let mut components = result.component_names().collect::<Vec<_>>();
2447 components.sort();
2448 assert_eq!(components, vec!["Bar", "Xyz"]);
2449 let diag = result.diagnostics().collect::<Vec<_>>();
2450 assert_eq!(diag.len(), 1);
2451 assert_eq!(diag[0].level(), DiagnosticLevel::Warning);
2452 assert_eq!(
2453 diag[0].message(),
2454 "Exported component 'Foo' doesn't inherit Window. No code will be generated for it"
2455 );
2456
2457 let comp1 = result.component("Xyz").unwrap();
2458 assert_eq!(comp1.name(), "Xyz");
2459 let instance1a = comp1.create().unwrap();
2460 let comp2 = result.component("Bar").unwrap();
2461 let instance2 = comp2.create().unwrap();
2462 let instance1b = comp1.create().unwrap();
2463
2464 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2466 assert_eq!(instance1a.set_global_property("ExpGlo", "test", Value::Number(88.0)), Ok(()));
2467 assert_eq!(instance2.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2468 assert_eq!(instance1b.get_global_property("ExpGlo", "test"), Ok(Value::Number(42.0)));
2469 assert_eq!(instance1a.get_global_property("ExpGlo", "test"), Ok(Value::Number(88.0)));
2470
2471 assert!(result.component("Settings").is_none());
2472 assert!(result.component("Foo").is_none());
2473 assert!(result.component("Common").is_none());
2474 assert!(result.component("ExpGlo").is_none());
2475 assert!(result.component("xyz").is_none());
2476}
2477
2478#[cfg(all(test, feature = "internal-highlight"))]
2479fn compile(code: &str) -> (ComponentInstance, PathBuf) {
2480 i_slint_backend_testing::init_no_event_loop();
2481 let mut compiler = Compiler::default();
2482 compiler.set_style("fluent".into());
2483 let path = PathBuf::from("/tmp/test.slint");
2484
2485 let compile_result =
2486 spin_on::spin_on(compiler.build_from_source(code.to_string(), path.clone()));
2487
2488 for d in &compile_result.diagnostics {
2489 eprintln!("{d}");
2490 }
2491
2492 assert!(!compile_result.has_errors());
2493
2494 let definition = compile_result.components().next().unwrap();
2495 let instance = definition.create().unwrap();
2496
2497 (instance, path)
2498}
2499
2500#[cfg(feature = "internal-highlight")]
2501#[test]
2502fn test_element_node_at_source_code_position() {
2503 let code = r#"
2504component Bar1 {}
2505
2506component Foo1 {
2507}
2508
2509export component Foo2 inherits Window {
2510 Bar1 {}
2511 Foo1 {}
2512}"#;
2513
2514 let (handle, path) = compile(code);
2515
2516 for i in 0..code.len() as u32 {
2517 let elements = handle.element_node_at_source_code_position(&path, i);
2518 eprintln!("{i}: {}", code.as_bytes()[i as usize] as char);
2519 match i {
2520 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()),
2526 }
2527 }
2528}
2529
2530#[cfg(feature = "internal-highlight")]
2534#[test]
2535fn test_element_positions_instances_and_repeaters() {
2536 use i_slint_core::graphics::euclid;
2537 let code = r#"
2538component MyBox inherits Rectangle {
2539 width: 50px;
2540 height: 50px;
2541}
2542
2543export component Foo3 inherits Window {
2544 width: 400px;
2545 height: 400px;
2546 b1 := MyBox { x: 0px; y: 0px; }
2547 b2 := MyBox { x: 200px; y: 200px; }
2548 for xo in [0, 1, 2]: Rectangle {
2549 x: xo * 10px;
2550 y: 300px;
2551 width: 10px;
2552 height: 10px;
2553 }
2554}"#;
2555
2556 let (handle, path) = compile(code);
2557
2558 let element_at = |pattern: &str| {
2559 let offset = code.find(pattern).unwrap() as u32;
2560 let elements = handle.element_node_at_source_code_position(&path, offset);
2561 assert_eq!(elements.len(), 1, "expected one element at {pattern:?}");
2562 elements.into_iter().next().unwrap().0
2563 };
2564
2565 let b1_rects = handle.element_positions(&element_at("MyBox { x: 0px"));
2567 assert_eq!(b1_rects.len(), 1, "{b1_rects:?}");
2568 assert_eq!(b1_rects[0].rect.origin, euclid::point2(0., 0.));
2569
2570 let b2_rects = handle.element_positions(&element_at("MyBox { x: 200px"));
2571 assert_eq!(b2_rects.len(), 1, "{b2_rects:?}");
2572 assert_eq!(b2_rects[0].rect.origin, euclid::point2(200., 200.));
2573
2574 let def_rects = handle.element_positions(&element_at("Rectangle {\n width: 50px"));
2576 assert_eq!(def_rects.len(), 2, "{def_rects:?}");
2577
2578 let repeated = element_at("Rectangle {\n x: xo");
2580 let mut row_rects = handle.element_positions(&repeated);
2581 row_rects.sort_by(|a, b| a.rect.origin.x.total_cmp(&b.rect.origin.x));
2582 assert_eq!(row_rects.len(), 3, "{row_rects:?}");
2583 for (i, r) in row_rects.iter().enumerate() {
2584 assert_eq!(r.rect.origin, euclid::point2(i as f32 * 10., 300.));
2585 assert_eq!(r.rect.size, euclid::size2(10., 10.));
2586 }
2587
2588 let offset = code.find("Rectangle {\n x: xo").unwrap() as u32;
2591 assert_eq!(handle.component_positions(&path, offset).len(), 3);
2592 assert!(handle.component_positions(&path, code.len() as u32 - 1).is_empty());
2593}