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
use super::*;
use qmetaobject::scenegraph::{ContainerNode, RectangleNode, SGNode, TransformNode};
use qmetaobject::{QColor, QJSValue, QMetaType, QPointF, QQuickItem, QRectF, QString};
use std::cell::RefCell;
use std::ffi::CStr;
use std::os::raw::c_void;
use std::rc::Rc;

#[derive(Default)]
pub struct Geometry<'a> {
    pub x: Property<'a, f64>,
    pub y: Property<'a, f64>,
    pub width: Property<'a, f64>,
    pub height: Property<'a, f64>,
}
impl<'a> Geometry<'a> {
    pub fn width(&self) -> f64 {
        self.width.get()
    }
    pub fn height(&self) -> f64 {
        self.height.get()
    }
    pub fn left(&self) -> f64 {
        self.x.get()
    }
    pub fn top(&self) -> f64 {
        self.y.get()
    }
    pub fn right(&self) -> f64 {
        self.x.get() + self.width.get()
    }
    pub fn bottom(&self) -> f64 {
        self.y.get() + self.height.get()
    }
    pub fn vertical_center(&self) -> f64 {
        self.x.get() + self.width.get() / 2.
    }
    pub fn horizontal_center(&self) -> f64 {
        self.y.get() + self.height.get() / 2.
    }

    pub fn to_qrectf(&self) -> QRectF {
        QRectF {
            x: self.left(),
            y: self.top(),
            width: self.width(),
            height: self.height(),
        }
    }
}
/*
enum SizePolicy {
    Fixed(f64),
    Minimum(f64),
    Maximum(f64)
}*/

pub struct LayoutInfo<'a> {
    pub preferred_width: Property<'a, f64>,
    pub preferred_height: Property<'a, f64>,
    pub maximum_width: Property<'a, f64>,
    pub maximum_height: Property<'a, f64>,
    pub minimum_width: Property<'a, f64>,
    pub minimum_height: Property<'a, f64>,
}
impl<'a> Default for LayoutInfo<'a> {
    fn default() -> Self {
        LayoutInfo {
            preferred_width: 0.0.into(),
            preferred_height: 0.0.into(),
            maximum_height: std::f64::MAX.into(),
            maximum_width: std::f64::MAX.into(),
            minimum_width: 0.0.into(),
            minimum_height: 0.0.into(),
        }
    }
}

#[derive(Clone, Copy)]
pub enum MouseEvent {
    Press(QPointF),
    Release(QPointF),
    Move(QPointF),
}
impl MouseEvent {
    fn position_ref(&mut self) -> &mut QPointF {
        match self {
            MouseEvent::Press(ref mut x) => x,
            MouseEvent::Release(ref mut x) => x,
            MouseEvent::Move(ref mut x) => x,
        }
    }

    pub fn position(mut self) -> QPointF {
        *self.position_ref()
    }

    pub fn translated(mut self, translation: QPointF) -> MouseEvent {
        {
            let pos = self.position_ref();
            *pos += translation;
        }
        self
    }
}

pub trait Item<'a> {
    fn geometry(&self) -> &Geometry<'a>;
    fn layout_info(&self) -> &LayoutInfo<'a>;
    fn update_paint_node(
        &self,
        node: SGNode<ContainerNode>,
        _item: &dyn QQuickItem,
    ) -> SGNode<ContainerNode> {
        node
    }
    fn init(&self, _item: &(dyn QQuickItem + 'a)) {}
    fn mouse_event(&self, _event: MouseEvent) -> bool {
        false
    }
}

pub trait ItemContainer<'a> {
    fn add_child(&self, child: Rc<dyn Item<'a> + 'a>);
}

impl<'a, T, I: Item<'a> + 'a> Item<'a> for T
where
    T: ::std::ops::Deref<Target = I>,
{
    fn geometry(&self) -> &Geometry<'a> {
        ::std::ops::Deref::deref(self).geometry()
    }
    fn layout_info(&self) -> &LayoutInfo<'a> {
        ::std::ops::Deref::deref(self).layout_info()
    }
    fn update_paint_node(
        &self,
        node: SGNode<ContainerNode>,
        item: &dyn QQuickItem,
    ) -> SGNode<ContainerNode> {
        ::std::ops::Deref::deref(self).update_paint_node(node, item)
    }
    fn init(&self, item: &(dyn QQuickItem + 'a)) {
        (**self).init(item)
    }
    fn mouse_event(&self, event: MouseEvent) -> bool {
        ::std::ops::Deref::deref(self).mouse_event(event)
    }
}

mod layout_engine {

    use std::ops::Add;

    pub type Coord = f64;

    #[derive(Default)]
    pub struct ItemInfo {
        pub min: Coord,
        pub max: Coord,
        pub preferred: Coord,
        pub expand: usize,
    }

    impl<'a> Add<&'a ItemInfo> for ItemInfo {
        type Output = ItemInfo;

        fn add(self, other: &'a ItemInfo) -> ItemInfo {
            ItemInfo {
                min: self.min + other.min,
                max: self.max + other.max, // the idea is that it saturate with the max value or infinity
                preferred: self.preferred + other.preferred,
                expand: self.expand + other.expand,
            }
        }
    }

    pub fn compute_total_info(info: &[ItemInfo], spacing: Coord) -> ItemInfo {
        let mut sum: ItemInfo = info.iter().fold(ItemInfo::default(), Add::add);
        let total_spacing = spacing * (info.len() - 1) as Coord;
        sum.min += total_spacing;
        sum.max += total_spacing;
        sum.preferred += total_spacing;
        sum
    }

    #[derive(Clone, Copy)]
    pub struct ItemResult {
        pub size: Coord,
        pub pos: Coord,
    }

    pub fn do_layout(
        info: &[ItemInfo],
        total: ItemInfo,
        spacing: Coord,
        size: Coord,
    ) -> Vec<ItemResult> {
        // FIXME! consider maximum, or the case where we are smaller that the minimum
        if size < total.preferred {
            let to_remove = total.preferred - size;
            let total_allowed_to_remove = total.preferred - total.min;

            let mut pos = 0 as Coord;
            info.iter()
                .map(|it| {
                    let s = it.preferred
                        - (it.preferred - it.min) * to_remove / total_allowed_to_remove;
                    let p = pos;
                    pos += s + spacing;
                    ItemResult { size: s, pos: p }
                })
                .collect()
        } else {
            let to_add = size - total.preferred;
            //let total_allowed_to_add = total.max - preferred;

            let mut pos = 0 as Coord;
            info.iter()
                .map(|it| {
                    let s = if total.expand > 0 {
                        it.preferred + to_add * it.expand as Coord / total.expand as Coord
                    } else {
                        it.preferred + to_add / info.len() as Coord
                    };
                    let p = pos;
                    pos += s + spacing;
                    ItemResult { size: s, pos: p }
                })
                .collect()
        }
    }

}

macro_rules! declare_box_layout {
    ($ColumnLayout:ident, $x:ident, $width:ident, $minimum_width:ident, $maximum_width:ident, $preferred_width:ident,
        $y:ident, $height:ident, $minimum_height:ident, $maximum_height:ident, $preferred_height:ident) => {
        #[derive(Default)]
        pub struct $ColumnLayout<'a> {
            pub geometry: Geometry<'a>,
            pub layout_info: LayoutInfo<'a>,
            pub spacing: Property<'a, f64>,

            children: RefCell<Vec<Rc<dyn Item<'a> + 'a>>>,
            positions: Property<'a, Vec<layout_engine::ItemResult>>,
        }
        impl<'a> Item<'a> for $ColumnLayout<'a> {
            fn geometry(&self) -> &Geometry<'a> {
                &self.geometry
            }
            fn layout_info(&self) -> &LayoutInfo<'a> {
                &self.layout_info
            }

            fn update_paint_node(
                &self,
                mut node: SGNode<ContainerNode>,
                item: &dyn QQuickItem,
            ) -> SGNode<ContainerNode> {
                let g = self.geometry();
                node.update_static(|mut n: SGNode<TransformNode>| -> SGNode<TransformNode> {
                    n.set_translation(g.left(), g.top());
                    n.update_sub_node(|mut node: SGNode<ContainerNode>| {
                        node.update_dynamic(self.children.borrow().iter(), |i, n| {
                            i.update_paint_node(n, item)
                        });
                        node
                    });
                    n
                });
                node
            }

            fn init(&self, item: &(dyn QQuickItem + 'a)) {
                for i in self.children.borrow().iter() {
                    i.init(item);
                }
            }

            fn mouse_event(&self, event: MouseEvent) -> bool {
                for i in self.children.borrow().iter() {
                    let g = i.geometry().to_qrectf();
                    if g.contains(event.position()) {
                        return i.mouse_event(event.translated(g.top_left()));
                    }
                }
                return false;
            }
        }

        impl<'a> ItemContainer<'a> for Rc<$ColumnLayout<'a>> {
            fn add_child(&self, child: Rc<dyn Item<'a> + 'a>) {
                self.children.borrow_mut().push(child);
                $ColumnLayout::build_layout(self);
            }
        }

        impl<'a> $ColumnLayout<'a> {
            pub fn new() -> Rc<Self> {
                Default::default()
            }

            fn build_layout(this: &Rc<Self>) {
                // The minimum width is the max of the minimums
                let w = Rc::downgrade(this);
                this.layout_info.$minimum_width.set_binding(move || {
                    w.upgrade().map_or(0., |x| {
                        x.children
                            .borrow()
                            .iter()
                            .map(|i| i.layout_info().$minimum_width.get())
                            .fold(0., f64::max)
                    })
                });

                // The minimum height is the sum of the minimums
                let w = Rc::downgrade(this);
                this.layout_info.$minimum_height.set_binding(move || {
                    w.upgrade().map_or(0., |x| {
                        x.children
                            .borrow()
                            .iter()
                            .map(|i| i.layout_info().$minimum_height.get())
                            .sum()
                    })
                });

                // The maximum width is the min of the maximums
                let w = Rc::downgrade(this);
                this.layout_info.$maximum_width.set_binding(move || {
                    w.upgrade().map_or(0., |x| {
                        x.children
                            .borrow()
                            .iter()
                            .map(|i| i.layout_info().$maximum_width.get())
                            .fold(std::f64::MAX, f64::min)
                    })
                });
                // The maximum height is the sum of the maximums (assume it saturates)
                let w = Rc::downgrade(this);
                this.layout_info.$maximum_height.set_binding(move || {
                    w.upgrade().map_or(0., |x| {
                        x.children
                            .borrow()
                            .iter()
                            .map(|i| i.layout_info().$maximum_height.get())
                            .sum()
                    })
                });

                // preferred width is the minimum width
                let w = Rc::downgrade(this);
                this.layout_info.$preferred_width.set_binding(Some(move || {
                    Some(w.upgrade()?.layout_info.$minimum_width.get())
                }));

                // preferred height is the sum of preferred height
                let w = Rc::downgrade(this);
                this.layout_info.$preferred_height.set_binding(move || {
                    w.upgrade().map_or(0., |x| {
                        x.children
                            .borrow()
                            .iter()
                            .map(|i| i.layout_info().$preferred_height.get())
                            .sum()
                    })
                });

                // Set the positions
                let w = Rc::downgrade(this);
                this.positions.set_binding(move || {
                    w.upgrade().map_or(Vec::default(), |w| {
                        let v = w
                            .children
                            .borrow()
                            .iter()
                            .map(|x| {
                                layout_engine::ItemInfo {
                                    min: x.layout_info().$minimum_height.get(),
                                    max: x.layout_info().$maximum_height.get(),
                                    preferred: x.layout_info().$preferred_height.get(),
                                    expand: 1, // FIXME
                                }
                            })
                            .collect::<Vec<_>>();
                        layout_engine::do_layout(
                            &v,
                            layout_engine::compute_total_info(&v, 0.),
                            0.,
                            w.geometry.$height(),
                        )
                    })
                });

                // Set the sizes
                for (idx, x) in this.children.borrow().iter().enumerate() {
                    let w = Rc::downgrade(this);
                    x.geometry()
                        .$width
                        .set_binding(Some(move || Some(w.upgrade()?.geometry().$width())));
                    x.geometry().$x.set_binding(|| 0.);
                    let w = Rc::downgrade(this);
                    x.geometry().$height.set_binding(Some(move || {
                        Some(w.upgrade()?.positions.get().get(idx)?.size)
                    }));
                    let w = Rc::downgrade(this);
                    x.geometry().$y.set_binding(Some(move || {
                        Some(w.upgrade()?.positions.get().get(idx)?.pos)
                    }));
                }
            }
        }
    };
}

declare_box_layout!(
    ColumnLayout,
    x,
    width,
    minimum_width,
    maximum_width,
    preferred_width,
    y,
    height,
    minimum_height,
    maximum_height,
    preferred_height
);

declare_box_layout!(
    RowLayout,
    y,
    height,
    minimum_height,
    maximum_height,
    preferred_height,
    x,
    width,
    minimum_width,
    maximum_width,
    preferred_width
);

#[test]
fn test_layout() {
    #[derive(Default)]
    pub struct LItem<'a> {
        geometry: Geometry<'a>,
        layout_info: LayoutInfo<'a>,
        width: Property<'a, f64>,
        height: Property<'a, f64>,
    }
    impl<'a> Item<'a> for LItem<'a> {
        fn geometry(&self) -> &Geometry<'a> {
            &self.geometry
        }
        fn layout_info(&self) -> &LayoutInfo<'a> {
            &self.layout_info
        }
    }
    impl<'a> LItem<'a> {
        pub fn new() -> Rc<Self> {
            let r = Rc::new(LItem::default());
            let w = Rc::downgrade(&r);
            r.layout_info
                .minimum_height
                .set_binding(move || w.upgrade().map_or(0., |w| w.height.get()));
            let w = Rc::downgrade(&r);
            r.layout_info
                .preferred_height
                .set_binding(move || w.upgrade().map_or(0., |w| w.height.get()));
            let w = Rc::downgrade(&r);
            r.layout_info
                .maximum_height
                .set_binding(move || w.upgrade().map_or(0., |w| w.height.get()));
            let w = Rc::downgrade(&r);
            r.layout_info
                .minimum_width
                .set_binding(move || w.upgrade().map_or(0., |w| w.width.get()));
            let w = Rc::downgrade(&r);
            r.layout_info
                .preferred_width
                .set_binding(move || w.upgrade().map_or(0., |w| w.width.get()));
            let w = Rc::downgrade(&r);
            r.layout_info
                .maximum_width
                .set_binding(move || w.upgrade().map_or(0., |w| w.width.get()));
            r
        }
    }

    let lay = rsml! {
        ColumnLayout {
            geometry.width: ColumnLayout.layout_info.preferred_width.get(),
            geometry.height: ColumnLayout.layout_info.preferred_height.get(),
        }
    };

    lay.add_child(rsml! {
        LItem {
            width : 150.,
            height : 100.,
        }
    });
    assert_eq!(lay.geometry.width(), 150.);
    assert_eq!(lay.geometry.height(), 100.);
    let middle = rsml! {
        LItem {
            width : 110.,
            height : 90.,
        }
    };
    lay.add_child(middle.clone());
    lay.add_child(rsml! {
        LItem {
            width : 190.,
            height : 60.,
        }
    });
    assert_eq!(lay.geometry.width(), 190.);
    assert_eq!(lay.geometry.height(), 100. + 90. + 60.);

    middle.width.set(200.);
    middle.height.set(50.);

    assert_eq!(lay.geometry.width(), 200.);
    assert_eq!(lay.geometry.height(), 100. + 50. + 60.);

    assert_eq!(
        lay.geometry.height(),
        lay.children.borrow()[2].geometry().bottom()
    );
}

/// Can contains other Items, resize the items to the size of the Caintainer
#[derive(Default)]
pub struct Container<'a> {
    pub geometry: Geometry<'a>,
    pub layout_info: LayoutInfo<'a>,
    children: RefCell<Vec<Rc<dyn Item<'a> + 'a>>>,
}
impl<'a> Item<'a> for Container<'a> {
    fn geometry(&self) -> &Geometry<'a> {
        &self.geometry
    }
    fn layout_info(&self) -> &LayoutInfo<'a> {
        &self.layout_info
    }

    fn update_paint_node(
        &self,
        mut node: SGNode<ContainerNode>,
        item: &dyn QQuickItem,
    ) -> SGNode<ContainerNode> {
        let g = self.geometry();
        node.update_static(|mut n: SGNode<TransformNode>| -> SGNode<TransformNode> {
            n.set_translation(g.left(), g.top());
            n.update_sub_node(|mut node: SGNode<ContainerNode>| {
                node.update_dynamic(self.children.borrow().iter(), |i, n| {
                    i.update_paint_node(n, item)
                });
                node
            });
            n
        });
        node
    }

    fn init(&self, item: &(dyn QQuickItem + 'a)) {
        for i in self.children.borrow().iter() {
            i.init(item);
        }
    }

    fn mouse_event(&self, event: MouseEvent) -> bool {
        let mut ret = false;
        for i in self.children.borrow().iter() {
            ret = ret || i.mouse_event(event);
        }
        ret
    }
}

impl<'a> ItemContainer<'a> for Rc<Container<'a>> {
    fn add_child(&self, child: Rc<dyn Item<'a> + 'a>) {
        self.children.borrow_mut().push(child);
        Container::build_layout(self);
    }
}

impl<'a> Container<'a> {
    pub fn new() -> Rc<Self> {
        Default::default()
    }

    fn build_layout(this: &Rc<Self>) {
        for x in this.children.borrow().iter() {
            let w = Rc::downgrade(this);
            x.geometry()
                .width
                .set_binding(Some(move || Some(w.upgrade()?.geometry().width())));
            let w = Rc::downgrade(this);
            x.geometry()
                .height
                .set_binding(Some(move || Some(w.upgrade()?.geometry().height())));
            x.geometry().x.set(0.);
            x.geometry().y.set(0.);
        }
    }
}

#[derive(Default)]
pub struct Rectangle<'a> {
    pub geometry: Geometry<'a>,
    pub layout_info: LayoutInfo<'a>,
    pub color: Property<'a, QColor>,
}

impl<'a> Item<'a> for Rectangle<'a> {
    fn geometry(&self) -> &Geometry<'a> {
        &self.geometry
    }
    fn layout_info(&self) -> &LayoutInfo<'a> {
        &self.layout_info
    }

    fn init(&self, item: &(dyn QQuickItem + 'a)) {
        let item_ptr = qmetaobject::QPointer::<dyn QQuickItem>::from(item);
        self.color.on_notify(move |_| {
            if let Some(x) = item_ptr.as_ref() {
                x.update()
            };
        });
    }

    fn update_paint_node(
        &self,
        mut node: SGNode<ContainerNode>,
        item: &dyn QQuickItem,
    ) -> SGNode<ContainerNode> {
        node.update_static(|mut n: SGNode<RectangleNode>| -> SGNode<RectangleNode> {
            n.create(item);
            n.set_color(self.color.get());
            n.set_rect(self.geometry.to_qrectf());
            n
        });
        node
    }
}
impl<'a> Rectangle<'a> {
    pub fn new() -> Rc<Self> {
        Default::default()
    }
}

cpp! {{
#include <QtQuick/QQuickItem>
#include <QtQml/QQmlEngine>
}}

/// This allow to wrap any QQuickItem in order to get its scene graph node.
/// Note that the wrapped item will be hidden and will not handle events.
/// The goal is mostly to access scene graph nodes which would otherwise be private.
#[derive(Default)]
pub struct QmlItemWrapper {
    internal_item: RefCell<QJSValue>,
}
impl QmlItemWrapper {
    /// Create the internal QQuickItem, as a child of `item`.
    /// `name`  is the QML Type  (for example "Text".
    /// You should call link_property after calling init to initialize the properties.
    pub fn init(&self, item: &dyn QQuickItem, name: QString) {
        let item = item.get_cpp_object();
        let js = cpp!(unsafe [item as "QQuickItem*", name as "QString"] -> QJSValue as "QJSValue" {
            if (!item) return {};
            if (auto *engine = qmlEngine(item)) {
                auto v = engine->evaluate(
                    "(function (i) { return Qt.createQmlObject('import QtQuick 2.0; " + name
                        + "{visible: false;}', i, 'RustTextItem')} )");
                auto js = v.call( { engine->newQObject(item) });
                if (auto i = qobject_cast<QQuickItem*>(js.toQObject())) {
                    // Don't let the normal scenegraph call updatePaintNode on it.
                    i->setFlag(QQuickItem::ItemHasContents, false);
                }
                return js;
            }
            return {};
        });
        *self.internal_item.borrow_mut() = js.clone();
    }

    /// Link a Property to a QML property of the item.
    /// When the Property is changed, it will be updated the property on QQuickItem with the
    /// given name. (Not the other way around).
    pub fn link_property<'a, T: QMetaType>(&self, p: &Property<'a, T>, name: &'static CStr) {
        let js = self.internal_item.borrow().clone();
        let func = move |t: &T| {
            let var = t.to_qvariant();
            let name = name.as_ptr();
            cpp!(unsafe [var as "QVariant", js as "QJSValue", name as "const char*"] {
                if (auto item = qobject_cast<QQuickItem*>(js.toQObject())) {
                    item->setProperty(name, var);
                    if (QQuickItem *par = item->parentItem())
                        par->update();
                }
            });
        };
        func(&p.value());
        p.on_notify(func);
    }

    // unsafe because the node is not typed to this particular item
    pub unsafe fn update_node(&self, n: SGNode<()>) -> SGNode<()> {
        let raw = n.into_raw();
        let internal_item = self.internal_item.as_ptr();
        SGNode::from_raw(cpp!([internal_item as "QJSValue*", raw as "QSGNode*"]
                ->  *mut c_void as "QSGNode*" {
            if (auto item = qobject_cast<QQuickItem*>(internal_item->toQObject())) {
                // updatePaintNode is protected
                struct Helper : QQuickItem {
                    static constexpr auto upn() -> QSGNode* (QQuickItem::*)(QSGNode *, QQuickItem::UpdatePaintNodeData *)
                    { return &Helper::updatePaintNode; }
                };
                return (item->*Helper::upn())(raw, nullptr);
            }
            return nullptr;
        }))
    }
}

/// constants that follow Qt::Alignment
pub mod alignment {
    pub const LEFT: i32 = 1;
    pub const RIGHT: i32 = 2;
    pub const HCENTER: i32 = 4;
    pub const JUSTIFY: i32 = 8;
    pub const TOP: i32 = 32;
    pub const BOTTOM: i32 = 64;
    pub const VCENTER: i32 = 128;

}

/// Wraps a QtQuick Text
#[derive(Default)]
pub struct Text<'a> {
    pub geometry: Geometry<'a>,
    pub layout_info: LayoutInfo<'a>,
    pub text: Property<'a, QString>,
    pub vertical_alignment: Property<'a, i32>,
    pub horizontal_alignment: Property<'a, i32>,
    wrapper: QmlItemWrapper,
}

impl<'a> Item<'a> for Text<'a> {
    fn geometry(&self) -> &Geometry<'a> {
        &self.geometry
    }
    fn layout_info(&self) -> &LayoutInfo<'a> {
        &self.layout_info
    }

    fn update_paint_node(
        &self,
        mut node: SGNode<ContainerNode>,
        _item: &dyn QQuickItem,
    ) -> SGNode<ContainerNode> {
        node.update_static(|mut n: SGNode<TransformNode>| {
            let g = self.geometry();
            n.set_translation(g.left(), g.top());
            n.update_sub_node(|mut node: SGNode<ContainerNode>| {
                node.update_static(|n: SGNode<()>| -> SGNode<()> {
                    unsafe { self.wrapper.update_node(n) }
                });
                node
            });
            n
        });
        node
    }

    fn init(&self, item: &(dyn QQuickItem + 'a)) {
        self.wrapper.init(item, "Text".into());
        self.wrapper.link_property(&self.text, cstr!("text"));
        self.wrapper
            .link_property(&self.geometry.width, cstr!("width"));
        self.wrapper
            .link_property(&self.geometry.height, cstr!("height"));
        self.wrapper
            .link_property(&self.vertical_alignment, cstr!("verticalAlignment"));
        self.wrapper
            .link_property(&self.horizontal_alignment, cstr!("horizontalAlignment"));
    }
}
impl<'a> Text<'a> {
    pub fn new() -> Rc<Self> {
        Default::default()
    }
}

/// Similar to a QtQuick MouseArea
#[derive(Default)]
pub struct MouseArea<'a> {
    pub geometry: Geometry<'a>,
    pub layout_info: LayoutInfo<'a>,
    pub pressed: Property<'a, bool>,
    pub on_clicked: Signal<'a>,
}

impl<'a> Item<'a> for MouseArea<'a> {
    fn geometry(&self) -> &Geometry<'a> {
        &self.geometry
    }
    fn layout_info(&self) -> &LayoutInfo<'a> {
        &self.layout_info
    }
    fn mouse_event(&self, event: MouseEvent) -> bool {
        match event {
            MouseEvent::Press(_) => self.pressed.set(true),
            MouseEvent::Release(_) => {
                self.pressed.set(false);
                self.on_clicked.emit();
            }
            _ => {}
        }
        true
    }
}
impl<'a> MouseArea<'a> {
    pub fn new() -> Rc<Self> {
        Default::default()
    }
}