-
Notifications
You must be signed in to change notification settings - Fork 502
/
cpp.rs
2500 lines (2303 loc) · 98.2 KB
/
cpp.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 <info@slint-ui.com>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
/*! module for the C++ code generator
*/
// cSpell:ignore cmath constexpr cstdlib decltype intptr itertools nullptr prepended struc subcomponent uintptr vals
use std::fmt::Write;
fn ident(ident: &str) -> String {
if ident.contains('-') {
ident.replace('-', "_")
} else {
ident.into()
}
}
/// Given a property reference to a native item (eg, the property name is empty)
/// return tokens to the `ItemRc`
fn access_item_rc(pr: &llr::PropertyReference, ctx: &EvaluationContext) -> String {
let mut ctx = ctx;
let mut component_access = "self".into();
let pr = match pr {
llr::PropertyReference::InParent { level, parent_reference } => {
for _ in 0..level.get() {
component_access = format!("{}->parent", component_access);
ctx = ctx.parent.as_ref().unwrap().ctx;
}
parent_reference
}
other => other,
};
match pr {
llr::PropertyReference::InNativeItem { sub_component_path, item_index, prop_name } => {
assert!(prop_name.is_empty());
let (sub_compo_path, sub_component) =
follow_sub_component_path(ctx.current_sub_component.unwrap(), sub_component_path);
if !sub_component_path.is_empty() {
component_access = format!("{}->{}", &component_access, &sub_compo_path);
}
let component_rc = format!("{}->self_weak.lock()->into_dyn()", &component_access);
let item_index_in_tree = sub_component.items[*item_index].index_in_tree;
let item_index = if item_index_in_tree == 0 {
format!("{}->tree_index", &component_access)
} else {
format!(
"{}->tree_index_of_first_child + {} - 1",
&component_access, item_index_in_tree
)
};
format!("{}, {}", &component_rc, item_index)
}
_ => unreachable!(),
}
}
/// This module contains some data structure that helps represent a C++ code.
/// It is then rendered into an actual C++ text using the Display trait
mod cpp_ast {
use std::cell::Cell;
use std::fmt::{Display, Error, Formatter};
thread_local!(static INDENTATION : Cell<u32> = Cell::new(0));
fn indent(f: &mut Formatter<'_>) -> Result<(), Error> {
INDENTATION.with(|i| {
for _ in 0..(i.get()) {
write!(f, " ")?;
}
Ok(())
})
}
///A full C++ file
#[derive(Default, Debug)]
pub struct File {
pub includes: Vec<String>,
pub declarations: Vec<Declaration>,
pub definitions: Vec<Declaration>,
}
impl Display for File {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
for i in &self.includes {
writeln!(f, "#include {}", i)?;
}
for d in &self.declarations {
write!(f, "\n{}", d)?;
}
for d in &self.definitions {
write!(f, "\n{}", d)?;
}
Ok(())
}
}
/// Declarations (top level, or within a struct)
#[derive(Debug, derive_more::Display)]
pub enum Declaration {
Struct(Struct),
Function(Function),
Var(Var),
TypeAlias(TypeAlias),
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Access {
Public,
Private,
/*Protected,*/
}
#[derive(Default, Debug)]
pub struct Struct {
pub name: String,
pub members: Vec<(Access, Declaration)>,
pub friends: Vec<String>,
}
impl Display for Struct {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
if self.members.is_empty() && self.friends.is_empty() {
writeln!(f, "class {};", self.name)
} else {
writeln!(f, "class {} {{", self.name)?;
INDENTATION.with(|x| x.set(x.get() + 1));
let mut access = Access::Private;
for m in &self.members {
if m.0 != access {
access = m.0;
indent(f)?;
match access {
Access::Public => writeln!(f, "public:")?,
Access::Private => writeln!(f, "private:")?,
}
}
write!(f, "{}", m.1)?;
}
for friend in &self.friends {
indent(f)?;
writeln!(f, "friend class {};", friend)?;
}
INDENTATION.with(|x| x.set(x.get() - 1));
indent(f)?;
writeln!(f, "}};")
}
}
}
impl Struct {
pub fn extract_definitions(&mut self) -> impl Iterator<Item = Declaration> + '_ {
let struct_name = self.name.clone();
self.members.iter_mut().filter_map(move |x| match &mut x.1 {
Declaration::Function(f) if f.statements.is_some() => {
Some(Declaration::Function(Function {
name: format!("{}::{}", struct_name, f.name),
signature: f.signature.clone(),
is_constructor_or_destructor: f.is_constructor_or_destructor,
is_static: false,
is_friend: false,
statements: f.statements.take(),
template_parameters: f.template_parameters.clone(),
constructor_member_initializers: f.constructor_member_initializers.clone(),
}))
}
_ => None,
})
}
}
/// Function or method
#[derive(Default, Debug)]
pub struct Function {
pub name: String,
/// "(...) -> ..."
pub signature: String,
/// The function does not have return type
pub is_constructor_or_destructor: bool,
pub is_static: bool,
pub is_friend: bool,
/// The list of statement instead the function. When None, this is just a function
/// declaration without the definition
pub statements: Option<Vec<String>>,
/// What's inside template<...> if any
pub template_parameters: Option<String>,
/// Explicit initializers, such as FooClass::FooClass() : someMember(42) {}
pub constructor_member_initializers: Vec<String>,
}
impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
if let Some(tpl) = &self.template_parameters {
write!(f, "template<{}> ", tpl)?;
}
if self.is_static {
write!(f, "static ")?;
}
if self.is_friend {
write!(f, "friend ")?;
}
// all functions are `inline` because we are in a header
write!(f, "inline ")?;
if !self.is_constructor_or_destructor {
write!(f, "auto ")?;
}
write!(f, "{} {}", self.name, self.signature)?;
if let Some(st) = &self.statements {
if !self.constructor_member_initializers.is_empty() {
writeln!(f, "\n : {}", self.constructor_member_initializers.join(","))?;
}
writeln!(f, "{{")?;
for s in st {
indent(f)?;
writeln!(f, " {}", s)?;
}
indent(f)?;
writeln!(f, "}}")
} else {
writeln!(f, ";")
}
}
}
/// A variable or a member declaration.
#[derive(Default, Debug)]
pub struct Var {
pub ty: String,
pub name: String,
pub array_size: Option<usize>,
pub init: Option<String>,
}
impl Display for Var {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
write!(f, "{} {}", self.ty, self.name)?;
if let Some(size) = self.array_size {
write!(f, "[{}]", size)?;
}
if let Some(i) = &self.init {
write!(f, " = {}", i)?;
}
writeln!(f, ";")
}
}
#[derive(Default, Debug)]
pub struct TypeAlias {
pub new_name: String,
pub old_name: String,
}
impl Display for TypeAlias {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
indent(f)?;
writeln!(f, "using {} = {};", self.new_name, self.old_name)
}
}
pub trait CppType {
fn cpp_type(&self) -> Option<String>;
}
pub fn escape_string(str: &str) -> String {
let mut result = String::with_capacity(str.len());
for x in str.chars() {
match x {
'\n' => result.push_str("\\n"),
'\\' => result.push_str("\\\\"),
'\"' => result.push_str("\\\""),
'\t' => result.push_str("\\t"),
'\r' => result.push_str("\\r"),
_ if !x.is_ascii() || (x as u32) < 32 => {
use std::fmt::Write;
write!(result, "\\U{:0>8x}", x as u32).unwrap();
}
_ => result.push(x),
}
}
result
}
}
use crate::expression_tree::{BuiltinFunction, EasingCurve};
use crate::langtype::{NativeClass, Type};
use crate::layout::Orientation;
use crate::llr::{
self, EvaluationContext as llr_EvaluationContext, ParentCtx as llr_ParentCtx,
TypeResolutionContext as _,
};
use crate::object_tree::Document;
use cpp_ast::*;
use itertools::{Either, Itertools};
use std::collections::BTreeMap;
use std::num::NonZeroUsize;
type EvaluationContext<'a> = llr_EvaluationContext<'a, String>;
type ParentCtx<'a> = llr_ParentCtx<'a, String>;
impl CppType for Type {
fn cpp_type(&self) -> Option<String> {
match self {
Type::Void => Some("void".to_owned()),
Type::Float32 => Some("float".to_owned()),
Type::Int32 => Some("int".to_owned()),
Type::String => Some("slint::SharedString".to_owned()),
Type::Color => Some("slint::Color".to_owned()),
Type::Duration => Some("std::int64_t".to_owned()),
Type::Angle => Some("float".to_owned()),
Type::PhysicalLength => Some("float".to_owned()),
Type::LogicalLength => Some("float".to_owned()),
Type::Percent => Some("float".to_owned()),
Type::Bool => Some("bool".to_owned()),
Type::Struct { name: Some(name), node: Some(_), .. } => Some(ident(name)),
Type::Struct { name: Some(name), node: None, .. } => {
Some(if name.starts_with("slint::") {
name.clone()
} else {
format!("slint::cbindgen_private::{}", ident(name))
})
}
Type::Struct { fields, .. } => {
let elem = fields.values().map(|v| v.cpp_type()).collect::<Option<Vec<_>>>()?;
Some(format!("std::tuple<{}>", elem.join(", ")))
}
Type::Array(i) => Some(format!("std::shared_ptr<slint::Model<{}>>", i.cpp_type()?)),
Type::Image => Some("slint::Image".to_owned()),
Type::Builtin(elem) => elem.native_class.cpp_type.clone(),
Type::Enumeration(enumeration) => {
Some(format!("slint::cbindgen_private::{}", ident(&enumeration.name)))
}
Type::Brush => Some("slint::Brush".to_owned()),
Type::LayoutCache => Some("slint::SharedVector<float>".into()),
_ => None,
}
}
}
fn to_cpp_orientation(o: Orientation) -> &'static str {
match o {
Orientation::Horizontal => "slint::cbindgen_private::Orientation::Horizontal",
Orientation::Vertical => "slint::cbindgen_private::Orientation::Vertical",
}
}
/// If the expression is surrounded with parentheses, remove these parentheses
fn remove_parentheses(expr: &str) -> &str {
if expr.starts_with('(') && expr.ends_with(')') {
let mut level = 0;
// check that the opening and closing parentheses are on the same level
for byte in expr[1..expr.len() - 1].as_bytes() {
match byte {
b')' if level == 0 => return expr,
b')' => level -= 1,
b'(' => level += 1,
_ => (),
}
}
&expr[1..expr.len() - 1]
} else {
expr
}
}
#[test]
fn remove_parentheses_test() {
assert_eq!(remove_parentheses("(foo(bar))"), "foo(bar)");
assert_eq!(remove_parentheses("(foo).bar"), "(foo).bar");
assert_eq!(remove_parentheses("(foo(bar))"), "foo(bar)");
assert_eq!(remove_parentheses("(foo)(bar)"), "(foo)(bar)");
assert_eq!(remove_parentheses("(foo).get()"), "(foo).get()");
assert_eq!(remove_parentheses("((foo).get())"), "(foo).get()");
assert_eq!(remove_parentheses("(((()())()))"), "((()())())");
assert_eq!(remove_parentheses("((()())())"), "(()())()");
assert_eq!(remove_parentheses("(()())()"), "(()())()");
assert_eq!(remove_parentheses("()())("), "()())(");
}
fn property_set_value_code(
property: &llr::PropertyReference,
value_expr: &str,
ctx: &EvaluationContext,
) -> String {
let prop = access_member(property, ctx);
if let Some(animation) = ctx.current_sub_component.and_then(|c| c.animations.get(property)) {
let animation_code = compile_expression(animation, ctx);
return format!("{}.set_animated_value({}, {})", prop, value_expr, animation_code);
}
format!("{}.set({})", prop, value_expr)
}
fn handle_property_init(
prop: &llr::PropertyReference,
binding_expression: &llr::BindingExpression,
init: &mut Vec<String>,
ctx: &EvaluationContext,
) {
let prop_access = access_member(prop, ctx);
let prop_type = ctx.property_ty(prop);
if let Type::Callback { args, .. } = &prop_type {
let mut ctx2 = ctx.clone();
ctx2.argument_types = args;
let mut params = args.iter().enumerate().map(|(i, ty)| {
format!("[[maybe_unused]] {} arg_{}", ty.cpp_type().unwrap_or_default(), i)
});
init.push(format!(
"{prop_access}.set_handler(
[this]({params}) {{
[[maybe_unused]] auto self = this;
return {code};
}});",
prop_access = prop_access,
params = params.join(", "),
code = compile_expression_wrap_return(&binding_expression.expression.borrow(), &ctx2)
));
} else {
let init_expr =
compile_expression_wrap_return(&binding_expression.expression.borrow(), ctx);
init.push(if binding_expression.is_constant {
format!("{}.set({});", prop_access, init_expr)
} else {
let binding_code = format!(
"[this]() {{
[[maybe_unused]] auto self = this;
return {init};
}}",
init = init_expr
);
if binding_expression.is_state_info {
format!("slint::private_api::set_state_binding({}, {});", prop_access, binding_code)
} else {
match &binding_expression.animation {
Some(llr::Animation::Static(anim)) => {
let anim = compile_expression(anim, ctx);
format!("{}.set_animated_binding({}, {});", prop_access, binding_code, anim)
}
Some(llr::Animation::Transition (
anim
)) => {
let anim = compile_expression(anim, ctx);
format!(
"{}.set_animated_binding_for_transition({},
[this](uint64_t *start_time) -> slint::cbindgen_private::PropertyAnimation {{
[[maybe_unused]] auto self = this;
auto [anim, time] = {};
*start_time = time;
return anim;
}});",
prop_access,
binding_code,
anim,
)
}
None => format!("{}.set_binding({});", prop_access, binding_code),
}
}
});
}
}
/// Returns the text of the C++ code produced by the given root component
pub fn generate(doc: &Document) -> impl std::fmt::Display {
let mut file = File::default();
file.includes.push("<array>".into());
file.includes.push("<limits>".into());
file.includes.push("<cstdlib>".into()); // TODO: ideally only include this if needed (by to_float)
file.includes.push("<cmath>".into()); // TODO: ideally only include this if needed (by floor/ceil/round)
file.includes.push("<slint.h>".into());
file.declarations.extend(doc.root_component.embedded_file_resources.borrow().iter().map(
|(path, er)| {
match &er.kind {
crate::embedded_resources::EmbeddedResourcesKind::RawData => {
let file = crate::fileaccess::load_file(std::path::Path::new(path)).unwrap(); // embedding pass ensured that the file exists
let data = file.read();
let mut init = "{ ".to_string();
for (index, byte) in data.iter().enumerate() {
if index > 0 {
init.push(',');
}
write!(&mut init, "0x{:x}", byte).unwrap();
if index % 16 == 0 {
init.push('\n');
}
}
init.push('}');
Declaration::Var(Var {
ty: "inline uint8_t".into(),
name: format!("slint_embedded_resource_{}", er.id),
array_size: Some(data.len()),
init: Some(init),
})
}
crate::embedded_resources::EmbeddedResourcesKind::TextureData(_) => todo!(),
crate::embedded_resources::EmbeddedResourcesKind::BitmapFontData(_) => todo!(),
}
},
));
for ty in doc.root_component.used_types.borrow().structs.iter() {
if let Type::Struct { fields, name: Some(name), node: Some(_) } = ty {
generate_struct(&mut file, name, fields);
}
}
let llr = llr::lower_to_item_tree::lower_to_item_tree(&doc.root_component);
// Forward-declare the root so that sub-components can access singletons, the window, etc.
file.declarations.push(Declaration::Struct(Struct {
name: ident(&llr.item_tree.root.name),
..Default::default()
}));
for sub_compo in &llr.sub_components {
let sub_compo_id = ident(&sub_compo.name);
let mut sub_compo_struct = Struct { name: sub_compo_id.clone(), ..Default::default() };
generate_sub_component(
&mut sub_compo_struct,
sub_compo,
&llr,
None,
Access::Public,
&mut file,
);
file.definitions.extend(sub_compo_struct.extract_definitions().collect::<Vec<_>>());
file.declarations.push(Declaration::Struct(sub_compo_struct));
}
for glob in llr.globals.iter().filter(|glob| !glob.is_builtin) {
generate_global(&mut file, glob, &llr);
file.definitions.extend(glob.aliases.iter().map(|name| {
Declaration::TypeAlias(TypeAlias { old_name: ident(&glob.name), new_name: ident(name) })
}))
}
generate_public_component(&mut file, &llr);
file.definitions.push(Declaration::Var(Var{
ty: format!(
"[[maybe_unused]] constexpr slint::private_api::VersionCheckHelper<{}, {}, {}>",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH")),
name: "THE_SAME_VERSION_MUST_BE_USED_FOR_THE_COMPILER_AND_THE_RUNTIME".into(),
init: Some("slint::private_api::VersionCheckHelper<SLINT_VERSION_MAJOR, SLINT_VERSION_MINOR, SLINT_VERSION_PATCH>()".into()),
..Default::default()
}));
file
}
fn generate_struct(file: &mut File, name: &str, fields: &BTreeMap<String, Type>) {
let mut members = fields
.iter()
.map(|(name, t)| {
(
Access::Public,
Declaration::Var(Var {
ty: t.cpp_type().unwrap(),
name: ident(name),
..Default::default()
}),
)
})
.collect::<Vec<_>>();
members.sort_unstable_by(|a, b| match (&a.1, &b.1) {
(Declaration::Var(a), Declaration::Var(b)) => a.name.cmp(&b.name),
_ => unreachable!(),
});
members.push((
Access::Public,
Declaration::Function(Function {
name: "operator==".to_owned(),
signature: format!("(const {0} &a, const {0} &b) -> bool = default", name),
is_friend: true,
statements: None,
..Function::default()
}),
));
file.declarations.push(Declaration::Struct(Struct {
name: name.into(),
members,
..Default::default()
}))
}
/// Generate the component in `file`.
///
/// `sub_components`, if Some, will be filled with all the sub component which needs to be added as friends
fn generate_public_component(file: &mut File, component: &llr::PublicComponent) {
let root_component = &component.item_tree.root;
let component_id = ident(&root_component.name);
let mut component_struct = Struct { name: component_id.clone(), ..Default::default() };
// The window need to be the first member so it is destroyed last
component_struct.members.push((
// FIXME: many of the different component bindings need to access this
Access::Public,
Declaration::Var(Var {
ty: "slint::Window".into(),
name: "m_window".into(),
init: Some("slint::Window{slint::private_api::WindowRc()}".into()),
..Default::default()
}),
));
let ctx = EvaluationContext {
public_component: component,
current_sub_component: Some(&component.item_tree.root),
current_global: None,
generator_state: "this".to_string(),
parent: None,
argument_types: &[],
};
let old_declarations = file.declarations.len();
generate_item_tree(
&mut component_struct,
&component.item_tree,
component,
None,
component_id,
Access::Private, // Hide properties and other fields from the C++ API
file,
);
// Give generated sub-components, etc. access to our fields
for new_decl in file.declarations.iter().skip(old_declarations) {
if let Declaration::Struct(struc @ Struct { .. }) = new_decl {
component_struct.friends.push(struc.name.clone());
};
}
let declarations = generate_public_api_for_properties(&component.public_properties, &ctx);
component_struct.members.extend(declarations.into_iter().map(|decl| (Access::Public, decl)));
component_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "show".into(),
signature: "()".into(),
statements: Some(vec!["m_window.show();".into()]),
..Default::default()
}),
));
component_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "hide".into(),
signature: "()".into(),
statements: Some(vec!["m_window.hide();".into()]),
..Default::default()
}),
));
component_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "window".into(),
signature: "() const -> slint::Window&".into(),
statements: Some(vec![format!(
"return const_cast<{} *>(this)->m_window;",
component_struct.name
)]),
..Default::default()
}),
));
component_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "run".into(),
signature: "()".into(),
statements: Some(vec![
"show();".into(),
"slint::run_event_loop();".into(),
"hide();".into(),
]),
..Default::default()
}),
));
component_struct.friends.push("slint::private_api::WindowRc".into());
component_struct
.friends
.extend(component.sub_components.iter().map(|sub_compo| ident(&sub_compo.name)));
component_struct.friends.extend(
component
.item_tree
.root
.repeated
.iter()
.map(|repeater| ident(&repeater.sub_tree.root.name)),
);
for glob in &component.globals {
let ty = if glob.is_builtin {
format!("slint::cbindgen_private::{}", glob.name)
} else {
ident(&glob.name)
};
component_struct.members.push((
Access::Public, // FIXME
Declaration::Var(Var {
ty: format!("std::shared_ptr<{}>", ty),
name: format!("global_{}", ident(&glob.name)),
init: Some(format!("std::make_shared<{}>(this)", ty)),
..Default::default()
}),
));
}
let mut global_accessor_function_body = Vec::new();
for glob in component.globals.iter().filter(|glob| glob.exported && !glob.is_builtin) {
let accessor_statement = format!(
"{0}if constexpr(std::is_same_v<T, {1}>) {{ return *global_{1}.get(); }}",
if global_accessor_function_body.is_empty() { "" } else { "else " },
ident(&glob.name),
);
global_accessor_function_body.push(accessor_statement);
}
if !global_accessor_function_body.is_empty() {
global_accessor_function_body.push(
"else { static_assert(!sizeof(T*), \"The type is not global/or exported\"); }".into(),
);
component_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "global".into(),
signature: "() const -> const T&".into(),
statements: Some(global_accessor_function_body),
template_parameters: Some("typename T".into()),
..Default::default()
}),
));
}
file.definitions.extend(component_struct.extract_definitions().collect::<Vec<_>>());
file.declarations.push(Declaration::Struct(component_struct));
}
fn generate_item_tree(
target_struct: &mut Struct,
sub_tree: &llr::ItemTree,
root: &llr::PublicComponent,
parent_ctx: Option<ParentCtx>,
item_tree_class_name: String,
field_access: Access,
file: &mut File,
) {
target_struct.friends.push(format!(
"vtable::VRc<slint::private_api::ComponentVTable, {}>",
item_tree_class_name
));
generate_sub_component(
target_struct,
&sub_tree.root,
root,
parent_ctx.clone(),
field_access,
file,
);
let root_access = if parent_ctx.is_some() { "parent->root" } else { "self" };
let mut item_tree_array: Vec<String> = Default::default();
let mut item_array: Vec<String> = Default::default();
sub_tree.tree.visit_in_array(&mut |node, children_offset, parent_index| {
let parent_index = parent_index as u32;
if node.repeated {
assert_eq!(node.children.len(), 0);
let mut repeater_index = node.item_index;
let mut sub_component = &sub_tree.root;
for i in &node.sub_component_path {
repeater_index += sub_component.sub_components[*i].repeater_offset;
sub_component = &sub_component.sub_components[*i].ty;
}
item_tree_array.push(format!(
"slint::private_api::make_dyn_node({}, {})",
repeater_index, parent_index
));
} else {
let mut compo_offset = String::new();
let mut sub_component = &sub_tree.root;
for i in &node.sub_component_path {
let next_sub_component_name = ident(&sub_component.sub_components[*i].name);
write!(
compo_offset,
"offsetof({}, {}) + ",
ident(&sub_component.name),
next_sub_component_name
)
.unwrap();
sub_component = &sub_component.sub_components[*i].ty;
}
let item = &sub_component.items[node.item_index];
if item.is_flickable_viewport {
compo_offset += "offsetof(slint::cbindgen_private::Flickable, viewport) + ";
}
let children_count = node.children.len() as u32;
let children_index = children_offset as u32;
let item_array_index = item_array.len() as u32;
item_tree_array.push(format!(
"slint::private_api::make_item_node({}, {}, {}, {})",
children_count, children_index, parent_index, item_array_index,
));
item_array.push(format!(
"{{ {}, {} offsetof({}, {}) }}",
item.ty.cpp_vtable_getter,
compo_offset,
&ident(&sub_component.name),
ident(&item.name),
));
}
});
let mut visit_children_statements = vec![
"static const auto dyn_visit = [] (const uint8_t *base, [[maybe_unused]] slint::private_api::TraversalOrder order, [[maybe_unused]] slint::private_api::ItemVisitorRefMut visitor, [[maybe_unused]] uintptr_t dyn_index) -> uint64_t {".to_owned(),
format!(" [[maybe_unused]] auto self = reinterpret_cast<const {}*>(base);", item_tree_class_name)];
let mut subtree_range_statement = vec![" std::abort();".into()];
let mut subtree_component_statement = vec![" std::abort();".into()];
if target_struct.members.iter().any(|(_, declaration)| {
matches!(&declaration, Declaration::Function(func @ Function { .. }) if func.name == "visit_dynamic_children")
}) {
visit_children_statements
.push(" return self->visit_dynamic_children(dyn_index, order, visitor);".into());
subtree_range_statement = vec![
format!("auto self = reinterpret_cast<const {}*>(component.instance);", item_tree_class_name),
"return self->subtree_range(dyn_index);".to_owned(),
];
subtree_component_statement = vec![
format!("auto self = reinterpret_cast<const {}*>(component.instance);", item_tree_class_name),
"self->subtree_component(dyn_index, subtree_index, result);".to_owned(),
];
} else {
visit_children_statements.push(" std::abort();".into());
}
visit_children_statements.extend([
"};".into(),
format!("auto self_rc = reinterpret_cast<const {}*>(component.instance)->self_weak.lock()->into_dyn();", item_tree_class_name),
"return slint::cbindgen_private::slint_visit_item_tree(&self_rc, get_item_tree(component) , index, order, visitor, dyn_visit);".to_owned(),
]);
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "visit_children".into(),
signature: "(slint::private_api::ComponentRef component, intptr_t index, slint::private_api::TraversalOrder order, slint::private_api::ItemVisitorRefMut visitor) -> uint64_t".into(),
is_static: true,
statements: Some(visit_children_statements),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "get_item_ref".into(),
signature: "(slint::private_api::ComponentRef component, uintptr_t index) -> slint::private_api::ItemRef".into(),
is_static: true,
statements: Some(vec![
"return slint::private_api::get_item_ref(component, get_item_tree(component), item_array(), index);".to_owned(),
]),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "get_subtree_range".into(),
signature: "([[maybe_unused]] slint::private_api::ComponentRef component, [[maybe_unused]] uintptr_t dyn_index) -> slint::private_api::IndexRange".into(),
is_static: true,
statements: Some(subtree_range_statement),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "get_subtree_component".into(),
signature: "([[maybe_unused]] slint::private_api::ComponentRef component, [[maybe_unused]] uintptr_t dyn_index, [[maybe_unused]] uintptr_t subtree_index, [[maybe_unused]] slint::private_api::ComponentWeak *result) -> void".into(),
is_static: true,
statements: Some(subtree_component_statement),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "get_item_tree".into(),
signature: "(slint::private_api::ComponentRef) -> slint::cbindgen_private::Slice<slint::private_api::ItemTreeNode>".into(),
is_static: true,
statements: Some(vec![
"return item_tree();".to_owned(),
]),
..Default::default()
}),
));
let parent_item_from_parent_component = if let Some(parent_index) =
parent_ctx.as_ref().and_then(|parent| {
parent
.repeater_index
.map(|idx| parent.ctx.current_sub_component.unwrap().repeated[idx].index_in_tree)
}) {
format!(
// that does not work when the parent is not a component with a ComponentVTable
//" *result = slint::private_api::parent_item(self->parent->self_weak.into_dyn(), self->parent->get_item_tree(), {});",
"*result = {{ self->parent->self_weak, self->parent->tree_index_of_first_child + {} - 1 }};",
parent_index,
)
} else {
"".to_owned()
};
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "parent_item".into(),
signature: "(slint::private_api::ComponentRef component, uintptr_t index, slint::private_api::ItemWeak *result) -> void".into(),
is_static: true,
statements: Some(vec![
format!("auto self = reinterpret_cast<const {}*>(component.instance);", item_tree_class_name),
"if (index == 0) {".into(),
parent_item_from_parent_component,
" return;".into(),
"}".into(),
"*result = slint::private_api::parent_item(self->self_weak.into_dyn(), get_item_tree(component), index);".into(),
]),
..Default::default()
}),
));
// Statements will be overridden for repeated components!
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "subtree_index".into(),
signature: "([[maybe_unused]] slint::private_api::ComponentRef component) -> uintptr_t"
.into(),
is_static: true,
statements: Some(vec!["return std::numeric_limits<uintptr_t>::max();".into()]),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: "item_tree".into(),
signature: "() -> slint::cbindgen_private::Slice<slint::private_api::ItemTreeNode>".into(),
is_static: true,
statements: Some(vec![
"static const slint::private_api::ItemTreeNode children[] {".to_owned(),
format!(" {} }};", item_tree_array.join(", \n")),
"return { const_cast<slint::private_api::ItemTreeNode*>(children), std::size(children) };"
.to_owned(),
]),
..Default::default()
}),
));
target_struct.members.push((
Access::Private,
Declaration::Function(Function {