jay-compositor 1.15.0

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

mod auth;
mod dynamic_type;
mod formatter;
mod holder;
mod incoming;
mod outgoing;
mod parser;
mod property;
mod socket;
mod types;

#[derive(Debug)]
pub struct CallError {
    name: String,
    msg: Option<String>,
}

impl Display for CallError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(msg) = &self.msg {
            write!(f, "{}: {}", self.name, msg)
        } else {
            write!(f, "{}", self.name)
        }
    }
}

#[derive(Debug, Error)]
pub enum DbusError {
    #[error("Encountered an unknown type in a signature")]
    UnknownType,
    #[error("Function call reply does not contain a reply serial")]
    NoReplySerial,
    #[error("Signal message contains no interface or member or path")]
    MissingSignalHeaders,
    #[error("Method call message contains no interface or member or path")]
    MissingMethodCallHeaders,
    #[error("Error has no error name")]
    NoErrorName,
    #[error("The socket was killed")]
    Killed,
    #[error("{0}")]
    CallError(CallError),
    #[error("FD index is out of bounds")]
    OobFds,
    #[error("Variant has an invalid type")]
    InvalidVariantType,
    #[error("Could not create a socket")]
    Socket(#[source] OsError),
    #[error("Could not connect")]
    Connect(#[source] IoUringError),
    #[error("Could not write to the dbus socket")]
    WriteError(#[source] IoUringError),
    #[error("Could not read from the dbus socket")]
    ReadError(#[source] IoUringError),
    #[error("timeout")]
    IoUringError(#[source] Box<IoUringError>),
    #[error("Server did not send auth challenge")]
    NoChallenge,
    #[error("Server did not accept our authentication")]
    Auth,
    #[error("Array length is not a multiple of the element size")]
    PodArrayLength,
    #[error("Peer did not send enough fds")]
    TooFewFds,
    #[error("Variant signature is not a single type")]
    TrailingVariantSignature,
    #[error("Dict signature does not contain a terminating '}}'")]
    UnterminatedDict,
    #[error("Struct signature does not contain a terminating '}}'")]
    UnterminatedStruct,
    #[error("Dict signature contains trailing types")]
    DictTrailing,
    #[error("String does not contain valid UTF-8")]
    InvalidUtf8,
    #[error("Unexpected end of message")]
    UnexpectedEof,
    #[error("Boolean value was not 0 or 1")]
    InvalidBoolValue,
    #[error("Signature is empty")]
    EmptySignature,
    #[error("The session bus address is not set")]
    SessionBusAddressNotSet,
    #[error("Server does not support FD passing")]
    UnixFd,
    #[error("Server message has a different endianess than ourselves")]
    InvalidEndianess,
    #[error("Server speaks an unexpected protocol version")]
    InvalidProtocol,
    #[error("Signature contains an invalid type")]
    InvalidSignatureType,
    #[error("The signal already has a handler")]
    AlreadyHandled,
    #[error(transparent)]
    BufIoError(#[from] BufIoError),
    #[error(transparent)]
    DbusError(Rc<DbusError>),
}
efrom!(DbusError, IoUringError);

pub struct Dbus {
    eng: Rc<AsyncEngine>,
    ring: Rc<IoUring>,
    system: Rc<DbusHolder>,
    session: Rc<DbusHolder>,
    user_path: Option<String>,
}

impl Dbus {
    pub fn new(eng: &Rc<AsyncEngine>, ring: &Rc<IoUring>, run_toplevel: &Rc<RunToplevel>) -> Self {
        // https://dbus.freedesktop.org/doc/dbus-specification.html#addresses
        fn unescape_value(escaped: &str) -> Option<String> {
            let mut unescaped = Vec::new();
            let mut bytes = escaped.bytes();
            while let Some(c) = bytes.next() {
                match c {
                    b'-'
                    | b'0'..=b'9'
                    | b'A'..=b'Z'
                    | b'a'..=b'z'
                    | b'_'
                    | b'/'
                    | b'.'
                    | b'\\'
                    | b'*' => {
                        unescaped.push(c);
                    }
                    b'%' => {
                        let hi = (bytes.next()? as char).to_digit(16)?;
                        let lo = (bytes.next()? as char).to_digit(16)?;
                        unescaped.push((hi << 4 | lo) as u8);
                    }
                    _ => return None,
                }
            }
            String::from_utf8(unescaped).ok()
        }
        let user_path = 'path: {
            let Some(addr) = *DBUS_SESSION_BUS_ADDRESS else {
                if let Some(xrd) = *XDG_RUNTIME_DIR {
                    break 'path Some(format!("{xrd}/bus"));
                }
                log::warn!(
                    "Neither {} nor {} is set",
                    DBUS_SESSION_BUS_ADDRESS.name(),
                    XDG_RUNTIME_DIR.name(),
                );
                break 'path None;
            };
            let (first_addr, _) = addr.split_once(';').unwrap_or((&addr, ""));
            let Some((transport, attrs)) = first_addr.split_once(':') else {
                log::warn!("{} is invalid", DBUS_SESSION_BUS_ADDRESS.as_env());
                break 'path None;
            };
            if transport != "unix" {
                log::warn!(
                    "{} has unsupported transport {transport}",
                    DBUS_SESSION_BUS_ADDRESS.as_env(),
                );
                break 'path None;
            }
            for attr in attrs.split(',') {
                let Some((k, v)) = attr.split_once("=") else {
                    log::warn!("{} is invalid", DBUS_SESSION_BUS_ADDRESS.as_env());
                    break 'path None;
                };
                if k != "path" {
                    continue;
                }
                let Some(path) = unescape_value(v) else {
                    log::warn!("{} is invalid", DBUS_SESSION_BUS_ADDRESS.as_env());
                    break 'path None;
                };
                break 'path Some(path);
            }
            log::warn!("{} is invalid", DBUS_SESSION_BUS_ADDRESS.as_env());
            None
        };
        log::info!("dbus path = {user_path:?}");
        Self {
            eng: eng.clone(),
            ring: ring.clone(),
            system: Rc::new(DbusHolder::new(run_toplevel)),
            session: Rc::new(DbusHolder::new(run_toplevel)),
            user_path,
        }
    }

    pub fn clear(&self) {
        self.system.clear();
        self.session.clear();
    }

    pub async fn system(&self) -> Result<Rc<DbusSocket>, DbusError> {
        self.system
            .get(
                &self.eng,
                &self.ring,
                "/var/run/dbus/system_bus_socket",
                "System bus",
            )
            .await
    }

    pub async fn session(&self) -> Result<Rc<DbusSocket>, DbusError> {
        let Some(sba) = self.user_path.as_deref() else {
            return Err(DbusError::SessionBusAddressNotSet);
        };
        self.session
            .get(&self.eng, &self.ring, sba, "Session bus")
            .await
    }
}

unsafe trait ReplyHandler {
    fn signature(&self) -> &str;
    fn handle_error(self: Box<Self>, socket: &Rc<DbusSocket>, error: DbusError);
    fn handle(
        self: Box<Self>,
        socket: &Rc<DbusSocket>,
        headers: &Headers<'_>,
        parser: &mut Parser<'_>,
        buf: Vec<u8>,
    ) -> Result<(), DbusError>;
}

pub struct DbusSocket {
    bus_name: &'static str,
    fd: Rc<OwnedFd>,
    ring: Rc<IoUring>,
    in_bufs: Stack<Vec<u8>>,
    bufio: Rc<BufIo>,
    eng: Rc<AsyncEngine>,
    next_serial: NumCell<u32>,
    unique_name: CloneCell<Rc<String>>,
    reply_handlers: CopyHashMap<u32, Box<dyn ReplyHandler>>,
    incoming: Cell<Option<SpawnedFuture<()>>>,
    outgoing_: Cell<Option<SpawnedFuture<()>>>,
    auth: Cell<Option<SpawnedFuture<()>>>,
    dead: Cell<bool>,
    headers: RefCell<VecStorage<(u8, Variant<'static>)>>,
    run_toplevel: Rc<RunToplevel>,
    signal_handlers: RefCell<BHashMap<(&'static str, &'static str), InterfaceSignalHandlers>>,
    objects: CopyHashMap<Cow<'static, str>, Rc<DbusObjectData>>,
}

#[jay_hash]
#[derive(Eq)]
struct MemberHandlerOwnedKey {
    key: MemberHandlerKey<'static>,
}

#[jay_hash]
#[derive(Eq)]
struct MemberHandlerKey<'a> {
    interface: &'a str,
    member: &'a str,
}

impl<'a> Borrow<MemberHandlerKey<'a>> for MemberHandlerOwnedKey {
    fn borrow(&self) -> &MemberHandlerKey<'a> {
        &self.key
    }
}

const TY_BYTE: u8 = b'y';
const TY_BOOLEAN: u8 = b'b';
const TY_INT16: u8 = b'n';
const TY_UINT16: u8 = b'q';
const TY_INT32: u8 = b'i';
const TY_UINT32: u8 = b'u';
const TY_INT64: u8 = b'x';
const TY_UINT64: u8 = b't';
const TY_DOUBLE: u8 = b'd';
const TY_STRING: u8 = b's';
const TY_OBJECT_PATH: u8 = b'o';
const TY_SIGNATURE: u8 = b'g';
const TY_ARRAY: u8 = b'a';
const TY_VARIANT: u8 = b'v';
const TY_UNIX_FD: u8 = b'h';

const HDR_PATH: u8 = 1;
const HDR_INTERFACE: u8 = 2;
const HDR_MEMBER: u8 = 3;
const HDR_ERROR_NAME: u8 = 4;
const HDR_REPLY_SERIAL: u8 = 5;
const HDR_DESTINATION: u8 = 6;
const HDR_SENDER: u8 = 7;
const HDR_SIGNATURE: u8 = 8;
const HDR_UNIX_FDS: u8 = 9;

const MSG_METHOD_CALL: u8 = 1;
const MSG_METHOD_RETURN: u8 = 2;
const MSG_ERROR: u8 = 3;
const MSG_SIGNAL: u8 = 4;

const NO_REPLY_EXPECTED: u8 = 0x1;
#[expect(unused)]
const NO_AUTO_START: u8 = 0x2;
#[expect(unused)]
const ALLOW_INTERACTIVE_AUTHORIZATION: u8 = 0x4;

#[expect(unused)]
pub const DBUS_NAME_FLAG_ALLOW_REPLACEMENT: u32 = 0x1;
#[expect(unused)]
pub const DBUS_NAME_FLAG_REPLACE_EXISTING: u32 = 0x2;
pub const DBUS_NAME_FLAG_DO_NOT_QUEUE: u32 = 0x4;

pub const DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: u32 = 1;
#[expect(unused)]
pub const DBUS_REQUEST_NAME_REPLY_IN_QUEUE: u32 = 2;
#[expect(unused)]
pub const DBUS_REQUEST_NAME_REPLY_EXISTS: u32 = 3;
#[expect(unused)]
pub const DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: u32 = 4;

pub const BUS_DEST: &str = "org.freedesktop.DBus";
pub const BUS_PATH: &str = "/org/freedesktop/DBus";

#[derive(Default, Debug)]
struct Headers<'a> {
    path: Option<ObjectPath<'a>>,
    interface: Option<Cow<'a, str>>,
    member: Option<Cow<'a, str>>,
    error_name: Option<Cow<'a, str>>,
    reply_serial: Option<u32>,
    destination: Option<Cow<'a, str>>,
    sender: Option<Cow<'a, str>>,
    signature: Option<Signature<'a>>,
    unix_fds: Option<u32>,
}

struct DbusHolder {
    socket: CloneCell<Option<Rc<DbusSocket>>>,
    run_toplevel: Rc<RunToplevel>,
}

impl DbusHolder {
    fn new(run_toplevel: &Rc<RunToplevel>) -> Self {
        Self {
            socket: Default::default(),
            run_toplevel: run_toplevel.clone(),
        }
    }

    fn clear(&self) {
        if let Some(socket) = self.socket.take() {
            socket.clear();
        }
    }
}

impl Drop for DbusHolder {
    fn drop(&mut self) {
        if let Some(socket) = self.socket.take() {
            socket.auth.take();
            socket.outgoing_.take();
            socket.incoming.take();
        }
    }
}

#[derive(Clone, Debug)]
pub enum DynamicType {
    U8,
    Bool,
    I16,
    U16,
    I32,
    U32,
    I64,
    U64,
    F64,
    String,
    ObjectPath,
    Signature,
    Variant,
    Fd,
    Array(Box<DynamicType>),
    DictEntry(Box<DynamicType>, Box<DynamicType>),
    Struct(Vec<DynamicType>),
}

pub struct Parser<'a> {
    buf: &'a [u8],
    pos: usize,
    fds: &'a [Rc<OwnedFd>],
}

pub struct Formatter<'a> {
    fds: &'a mut Vec<Rc<OwnedFd>>,
    buf: &'a mut DynamicBuf,
}

pub unsafe trait Message<'a>: Sized + 'a {
    const SIGNATURE: &'static str;
    const INTERFACE: &'static str;
    const MEMBER: &'static str;
    type Generic<'b>: Message<'b>;

    fn marshal(&self, w: &mut Formatter<'_>);
    fn unmarshal(p: &mut Parser<'a>) -> Result<Self, DbusError>;
    fn num_fds(&self) -> u32;
}

pub struct ErrorMessage<'a> {
    msg: Cow<'a, str>,
}

unsafe impl<'a> Message<'a> for ErrorMessage<'a> {
    const SIGNATURE: &'static str = "s";
    const INTERFACE: &'static str = "";
    const MEMBER: &'static str = "";
    type Generic<'b> = ErrorMessage<'b>;

    fn marshal(&self, w: &mut Formatter<'_>) {
        self.msg.marshal(w);
    }

    fn unmarshal(p: &mut Parser<'a>) -> Result<Self, DbusError> {
        Ok(Self {
            msg: p.unmarshal()?,
        })
    }

    fn num_fds(&self) -> u32 {
        0
    }
}

pub trait Property {
    const INTERFACE: &'static str;
    const PROPERTY: &'static str;
    type Type: DbusType<'static>;
}

pub trait Signal<'a>: Message<'a> {}

pub trait MethodCall<'a>: Message<'a> {
    type Reply: Message<'static>;
}

pub unsafe trait DbusType<'a>: Clone + 'a {
    const ALIGNMENT: usize;
    const IS_POD: bool;
    type Generic<'b>: DbusType<'b> + 'b;

    fn consume_signature(s: &mut &[u8]) -> Result<(), DbusError>;
    #[allow(dead_code)]
    fn write_signature(w: &mut Vec<u8>);
    fn marshal(&self, fmt: &mut Formatter<'_>);
    fn unmarshal(parser: &mut Parser<'a>) -> Result<Self, DbusError>;

    fn num_fds(&self) -> u32 {
        0
    }
}

pub struct Reply<T: Message<'static>> {
    socket: Rc<DbusSocket>,
    buf: Vec<u8>,
    t: T::Generic<'static>,
}

pub struct PropertyValue<T: Property> {
    reply: Reply<GetReply<'static, T::Type>>,
}

impl<T: Property> Debug for PropertyValue<T>
where
    for<'a> <T::Type as DbusType<'static>>::Generic<'a>: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.get().fmt(f)
    }
}

impl<T: Property> PropertyValue<T> {
    pub fn get(&self) -> &<T::Type as DbusType<'static>>::Generic<'_> {
        &self.reply.get().value
    }
}

impl<T: Message<'static>> Debug for Reply<T>
where
    for<'a> T::Generic<'a>: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.get().fmt(f)
    }
}

impl<T: Message<'static>> Reply<T> {
    pub fn get(&self) -> &T::Generic<'_> {
        unsafe { mem::transmute(&self.t) }
    }
}

impl<T: Message<'static>> Drop for Reply<T> {
    fn drop(&mut self) {
        self.socket.in_bufs.push(mem::take(&mut self.buf));
    }
}

struct AsyncReplySlot<T: Message<'static>> {
    data: Cell<Option<Result<Reply<T>, DbusError>>>,
    waker: Cell<Option<Waker>>,
}

pub struct AsyncReply<T: Message<'static>> {
    socket: Rc<DbusSocket>,
    serial: u32,
    slot: Rc<AsyncReplySlot<T>>,
}

#[pin_project::pin_project]
pub struct AsyncProperty<T: Property> {
    #[pin]
    reply: AsyncReply<GetReply<'static, T::Type>>,
}

impl<T: Message<'static>> Drop for AsyncReply<T> {
    fn drop(&mut self) {
        self.socket.reply_handlers.remove(&self.serial);
    }
}

impl<T: Message<'static>> Future for AsyncReply<T> {
    type Output = Result<Reply<T>, DbusError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(d) = self.slot.data.take() {
            Poll::Ready(d)
        } else {
            self.slot.waker.set(Some(cx.waker().clone()));
            Poll::Pending
        }
    }
}

impl<T: Property> Future for AsyncProperty<T> {
    type Output = Result<PropertyValue<T>, DbusError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        AsyncProperty::project(self)
            .reply
            .poll(cx)
            .map(|r| r.map(|v| PropertyValue { reply: v }))
    }
}

struct SignalHandlerData<T, F> {
    path: Option<String>,
    rule: String,
    handler: F,
    _phantom: PhantomData<T>,
}

trait SignalHandlerApi {
    fn interface(&self) -> &'static str;
    fn member(&self) -> &'static str;
    fn signature(&self) -> &'static str;
    fn path(&self) -> Option<&str>;
    fn rule(&self) -> &str;
    fn handle(&self, parser: &mut Parser<'_>) -> Result<(), DbusError>;
}

impl<T, F> SignalHandlerApi for SignalHandlerData<T, F>
where
    T: Signal<'static>,
    F: for<'a> Fn(T::Generic<'a>),
{
    fn interface(&self) -> &'static str {
        T::INTERFACE
    }

    fn member(&self) -> &'static str {
        T::MEMBER
    }

    fn signature(&self) -> &'static str {
        T::SIGNATURE
    }

    fn path(&self) -> Option<&str> {
        self.path.as_deref()
    }

    fn rule(&self) -> &str {
        &self.rule
    }

    fn handle<'a>(&self, parser: &mut Parser<'a>) -> Result<(), DbusError> {
        (self.handler)(T::Generic::<'a>::unmarshal(parser)?);
        Ok(())
    }
}

#[must_use]
pub struct SignalHandler {
    socket: Rc<DbusSocket>,
    data: Rc<dyn SignalHandlerApi>,
}

impl Drop for SignalHandler {
    fn drop(&mut self) {
        self.socket.remove_signal_handler(&*self.data);
    }
}

struct InterfaceSignalHandlers {
    unconditional: Option<Rc<dyn SignalHandlerApi>>,
    conditional: BHashMap<String, Rc<dyn SignalHandlerApi>>,
}

struct DbusObjectData {
    path: Cow<'static, str>,
    methods: CopyHashMap<MemberHandlerOwnedKey, Rc<dyn MethodHandlerApi>>,
    properties: CopyHashMap<MemberHandlerOwnedKey, Rc<dyn PropertyHandlerApi>>,
}

pub struct DbusObject {
    socket: Rc<DbusSocket>,
    data: Rc<DbusObjectData>,
}

impl Drop for DbusObject {
    fn drop(&mut self) {
        self.socket.objects.remove(&self.data.path);
    }
}

impl DbusObject {
    pub fn add_method<T, F>(&self, handler: F)
    where
        T: MethodCall<'static>,
        F: for<'a> Fn(T::Generic<'a>, PendingReply<T::Reply>) + 'static,
    {
        let rhd = Rc::new(MethodHandlerData {
            handler,
            _phantom: Default::default(),
        });
        let key = MemberHandlerOwnedKey {
            key: MemberHandlerKey {
                interface: T::INTERFACE,
                member: T::MEMBER,
            },
        };
        self.data.methods.set(key, rhd);
    }

    pub fn set_property<T>(&self, value: Variant<'static>)
    where
        T: Property + 'static,
    {
        self.emit_signal(&PropertiesChanged {
            interface_name: T::INTERFACE.into(),
            changed_properties: Cow::Borrowed(&[DictEntry {
                key: T::PROPERTY.into(),
                value: value.borrow(),
            }]),
            invalidated_properties: Default::default(),
        });
        let phd = Rc::new(PropertyHandlerData::<T> {
            data: value,
            _phantom: Default::default(),
        });
        let key = MemberHandlerOwnedKey {
            key: MemberHandlerKey {
                interface: T::INTERFACE,
                member: T::PROPERTY,
            },
        };
        self.data.properties.set(key, phd);
    }

    pub fn emit_signal<'a, T: Signal<'a>>(&self, signal: &T) {
        self.socket.emit_signal(&self.data.path, signal);
    }

    pub fn path(&self) -> &str {
        &self.data.path
    }
}

trait PropertyHandlerApi {
    fn interface(&self) -> &'static str;
    fn member(&self) -> &'static str;
    fn value(&self) -> Variant<'_>;
}

struct PropertyHandlerData<T> {
    data: Variant<'static>,
    _phantom: PhantomData<T>,
}

impl<T> PropertyHandlerApi for PropertyHandlerData<T>
where
    T: Property,
{
    fn interface(&self) -> &'static str {
        T::INTERFACE
    }

    fn member(&self) -> &'static str {
        T::PROPERTY
    }

    fn value(&self) -> Variant<'_> {
        self.data.borrow()
    }
}

pub struct PendingReply<T> {
    reply_expected: bool,
    socket: Rc<DbusSocket>,
    destination: String,
    serial: u32,
    _phantom: PhantomData<T>,
}

impl<T> PendingReply<T> {
    #[expect(unused)]
    pub fn reply_expected(&self) -> bool {
        self.reply_expected
    }

    pub fn err(&self, msg: &str) {
        if self.reply_expected {
            self.socket.send_error(&self.destination, self.serial, msg);
        }
    }
}

impl<T> PendingReply<T>
where
    T: Message<'static>,
{
    pub fn ok(&self, msg: &T::Generic<'_>) {
        if self.reply_expected {
            self.socket.send_reply(&self.destination, self.serial, msg);
        }
    }

    #[expect(unused)]
    pub fn complete(&self, res: Result<&T::Generic<'_>, &str>) {
        match res {
            Ok(m) => self.ok(m),
            Err(e) => self.err(e),
        }
    }
}

trait MethodHandlerApi {
    fn signature(&self) -> &'static str;
    fn handle(
        &self,
        object: &DbusObjectData,
        socket: &Rc<DbusSocket>,
        dest: &str,
        serial: u32,
        reply_expected: bool,
        parser: &mut Parser<'_>,
    ) -> Result<(), DbusError>;
}

struct MethodHandlerData<T, F> {
    handler: F,
    _phantom: PhantomData<T>,
}

impl<T, F> MethodHandlerApi for MethodHandlerData<T, F>
where
    T: MethodCall<'static>,
    F: for<'a> Fn(T::Generic<'a>, PendingReply<T::Reply>) + 'static,
{
    fn signature(&self) -> &'static str {
        T::SIGNATURE
    }

    fn handle<'a>(
        &self,
        _object: &DbusObjectData,
        socket: &Rc<DbusSocket>,
        dest: &str,
        serial: u32,
        reply_expected: bool,
        parser: &mut Parser<'a>,
    ) -> Result<(), DbusError> {
        let msg = T::Generic::<'a>::unmarshal(parser)?;
        let pr = PendingReply {
            reply_expected,
            socket: socket.clone(),
            destination: dest.to_string(),
            serial,
            _phantom: Default::default(),
        };
        (self.handler)(msg, pr);
        Ok(())
    }
}

struct PropertyGetHandlerProxy;

impl MethodHandlerApi for PropertyGetHandlerProxy {
    fn signature(&self) -> &'static str {
        Get::<u32>::SIGNATURE
    }

    fn handle(
        &self,
        object: &DbusObjectData,
        socket: &Rc<DbusSocket>,
        dest: &str,
        serial: u32,
        reply_expected: bool,
        parser: &mut Parser<'_>,
    ) -> Result<(), DbusError> {
        if !reply_expected {
            return Ok(());
        }
        let msg = org::freedesktop::dbus::properties::Get::unmarshal(parser)?;
        let key = MemberHandlerKey {
            interface: msg.interface_name.deref(),
            member: msg.property_name.deref(),
        };
        match object.properties.get(&key) {
            Some(h) => socket.send_reply(
                dest,
                serial,
                &org::freedesktop::dbus::properties::GetReply { value: h.value() },
            ),
            _ => socket.send_error(dest, serial, "Property does not exist"),
        };
        Ok(())
    }
}

struct PropertyGetAllHandlerProxy;

impl MethodHandlerApi for PropertyGetAllHandlerProxy {
    fn signature(&self) -> &'static str {
        GetAll::SIGNATURE
    }

    fn handle(
        &self,
        object: &DbusObjectData,
        socket: &Rc<DbusSocket>,
        dest: &str,
        serial: u32,
        reply_expected: bool,
        parser: &mut Parser<'_>,
    ) -> Result<(), DbusError> {
        if !reply_expected {
            return Ok(());
        }
        let msg = GetAll::unmarshal(parser)?;
        let all_props = object.properties.lock();
        let mut props = vec![];
        for property in all_props.values() {
            if property.interface() == msg.interface_name {
                props.push(DictEntry {
                    key: property.member().into(),
                    value: property.value(),
                });
            }
        }
        socket.send_reply(
            dest,
            serial,
            &GetAllReply {
                props: props.into(),
            },
        );
        Ok(())
    }
}

pub mod prelude {
    pub use super::DbusError;
    pub use super::DbusType;
    pub use super::Formatter;
    pub use super::Message;
    pub use super::MethodCall;
    pub use super::Parser;
    pub use super::Property;
    pub use super::Signal;
    pub use super::types::Bool;
    pub use super::types::DictEntry;
    pub use super::types::ObjectPath;
    pub use super::types::Variant;
    pub use std::borrow::Cow;
    pub use std::rc::Rc;
    pub use uapi::OwnedFd;
}