-
Notifications
You must be signed in to change notification settings - Fork 660
/
Copy pathapi.rs
2222 lines (2032 loc) · 83.6 KB
/
api.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
use i_slint_compiler::langtype::Type as LangType;
use i_slint_core::component_factory::ComponentFactory;
#[cfg(feature = "internal")]
use i_slint_core::component_factory::FactoryContext;
use i_slint_core::graphics::euclid::approxeq::ApproxEq as _;
use i_slint_core::model::{Model, ModelExt, ModelRc};
#[cfg(feature = "internal")]
use i_slint_core::window::WindowInner;
use i_slint_core::{PathData, SharedVector};
use smol_str::{SmolStr, StrExt};
use std::borrow::Cow;
use std::collections::HashMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::rc::Rc;
#[doc(inline)]
pub use i_slint_compiler::diagnostics::{Diagnostic, DiagnosticLevel};
pub use i_slint_core::api::*;
// keep in sync with api/rs/slint/lib.rs
pub use i_slint_backend_selector::api::*;
pub use i_slint_core::graphics::{
Brush, Color, Image, LoadImageError, Rgb8Pixel, Rgba8Pixel, RgbaColor, SharedPixelBuffer,
};
use i_slint_core::items::*;
use crate::dynamic_item_tree::ErasedItemTreeBox;
#[cfg(any(feature = "internal", target_arch = "wasm32"))]
use crate::dynamic_item_tree::WindowOptions;
/// This enum represents the different public variants of the [`Value`] enum, without
/// the contained values.
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(i8)]
#[non_exhaustive]
pub enum ValueType {
/// The variant that expresses the non-type. This is the default.
Void,
/// An `int` or a `float` (this is also used for unit based type such as `length` or `angle`)
Number,
/// Correspond to the `string` type in .slint
String,
/// Correspond to the `bool` type in .slint
Bool,
/// A model (that includes array in .slint)
Model,
/// An object
Struct,
/// Correspond to `brush` or `color` type in .slint. For color, this is then a [`Brush::SolidColor`]
Brush,
/// Correspond to `image` type in .slint.
Image,
/// The type is not a public type but something internal.
#[doc(hidden)]
Other = -1,
}
impl From<LangType> for ValueType {
fn from(ty: LangType) -> Self {
match ty {
LangType::Float32
| LangType::Int32
| LangType::Duration
| LangType::Angle
| LangType::PhysicalLength
| LangType::LogicalLength
| LangType::Percent
| LangType::UnitProduct(_) => Self::Number,
LangType::String => Self::String,
LangType::Color => Self::Brush,
LangType::Brush => Self::Brush,
LangType::Array(_) => Self::Model,
LangType::Bool => Self::Bool,
LangType::Struct { .. } => Self::Struct,
LangType::Void => Self::Void,
LangType::Image => Self::Image,
_ => Self::Other,
}
}
}
/// This is a dynamically typed value used in the Slint interpreter.
/// It can hold a value of different types, and you should use the
/// [`From`] or [`TryFrom`] traits to access the value.
///
/// ```
/// # use slint_interpreter::*;
/// use core::convert::TryInto;
/// // create a value containing an integer
/// let v = Value::from(100u32);
/// assert_eq!(v.try_into(), Ok(100u32));
/// ```
#[derive(Clone, Default)]
#[non_exhaustive]
#[repr(u8)]
pub enum Value {
/// There is nothing in this value. That's the default.
/// For example, a function that do not return a result would return a Value::Void
#[default]
Void = 0,
/// An `int` or a `float` (this is also used for unit based type such as `length` or `angle`)
Number(f64) = 1,
/// Correspond to the `string` type in .slint
String(SharedString) = 2,
/// Correspond to the `bool` type in .slint
Bool(bool) = 3,
/// Correspond to the `image` type in .slint
Image(Image) = 4,
/// A model (that includes array in .slint)
Model(ModelRc<Value>) = 5,
/// An object
Struct(Struct) = 6,
/// Correspond to `brush` or `color` type in .slint. For color, this is then a [`Brush::SolidColor`]
Brush(Brush) = 7,
#[doc(hidden)]
/// The elements of a path
PathData(PathData) = 8,
#[doc(hidden)]
/// An easing curve
EasingCurve(i_slint_core::animations::EasingCurve) = 9,
#[doc(hidden)]
/// An enumeration, like `TextHorizontalAlignment::align_center`, represented by `("TextHorizontalAlignment", "align_center")`.
/// FIXME: consider representing that with a number?
EnumerationValue(String, String) = 10,
#[doc(hidden)]
LayoutCache(SharedVector<f32>) = 11,
#[doc(hidden)]
/// Correspond to the `component-factory` type in .slint
ComponentFactory(ComponentFactory) = 12,
}
impl Value {
/// Returns the type variant that this value holds without the containing value.
pub fn value_type(&self) -> ValueType {
match self {
Value::Void => ValueType::Void,
Value::Number(_) => ValueType::Number,
Value::String(_) => ValueType::String,
Value::Bool(_) => ValueType::Bool,
Value::Model(_) => ValueType::Model,
Value::Struct(_) => ValueType::Struct,
Value::Brush(_) => ValueType::Brush,
Value::Image(_) => ValueType::Image,
_ => ValueType::Other,
}
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match self {
Value::Void => matches!(other, Value::Void),
Value::Number(lhs) => matches!(other, Value::Number(rhs) if lhs.approx_eq(rhs)),
Value::String(lhs) => matches!(other, Value::String(rhs) if lhs == rhs),
Value::Bool(lhs) => matches!(other, Value::Bool(rhs) if lhs == rhs),
Value::Image(lhs) => matches!(other, Value::Image(rhs) if lhs == rhs),
Value::Model(lhs) => {
if let Value::Model(rhs) = other {
lhs == rhs
} else {
false
}
}
Value::Struct(lhs) => matches!(other, Value::Struct(rhs) if lhs == rhs),
Value::Brush(lhs) => matches!(other, Value::Brush(rhs) if lhs == rhs),
Value::PathData(lhs) => matches!(other, Value::PathData(rhs) if lhs == rhs),
Value::EasingCurve(lhs) => matches!(other, Value::EasingCurve(rhs) if lhs == rhs),
Value::EnumerationValue(lhs_name, lhs_value) => {
matches!(other, Value::EnumerationValue(rhs_name, rhs_value) if lhs_name == rhs_name && lhs_value == rhs_value)
}
Value::LayoutCache(lhs) => matches!(other, Value::LayoutCache(rhs) if lhs == rhs),
Value::ComponentFactory(lhs) => {
matches!(other, Value::ComponentFactory(rhs) if lhs == rhs)
}
}
}
}
impl std::fmt::Debug for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Void => write!(f, "Value::Void"),
Value::Number(n) => write!(f, "Value::Number({n:?})"),
Value::String(s) => write!(f, "Value::String({s:?})"),
Value::Bool(b) => write!(f, "Value::Bool({b:?})"),
Value::Image(i) => write!(f, "Value::Image({i:?})"),
Value::Model(m) => {
write!(f, "Value::Model(")?;
f.debug_list().entries(m.iter()).finish()?;
write!(f, "])")
}
Value::Struct(s) => write!(f, "Value::Struct({s:?})"),
Value::Brush(b) => write!(f, "Value::Brush({b:?})"),
Value::PathData(e) => write!(f, "Value::PathElements({e:?})"),
Value::EasingCurve(c) => write!(f, "Value::EasingCurve({c:?})"),
Value::EnumerationValue(n, v) => write!(f, "Value::EnumerationValue({n:?}, {v:?})"),
Value::LayoutCache(v) => write!(f, "Value::LayoutCache({v:?})"),
Value::ComponentFactory(factory) => write!(f, "Value::ComponentFactory({factory:?})"),
}
}
}
/// Helper macro to implement the From / TryFrom for Value
///
/// For example
/// `declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64] );`
/// means that `Value::Number` can be converted to / from each of the said rust types
///
/// For `Value::Object` mapping to a rust `struct`, one can use [`declare_value_struct_conversion!`]
/// And for `Value::EnumerationValue` which maps to a rust `enum`, one can use [`declare_value_struct_conversion!`]
macro_rules! declare_value_conversion {
( $value:ident => [$($ty:ty),*] ) => {
$(
impl From<$ty> for Value {
fn from(v: $ty) -> Self {
Value::$value(v as _)
}
}
impl TryFrom<Value> for $ty {
type Error = Value;
fn try_from(v: Value) -> Result<$ty, Self::Error> {
match v {
Value::$value(x) => Ok(x as _),
_ => Err(v)
}
}
}
)*
};
}
declare_value_conversion!(Number => [u32, u64, i32, i64, f32, f64, usize, isize] );
declare_value_conversion!(String => [SharedString] );
declare_value_conversion!(Bool => [bool] );
declare_value_conversion!(Image => [Image] );
declare_value_conversion!(Struct => [Struct] );
declare_value_conversion!(Brush => [Brush] );
declare_value_conversion!(PathData => [PathData]);
declare_value_conversion!(EasingCurve => [i_slint_core::animations::EasingCurve]);
declare_value_conversion!(LayoutCache => [SharedVector<f32>] );
declare_value_conversion!(ComponentFactory => [ComponentFactory] );
/// Implement From / TryFrom for Value that convert a `struct` to/from `Value::Struct`
macro_rules! declare_value_struct_conversion {
(struct $name:path { $($field:ident),* $(, ..$extra:expr)? }) => {
impl From<$name> for Value {
fn from($name { $($field),* , .. }: $name) -> Self {
let mut struct_ = Struct::default();
$(struct_.set_field(stringify!($field).into(), $field.into());)*
Value::Struct(struct_)
}
}
impl TryFrom<Value> for $name {
type Error = ();
fn try_from(v: Value) -> Result<$name, Self::Error> {
#[allow(clippy::field_reassign_with_default)]
match v {
Value::Struct(x) => {
type Ty = $name;
#[allow(unused)]
let mut res: Ty = Ty::default();
$(let mut res: Ty = $extra;)?
$(res.$field = x.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
Ok(res)
}
_ => Err(()),
}
}
}
};
($(
$(#[$struct_attr:meta])*
struct $Name:ident {
@name = $inner_name:literal
export {
$( $(#[$pub_attr:meta])* $pub_field:ident : $pub_type:ty, )*
}
private {
$( $(#[$pri_attr:meta])* $pri_field:ident : $pri_type:ty, )*
}
}
)*) => {
$(
impl From<$Name> for Value {
fn from(item: $Name) -> Self {
let mut struct_ = Struct::default();
$(struct_.set_field(stringify!($pub_field).into(), item.$pub_field.into());)*
$(handle_private!(SET $Name $pri_field, struct_, item);)*
Value::Struct(struct_)
}
}
impl TryFrom<Value> for $Name {
type Error = ();
fn try_from(v: Value) -> Result<$Name, Self::Error> {
#[allow(clippy::field_reassign_with_default)]
match v {
Value::Struct(x) => {
type Ty = $Name;
#[allow(unused)]
let mut res: Ty = Ty::default();
$(res.$pub_field = x.get_field(stringify!($pub_field)).ok_or(())?.clone().try_into().map_err(|_|())?;)*
$(handle_private!(GET $Name $pri_field, x, res);)*
Ok(res)
}
_ => Err(()),
}
}
}
)*
};
}
macro_rules! handle_private {
(SET StateInfo $field:ident, $struct_:ident, $item:ident) => {
$struct_.set_field(stringify!($field).into(), $item.$field.into())
};
(SET $_:ident $field:ident, $struct_:ident, $item:ident) => {{}};
(GET StateInfo $field:ident, $struct_:ident, $item:ident) => {
$item.$field =
$struct_.get_field(stringify!($field)).ok_or(())?.clone().try_into().map_err(|_| ())?
};
(GET $_:ident $field:ident, $struct_:ident, $item:ident) => {{}};
}
declare_value_struct_conversion!(struct i_slint_core::layout::LayoutInfo { min, max, min_percent, max_percent, preferred, stretch });
declare_value_struct_conversion!(struct i_slint_core::graphics::Point { x, y, ..Default::default()});
declare_value_struct_conversion!(struct i_slint_core::api::LogicalPosition { x, y });
i_slint_common::for_each_builtin_structs!(declare_value_struct_conversion);
/// Implement From / TryFrom for Value that convert an `enum` to/from `Value::EnumerationValue`
///
/// The `enum` must derive `Display` and `FromStr`
/// (can be done with `strum_macros::EnumString`, `strum_macros::Display` derive macro)
macro_rules! declare_value_enum_conversion {
($( $(#[$enum_doc:meta])* enum $Name:ident { $($body:tt)* })*) => { $(
impl From<i_slint_core::items::$Name> for Value {
fn from(v: i_slint_core::items::$Name) -> Self {
Value::EnumerationValue(
stringify!($Name).to_owned(),
v.to_string().trim_start_matches("r#").replace('_', "-"),
)
}
}
impl TryFrom<Value> for i_slint_core::items::$Name {
type Error = ();
fn try_from(v: Value) -> Result<i_slint_core::items::$Name, ()> {
use std::str::FromStr;
match v {
Value::EnumerationValue(enumeration, value) => {
if enumeration != stringify!($Name) {
return Err(());
}
<i_slint_core::items::$Name>::from_str(value.as_str())
.or_else(|_| {
let norm = value.as_str().replace('-', "_");
<i_slint_core::items::$Name>::from_str(&norm)
.or_else(|_| <i_slint_core::items::$Name>::from_str(&format!("r#{}", norm)))
})
.map_err(|_| ())
}
_ => Err(()),
}
}
}
)*};
}
i_slint_common::for_each_enums!(declare_value_enum_conversion);
impl From<i_slint_core::animations::Instant> for Value {
fn from(value: i_slint_core::animations::Instant) -> Self {
Value::Number(value.0 as _)
}
}
impl TryFrom<Value> for i_slint_core::animations::Instant {
type Error = ();
fn try_from(v: Value) -> Result<i_slint_core::animations::Instant, Self::Error> {
match v {
Value::Number(x) => Ok(i_slint_core::animations::Instant(x as _)),
_ => Err(()),
}
}
}
impl From<()> for Value {
#[inline]
fn from(_: ()) -> Self {
Value::Void
}
}
impl TryFrom<Value> for () {
type Error = ();
#[inline]
fn try_from(_: Value) -> Result<(), Self::Error> {
Ok(())
}
}
impl From<Color> for Value {
#[inline]
fn from(c: Color) -> Self {
Value::Brush(Brush::SolidColor(c))
}
}
impl TryFrom<Value> for Color {
type Error = Value;
#[inline]
fn try_from(v: Value) -> Result<Color, Self::Error> {
match v {
Value::Brush(Brush::SolidColor(c)) => Ok(c),
_ => Err(v),
}
}
}
impl From<i_slint_core::lengths::LogicalLength> for Value {
#[inline]
fn from(l: i_slint_core::lengths::LogicalLength) -> Self {
Value::Number(l.get() as _)
}
}
impl TryFrom<Value> for i_slint_core::lengths::LogicalLength {
type Error = Value;
#[inline]
fn try_from(v: Value) -> Result<i_slint_core::lengths::LogicalLength, Self::Error> {
match v {
Value::Number(n) => Ok(i_slint_core::lengths::LogicalLength::new(n as _)),
_ => Err(v),
}
}
}
impl<T: Into<Value> + 'static> From<ModelRc<T>> for Value {
fn from(m: ModelRc<T>) -> Self {
if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<Value>>(&m) {
Value::Model(v.clone())
} else {
Value::Model(ModelRc::new(m.map(|v| v.into())))
}
}
}
impl<T: TryFrom<Value> + Default + 'static> TryFrom<Value> for ModelRc<T> {
type Error = Value;
#[inline]
fn try_from(v: Value) -> Result<ModelRc<T>, Self::Error> {
match v {
Value::Model(m) => {
if let Some(v) = <dyn core::any::Any>::downcast_ref::<ModelRc<T>>(&m) {
Ok(v.clone())
} else {
Ok(ModelRc::new(m.map(|v| T::try_from(v).unwrap_or_default())))
}
}
_ => Err(v),
}
}
}
#[test]
fn value_model_conversion() {
use i_slint_core::model::*;
let m = ModelRc::new(VecModel::from_slice(&[Value::Number(42.), Value::Number(12.)]));
let v = Value::from(m.clone());
assert_eq!(v, Value::Model(m.clone()));
let m2: ModelRc<Value> = v.clone().try_into().unwrap();
assert_eq!(m2, m);
let int_model: ModelRc<i32> = v.clone().try_into().unwrap();
assert_eq!(int_model.row_count(), 2);
assert_eq!(int_model.iter().collect::<Vec<_>>(), vec![42, 12]);
let Value::Model(m3) = int_model.clone().into() else { panic!("not a model?") };
assert_eq!(m3.row_count(), 2);
assert_eq!(m3.iter().collect::<Vec<_>>(), vec![Value::Number(42.), Value::Number(12.)]);
let str_model: ModelRc<SharedString> = v.clone().try_into().unwrap();
assert_eq!(str_model.row_count(), 2);
// Value::Int doesn't convert to string, but since the mapping can't report error, we get the default constructed string
assert_eq!(str_model.iter().collect::<Vec<_>>(), vec!["", ""]);
let err: Result<ModelRc<Value>, _> = Value::Bool(true).try_into();
assert!(err.is_err());
}
/// Normalize the identifier to use dashes
pub(crate) fn normalize_identifier(ident: &str) -> Cow<'_, str> {
if ident.contains('_') {
ident.replace('_', "-").into()
} else {
ident.into()
}
}
pub(crate) fn normalize_identifier_smolstr(ident: &str) -> SmolStr {
if ident.contains('_') {
ident.replace_smolstr("_", "-")
} else {
ident.into()
}
}
/// This type represents a runtime instance of structure in `.slint`.
///
/// This can either be an instance of a name structure introduced
/// with the `struct` keyword in the .slint file, or an anonymous struct
/// written with the `{ key: value, }` notation.
///
/// It can be constructed with the [`FromIterator`] trait, and converted
/// into or from a [`Value`] with the [`From`], [`TryFrom`] trait
///
///
/// ```
/// # use slint_interpreter::*;
/// use core::convert::TryInto;
/// // Construct a value from a key/value iterator
/// let value : Value = [("foo".into(), 45u32.into()), ("bar".into(), true.into())]
/// .iter().cloned().collect::<Struct>().into();
///
/// // get the properties of a `{ foo: 45, bar: true }`
/// let s : Struct = value.try_into().unwrap();
/// assert_eq!(s.get_field("foo").cloned().unwrap().try_into(), Ok(45u32));
/// ```
#[derive(Clone, PartialEq, Debug, Default)]
pub struct Struct(pub(crate) HashMap<String, Value>);
impl Struct {
/// Get the value for a given struct field
pub fn get_field(&self, name: &str) -> Option<&Value> {
self.0.get(&*normalize_identifier(name))
}
/// Set the value of a given struct field
pub fn set_field(&mut self, name: String, value: Value) {
if name.contains('_') {
self.0.insert(name.replace('_', "-"), value);
} else {
self.0.insert(name, value);
}
}
/// Iterate over all the fields in this struct
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
self.0.iter().map(|(a, b)| (a.as_str(), b))
}
}
impl FromIterator<(String, Value)> for Struct {
fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
Self(
iter.into_iter()
.map(|(s, v)| (if s.contains('_') { s.replace('_', "-") } else { s }, v))
.collect(),
)
}
}
/// ComponentCompiler is deprecated, use [`Compiler`] instead
#[deprecated(note = "Use slint_interpreter::Compiler instead")]
pub struct ComponentCompiler {
config: i_slint_compiler::CompilerConfiguration,
diagnostics: Vec<Diagnostic>,
}
#[allow(deprecated)]
impl Default for ComponentCompiler {
fn default() -> Self {
let mut config = i_slint_compiler::CompilerConfiguration::new(
i_slint_compiler::generator::OutputFormat::Interpreter,
);
config.components_to_generate = i_slint_compiler::ComponentSelection::LastExported;
Self { config, diagnostics: vec![] }
}
}
#[allow(deprecated)]
impl ComponentCompiler {
/// Returns a new ComponentCompiler.
pub fn new() -> Self {
Self::default()
}
/// Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
self.config.include_paths = include_paths;
}
/// Returns the include paths the component compiler is currently configured with.
pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
&self.config.include_paths
}
/// Sets the library paths used for looking up `@library` imports to the specified map of library names to paths.
pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
self.config.library_paths = library_paths;
}
/// Returns the library paths the component compiler is currently configured with.
pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
&self.config.library_paths
}
/// Sets the style to be used for widgets.
///
/// Use the "material" style as widget style when compiling:
/// ```rust
/// use slint_interpreter::{ComponentDefinition, ComponentCompiler, ComponentHandle};
///
/// let mut compiler = ComponentCompiler::default();
/// compiler.set_style("material".into());
/// let definition =
/// spin_on::spin_on(compiler.build_from_path("hello.slint"));
/// ```
pub fn set_style(&mut self, style: String) {
self.config.style = Some(style);
}
/// Returns the widget style the compiler is currently using when compiling .slint files.
pub fn style(&self) -> Option<&String> {
self.config.style.as_ref()
}
/// The domain used for translations
pub fn set_translation_domain(&mut self, domain: String) {
self.config.translation_domain = Some(domain);
}
/// Sets the callback that will be invoked when loading imported .slint files. The specified
/// `file_loader_callback` parameter will be called with a canonical file path as argument
/// and is expected to return a future that, when resolved, provides the source code of the
/// .slint file to be imported as a string.
/// If an error is returned, then the build will abort with that error.
/// If None is returned, it means the normal resolution algorithm will proceed as if the hook
/// was not in place (i.e: load from the file system following the include paths)
pub fn set_file_loader(
&mut self,
file_loader_fallback: impl Fn(&Path) -> core::pin::Pin<Box<dyn Future<Output = Option<std::io::Result<String>>>>>
+ 'static,
) {
self.config.open_import_fallback =
Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
}
/// Returns the diagnostics that were produced in the last call to [`Self::build_from_path`] or [`Self::build_from_source`].
pub fn diagnostics(&self) -> &Vec<Diagnostic> {
&self.diagnostics
}
/// Compile a .slint file into a ComponentDefinition
///
/// Returns the compiled `ComponentDefinition` if there were no errors.
///
/// Any diagnostics produced during the compilation, such as warnings or errors, are collected
/// in this ComponentCompiler and can be retrieved after the call using the [`Self::diagnostics()`]
/// function. The [`print_diagnostics`] function can be used to display the diagnostics
/// to the users.
///
/// Diagnostics from previous calls are cleared when calling this function.
///
/// If the path is `"-"`, the file will be read from stdin.
/// If the extension of the file .rs, the first `slint!` macro from a rust file will be extracted
///
/// This function is `async` but in practice, this is only asynchronous if
/// [`Self::set_file_loader`] was called and its future is actually asynchronous.
/// If that is not used, then it is fine to use a very simple executor, such as the one
/// provided by the `spin_on` crate
pub async fn build_from_path<P: AsRef<Path>>(
&mut self,
path: P,
) -> Option<ComponentDefinition> {
let path = path.as_ref();
let source = match i_slint_compiler::diagnostics::load_from_path(path) {
Ok(s) => s,
Err(d) => {
self.diagnostics = vec![d];
return None;
}
};
let r = crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await;
self.diagnostics = r.diagnostics.into_iter().collect();
r.components.into_values().next()
}
/// Compile some .slint code into a ComponentDefinition
///
/// The `path` argument will be used for diagnostics and to compute relative
/// paths while importing.
///
/// Any diagnostics produced during the compilation, such as warnings or errors, are collected
/// in this ComponentCompiler and can be retrieved after the call using the [`Self::diagnostics()`]
/// function. The [`print_diagnostics`] function can be used to display the diagnostics
/// to the users.
///
/// Diagnostics from previous calls are cleared when calling this function.
///
/// This function is `async` but in practice, this is only asynchronous if
/// [`Self::set_file_loader`] is set and its future is actually asynchronous.
/// If that is not used, then it is fine to use a very simple executor, such as the one
/// provided by the `spin_on` crate
pub async fn build_from_source(
&mut self,
source_code: String,
path: PathBuf,
) -> Option<ComponentDefinition> {
let r = crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await;
self.diagnostics = r.diagnostics.into_iter().collect();
r.components.into_values().next()
}
}
/// This is the entry point of the crate, it can be used to load a `.slint` file and
/// compile it into a [`CompilationResult`].
pub struct Compiler {
config: i_slint_compiler::CompilerConfiguration,
}
impl Default for Compiler {
fn default() -> Self {
let config = i_slint_compiler::CompilerConfiguration::new(
i_slint_compiler::generator::OutputFormat::Interpreter,
);
Self { config }
}
}
impl Compiler {
/// Returns a new Compiler.
pub fn new() -> Self {
Self::default()
}
/// Allow access to the underlying `CompilerConfiguration`
///
/// This is an internal function without and ABI or API stability guarantees.
#[doc(hidden)]
#[cfg(feature = "internal")]
pub fn compiler_configuration(
&mut self,
_: i_slint_core::InternalToken,
) -> &mut i_slint_compiler::CompilerConfiguration {
&mut self.config
}
/// Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
pub fn set_include_paths(&mut self, include_paths: Vec<std::path::PathBuf>) {
self.config.include_paths = include_paths;
}
/// Returns the include paths the component compiler is currently configured with.
pub fn include_paths(&self) -> &Vec<std::path::PathBuf> {
&self.config.include_paths
}
/// Sets the library paths used for looking up `@library` imports to the specified map of library names to paths.
pub fn set_library_paths(&mut self, library_paths: HashMap<String, PathBuf>) {
self.config.library_paths = library_paths;
}
/// Returns the library paths the component compiler is currently configured with.
pub fn library_paths(&self) -> &HashMap<String, PathBuf> {
&self.config.library_paths
}
/// Sets the style to be used for widgets.
///
/// Use the "material" style as widget style when compiling:
/// ```rust
/// use slint_interpreter::{ComponentDefinition, Compiler, ComponentHandle};
///
/// let mut compiler = Compiler::default();
/// compiler.set_style("material".into());
/// let result = spin_on::spin_on(compiler.build_from_path("hello.slint"));
/// ```
pub fn set_style(&mut self, style: String) {
self.config.style = Some(style);
}
/// Returns the widget style the compiler is currently using when compiling .slint files.
pub fn style(&self) -> Option<&String> {
self.config.style.as_ref()
}
/// The domain used for translations
pub fn set_translation_domain(&mut self, domain: String) {
self.config.translation_domain = Some(domain);
}
/// Sets the callback that will be invoked when loading imported .slint files. The specified
/// `file_loader_callback` parameter will be called with a canonical file path as argument
/// and is expected to return a future that, when resolved, provides the source code of the
/// .slint file to be imported as a string.
/// If an error is returned, then the build will abort with that error.
/// If None is returned, it means the normal resolution algorithm will proceed as if the hook
/// was not in place (i.e: load from the file system following the include paths)
pub fn set_file_loader(
&mut self,
file_loader_fallback: impl Fn(&Path) -> core::pin::Pin<Box<dyn Future<Output = Option<std::io::Result<String>>>>>
+ 'static,
) {
self.config.open_import_fallback =
Some(Rc::new(move |path| file_loader_fallback(Path::new(path.as_str()))));
}
/// Compile a .slint file
///
/// Returns a structure that holds the diagnostics and the compiled components.
///
/// Any diagnostics produced during the compilation, such as warnings or errors, can be retrieved
/// after the call using [`CompilationResult::diagnostics()`].
///
/// If the file was compiled without error, the list of component names can be obtained with
/// [`CompilationResult::component_names`], and the compiled components themselves with
/// [`CompilationResult::component()`].
///
/// If the path is `"-"`, the file will be read from stdin.
/// If the extension of the file .rs, the first `slint!` macro from a rust file will be extracted
///
/// This function is `async` but in practice, this is only asynchronous if
/// [`Self::set_file_loader`] was called and its future is actually asynchronous.
/// If that is not used, then it is fine to use a very simple executor, such as the one
/// provided by the `spin_on` crate
pub async fn build_from_path<P: AsRef<Path>>(&self, path: P) -> CompilationResult {
let path = path.as_ref();
let source = match i_slint_compiler::diagnostics::load_from_path(path) {
Ok(s) => s,
Err(d) => {
let mut diagnostics = i_slint_compiler::diagnostics::BuildDiagnostics::default();
diagnostics.push_compiler_error(d);
return CompilationResult {
components: HashMap::new(),
diagnostics: diagnostics.into_iter().collect(),
#[cfg(feature = "internal")]
structs_and_enums: Vec::new(),
#[cfg(feature = "internal")]
named_exports: Vec::new(),
};
}
};
crate::dynamic_item_tree::load(source, path.into(), self.config.clone()).await
}
/// Compile some .slint code
///
/// The `path` argument will be used for diagnostics and to compute relative
/// paths while importing.
///
/// Any diagnostics produced during the compilation, such as warnings or errors, can be retrieved
/// after the call using [`CompilationResult::diagnostics()`].
///
/// This function is `async` but in practice, this is only asynchronous if
/// [`Self::set_file_loader`] is set and its future is actually asynchronous.
/// If that is not used, then it is fine to use a very simple executor, such as the one
/// provided by the `spin_on` crate
pub async fn build_from_source(&self, source_code: String, path: PathBuf) -> CompilationResult {
crate::dynamic_item_tree::load(source_code, path, self.config.clone()).await
}
}
/// The result of a compilation
///
/// If [`Self::has_errors()`] is true, then the compilation failed.
/// The [`Self::diagnostics()`] function can be used to retrieve the diagnostics (errors and/or warnings)
/// or [`Self::print_diagnostics()`] can be used to print them to stderr.
/// The components can be retrieved using [`Self::components()`]
#[derive(Clone)]
pub struct CompilationResult {
pub(crate) components: HashMap<String, ComponentDefinition>,
pub(crate) diagnostics: Vec<Diagnostic>,
#[cfg(feature = "internal")]
pub(crate) structs_and_enums: Vec<LangType>,
/// For `export { Foo as Bar }` this vec contains tuples of (`Foo`, `Bar`)
#[cfg(feature = "internal")]
pub(crate) named_exports: Vec<(String, String)>,
}
impl core::fmt::Debug for CompilationResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompilationResult")
.field("components", &self.components.keys())
.field("diagnostics", &self.diagnostics)
.finish()
}
}
impl CompilationResult {
/// Returns true if the compilation failed.
/// The errors can be retrieved using the [`Self::diagnostics()`] function.
pub fn has_errors(&self) -> bool {
self.diagnostics().any(|diag| diag.level() == DiagnosticLevel::Error)
}
/// Return an iterator over the diagnostics.
///
/// You can also call [`Self::print_diagnostics()`] to output the diagnostics to stderr
pub fn diagnostics(&self) -> impl Iterator<Item = Diagnostic> + '_ {
self.diagnostics.iter().cloned()
}
/// Print the diagnostics to stderr
///
/// The diagnostics are printed in the same style as rustc errors
///
/// This function is available when the `display-diagnostics` is enabled.
#[cfg(feature = "display-diagnostics")]
pub fn print_diagnostics(&self) {
print_diagnostics(&self.diagnostics)
}
/// Returns an iterator over the compiled components.
pub fn components(&self) -> impl Iterator<Item = ComponentDefinition> + '_ {
self.components.values().cloned()
}
/// Returns the names of the components that were compiled.
pub fn component_names(&self) -> impl Iterator<Item = &str> + '_ {
self.components.keys().map(|s| s.as_str())
}
/// Return the component definition for the given name.
/// If the component does not exist, then `None` is returned.
pub fn component(&self, name: &str) -> Option<ComponentDefinition> {
self.components.get(name).cloned()
}
/// This is an internal function without API stability guarantees.
#[doc(hidden)]
#[cfg(feature = "internal")]
pub fn structs_and_enums(
&self,
_: i_slint_core::InternalToken,
) -> impl Iterator<Item = &LangType> {
self.structs_and_enums.iter()
}
/// This is an internal function without API stability guarantees.
/// Returns the list of named export aliases as tuples (`export { Foo as Bar}` is (`Foo`, `Bar` tuple)).
#[doc(hidden)]
#[cfg(feature = "internal")]
pub fn named_exports(
&self,
_: i_slint_core::InternalToken,
) -> impl Iterator<Item = &(String, String)> {
self.named_exports.iter()
}
}
/// ComponentDefinition is a representation of a compiled component from .slint markup.
///
/// It can be constructed from a .slint file using the [`Compiler::build_from_path`] or [`Compiler::build_from_source`] functions.
/// And then it can be instantiated with the [`Self::create`] function.
///
/// The ComponentDefinition acts as a factory to create new instances. When you've finished
/// creating the instances it is safe to drop the ComponentDefinition.
#[derive(Clone)]
pub struct ComponentDefinition {
pub(crate) inner: crate::dynamic_item_tree::ErasedItemTreeDescription,
}
impl ComponentDefinition {
/// Creates a new instance of the component and returns a shared handle to it.
pub fn create(&self) -> Result<ComponentInstance, PlatformError> {
generativity::make_guard!(guard);
let instance = self.inner.unerase(guard).clone().create(Default::default())?;
// Make sure the window adapter is created so call to `window()` do not panic later.
instance.window_adapter_ref()?;
Ok(ComponentInstance { inner: instance })
}
/// Creates a new instance of the component and returns a shared handle to it.
#[doc(hidden)]
#[cfg(feature = "internal")]
pub fn create_embedded(&self, ctx: FactoryContext) -> Result<ComponentInstance, PlatformError> {
generativity::make_guard!(guard);
Ok(ComponentInstance {
inner: self.inner.unerase(guard).clone().create(WindowOptions::Embed {
parent_item_tree: ctx.parent_item_tree,
parent_item_tree_index: ctx.parent_item_tree_index,
})?,
})
}
/// Instantiate the component using an existing window.
#[doc(hidden)]
#[cfg(feature = "internal")]
pub fn create_with_existing_window(
&self,
window: &Window,
) -> Result<ComponentInstance, PlatformError> {
generativity::make_guard!(guard);
Ok(ComponentInstance {
inner: self.inner.unerase(guard).clone().create(WindowOptions::UseExistingWindow(
WindowInner::from_pub(window).window_adapter(),
))?,
})
}