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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
/* 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.
*/
//! This crate contains manually generated bindings to Qt basic value types.
//! It is meant to be used by other crates, such as the `qmetaobject` crate which re-expose them.
//!
//! The Qt types are basically exposed using the [`mod@cpp`] crate. They have manually writen rust idiomatic
//! API which expose the C++ API.
//! These types are the direct equivalent of the Qt types and are exposed on the stack.
//!
//! In addition, the build script of this crate expose some metadata to downstream crate that also
//! want to use Qt's C++ API.
//! Build scripts of crates that depends directly from this crate will have the following
//! environment variables set when the build script is run:
//! - `DEP_QT_VERSION`: The Qt version as given by qmake.
//! - `DEP_QT_INCLUDE_PATH`: The include directory to give to the `cpp_build` crate to locate the Qt headers.
//! - `DEP_QT_LIBRARY_PATH`: The path containing the Qt libraries.
//! - `DEP_QT_COMPILE_FLAGS`: A list of flags separated by `;`
//! - `DEP_QT_FOUND`: Set to 1 when qt was found, or 0 if qt was not found and the `required` feature is not set.
//! - `DEP_QT_ERROR_MESSAGE`: when `DEP_QT_FOUND` is 0, contains the error that caused the build to fail
//!
//! ## Finding Qt
//!
//! This is the algorithm used to find Qt.
//!
//! - You can set the environment variable `QT_INCLUDE_PATH` and `QT_LIBRARY_PATH` to be a single
//!   directory where the Qt headers and Qt libraries are installed.
//! - Otherwise you can specify a `QMAKE` environment variable with the absolute path of the
//!   `qmake` executable which will be used to query these paths.
//! - If none of these environment variable is set, the `qmake` executable found in `$PATH`.
//!
//! ## Philosophy
//!
//! The goal of this crate is to expose a idiomatic Qt API for the core value type classes.
//! The API is manually generated to expose required feature in the most rust-like API, while
//! still keeping the similarities with the Qt API itself.
//!
//! It is not meant to expose all of the Qt API exhaustively, but only the part which is
//! relevant for the usage in other crate.
//! If you see a feature missing, feel free to write a issue or a pull request.
//!
//! Note that this crate concentrate on the value types, not the widgets or the
//! the `QObject`.  For that, there is the `qmetaobject` crate.
//!
//! ## Usage with the `cpp` crate
//!
//! Here is an example that make use of the types exposed by this crate in combination
//! with the [`mod@cpp`] crate to call native API:
//!
//! In `Cargo.toml`
//! ```toml
//! #...
//! [dependencies]
//! qttype = "0.1"
//! cpp = "0.5"
//! #...
//! [build-dependencies]
//! cpp_build = "0.5"
//! ```
//!
//! Note: It is important to depend directly on `qttype`, it is not enough to rely on the
//! dependency coming transitively from another dependencies, otherwise the `DEP_QT_*`
//! environment variables won't be defined.
//!
//! Then in the `build.rs` file:
//! ```rust,no_run
//! fn main() {
//!     let mut config = cpp_build::Config::new();
//!     config.include(std::env::var("DEP_QT_INCLUDE_PATH").unwrap());
//!     for f in std::env::var("DEP_QT_COMPILE_FLAGS").unwrap().split_terminator(";") {
//!        config.flag(f);
//!     }
//!     config.build("src/main.rs");
//! }
//! ```
//!
//! With that, you can now use the types inside your .rs files:
//!
//! ```ignore
//! let byte_array = qttypes::QByteArray::from("Hello World!");
//! cpp::cpp!([byte_array as "QByteArray"] { qDebug() << byte_array; });
//! ```
//!
//! You will find a small but working example in the
//! [qmetaobject-rs repository](https://github.com/woboq/qmetaobject-rs/tree/master/examples/graph).
//!
//! ## Cargo Features
//!
//! - **`required`**: When this feature is enabled (the default), the build script will panic with an error
//!   if Qt is not found. Otherwise, when not enabled, the build will continue, but any use of the classes will
//!   panic at runtime.
//! - **`chrono`**: enable the conversion between [`QDateTime`] related types and the types from the `chrono` crate.
//!
//! Link against these Qt modules using cargo features:
//!
//! | Cargo feature             | Qt module             |
//! | ------------------------- | --------------------- |
//! | **`qtmultimedia`**        | Qt Multimedia         |
//! | **`qtmultimediawidgets`** | Qt Multimedia Widgets |
//! | **`qtquick`**             | Qt Quick              |
//! | **`qtquickcontrols2`**    | Qt Quick Controls     |
//! | **`qtsql`**               | Qt SQL                |
//! | **`qttest`**              | Qt Test               |
//! | **`qtwebengine`**         | Qt WebEngine          |
//!

#![cfg_attr(no_qt, allow(unused))]

use std::collections::HashMap;
use std::convert::From;
use std::fmt;
use std::hash::Hash;
use std::iter::FromIterator;
use std::ops::{Index, IndexMut};

#[cfg(feature = "chrono")]
use chrono::prelude::*;

#[cfg(no_qt)]
pub(crate) mod no_qt {
    pub fn panic<T>() -> T {
        panic!("Qt was not found during build")
    }
}

pub(crate) mod internal_prelude {
    #[cfg(not(no_qt))]
    pub(crate) use cpp::{cpp, cpp_class};
    #[cfg(no_qt)]
    macro_rules! cpp {
        {{ $($t:tt)* }} => {};
        {$(unsafe)? [$($a:tt)*] -> $ret:ty as $b:tt { $($t:tt)* } } => {
            crate::no_qt::panic::<$ret>()
        };
        { $($t:tt)* } => {
            crate::no_qt::panic::<()>()
        };
    }

    #[cfg(no_qt)]
    macro_rules! cpp_class {
        ($(#[$($attrs:tt)*])* $vis:vis unsafe struct $name:ident as $type:expr) => {
            #[derive(Default, Ord, Eq, PartialEq, PartialOrd, Clone, Copy)]
            #[repr(C)]
            $vis struct $name;
        };
    }
    #[cfg(no_qt)]
    pub(crate) use cpp;
    #[cfg(no_qt)]
    pub(crate) use cpp_class;
}
use internal_prelude::*;

mod qtcore;
pub use crate::qtcore::{
    qreal, NormalizationForm, QByteArray, QListIterator, QSettings, QString, QStringList, QUrl,
    QVariant, QVariantList, UnicodeVersion,
};

mod qtgui;
pub use crate::qtgui::{QColor, QColorNameFormat, QColorSpec, QRgb, QRgba64};

cpp! {{
    #include <QtCore/QByteArray>
    #include <QtCore/QDateTime>
    #include <QtCore/QModelIndex>
    #include <QtCore/QString>
    #include <QtCore/QUrl>
    #include <QtCore/QVariant>

    #include <QtGui/QImage>
    #include <QtGui/QPixmap>
    #include <QtGui/QPainter>
    #include <QtGui/QPen>
    #include <QtGui/QBrush>
}}

cpp_class!(
    /// Wrapper around [`QDate`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qdate.html
    #[derive(PartialEq, PartialOrd, Eq, Ord)]
    pub unsafe struct QDate as "QDate"
);
impl QDate {
    /// Wrapper around [`QDate(int y, int m, int d)`][ctor] constructor.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qdate.html#QDate-2
    pub fn from_y_m_d(y: i32, m: i32, d: i32) -> Self {
        cpp!(unsafe [y as "int", m as "int", d as "int"] -> QDate as "QDate" {
            return QDate(y, m, d);
        })
    }

    /// Wrapper around [`QDate::getDate(int *year, int *month, int *day)`][method] method.
    ///
    /// # Wrapper-specific
    ///
    /// Returns the year, month and day components as a tuple, instead of mutable references.
    ///
    /// [method]: https://doc.qt.io/qt-5/qdate.html#getDate
    pub fn get_y_m_d(&self) -> (i32, i32, i32) {
        let mut res = (0, 0, 0);
        let (ref mut y, ref mut m, ref mut d) = res;

        // In version prior to Qt 5.7, this method was marked non-const.
        // A #[cfg(qt_5_7)] attribute does not solve that issue, because the cpp_build crate is not
        // smart enough not to compile the non-qualifying closure.
        cpp!(unsafe [self as "QDate*", y as "int*", m as "int*", d as "int*"] {
            return self->getDate(y, m, d);
        });

        res
    }

    /// Wrapper around [`QDate::isValid()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qdate.html#isValid
    pub fn is_valid(&self) -> bool {
        cpp!(unsafe [self as "const QDate*"] -> bool as "bool" {
            return self->isValid();
        })
    }
}
#[cfg(feature = "chrono")]
impl From<NaiveDate> for QDate {
    fn from(a: NaiveDate) -> QDate {
        QDate::from_y_m_d(a.year() as i32, a.month() as i32, a.day() as i32)
    }
}
#[cfg(feature = "chrono")]
impl Into<NaiveDate> for QDate {
    fn into(self) -> NaiveDate {
        let (y, m, d) = self.get_y_m_d();
        NaiveDate::from_ymd(y, m as u32, d as u32)
    }
}

#[test]
fn test_qdate() {
    let date = QDate::from_y_m_d(2019, 10, 22);
    assert_eq!((2019, 10, 22), date.get_y_m_d());
}

#[test]
fn test_qdate_is_valid() {
    let valid_qdate = QDate::from_y_m_d(2019, 10, 26);
    assert!(valid_qdate.is_valid());

    let invalid_qdate = QDate::from_y_m_d(-1, -1, -1);
    assert!(!invalid_qdate.is_valid());
}

#[cfg(feature = "chrono")]
#[test]
fn test_qdate_chrono() {
    let chrono_date = NaiveDate::from_ymd(2019, 10, 22);
    let qdate: QDate = chrono_date.into();
    let actual_chrono_date: NaiveDate = qdate.into();

    // Ensure that conversion works for both the Into trait and get_y_m_d() function
    assert_eq!((2019, 10, 22), qdate.get_y_m_d());
    assert_eq!(chrono_date, actual_chrono_date);
}

cpp_class!(
    /// Wrapper around [`QTime`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qtime.html
    #[derive(PartialEq, PartialOrd, Eq, Ord)]
    pub unsafe struct QTime as "QTime"
);
impl QTime {
    /// Wrapper around [`QTime(int h, int m, int s = 0, int ms = 0)`][ctor] constructor.
    ///
    /// # Wrapper-specific
    ///
    /// Default arguments converted to `Option`s.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qtime.html#QTime-2
    pub fn from_h_m_s_ms(h: i32, m: i32, s: Option<i32>, ms: Option<i32>) -> Self {
        let s = s.unwrap_or(0);
        let ms = ms.unwrap_or(0);

        cpp!(unsafe [h as "int", m as "int", s as "int", ms as "int"] -> QTime as "QTime" {
            return QTime(h, m, s, ms);
        })
    }

    /// Wrapper around [`QTime::hour()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qtime.html#hour
    pub fn get_hour(&self) -> i32 {
        cpp!(unsafe [self as "const QTime*"] -> i32 as "int" {
            return self->hour();
        })
    }

    /// Wrapper around [`QTime::minute()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qtime.html#minute
    pub fn get_minute(&self) -> i32 {
        cpp!(unsafe [self as "const QTime*"] -> i32 as "int" {
            return self->minute();
        })
    }

    /// Wrapper around [`QTime::second()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qtime.html#second
    pub fn get_second(&self) -> i32 {
        cpp!(unsafe [self as "const QTime*"] -> i32 as "int" {
            return self->second();
        })
    }

    /// Wrapper around [`QTime::msec()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qtime.html#msec
    pub fn get_msec(&self) -> i32 {
        cpp!(unsafe [self as "const QTime*"] -> i32 as "int" {
            return self->msec();
        })
    }

    /// Convenience function for obtaining the hour, minute, second and millisecond components.
    pub fn get_h_m_s_ms(&self) -> (i32, i32, i32, i32) {
        (self.get_hour(), self.get_minute(), self.get_second(), self.get_msec())
    }

    /// Wrapper around [`QTime::isValid()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qtime.html#isValid
    pub fn is_valid(&self) -> bool {
        cpp!(unsafe [self as "const QTime*"] -> bool as "bool" {
            return self->isValid();
        })
    }
}

#[cfg(feature = "chrono")]
impl From<NaiveTime> for QTime {
    fn from(a: NaiveTime) -> QTime {
        QTime::from_h_m_s_ms(
            a.hour() as i32,
            a.minute() as i32,
            Some(a.second() as i32),
            Some(a.nanosecond() as i32 / 1_000_000),
        )
    }
}

#[cfg(feature = "chrono")]
impl Into<NaiveTime> for QTime {
    fn into(self) -> NaiveTime {
        let (h, m, s, ms) = self.get_h_m_s_ms();
        NaiveTime::from_hms_milli(h as u32, m as u32, s as u32, ms as u32)
    }
}

#[test]
fn test_qtime() {
    let qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(300));
    assert_eq!((10, 30, 40, 300), qtime.get_h_m_s_ms());
}

#[cfg(feature = "chrono")]
#[test]
fn test_qtime_chrono() {
    let chrono_time = NaiveTime::from_hms(10, 30, 50);
    let qtime: QTime = chrono_time.into();
    let actual_chrono_time: NaiveTime = qtime.into();

    // Ensure that conversion works for both the Into trait and get_h_m_s_ms() function
    assert_eq!((10, 30, 50, 0), qtime.get_h_m_s_ms());
    assert_eq!(chrono_time, actual_chrono_time);
}

#[test]
fn test_qtime_is_valid() {
    let valid_qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(300));
    assert!(valid_qtime.is_valid());

    let invalid_qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(9999));
    assert!(!invalid_qtime.is_valid());
}

cpp_class!(
    /// Wrapper around [`QDateTime`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qdatetime.html
    #[derive(PartialEq, PartialOrd, Eq, Ord)]
    pub unsafe struct QDateTime as "QDateTime"
);
impl QDateTime {
    /// Wrapper around [`QDateTime(const QDateTime &other)`][ctor] constructor.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qdatetime.html#QDateTime-1
    pub fn from_date(date: QDate) -> Self {
        cpp!(unsafe [date as "QDate"] -> QDateTime as "QDateTime" {
        #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
                    return date.startOfDay();
        #else
                    return QDateTime(date);
        #endif
        })
    }

    /// Wrapper around [`QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec = Qt::LocalTime)`][ctor] constructor.
    ///
    /// # Wrapper-specific
    ///
    /// `spec` is left as it is, thus it is always `Qt::LocalTime`.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qdatetime.html#QDateTime-2
    pub fn from_date_time_local_timezone(date: QDate, time: QTime) -> Self {
        cpp!(unsafe [date as "QDate", time as "QTime"] -> QDateTime as "QDateTime" {
            return QDateTime(date, time);
        })
    }

    /// Wrapper around [`QDateTime::date()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qdatetime.html#date
    pub fn get_date(&self) -> QDate {
        cpp!(unsafe [self as "const QDateTime*"] -> QDate as "QDate" {
            return self->date();
        })
    }

    /// Wrapper around [`QDateTime::time()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qdatetime.html#time
    pub fn get_time(&self) -> QTime {
        cpp!(unsafe [self as "const QDateTime*"] -> QTime as "QTime" {
            return self->time();
        })
    }

    /// Convenience function for obtaining both date and time components.
    pub fn get_date_time(&self) -> (QDate, QTime) {
        (self.get_date(), self.get_time())
    }

    /// Wrapper around [`QDateTime::isValid()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qdatetime.html#isValid
    pub fn is_valid(&self) -> bool {
        cpp!(unsafe [self as "const QDateTime*"] -> bool as "bool" {
            return self->isValid();
        })
    }
}

#[test]
fn test_qdatetime_from_date() {
    let qdate = QDate::from_y_m_d(2019, 10, 22);
    let qdatetime = QDateTime::from_date(qdate);
    let actual_qdate = qdatetime.get_date();

    assert_eq!((2019, 10, 22), actual_qdate.get_y_m_d());
}

#[test]
fn test_qdatetime_from_date_time_local_timezone() {
    let qdate = QDate::from_y_m_d(2019, 10, 22);
    let qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(300));
    let qdatetime = QDateTime::from_date_time_local_timezone(qdate, qtime);
    let (actual_qdate, actual_qtime) = qdatetime.get_date_time();

    assert_eq!((2019, 10, 22), actual_qdate.get_y_m_d());
    assert_eq!((10, 30, 40, 300), actual_qtime.get_h_m_s_ms());

    assert_eq!(10, actual_qtime.get_hour());
    assert_eq!(30, actual_qtime.get_minute());
    assert_eq!(40, actual_qtime.get_second());
    assert_eq!(300, actual_qtime.get_msec());
}

#[test]
fn test_qdatetime_is_valid() {
    let valid_qdate = QDate::from_y_m_d(2019, 10, 26);
    let invalid_qdate = QDate::from_y_m_d(-1, -1, -1);

    let valid_qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(300));
    let invalid_qtime = QTime::from_h_m_s_ms(10, 30, Some(40), Some(9999));

    let valid_qdatetime_from_date = QDateTime::from_date(valid_qdate);
    assert!(valid_qdatetime_from_date.is_valid());

    let valid_qdatetime_from_valid_date_valid_time =
        QDateTime::from_date_time_local_timezone(valid_qdate, valid_qtime);
    assert!(valid_qdatetime_from_valid_date_valid_time.is_valid());

    // Refer to the documentation for QDateTime's constructors using QDate, QTime.
    // If the date is valid, but the time is not, the time will be set to midnight
    let valid_qdatetime_from_valid_date_invalid_time =
        QDateTime::from_date_time_local_timezone(valid_qdate, invalid_qtime);
    assert!(valid_qdatetime_from_valid_date_invalid_time.is_valid());

    let invalid_qdatetime_from_invalid_date_valid_time =
        QDateTime::from_date_time_local_timezone(invalid_qdate, valid_qtime);
    assert!(!invalid_qdatetime_from_invalid_date_valid_time.is_valid());

    let invalid_qdatetime_from_invalid_date_invalid_time =
        QDateTime::from_date_time_local_timezone(invalid_qdate, invalid_qtime);
    assert!(!invalid_qdatetime_from_invalid_date_invalid_time.is_valid());
}

cpp_class!(
    /// Wrapper around [`QVariantMap`][type] typedef.
    ///
    /// [type]: https://doc.qt.io/qt-5/qvariant.html#QVariantMap-typedef
    #[derive(Default, PartialEq, Eq)]
    pub unsafe struct QVariantMap as "QVariantMap"
);

impl QVariantMap {
    /// Wrapper around [`insert(int, const QString &, const QVariant &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qlist.html#insert
    pub fn insert(&mut self, key: QString, element: QVariant) {
        cpp!(unsafe [self as "QVariantMap*", key as "QString", element as "QVariant"] {
            self->insert(key, std::move(element));
        })
    }

    /// Wrapper around [`remove(const QString &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#remove
    pub fn remove(&mut self, key: QString) -> usize {
        cpp!(unsafe [self as "QVariantMap*", key as "QString"] -> usize as "size_t" {
            return self->remove(key);
        })
    }

    /// Wrapper around [`take(const QString &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#take
    pub fn take(&mut self, key: QString) -> QVariant {
        cpp!(unsafe [self as "QVariantMap*", key as "QString"] -> QVariant as "QVariant" {
            return self->take(key);
        })
    }

    /// Wrapper around [`size()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#size
    pub fn len(&self) -> usize {
        cpp!(unsafe [self as "const QVariantMap*"] -> usize as "size_t" {
            return self->size();
        })
    }

    /// Wrapper around [`isEmpty()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#isEmpty
    pub fn is_empty(&self) -> bool {
        cpp!(unsafe [self as "const QVariantMap*"] -> bool as "bool" {
            return self->isEmpty();
        })
    }

    /// Wrapper around [`contains(const QString &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#contains
    pub fn contains(&self, key: QString) -> bool {
        cpp!(unsafe [self as "const QVariantMap*", key as "QString"] -> bool as "bool" {
            return self->contains(key);
        })
    }

    /// Wrapper around [`clear()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#clear
    pub fn clear(&mut self) {
        cpp!(unsafe [self as "QVariantMap*"] {
            self->clear();
        })
    }

    /// Wrapper around [`value(const QString &, const QVariant &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#value
    pub fn value(&self, key: QString, default_value: QVariant) -> QVariant {
        cpp!(unsafe [self as "const QVariantMap*", key as "QString", default_value as "QVariant"] -> QVariant as "QVariant" {
            return self->value(key, default_value);
        })
    }

    /// Wrapper around [`key(const QVariant &, const QString &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmap.html#key
    pub fn key(&self, value: QVariant, default_key: QString) -> QString {
        cpp!(unsafe [self as "const QVariantMap*", default_key as "QString", value as "QVariant"] -> QString as "QString" {
            return self->key(value, default_key);
        })
    }
}

impl Index<QString> for QVariantMap {
    type Output = QVariant;

    /// Wrapper around [`at(int)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qlist.html#at
    #[track_caller]
    fn index(&self, key: QString) -> &Self::Output {
        cpp!(unsafe [self as "const QVariantMap*", key as "QString"] -> Option<&QVariant> as "const QVariant*" {
                auto x = self->constFind(key);
                if (x == self->constEnd()) {
                    return NULL;
                } else {
                    return &x.value();
                }
            }).expect("key not in the QVariant")
    }
}
impl IndexMut<QString> for QVariantMap {
    /// Wrapper around [`operator[](int)`][method] operator method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qlist.html#operator-5b-5d
    fn index_mut(&mut self, key: QString) -> &mut Self::Output {
        unsafe {
            &mut *cpp!([self as "QVariantMap*", key as "QString"] -> *mut QVariant as "QVariant*" {
                return &(*self)[key];
            })
        }
    }
}

impl fmt::Debug for QVariantMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.into_iter()).finish()
    }
}

cpp_class!(unsafe struct QVariantMapIteratorInternal as "QVariantMap::iterator");

/// Internal class used to iterate over a [`QVariantMap`]
pub struct QVariantMapIterator<'a> {
    map: &'a QVariantMap,
    iterator: QVariantMapIteratorInternal,
}

impl<'a> QVariantMapIterator<'a> {
    fn key(&self) -> Option<&'a QString> {
        let iterator = &self.iterator;
        cpp!(unsafe [iterator as "const QVariantMap::iterator*"] -> Option<&QString> as "const QString*" {
            return &iterator->key();
        })
    }

    fn value(&self) -> Option<&'a QVariant> {
        let iterator = &self.iterator;
        cpp!(unsafe [iterator as "const QVariantMap::iterator*"] -> Option<&QVariant> as "QVariant*" {
            return &iterator->value();
        })
    }

    fn check_end(&self) -> bool {
        let map = self.map;
        let iterator = &self.iterator;
        cpp!(unsafe [iterator as "const QVariantMap::iterator*", map as "const QVariantMap*"] -> bool as "bool" {
            return (*iterator == map->end());
        })
    }

    fn increment(&mut self) {
        let iterator = &self.iterator;
        cpp!(unsafe [iterator as "QVariantMap::iterator*"] {
            ++(*iterator);
        })
    }
}

impl<'a> Iterator for QVariantMapIterator<'a> {
    type Item = (&'a QString, &'a QVariant);

    fn next(&mut self) -> Option<Self::Item> {
        if self.check_end() {
            return None;
        }

        let key = self.key();
        let value = self.value();

        self.increment();

        match (key, value) {
            (Some(k), Some(v)) => Some((k, v)),
            _ => None,
        }
    }
}

impl<'a> IntoIterator for &'a QVariantMap {
    type Item = (&'a QString, &'a QVariant);
    type IntoIter = QVariantMapIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        let iter = cpp!(unsafe [self as "QVariantMap*"] -> QVariantMapIteratorInternal as "QVariantMap::iterator" {
            return self->begin();
        });
        Self::IntoIter { map: self, iterator: iter }
    }
}

impl<K, V> FromIterator<(K, V)> for QVariantMap
where
    K: Into<QString>,
    V: Into<QVariant>,
{
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut m = QVariantMap::default();
        for i in iter {
            let (k, v) = i;
            m.insert(k.into(), v.into());
        }
        m
    }
}

impl<K, V> From<HashMap<K, V>> for QVariantMap
where
    K: Into<QString>,
    V: Into<QVariant>,
{
    fn from(m: HashMap<K, V>) -> Self {
        m.into_iter().collect()
    }
}

impl<K, V, const N: usize> From<[(K, V); N]> for QVariantMap
where
    K: Into<QString>,
    V: Into<QVariant>,
{
    fn from(m: [(K, V); N]) -> Self {
        let mut temp = QVariantMap::default();
        for (key, val) in m {
            temp.insert(key.into(), val.into());
        }
        temp
    }
}

impl<K, V> From<QVariantMap> for HashMap<K, V>
where
    K: Hash + Eq,
    V: Eq,
    QString: Into<K>,
    QVariant: Into<V>,
{
    fn from(m: QVariantMap) -> Self {
        m.into_iter().map(|(k, v)| (k.clone().into(), v.clone().into())).collect()
    }
}

#[cfg(test)]
mod qvariantmap_tests {
    use super::*;

    #[test]
    fn test_qvariantmap() {
        let mut map = QVariantMap::default();

        let key1 = QString::from("a");
        let val1 = QString::from("abc");

        assert!(map.is_empty());
        map.insert(key1.clone(), val1.clone().into());
        assert_eq!(map.len(), 1);
        assert_eq!(map[key1.clone()].to_qbytearray().to_string(), val1.to_string());

        assert_eq!(map.take(key1.clone()).to_qbytearray().to_string(), val1.to_string());
        assert!(map.is_empty());

        map[key1.clone()] = val1.clone().into();

        let default_value = QVariant::from(10);

        assert_eq!(map[key1.clone()].to_qbytearray().to_string(), val1.to_string());
        assert_eq!(map.value(key1.clone(), default_value.clone()), val1.clone().into());
        assert_eq!(map.value(val1.clone(), default_value.clone()), default_value.clone());

        assert_eq!(map.key(val1.clone().into(), val1.clone()), key1.clone());
        assert_eq!(map.key(key1.clone().into(), val1.clone()), val1.clone());
    }

    #[test]
    #[should_panic(expected = "key not in the QVariant")]
    fn test_index_panic() {
        let map = QVariantMap::default();

        map[QString::from("t")].to_qbytearray().to_string();
    }

    #[test]
    fn test_iter() {
        let hashmap =
            HashMap::from([("Mercury", 0.4), ("Venus", 0.7), ("Earth", 1.0), ("Mars", 1.5)]);
        let map: QVariantMap = hashmap.clone().into();

        assert_eq!(map.len(), hashmap.len());

        for (k, v) in map.into_iter() {
            assert_eq!(hashmap[k.to_string().as_str()].to_string(), v.to_qbytearray().to_string());
        }
    }

    #[test]
    fn test_from() {
        let hashmap1 = HashMap::from([
            ("A".to_string(), QVariant::from(QString::from("abc"))),
            ("B".to_string(), QVariant::from(QString::from("def"))),
        ]);
        let qvariantmap1: QVariantMap = hashmap1.clone().into();
        let hashmap2 = qvariantmap1.clone().into();
        assert_eq!(hashmap1, hashmap2);

        let qvariantmap2 = QVariantMap::from([
            ("A".to_string(), QVariant::from(QString::from("abc"))),
            ("B".to_string(), QVariant::from(QString::from("def"))),
        ]);
        assert_eq!(qvariantmap1, qvariantmap2);
    }
}

cpp_class!(
    /// Wrapper around [`QModelIndex`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qmodelindex.html
    #[derive(PartialEq, Eq)]
    pub unsafe struct QModelIndex as "QModelIndex"
);
impl QModelIndex {
    /// Wrapper around [`internalId()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmodelindex.html#internalId
    pub fn id(&self) -> usize {
        cpp!(unsafe [self as "const QModelIndex*"] -> usize as "uintptr_t" { return self->internalId(); })
    }

    /// Wrapper around [`column()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmodelindex.html#column
    pub fn column(&self) -> i32 {
        cpp!(unsafe [self as "const QModelIndex*"] -> i32 as "int" { return self->column(); })
    }

    /// Wrapper around [`row()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmodelindex.html#row
    pub fn row(&self) -> i32 {
        cpp!(unsafe [self as "const QModelIndex*"] -> i32 as "int" { return self->row(); })
    }

    /// Wrapper around [`isValid()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qmodelindex.html#isValid
    pub fn is_valid(&self) -> bool {
        cpp!(unsafe [self as "const QModelIndex*"] -> bool as "bool" { return self->isValid(); })
    }
}

/// Bindings for [`QRectF`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qrectf.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QRectF {
    pub x: qreal,
    pub y: qreal,
    pub width: qreal,
    pub height: qreal,
}
impl QRectF {
    /// Wrapper around [`contains(const QPointF &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qrectf.html#contains
    pub fn contains(&self, pos: QPointF) -> bool {
        cpp!(unsafe [self as "const QRectF*", pos as "QPointF"] -> bool as "bool" {
            return self->contains(pos);
        })
    }

    /// Same as the [`topLeft`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qrectf.html#topLeft
    pub fn top_left(&self) -> QPointF {
        QPointF { x: self.x, y: self.y }
    }

    /// Same as the [`isValid`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qrectf.html#isValid
    pub fn is_valid(&self) -> bool {
        self.width > 0. && self.height > 0.
    }
}

/// Bindings for [`QPointF`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qpointf.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QPointF {
    pub x: qreal,
    pub y: qreal,
}
impl std::ops::Add for QPointF {
    type Output = QPointF;
    /// Wrapper around [`operator+(const QPointF &, const QPointF &)`][func] function.
    ///
    /// [func]: https://doc.qt.io/qt-5/qpointf.html#operator-2b
    fn add(self, other: QPointF) -> QPointF {
        QPointF { x: self.x + other.x, y: self.y + other.y }
    }
}
impl std::ops::AddAssign for QPointF {
    /// Wrapper around [`operator+=(const QPointF &`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qpointf.html#operator-2b-eq
    fn add_assign(&mut self, other: QPointF) {
        *self = QPointF { x: self.x + other.x, y: self.y + other.y };
    }
}

/// Bindings for [`QSizeF`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qsizef.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QSizeF {
    pub width: qreal,
    pub height: qreal,
}

#[test]
fn test_qpointf_qrectf() {
    let rect = QRectF { x: 200., y: 150., width: 60., height: 75. };
    let pt = QPointF { x: 12., y: 5.5 };
    assert!(!rect.contains(pt));
    assert!(rect.contains(pt + rect.top_left()));
}

/// Bindings for [`QSize`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qsize.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QSize {
    pub width: u32,
    pub height: u32,
}

/// Bindings for [`QPoint`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qpoint.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QPoint {
    pub x: i32,
    pub y: i32,
}

/// Bindings for [`QMargins`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qmargins.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QMargins {
    pub left: i32,
    pub top: i32,
    pub right: i32,
    pub bottom: i32,
}

/// Bindings for [`QImage::Format`][class] enum class.
///
/// [class]: https://doc.qt.io/qt-5/qimage.html#Format-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum ImageFormat {
    Invalid = 0,
    Mono = 1,
    MonoLSB = 2,
    Indexed8 = 3,
    RGB32 = 4,
    ARGB32 = 5,
    ARGB32_Premultiplied = 6,
    RGB16 = 7,
    ARGB8565_Premultiplied = 8,
    RGB666 = 9,
    ARGB6666_Premultiplied = 10,
    RGB555 = 11,
    ARGB8555_Premultiplied = 12,
    RGB888 = 13,
    RGB444 = 14,
    ARGB4444_Premultiplied = 15,
    RGBX8888 = 16,
    RGBA8888 = 17,
    RGBA8888_Premultiplied = 18,
    BGR30 = 19,
    A2BGR30_Premultiplied = 20,
    RGB30 = 21,
    A2RGB30_Premultiplied = 22,
    Alpha8 = 23,
    Grayscale8 = 24,
    Grayscale16 = 28,
    RGBX64 = 25,
    RGBA64 = 26,
    RGBA64_Premultiplied = 27,
    BGR888 = 29,
}
cpp_class!(
    /// Wrapper around [`QImage`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qimage.html
    #[derive(Default, Clone, PartialEq)]
    pub unsafe struct QImage as "QImage"
);
impl QImage {
    /// Wrapper around [`QImage(const QString &fileName, const char *format = nullptr)`][ctor] constructor.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qimage.html#QImage-8
    pub fn load_from_file(filename: QString) -> Self {
        cpp!(unsafe [filename as "QString"] -> QImage as "QImage" {
            return QImage(filename);
        })
    }

    /// Wrapper around [`QImage(const QSize &, QImage::Format)`][ctor] constructor.
    ///
    /// [ctor]: https://doc.qt.io/qt-5/qimage.html#QImage-1
    pub fn new(size: QSize, format: ImageFormat) -> Self {
        cpp!(unsafe [size as "QSize", format as "QImage::Format" ] -> QImage as "QImage" {
            return QImage(size, format);
        })
    }

    /// Wrapper around [`size()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qimage.html#size
    pub fn size(&self) -> QSize {
        cpp!(unsafe [self as "const QImage*"] -> QSize as "QSize" { return self->size(); })
    }

    /// Wrapper around [`format()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qimage.html#format
    pub fn format(&self) -> ImageFormat {
        cpp!(unsafe [self as "const QImage*"] -> ImageFormat as "QImage::Format" { return self->format(); })
    }

    /// Wrapper around [`fill(const QColor &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qimage.html#fill-1
    pub fn fill(&mut self, color: QColor) {
        cpp!(unsafe [self as "QImage*", color as "QColor"] { self->fill(color); })
    }

    /// Wrapper around [`setPixelColor(const QPoint &, const QColor &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qimage.html#setPixelColor
    pub fn set_pixel_color(&mut self, x: u32, y: u32, color: QColor) {
        cpp!(unsafe [self as "QImage*", x as "int", y as "int", color as "QColor"] {
            self->setPixelColor(x, y, color);
        })
    }

    /// Wrapper around [`pixelColor(const QPoint &)`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qimage.html#pixelColor
    pub fn get_pixel_color(&self, x: u32, y: u32) -> QColor {
        cpp!(unsafe [self as "const QImage*", x as "int", y as "int"] -> QColor as "QColor" {
            return self->pixelColor(x, y);
        })
    }
}

cpp_class!(
    /// Wrapper around [`QPixmap`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qpixmap.html
    pub unsafe struct QPixmap as "QPixmap"
);

impl QPixmap {
    /// Wrapper around [`size()`][method] method.
    ///
    /// [method]: https://doc.qt.io/qt-5/qpixmap.html#size
    pub fn size(&self) -> QSize {
        cpp!(unsafe [self as "const QPixmap*"] -> QSize as "QSize" { return self->size(); })
    }
}

impl From<QPixmap> for QImage {
    fn from(pixmap: QPixmap) -> Self {
        cpp!(unsafe [pixmap as "QPixmap"] -> QImage as "QImage" { return pixmap.toImage(); })
    }
}

impl From<QImage> for QPixmap {
    fn from(image: QImage) -> Self {
        cpp!(unsafe [image as "QImage"] -> QPixmap as "QPixmap" { return QPixmap::fromImage(image); })
    }
}

/// Bindings for [`Qt::PenStyle`][enum] enum.
///
/// [enum]: https://doc.qt.io/qt-5/qt.html#PenStyle-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum PenStyle {
    NoPen = 0,
    SolidLine = 1,
    DashLine = 2,
    DotLine = 3,
    DashDotLine = 4,
    DashDotDotLine = 5,
    CustomDashLine = 6,
}
cpp_class!(
    /// Wrapper around [`QPen`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qpen.html
    #[derive(Default)]
    pub unsafe struct QPen as "QPen"
);

impl QPen {
    pub fn from_color(color: QColor) -> Self {
        cpp!(unsafe [color as "QColor"] -> QPen as "QPen" { return QPen(color); })
    }
    pub fn from_style(style: PenStyle) -> Self {
        cpp!(unsafe [style as "Qt::PenStyle"] -> QPen as "QPen" { return QPen(style); })
    }
    pub fn set_color(&mut self, color: QColor) {
        cpp!(unsafe [self as "QPen*", color as "QColor"] { return self->setColor(color); });
    }
    pub fn set_style(&mut self, style: PenStyle) {
        cpp!(unsafe [self as "QPen*", style as "Qt::PenStyle"] { return self->setStyle(style); });
    }
    pub fn set_width(&mut self, width: i32) {
        cpp!(unsafe [self as "QPen*", width as "int"] { return self->setWidth(width); });
    }
    pub fn set_width_f(&mut self, width: qreal) {
        cpp!(unsafe [self as "QPen*", width as "qreal"] { return self->setWidthF(width); });
    }

    //    QBrush	brush() const
    //    Qt::PenCapStyle	capStyle() const
    //    QColor	color() const
    //    qreal	dashOffset() const
    //    QVector<qreal>	dashPattern() const
    //    bool	isCosmetic() const
    //    bool	isSolid() const
    //    Qt::PenJoinStyle	joinStyle() const
    //    qreal	miterLimit() const
    //    void	setBrush(const QBrush &brush)
    //    void	setCapStyle(Qt::PenCapStyle style)
    //    void	setCosmetic(bool cosmetic)
    //    void	setDashOffset(qreal offset)
    //    void	setDashPattern(const QVector<qreal> &pattern)
    //    void	setJoinStyle(Qt::PenJoinStyle style)
    //    void	setMiterLimit(qreal limit)
    //    Qt::PenStyle	style() const
    //    void	swap(QPen &other)
    //    int	width() const
    //    qreal	widthF() const
}

/// Bindings for [`QStandardPaths::StandardLocation`][enum] enum.
///
/// [enum]: https://doc.qt.io/qt-5/qstandardpaths.html#StandardLocation-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum QStandardPathLocation {
    DesktopLocation = 0,
    DocumentsLocation = 1,
    FontsLocation = 2,
    ApplicationsLocation = 3,
    MusicLocation = 4,
    MoviesLocation = 5,
    PicturesLocation = 6,
    TempLocation = 7,
    HomeLocation = 8,
    AppLocalDataLocation = 9,
    CacheLocation = 10,
    GenericDataLocation = 11,
    RuntimeLocation = 12,
    ConfigLocation = 13,
    DownloadLocation = 14,
    GenericCacheLocation = 15,
    GenericConfigLocation = 16,
    AppDataLocation = 17,
    AppConfigLocation = 18,
}

/// Bindings for [`Qt::BrushStyle`][enum] enum.
///
/// [enum]: https://doc.qt.io/qt-5/qt.html#BrushStyle-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum BrushStyle {
    NoBrush = 0,
    SolidPattern = 1,
    Dense1Pattern = 2,
    Dense2Pattern = 3,
    Dense3Pattern = 4,
    Dense4Pattern = 5,
    Dense5Pattern = 6,
    Dense6Pattern = 7,
    Dense7Pattern = 8,
    HorPattern = 9,
    VerPattern = 10,
    CrossPattern = 11,
    BDiagPattern = 12,
    FDiagPattern = 13,
    DiagCrossPattern = 14,
    LinearGradientPattern = 15,
    ConicalGradientPattern = 17,
    RadialGradientPattern = 16,
    TexturePattern = 24,
}
cpp_class!(
    /// Wrapper around [`QBrush`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qbrush.html
    #[derive(Default)]
    pub unsafe struct QBrush as "QBrush "
);
impl QBrush {
    pub fn from_color(color: QColor) -> Self {
        cpp!(unsafe [color as "QColor"] -> QBrush as "QBrush" { return QBrush(color); })
    }
    pub fn from_style(style: BrushStyle) -> Self {
        cpp!(unsafe [style as "Qt::BrushStyle"] -> QBrush as "QBrush" { return QBrush(style); })
    }
    pub fn set_color(&mut self, color: QColor) {
        cpp!(unsafe [self as "QBrush*", color as "QColor"] { return self->setColor(color); });
    }
    pub fn set_style(&mut self, style: BrushStyle) {
        cpp!(unsafe [self as "QBrush*", style as "Qt::BrushStyle"] { return self->setStyle(style); });
    }
}

/// Bindings for [`QLineF`][class] class.
///
/// [class]: https://doc.qt.io/qt-5/qlinef.html
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
pub struct QLineF {
    pub pt1: QPointF,
    pub pt2: QPointF,
}

cpp_class!(
    /// Wrapper around [`QPainter`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qpainter.html
    pub unsafe struct QPainter as "QPainter "
);
impl QPainter {
    pub fn draw_arc(&mut self, rectangle: QRectF, start_angle: i32, span_angle: i32) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", start_angle as "int", span_angle as "int"] {
            self->drawArc(rectangle, start_angle, span_angle);
        });
    }
    pub fn draw_chord(&mut self, rectangle: QRectF, start_angle: i32, span_angle: i32) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", start_angle as "int", span_angle as "int"] {
            self->drawChord(rectangle, start_angle, span_angle);
        });
    }

    pub fn draw_convex_polygon(&mut self, points: &[QPointF]) {
        let points_ptr = points.as_ptr();
        let points_count = points.len() as u64;
        cpp!(unsafe [self as "QPainter *", points_ptr as "QPointF*", points_count as "uint64_t"] {
            self->drawConvexPolygon(points_ptr, points_count);
        });
    }

    pub fn draw_ellipse(&mut self, rectangle: QRectF) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF"] {
            self->drawEllipse(rectangle);
        });
    }
    pub fn draw_ellipse_with_center(&mut self, center: QPointF, rx: qreal, ry: qreal) {
        cpp!(unsafe [self as "QPainter *", center as "QPointF", rx as "qreal", ry as "qreal"] {
            self->drawEllipse(center, rx, ry);
        });
    }

    pub fn draw_image_fit_rect(&mut self, rectangle: QRectF, image: QImage) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", image as "QImage"] {
            self->drawImage(rectangle, image);
        });
    }
    pub fn draw_image_at_point(&mut self, point: QPointF, image: QImage) {
        cpp!(unsafe [self as "QPainter *", point as "QPointF", image as "QImage"] {
            self->drawImage(point, image);
        });
    }
    pub fn draw_image_fit_rect_with_source(
        &mut self,
        rectangle: QRectF,
        image: QImage,
        source_rect: QRectF,
    ) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", image as "QImage", source_rect as "QRectF"] {
            self->drawImage(rectangle, image, source_rect);
        });
    }
    pub fn draw_image_at_point_with_source(
        &mut self,
        point: QPointF,
        image: QImage,
        source_rect: QRectF,
    ) {
        cpp!(unsafe [self as "QPainter *", point as "QPointF", image as "QImage", source_rect as "QRectF"] {
            self->drawImage(point, image, source_rect);
        });
    }

    pub fn draw_line(&mut self, line: QLineF) {
        cpp!(unsafe [self as "QPainter *", line as "QLineF"] {
            self->drawLine(line);
        });
    }
    pub fn draw_lines(&mut self, lines: &[QLineF]) {
        let lines_ptr = lines.as_ptr();
        let lines_count = lines.len() as u64;
        cpp!(unsafe [self as "QPainter *", lines_ptr as "QLineF*", lines_count as "uint64_t"] {
            self->drawLines(lines_ptr, lines_count);
        });
    }
    pub fn draw_lines_from_points(&mut self, point_pairs: &[QPointF]) {
        let point_pairs_ptr = point_pairs.as_ptr();
        let point_pairs_count = point_pairs.len() as u64;
        cpp!(unsafe [self as "QPainter *", point_pairs_ptr as "QLineF*", point_pairs_count as "uint64_t"] {
            self->drawLines(point_pairs_ptr, point_pairs_count);
        });
    }

    pub fn draw_pie(&mut self, rectangle: QRectF, start_angle: i32, span_angle: i32) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", start_angle as "int", span_angle as "int"] {
            self->drawPie(rectangle, start_angle, span_angle);
        });
    }

    pub fn draw_point(&mut self, point: QPointF) {
        cpp!(unsafe [self as "QPainter *", point as "QPointF"] {
            self->drawPoint(point);
        });
    }
    pub fn draw_points(&mut self, points: &[QPointF]) {
        let points_ptr = points.as_ptr();
        let points_count = points.len() as u64;
        cpp!(unsafe [self as "QPainter *", points_ptr as "QPointF*", points_count as "uint64_t"] {
            self->drawPoints(points_ptr, points_count);
        });
    }

    pub fn draw_polygon(&mut self, points: &[QPointF]) {
        let points_ptr = points.as_ptr();
        let points_count = points.len() as u64;
        cpp!(unsafe [self as "QPainter *", points_ptr as "QPointF*", points_count as "uint64_t"] {
            self->drawPolygon(points_ptr, points_count);
        });
    }
    pub fn draw_polyline(&mut self, points: &[QPointF]) {
        let points_ptr = points.as_ptr();
        let points_count = points.len() as u64;
        cpp!(unsafe [self as "QPainter *", points_ptr as "QPointF*", points_count as "uint64_t"] {
            self->drawPolyline(points_ptr, points_count);
        });
    }

    pub fn draw_rect(&mut self, rectangle: QRectF) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF"] {
            self->drawRect(rectangle);
        });
    }
    pub fn draw_rects(&mut self, rects: &[QRectF]) {
        let rects_ptr = rects.as_ptr();
        let rects_count = rects.len() as u64;
        cpp!(unsafe [self as "QPainter *", rects_ptr as "QRectF*", rects_count as "uint64_t"] {
            self->drawRects(rects_ptr, rects_count);
        });
    }
    pub fn draw_rounded_rect(&mut self, rect: QRectF, x_radius: qreal, y_radius: qreal) {
        cpp!(unsafe [self as "QPainter *", rect as "QRectF", x_radius as "qreal", y_radius as "qreal"] {
            self->drawRoundedRect(rect, x_radius, y_radius);
        });
    }

    pub fn draw_text(&mut self, position: QPointF, text: QString) {
        cpp!(unsafe [self as "QPainter *", position as "QPointF", text as "QString"] {
            self->drawText(position, text);
        });
    }
    pub fn draw_text_in_rect(&mut self, rectangle: QRectF, flags: u32, text: QString) -> QRectF {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", flags as "uint32_t", text as "QString"] -> QRectF as "QRectF" {
            QRectF boundingRect;
            self->drawText(rectangle, flags, text, &boundingRect);
            return boundingRect;
        })
    }

    pub fn erase_rect(&mut self, rectangle: QRectF) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF"] {
            self->eraseRect(rectangle);
        });
    }

    pub fn fill_rect(&mut self, rectangle: QRectF, brush: QBrush) {
        cpp!(unsafe [self as "QPainter *", rectangle as "QRectF", brush as "QBrush"] {
            self->fillRect(rectangle, brush);
        });
    }

    pub fn reset_transform(&mut self) {
        cpp!(unsafe [self as "QPainter *"] {
            self->resetTransform();
        });
    }

    pub fn restore(&mut self) {
        cpp!(unsafe [self as "QPainter *"] {
            self->restore();
        });
    }

    pub fn rotate(&mut self, angle: qreal) {
        cpp!(unsafe [self as "QPainter *", angle as "qreal"] {
            self->rotate(angle);
        });
    }

    pub fn save(&mut self) {
        cpp!(unsafe [self as "QPainter *"] {
            self->save();
        });
    }

    pub fn scale(&mut self, sx: qreal, sy: qreal) {
        cpp!(unsafe [self as "QPainter *", sx as "qreal", sy as "qreal"] {
            self->scale(sx, sy);
        });
    }

    pub fn set_background(&mut self, brush: QBrush) {
        cpp!(unsafe [self as "QPainter *", brush as "QBrush"] {
            self->setBackground(brush);
        });
    }

    pub fn set_brush(&mut self, brush: QBrush) {
        cpp!(unsafe [self as "QPainter *", brush as "QBrush"] {
            self->setBrush(brush);
        });
    }

    pub fn set_opacity(&mut self, opacity: qreal) {
        cpp!(unsafe [self as "QPainter *", opacity as "qreal"] {
            self->setOpacity(opacity);
        });
    }

    pub fn set_pen(&mut self, pen: QPen) {
        cpp!(unsafe [self as "QPainter *", pen as "QPen"] {
            self->setPen(pen);
        });
    }

    pub fn translate(&mut self, offset: QPointF) {
        cpp!(unsafe [self as "QPainter *", offset as "QPointF"] {
            self->translate(offset);
        });
    }
    pub fn set_render_hint(&mut self, hint: QPainterRenderHint, on: bool) {
        cpp!(unsafe [self as "QPainter *", hint as "QPainter::RenderHint", on as "bool"] {
            self->setRenderHint(hint, on);
        });
    }

    // void	setBackgroundMode(Qt::BGMode mode)
    // void	setCompositionMode(QPainter::CompositionMode mode)
    // void	setFont(const QFont &font)
}

/// Bindings for [`QPainter::RenderHint`][enum] enum.
///
/// [enum]: https://doc.qt.io/qt-5/qpainter.html#RenderHint-enum
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
#[allow(non_camel_case_types)]
pub enum QPainterRenderHint {
    Antialiasing = 0x01,
    TextAntialiasing = 0x02,
    SmoothPixmapTransform = 0x04,
    HighQualityAntialiasing = 0x08,
    NonCosmeticDefaultPen = 0x10,
    Qt4CompatiblePainting = 0x20,
    LosslessImageRendering = 0x40,
}

cpp! {{
    #include <QtCore/QJsonDocument>
    #include <QtCore/QJsonValue>
    #include <QtCore/QJsonObject>
    #include <QtCore/QJsonArray>
}}
cpp_class!(
    /// Wrapper around [`QJsonValue`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qjsonvalue.html
    #[derive(Default, PartialEq, Eq, Clone)]
    pub unsafe struct QJsonValue as "QJsonValue"
);

impl Into<QVariant> for QJsonValue {
    fn into(self) -> QVariant {
        cpp!(unsafe [self as "QJsonValue"] -> QVariant as "QVariant" { return self.toVariant(); })
    }
}
impl From<QVariant> for QJsonValue {
    fn from(v: QVariant) -> QJsonValue {
        cpp!(unsafe [v as "QVariant"] -> QJsonValue as "QJsonValue" { return QJsonValue::fromVariant(v); })
    }
}

impl Into<QJsonObject> for QJsonValue {
    fn into(self) -> QJsonObject {
        cpp!(unsafe [self as "QJsonValue"] -> QJsonObject as "QJsonObject" { return self.toObject(); })
    }
}
impl From<QJsonObject> for QJsonValue {
    fn from(v: QJsonObject) -> QJsonValue {
        cpp!(unsafe [v as "QJsonObject"] -> QJsonValue as "QJsonValue" { return QJsonValue(v); })
    }
}
impl Into<QJsonArray> for QJsonValue {
    fn into(self) -> QJsonArray {
        cpp!(unsafe [self as "QJsonValue"] -> QJsonArray as "QJsonArray" { return self.toArray(); })
    }
}
impl From<QJsonArray> for QJsonValue {
    fn from(v: QJsonArray) -> QJsonValue {
        cpp!(unsafe [v as "QJsonArray"] -> QJsonValue as "QJsonValue" { return QJsonValue(v); })
    }
}

impl Into<QString> for QJsonValue {
    fn into(self) -> QString {
        cpp!(unsafe [self as "QJsonValue"] -> QString as "QString" { return self.toString(); })
    }
}
impl From<QString> for QJsonValue {
    fn from(v: QString) -> QJsonValue {
        cpp!(unsafe [v as "QString"] -> QJsonValue as "QJsonValue" { return QJsonValue(v); })
    }
}

impl Into<bool> for QJsonValue {
    fn into(self) -> bool {
        cpp!(unsafe [self as "QJsonValue"] -> bool as "bool" { return self.toBool(); })
    }
}
impl From<bool> for QJsonValue {
    fn from(v: bool) -> QJsonValue {
        cpp!(unsafe [v as "bool"] -> QJsonValue as "QJsonValue" { return QJsonValue(v); })
    }
}

impl Into<f64> for QJsonValue {
    fn into(self) -> f64 {
        cpp!(unsafe [self as "QJsonValue"] -> f64 as "double" { return self.toDouble(); })
    }
}
impl From<f64> for QJsonValue {
    fn from(v: f64) -> QJsonValue {
        cpp!(unsafe [v as "double"] -> QJsonValue as "QJsonValue" { return QJsonValue(v); })
    }
}

#[test]
fn test_qjsonvalue() {
    let test_str = QJsonValue::from(QVariant::from(QString::from("test")));
    let test_str2 = QJsonValue::from(QString::from("test"));
    assert!(test_str == test_str2);
    assert_eq!(<QJsonValue as Into<QString>>::into(test_str), QString::from("test"));

    let test_bool = QJsonValue::from(true);
    let test_bool_variant: QVariant = QJsonValue::from(true).into();
    let test_bool_variant2 = QVariant::from(true);
    assert!(test_bool_variant == test_bool_variant2);
    assert_eq!(<QJsonValue as Into<bool>>::into(test_bool), true);

    let test_f64 = QJsonValue::from(1.2345);
    let test_f64_variant: QVariant = QJsonValue::from(1.2345).into();
    let test_f64_variant2 = QVariant::from(1.2345);
    assert!(test_f64_variant == test_f64_variant2);
    assert_eq!(<QJsonValue as Into<f64>>::into(test_f64), 1.2345);

    let values = QJsonArray::from(vec![
        QJsonValue::from(QString::from("test")),
        QJsonValue::from(true),
        QJsonValue::from(false),
        QJsonValue::from(1.2345),
        QJsonValue::from(456.0),
    ]);

    assert_eq!(values.to_json().to_string(), "[\"test\",true,false,1.2345,456]");
}

cpp_class!(
    /// Wrapper around [`QJsonObject`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qjsonobject.html
    #[derive(Default, PartialEq, Eq, Clone)]
    pub unsafe struct QJsonObject as "QJsonObject"
);

impl QJsonObject {
    pub fn to_json(&self) -> QByteArray {
        cpp!(unsafe [self as "QJsonObject*"] -> QByteArray as "QByteArray" { return QJsonDocument(*self).toJson(QJsonDocument::Compact); })
    }
    pub fn to_json_pretty(&self) -> QByteArray {
        cpp!(unsafe [self as "QJsonObject*"] -> QByteArray as "QByteArray" { return QJsonDocument(*self).toJson(QJsonDocument::Indented); })
    }
    pub fn insert(&mut self, key: &str, value: QJsonValue) {
        let len = key.len();
        let ptr = key.as_ptr();
        cpp!(unsafe [self as "QJsonObject*", len as "size_t", ptr as "char*", value as "QJsonValue"] { self->insert(QString::fromUtf8(ptr, len), std::move(value)); })
    }
    pub fn value(&self, key: &str) -> QJsonValue {
        let len = key.len();
        let ptr = key.as_ptr();
        cpp!(unsafe [self as "QJsonObject*", len as "size_t", ptr as "char*"] -> QJsonValue as "QJsonValue" { return self->value(QString::fromUtf8(ptr, len)); })
    }
    pub fn take(&mut self, key: &str) -> QJsonValue {
        let len = key.len();
        let ptr = key.as_ptr();
        cpp!(unsafe [self as "QJsonObject*", len as "size_t", ptr as "char*"] -> QJsonValue as "QJsonValue" { return self->take(QString::fromUtf8(ptr, len)); })
    }
    pub fn remove(&mut self, key: &str) {
        let len = key.len();
        let ptr = key.as_ptr();
        cpp!(unsafe [self as "QJsonObject*", len as "size_t", ptr as "char*"] { return self->remove(QString::fromUtf8(ptr, len)); })
    }
    pub fn len(&self) -> usize {
        cpp!(unsafe [self as "QJsonObject*"] -> usize as "size_t" { return self->size(); })
    }
    pub fn is_empty(&self) -> bool {
        cpp!(unsafe [self as "QJsonObject*"] -> bool as "bool" { return self->isEmpty(); })
    }
    pub fn contains(&self, key: &str) -> bool {
        let len = key.len();
        let ptr = key.as_ptr();
        cpp!(unsafe [self as "QJsonObject*", len as "size_t", ptr as "char*"] -> bool as "bool" { return self->contains(QString::fromUtf8(ptr, len)); })
    }
    pub fn keys(&self) -> Vec<String> {
        let len = self.len();
        let mut vec = Vec::with_capacity(len);

        let keys = cpp!(unsafe [self as "QJsonObject*"] -> QStringList as "QStringList" { return self->keys(); });

        for i in 0..len {
            vec.push(keys[i].to_string());
        }
        vec
    }
}

impl From<HashMap<String, String>> for QJsonObject {
    fn from(v: HashMap<String, String>) -> QJsonObject {
        let keys: Vec<QString> = v.keys().cloned().map(QString::from).collect();
        let values: Vec<QString> = v.values().cloned().map(QString::from).collect();
        let keys_ptr = keys.as_ptr();
        let values_ptr = values.as_ptr();
        let len = keys.len();
        cpp!(unsafe [keys_ptr as "const QString*", values_ptr as "const QString*", len as "size_t"] -> QJsonObject as "QJsonObject" {
            QJsonObject obj;
            for (size_t i = 0; i < len; ++i) {
                obj.insert(keys_ptr[i], values_ptr[i]);
            }
            return obj;
        })
    }
}
impl From<HashMap<String, QJsonValue>> for QJsonObject {
    fn from(v: HashMap<String, QJsonValue>) -> QJsonObject {
        let keys: Vec<QString> = v.keys().cloned().map(QString::from).collect();
        let values: Vec<QJsonValue> = v.values().cloned().collect();
        let keys_ptr = keys.as_ptr();
        let values_ptr = values.as_ptr();
        let len = keys.len();
        cpp!(unsafe [keys_ptr as "const QString*", values_ptr as "const QJsonValue*", len as "size_t"] -> QJsonObject as "QJsonObject" {
            QJsonObject obj;
            for (size_t i = 0; i < len; ++i) {
                obj.insert(keys_ptr[i], values_ptr[i]);
            }
            return obj;
        })
    }
}

cpp! {{ #include <QtCore/QDebug> }}

#[test]
fn test_qjsonobject() {
    let mut hashmap = HashMap::new();
    hashmap.insert("key".to_owned(), "value".to_owned());
    hashmap.insert("test".to_owned(), "hello".to_owned());
    let object = QJsonObject::from(hashmap);
    assert_eq!(object.to_json().to_string(), "{\"key\":\"value\",\"test\":\"hello\"}");

    let array = QJsonArray::from(vec![
        QJsonValue::from(QString::from("test")),
        QJsonValue::from(true),
        QJsonValue::from(false),
        QJsonValue::from(1.2345),
        QJsonValue::from(456.0),
    ]);

    let mut valuemap = HashMap::new();
    valuemap.insert("1_string".to_owned(), QJsonValue::from(QString::from("test")));
    valuemap.insert("2_bool".to_owned(), QJsonValue::from(true));
    valuemap.insert("3_f64".to_owned(), QJsonValue::from(1.2345));
    valuemap.insert("4_int".to_owned(), QJsonValue::from(456.0));
    valuemap.insert("5_array".to_owned(), QJsonValue::from(array));
    valuemap.insert("6_object".to_owned(), QJsonValue::from(object));
    let object = QJsonObject::from(valuemap);
    assert_eq!(object.to_json().to_string(), "{\"1_string\":\"test\",\"2_bool\":true,\"3_f64\":1.2345,\"4_int\":456,\"5_array\":[\"test\",true,false,1.2345,456],\"6_object\":{\"key\":\"value\",\"test\":\"hello\"}}");

    let at_f64: f64 = object.value("3_f64").into();
    assert_eq!(at_f64, 1.2345);

    let at_string = object.value("1_string");
    assert_eq!(<QJsonValue as Into<QString>>::into(at_string).to_string(), "test");

    let mut object = QJsonObject::default();
    object.insert("key", QJsonValue::from(QString::from("value")));
    object.insert("test", QJsonValue::from(QString::from("hello")));
    assert_eq!(object.to_json().to_string(), "{\"key\":\"value\",\"test\":\"hello\"}");

    assert_eq!(object.keys(), vec!["key".to_owned(), "test".to_owned()]);
}

#[test]
fn test_qjsonobject_utf8() {
    let emoji = String::from("🦀");
    let expected = String::from("{\"🦀\":1}");

    let mut qmap: QJsonObject = QJsonObject::default();
    qmap.insert(&emoji, QVariant::from(1).into());

    let actual = qmap.to_json();
    let actual = actual.to_str().unwrap();

    assert_eq!(actual, expected);
}

cpp_class!(
    /// Wrapper around [`QJsonArray`][class] class.
    ///
    /// [class]: https://doc.qt.io/qt-5/qjsonarray.html
    #[derive(Default, PartialEq, Eq, Clone)]
    pub unsafe struct QJsonArray as "QJsonArray"
);

impl QJsonArray {
    pub fn to_json(&self) -> QByteArray {
        cpp!(unsafe [self as "QJsonArray*"] -> QByteArray as "QByteArray" { return QJsonDocument(*self).toJson(QJsonDocument::Compact); })
    }
    pub fn to_json_pretty(&self) -> QByteArray {
        cpp!(unsafe [self as "QJsonArray*"] -> QByteArray as "QByteArray" { return QJsonDocument(*self).toJson(QJsonDocument::Indented); })
    }
    pub fn push(&mut self, value: QJsonValue) {
        cpp!(unsafe [self as "QJsonArray*", value as "QJsonValue"] { self->append(std::move(value)); })
    }
    pub fn insert(&mut self, index: usize, element: QJsonValue) {
        cpp!(unsafe [self as "QJsonArray*", index as "size_t", element as "QJsonValue"] { self->insert(index, std::move(element)); })
    }
    pub fn at(&self, index: usize) -> QJsonValue {
        cpp!(unsafe [self as "QJsonArray*", index as "size_t"] -> QJsonValue as "QJsonValue" { return self->at(index); })
    }
    pub fn take_at(&mut self, index: usize) -> QJsonValue {
        cpp!(unsafe [self as "QJsonArray*", index as "size_t"] -> QJsonValue as "QJsonValue" { return self->takeAt(index); })
    }
    pub fn remove_at(&mut self, index: usize) {
        cpp!(unsafe [self as "QJsonArray*", index as "size_t"] { return self->removeAt(index); })
    }
    pub fn len(&self) -> usize {
        cpp!(unsafe [self as "QJsonArray*"] -> usize as "size_t" { return self->size(); })
    }
    pub fn is_empty(&self) -> bool {
        cpp!(unsafe [self as "QJsonArray*"] -> bool as "bool" { return self->isEmpty(); })
    }
}

impl From<Vec<QJsonValue>> for QJsonArray {
    fn from(v: Vec<QJsonValue>) -> QJsonArray {
        let ptr = v.as_ptr();
        let len = v.len();
        cpp!(unsafe [ptr as "const QJsonValue*", len as "size_t"] -> QJsonArray as "QJsonArray" {
            QJsonArray arr;
            for (size_t i = 0; i < len; ++i) {
                arr.append(ptr[i]);
            }
            return arr;
        })
    }
}

#[test]
fn test_qjsonarray() {
    let mut array = QJsonArray::default();
    array.push(QJsonValue::from(QString::from("test")));
    array.push(QJsonValue::from(true));
    array.push(QJsonValue::from(false));
    array.push(QJsonValue::from(1.2345));
    assert_eq!(array.to_json().to_string(), "[\"test\",true,false,1.2345]");

    let mut vec = Vec::new();
    vec.push(QJsonValue::from(QString::from("test")));
    vec.push(QJsonValue::from(true));
    vec.push(QJsonValue::from(false));
    vec.push(QJsonValue::from(1.2345));
    assert!(QJsonArray::from(vec) == array);

    assert_eq!(array.len(), 4);

    assert_eq!(<QJsonValue as Into<QString>>::into(array.at(0)).to_string(), "test");
    assert!(array.at(3) == QJsonValue::from(1.2345));
}