forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyperegister.rs
More file actions
834 lines (755 loc) · 31.3 KB
/
typeregister.rs
File metadata and controls
834 lines (755 loc) · 31.3 KB
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
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore imum
use smol_str::{SmolStr, StrExt, ToSmolStr};
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;
use crate::expression_tree::BuiltinFunction;
use crate::langtype::{
BuiltinElement, BuiltinPrivateStruct, BuiltinPropertyDefault, BuiltinPropertyInfo,
BuiltinPublicStruct, ElementType, Enumeration, Function, PropertyLookupResult, Struct, Type,
};
use crate::object_tree::{Component, PropertyVisibility};
use crate::typeloader;
pub const RESERVED_GEOMETRY_PROPERTIES: &[(&str, Type)] = &[
("x", Type::LogicalLength),
("y", Type::LogicalLength),
("width", Type::LogicalLength),
("height", Type::LogicalLength),
("z", Type::Float32),
];
pub const RESERVED_LAYOUT_PROPERTIES: &[(&str, Type)] = &[
("min-width", Type::LogicalLength),
("min-height", Type::LogicalLength),
("max-width", Type::LogicalLength),
("max-height", Type::LogicalLength),
("padding", Type::LogicalLength),
("padding-left", Type::LogicalLength),
("padding-right", Type::LogicalLength),
("padding-top", Type::LogicalLength),
("padding-bottom", Type::LogicalLength),
("preferred-width", Type::LogicalLength),
("preferred-height", Type::LogicalLength),
("horizontal-stretch", Type::Float32),
("vertical-stretch", Type::Float32),
];
pub const RESERVED_GRIDLAYOUT_PROPERTIES: &[(&str, Type)] = &[
("col", Type::Int32),
("row", Type::Int32),
("colspan", Type::Int32),
("rowspan", Type::Int32),
];
macro_rules! declare_enums {
($( $(#[$enum_doc:meta])* enum $Name:ident { $( $(#[$value_doc:meta])* $Value:ident,)* })*) => {
#[allow(non_snake_case)]
pub struct BuiltinEnums {
$(pub $Name : Rc<Enumeration>),*
}
impl BuiltinEnums {
fn new() -> Self {
Self {
$($Name : Rc::new(Enumeration {
name: stringify!($Name).replace_smolstr("_", "-"),
values: vec![$(crate::generator::to_kebab_case(stringify!($Value).trim_start_matches("r#")).into()),*],
default_value: 0,
node: None,
})),*
}
}
fn fill_register(&self, register: &mut TypeRegister) {
$(if stringify!($Name) != "PathEvent" {
register.insert_type_with_name(
Type::Enumeration(self.$Name.clone()),
stringify!($Name).replace_smolstr("_", "-")
);
})*
}
}
};
}
i_slint_common::for_each_enums!(declare_enums);
pub struct BuiltinTypes {
pub enums: BuiltinEnums,
pub noarg_callback_type: Type,
pub strarg_callback_type: Type,
pub logical_point_type: Rc<Struct>,
pub logical_size_type: Rc<Struct>,
pub font_metrics_type: Type,
pub layout_info_type: Rc<Struct>,
pub gridlayout_input_data_type: Type,
pub path_element_type: Type,
pub layout_item_info_type: Type,
}
impl BuiltinTypes {
fn new() -> Self {
let layout_info_type = Rc::new(Struct {
fields: ["min", "max", "preferred"]
.iter()
.map(|s| (SmolStr::new_static(s), Type::LogicalLength))
.chain(
["min_percent", "max_percent", "stretch"]
.iter()
.map(|s| (SmolStr::new_static(s), Type::Float32)),
)
.collect(),
name: BuiltinPrivateStruct::LayoutInfo.into(),
});
Self {
enums: BuiltinEnums::new(),
logical_point_type: Rc::new(Struct {
fields: IntoIterator::into_iter([
(SmolStr::new_static("x"), Type::LogicalLength),
(SmolStr::new_static("y"), Type::LogicalLength),
])
.collect(),
name: BuiltinPublicStruct::LogicalPosition.into(),
}),
logical_size_type: Rc::new(Struct {
fields: IntoIterator::into_iter([
(SmolStr::new_static("width"), Type::LogicalLength),
(SmolStr::new_static("height"), Type::LogicalLength),
])
.collect(),
name: BuiltinPublicStruct::LogicalSize.into(),
}),
font_metrics_type: Type::Struct(Rc::new(Struct {
fields: IntoIterator::into_iter([
(SmolStr::new_static("ascent"), Type::LogicalLength),
(SmolStr::new_static("descent"), Type::LogicalLength),
(SmolStr::new_static("x-height"), Type::LogicalLength),
(SmolStr::new_static("cap-height"), Type::LogicalLength),
])
.collect(),
name: BuiltinPrivateStruct::FontMetrics.into(),
})),
noarg_callback_type: Type::Callback(Rc::new(Function {
return_type: Type::Void,
args: Vec::new(),
arg_names: Vec::new(),
})),
strarg_callback_type: Type::Callback(Rc::new(Function {
return_type: Type::Void,
args: vec![Type::String],
arg_names: Vec::new(),
})),
layout_info_type: layout_info_type.clone(),
path_element_type: Type::Struct(Rc::new(Struct {
fields: Default::default(),
name: BuiltinPrivateStruct::PathElement.into(),
})),
layout_item_info_type: Type::Struct(Rc::new(Struct {
fields: IntoIterator::into_iter([("constraint".into(), layout_info_type.into())])
.collect(),
name: BuiltinPrivateStruct::LayoutItemInfo.into(),
})),
gridlayout_input_data_type: Type::Struct(Rc::new(Struct {
fields: IntoIterator::into_iter([
("row".into(), Type::Int32),
("column".into(), Type::Int32),
("rowspan".into(), Type::Int32),
("colspan".into(), Type::Int32),
])
.collect(),
name: BuiltinPrivateStruct::GridLayoutInputData.into(),
})),
}
}
}
thread_local! {
pub static BUILTIN: BuiltinTypes = BuiltinTypes::new();
}
const RESERVED_OTHER_PROPERTIES: &[(&str, Type)] = &[
("clip", Type::Bool),
("opacity", Type::Float32),
("cache-rendering-hint", Type::Bool),
("visible", Type::Bool), // ("enabled", Type::Bool),
];
pub const RESERVED_DROP_SHADOW_PROPERTIES: &[(&str, Type)] = &[
("drop-shadow-offset-x", Type::LogicalLength),
("drop-shadow-offset-y", Type::LogicalLength),
("drop-shadow-blur", Type::LogicalLength),
("drop-shadow-color", Type::Color),
];
pub const RESERVED_TRANSFORM_PROPERTIES: &[(&str, Type)] = &[
("transform-rotation", Type::Angle),
("transform-scale-x", Type::Float32),
("transform-scale-y", Type::Float32),
("transform-scale", Type::Float32),
];
pub fn transform_origin_property() -> (&'static str, Rc<Struct>) {
("transform-origin", logical_point_type())
}
pub const DEPRECATED_ROTATION_ORIGIN_PROPERTIES: [(&str, Type); 2] =
[("rotation-origin-x", Type::LogicalLength), ("rotation-origin-y", Type::LogicalLength)];
pub fn noarg_callback_type() -> Type {
BUILTIN.with(|types| types.noarg_callback_type.clone())
}
fn strarg_callback_type() -> Type {
BUILTIN.with(|types| types.strarg_callback_type.clone())
}
pub fn reserved_accessibility_properties() -> impl Iterator<Item = (&'static str, Type)> {
[
//("accessible-role", ...)
("accessible-checkable", Type::Bool),
("accessible-checked", Type::Bool),
("accessible-delegate-focus", Type::Int32),
("accessible-description", Type::String),
("accessible-enabled", Type::Bool),
("accessible-expandable", Type::Bool),
("accessible-expanded", Type::Bool),
("accessible-id", Type::String),
("accessible-label", Type::String),
("accessible-value", Type::String),
("accessible-value-maximum", Type::Float32),
("accessible-value-minimum", Type::Float32),
("accessible-value-step", Type::Float32),
("accessible-placeholder-text", Type::String),
("accessible-action-default", noarg_callback_type()),
("accessible-action-increment", noarg_callback_type()),
("accessible-action-decrement", noarg_callback_type()),
("accessible-action-set-value", strarg_callback_type()),
("accessible-action-expand", noarg_callback_type()),
("accessible-item-selectable", Type::Bool),
("accessible-item-selected", Type::Bool),
("accessible-item-index", Type::Int32),
("accessible-item-count", Type::Int32),
("accessible-read-only", Type::Bool),
]
.into_iter()
}
/// list of reserved property injected in every item
pub fn reserved_properties() -> impl Iterator<Item = (&'static str, Type, PropertyVisibility)> {
RESERVED_GEOMETRY_PROPERTIES
.iter()
.chain(RESERVED_LAYOUT_PROPERTIES.iter())
.chain(RESERVED_OTHER_PROPERTIES.iter())
.chain(RESERVED_DROP_SHADOW_PROPERTIES.iter())
.chain(RESERVED_TRANSFORM_PROPERTIES.iter())
.chain(DEPRECATED_ROTATION_ORIGIN_PROPERTIES.iter())
.map(|(k, v)| (*k, v.clone(), PropertyVisibility::Input))
.chain(
std::iter::once(transform_origin_property())
.map(|(k, v)| (k, v.into(), PropertyVisibility::Input)),
)
.chain(reserved_accessibility_properties().map(|(k, v)| (k, v, PropertyVisibility::Input)))
.chain(
RESERVED_GRIDLAYOUT_PROPERTIES
.iter()
.map(|(k, v)| (*k, v.clone(), PropertyVisibility::Input)),
)
.chain(IntoIterator::into_iter([
("absolute-position", logical_point_type().into(), PropertyVisibility::Output),
("forward-focus", Type::ElementReference, PropertyVisibility::Constexpr),
(
"focus",
Type::Function(BuiltinFunction::SetFocusItem.ty()),
PropertyVisibility::Public,
),
(
"clear-focus",
Type::Function(BuiltinFunction::ClearFocusItem.ty()),
PropertyVisibility::Public,
),
(
"dialog-button-role",
Type::Enumeration(BUILTIN.with(|e| e.enums.DialogButtonRole.clone())),
PropertyVisibility::Constexpr,
),
(
"accessible-role",
Type::Enumeration(BUILTIN.with(|e| e.enums.AccessibleRole.clone())),
PropertyVisibility::Constexpr,
),
]))
.chain(std::iter::once(("init", noarg_callback_type(), PropertyVisibility::Private)))
}
/// lookup reserved property injected in every item
pub fn reserved_property(name: std::borrow::Cow<'_, str>) -> PropertyLookupResult<'_> {
thread_local! {
static RESERVED_PROPERTIES: HashMap<&'static str, (Type, PropertyVisibility, Option<BuiltinFunction>)>
= reserved_properties().map(|(name, ty, visibility)| (name, (ty, visibility, reserved_member_function(name)))).collect();
}
if let Some((ty, visibility, builtin_function)) =
RESERVED_PROPERTIES.with(|reserved| reserved.get(name.as_ref()).cloned())
{
return PropertyLookupResult {
property_type: ty,
resolved_name: name,
is_local_to_component: false,
is_in_direct_base: false,
property_visibility: visibility,
declared_pure: None,
builtin_function,
};
}
// Report deprecated known reserved properties (maximum_width, minimum_height, ...)
for pre in &["min", "max"] {
if let Some(a) = name.strip_prefix(pre) {
for suf in &["width", "height"] {
if let Some(b) = a.strip_suffix(suf)
&& b == "imum-"
{
return PropertyLookupResult {
property_type: Type::LogicalLength,
resolved_name: format!("{pre}-{suf}").into(),
is_local_to_component: false,
is_in_direct_base: false,
property_visibility: crate::object_tree::PropertyVisibility::InOut,
declared_pure: None,
builtin_function: None,
};
}
}
}
}
PropertyLookupResult::invalid(name)
}
/// These member functions are injected in every time
pub fn reserved_member_function(name: &str) -> Option<BuiltinFunction> {
for (m, e) in [
("focus", BuiltinFunction::SetFocusItem), // match for callable "focus" property
("clear-focus", BuiltinFunction::ClearFocusItem), // match for callable "clear-focus" property
] {
if m == name {
return Some(e);
}
}
None
}
/// All types (datatypes, internal elements, properties, ...) are stored in this type
#[derive(Debug, Default)]
pub struct TypeRegister {
/// The set of property types.
types: HashMap<SmolStr, Type>,
/// The set of element types
elements: HashMap<SmolStr, ElementType>,
supported_property_animation_types: HashSet<String>,
pub(crate) property_animation_type: ElementType,
pub(crate) empty_type: ElementType,
/// Map from a context restricted type to the list of contexts (parent type) it is allowed in. This is
/// used to construct helpful error messages, such as "Row can only be within a GridLayout element".
context_restricted_types: HashMap<SmolStr, HashSet<SmolStr>>,
parent_registry: Option<Rc<RefCell<TypeRegister>>>,
/// If the lookup function should return types that are marked as internal
pub(crate) expose_internal_types: bool,
}
impl TypeRegister {
pub(crate) fn snapshot(&self, snapshotter: &mut typeloader::Snapshotter) -> Self {
Self {
types: self.types.clone(),
elements: self
.elements
.iter()
.map(|(k, v)| (k.clone(), snapshotter.snapshot_element_type(v)))
.collect(),
supported_property_animation_types: self.supported_property_animation_types.clone(),
property_animation_type: snapshotter
.snapshot_element_type(&self.property_animation_type),
empty_type: snapshotter.snapshot_element_type(&self.empty_type),
context_restricted_types: self.context_restricted_types.clone(),
parent_registry: self
.parent_registry
.as_ref()
.map(|tr| snapshotter.snapshot_type_register(tr)),
expose_internal_types: self.expose_internal_types,
}
}
/// Insert a type into the type register with its builtin type name.
///
/// Returns false if it replaced an existing type.
pub fn insert_type(&mut self, t: Type) -> bool {
self.types.insert(t.to_smolstr(), t).is_none()
}
/// Insert a type into the type register with a specified name.
///
/// Returns false if it replaced an existing type.
pub fn insert_type_with_name(&mut self, t: Type, name: SmolStr) -> bool {
self.types.insert(name, t).is_none()
}
fn builtin_internal() -> Self {
let mut register = TypeRegister::default();
register.insert_type(Type::Float32);
register.insert_type(Type::Int32);
register.insert_type(Type::String);
register.insert_type(Type::PhysicalLength);
register.insert_type(Type::LogicalLength);
register.insert_type(Type::Color);
register.insert_type(Type::ComponentFactory);
register.insert_type(Type::Duration);
register.insert_type(Type::Image);
register.insert_type(Type::Bool);
register.insert_type(Type::Model);
register.insert_type(Type::Percent);
register.insert_type(Type::Easing);
register.insert_type(Type::Angle);
register.insert_type(Type::Brush);
register.insert_type(Type::Rem);
register.insert_type(Type::StyledText);
register.insert_type(Type::KeyboardShortcutType);
register.types.insert("Point".into(), logical_point_type().into());
register.types.insert("Size".into(), logical_size_type().into());
BUILTIN.with(|e| e.enums.fill_register(&mut register));
register.supported_property_animation_types.insert(Type::Float32.to_string());
register.supported_property_animation_types.insert(Type::Int32.to_string());
register.supported_property_animation_types.insert(Type::Color.to_string());
register.supported_property_animation_types.insert(Type::PhysicalLength.to_string());
register.supported_property_animation_types.insert(Type::LogicalLength.to_string());
register.supported_property_animation_types.insert(Type::Brush.to_string());
register.supported_property_animation_types.insert(Type::Angle.to_string());
macro_rules! register_builtin_structs {
($(
$(#[$attr:meta])*
struct $Name:ident {
@name = $inner_name:expr,
export {
$( $(#[$pub_attr:meta])* $pub_field:ident : $pub_type:ident, )*
}
private {
$( $(#[$pri_attr:meta])* $pri_field:ident : $pri_type:ty, )*
}
}
)*) => { $(
register.insert_type_with_name(Type::Struct(builtin_structs::$Name()), SmolStr::new(stringify!($Name)));
)* };
}
i_slint_common::for_each_builtin_structs!(register_builtin_structs);
crate::load_builtins::load_builtins(&mut register);
for e in register.elements.values() {
if let ElementType::Builtin(b) = e {
for accepted_child_type_name in b.additional_accepted_child_types.keys() {
register
.context_restricted_types
.entry(accepted_child_type_name.clone())
.or_default()
.insert(b.native_class.class_name.clone());
}
if b.additional_accept_self {
register
.context_restricted_types
.entry(b.native_class.class_name.clone())
.or_default()
.insert(b.native_class.class_name.clone());
}
}
}
match &mut register.elements.get_mut("PopupWindow").unwrap() {
ElementType::Builtin(b) => {
let popup = Rc::get_mut(b).unwrap();
popup.properties.insert(
"show".into(),
BuiltinPropertyInfo::from(BuiltinFunction::ShowPopupWindow),
);
popup.properties.insert(
"close".into(),
BuiltinPropertyInfo::from(BuiltinFunction::ClosePopupWindow),
);
popup.properties.get_mut("close-on-click").unwrap().property_visibility =
PropertyVisibility::Constexpr;
popup.properties.get_mut("close-policy").unwrap().property_visibility =
PropertyVisibility::Constexpr;
}
_ => unreachable!(),
};
match &mut register.elements.get_mut("Timer").unwrap() {
ElementType::Builtin(b) => {
let timer = Rc::get_mut(b).unwrap();
timer
.properties
.insert("start".into(), BuiltinPropertyInfo::from(BuiltinFunction::StartTimer));
timer
.properties
.insert("stop".into(), BuiltinPropertyInfo::from(BuiltinFunction::StopTimer));
timer.properties.insert(
"restart".into(),
BuiltinPropertyInfo::from(BuiltinFunction::RestartTimer),
);
}
_ => unreachable!(),
}
let font_metrics_prop = crate::langtype::BuiltinPropertyInfo {
ty: font_metrics_type(),
property_visibility: PropertyVisibility::Output,
default_value: BuiltinPropertyDefault::WithElement(|elem| {
crate::expression_tree::Expression::FunctionCall {
function: BuiltinFunction::ItemFontMetrics.into(),
arguments: vec![crate::expression_tree::Expression::ElementReference(
Rc::downgrade(elem),
)],
source_location: None,
}
}),
};
match &mut register.elements.get_mut("TextInput").unwrap() {
ElementType::Builtin(b) => {
let text_input = Rc::get_mut(b).unwrap();
text_input.properties.insert(
"set-selection-offsets".into(),
BuiltinPropertyInfo::from(BuiltinFunction::SetSelectionOffsets),
);
text_input.properties.insert("font-metrics".into(), font_metrics_prop.clone());
}
_ => unreachable!(),
};
match &mut register.elements.get_mut("Text").unwrap() {
ElementType::Builtin(b) => {
let text = Rc::get_mut(b).unwrap();
text.properties.insert("font-metrics".into(), font_metrics_prop);
}
_ => unreachable!(),
};
match &mut register.elements.get_mut("Path").unwrap() {
ElementType::Builtin(b) => {
let path = Rc::get_mut(b).unwrap();
path.properties.get_mut("commands").unwrap().property_visibility =
PropertyVisibility::Fake;
}
_ => unreachable!(),
};
match &mut register.elements.get_mut("TabWidget").unwrap() {
ElementType::Builtin(b) => {
let tabwidget = Rc::get_mut(b).unwrap();
tabwidget.properties.get_mut("orientation").unwrap().property_visibility =
PropertyVisibility::Constexpr;
}
_ => unreachable!(),
}
register
}
#[doc(hidden)]
/// All builtins incl. experimental ones! Do not use in production code!
pub fn builtin_experimental() -> Rc<RefCell<Self>> {
let register = Self::builtin_internal();
Rc::new(RefCell::new(register))
}
pub fn builtin() -> Rc<RefCell<Self>> {
let mut register = Self::builtin_internal();
register.elements.remove("ComponentContainer").unwrap();
register.types.remove("component-factory").unwrap();
register.elements.remove("DragArea").unwrap();
register.elements.remove("DropArea").unwrap();
register.types.remove("DropEvent").unwrap(); // Also removed in xtask/src/slintdocs.rs
match register.elements.get_mut("Window").unwrap() {
ElementType::Builtin(b) => {
Rc::get_mut(b)
.expect("Should not be shared at this point")
.properties
.remove("hide")
.unwrap();
}
_ => unreachable!(),
}
Rc::new(RefCell::new(register))
}
pub fn new(parent: &Rc<RefCell<TypeRegister>>) -> Self {
Self {
parent_registry: Some(parent.clone()),
expose_internal_types: parent.borrow().expose_internal_types,
..Default::default()
}
}
pub fn lookup(&self, name: &str) -> Type {
self.types
.get(name)
.cloned()
.or_else(|| self.parent_registry.as_ref().map(|r| r.borrow().lookup(name)))
.unwrap_or_default()
}
fn lookup_element_as_result(
&self,
name: &str,
) -> Result<ElementType, HashMap<SmolStr, HashSet<SmolStr>>> {
match self.elements.get(name).cloned() {
Some(ty) => Ok(ty),
None => match &self.parent_registry {
Some(r) => r.borrow().lookup_element_as_result(name),
None => Err(self.context_restricted_types.clone()),
},
}
}
pub fn lookup_element(&self, name: &str) -> Result<ElementType, String> {
self.lookup_element_as_result(name).map_err(|context_restricted_types| {
if let Some(permitted_parent_types) = context_restricted_types.get(name) {
if permitted_parent_types.len() == 1 {
format!(
"{} can only be within a {} element",
name,
permitted_parent_types.iter().next().unwrap()
)
} else {
let mut elements = permitted_parent_types.iter().cloned().collect::<Vec<_>>();
elements.sort();
format!(
"{} can only be within the following elements: {}",
name,
elements.join(", ")
)
}
} else if let Some(ty) = self.types.get(name) {
format!("'{ty}' cannot be used as an element")
} else {
format!("Unknown element '{name}'")
}
})
}
pub fn lookup_builtin_element(&self, name: &str) -> Option<ElementType> {
self.parent_registry.as_ref().map_or_else(
|| self.elements.get(name).cloned(),
|p| p.borrow().lookup_builtin_element(name),
)
}
pub fn lookup_qualified<Member: AsRef<str>>(&self, qualified: &[Member]) -> Type {
if qualified.len() != 1 {
return Type::Invalid;
}
self.lookup(qualified[0].as_ref())
}
/// Add the component with its defined name
///
/// Returns false if there was already an element with the same name
pub fn add(&mut self, comp: Rc<Component>) -> bool {
self.add_with_name(comp.id.clone(), comp)
}
/// Add the component with a specified name
///
/// Returns false if there was already an element with the same name
pub fn add_with_name(&mut self, name: SmolStr, comp: Rc<Component>) -> bool {
self.elements.insert(name, ElementType::Component(comp)).is_none()
}
pub fn add_builtin(&mut self, builtin: Rc<BuiltinElement>) {
self.elements.insert(builtin.name.clone(), ElementType::Builtin(builtin));
}
pub fn property_animation_type_for_property(&self, property_type: Type) -> ElementType {
if self.supported_property_animation_types.contains(&property_type.to_string()) {
self.property_animation_type.clone()
} else {
self.parent_registry
.as_ref()
.map(|registry| {
registry.borrow().property_animation_type_for_property(property_type)
})
.unwrap_or_default()
}
}
/// Return a hashmap with all the registered type
pub fn all_types(&self) -> HashMap<SmolStr, Type> {
let mut all =
self.parent_registry.as_ref().map(|r| r.borrow().all_types()).unwrap_or_default();
for (k, v) in &self.types {
all.insert(k.clone(), v.clone());
}
all
}
/// Return a hashmap with all the registered element type
pub fn all_elements(&self) -> HashMap<SmolStr, ElementType> {
let mut all =
self.parent_registry.as_ref().map(|r| r.borrow().all_elements()).unwrap_or_default();
for (k, v) in &self.elements {
all.insert(k.clone(), v.clone());
}
all
}
pub fn empty_type(&self) -> ElementType {
match self.parent_registry.as_ref() {
Some(parent) => parent.borrow().empty_type(),
None => self.empty_type.clone(),
}
}
}
/// Type definitions for each builtin struct
pub mod builtin_structs {
use super::*;
thread_local! {
pub static BUILTIN_STRUCTS: BuiltinStructs = BuiltinStructs::new();
}
#[rustfmt::skip]
macro_rules! map_type {
($pub_type:ident, bool) => { Type::Bool };
($pub_type:ident, i32) => { Type::Int32 };
($pub_type:ident, f32) => { Type::Float32 };
($pub_type:ident, SharedString) => { Type::String };
($pub_type:ident, Image) => { Type::Image };
($pub_type:ident, Coord) => { Type::LogicalLength };
($pub_type:ident, LogicalPosition) => { Type::Struct(logical_point_type()) };
($pub_type:ident, LogicalSize) => { Type::Struct(logical_size_type()) };
// builtin structs
($pub_type:ident, KeyboardModifiers) => {
// Note, this references the local variable in the BuiltinStructs constructor
Type::Struct($pub_type.clone())
};
// builtin enums
($pub_type:ident, $_:ident) => {
BUILTIN.with(|e| Type::Enumeration(e.enums.$pub_type.clone()))
};
}
macro_rules! declare_builtin_structs {
($(
$(#[$attr:meta])*
struct $Name:ident {
@name = $inner_name:expr,
export {
$( $(#[$pub_attr:meta])* $pub_field:ident : $pub_type:ident, )*
}
private {
$( $(#[$pri_attr:meta])* $pri_field:ident : $pri_type:ty, )*
}
}
)*) => {
pub struct BuiltinStructs {
$(
#[allow(non_snake_case)]
$Name: Rc<Struct>
),*
}
impl BuiltinStructs {
pub fn new() -> Self {
$(
#[allow(non_snake_case)]
let $Name = Rc::new(Struct{
fields: BTreeMap::from([
$((stringify!($pub_field).replace_smolstr("_", "-"), map_type!($pub_type, $pub_type))),*
]),
name: $inner_name.into(),
});
)*
Self {
$($Name),*
}
}
}
impl Default for BuiltinStructs {
fn default() -> Self {
Self::new()
}
}
$(
#[allow(non_snake_case)]
pub fn $Name() -> Rc<Struct> {
BUILTIN_STRUCTS.with(|types| types.$Name.clone())
}
)*
};
}
i_slint_common::for_each_builtin_structs!(declare_builtin_structs);
}
pub fn logical_point_type() -> Rc<Struct> {
BUILTIN.with(|types| types.logical_point_type.clone())
}
pub fn logical_size_type() -> Rc<Struct> {
BUILTIN.with(|types| types.logical_size_type.clone())
}
pub fn font_metrics_type() -> Type {
BUILTIN.with(|types| types.font_metrics_type.clone())
}
/// The [`Type`] for a runtime LayoutInfo structure
pub fn layout_info_type() -> Rc<Struct> {
BUILTIN.with(|types| types.layout_info_type.clone())
}
/// The [`Type`] for a runtime PathElement structure
pub fn path_element_type() -> Type {
BUILTIN.with(|types| types.path_element_type.clone())
}
/// The [`Type`] for a runtime LayoutItemInfo structure
pub fn layout_item_info_type() -> Type {
BUILTIN.with(|types| types.layout_item_info_type.clone())
}