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
use translate::*;
use types::{self, StaticType};
use wrapper::{UnsafeFrom, Wrapper};
use ffi as glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
use std::iter;
use std::ops;
use std::marker::PhantomData;
use Value;
use value::{ToValue, SetValue};
use Type;
use BoolError;
use Closure;
use SignalHandlerId;
use get_thread_id;
pub trait Cast: IsA<Object> {
#[inline]
fn upcast<T>(self) -> T
where T: StaticType + UnsafeFrom<ObjectRef> + Wrapper,
Self: IsA<T> {
unsafe { T::from(self.into()) }
}
#[inline]
fn upcast_ref<T>(&self) -> &T
where T: StaticType + UnsafeFrom<ObjectRef> + Wrapper,
Self: IsA<T> {
unsafe {
mem::transmute(self)
}
}
#[inline]
fn downcast<T>(self) -> Result<T, Self>
where Self: Sized + Downcast<T> {
Downcast::downcast(self)
}
#[inline]
fn downcast_ref<T>(&self) -> Option<&T>
where Self: Sized + Downcast<T> {
Downcast::downcast_ref(self)
}
fn is<T>(&self) -> bool
where T: StaticType {
unsafe {
types::instance_of::<T>(self.to_glib_none().0 as *const _)
}
}
#[inline]
fn dynamic_cast<T>(self) -> Result<T, Self>
where T: StaticType + UnsafeFrom<ObjectRef> + Wrapper {
if !self.is::<T>() {
Err(self)
} else {
Ok(unsafe { T::from(self.into()) })
}
}
#[inline]
fn dynamic_cast_ref<T>(&self) -> Option<&T>
where T: StaticType + UnsafeFrom<ObjectRef> + Wrapper {
if !self.is::<T>() {
None
} else {
Some(unsafe { mem::transmute(self) })
}
}
}
impl<T: IsA<Object>> Cast for T { }
pub unsafe trait IsA<T: StaticType + UnsafeFrom<ObjectRef> + Wrapper>: StaticType + Wrapper +
Into<ObjectRef> + UnsafeFrom<ObjectRef> +
for<'a> ToGlibPtr<'a, *mut <T as Wrapper>::GlibType> { }
unsafe impl<T> IsA<T> for T
where T: StaticType + Wrapper + Into<ObjectRef> + UnsafeFrom<ObjectRef> +
for<'a> ToGlibPtr<'a, *mut <T as Wrapper>::GlibType> { }
pub trait Downcast<T> {
fn can_downcast(&self) -> bool;
fn downcast(self) -> Result<T, Self> where Self: Sized;
fn downcast_ref(&self) -> Option<&T>;
unsafe fn downcast_unchecked(self) -> T;
unsafe fn downcast_ref_unchecked(&self) -> &T;
}
impl<Super: IsA<Super>, Sub: IsA<Super>> Downcast<Sub> for Super {
#[inline]
fn can_downcast(&self) -> bool {
unsafe {
types::instance_of::<Sub>(self.to_glib_none().0 as *const _)
}
}
#[inline]
fn downcast(self) -> Result<Sub, Super> {
unsafe {
if !types::instance_of::<Sub>(self.to_glib_none().0 as *const _) {
return Err(self);
}
Ok(Sub::from(self.into()))
}
}
#[inline]
fn downcast_ref(&self) -> Option<&Sub> {
unsafe {
if !types::instance_of::<Sub>(self.to_glib_none().0 as *const _) {
return None;
}
Some(mem::transmute(self))
}
}
#[inline]
unsafe fn downcast_unchecked(self) -> Sub {
debug_assert!(types::instance_of::<Sub>(self.to_glib_none().0 as *const _));
Sub::from(self.into())
}
#[inline]
unsafe fn downcast_ref_unchecked(&self) -> &Sub {
debug_assert!(types::instance_of::<Sub>(self.to_glib_none().0 as *const _));
mem::transmute(self)
}
}
#[doc(hidden)]
pub use gobject_ffi::GObject;
#[doc(hidden)]
pub use gobject_ffi::GObjectClass;
glib_wrapper! {
#[doc(hidden)]
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq, Hash)]
pub struct ObjectRef(Shared<GObject>);
match fn {
ref => |ptr| gobject_ffi::g_object_ref_sink(ptr),
unref => |ptr| gobject_ffi::g_object_unref(ptr),
}
}
#[macro_export]
macro_rules! glib_object_wrapper {
([$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, @get_type $get_type_expr:expr) => {
$(#[$attr])*
#[derive(Clone, Hash, Ord)]
pub struct $name($crate::object::ObjectRef, ::std::marker::PhantomData<$ffi_name>);
#[doc(hidden)]
impl Into<$crate::object::ObjectRef> for $name {
fn into(self) -> $crate::object::ObjectRef {
self.0
}
}
#[doc(hidden)]
impl $crate::wrapper::UnsafeFrom<$crate::object::ObjectRef> for $name {
unsafe fn from(t: $crate::object::ObjectRef) -> Self {
$name(t, ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::GlibPtrDefault for $name {
type GlibType = *mut $ffi_name;
}
#[doc(hidden)]
impl $crate::wrapper::Wrapper for $name {
type GlibType = $ffi_name;
type GlibClassType = $ffi_class_name;
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *const $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *const $ffi_name, Self> {
let stash = self.0.to_glib_none();
$crate::translate::Stash(stash.0 as *const _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *const $ffi_name {
self.0.to_glib_full() as *const _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *mut $ffi_name> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *mut $ffi_name, Self> {
let stash = self.0.to_glib_none();
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $ffi_name {
self.0.to_glib_full() as *mut _
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *mut *mut $ffi_name> for $name {
type Storage = (Vec<Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(ptr::null_mut() as *mut $ffi_name);
(v_ptr.as_ptr() as *mut *mut $ffi_name, (v, Some(v_ptr)))
}
fn to_glib_container_from_slice(t: &'a [$name]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let v_ptr = unsafe {
let v_ptr = glib_ffi::g_malloc0(mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in v.iter().enumerate() {
ptr::write(v_ptr.offset(i as isize), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[$name]) -> *mut *mut $ffi_name {
unsafe {
let v_ptr = glib_ffi::g_malloc0(mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in t.iter().enumerate() {
ptr::write(v_ptr.offset(i as isize), s.to_glib_full());
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibContainerFromSlice<'a, *const *mut $ffi_name> for $name {
type Storage = (Vec<Stash<'a, *mut $ffi_name, $name>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
let (ptr, stash) = $crate::translate::ToGlibContainerFromSlice::<'a, *mut *mut $ffi_name>::to_glib_none_from_slice(t);
(ptr as *const *mut $ffi_name, stash)
}
fn to_glib_container_from_slice(_: &'a [$name]) -> (*const *mut $ffi_name, Self::Storage) {
unimplemented!()
}
fn to_glib_full_from_slice(_: &[$name]) -> *const *mut $ffi_name {
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*mut $ffi_name> for $name {
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn from_glib_none(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrNone<*const $ffi_name> for $name {
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn from_glib_none(ptr: *const $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_none(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrFull<*mut $ffi_name> for $name {
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn from_glib_full(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_full(ptr as *mut _), ::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrBorrow<*mut $ffi_name> for $name {
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn from_glib_borrow(ptr: *mut $ffi_name) -> Self {
debug_assert!($crate::types::instance_of::<Self>(ptr as *const _));
$name($crate::translate::from_glib_borrow(ptr as *mut _),
::std::marker::PhantomData)
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
unsafe fn from_glib_none_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_none(ptr::read(ptr.offset(i as isize))));
}
res
}
unsafe fn from_glib_container_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
let res = $crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
glib_ffi::g_free(ptr as *mut _);
res
}
unsafe fn from_glib_full_num_as_vec(ptr: *mut *mut $ffi_name, num: usize) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push($crate::translate::from_glib_full(ptr::read(ptr.offset(i as isize))));
}
glib_ffi::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *mut *mut $ffi_name> for $name {
unsafe fn from_glib_none_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
unsafe fn from_glib_container_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
unsafe fn from_glib_full_as_vec(ptr: *mut *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, $crate::translate::c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
unsafe fn from_glib_none_num_as_vec(ptr: *const *mut $ffi_name, num: usize) -> Vec<Self> {
$crate::translate::FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
unsafe fn from_glib_container_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
unimplemented!()
}
unsafe fn from_glib_full_num_as_vec(_: *const *mut $ffi_name, _: usize) -> Vec<Self> {
unimplemented!()
}
}
#[doc(hidden)]
impl $crate::translate::FromGlibPtrArrayContainerAsVec<*mut $ffi_name, *const *mut $ffi_name> for $name {
unsafe fn from_glib_none_as_vec(ptr: *const *mut $ffi_name) -> Vec<Self> {
$crate::translate::FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
unsafe fn from_glib_container_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
unimplemented!()
}
unsafe fn from_glib_full_as_vec(_: *const *mut $ffi_name) -> Vec<Self> {
unimplemented!()
}
}
impl $crate::types::StaticType for $name {
fn static_type() -> $crate::types::Type {
#[allow(unused_unsafe)]
unsafe { $crate::translate::from_glib($get_type_expr) }
}
}
impl<T: $crate::object::IsA<$crate::object::Object>> ::std::cmp::PartialEq<T> for $name {
#[inline]
fn eq(&self, other: &T) -> bool {
use $crate::translate::ToGlibPtr;
self.0.to_glib_none().0 == other.to_glib_none().0
}
}
impl ::std::cmp::Eq for $name { }
impl<T: $crate::object::IsA<$crate::object::Object>> ::std::cmp::PartialOrd<T> for $name {
#[inline]
fn partial_cmp(&self, other: &T) -> Option<::std::cmp::Ordering> {
use $crate::translate::ToGlibPtr;
self.0.to_glib_none().0.partial_cmp(&other.to_glib_none().0)
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
f.debug_struct(stringify!($name))
.field("inner", &self.0)
.field("type", &<$name as $crate::ObjectExt>::get_type(self))
.finish()
}
}
#[doc(hidden)]
impl<'a> $crate::value::FromValueOptional<'a> for $name {
unsafe fn from_value_optional(value: &$crate::Value) -> Option<Self> {
Option::<$name>::from_glib_full(gobject_ffi::g_value_dup_object(value.to_glib_none().0) as *mut $ffi_name)
.map(|o| $crate::object::Downcast::downcast_unchecked(o))
}
}
#[doc(hidden)]
impl $crate::value::SetValue for $name {
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn set_value(value: &mut $crate::Value, this: &Self) {
gobject_ffi::g_value_set_object(value.to_glib_none_mut().0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(this).0 as *mut gobject_ffi::GObject)
}
}
#[doc(hidden)]
impl $crate::value::SetValueOptional for $name {
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe fn set_value_optional(value: &mut $crate::Value, this: Option<&Self>) {
gobject_ffi::g_value_set_object(value.to_glib_none_mut().0, $crate::translate::ToGlibPtr::<*mut $ffi_name>::to_glib_none(&this).0 as *mut gobject_ffi::GObject)
}
}
};
(@munch_impls $name:ident, ) => { };
(@munch_impls $name:ident, $super_name:path) => {
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a,
*mut <$super_name as $crate::wrapper::Wrapper>::GlibType> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a,
*mut <$super_name as $crate::wrapper::Wrapper>::GlibType, Self> {
let stash = self.0.to_glib_none();
unsafe {
debug_assert!($crate::types::instance_of::<$super_name>(stash.0 as *const _));
}
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self)
-> *mut <$super_name as $crate::wrapper::Wrapper>::GlibType {
let ptr = self.0.to_glib_full();
unsafe {
debug_assert!($crate::types::instance_of::<$super_name>(ptr as *const _));
}
ptr as *mut _
}
}
unsafe impl $crate::object::IsA<$super_name> for $name { }
};
(@munch_impls $name:ident, $super_name:path => $super_ffi:path) => {
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *mut $super_ffi> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *mut $super_ffi, Self> {
let stash = self.0.to_glib_none();
unsafe {
debug_assert!($crate::types::instance_of::<$super_name>(stash.0 as *const _));
}
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $super_ffi {
let ptr = self.0.to_glib_full();
unsafe {
debug_assert!($crate::types::instance_of::<$super_name>(ptr as *const _));
}
ptr as *mut _
}
}
unsafe impl $crate::object::IsA<$super_name> for $name { }
};
(@munch_impls $name:ident, $super_name:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
(@munch_impls $name:ident, $super_name:path => $super_ffi:path, $($implements:tt)*) => {
glib_object_wrapper!(@munch_impls $name, $super_name => $super_ffi);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
};
([$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, @get_type $get_type_expr:expr,
@implements $($implements:tt)*) => {
glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr);
glib_object_wrapper!(@munch_impls $name, $($implements)*);
#[doc(hidden)]
impl<'a> $crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject> for $name {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::object::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self)
-> $crate::translate::Stash<'a, *mut $crate::object::GObject, Self> {
let stash = self.0.to_glib_none();
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $crate::object::GObject {
(&self.0).to_glib_full() as *mut _
}
}
unsafe impl $crate::object::IsA<$crate::object::Object> for $name { }
};
([$($attr:meta)*] $name:ident, $ffi_name:path, $ffi_class_name:path, @get_type $get_type_expr:expr,
[$($implements:path),*]) => {
glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr,
@implements $($implements),*);
}
}
glib_object_wrapper! {
[doc = "The base class in the object hierarchy."]
Object, GObject, GObjectClass, @get_type gobject_ffi::g_object_get_type()
}
impl Object {
pub fn new(type_: Type, properties: &[(&str, &ToValue)]) -> Result<Object, BoolError> {
use std::ffi::CString;
if !type_.is_a(&Object::static_type()) {
return Err(BoolError("Can't instantiate non-GObject objects"));
}
let params = properties.iter()
.map(|&(name, value)|
(CString::new(name).unwrap(), value.to_value()))
.collect::<Vec<_>>();
let params_c = params.iter()
.map(|&(ref name, ref value)|
gobject_ffi::GParameter {
name: name.as_ptr(),
value: unsafe { *value.to_glib_none().0 }
})
.collect::<Vec<_>>();
unsafe {
let ptr = gobject_ffi::g_object_newv(type_.to_glib(), params_c.len() as u32, mut_override(params_c.as_ptr()));
if ptr.is_null() {
Err(BoolError("Can't instantiate object"))
} else if gobject_ffi::g_object_is_floating(ptr) != glib_ffi::GFALSE {
Ok(from_glib_none(ptr))
} else {
Ok(from_glib_full(ptr))
}
}
}
}
pub trait ObjectExt: IsA<Object> {
fn get_type(&self) -> Type;
fn set_property<'a, N: Into<&'a str>>(&self, property_name: N, value: &ToValue) -> Result<(), BoolError>;
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError>;
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> Result<(), BoolError>;
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type>;
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec>;
fn list_properties(&self) -> Vec<::ParamSpec>;
fn block_signal(&self, handler_id: &SignalHandlerId);
fn unblock_signal(&self, handler_id: &SignalHandlerId);
fn stop_signal_emission(&self, signal_name: &str);
fn connect<'a, N, F>(&self, signal_name: N, after: bool, callback: F) -> Result<SignalHandlerId, BoolError>
where N: Into<&'a str>, F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static;
fn emit<'a, N: Into<&'a str>>(&self, signal_name: N, args: &[&ToValue]) -> Result<Option<Value>, BoolError>;
fn disconnect(&self, handler_id: SignalHandlerId);
fn connect_notify<'a, P: Into<Option<&'a str>>, F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(&self, name: P, f: F) -> SignalHandlerId;
fn notify<'a, N: Into<&'a str>>(&self, property_name: N);
fn notify_by_pspec(&self, pspec: &::ParamSpec);
fn downgrade(&self) -> WeakRef<Self>;
fn bind_property<'a, O: IsA<Object>, N: Into<&'a str>, M: Into<&'a str>>(&'a self, source_property: N, target: &'a O, target_property: M) -> BindingBuilder<'a, Self, O>;
fn ref_count(&self) -> u32;
}
impl<T: IsA<Object> + SetValue> ObjectExt for T {
fn get_type(&self) -> Type {
unsafe {
let obj = self.to_glib_none().0;
let klass = (*obj).g_type_instance.g_class as *mut gobject_ffi::GTypeClass;
from_glib((*klass).g_type)
}
}
fn set_property<'a, N: Into<&'a str>>(&self, property_name: N, value: &ToValue) -> Result<(), BoolError> {
let property_name = property_name.into();
let property_value = value.to_value();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(BoolError("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::WRITABLE) || pspec.get_flags().contains(::ParamFlags::CONSTRUCT_ONLY) {
return Err(BoolError("property is not writable"));
}
unsafe {
let valid_type: bool = from_glib(gobject_ffi::g_type_check_value_holds(
mut_override(property_value.to_glib_none().0),
pspec.get_value_type().to_glib()));
if !valid_type {
return Err(BoolError("property can't be set from the given type"));
}
let changed: bool = from_glib(gobject_ffi::g_param_value_validate(
pspec.to_glib_none().0, mut_override(property_value.to_glib_none().0)));
let change_allowed = pspec.get_flags().contains(::ParamFlags::LAX_VALIDATION);
if changed && !change_allowed {
return Err(BoolError("property can't be set from given value, it is invalid or out of range"));
}
gobject_ffi::g_object_set_property(self.to_glib_none().0,
property_name.to_glib_none().0,
property_value.to_glib_none().0);
}
Ok(())
}
fn get_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Result<Value, BoolError> {
let property_name = property_name.into();
let pspec = match self.find_property(property_name) {
Some(pspec) => pspec,
None => {
return Err(BoolError("property not found"));
}
};
if !pspec.get_flags().contains(::ParamFlags::READABLE) {
return Err(BoolError("property is not readable"));
}
unsafe {
let mut value = Value::from_type(pspec.get_value_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, property_name.to_glib_none().0, value.to_glib_none_mut().0);
if value.type_() == ::Type::Invalid {
Err(BoolError("Failed to get property value"))
} else {
Ok(value)
}
}
}
fn block_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_ffi::g_signal_handler_block(self.to_glib_none().0, handler_id.to_glib());
}
}
fn unblock_signal(&self, handler_id: &SignalHandlerId) {
unsafe {
gobject_ffi::g_signal_handler_unblock(self.to_glib_none().0, handler_id.to_glib());
}
}
fn stop_signal_emission(&self, signal_name: &str) {
unsafe {
gobject_ffi::g_signal_stop_emission_by_name(self.to_glib_none().0, signal_name.to_glib_none().0);
}
}
fn disconnect(&self, handler_id: SignalHandlerId) {
unsafe {
gobject_ffi::g_signal_handler_disconnect(self.to_glib_none().0, handler_id.to_glib());
}
}
fn connect_notify<'a, P: Into<Option<&'a str>>, F: Fn(&Self, &::ParamSpec) + Send + Sync + 'static>(&self, name: P, f: F) -> SignalHandlerId {
use std::mem::transmute;
unsafe extern "C" fn notify_trampoline<P>(this: *mut gobject_ffi::GObject, param_spec: *mut gobject_ffi::GParamSpec, f: glib_ffi::gpointer)
where P: IsA<Object> {
let f: &&(Fn(&P, &::ParamSpec) + Send + Sync + 'static) = transmute(f);
f(&Object::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(param_spec))
}
let name = name.into();
let signal_name = if let Some(name) = name {
format!("notify::{}", name)
} else {
"notify".into()
};
unsafe {
let f: Box<Box<Fn(&Self, &::ParamSpec) + Send + Sync + 'static>> = Box::new(Box::new(f));
::signal::connect(self.to_glib_none().0, &signal_name,
transmute(notify_trampoline::<Self> as usize), Box::into_raw(f) as *mut _)
}
}
fn notify<'a, N: Into<&'a str>>(&self, property_name: N) {
let property_name = property_name.into();
unsafe {
gobject_ffi::g_object_notify(self.to_glib_none().0, property_name.to_glib_none().0);
}
}
fn notify_by_pspec(&self, pspec: &::ParamSpec) {
unsafe {
gobject_ffi::g_object_notify_by_pspec(self.to_glib_none().0, pspec.to_glib_none().0);
}
}
fn has_property<'a, N: Into<&'a str>>(&self, property_name: N, type_: Option<Type>) -> Result<(), BoolError> {
let property_name = property_name.into();
let ptype = self.get_property_type(property_name);
match (ptype, type_) {
(None, _) => Err(BoolError("Invalid property name")),
(Some(_), None) => Ok(()),
(Some(ptype), Some(type_)) => {
if ptype == type_ {
Ok(())
} else {
Err(BoolError("Invalid property type"))
}
},
}
}
fn get_property_type<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<Type> {
self.find_property(property_name).map(|pspec| pspec.get_value_type())
}
fn find_property<'a, N: Into<&'a str>>(&self, property_name: N) -> Option<::ParamSpec> {
let property_name = property_name.into();
unsafe {
let obj = self.to_glib_none().0;
let klass = (*obj).g_type_instance.g_class as *mut gobject_ffi::GObjectClass;
from_glib_none(gobject_ffi::g_object_class_find_property(klass, property_name.to_glib_none().0))
}
}
fn list_properties(&self) -> Vec<::ParamSpec> {
unsafe {
let obj = self.to_glib_none().0;
let klass = (*obj).g_type_instance.g_class as *mut gobject_ffi::GObjectClass;
let mut n_properties = 0;
let props = gobject_ffi::g_object_class_list_properties(klass, &mut n_properties);
FromGlibContainer::from_glib_none_num(props, n_properties as usize)
}
}
fn connect<'a, N, F>(&self, signal_name: N, after: bool, callback: F) -> Result<SignalHandlerId, BoolError>
where N: Into<&'a str>, F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static {
let signal_name: &str = signal_name.into();
unsafe {
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_ffi::g_signal_parse_name(signal_name.to_glib_none().0,
type_.to_glib(), &mut signal_id,
&mut signal_detail, true.to_glib()));
if !found {
return Err(BoolError("Signal not found"));
}
let mut details = mem::zeroed();
gobject_ffi::g_signal_query(signal_id, &mut details);
if details.signal_id != signal_id {
return Err(BoolError("Signal not found"));
}
let return_type: Type = from_glib(details.return_type & (!gobject_ffi::G_TYPE_FLAG_RESERVED_ID_BIT));
let closure = Closure::new(move |values| {
let ret = callback(values);
if return_type == Type::Unit {
if let Some(ret) = ret {
panic!("Signal required no return value but got value of type {}", ret.type_().name());
}
None
} else {
match ret {
Some(ret) => {
let valid_type: bool = from_glib(gobject_ffi::g_type_check_value_holds(
mut_override(ret.to_glib_none().0),
return_type.to_glib()));
if !valid_type {
panic!("Signal required return value of type {} but got {}",
return_type.name(), ret.type_().name());
}
Some(ret)
},
None => {
panic!("Signal required return value of type {} but got None", return_type.name());
},
}
}
});
let handler = gobject_ffi::g_signal_connect_closure_by_id(self.to_glib_none().0, signal_id, signal_detail,
closure.to_glib_none().0, after.to_glib());
if handler == 0 {
Err(BoolError("Failed to connect to signal"))
} else {
Ok(from_glib(handler))
}
}
}
fn emit<'a, N: Into<&'a str>>(&self, signal_name: N, args: &[&ToValue]) -> Result<Option<Value>, BoolError> {
let signal_name: &str = signal_name.into();
unsafe {
let type_ = self.get_type();
let mut signal_id = 0;
let mut signal_detail = 0;
let found: bool = from_glib(gobject_ffi::g_signal_parse_name(signal_name.to_glib_none().0,
type_.to_glib(), &mut signal_id,
&mut signal_detail, true.to_glib()));
if !found {
return Err(BoolError("Signal not found"));
}
let mut details = mem::zeroed();
gobject_ffi::g_signal_query(signal_id, &mut details);
if details.signal_id != signal_id {
return Err(BoolError("Signal not found"));
}
if details.n_params != args.len() as u32 {
return Err(BoolError("Incompatible number of arguments"));
}
for i in 0..details.n_params {
let arg_type = *(details.param_types.offset(i as isize)) & (!gobject_ffi::G_TYPE_FLAG_RESERVED_ID_BIT);
if arg_type != args[i as usize].to_value_type().to_glib() {
return Err(BoolError("Incompatible argument types"));
}
}
let mut v_args: Vec<Value>;
let mut s_args: [Value; 10] = mem::zeroed();
let args = if args.len() < 10 {
for (i, arg) in iter::once(&(self as &ToValue)).chain(args).enumerate() {
s_args[i] = arg.to_value();
}
&s_args[0..args.len()+1]
} else {
v_args = Vec::with_capacity(args.len() + 1);
for arg in iter::once(&(self as &ToValue)).chain(args) {
v_args.push(arg.to_value());
}
v_args.as_slice()
};
let mut return_value = Value::uninitialized();
if details.return_type != gobject_ffi::G_TYPE_NONE {
gobject_ffi::g_value_init(return_value.to_glib_none_mut().0, details.return_type);
}
gobject_ffi::g_signal_emitv(mut_override(args.as_ptr()) as *mut gobject_ffi::GValue,
signal_id, signal_detail, return_value.to_glib_none_mut().0);
if return_value.type_() != Type::Unit && return_value.type_() != Type::Invalid {
Ok(Some(return_value))
} else {
Ok(None)
}
}
}
fn downgrade(&self) -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::uninitialized()), PhantomData);
gobject_ffi::g_weak_ref_init(mut_override(&*w.0), self.to_glib_none().0);
w
}
}
fn bind_property<'a, O: IsA<Object>, N: Into<&'a str>, M: Into<&'a str>>(&'a self, source_property: N, target: &'a O, target_property: M) -> BindingBuilder<'a, Self, O> {
let source_property = source_property.into();
let target_property = target_property.into();
BindingBuilder::new(self, source_property, target, target_property)
}
fn ref_count(&self) -> u32 {
let stash = self.to_glib_none();
let ptr: *mut gobject_ffi::GObject = stash.0;
unsafe { glib_ffi::g_atomic_int_get(&(*ptr).ref_count as *const u32 as *const i32) as u32 }
}
}
pub struct WeakRef<T: IsA<Object> + ?Sized>(Box<gobject_ffi::GWeakRef>, PhantomData<*const T>);
impl<T: IsA<Object> + StaticType + UnsafeFrom<ObjectRef> + Wrapper + ?Sized> WeakRef<T> {
pub fn new() -> WeakRef<T> {
unsafe {
let w = WeakRef(Box::new(mem::uninitialized()), PhantomData);
gobject_ffi::g_weak_ref_init(mut_override(&*w.0), ptr::null_mut());
w
}
}
pub fn upgrade(&self) -> Option<T> {
unsafe {
let ptr = gobject_ffi::g_weak_ref_get(mut_override(&*self.0));
if ptr.is_null() {
None
} else {
let obj: Object = from_glib_full(ptr);
Some(T::from(obj.into()))
}
}
}
}
impl<T: IsA<Object> + ?Sized> Drop for WeakRef<T> {
fn drop(&mut self) {
unsafe {
gobject_ffi::g_weak_ref_clear(mut_override(&*self.0));
}
}
}
impl<T: IsA<Object> + ?Sized> Clone for WeakRef<T> {
fn clone(&self) -> Self {
unsafe {
let c = WeakRef(Box::new(mem::uninitialized()), PhantomData);
let o = gobject_ffi::g_weak_ref_get(mut_override(&*self.0));
gobject_ffi::g_weak_ref_init(mut_override(&*c.0), o);
if !o.is_null() {
gobject_ffi::g_object_unref(o);
}
c
}
}
}
impl<T: IsA<Object>> Default for WeakRef<T> {
fn default() -> Self {
Self::new()
}
}
unsafe impl<T: IsA<Object> + Sync + Sync> Sync for WeakRef<T> {}
unsafe impl<T: IsA<Object> + Send + Sync> Send for WeakRef<T> {}
pub struct SendWeakRef<T: IsA<Object>>(WeakRef<T>, Option<usize>);
impl<T: IsA<Object>> SendWeakRef<T> {
pub fn new() -> SendWeakRef<T> {
SendWeakRef(WeakRef::new(), None)
}
pub fn into_weak_ref(self) -> WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
self.0
}
}
impl<T: IsA<Object>> ops::Deref for SendWeakRef<T> {
type Target = WeakRef<T>;
fn deref(&self) -> &WeakRef<T> {
if self.1.is_some() && self.1 != Some(get_thread_id()) {
panic!("SendWeakRef dereferenced on a different thread");
}
&self.0
}
}
impl<T: IsA<Object>> Clone for SendWeakRef<T> {
fn clone(&self) -> Self {
SendWeakRef(self.0.clone(), self.1.clone())
}
}
impl<T: IsA<Object>> Default for SendWeakRef<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: IsA<Object>> From<WeakRef<T>> for SendWeakRef<T> {
fn from(v: WeakRef<T>) -> SendWeakRef<T> {
SendWeakRef(v, Some(get_thread_id()))
}
}
unsafe impl<T: IsA<Object>> Sync for SendWeakRef<T> {}
unsafe impl<T: IsA<Object>> Send for SendWeakRef<T> {}
pub struct BindingBuilder<'a, S: IsA<Object> + 'a, T: IsA<Object> + 'a> {
source: &'a S,
source_property: &'a str,
target: &'a T,
target_property: &'a str,
flags: ::BindingFlags,
transform_to: Option<::Closure>,
transform_from: Option<::Closure>,
}
impl<'a, S: IsA<Object> + 'a, T: IsA<Object> + 'a> BindingBuilder<'a, S, T> {
fn new(source: &'a S, source_property: &'a str, target: &'a T, target_property: &'a str) -> Self {
Self { source, source_property, target, target_property, flags: ::BindingFlags::DEFAULT, transform_to: None, transform_from: None }
}
fn transform_closure<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(func: F) -> ::Closure {
::Closure::new(move |values| {
assert_eq!(values.len(), 3);
let binding = values[0].get::<::Binding>().unwrap();
let from = unsafe {
let ptr = gobject_ffi::g_value_get_boxed(mut_override(&values[1] as *const Value as *const gobject_ffi::GValue));
assert!(!ptr.is_null());
&*(ptr as *const gobject_ffi::GValue as *const Value)
};
match func(&binding, &from) {
None => Some(false.to_value()),
Some(value) => {
unsafe {
gobject_ffi::g_value_set_boxed(mut_override(&values[2] as *const Value as *const gobject_ffi::GValue), &value as *const Value as *const _);
}
Some(true.to_value())
}
}
})
}
pub fn transform_from<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(self, func: F) -> Self {
Self {
transform_from: Some(Self::transform_closure(func)),
..self
}
}
pub fn transform_to<F: Fn(&::Binding, &Value) -> Option<Value> + Send + Sync + 'static>(self, func: F) -> Self {
Self {
transform_to: Some(Self::transform_closure(func)),
..self
}
}
pub fn flags(self, flags: ::BindingFlags) -> Self {
Self {
flags: flags,
..self
}
}
pub fn build(self) -> Option<::Binding> {
unsafe {
from_glib_none(
gobject_ffi::g_object_bind_property_with_closures(
self.source.to_glib_none().0,
self.source_property.to_glib_none().0,
self.target.to_glib_none().0,
self.target_property.to_glib_none().0,
self.flags.to_glib(),
self.transform_to.to_glib_none().0,
self.transform_from.to_glib_none().0,
)
)
}
}
}