-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
object.rs
4587 lines (4016 loc) · 160 KB
/
object.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
// Take a look at the license at the top of the repository in the LICENSE file.
// rustdoc-stripper-ignore-next
//! `IMPL` Object wrapper implementation and `Object` binding.
use crate::types::StaticType;
use crate::PtrSlice;
use crate::{quark::Quark, subclass::signal::SignalQuery};
use crate::{translate::*, value::FromValue};
use std::cmp;
use std::fmt;
use std::hash;
use std::marker::PhantomData;
use std::mem;
use std::mem::ManuallyDrop;
use std::ops;
use std::pin::Pin;
use std::ptr;
use crate::closure::TryFromClosureReturnValue;
use crate::subclass::{prelude::ObjectSubclass, SignalId};
use crate::value::ToValue;
use crate::SignalHandlerId;
use crate::Type;
use crate::Value;
use crate::{Closure, RustClosure};
use crate::thread_guard::thread_id;
// rustdoc-stripper-ignore-next
/// Implemented by types representing `glib::Object` and subclasses of it.
pub unsafe trait ObjectType:
UnsafeFrom<ObjectRef>
+ Into<ObjectRef>
+ StaticType
+ fmt::Debug
+ Clone
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ hash::Hash
+ crate::value::ValueType
+ crate::value::ToValue
+ crate::value::ToValueOptional
+ crate::value::FromValueOptional<'static>
+ for<'a> ToGlibPtr<'a, *mut <Self as ObjectType>::GlibType>
+ IntoGlibPtr<*mut <Self as ObjectType>::GlibType>
+ 'static
{
// rustdoc-stripper-ignore-next
/// type of the FFI Instance structure.
type GlibType: 'static;
// rustdoc-stripper-ignore-next
/// type of the FFI Class structure.
type GlibClassType: 'static;
fn as_object_ref(&self) -> &ObjectRef;
fn as_ptr(&self) -> *mut Self::GlibType;
}
// rustdoc-stripper-ignore-next
/// Declares the "is a" relationship.
///
/// `Self` is said to implement `T`.
///
/// For instance, since originally `GtkWidget` is a subclass of `GObject` and
/// implements the `GtkBuildable` interface, `gtk::Widget` implements
/// `IsA<glib::Object>` and `IsA<gtk::Buildable>`.
///
///
/// The trait can only be implemented if the appropriate `ToGlibPtr`
/// implementations exist.
pub unsafe trait IsA<T: ObjectType>:
ObjectType + Into<T> + AsRef<T> + std::borrow::Borrow<T>
{
}
// rustdoc-stripper-ignore-next
/// Upcasting and downcasting support.
///
/// Provides conversions up and down the class hierarchy tree.
pub trait Cast: ObjectType {
// rustdoc-stripper-ignore-next
/// Upcasts an object to a superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// ```
#[inline]
fn upcast<T: ObjectType>(self) -> T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast() }
}
// rustdoc-stripper-ignore-next
/// Upcasts an object to a reference of its superclass or interface `T`.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast_ref::<gtk::Widget>();
/// ```
#[inline]
fn upcast_ref<T: ObjectType>(&self) -> &T
where
Self: IsA<T>,
{
unsafe { self.unsafe_cast_ref() }
}
// rustdoc-stripper-ignore-next
/// Tries to downcast to a subclass or interface implementor `T`.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn downcast<T: ObjectType>(self) -> Result<T, Self>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Ok(unsafe { self.unsafe_cast() })
} else {
Err(self)
}
}
// rustdoc-stripper-ignore-next
/// Tries to downcast to a reference of its subclass or interface implementor `T`.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// *NOTE*: This statically checks at compile-time if casting is possible. It is not always
/// known at compile-time, whether a specific object implements an interface or not, in which case
/// `upcast` would fail to compile. `dynamic_cast` can be used in these circumstances, which
/// is checking the types at runtime.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.upcast::<gtk::Widget>();
/// assert!(widget.downcast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self: CanDowncast<T>,
{
if self.is::<T>() {
Some(unsafe { self.unsafe_cast_ref() })
} else {
None
}
}
// rustdoc-stripper-ignore-next
/// Tries to cast to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking has to be performed at runtime.
///
/// Returns `Ok(T)` if the object is an instance of `T` and `Err(self)`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast::<gtk::Widget>();
/// assert!(widget.is_ok());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast::<gtk::Button>().is_ok());
/// ```
#[inline]
fn dynamic_cast<T: ObjectType>(self) -> Result<T, Self> {
if !self.is::<T>() {
Err(self)
} else {
Ok(unsafe { self.unsafe_cast() })
}
}
// rustdoc-stripper-ignore-next
/// Tries to cast to reference to an object of type `T`. This handles upcasting, downcasting
/// and casting between interface and interface implementors. All checks are performed at
/// runtime, while `downcast` and `upcast` will do many checks at compile-time already.
///
/// It is not always known at compile-time, whether a specific object implements an interface or
/// not, and checking has to be performed at runtime.
///
/// Returns `Some(T)` if the object is an instance of `T` and `None`
/// otherwise.
///
/// # Example
///
/// ```ignore
/// let button = gtk::Button::new();
/// let widget = button.dynamic_cast_ref::<gtk::Widget>();
/// assert!(widget.is_some());
/// let widget = widget.unwrap();
/// assert!(widget.dynamic_cast_ref::<gtk::Button>().is_some());
/// ```
#[inline]
fn dynamic_cast_ref<T: ObjectType>(&self) -> Option<&T> {
if !self.is::<T>() {
None
} else {
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
Some(unsafe { self.unsafe_cast_ref() })
}
}
// rustdoc-stripper-ignore-next
/// Casts to `T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
#[track_caller]
unsafe fn unsafe_cast<T: ObjectType>(self) -> T {
debug_assert!(self.is::<T>());
T::unsafe_from(self.into())
}
// rustdoc-stripper-ignore-next
/// Casts to `&T` unconditionally.
///
/// # Panics
///
/// Panics if compiled with `debug_assertions` and the instance doesn't implement `T`.
///
/// # Safety
///
/// If not running with `debug_assertions` enabled, the caller is responsible
/// for ensuring that the instance implements `T`
#[track_caller]
unsafe fn unsafe_cast_ref<T: ObjectType>(&self) -> &T {
debug_assert!(self.is::<T>());
// This cast is safe because all our wrapper types have the
// same representation except for the name and the phantom data
// type. IsA<> is an unsafe trait that must only be implemented
// if this is a valid wrapper type
&*(self as *const Self as *const T)
}
}
impl<T: ObjectType> Cast for T {}
// rustdoc-stripper-ignore-next
/// Convenience trait mirroring `Cast`, implemented on `Option<Object>` types.
///
/// # Warning
/// Inveitably this trait will discard informations about a downcast failure:
/// you don't know if the object was not of the expected type, or if it was `None`.
/// If you need to handle the downcast error, use `Cast` over a `glib::Object`.
///
/// # Example
/// ```ignore
/// let widget: Option<Widget> = list_item.child();
///
/// // Without using `CastNone`
/// let label = widget.unwrap().downcast::<gtk::Label>().unwrap();
///
/// // Using `CastNone` we can avoid the first `unwrap()` call
/// let label = widget.and_downcast::<gtk::Label>().unwrap();
/// ````
pub trait CastNone: Sized {
type Inner;
fn and_downcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: CanDowncast<T>;
fn and_downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: CanDowncast<T>;
fn and_upcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: IsA<T>;
fn and_upcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: IsA<T>;
fn and_dynamic_cast<T: ObjectType>(self) -> Result<T, Self>;
fn and_dynamic_cast_ref<T: ObjectType>(&self) -> Option<&T>;
}
impl<I: ObjectType + Sized> CastNone for Option<I> {
type Inner = I;
fn and_downcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: CanDowncast<T>,
{
self.and_then(|i| i.downcast().ok())
}
fn and_downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: CanDowncast<T>,
{
self.as_ref().and_then(|i| i.downcast_ref())
}
fn and_upcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: IsA<T>,
{
self.map(|i| i.upcast())
}
fn and_upcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: IsA<T>,
{
self.as_ref().map(|i| i.upcast_ref())
}
fn and_dynamic_cast<T: ObjectType>(self) -> Result<T, Self> {
self.ok_or(None)
.and_then(|i| i.dynamic_cast().map_err(|e| Some(e)))
}
fn and_dynamic_cast_ref<T: ObjectType>(&self) -> Option<&T> {
self.as_ref().and_then(|i| i.dynamic_cast_ref())
}
}
// rustdoc-stripper-ignore-next
/// Marker trait for the statically known possibility of downcasting from `Self` to `T`.
pub trait CanDowncast<T> {}
impl<Super: IsA<Super>, Sub: IsA<Super>> CanDowncast<Sub> for Super {}
// Manual implementation of glib_shared_wrapper! because of special cases
#[repr(transparent)]
pub struct ObjectRef {
inner: ptr::NonNull<gobject_ffi::GObject>,
}
impl Clone for ObjectRef {
fn clone(&self) -> Self {
unsafe {
Self {
inner: ptr::NonNull::new_unchecked(gobject_ffi::g_object_ref(self.inner.as_ptr())),
}
}
}
}
impl Drop for ObjectRef {
fn drop(&mut self) {
unsafe {
gobject_ffi::g_object_unref(self.inner.as_ptr());
}
}
}
impl fmt::Debug for ObjectRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let type_ = unsafe {
let klass = (*self.inner.as_ptr()).g_type_instance.g_class as *const ObjectClass;
(*klass).type_()
};
f.debug_struct("ObjectRef")
.field("inner", &self.inner)
.field("type", &type_)
.finish()
}
}
impl PartialOrd for ObjectRef {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.inner.partial_cmp(&other.inner)
}
}
impl Ord for ObjectRef {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.inner.cmp(&other.inner)
}
}
impl PartialEq for ObjectRef {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl Eq for ObjectRef {}
impl hash::Hash for ObjectRef {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.inner.hash(state)
}
}
#[doc(hidden)]
impl GlibPtrDefault for ObjectRef {
type GlibType = *mut gobject_ffi::GObject;
}
#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *mut gobject_ffi::GObject> for ObjectRef {
type Storage = &'a ObjectRef;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *mut gobject_ffi::GObject, Self> {
Stash(self.inner.as_ptr(), self)
}
#[inline]
fn to_glib_full(&self) -> *mut gobject_ffi::GObject {
unsafe { gobject_ffi::g_object_ref(self.inner.as_ptr()) }
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *mut *mut gobject_ffi::GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut gobject_ffi::GObject, ObjectRef>>,
Option<Vec<*mut gobject_ffi::GObject>>,
);
fn to_glib_none_from_slice(
t: &'a [ObjectRef],
) -> (*mut *mut gobject_ffi::GObject, 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 gobject_ffi::GObject);
(
v_ptr.as_ptr() as *mut *mut gobject_ffi::GObject,
(v, Some(v_ptr)),
)
}
fn to_glib_container_from_slice(
t: &'a [ObjectRef],
) -> (*mut *mut gobject_ffi::GObject, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| s.to_glib_none()).collect();
let v_ptr = unsafe {
let v_ptr = ffi::g_malloc0(mem::size_of::<*mut gobject_ffi::GObject>() * (t.len() + 1))
as *mut *mut gobject_ffi::GObject;
for (i, s) in v.iter().enumerate() {
ptr::write(v_ptr.add(i), s.0);
}
v_ptr
};
(v_ptr, (v, None))
}
fn to_glib_full_from_slice(t: &[ObjectRef]) -> *mut *mut gobject_ffi::GObject {
unsafe {
let v_ptr =
ffi::g_malloc0(std::mem::size_of::<*mut gobject_ffi::GObject>() * (t.len() + 1))
as *mut *mut gobject_ffi::GObject;
for (i, s) in t.iter().enumerate() {
ptr::write(v_ptr.add(i), s.to_glib_full());
}
v_ptr
}
}
}
#[doc(hidden)]
impl<'a> ToGlibContainerFromSlice<'a, *const *mut gobject_ffi::GObject> for ObjectRef {
type Storage = (
Vec<Stash<'a, *mut gobject_ffi::GObject, ObjectRef>>,
Option<Vec<*mut gobject_ffi::GObject>>,
);
fn to_glib_none_from_slice(
t: &'a [ObjectRef],
) -> (*const *mut gobject_ffi::GObject, Self::Storage) {
let (ptr, stash) =
ToGlibContainerFromSlice::<'a, *mut *mut gobject_ffi::GObject>::to_glib_none_from_slice(
t,
);
(ptr as *const *mut gobject_ffi::GObject, stash)
}
fn to_glib_container_from_slice(
_: &'a [ObjectRef],
) -> (*const *mut gobject_ffi::GObject, Self::Storage) {
// Can't have consumer free a *const pointer
unimplemented!()
}
fn to_glib_full_from_slice(_: &[ObjectRef]) -> *const *mut gobject_ffi::GObject {
// Can't have consumer free a *const pointer
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*mut gobject_ffi::GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *mut gobject_ffi::GObject) -> Self {
assert!(!ptr.is_null());
assert_ne!((*ptr).ref_count, 0);
// Attention: This takes ownership of floating references!
Self {
inner: ptr::NonNull::new_unchecked(gobject_ffi::g_object_ref_sink(ptr)),
}
}
}
#[doc(hidden)]
impl FromGlibPtrNone<*const gobject_ffi::GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_none(ptr: *const gobject_ffi::GObject) -> Self {
// Attention: This takes ownership of floating references!
from_glib_none(ptr as *mut gobject_ffi::GObject)
}
}
#[doc(hidden)]
impl FromGlibPtrFull<*mut gobject_ffi::GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_full(ptr: *mut gobject_ffi::GObject) -> Self {
assert!(!ptr.is_null());
assert_ne!((*ptr).ref_count, 0);
Self {
inner: ptr::NonNull::new_unchecked(ptr),
}
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*mut gobject_ffi::GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *mut gobject_ffi::GObject) -> Borrowed<Self> {
assert!(!ptr.is_null());
assert_ne!((*ptr).ref_count, 0);
Borrowed::new(Self {
inner: ptr::NonNull::new_unchecked(ptr),
})
}
}
#[doc(hidden)]
impl FromGlibPtrBorrow<*const gobject_ffi::GObject> for ObjectRef {
#[inline]
unsafe fn from_glib_borrow(ptr: *const gobject_ffi::GObject) -> Borrowed<Self> {
from_glib_borrow(ptr as *mut gobject_ffi::GObject)
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut gobject_ffi::GObject, *mut *mut gobject_ffi::GObject>
for ObjectRef
{
unsafe fn from_glib_none_num_as_vec(
ptr: *mut *mut gobject_ffi::GObject,
num: usize,
) -> Vec<Self> {
if num == 0 || ptr.is_null() {
return Vec::new();
}
// Attention: This takes ownership of floating references!
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_none(ptr::read(ptr.add(i))));
}
res
}
unsafe fn from_glib_container_num_as_vec(
ptr: *mut *mut gobject_ffi::GObject,
num: usize,
) -> Vec<Self> {
// Attention: This takes ownership of floating references!
let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
ffi::g_free(ptr as *mut _);
res
}
unsafe fn from_glib_full_num_as_vec(
ptr: *mut *mut gobject_ffi::GObject,
num: usize,
) -> Vec<Self> {
if num == 0 || ptr.is_null() {
ffi::g_free(ptr as *mut _);
return Vec::new();
}
let mut res = Vec::with_capacity(num);
for i in 0..num {
res.push(from_glib_full(ptr::read(ptr.add(i))));
}
ffi::g_free(ptr as *mut _);
res
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut gobject_ffi::GObject, *mut *mut gobject_ffi::GObject>
for ObjectRef
{
unsafe fn from_glib_none_as_vec(ptr: *mut *mut gobject_ffi::GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_container_as_vec(ptr: *mut *mut gobject_ffi::GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, c_ptr_array_len(ptr))
}
unsafe fn from_glib_full_as_vec(ptr: *mut *mut gobject_ffi::GObject) -> Vec<Self> {
FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, c_ptr_array_len(ptr))
}
}
#[doc(hidden)]
impl FromGlibContainerAsVec<*mut gobject_ffi::GObject, *const *mut gobject_ffi::GObject>
for ObjectRef
{
unsafe fn from_glib_none_num_as_vec(
ptr: *const *mut gobject_ffi::GObject,
num: usize,
) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *mut *mut _, num)
}
unsafe fn from_glib_container_num_as_vec(
_: *const *mut gobject_ffi::GObject,
_: usize,
) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_num_as_vec(
_: *const *mut gobject_ffi::GObject,
_: usize,
) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[doc(hidden)]
impl FromGlibPtrArrayContainerAsVec<*mut gobject_ffi::GObject, *const *mut gobject_ffi::GObject>
for ObjectRef
{
unsafe fn from_glib_none_as_vec(ptr: *const *mut gobject_ffi::GObject) -> Vec<Self> {
// Attention: This takes ownership of floating references!
FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr as *mut *mut _)
}
unsafe fn from_glib_container_as_vec(_: *const *mut gobject_ffi::GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
unsafe fn from_glib_full_as_vec(_: *const *mut gobject_ffi::GObject) -> Vec<Self> {
// Can't free a *const
unimplemented!()
}
}
#[repr(transparent)]
pub struct TypedObjectRef<T, P> {
inner: ObjectRef,
imp: PhantomData<T>,
parent: PhantomData<P>,
}
impl<T, P> TypedObjectRef<T, P> {
pub unsafe fn new(obj: ObjectRef) -> Self {
Self {
inner: obj,
imp: PhantomData,
parent: PhantomData,
}
}
pub fn into_inner(self) -> ObjectRef {
self.inner
}
}
impl<T, P> Clone for TypedObjectRef<T, P> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
imp: PhantomData,
parent: PhantomData,
}
}
}
impl<T, P> ops::Deref for TypedObjectRef<T, P> {
type Target = ObjectRef;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T, P> fmt::Debug for TypedObjectRef<T, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let type_ = unsafe {
let klass = (*self.inner.inner.as_ptr()).g_type_instance.g_class as *const ObjectClass;
(*klass).type_()
};
f.debug_struct("TypedObjectRef")
.field("inner", &self.inner.inner)
.field("type", &type_)
.finish()
}
}
impl<T, P> PartialOrd for TypedObjectRef<T, P> {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.inner.partial_cmp(&other.inner)
}
}
impl<T, P> Ord for TypedObjectRef<T, P> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.inner.cmp(&other.inner)
}
}
impl<T, P> PartialEq for TypedObjectRef<T, P> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, P> Eq for TypedObjectRef<T, P> {}
impl<T, P> hash::Hash for TypedObjectRef<T, P> {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.inner.hash(state)
}
}
unsafe impl<T: Send + Sync, P: Send + Sync> Send for TypedObjectRef<T, P> {}
unsafe impl<T: Send + Sync, P: Send + Sync> Sync for TypedObjectRef<T, P> {}
// rustdoc-stripper-ignore-next
/// ObjectType implementations for Object types. See `wrapper!`.
#[macro_export]
macro_rules! glib_object_wrapper {
(@generic_impl [$($attr:meta)*] $visibility:vis $name:ident $(<$($generic:ident $(: $bound:tt $(+ $bound2:tt)*)?),+>)?, $impl_type:ty, $parent_type:ty, $ffi_name:ty, $ffi_class_name:ty, @type_ $get_type_expr:expr) => {
$(#[$attr])*
#[repr(transparent)]
$visibility struct $name $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? {
inner: $crate::object::TypedObjectRef<$impl_type, $parent_type>,
phantom: std::marker::PhantomData<($($($generic),+)?)>,
}
// Always implement Clone, Hash, PartialEq, Eq, PartialOrd, Ord, and Debug for object types.
// Due to inheritance and up/downcasting we must implement these by pointer or otherwise they
// would potentially give different results for the same object depending on the type we
// currently know for it.
// Implement them manually rather than generating #[derive] macros since so that when generics
// are specified, these traits are not required.
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::clone::Clone for $name $(<$($generic),+>)? {
#[inline]
fn clone(&self) -> Self {
Self {
inner: std::clone::Clone::clone(&self.inner),
phantom: std::marker::PhantomData,
}
}
}
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::hash::Hash for $name $(<$($generic),+>)? {
#[inline]
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher
{
std::hash::Hash::hash(&self.inner, state);
}
}
impl<OT: $crate::object::ObjectType $(, $($generic $(: $bound $(+ $bound2)*)?),+)?> std::cmp::PartialEq<OT> for $name $(<$($generic),+>)? {
#[inline]
fn eq(&self, other: &OT) -> bool {
std::cmp::PartialEq::eq(&*self.inner, $crate::object::ObjectType::as_object_ref(other))
}
}
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::cmp::Eq for $name $(<$($generic),+>)? {}
impl<OT: $crate::object::ObjectType $(, $($generic $(: $bound $(+ $bound2)*)?),+)?> std::cmp::PartialOrd<OT> for $name $(<$($generic),+>)? {
#[inline]
fn partial_cmp(&self, other: &OT) -> Option<std::cmp::Ordering> {
std::cmp::PartialOrd::partial_cmp(&*self.inner, $crate::object::ObjectType::as_object_ref(other))
}
}
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::cmp::Ord for $name $(<$($generic),+>)? {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
std::cmp::Ord::cmp(&*self.inner, $crate::object::ObjectType::as_object_ref(other))
}
}
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? std::fmt::Debug for $name $(<$($generic),+>)? {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct(stringify!($name)).field("inner", &self.inner).finish()
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? From<$name $(<$($generic),+>)?> for $crate::object::ObjectRef {
fn from(s: $name $(<$($generic),+>)?) -> $crate::object::ObjectRef {
s.inner.into_inner()
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::translate::UnsafeFrom<$crate::object::ObjectRef> for $name $(<$($generic),+>)? {
unsafe fn unsafe_from(t: $crate::object::ObjectRef) -> Self {
$name {
inner: $crate::object::TypedObjectRef::new(t),
phantom: std::marker::PhantomData,
}
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::translate::GlibPtrDefault for $name $(<$($generic),+>)? {
type GlibType = *mut $ffi_name;
}
#[doc(hidden)]
unsafe impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::object::ObjectType for $name $(<$($generic),+>)? {
type GlibType = $ffi_name;
type GlibClassType = $ffi_class_name;
fn as_object_ref(&self) -> &$crate::object::ObjectRef {
&self.inner
}
fn as_ptr(&self) -> *mut Self::GlibType {
$crate::translate::ToGlibPtr::to_glib_none(&*self.inner).0 as *mut _
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? AsRef<$crate::object::ObjectRef> for $name $(<$($generic),+>)? {
fn as_ref(&self) -> &$crate::object::ObjectRef {
&self.inner
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? AsRef<Self> for $name $(<$($generic),+>)? {
fn as_ref(&self) -> &Self {
self
}
}
#[doc(hidden)]
unsafe impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::object::IsA<Self> for $name $(<$($generic),+>)? { }
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::subclass::types::FromObject for $name $(<$($generic),+>)? {
type FromObjectType = Self;
fn from_object(obj: &Self::FromObjectType) -> &Self {
obj
}
}
#[doc(hidden)]
impl<'a $(, $($generic $(: $bound $(+ $bound2)*)?),+)?> $crate::translate::ToGlibPtr<'a, *const $ffi_name> for $name $(<$($generic),+>)? {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::gobject_ffi::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *const $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&*self.inner);
$crate::translate::Stash(stash.0 as *const _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *const $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&*self.inner) as *const _
}
}
#[doc(hidden)]
impl<'a $(, $($generic $(: $bound $(+ $bound2)*)?),+)?> $crate::translate::ToGlibPtr<'a, *mut $ffi_name> for $name $(<$($generic),+>)? {
type Storage = <$crate::object::ObjectRef as
$crate::translate::ToGlibPtr<'a, *mut $crate::gobject_ffi::GObject>>::Storage;
#[inline]
fn to_glib_none(&'a self) -> $crate::translate::Stash<'a, *mut $ffi_name, Self> {
let stash = $crate::translate::ToGlibPtr::to_glib_none(&*self.inner);
$crate::translate::Stash(stash.0 as *mut _, stash.1)
}
#[inline]
fn to_glib_full(&self) -> *mut $ffi_name {
$crate::translate::ToGlibPtr::to_glib_full(&*self.inner) as *mut _
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::translate::IntoGlibPtr<*mut $ffi_name> for $name $(<$($generic),+>)? {
unsafe fn into_glib_ptr(self) -> *mut $ffi_name {
let s = std::mem::ManuallyDrop::new(self);
$crate::translate::ToGlibPtr::<*const $ffi_name>::to_glib_none(&*s).0 as *mut _
}
}
#[doc(hidden)]
impl $(<$($generic $(: $bound $(+ $bound2)*)?),+>)? $crate::translate::IntoGlibPtr<*const $ffi_name> for $name $(<$($generic),+>)? {
unsafe fn into_glib_ptr(self) -> *const $ffi_name {
let s = std::mem::ManuallyDrop::new(self);
$crate::translate::ToGlibPtr::<*const $ffi_name>::to_glib_none(&*s).0 as *const _
}
}
#[doc(hidden)]
impl<'a $(, $($generic $(: $bound $(+ $bound2)*)?),+)?> $crate::translate::ToGlibContainerFromSlice<'a, *mut *mut $ffi_name> for $name $(<$($generic),+>)? {
type Storage = (Vec<$crate::translate::Stash<'a, *mut $ffi_name, Self>>, Option<Vec<*mut $ffi_name>>);
fn to_glib_none_from_slice(t: &'a [Self]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
v_ptr.push(std::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 [Self]) -> (*mut *mut $ffi_name, Self::Storage) {
let v: Vec<_> = t.iter().map(|s| $crate::translate::ToGlibPtr::to_glib_none(s)).collect();
let v_ptr = unsafe {
let v_ptr = $crate::ffi::g_malloc0(std::mem::size_of::<*mut $ffi_name>() * (t.len() + 1)) as *mut *mut $ffi_name;
for (i, s) in v.iter().enumerate() {
std::ptr::write(v_ptr.add(i), s.0);
}