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
/* Copyright (C) 2018 Olivier Goffart <ogoffart@woboq.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use super::scenegraph::*;
use super::*;

/// Qt is not thread safe, and the engine can only be created once and in one thread.
/// So this is a guard that will be used to panic if the engine is created twice
static HAS_ENGINE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

cpp! {{
    #include <memory>
    #include <QtQuick/QtQuick>
    #include <QtCore/QDebug>
    #include <QtWidgets/QApplication>
    #include <QtQml/QQmlComponent>

    struct SingleApplicationGuard {
        SingleApplicationGuard() {
            rust!(Rust_QmlEngineHolder_ctor[] {
                HAS_ENGINE.compare_exchange(false, true, std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst)
                        .expect("There can only be one QmlEngine in the process");
            });
        }
        ~SingleApplicationGuard() {
            rust!(Rust_QmlEngineHolder_dtor[] {
                HAS_ENGINE.compare_exchange(true, false, std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst)
                    .unwrap();
            });
        }
    };

    struct QmlEngineHolder : SingleApplicationGuard {
        std::unique_ptr<QApplication> app;
        std::unique_ptr<QQmlApplicationEngine> engine;
        std::unique_ptr<QQuickView> view;

        static QApplication* createApplication() {
            static int argc = 1;
            static char name[] = "rust";
            static char *argv[] = { name };
            return new QApplication(argc, argv);
        }

        QmlEngineHolder() : app(createApplication()), engine(new QQmlApplicationEngine) { }
    };
}}

cpp_class!(
    /// Wrap a Qt Application and a QmlEngine
    ///
    /// Note that since there can only be one Application in the process, creating two
    /// QmlEngine at the same time is not allowed. Doing that will panic.
    pub unsafe struct QmlEngine as "QmlEngineHolder"
);
impl QmlEngine {
    /// create a new QmlEngine
    pub fn new() -> QmlEngine {
        Default::default()
    }

    /// Loads a file as a qml file (See QQmlApplicationEngine::load(const QString & filePath))
    pub fn load_file(&mut self, path: QString) {
        unsafe {
            cpp!([self as "QmlEngineHolder*", path as "QString"] {
                self->engine->load(path);
            })
        }
    }

    //     pub fn load_url(&mut self, uri: &str) {
    //     }

    /// Loads qml data (See QQmlApplicationEngine::loadData)
    pub fn load_data(&mut self, data: QByteArray) {
        unsafe {
            cpp!([self as "QmlEngineHolder*", data as "QByteArray"] {
                self->engine->loadData(data);
            })
        }
    }

    /// Loads qml data with `url` as base url component (See QQmlApplicationEngine::loadData)
    pub fn load_data_as(&mut self, data: QByteArray, url: QUrl) {
        unsafe {
            cpp!([self as "QmlEngineHolder*", data as "QByteArray", url as "QUrl"] {
                self->engine->loadData(data, url);
            })
        }
    }

    /// Launches the application
    pub fn exec(&self) {
        unsafe { cpp!([self as "QmlEngineHolder*"] { self->app->exec(); }) }
    }
    /// Closes the application
    pub fn quit(&self) {
        unsafe { cpp!([self as "QmlEngineHolder*"] { self->app->quit(); }) }
    }

    /// Sets a property for this QML context (calls QQmlEngine::rootContext()->setContextProperty)
    pub fn set_property(&mut self, name: QString, value: QVariant) {
        unsafe {
            cpp!([self as "QmlEngineHolder*", name as "QString", value as "QVariant"] {
                self->engine->rootContext()->setContextProperty(name, value);
            })
        }
    }

    /// Sets a property for this QML context (calls QQmlEngine::rootContext()->setContextProperty)
    ///
    // (TODO: consider making the lifetime the one of the engine, instead of static)
    pub fn set_object_property<T: QObject + Sized>(
        &mut self,
        name: QString,
        obj: QObjectPinned<T>,
    ) {
        let obj_ptr = obj.get_or_create_cpp_object();
        cpp!(unsafe [self as "QmlEngineHolder*", name as "QString", obj_ptr as "QObject*"] {
            self->engine->rootContext()->setContextProperty(name, obj_ptr);
        })
    }

    pub fn invoke_method(&mut self, name: QByteArray, args: &[QVariant]) -> QVariant {
        let args_size = args.len();
        let args_ptr = args.as_ptr();
        unsafe {
            cpp!([self as "QmlEngineHolder*", name as "QByteArray", args_size as "size_t", args_ptr as "QVariant*"]
                    -> QVariant as "QVariant" {
                auto robjs = self->engine->rootObjects();
                if (robjs.isEmpty())
                    return {};
                QVariant ret;
                QGenericArgument args[9] = {};
                for (uint i = 0; i < args_size; ++i)
                    args[i] = Q_ARG(QVariant, args_ptr[i]);
                QMetaObject::invokeMethod(robjs.first(), name, Q_RETURN_ARG(QVariant,ret),
                        args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
                return ret;
            })
        }
    }

    /// Give a QObject to the engine by wraping it in a QJSValue
    ///
    /// This will create the C++ object.
    /// Panic if the C++ object was already created.
    pub fn new_qobject<T: QObject>(&mut self, obj: T) -> QJSValue {
        let obj_ptr = into_leaked_cpp_ptr(obj);
        unsafe {
            cpp!([self as "QmlEngineHolder*", obj_ptr as "QObject*"] -> QJSValue as "QJSValue" {
                return self->engine->newQObject(obj_ptr);
            })
        }
    }

    /// Adds an import path for this QML engine (calls QQmlEngine::addImportPath)
    pub fn add_import_path(&mut self, path: QString) {
        unsafe {
            cpp!([self as "QmlEngineHolder*", path as "QString"] {
                self->engine->addImportPath(path);
            })
        }
    }
}

/// Bindings to a QQuickView
pub struct QQuickView {
    engine: QmlEngine,
}
impl QQuickView {
    /// Creates a new QQuickView, it's engine and an application
    pub fn new() -> QQuickView {
        let mut engine = QmlEngine::new();
        unsafe {
            cpp!([mut engine as "QmlEngineHolder"] {
            engine.view = std::unique_ptr<QQuickView>(new QQuickView(engine.engine.get(), nullptr));
            engine.view->setResizeMode(QQuickView::SizeRootObjectToView);
        } )
        };
        QQuickView { engine }
    }

    /// Returns the wrapper to the engine
    pub fn engine(&mut self) -> &mut QmlEngine {
        &mut self.engine
    }

    /// Refer to the Qt documentation of QQuickView::show
    pub fn show(&mut self) {
        let engine = self.engine();
        unsafe {
            cpp!([engine as "QmlEngineHolder*"] {
            engine->view->show();
        } )
        };
    }

    /// Refer to the Qt documentation of QQuickView::setSource
    pub fn set_source(&mut self, url: QString) {
        let engine = self.engine();
        unsafe {
            cpp!([engine as "QmlEngineHolder*", url as "QString"] {
            engine->view->setSource(url);
        } )
        };
    }
}

impl Default for QQuickView {
    fn default() -> Self {
        Self::new()
    }
}

/// See QQmlComponent::CompilationMode
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CompilationMode {
    PreferSynchronous,
    Asynchronous,
}

/// See QQmlComponent::Status
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ComponentStatus {
    Null,
    Ready,
    Loading,
    Error,
}

cpp! {{
    struct QQmlComponentHolder {
        std::unique_ptr<QQmlComponent> component;

        QQmlComponentHolder(QQmlEngine *e) : component(new QQmlComponent(e)) {}
    };
}}

cpp_class!(
    /// Wrapper for QQmlComponent
    pub unsafe struct QmlComponent as "QQmlComponentHolder"
);

impl QmlComponent {
    /// Create a QmlComponent using the QmlEngine.
    pub fn new(engine: &QmlEngine) -> QmlComponent {
        unsafe {
            cpp!([engine as "QmlEngineHolder*"] -> QmlComponent as "QQmlComponentHolder" {
                return QQmlComponentHolder(engine->engine.get());
            })
        }
    }

    /// Returns a pointer to the underlying QQmlComponent. Similar to QObject::get_cpp_object()
    pub fn get_cpp_object(&self) -> *mut c_void {
        unsafe { cpp!([self as "QQmlComponentHolder*"] -> *mut c_void as "QQmlComponent*" {
            return self->component.get();
        })}
    }

    /// Performs QQmlComponent::loadUrl
    pub fn load_url(&mut self, url: QUrl, compilation_mode: CompilationMode) {
        unsafe { cpp!([self as "QQmlComponentHolder*", url as "QUrl", compilation_mode as "QQmlComponent::CompilationMode"]{
            self->component->loadUrl(url, compilation_mode);
        })}
    }

    /// Performs QQmlComponent::setData with a default url
    pub fn set_data(&mut self, data: QByteArray) {
        unsafe { cpp!([self as "QQmlComponentHolder*", data as "QByteArray"]{
            self->component->setData(data, QUrl());
        })}
    }

    /// Performs QQmlComponent::setData
    pub fn set_data_as(&mut self, data: QByteArray, url: QUrl) {
        unsafe { cpp!([self as "QQmlComponentHolder*", data as "QByteArray", url as "QUrl"]{
            self->component->setData(data, url);
        })}
    }

    /// Performs QQmlComponent::create
    pub fn create(&mut self) -> *mut c_void {
        unsafe { cpp!([self as "QQmlComponentHolder*"] -> *mut c_void as "QObject*" {
            return self->component->create();
        })}
    }

    /// Performs QQmlComponent::status
    pub fn status(&self) -> ComponentStatus {
        unsafe { cpp!([self as "QQmlComponentHolder*"] -> ComponentStatus as "QQmlComponent::Status" {
            return self->component->status();
        })}
    }

    /// See Qt documentation for QQmlComponent::statusChanged
    pub fn status_changed_signal() -> CppSignal<fn(status: ComponentStatus)> {
        unsafe { CppSignal::new(cpp!([] -> SignalCppRepresentation as "SignalCppRepresentation"  {
            return &QQmlComponent::statusChanged;
        }))}
    }
}

/// Register the given type as a QML type
///
/// Refer to the Qt documentation for qmlRegisterType.
pub fn qml_register_type<T: QObject + Default + Sized>(
    uri: &std::ffi::CStr,
    version_major: u32,
    version_minor: u32,
    qml_name: &std::ffi::CStr,
) {
    let uri_ptr = uri.as_ptr();
    let qml_name_ptr = qml_name.as_ptr();
    let meta_object = T::static_meta_object();

    extern "C" fn extra_destruct(c: *mut c_void) {
        unsafe { cpp!([c as "QObject*"]{ QQmlPrivate::qdeclarativeelement_destructor(c); }) }
    }

    extern "C" fn creator_fn<T: QObject + Default + Sized>(c: *mut c_void) {
        let b: Box<RefCell<T>> = Box::new(RefCell::new(T::default()));
        let ed: extern "C" fn(c: *mut c_void) = extra_destruct;
        unsafe {
            T::qml_construct(&b, c, ed);
        }
        std::boxed::Box::into_raw(b);
    };
    let creator_fn: extern "C" fn(c: *mut c_void) = creator_fn::<T>;

    let size = T::cpp_size();

    unsafe { cpp!([qml_name_ptr as "char*", uri_ptr as "char*", version_major as "int",
                    version_minor as "int", meta_object as "const QMetaObject *",
                    creator_fn as "CreatorFunction", size as "size_t"]{

        const char *className = qml_name_ptr;
        // BEGIN: From QML_GETTYPENAMES
        const int nameLen = int(strlen(className));
        QVarLengthArray<char,48> pointerName(nameLen+2);
        memcpy(pointerName.data(), className, size_t(nameLen));
        pointerName[nameLen] = '*';
        pointerName[nameLen+1] = '\0';
        /*const int listLen = int(strlen("QQmlListProperty<"));
        QVarLengthArray<char,64> listName(listLen + nameLen + 2);
        memcpy(listName.data(), "QQmlListProperty<", size_t(listLen));
        memcpy(listName.data()+listLen, className, size_t(nameLen));
        listName[listLen+nameLen] = '>';
        listName[listLen+nameLen+1] = '\0';*/
        //END

        auto ptrType = QMetaType::registerNormalizedType(pointerName.constData(),
            QtMetaTypePrivate::QMetaTypeFunctionHelper<void*>::Destruct,
            QtMetaTypePrivate::QMetaTypeFunctionHelper<void*>::Construct,
            int(sizeof(void*)), QMetaType::MovableType | QMetaType::PointerToQObject,
            meta_object);

        int parserStatusCast = meta_object && meta_object->inherits(&QQuickItem::staticMetaObject)
            ? QQmlPrivate::StaticCastSelector<QQuickItem,QQmlParserStatus>::cast() : -1;

        QQmlPrivate::RegisterType type = {
            0 /*version*/, ptrType, 0, /* FIXME?*/
            int(size), creator_fn,
            QString(),
            uri_ptr, version_major, version_minor, qml_name_ptr, meta_object,
            nullptr, nullptr, // attached properties
            parserStatusCast, -1, -1,
            nullptr, nullptr,
            nullptr,
            0
        };
        QQmlPrivate::qmlregister(QQmlPrivate::TypeRegistration, &type);
    })}
}

/// Register the given enum as a QML type
///
/// Refer to the Qt documentation for qmlRegisterUncreatableMetaObject.
pub fn qml_register_enum<T: QEnum>(
    uri: &std::ffi::CStr,
    version_major: u32,
    version_minor: u32,
    qml_name: &std::ffi::CStr,
) {
    let uri_ptr = uri.as_ptr();
    let qml_name_ptr = qml_name.as_ptr();
    let meta_object = T::static_meta_object();

    unsafe {
        cpp!([qml_name_ptr as "char*", uri_ptr as "char*", version_major as "int",
                        version_minor as "int", meta_object as "const QMetaObject *"]{
            qmlRegisterUncreatableMetaObject(*meta_object, uri_ptr, version_major,
                version_minor, qml_name_ptr, "Access to enums & flags only");
        })
    }
}

/// A QObject-like trait to inherit from QQuickItem.
///
/// Work in progress
pub trait QQuickItem: QObject {
    fn get_object_description() -> &'static QObjectDescription
    where
        Self: Sized,
    {
        unsafe {
            &*cpp!([]-> *const QObjectDescription as "RustObjectDescription const*" {
            return rustObjectDescription<Rust_QQuickItem>();
        } )
        }
    }

    fn class_begin(&mut self) {}
    fn component_complete(&mut self) {}

    /// Handle mouse press, release, or move events. Returns true if the event was accepted.
    fn mouse_event(&mut self, _event: QMouseEvent) -> bool {
        false
    }

    fn geometry_changed(&mut self, _new_geometry: QRectF, _old_geometry: QRectF) {}

    fn update_paint_node(&mut self, node: SGNode<ContainerNode>) -> SGNode<ContainerNode> {
        node
    }
}

cpp! {{
#include <qmetaobject_rust.hpp>
#include <QtQuick/QQuickItem>
struct Rust_QQuickItem : RustObject<QQuickItem> {
/*
    virtual QRectF boundingRect() const;
    virtual QRectF clipRect() const;
    virtual bool contains(const QPointF &point) const;
    virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
    virtual bool isTextureProvider() const;
    virtual QSGTextureProvider *textureProvider() const;
    virtual void itemChange(ItemChange, const ItemChangeData &);*/
    void classBegin() override {
        QQuickItem::classBegin();
        rust!(Rust_QQuickItem_classBegin[rust_object : QObjectPinned<dyn QQuickItem> as "TraitObject"] {
            rust_object.borrow_mut().class_begin();
        });
    }

    void componentComplete() override {
        QQuickItem::componentComplete();
        rust!(Rust_QQuickItem_componentComplete[rust_object : QObjectPinned<dyn QQuickItem> as "TraitObject"] {
            rust_object.borrow_mut().component_complete();
        });
    }

    /*virtual void keyPressEvent(QKeyEvent *event);
    virtual void keyReleaseEvent(QKeyEvent *event);
    virtual void inputMethodEvent(QInputMethodEvent *);
    virtual void focusInEvent(QFocusEvent *);
    virtual void focusOutEvent(QFocusEvent *);*/

    void mousePressEvent(QMouseEvent *event) override { handleMouseEvent(event); }
    void mouseMoveEvent(QMouseEvent *event) override { handleMouseEvent(event); }
    void mouseReleaseEvent(QMouseEvent *event) override { handleMouseEvent(event); }
    //void mouseDoubleClickEvent(QMouseEvent *event) override { handleMouseEvent(event); }

    void handleMouseEvent(QMouseEvent *event) {
       if (!rust!(Rust_QQuickItem_mousePressEvent[
            rust_object : QObjectPinned<dyn QQuickItem> as "TraitObject",
            event : QMouseEvent as "QMouseEvent*"
        ] -> bool as "bool" {
            rust_object.borrow_mut().mouse_event(event)
        })) { event->ignore(); }
    }

    /*


    virtual void mouseUngrabEvent(); // XXX todo - params?
    virtual void touchUngrabEvent();
    virtual void wheelEvent(QWheelEvent *event);
    virtual void touchEvent(QTouchEvent *event);
    virtual void hoverEnterEvent(QHoverEvent *event);
    virtual void hoverMoveEvent(QHoverEvent *event);
    virtual void hoverLeaveEvent(QHoverEvent *event);
    virtual void dragEnterEvent(QDragEnterEvent *);
    virtual void dragMoveEvent(QDragMoveEvent *);
    virtual void dragLeaveEvent(QDragLeaveEvent *);
    virtual void dropEvent(QDropEvent *);
    virtual bool childMouseEventFilter(QQuickItem *, QEvent *);
    virtual void windowDeactivateEvent();*/
    virtual void geometryChanged(const QRectF &new_geometry,
                                 const QRectF &old_geometry) {
        rust!(Rust_QQuickItem_geometryChanged[rust_object : QObjectPinned<dyn QQuickItem> as "TraitObject",
                new_geometry : QRectF as "QRectF", old_geometry : QRectF as "QRectF"] {
            rust_object.borrow_mut().geometry_changed(new_geometry, old_geometry);
        });
        QQuickItem::geometryChanged(new_geometry, old_geometry);
    }

    QSGNode *updatePaintNode(QSGNode *node, UpdatePaintNodeData *) override {
        return rust!(Rust_QQuickItem_updatePaintNode[rust_object : QObjectPinned<dyn QQuickItem> as "TraitObject",
                    node : *mut c_void as "QSGNode*"] -> SGNode<ContainerNode> as "QSGNode*" {
            rust_object.borrow_mut().update_paint_node(unsafe { SGNode::<ContainerNode>::from_raw(node) })
        });
    }
    /*
    virtual void releaseResources();
    virtual void updatePolish();
*/

};

}}

impl<'a> dyn QQuickItem + 'a {
    pub fn bounding_rect(&self) -> QRectF {
        let obj = self.get_cpp_object();
        cpp!(unsafe [obj as "Rust_QQuickItem*"] -> QRectF as "QRectF" {
            return obj ? obj->boundingRect() : QRectF();
        })
    }
    pub fn update(&self) {
        let obj = self.get_cpp_object();
        cpp!(unsafe [obj as "Rust_QQuickItem*"] { if (obj) obj->update(); });
    }
}

#[repr(u32)]
pub enum QMouseEventType {
    MouseButtonPress = 2,
    MouseButtonRelease = 3,
    //MouseButtonDblClick = 4,
    MouseMove = 5,
}

/// A reference to a QMouseEvent
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct QMouseEvent<'a>(*const c_void, std::marker::PhantomData<&'a u32>);
impl<'a> QMouseEvent<'a> {
    /// Returns the type of event
    pub fn event_type(self) -> QMouseEventType {
        cpp!(unsafe [self as "QMouseEvent*"] -> QMouseEventType as "int" { return self->type(); })
    }
    /// Return the position, wrapper around Qt's QMouseEvent::localPos()
    pub fn position(self) -> QPointF {
        cpp!(unsafe [self as "QMouseEvent*"] -> QPointF as "QPointF" { return self->localPos(); })
    }
}

cpp_class!(
    /// Wrapper for QJSValue
    pub unsafe struct QJSValue as "QJSValue"
);
impl QJSValue {
    pub fn to_string(&self) -> QString {
        unsafe {
            cpp!([self as "const QJSValue*"] -> QString as "QString" { return self->toString(); })
        }
    }

    pub fn to_bool(&self) -> bool {
        unsafe { cpp!([self as "const QJSValue*"] -> bool as "bool" { return self->toBool(); }) }
    }

    pub fn to_number(&self) -> f64 {
        unsafe { cpp!([self as "const QJSValue*"] -> f64 as "double" { return self->toNumber(); }) }
    }

    pub fn to_variant(&self) -> QVariant {
        unsafe {
            cpp!([self as "const QJSValue*"] -> QVariant as "QVariant" { return self->toVariant(); })
        }
    }

    pub fn to_qobject<'a, T: QObject + 'a>(&'a self) -> Option<QObjectPinned<'a, T>> {
        let mo = T::static_meta_object();
        let obj = unsafe {
            cpp!([self as "const QJSValue*", mo as "const QMetaObject*"] -> *mut c_void as "QObject*" {
                QObject *obj = self->toQObject();
                // FIXME! inheritence?
                return obj && obj->metaObject()->inherits(mo) ? obj : nullptr;
            })
        };
        if obj.is_null() {
            return None;
        }
        Some(unsafe { T::get_from_cpp(obj) })
    }
}
impl From<QString> for QJSValue {
    fn from(a: QString) -> QJSValue {
        unsafe { cpp!([a as "QString"] -> QJSValue as "QJSValue" { return QJSValue(a); }) }
    }
}
impl From<i32> for QJSValue {
    fn from(a: i32) -> QJSValue {
        unsafe { cpp!([a as "int"] -> QJSValue as "QJSValue" { return QJSValue(a); }) }
    }
}
impl From<u32> for QJSValue {
    fn from(a: u32) -> QJSValue {
        unsafe { cpp!([a as "uint"] -> QJSValue as "QJSValue" { return QJSValue(a); }) }
    }
}
impl From<f64> for QJSValue {
    fn from(a: f64) -> QJSValue {
        unsafe { cpp!([a as "double"] -> QJSValue as "QJSValue" { return QJSValue(a); }) }
    }
}
impl From<bool> for QJSValue {
    fn from(a: bool) -> QJSValue {
        unsafe { cpp!([a as "bool"] -> QJSValue as "QJSValue" { return QJSValue(a); }) }
    }
}

#[cfg(test)]
mod qjsvalue_tests {
    use super::*;
    #[test]
    fn test_qjsvalue() {
        let foo = QJSValue::from(45);
        assert_eq!(foo.to_number(), 45 as f64);
        assert_eq!(foo.to_string(), "45".into());
        assert_eq!(foo.to_variant().to_qbytearray(), "45".into());
    }

    #[test]
    fn test_qvariantlist_from_iter() {
        let v = vec![1u32, 2u32, 3u32];
        let qvl: QVariantList = v.iter().collect();
        assert_eq!(qvl.len(), 3);
        assert_eq!(qvl[1].to_qbytearray().to_string(), "2");
    }
}

/// A QObject-like trait to inherit from QQmlExtensionPlugin.
///
/// Refer to the Qt documentation of QQmlExtensionPlugin
///
/// See also the 'qmlextensionplugins' example.
///
/// ```
/// # extern crate qmetaobject; use qmetaobject::*;
/// #[derive(Default, QObject)]
/// struct QExampleQmlPlugin {
///     base: qt_base_class!(trait QQmlExtensionPlugin),
///     plugin: qt_plugin!("org.qt-project.Qt.QQmlExtensionInterface/1.0"),
/// }
///
/// impl QQmlExtensionPlugin for QExampleQmlPlugin {
///     fn register_types(&mut self, uri: &std::ffi::CStr) {
///         // call `qml_register_type` here
///     }
/// }
/// ```

pub trait QQmlExtensionPlugin: QObject {
    #[doc(hidden)] // implementation detail for the QObject custom derive
    fn get_object_description() -> &'static QObjectDescription
    where
        Self: Sized,
    {
        unsafe {
            &*cpp!([]-> *const QObjectDescription as "RustObjectDescription const*" {
            return rustObjectDescription<Rust_QQmlExtensionPlugin>();
        } )
        }
    }

    /// Refer to the Qt documentation of QQmlExtensionPlugin::registerTypes
    fn register_types(&mut self, uri: &std::ffi::CStr);
}

cpp! {{
#include <qmetaobject_rust.hpp>
#include <QtQml/QQmlExtensionPlugin>
struct Rust_QQmlExtensionPlugin : RustObject<QQmlExtensionPlugin> {
    void registerTypes(const char *uri) override  {
        rust!(Rust_QQmlExtensionPlugin_registerTypes[rust_object : QObjectPinned<dyn QQmlExtensionPlugin> as "TraitObject",
                                                            uri : *const std::os::raw::c_char as "const char*"] {
            rust_object.borrow_mut().register_types(unsafe { std::ffi::CStr::from_ptr(uri) });
        });
    }
};

}}