-
Notifications
You must be signed in to change notification settings - Fork 88
/
lib.rs
1845 lines (1658 loc) · 61.8 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (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, 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)]