pub fn same_interface(a: &'static Interface, b: &'static Interface) -> bool
Expand description

Returns true if the two interfaces are the same.

Examples found in repository?
src/protocol.rs (line 286)
285
286
287
pub(crate) fn same_interface_or_anonymous(a: &'static Interface, b: &'static Interface) -> bool {
    same_interface(a, b) || same_interface(a, &ANONYMOUS_INTERFACE)
}
More examples
Hide additional examples
src/rs/client_impl/mod.rs (line 52)
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
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.serial == other.serial
            && same_interface(self.interface, other.interface)
    }
}

impl std::cmp::Eq for InnerObjectId {}

impl std::hash::Hash for InnerObjectId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.serial.hash(state);
        self.id.hash(state);
    }
}

impl fmt::Display for InnerObjectId {
    #[cfg_attr(coverage, no_coverage)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}@{}", self.interface.name, self.id)
    }
}

impl fmt::Debug for InnerObjectId {
    #[cfg_attr(coverage, no_coverage)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ObjectId({}, {})", self, self.serial)
    }
}

impl InnerObjectId {
    pub fn is_null(&self) -> bool {
        self.id == 0
    }

    pub fn interface(&self) -> &'static Interface {
        self.interface
    }

    pub fn protocol_id(&self) -> u32 {
        self.id
    }
}

#[derive(Debug)]
struct ProtocolState {
    socket: BufferedSocket,
    map: ObjectMap<Data>,
    last_error: Option<WaylandError>,
    last_serial: u32,
    debug: bool,
}

#[derive(Debug)]
struct ReadingState {
    prepared_reads: usize,
    read_condvar: Arc<Condvar>,
    read_serial: usize,
}

#[derive(Debug)]
pub struct ConnectionState {
    protocol: Mutex<ProtocolState>,
    read: Mutex<ReadingState>,
}

impl ConnectionState {
    fn lock_protocol(&self) -> MutexGuard<ProtocolState> {
        self.protocol.lock().unwrap()
    }

    fn lock_read(&self) -> MutexGuard<ReadingState> {
        self.read.lock().unwrap()
    }
}

#[derive(Clone, Debug)]
pub struct InnerBackend {
    state: Arc<ConnectionState>,
}

#[derive(Clone, Debug)]
pub struct WeakInnerBackend {
    state: Weak<ConnectionState>,
}

impl WeakInnerBackend {
    pub fn upgrade(&self) -> Option<InnerBackend> {
        Weak::upgrade(&self.state).map(|state| InnerBackend { state })
    }
}

impl InnerBackend {
    pub fn downgrade(&self) -> WeakInnerBackend {
        WeakInnerBackend { state: Arc::downgrade(&self.state) }
    }

    pub fn connect(stream: UnixStream) -> Result<Self, NoWaylandLib> {
        let socket = BufferedSocket::new(Socket::from(stream));
        let mut map = ObjectMap::new();
        map.insert_at(
            1,
            Object {
                interface: &WL_DISPLAY_INTERFACE,
                version: 1,
                data: Data {
                    client_destroyed: false,
                    server_destroyed: false,
                    user_data: Arc::new(DumbObjectData),
                    serial: 0,
                },
            },
        )
        .unwrap();

        let debug =
            matches!(std::env::var_os("WAYLAND_DEBUG"), Some(str) if str == "1" || str == "client");

        Ok(Self {
            state: Arc::new(ConnectionState {
                protocol: Mutex::new(ProtocolState {
                    socket,
                    map,
                    last_error: None,
                    last_serial: 0,
                    debug,
                }),
                read: Mutex::new(ReadingState {
                    prepared_reads: 0,
                    read_condvar: Arc::new(Condvar::new()),
                    read_serial: 0,
                }),
            }),
        })
    }

    /// Flush all pending outgoing requests to the server
    pub fn flush(&self) -> Result<(), WaylandError> {
        let mut guard = self.state.lock_protocol();
        guard.no_last_error()?;
        if let Err(e) = guard.socket.flush() {
            return Err(guard.store_if_not_wouldblock_and_return_error(e));
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct InnerReadEventsGuard {
    state: Arc<ConnectionState>,
    done: bool,
}

impl InnerReadEventsGuard {
    /// Create a new reading guard
    ///
    /// This call will not block, but event callbacks may be invoked in the process
    /// of preparing the guard.
    pub fn try_new(backend: InnerBackend) -> Result<Self, WaylandError> {
        backend.state.lock_read().prepared_reads += 1;
        Ok(Self { state: backend.state, done: false })
    }

    /// Access the Wayland socket FD for polling
    pub fn connection_fd(&self) -> BorrowedFd {
        let raw_fd = self.state.lock_protocol().socket.as_raw_fd();
        // This allows the lifetime of the BorrowedFd to be tied to &self rather than the lock guard,
        // which is the real safety concern
        unsafe { BorrowedFd::borrow_raw(raw_fd) }
    }

    /// Attempt to read events from the Wayland socket
    ///
    /// If multiple threads have a live reading guard, this method will block until all of them
    /// are either dropped or have their `read()` method invoked, at which point on of the threads
    /// will read events from the socket and invoke the callbacks for the received events. All
    /// threads will then resume their execution.
    ///
    /// This returns the number of dispatched events, or `0` if an other thread handled the dispatching.
    /// If no events are available to read from the socket, this returns a `WouldBlock` IO error.
    pub fn read(mut self) -> Result<usize, WaylandError> {
        let mut guard = self.state.lock_read();
        guard.prepared_reads -= 1;
        self.done = true;
        if guard.prepared_reads == 0 {
            // We should be the one reading
            let ret = dispatch_events(self.state.clone());
            // wake up other threads
            guard.read_serial = guard.read_serial.wrapping_add(1);
            guard.read_condvar.notify_all();
            // forward the return value
            ret
        } else {
            // We should wait for an other thread to read (or cancel)
            let serial = guard.read_serial;
            let condvar = guard.read_condvar.clone();
            let _guard =
                condvar.wait_while(guard, |backend| serial == backend.read_serial).unwrap();
            self.state.lock_protocol().no_last_error()?;
            Ok(0)
        }
    }
}

impl Drop for InnerReadEventsGuard {
    fn drop(&mut self) {
        if !self.done {
            let mut guard = self.state.lock_read();
            guard.prepared_reads -= 1;
            if guard.prepared_reads == 0 {
                // Cancel the read
                guard.read_serial = guard.read_serial.wrapping_add(1);
                guard.read_condvar.notify_all();
            }
        }
    }
}

impl InnerBackend {
    pub fn display_id(&self) -> ObjectId {
        ObjectId { id: InnerObjectId { serial: 0, id: 1, interface: &WL_DISPLAY_INTERFACE } }
    }

    pub fn last_error(&self) -> Option<WaylandError> {
        self.state.lock_protocol().last_error.clone()
    }

    pub fn info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> {
        let object = self.state.lock_protocol().get_object(id.id.clone())?;
        if object.data.client_destroyed {
            Err(InvalidId)
        } else {
            Ok(ObjectInfo { id: id.id.id, interface: object.interface, version: object.version })
        }
    }

    pub fn null_id() -> ObjectId {
        ObjectId { id: InnerObjectId { serial: 0, id: 0, interface: &ANONYMOUS_INTERFACE } }
    }

    pub fn send_request(
        &self,
        Message { sender_id: ObjectId { id }, opcode, args }: Message<ObjectId, RawFd>,
        data: Option<Arc<dyn ObjectData>>,
        child_spec: Option<(&'static Interface, u32)>,
    ) -> Result<ObjectId, InvalidId> {
        let mut guard = self.state.lock_protocol();
        let object = guard.get_object(id.clone())?;
        if object.data.client_destroyed {
            return Err(InvalidId);
        }

        let message_desc = match object.interface.requests.get(opcode as usize) {
            Some(msg) => msg,
            None => {
                panic!("Unknown opcode {} for object {}@{}.", opcode, object.interface.name, id.id);
            }
        };

        if !check_for_signature(message_desc.signature, &args) {
            panic!(
                "Unexpected signature for request {}@{}.{}: expected {:?}, got {:?}.",
                object.interface.name, id.id, message_desc.name, message_desc.signature, args
            );
        }

        // Prepare the child object
        let child_spec = if message_desc
            .signature
            .iter()
            .any(|arg| matches!(arg, ArgumentType::NewId))
        {
            if let Some((iface, version)) = child_spec {
                if let Some(child_interface) = message_desc.child_interface {
                    if !same_interface(child_interface, iface) {
                        panic!(
                            "Error when sending request {}@{}.{}: expected interface {} but got {}",
                            object.interface.name,
                            id.id,
                            message_desc.name,
                            child_interface.name,
                            iface.name
                        );
                    }
                    if version != object.version {
                        panic!(
                            "Error when sending request {}@{}.{}: expected version {} but got {}",
                            object.interface.name,
                            id.id,
                            message_desc.name,
                            object.version,
                            version
                        );
                    }
                }
                Some((iface, version))
            } else if let Some(child_interface) = message_desc.child_interface {
                Some((child_interface, object.version))
            } else {
                panic!(
                    "Error when sending request {}@{}.{}: target interface must be specified for a generic constructor.",
                    object.interface.name,
                    id.id,
                    message_desc.name
                );
            }
        } else {
            None
        };

        let child = if let Some((child_interface, child_version)) = child_spec {
            let child_serial = guard.next_serial();

            let child = Object {
                interface: child_interface,
                version: child_version,
                data: Data {
                    client_destroyed: false,
                    server_destroyed: false,
                    user_data: Arc::new(DumbObjectData),
                    serial: child_serial,
                },
            };

            let child_id = guard.map.client_insert_new(child);

            guard
                .map
                .with(child_id, |obj| {
                    obj.data.user_data = data.expect(
                        "Sending a request creating an object without providing an object data.",
                    );
                })
                .unwrap();
            Some((child_id, child_serial, child_interface))
        } else {
            None
        };

        // Prepare the message in a debug-compatible way
        let args = args.into_iter().map(|arg| {
            if let Argument::NewId(ObjectId { id: p }) = arg {
                if !p.id == 0 {
                    panic!("The newid provided when sending request {}@{}.{} is not a placeholder.", object.interface.name, id.id, message_desc.name);
                }
                if let Some((child_id, child_serial, child_interface)) = child {
                    Argument::NewId(ObjectId { id: InnerObjectId { id: child_id, serial: child_serial, interface: child_interface}})
                } else {
                    unreachable!();
                }
            } else {
                arg
            }
        }).collect::<SmallVec<[_; INLINE_ARGS]>>();

        if guard.debug {
            super::debug::print_send_message(
                object.interface.name,
                id.id,
                message_desc.name,
                &args,
            );
        }
        #[cfg(feature = "log")]
        crate::log_debug!(
            "Sending {}.{} ({})",
            id,
            message_desc.name,
            super::debug::DisplaySlice(&args)
        );

        // Send the message

        let mut msg_args = SmallVec::with_capacity(args.len());
        let mut arg_interfaces = message_desc.arg_interfaces.iter();
        for (i, arg) in args.into_iter().enumerate() {
            msg_args.push(match arg {
                Argument::Array(a) => Argument::Array(a),
                Argument::Int(i) => Argument::Int(i),
                Argument::Uint(u) => Argument::Uint(u),
                Argument::Str(s) => Argument::Str(s),
                Argument::Fixed(f) => Argument::Fixed(f),
                Argument::NewId(nid) => Argument::NewId(nid.id.id),
                Argument::Fd(f) => Argument::Fd(f),
                Argument::Object(o) => {
                    let next_interface = arg_interfaces.next().unwrap();
                    if o.id.id != 0 {
                        let arg_object = guard.get_object(o.id.clone())?;
                        if !same_interface_or_anonymous(next_interface, arg_object.interface) {
                            panic!("Request {}@{}.{} expects an argument of interface {} but {} was provided instead.", object.interface.name, id.id, message_desc.name, next_interface.name, arg_object.interface.name);
                        }
                    } else if !matches!(message_desc.signature[i], ArgumentType::Object(AllowNull::Yes)) {
                        panic!("Request {}@{}.{} expects an non-null object argument.", object.interface.name, id.id, message_desc.name);
                    }
                    Argument::Object(o.id.id)
                }
            });
        }

        let msg = Message { sender_id: id.id, opcode, args: msg_args };

        if let Err(err) = guard.socket.write_message(&msg) {
            guard.last_error = Some(WaylandError::Io(err));
        }

        // Handle destruction if relevant
        if message_desc.is_destructor {
            guard
                .map
                .with(id.id, |obj| {
                    obj.data.client_destroyed = true;
                })
                .unwrap();
            object.data.user_data.destroyed(ObjectId { id });
        }
        if let Some((child_id, child_serial, child_interface)) = child {
            Ok(ObjectId {
                id: InnerObjectId {
                    id: child_id,
                    serial: child_serial,
                    interface: child_interface,
                },
            })
        } else {
            Ok(Self::null_id())
        }
    }
src/rs/server_impl/mod.rs (line 64)
60
61
62
63
64
65
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.serial == other.serial
            && self.client_id == other.client_id
            && same_interface(self.interface, other.interface)
    }
src/rs/server_impl/handle.rs (line 392)
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    fn object_for_protocol_id(
        &self,
        client_id: InnerClientId,
        interface: &'static Interface,
        protocol_id: u32,
    ) -> Result<ObjectId, InvalidId> {
        let client = self.clients.get_client(client_id)?;
        let object = client.object_for_protocol_id(protocol_id)?;
        if same_interface(interface, object.interface) {
            Ok(ObjectId { id: object })
        } else {
            Err(InvalidId)
        }
    }
src/sys/client_impl/mod.rs (line 65)
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
    fn eq(&self, other: &Self) -> bool {
        match (&self.alive, &other.alive) {
            (Some(ref a), Some(ref b)) => {
                // this is an object we manage
                Arc::ptr_eq(a, b)
            }
            (None, None) => {
                // this is an external (un-managed) object
                self.ptr == other.ptr
                    && self.id == other.id
                    && same_interface(self.interface, other.interface)
            }
            _ => false,
        }
    }
}

impl std::cmp::Eq for InnerObjectId {}

impl std::hash::Hash for InnerObjectId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state);
        self.ptr.hash(state);
        self.alive
            .as_ref()
            .map(|arc| &**arc as *const AtomicBool)
            .unwrap_or(std::ptr::null())
            .hash(state);
    }
}

impl InnerObjectId {
    pub fn is_null(&self) -> bool {
        self.ptr.is_null()
    }

    pub fn interface(&self) -> &'static Interface {
        self.interface
    }

    pub fn protocol_id(&self) -> u32 {
        self.id
    }

    pub unsafe fn from_ptr(
        interface: &'static Interface,
        ptr: *mut wl_proxy,
    ) -> Result<Self, InvalidId> {
        // Safety: the provided pointer must be a valid wayland object
        let ptr_iface_name = unsafe {
            CStr::from_ptr(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_class, ptr))
        };
        // Safety: the code generated by wayland-scanner is valid
        let provided_iface_name = unsafe {
            CStr::from_ptr(
                interface
                    .c_ptr
                    .expect("[wayland-backend-sys] Cannot use Interface without c_ptr!")
                    .name,
            )
        };
        if ptr_iface_name != provided_iface_name {
            return Err(InvalidId);
        }

        let id = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_id, ptr);

        // Test if the proxy is managed by us.
        let is_rust_managed = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr)
            == &RUST_MANAGED as *const u8 as *const _;

        let alive = if is_rust_managed {
            // Safety: the object is rust_managed, so its user-data pointer must be valid
            let udata = unsafe {
                &*(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr)
                    as *mut ProxyUserData)
            };
            Some(udata.alive.clone())
        } else {
            None
        };

        Ok(Self { id, ptr, alive, interface })
    }

    pub fn as_ptr(&self) -> *mut wl_proxy {
        if self.alive.as_ref().map(|alive| alive.load(Ordering::Acquire)).unwrap_or(true) {
            self.ptr
        } else {
            std::ptr::null_mut()
        }
    }
}

impl std::fmt::Display for InnerObjectId {
    #[cfg_attr(coverage, no_coverage)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}@{}", self.interface.name, self.id)
    }
}

impl std::fmt::Debug for InnerObjectId {
    #[cfg_attr(coverage, no_coverage)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ObjectId({})", self)
    }
}

struct ProxyUserData {
    alive: Arc<AtomicBool>,
    data: Arc<dyn ObjectData>,
    interface: &'static Interface,
}

#[derive(Debug)]
struct ConnectionState {
    display: *mut wl_display,
    evq: *mut wl_event_queue,
    display_id: InnerObjectId,
    last_error: Option<WaylandError>,
    known_proxies: HashSet<*mut wl_proxy>,
}

unsafe impl Send for ConnectionState {}

#[derive(Debug)]
struct Dispatcher;

#[derive(Debug)]
struct Inner {
    state: Mutex<ConnectionState>,
    dispatch_lock: Mutex<Dispatcher>,
}

#[derive(Clone, Debug)]
pub struct InnerBackend {
    inner: Arc<Inner>,
}

#[derive(Clone, Debug)]
pub struct WeakInnerBackend {
    inner: Weak<Inner>,
}

impl InnerBackend {
    fn lock_state(&self) -> MutexGuard<ConnectionState> {
        self.inner.state.lock().unwrap()
    }

    pub fn downgrade(&self) -> WeakInnerBackend {
        WeakInnerBackend { inner: Arc::downgrade(&self.inner) }
    }

    pub fn display_ptr(&self) -> *mut wl_display {
        self.inner.state.lock().unwrap().display
    }
}

impl WeakInnerBackend {
    pub fn upgrade(&self) -> Option<InnerBackend> {
        Weak::upgrade(&self.inner).map(|inner| InnerBackend { inner })
    }
}

unsafe impl Send for InnerBackend {}
unsafe impl Sync for InnerBackend {}

impl InnerBackend {
    pub fn connect(stream: UnixStream) -> Result<Self, NoWaylandLib> {
        if !is_lib_available() {
            return Err(NoWaylandLib);
        }
        let display = unsafe {
            ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_connect_to_fd, stream.into_raw_fd())
        };
        if display.is_null() {
            panic!("[wayland-backend-sys] libwayland reported an allocation failure.");
        }
        // set the log trampoline
        #[cfg(feature = "log")]
        unsafe {
            ffi_dispatch!(
                WAYLAND_CLIENT_HANDLE,
                wl_log_set_handler_client,
                wl_log_trampoline_to_rust_client
            );
        }
        let display_alive = Arc::new(AtomicBool::new(true));
        Ok(Self {
            inner: Arc::new(Inner {
                state: Mutex::new(ConnectionState {
                    display,
                    evq: std::ptr::null_mut(),
                    display_id: InnerObjectId {
                        id: 1,
                        ptr: display as *mut wl_proxy,
                        alive: Some(display_alive),
                        interface: &WL_DISPLAY_INTERFACE,
                    },
                    last_error: None,
                    known_proxies: HashSet::new(),
                }),
                dispatch_lock: Mutex::new(Dispatcher),
            }),
        })
    }

    pub unsafe fn from_foreign_display(display: *mut wl_display) -> Self {
        let evq = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_create_queue, display) };
        Self {
            inner: Arc::new(Inner {
                state: Mutex::new(ConnectionState {
                    display,
                    evq,
                    display_id: InnerObjectId {
                        id: 1,
                        ptr: display as *mut wl_proxy,
                        alive: None,
                        interface: &WL_DISPLAY_INTERFACE,
                    },
                    last_error: None,
                    known_proxies: HashSet::new(),
                }),
                dispatch_lock: Mutex::new(Dispatcher),
            }),
        }
    }

    pub fn flush(&self) -> Result<(), WaylandError> {
        let mut guard = self.lock_state();
        guard.no_last_error()?;
        let ret = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_flush, guard.display) };
        if ret < 0 {
            Err(guard.store_if_not_wouldblock_and_return_error(std::io::Error::last_os_error()))
        } else {
            Ok(())
        }
    }

    pub fn dispatch_inner_queue(&self) -> Result<usize, WaylandError> {
        self.inner.dispatch_lock.lock().unwrap().dispatch_pending(self.inner.clone())
    }
}

impl ConnectionState {
    #[inline]
    fn no_last_error(&self) -> Result<(), WaylandError> {
        if let Some(ref err) = self.last_error {
            Err(err.clone())
        } else {
            Ok(())
        }
    }

    #[inline]
    fn store_and_return_error(&mut self, err: std::io::Error) -> WaylandError {
        // check if it was actually a protocol error
        let err = if err.raw_os_error() == Some(nix::errno::Errno::EPROTO as i32) {
            let mut object_id = 0;
            let mut interface = std::ptr::null();
            let code = unsafe {
                ffi_dispatch!(
                    WAYLAND_CLIENT_HANDLE,
                    wl_display_get_protocol_error,
                    self.display,
                    &mut interface,
                    &mut object_id
                )
            };
            let object_interface = unsafe {
                if interface.is_null() {
                    String::new()
                } else {
                    let cstr = std::ffi::CStr::from_ptr((*interface).name);
                    cstr.to_string_lossy().into()
                }
            };
            WaylandError::Protocol(ProtocolError {
                code,
                object_id,
                object_interface,
                message: String::new(),
            })
        } else {
            WaylandError::Io(err)
        };
        crate::log_error!("{}", err);
        self.last_error = Some(err.clone());
        err
    }

    #[inline]
    fn store_if_not_wouldblock_and_return_error(&mut self, e: std::io::Error) -> WaylandError {
        if e.kind() != std::io::ErrorKind::WouldBlock {
            self.store_and_return_error(e)
        } else {
            e.into()
        }
    }
}

impl Dispatcher {
    fn dispatch_pending(&self, inner: Arc<Inner>) -> Result<usize, WaylandError> {
        let (display, evq) = {
            let guard = inner.state.lock().unwrap();
            (guard.display, guard.evq)
        };
        let backend = Backend { backend: InnerBackend { inner } };

        // We erase the lifetime of the Handle to be able to store it in the tls,
        // it's safe as it'll only last until the end of this function call anyway
        let ret = BACKEND.set(&backend, || unsafe {
            if evq.is_null() {
                ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_dispatch_pending, display)
            } else {
                ffi_dispatch!(
                    WAYLAND_CLIENT_HANDLE,
                    wl_display_dispatch_queue_pending,
                    display,
                    evq
                )
            }
        });
        if ret < 0 {
            Err(backend
                .backend
                .inner
                .state
                .lock()
                .unwrap()
                .store_if_not_wouldblock_and_return_error(std::io::Error::last_os_error()))
        } else {
            Ok(ret as usize)
        }
    }
}

#[derive(Debug)]
pub struct InnerReadEventsGuard {
    inner: Arc<Inner>,
    display: *mut wl_display,
    done: bool,
}

impl InnerReadEventsGuard {
    pub fn try_new(backend: InnerBackend) -> Result<Self, WaylandError> {
        let (display, evq) = {
            let guard = backend.lock_state();
            (guard.display, guard.evq)
        };
        let dispatcher = backend.inner.dispatch_lock.lock().unwrap();
        // do the prepare_read() and dispatch as necessary
        loop {
            let ret = unsafe {
                if evq.is_null() {
                    ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_prepare_read, display)
                } else {
                    ffi_dispatch!(
                        WAYLAND_CLIENT_HANDLE,
                        wl_display_prepare_read_queue,
                        display,
                        evq
                    )
                }
            };
            if ret < 0 {
                dispatcher.dispatch_pending(backend.inner.clone())?;
            } else {
                break;
            }
        }
        std::mem::drop(dispatcher);

        // prepare_read is done, we are ready
        Ok(Self { inner: backend.inner, display, done: false })
    }

    pub fn connection_fd(&self) -> BorrowedFd {
        unsafe {
            BorrowedFd::borrow_raw(ffi_dispatch!(
                WAYLAND_CLIENT_HANDLE,
                wl_display_get_fd,
                self.display
            ))
        }
    }

    pub fn read(mut self) -> Result<usize, WaylandError> {
        self.done = true;
        let ret =
            unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_read_events, self.display) };
        if ret < 0 {
            // we have done the reading, and there is an error
            Err(self
                .inner
                .state
                .lock()
                .unwrap()
                .store_if_not_wouldblock_and_return_error(std::io::Error::last_os_error()))
        } else {
            // the read occured, dispatch pending events
            self.inner.dispatch_lock.lock().unwrap().dispatch_pending(self.inner.clone())
        }
    }
}

impl Drop for InnerReadEventsGuard {
    fn drop(&mut self) {
        if !self.done {
            unsafe {
                ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_cancel_read, self.display);
            }
        }
    }
}

impl InnerBackend {
    pub fn display_id(&self) -> ObjectId {
        ObjectId { id: self.lock_state().display_id.clone() }
    }

    pub fn last_error(&self) -> Option<WaylandError> {
        self.lock_state().last_error.clone()
    }

    pub fn info(&self, ObjectId { id }: ObjectId) -> Result<ObjectInfo, InvalidId> {
        if !id.alive.as_ref().map(|a| a.load(Ordering::Acquire)).unwrap_or(true) || id.ptr.is_null()
        {
            return Err(InvalidId);
        }

        let version = if id.id == 1 {
            // special case the display, because libwayland returns a version of 0 for it
            1
        } else {
            unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, id.ptr) }
        };

        Ok(ObjectInfo { id: id.id, interface: id.interface, version })
    }

    pub fn null_id() -> ObjectId {
        ObjectId {
            id: InnerObjectId {
                ptr: std::ptr::null_mut(),
                interface: &ANONYMOUS_INTERFACE,
                id: 0,
                alive: None,
            },
        }
    }

    pub fn send_request(
        &self,
        Message { sender_id: ObjectId { id }, opcode, args }: Message<ObjectId, RawFd>,
        data: Option<Arc<dyn ObjectData>>,
        child_spec: Option<(&'static Interface, u32)>,
    ) -> Result<ObjectId, InvalidId> {
        let mut guard = self.lock_state();
        if !id.alive.as_ref().map(|a| a.load(Ordering::Acquire)).unwrap_or(true) || id.ptr.is_null()
        {
            return Err(InvalidId);
        }
        let parent_version = if id.id == 1 {
            1
        } else {
            unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, id.ptr) }
        };
        // check that the argument list is valid
        let message_desc = match id.interface.requests.get(opcode as usize) {
            Some(msg) => msg,
            None => {
                panic!("Unknown opcode {} for object {}@{}.", opcode, id.interface.name, id.id);
            }
        };
        if !check_for_signature(message_desc.signature, &args) {
            panic!(
                "Unexpected signature for request {}@{}.{}: expected {:?}, got {:?}.",
                id.interface.name, id.id, message_desc.name, message_desc.signature, args
            );
        }

        // Prepare the child object data
        let child_spec = if message_desc
            .signature
            .iter()
            .any(|arg| matches!(arg, ArgumentType::NewId))
        {
            if let Some((iface, version)) = child_spec {
                if let Some(child_interface) = message_desc.child_interface {
                    if !same_interface(child_interface, iface) {
                        panic!(
                            "Wrong placeholder used when sending request {}@{}.{}: expected interface {} but got {}",
                            id.interface.name,
                            id.id,
                            message_desc.name,
                            child_interface.name,
                            iface.name
                        );
                    }
                    if version != parent_version {
                        panic!(
                            "Wrong placeholder used when sending request {}@{}.{}: expected version {} but got {}",
                            id.interface.name,
                            id.id,
                            message_desc.name,
                            parent_version,
                            version
                        );
                    }
                }
                Some((iface, version))
            } else if let Some(child_interface) = message_desc.child_interface {
                Some((child_interface, parent_version))
            } else {
                panic!(
                    "Wrong placeholder used when sending request {}@{}.{}: target interface must be specified for a generic constructor.",
                    id.interface.name,
                    id.id,
                    message_desc.name
                );
            }
        } else {
            None
        };

        let child_interface_ptr = child_spec
            .as_ref()
            .map(|(i, _)| {
                i.c_ptr.expect("[wayland-backend-sys] Cannot use Interface without c_ptr!")
                    as *const _
            })
            .unwrap_or(std::ptr::null());
        let child_version = child_spec.as_ref().map(|(_, v)| *v).unwrap_or(parent_version);

        // check that all input objects are valid and create the [wl_argument]
        let mut argument_list = SmallVec::<[wl_argument; 4]>::with_capacity(args.len());
        let mut arg_interfaces = message_desc.arg_interfaces.iter();
        for (i, arg) in args.iter().enumerate() {
            match *arg {
                Argument::Uint(u) => argument_list.push(wl_argument { u }),
                Argument::Int(i) => argument_list.push(wl_argument { i }),
                Argument::Fixed(f) => argument_list.push(wl_argument { f }),
                Argument::Fd(h) => argument_list.push(wl_argument { h }),
                Argument::Array(ref a) => {
                    let a = Box::new(wl_array {
                        size: a.len(),
                        alloc: a.len(),
                        data: a.as_ptr() as *mut _,
                    });
                    argument_list.push(wl_argument { a: Box::into_raw(a) })
                }
                Argument::Str(Some(ref s)) => argument_list.push(wl_argument { s: s.as_ptr() }),
                Argument::Str(None) => argument_list.push(wl_argument { s: std::ptr::null() }),
                Argument::Object(ref o) => {
                    let next_interface = arg_interfaces.next().unwrap();
                    if !o.id.ptr.is_null() {
                        if !id.alive.as_ref().map(|a| a.load(Ordering::Acquire)).unwrap_or(true) {
                            unsafe { free_arrays(message_desc.signature, &argument_list) };
                            return Err(InvalidId);
                        }
                        if !same_interface(next_interface, o.id.interface) {
                            panic!("Request {}@{}.{} expects an argument of interface {} but {} was provided instead.", id.interface.name, id.id, message_desc.name, next_interface.name, o.id.interface.name);
                        }
                    } else if !matches!(
                        message_desc.signature[i],
                        ArgumentType::Object(AllowNull::Yes)
                    ) {
                        panic!(
                            "Request {}@{}.{} expects an non-null object argument.",
                            id.interface.name, id.id, message_desc.name
                        );
                    }
                    argument_list.push(wl_argument { o: o.id.ptr as *const _ })
                }
                Argument::NewId(_) => argument_list.push(wl_argument { n: 0 }),
            }
        }

        let ret = if guard.evq.is_null() || child_spec.is_none() {
            unsafe {
                ffi_dispatch!(
                    WAYLAND_CLIENT_HANDLE,
                    wl_proxy_marshal_array_constructor_versioned,
                    id.ptr,
                    opcode as u32,
                    argument_list.as_mut_ptr(),
                    child_interface_ptr,
                    child_version
                )
            }
        } else {
            // We are a guest Backend, need to use a wrapper
            unsafe {
                let wrapped_ptr =
                    ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_create_wrapper, id.ptr);
                ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_queue, wrapped_ptr, guard.evq);
                let ret = ffi_dispatch!(
                    WAYLAND_CLIENT_HANDLE,
                    wl_proxy_marshal_array_constructor_versioned,
                    wrapped_ptr,
                    opcode as u32,
                    argument_list.as_mut_ptr(),
                    child_interface_ptr,
                    child_version
                );
                ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_wrapper_destroy, wrapped_ptr);
                ret
            }
        };

        unsafe {
            free_arrays(message_desc.signature, &argument_list);
        }

        if ret.is_null() && child_spec.is_some() {
            panic!("[wayland-backend-sys] libwayland reported an allocation failure.");
        }

        // initialize the proxy
        let child_id = if let Some((child_interface, _)) = child_spec {
            let child_alive = Arc::new(AtomicBool::new(true));
            let child_id = ObjectId {
                id: InnerObjectId {
                    ptr: ret,
                    alive: Some(child_alive.clone()),
                    id: unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_id, ret) },
                    interface: child_interface,
                },
            };
            let child_udata = match data {
                Some(data) => {
                    Box::new(ProxyUserData { alive: child_alive, data, interface: child_interface })
                }
                None => {
                    // we destroy this proxy before panicking to avoid a leak, as it cannot be destroyed by the
                    // main destructor given it does not yet have a proper user-data
                    unsafe {
                        ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, ret);
                    }
                    panic!(
                        "Sending a request creating an object without providing an object data."
                    );
                }
            };
            guard.known_proxies.insert(ret);
            unsafe {
                ffi_dispatch!(
                    WAYLAND_CLIENT_HANDLE,
                    wl_proxy_add_dispatcher,
                    ret,
                    dispatcher_func,
                    &RUST_MANAGED as *const u8 as *const c_void,
                    Box::into_raw(child_udata) as *mut c_void
                );
            }
            child_id
        } else {
            Self::null_id()
        };

        if message_desc.is_destructor {
            if let Some(ref alive) = id.alive {
                let udata = unsafe {
                    Box::from_raw(ffi_dispatch!(
                        WAYLAND_CLIENT_HANDLE,
                        wl_proxy_get_user_data,
                        id.ptr
                    ) as *mut ProxyUserData)
                };
                unsafe {
                    ffi_dispatch!(
                        WAYLAND_CLIENT_HANDLE,
                        wl_proxy_set_user_data,
                        id.ptr,
                        std::ptr::null_mut()
                    );
                }
                alive.store(false, Ordering::Release);
                udata.data.destroyed(ObjectId { id: id.clone() });
            }
            guard.known_proxies.remove(&id.ptr);
            unsafe {
                ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, id.ptr);
            }
        }

        Ok(child_id)
    }

    pub fn get_data(&self, ObjectId { id }: ObjectId) -> Result<Arc<dyn ObjectData>, InvalidId> {
        if !id.alive.as_ref().map(|a| a.load(Ordering::Acquire)).unwrap_or(false) {
            return Err(InvalidId);
        }

        if id.id == 1 {
            // special case the display whose object data is not accessible
            return Ok(Arc::new(DumbObjectData));
        }

        let udata = unsafe {
            &*(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, id.ptr)
                as *mut ProxyUserData)
        };
        Ok(udata.data.clone())
    }

    pub fn set_data(
        &self,
        ObjectId { id }: ObjectId,
        data: Arc<dyn ObjectData>,
    ) -> Result<(), InvalidId> {
        if !id.alive.as_ref().map(|a| a.load(Ordering::Acquire)).unwrap_or(false) {
            return Err(InvalidId);
        }

        // Cannot touch the user_data of the display
        if id.id == 1 {
            return Err(InvalidId);
        }

        let udata = unsafe {
            &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, id.ptr)
                as *mut ProxyUserData)
        };

        udata.data = data;

        Ok(())
    }
}

unsafe extern "C" fn dispatcher_func(
    _: *const c_void,
    proxy: *mut c_void,
    opcode: u32,
    _: *const wl_message,
    args: *const wl_argument,
) -> c_int {
    let proxy = proxy as *mut wl_proxy;

    // Safety: if our dispatcher fun is called, then the associated proxy must be rust_managed and have a valid user_data
    let udata_ptr = unsafe {
        ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, proxy) as *mut ProxyUserData
    };
    let udata = unsafe { &mut *udata_ptr };

    let interface = udata.interface;
    let message_desc = match interface.events.get(opcode as usize) {
        Some(desc) => desc,
        None => {
            crate::log_error!("Unknown event opcode {} for interface {}.", opcode, interface.name);
            return -1;
        }
    };

    let mut parsed_args =
        SmallVec::<[Argument<ObjectId, OwnedFd>; 4]>::with_capacity(message_desc.signature.len());
    let mut arg_interfaces = message_desc.arg_interfaces.iter().copied();
    let mut created = None;
    // Safety (args deference): the args array provided by libwayland is well-formed
    for (i, typ) in message_desc.signature.iter().enumerate() {
        match typ {
            ArgumentType::Uint => parsed_args.push(Argument::Uint(unsafe { (*args.add(i)).u })),
            ArgumentType::Int => parsed_args.push(Argument::Int(unsafe { (*args.add(i)).i })),
            ArgumentType::Fixed => parsed_args.push(Argument::Fixed(unsafe { (*args.add(i)).f })),
            ArgumentType::Fd => {
                parsed_args.push(Argument::Fd(unsafe { OwnedFd::from_raw_fd((*args.add(i)).h) }))
            }
            ArgumentType::Array => {
                let array = unsafe { &*((*args.add(i)).a) };
                // Safety: the array provided by libwayland must be valid
                let content =
                    unsafe { std::slice::from_raw_parts(array.data as *mut u8, array.size) };
                parsed_args.push(Argument::Array(Box::new(content.into())));
            }
            ArgumentType::Str(_) => {
                let ptr = unsafe { (*args.add(i)).s };
                // Safety: the c-string provided by libwayland must be valid
                if !ptr.is_null() {
                    let cstr = unsafe { std::ffi::CStr::from_ptr(ptr) };
                    parsed_args.push(Argument::Str(Some(Box::new(cstr.into()))));
                } else {
                    parsed_args.push(Argument::Str(None));
                }
            }
            ArgumentType::Object(_) => {
                let obj = unsafe { (*args.add(i)).o as *mut wl_proxy };
                if !obj.is_null() {
                    // retrieve the object relevant info
                    let obj_id = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_id, obj);
                    // check if this is a local or distant proxy
                    let next_interface = arg_interfaces.next().unwrap_or(&ANONYMOUS_INTERFACE);
                    let listener = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, obj);
                    if listener == &RUST_MANAGED as *const u8 as *const c_void {
                        // Safety: the object is rust-managed, its user-data must be valid
                        let obj_udata = unsafe {
                            &*(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, obj)
                                as *mut ProxyUserData)
                        };
                        if !same_interface(next_interface, obj_udata.interface) {
                            crate::log_error!(
                                "Received object {}@{} in {}.{} but expected interface {}.",
                                obj_udata.interface.name,
                                obj_id,
                                interface.name,
                                message_desc.name,
                                next_interface.name,
                            );
                            return -1;
                        }
                        parsed_args.push(Argument::Object(ObjectId {
                            id: InnerObjectId {
                                alive: Some(obj_udata.alive.clone()),
                                ptr: obj,
                                id: obj_id,
                                interface: obj_udata.interface,
                            },
                        }));
                    } else {
                        parsed_args.push(Argument::Object(ObjectId {
                            id: InnerObjectId {
                                alive: None,
                                id: obj_id,
                                ptr: obj,
                                interface: next_interface,
                            },
                        }));
                    }
                } else {
                    // libwayland-client.so checks nulls for us
                    parsed_args.push(Argument::Object(ObjectId {
                        id: InnerObjectId {
                            alive: None,
                            id: 0,
                            ptr: std::ptr::null_mut(),
                            interface: &ANONYMOUS_INTERFACE,
                        },
                    }))
                }
            }
            ArgumentType::NewId => {
                let obj = unsafe { (*args.add(i)).o as *mut wl_proxy };
                // this is a newid, it needs to be initialized
                if !obj.is_null() {
                    let child_interface = message_desc.child_interface.unwrap_or_else(|| {
                        crate::log_warn!(
                            "Event {}.{} creates an anonymous object.",
                            interface.name,
                            opcode
                        );
                        &ANONYMOUS_INTERFACE
                    });
                    let child_alive = Arc::new(AtomicBool::new(true));
                    let child_id = InnerObjectId {
                        ptr: obj,
                        alive: Some(child_alive.clone()),
                        id: ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_id, obj),
                        interface: child_interface,
                    };
                    let child_udata = Box::into_raw(Box::new(ProxyUserData {
                        alive: child_alive,
                        data: Arc::new(UninitObjectData),
                        interface: child_interface,
                    }));
                    created = Some((child_id.clone(), child_udata));
                    ffi_dispatch!(
                        WAYLAND_CLIENT_HANDLE,
                        wl_proxy_add_dispatcher,
                        obj,
                        dispatcher_func,
                        &RUST_MANAGED as *const u8 as *const c_void,
                        child_udata as *mut c_void
                    );
                    parsed_args.push(Argument::NewId(ObjectId { id: child_id }));
                } else {
                    parsed_args.push(Argument::NewId(ObjectId {
                        id: InnerObjectId {
                            id: 0,
                            ptr: std::ptr::null_mut(),
                            alive: None,
                            interface: &ANONYMOUS_INTERFACE,
                        },
                    }))
                }
            }
        }
    }

    let proxy_id = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_id, proxy);
    let id = ObjectId {
        id: InnerObjectId {
            alive: Some(udata.alive.clone()),
            ptr: proxy,
            id: proxy_id,
            interface: udata.interface,
        },
    };

    let ret = BACKEND.with(|backend| {
        let mut guard = backend.backend.lock_state();
        if let Some((ref new_id, _)) = created {
            guard.known_proxies.insert(new_id.ptr);
        }
        if message_desc.is_destructor {
            guard.known_proxies.remove(&proxy);
        }
        std::mem::drop(guard);
        udata.data.clone().event(
            backend,
            Message { sender_id: id.clone(), opcode: opcode as u16, args: parsed_args },
        )
    });

    if message_desc.is_destructor {
        // Safety: the udata_ptr must be valid as we are in a rust-managed object, and we are done with using udata
        let udata = unsafe { Box::from_raw(udata_ptr) };
        ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, proxy, std::ptr::null_mut());
        udata.alive.store(false, Ordering::Release);
        udata.data.destroyed(id);
        ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, proxy);
    }

    match (created, ret) {
        (Some((_, child_udata_ptr)), Some(child_data)) => {
            // Safety: child_udata_ptr is valid, we created it earlier
            unsafe {
                (*child_udata_ptr).data = child_data;
            }
        }
        (Some((child_id, _)), None) => {
            panic!("Callback creating object {} did not provide any object data.", child_id);
        }
        (None, Some(_)) => {
            panic!("An object data was returned from a callback not creating any object");
        }
        (None, None) => {}
    }

    0
}
src/sys/server_impl/mod.rs (line 151)
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
    pub unsafe fn from_ptr(
        interface: Option<&'static Interface>,
        ptr: *mut wl_resource,
    ) -> Result<InnerObjectId, InvalidId> {
        let id = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_id, ptr);

        // This is a horrible back to work around the fact that it is not possible to check if the
        // resource implementation is RUST_MANAGED without knowing the interface of that object...
        let is_rust_managed = {
            // wl_resource_instance_of uses wl_interface_equals, which only checks that the interface name
            // is correct, so we create a temporary dummy wl_interface with the correct name so that the
            // check only actually verifies that the object is RUST_MANAGED
            let iface_name = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_class, ptr);
            let dummy_iface = wl_interface {
                name: iface_name,
                version: 0,
                request_count: 0,
                event_count: 0,
                requests: std::ptr::null(),
                events: std::ptr::null(),
            };
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_instance_of,
                ptr,
                &dummy_iface,
                &RUST_MANAGED as *const u8 as *const _
            ) != 0
        };

        if is_rust_managed {
            // Using () instead of the type parameter here is safe, because:
            // 1) ResourceUserData is #[repr(C)], so its layout does not depend on D
            // 2) we are only accessing the field `.alive`, which type is independent of D
            //
            let udata = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_user_data, ptr)
                as *mut ResourceUserData<()>;
            let alive = unsafe { (*udata).alive.clone() };
            let udata_iface = unsafe { (*udata).interface };
            if let Some(iface) = interface {
                if !same_interface(iface, udata_iface) {
                    return Err(InvalidId);
                }
            }
            Ok(InnerObjectId { id, ptr, alive, interface: udata_iface })
        } else if let Some(interface) = interface {
            let iface_c_ptr =
                interface.c_ptr.expect("[wayland-backend-sys] Cannot use Interface without c_ptr!");
            // Safety: the provided pointer must be a valid wayland object
            let ptr_iface_name = unsafe {
                CStr::from_ptr(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_class, ptr))
            };
            // Safety: the code generated by wayland-scanner is valid
            let provided_iface_name = unsafe { CStr::from_ptr(iface_c_ptr.name) };
            if ptr_iface_name != provided_iface_name {
                return Err(InvalidId);
            }
            // On external resource, we use the wl_resource_add_destroy_listener mechanism to track their liveness
            let listener = ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_get_destroy_listener,
                ptr,
                external_resource_destroy_notify
            );
            let alive = if listener.is_null() {
                // The listener needs to be initialized
                let alive = Arc::new(AtomicBool::new(true));
                let data = Box::into_raw(Box::new(ExternalResourceData { alive: alive.clone() }));
                let listener = signal::rust_listener_create(external_resource_destroy_notify);
                // Safety: we just created listener and client_data, they are valid
                unsafe {
                    signal::rust_listener_set_user_data(listener, data as *mut c_void);
                }
                ffi_dispatch!(
                    WAYLAND_SERVER_HANDLE,
                    wl_resource_add_destroy_listener,
                    ptr,
                    listener
                );
                alive
            } else {
                unsafe {
                    let data =
                        signal::rust_listener_get_user_data(listener) as *mut ExternalResourceData;
                    (*data).alive.clone()
                }
            };
            Ok(InnerObjectId { id, ptr, alive, interface })
        } else {
            Err(InvalidId)
        }
    }

    pub fn as_ptr(&self) -> *mut wl_resource {
        if self.alive.load(Ordering::Acquire) {
            self.ptr
        } else {
            std::ptr::null_mut()
        }
    }
}

struct ExternalResourceData {
    alive: Arc<AtomicBool>,
}

unsafe extern "C" fn external_resource_destroy_notify(listener: *mut wl_listener, _: *mut c_void) {
    // Safety: if this function is invoked by libwayland its arguments must be valid
    let data = unsafe {
        Box::from_raw(signal::rust_listener_get_user_data(listener) as *mut ExternalResourceData)
    };
    unsafe {
        signal::rust_listener_destroy(listener);
    }
    data.alive.store(false, Ordering::Release);
}

/// An id of a client connected to the server.
#[derive(Debug, Clone)]
pub struct InnerClientId {
    ptr: *mut wl_client,
    alive: Arc<AtomicBool>,
}

unsafe impl Send for InnerClientId {}
unsafe impl Sync for InnerClientId {}

impl std::cmp::PartialEq for InnerClientId {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.alive, &other.alive)
    }
}

impl std::cmp::Eq for InnerClientId {}

impl std::hash::Hash for InnerClientId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        (&*self.alive as *const AtomicBool).hash(state)
    }
}

/// The ID of a global
#[derive(Debug, Clone)]
pub struct InnerGlobalId {
    ptr: *mut wl_global,
    alive: Arc<AtomicBool>,
}

unsafe impl Send for InnerGlobalId {}
unsafe impl Sync for InnerGlobalId {}

impl std::cmp::PartialEq for InnerGlobalId {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.alive, &other.alive)
    }
}

impl std::cmp::Eq for InnerGlobalId {}

impl std::hash::Hash for InnerGlobalId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        (&*self.alive as *const AtomicBool).hash(state)
    }
}

#[repr(C)]
struct ResourceUserData<D> {
    alive: Arc<AtomicBool>,
    data: Arc<dyn ObjectData<D>>,
    interface: &'static Interface,
}

struct ClientUserData {
    data: Arc<dyn ClientData>,
    alive: Arc<AtomicBool>,
}

struct GlobalUserData<D> {
    handler: Arc<dyn GlobalHandler<D>>,
    interface: &'static Interface,
    version: u32,
    disabled: bool,
    alive: Arc<AtomicBool>,
    ptr: *mut wl_global,
}

#[derive(Debug)]
pub struct State<D: 'static> {
    display: *mut wl_display,
    pending_destructors: Vec<PendingDestructor<D>>,
    _data: std::marker::PhantomData<fn(&mut D)>,
    known_globals: Vec<InnerGlobalId>,
}

unsafe impl<D> Send for State<D> {}

#[derive(Debug)]
pub struct InnerBackend<D: 'static> {
    state: Arc<Mutex<State<D>>>,
    display_ptr: *mut wl_display,
}

unsafe impl<D> Send for InnerBackend<D> {}
unsafe impl<D> Sync for InnerBackend<D> {}

impl<D> InnerBackend<D> {
    pub fn new() -> Result<Self, InitError> {
        if !is_lib_available() {
            return Err(InitError::NoWaylandLib);
        }

        let display = unsafe { ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_create) };
        if display.is_null() {
            panic!("[wayland-backend-sys] libwayland reported an allocation failure.");
        }

        #[cfg(feature = "log")]
        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_log_set_handler_server,
                wl_log_trampoline_to_rust_server
            )
        };

        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_display_set_global_filter,
                display,
                global_filter::<D>,
                std::ptr::null_mut()
            );
        }

        Ok(Self {
            state: Arc::new(Mutex::new(State {
                display,
                pending_destructors: Vec::new(),
                _data: std::marker::PhantomData,
                known_globals: Vec::new(),
            })),
            display_ptr: display,
        })
    }

    pub fn flush(&mut self, client: Option<ClientId>) -> std::io::Result<()> {
        let mut state = self.state.lock().unwrap();
        if let Some(ClientId { id: client_id }) = client {
            if client_id.alive.load(Ordering::Acquire) {
                unsafe { ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_client_flush, client_id.ptr) }
            }
        } else {
            // wl_display_flush_clients might invoke destructors
            PENDING_DESTRUCTORS.set(
                &(&mut state.pending_destructors as *mut _ as *mut _),
                || unsafe {
                    ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_flush_clients, state.display);
                },
            );
        }
        Ok(())
    }

    pub fn handle(&self) -> Handle {
        Handle { handle: InnerHandle { state: self.state.clone() as Arc<_> } }
    }

    pub fn poll_fd(&self) -> BorrowedFd {
        unsafe {
            let evl_ptr =
                ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_get_event_loop, self.display_ptr);
            BorrowedFd::borrow_raw(ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_event_loop_get_fd,
                evl_ptr
            ))
        }
    }

    pub fn dispatch_client(
        &mut self,
        data: &mut D,
        _client_id: InnerClientId,
    ) -> std::io::Result<usize> {
        self.dispatch_all_clients(data)
    }

    pub fn dispatch_all_clients(&mut self, data: &mut D) -> std::io::Result<usize> {
        let state = self.state.clone() as Arc<Mutex<dyn ErasedState + Send>>;
        let display = self.display_ptr;
        let ret = HANDLE.set(&(state, data as *mut _ as *mut c_void), || unsafe {
            let evl_ptr = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_get_event_loop, display);
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_event_loop_dispatch, evl_ptr, 0)
        });

        let pending_destructors =
            std::mem::take(&mut self.state.lock().unwrap().pending_destructors);
        for (object, client_id, object_id) in pending_destructors {
            object.destroyed(data, client_id, object_id);
        }

        if ret < 0 {
            Err(std::io::Error::last_os_error())
        } else {
            Ok(ret as usize)
        }
    }
}

impl<D> Drop for State<D> {
    fn drop(&mut self) {
        // wl_display_destroy_clients may result in the destruction of some wayland objects. Pending
        // destructors are queued up inside the PENDING_DESTRUCTORS scoped global. We need to set the scoped
        // global in order for destructors to be queued up properly.
        PENDING_DESTRUCTORS.set(&(&mut self.pending_destructors as *mut _ as *mut _), || unsafe {
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_destroy_clients, self.display);
        });

        let known_globals = std::mem::take(&mut self.known_globals);
        for global in known_globals {
            unsafe {
                ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_destroy, global.ptr);
            }
        }

        unsafe {
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_destroy, self.display);
        }
    }
}

#[derive(Clone)]
pub struct InnerHandle {
    state: Arc<Mutex<dyn ErasedState + Send>>,
}

impl std::fmt::Debug for InnerHandle {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_struct("InnerHandle[sys]").finish_non_exhaustive()
    }
}

#[derive(Clone)]
pub struct WeakInnerHandle {
    pub(crate) state: Weak<Mutex<dyn ErasedState + Send>>,
}

impl std::fmt::Debug for WeakInnerHandle {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_struct("WeakInnerHandle[sys]").finish_non_exhaustive()
    }
}

impl WeakInnerHandle {
    pub fn upgrade(&self) -> Option<InnerHandle> {
        self.state.upgrade().map(|state| InnerHandle { state })
    }
}

impl InnerHandle {
    pub fn downgrade(&self) -> WeakInnerHandle {
        WeakInnerHandle { state: Arc::downgrade(&self.state) }
    }

    pub fn object_info(&self, id: InnerObjectId) -> Result<ObjectInfo, InvalidId> {
        self.state.lock().unwrap().object_info(id)
    }

    pub fn insert_client(
        &self,
        stream: UnixStream,
        data: Arc<dyn ClientData>,
    ) -> std::io::Result<InnerClientId> {
        self.state.lock().unwrap().insert_client(stream, data)
    }

    pub fn get_client(&self, id: InnerObjectId) -> Result<ClientId, InvalidId> {
        self.state.lock().unwrap().get_client(id)
    }

    pub fn get_client_data(&self, id: InnerClientId) -> Result<Arc<dyn ClientData>, InvalidId> {
        self.state.lock().unwrap().get_client_data(id)
    }

    pub fn get_client_credentials(&self, id: InnerClientId) -> Result<Credentials, InvalidId> {
        self.state.lock().unwrap().get_client_credentials(id)
    }

    pub fn with_all_clients(&self, mut f: impl FnMut(ClientId)) {
        self.state.lock().unwrap().with_all_clients(&mut f)
    }

    pub fn with_all_objects_for(
        &self,
        client_id: InnerClientId,
        mut f: impl FnMut(ObjectId),
    ) -> Result<(), InvalidId> {
        self.state.lock().unwrap().with_all_objects_for(client_id, &mut f)
    }

    pub fn object_for_protocol_id(
        &self,
        client_id: InnerClientId,
        interface: &'static Interface,
        protocol_id: u32,
    ) -> Result<ObjectId, InvalidId> {
        self.state.lock().unwrap().object_for_protocol_id(client_id, interface, protocol_id)
    }

    pub fn create_object<D: 'static>(
        &self,
        client: InnerClientId,
        interface: &'static Interface,
        version: u32,
        data: Arc<dyn ObjectData<D>>,
    ) -> Result<ObjectId, InvalidId> {
        let mut state = self.state.lock().unwrap();
        // Keep this guard alive while the code is run to protect the C state
        let _state = (&mut *state as &mut dyn ErasedState)
            .downcast_mut::<State<D>>()
            .expect("Wrong type parameter passed to Handle::create_object().");

        if !client.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let interface_ptr =
            interface.c_ptr.expect("Interface without c_ptr are unsupported by the sys backend.");

        let resource = unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_create,
                client.ptr,
                interface_ptr,
                version as i32,
                0
            )
        };

        Ok(ObjectId { id: unsafe { init_resource(resource, interface, Some(data)).0 } })
    }

    pub fn null_id() -> ObjectId {
        ObjectId {
            id: InnerObjectId {
                ptr: std::ptr::null_mut(),
                id: 0,
                alive: Arc::new(AtomicBool::new(false)),
                interface: &ANONYMOUS_INTERFACE,
            },
        }
    }

    pub fn send_event(&self, msg: Message<ObjectId, RawFd>) -> Result<(), InvalidId> {
        self.state.lock().unwrap().send_event(msg)
    }

    pub fn get_object_data<D: 'static>(
        &self,
        id: InnerObjectId,
    ) -> Result<Arc<dyn ObjectData<D>>, InvalidId> {
        let mut state = self.state.lock().unwrap();
        // Keep this guard alive while the code is run to protect the C state
        let _state = (&mut *state as &mut dyn ErasedState)
            .downcast_mut::<State<D>>()
            .expect("Wrong type parameter passed to Handle::get_object_data().");

        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let iface_c_ptr =
            id.interface.c_ptr.expect("[wayland-backend-sys] Cannot use Interface without c_ptr!");
        let is_managed = unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_instance_of,
                id.ptr,
                iface_c_ptr,
                &RUST_MANAGED as *const u8 as *const _
            ) != 0
        };
        if !is_managed {
            return Err(InvalidId);
        }

        let udata = unsafe {
            &*(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_user_data, id.ptr)
                as *mut ResourceUserData<D>)
        };

        Ok(udata.data.clone())
    }

    pub fn get_object_data_any(
        &self,
        id: InnerObjectId,
    ) -> Result<Arc<dyn std::any::Any + Send + Sync>, InvalidId> {
        self.state.lock().unwrap().get_object_data_any(id)
    }

    pub fn set_object_data<D: 'static>(
        &self,
        id: InnerObjectId,
        data: Arc<dyn ObjectData<D>>,
    ) -> Result<(), InvalidId> {
        let mut state = self.state.lock().unwrap();
        // Keep this guard alive while the code is run to protect the C state
        let _state = (&mut *state as &mut dyn ErasedState)
            .downcast_mut::<State<D>>()
            .expect("Wrong type parameter passed to Handle::set_object_data().");

        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let iface_c_ptr =
            id.interface.c_ptr.expect("[wayland-backend-sys] Cannot use Interface without c_ptr!");
        let is_managed = unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_instance_of,
                id.ptr,
                iface_c_ptr,
                &RUST_MANAGED as *const u8 as *const _
            ) != 0
        };
        if !is_managed {
            return Err(InvalidId);
        }

        let udata = unsafe {
            &mut *(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_user_data, id.ptr)
                as *mut ResourceUserData<D>)
        };

        udata.data = data;

        Ok(())
    }

    pub fn post_error(&self, object_id: InnerObjectId, error_code: u32, message: CString) {
        self.state.lock().unwrap().post_error(object_id, error_code, message)
    }

    pub fn kill_client(&self, client_id: InnerClientId, reason: DisconnectReason) {
        self.state.lock().unwrap().kill_client(client_id, reason)
    }

    pub fn create_global<D: 'static>(
        &self,
        interface: &'static Interface,
        version: u32,
        handler: Arc<dyn GlobalHandler<D>>,
    ) -> InnerGlobalId {
        let display = {
            let mut state = self.state.lock().unwrap();
            let state = (&mut *state as &mut dyn ErasedState)
                .downcast_mut::<State<D>>()
                .expect("Wrong type parameter passed to Handle::create_global().");
            state.display
        };

        let alive = Arc::new(AtomicBool::new(true));

        let interface_ptr =
            interface.c_ptr.expect("Interface without c_ptr are unsupported by the sys backend.");

        let udata = Box::into_raw(Box::new(GlobalUserData {
            handler,
            alive: alive.clone(),
            interface,
            version,
            disabled: false,
            ptr: std::ptr::null_mut(),
        }));

        let ret = HANDLE.set(&(self.state.clone(), std::ptr::null_mut()), || unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_global_create,
                display,
                interface_ptr,
                version as i32,
                udata as *mut c_void,
                global_bind::<D>
            )
        });

        if ret.is_null() {
            // free the user data as global creation failed
            let _ = unsafe { Box::from_raw(udata) };
            panic!(
                "[wayland-backend-sys] Invalid global specification or memory allocation failure."
            );
        }

        unsafe {
            (*udata).ptr = ret;
        }

        let mut state = self.state.lock().unwrap();
        let state = (&mut *state as &mut dyn ErasedState)
            .downcast_mut::<State<D>>()
            .expect("Wrong type parameter passed to Handle::create_global().");

        let id = InnerGlobalId { ptr: ret, alive };
        state.known_globals.push(id.clone());
        id
    }

    pub fn disable_global<D: 'static>(&self, id: InnerGlobalId) {
        // check that `D` is correct
        {
            let mut state = self.state.lock().unwrap();
            let _state = (&mut *state as &mut dyn ErasedState)
                .downcast_mut::<State<D>>()
                .expect("Wrong type parameter passed to Handle::disable_global().");
        }

        if !id.alive.load(Ordering::Acquire) {
            return;
        }

        let udata = unsafe {
            &mut *(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_get_user_data, id.ptr)
                as *mut GlobalUserData<D>)
        };

        // libwayland will abort if wl_global_remove is called more than once.
        // This means we do nothing if the global is already disabled
        if !udata.disabled {
            udata.disabled = true;

            // send the global_remove
            HANDLE.set(&(self.state.clone(), std::ptr::null_mut()), || unsafe {
                ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_remove, id.ptr);
            });
        }
    }

    pub fn remove_global<D: 'static>(&self, id: InnerGlobalId) {
        {
            let mut state = self.state.lock().unwrap();
            let state = (&mut *state as &mut dyn ErasedState)
                .downcast_mut::<State<D>>()
                .expect("Wrong type parameter passed to Handle::remove_global().");
            state.known_globals.retain(|g| g != &id);
        }

        if !id.alive.load(Ordering::Acquire) {
            return;
        }

        let udata = unsafe {
            Box::from_raw(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_get_user_data, id.ptr)
                as *mut GlobalUserData<D>)
        };
        udata.alive.store(false, Ordering::Release);

        HANDLE.set(&(self.state.clone(), std::ptr::null_mut()), || unsafe {
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_destroy, id.ptr);
        });
    }

    pub fn global_info(&self, id: InnerGlobalId) -> Result<GlobalInfo, InvalidId> {
        self.state.lock().unwrap().global_info(id)
    }

    /// Returns the handler which manages the visibility and notifies when a client has bound the global.
    pub fn get_global_handler<D: 'static>(
        &self,
        id: InnerGlobalId,
    ) -> Result<Arc<dyn GlobalHandler<D>>, InvalidId> {
        let mut state = self.state.lock().unwrap();
        // Keep this guard alive while the code is run to protect the C state
        let _state = (&mut *state as &mut dyn ErasedState)
            .downcast_mut::<State<D>>()
            .expect("Wrong type parameter passed to Handle::set_object_data().");

        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let udata = unsafe {
            Box::from_raw(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_global_get_user_data, id.ptr)
                as *mut GlobalUserData<D>)
        };
        Ok(udata.handler.clone())
    }

    pub fn display_ptr(&self) -> *mut wl_display {
        self.state.lock().unwrap().display_ptr()
    }
}

pub(crate) trait ErasedState: downcast_rs::Downcast {
    fn object_info(&self, id: InnerObjectId) -> Result<ObjectInfo, InvalidId>;
    fn insert_client(
        &self,
        stream: UnixStream,
        data: Arc<dyn ClientData>,
    ) -> std::io::Result<InnerClientId>;
    fn get_client(&self, id: InnerObjectId) -> Result<ClientId, InvalidId>;
    fn get_client_credentials(&self, id: InnerClientId) -> Result<Credentials, InvalidId>;
    fn get_client_data(&self, id: InnerClientId) -> Result<Arc<dyn ClientData>, InvalidId>;
    fn with_all_clients(&self, f: &mut dyn FnMut(ClientId));
    fn with_all_objects_for(
        &self,
        client_id: InnerClientId,
        f: &mut dyn FnMut(ObjectId),
    ) -> Result<(), InvalidId>;
    fn object_for_protocol_id(
        &self,
        client_id: InnerClientId,
        interface: &'static Interface,
        protocol_id: u32,
    ) -> Result<ObjectId, InvalidId>;
    fn get_object_data_any(
        &self,
        id: InnerObjectId,
    ) -> Result<Arc<dyn std::any::Any + Send + Sync>, InvalidId>;
    fn send_event(&mut self, msg: Message<ObjectId, RawFd>) -> Result<(), InvalidId>;
    fn post_error(&mut self, object_id: InnerObjectId, error_code: u32, message: CString);
    fn kill_client(&mut self, client_id: InnerClientId, reason: DisconnectReason);
    fn global_info(&self, id: InnerGlobalId) -> Result<GlobalInfo, InvalidId>;
    fn is_known_global(&self, global_ptr: *const wl_global) -> bool;
    fn display_ptr(&self) -> *mut wl_display;
}

downcast_rs::impl_downcast!(ErasedState);

impl<D: 'static> ErasedState for State<D> {
    fn object_info(&self, id: InnerObjectId) -> Result<ObjectInfo, InvalidId> {
        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let version =
            unsafe { ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_version, id.ptr) } as u32;

        Ok(ObjectInfo { id: id.id, version, interface: id.interface })
    }

    fn insert_client(
        &self,
        stream: UnixStream,
        data: Arc<dyn ClientData>,
    ) -> std::io::Result<InnerClientId> {
        let ret = unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_client_create,
                self.display,
                stream.into_raw_fd()
            )
        };

        if ret.is_null() {
            return Err(std::io::Error::last_os_error());
        }

        Ok(unsafe { init_client::<D>(ret, data) })
    }

    fn get_client(&self, id: InnerObjectId) -> Result<ClientId, InvalidId> {
        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        unsafe {
            let client_ptr = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_client, id.ptr);
            client_id_from_ptr(client_ptr).ok_or(InvalidId).map(|id| ClientId { id })
        }
    }

    fn get_client_data(&self, id: InnerClientId) -> Result<Arc<dyn ClientData>, InvalidId> {
        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let data = unsafe {
            match client_user_data(id.ptr) {
                Some(ptr) => &mut *ptr,
                None => return Err(InvalidId),
            }
        };

        Ok(data.data.clone())
    }

    fn get_client_credentials(&self, id: InnerClientId) -> Result<Credentials, InvalidId> {
        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let mut creds = Credentials { pid: 0, uid: 0, gid: 0 };

        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_client_get_credentials,
                id.ptr,
                &mut creds.pid,
                &mut creds.uid,
                &mut creds.gid
            );
        }

        Ok(creds)
    }

    fn with_all_clients(&self, f: &mut dyn FnMut(ClientId)) {
        let mut client_list = unsafe {
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_display_get_client_list, self.display)
        };
        unsafe {
            while (*client_list).next != client_list {
                let client = ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_client_from_link, client_list);
                if let Some(id) = client_id_from_ptr(client) {
                    f(ClientId { id })
                }

                client_list = (*client_list).next;
            }
        }
    }

    fn with_all_objects_for(
        &self,
        client_id: InnerClientId,
        mut f: &mut dyn FnMut(ObjectId),
    ) -> Result<(), InvalidId> {
        if !client_id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        unsafe extern "C" fn iterator_func(
            resource: *mut wl_resource,
            user_data: *mut c_void,
        ) -> c_int {
            // the closure is passed by double-reference because we only have 1 pointer of user data
            let closure = unsafe { &mut *(user_data as *mut &mut dyn FnMut(ObjectId)) };

            // Only process objects that are RUST_MANAGED (we cannot guess the Interface for the others,
            // and thus cannot create the ObjectId).
            if let Ok(id) = unsafe { InnerObjectId::from_ptr(None, resource) } {
                closure(ObjectId { id })
            }

            // return WL_ITERATOR_CONTINUE
            1
        }

        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_client_for_each_resource,
                client_id.ptr,
                iterator_func,
                &mut f as *mut _ as *mut c_void,
            )
        }

        Ok(())
    }

    fn object_for_protocol_id(
        &self,
        client_id: InnerClientId,
        interface: &'static Interface,
        protocol_id: u32,
    ) -> Result<ObjectId, InvalidId> {
        if !client_id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }
        let resource = unsafe {
            ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_client_get_object, client_id.ptr, protocol_id)
        };
        if resource.is_null() {
            Err(InvalidId)
        } else {
            unsafe { ObjectId::from_ptr(interface, resource) }
        }
    }

    fn get_object_data_any(
        &self,
        id: InnerObjectId,
    ) -> Result<Arc<dyn std::any::Any + Send + Sync>, InvalidId> {
        if !id.alive.load(Ordering::Acquire) {
            return Err(InvalidId);
        }

        let iface_c_ptr =
            id.interface.c_ptr.expect("[wayland-backend-sys] Cannot use Interface without c_ptr!");
        let is_managed = unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_instance_of,
                id.ptr,
                iface_c_ptr,
                &RUST_MANAGED as *const u8 as *const _
            ) != 0
        };
        if !is_managed {
            return Err(InvalidId);
        }

        let udata = unsafe {
            &*(ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_get_user_data, id.ptr)
                as *mut ResourceUserData<D>)
        };

        Ok(udata.data.clone().into_any_arc())
    }

    fn send_event(
        &mut self,
        Message { sender_id: ObjectId { id }, opcode, args }: Message<ObjectId, RawFd>,
    ) -> Result<(), InvalidId> {
        if !id.alive.load(Ordering::Acquire) || id.ptr.is_null() {
            return Err(InvalidId);
        }

        // check that the argument list is valid
        let message_desc = match id.interface.events.get(opcode as usize) {
            Some(msg) => msg,
            None => {
                panic!("Unknown opcode {} for object {}@{}.", opcode, id.interface.name, id.id);
            }
        };
        if !check_for_signature(message_desc.signature, &args) {
            panic!(
                "Unexpected signature for request {}@{}.{}: expected {:?}, got {:?}.",
                id.interface.name, id.id, message_desc.name, message_desc.signature, args
            );
        }

        let mut argument_list = SmallVec::<[wl_argument; 4]>::with_capacity(args.len());
        let mut arg_interfaces = message_desc.arg_interfaces.iter();
        for (i, arg) in args.iter().enumerate() {
            match *arg {
                Argument::Uint(u) => argument_list.push(wl_argument { u }),
                Argument::Int(i) => argument_list.push(wl_argument { i }),
                Argument::Fixed(f) => argument_list.push(wl_argument { f }),
                Argument::Fd(h) => argument_list.push(wl_argument { h }),
                Argument::Array(ref a) => {
                    let a = Box::new(wl_array {
                        size: a.len(),
                        alloc: a.len(),
                        data: a.as_ptr() as *mut _,
                    });
                    argument_list.push(wl_argument { a: Box::into_raw(a) })
                }
                Argument::Str(Some(ref s)) => argument_list.push(wl_argument { s: s.as_ptr() }),
                Argument::Str(None) => argument_list.push(wl_argument { s: std::ptr::null() }),
                Argument::Object(ref o) => {
                    let next_interface = arg_interfaces.next().unwrap();
                    if !o.id.ptr.is_null() {
                        if !id.alive.load(Ordering::Acquire) {
                            unsafe { free_arrays(message_desc.signature, &argument_list) };
                            return Err(InvalidId);
                        }
                        // check that the object belongs to the right client
                        if self.get_client(id.clone()).unwrap().id.ptr
                            != self.get_client(o.id.clone()).unwrap().id.ptr
                        {
                            panic!("Attempting to send an event with objects from wrong client.");
                        }
                        if !same_interface(next_interface, o.id.interface) {
                            panic!("Event {}@{}.{} expects an argument of interface {} but {} was provided instead.", id.interface.name, id.id, message_desc.name, next_interface.name, o.id.interface.name);
                        }
                    } else if !matches!(
                        message_desc.signature[i],
                        ArgumentType::Object(AllowNull::Yes)
                    ) {
                        panic!(
                            "Event {}@{}.{} expects an non-null object argument.",
                            id.interface.name, id.id, message_desc.name
                        );
                    }
                    argument_list.push(wl_argument { o: o.id.ptr as *const _ })
                }
                Argument::NewId(ref o) => {
                    if !o.id.ptr.is_null() {
                        if !id.alive.load(Ordering::Acquire) {
                            unsafe { free_arrays(message_desc.signature, &argument_list) };
                            return Err(InvalidId);
                        }
                        // check that the object belongs to the right client
                        if self.get_client(id.clone()).unwrap().id.ptr
                            != self.get_client(o.id.clone()).unwrap().id.ptr
                        {
                            panic!("Attempting to send an event with objects from wrong client.");
                        }
                        let child_interface = match message_desc.child_interface {
                            Some(iface) => iface,
                            None => panic!("Trying to send event {}@{}.{} which creates an object without specifying its interface, this is unsupported.", id.interface.name, id.id, message_desc.name),
                        };
                        if !same_interface(child_interface, o.id.interface) {
                            panic!("Event {}@{}.{} expects an argument of interface {} but {} was provided instead.", id.interface.name, id.id, message_desc.name, child_interface.name, o.id.interface.name);
                        }
                    } else if !matches!(message_desc.signature[i], ArgumentType::NewId) {
                        panic!(
                            "Event {}@{}.{} expects an non-null object argument.",
                            id.interface.name, id.id, message_desc.name
                        );
                    }
                    argument_list.push(wl_argument { o: o.id.ptr as *const _ })
                }
            }
        }

        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_resource_post_event_array,
                id.ptr,
                opcode as u32,
                argument_list.as_mut_ptr()
            );
        }

        unsafe {
            free_arrays(message_desc.signature, &argument_list);
        }

        if message_desc.is_destructor {
            // wl_resource_destroy invokes a destructor
            PENDING_DESTRUCTORS.set(
                &(&mut self.pending_destructors as *mut _ as *mut _),
                || unsafe {
                    ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_resource_destroy, id.ptr);
                },
            );
        }

        Ok(())
    }