Skip to main content

gio/
dbus_connection.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{boxed::Box as Box_, future::Future, marker::PhantomData, num::NonZeroU32};
4
5use crate::{
6    ActionGroup, DBusConnection, DBusInterfaceInfo, DBusMessage, DBusMethodInvocation,
7    DBusSignalFlags, MenuModel, ffi,
8};
9use futures_channel::mpsc;
10use futures_core::{FusedStream, Stream};
11use glib::{WeakRef, prelude::*, translate::*, variant::VariantTypeMismatchError};
12use pin_project_lite::pin_project;
13
14pub trait DBusMethodCall: Sized {
15    fn parse_call(
16        obj_path: &str,
17        interface: Option<&str>,
18        method: &str,
19        params: glib::Variant,
20    ) -> Result<Self, glib::Error>;
21}
22
23// rustdoc-stripper-ignore-next
24/// Handle method invocations.
25pub struct MethodCallBuilder<'a, T> {
26    registration: RegistrationBuilder<'a>,
27    capture_type: PhantomData<T>,
28}
29
30impl<'a, T: DBusMethodCall> MethodCallBuilder<'a, T> {
31    // rustdoc-stripper-ignore-next
32    /// Handle invocation of a parsed method call.
33    ///
34    /// For each DBus method call parse the call, and then invoke the given closure
35    /// with
36    ///
37    /// 1. the DBus connection object,
38    /// 2. the name of the sender of the method call,
39    /// 3. the parsed call, and
40    /// 4. the method invocation object.
41    ///
42    /// The closure **must** return a value through the invocation object in all
43    /// code paths, using any of its `return_` functions, such as
44    /// [`DBusMethodInvocation::return_result`] or
45    /// [`DBusMethodInvocation::return_future_local`], to finish the call.
46    ///
47    /// If direct access to the invocation object is not needed,
48    /// [`invoke_and_return`] and [`invoke_and_return_future_local`] provide a
49    /// safer interface where the callback returns a result directly.
50    pub fn invoke<F>(self, f: F) -> RegistrationBuilder<'a>
51    where
52        F: Fn(DBusConnection, Option<&str>, T, DBusMethodInvocation) + 'static,
53    {
54        self.registration.method_call(
55            move |connection, sender, obj_path, interface, method, params, invocation| {
56                match T::parse_call(obj_path, interface, method, params) {
57                    Ok(call) => f(connection, sender, call, invocation),
58                    Err(error) => invocation.return_gerror(error),
59                }
60            },
61        )
62    }
63
64    // rustdoc-stripper-ignore-next
65    /// Handle invocation of a parsed method call.
66    ///
67    /// For each DBus method call parse the call, and then invoke the given closure
68    /// with
69    ///
70    /// 1. the DBus connection object,
71    /// 2. the name of the sender of the method call, and
72    /// 3. the parsed call.
73    ///
74    /// The return value of the closure is then returned on the method call.
75    /// If the returned variant value is not a tuple, it is automatically wrapped
76    /// in a single element tuple, as DBus methods must always return tuples.
77    /// See [`DBusMethodInvocation::return_result`] for details.
78    pub fn invoke_and_return<F>(self, f: F) -> RegistrationBuilder<'a>
79    where
80        F: Fn(DBusConnection, Option<&str>, T) -> Result<Option<glib::Variant>, glib::Error>
81            + 'static,
82    {
83        self.invoke(move |connection, sender, call, invocation| {
84            invocation.return_result(f(connection, sender, call))
85        })
86    }
87
88    // rustdoc-stripper-ignore-next
89    /// Handle an async invocation of a parsed method call.
90    ///
91    /// For each DBus method call parse the call, and then invoke the given closure
92    /// with
93    ///
94    /// 1. the DBus connection object,
95    /// 2. the name of the sender of the method call, and
96    /// 3. the parsed call.
97    ///
98    /// The output of the future is then returned on the method call.
99    /// If the returned variant value is not a tuple, it is automatically wrapped
100    /// in a single element tuple, as DBus methods must always return tuples.
101    /// See [`DBusMethodInvocation::return_future_local`] for details.
102    pub fn invoke_and_return_future_local<F, Fut>(self, f: F) -> RegistrationBuilder<'a>
103    where
104        F: Fn(DBusConnection, Option<&str>, T) -> Fut + 'static,
105        Fut: Future<Output = Result<Option<glib::Variant>, glib::Error>> + 'static,
106    {
107        self.invoke(move |connection, sender, call, invocation| {
108            invocation.return_future_local(f(connection, sender, call));
109        })
110    }
111}
112
113#[derive(Debug, Eq, PartialEq)]
114pub struct RegistrationId(NonZeroU32);
115#[derive(Debug, Eq, PartialEq)]
116pub struct WatcherId(NonZeroU32);
117#[derive(Debug, Eq, PartialEq)]
118pub struct ActionGroupExportId(NonZeroU32);
119#[derive(Debug, Eq, PartialEq)]
120pub struct MenuModelExportId(NonZeroU32);
121#[derive(Debug, Eq, PartialEq)]
122pub struct FilterId(NonZeroU32);
123
124#[derive(Debug, Eq, PartialEq)]
125pub struct SignalSubscriptionId(NonZeroU32);
126
127// rustdoc-stripper-ignore-next
128/// A strong subscription to a D-Bus signal.
129///
130/// Keep a reference to a D-Bus connection to maintain a subscription on a
131/// D-Bus signal even if the connection has no other strong reference.
132///
133/// When dropped, unsubscribes from signal on the connection, and then drop the
134/// reference on the connection.  If no other strong reference on the connection
135/// exists the connection is closed and destroyed.
136#[derive(Debug)]
137pub struct SignalSubscription(DBusConnection, Option<SignalSubscriptionId>);
138
139impl SignalSubscription {
140    // rustdoc-stripper-ignore-next
141    /// Downgrade this signal subscription to a weak one.
142    #[must_use]
143    pub fn downgrade(mut self) -> WeakSignalSubscription {
144        WeakSignalSubscription(self.0.downgrade(), self.1.take())
145    }
146}
147
148impl Drop for SignalSubscription {
149    fn drop(&mut self) {
150        if let Some(id) = self.1.take() {
151            #[allow(deprecated)]
152            self.0.signal_unsubscribe(id);
153        }
154    }
155}
156
157// rustdoc-stripper-ignore-next
158/// A weak subscription to a D-Bus signal.
159///
160/// Like [`SignalSubscription`] but hold only a weak reference to the D-Bus
161/// connection the signal is subscribed on, i.e. maintain the subscription on
162/// the D-Bus signal only as long as some strong reference exists on the
163/// corresponding D-Bus connection.
164///
165/// When dropped, unsubscribes from signal on the connection if it still exists,
166/// and then drop the reference on the connection.  If no other strong reference
167/// on the connection exists the connection is closed and destroyed.
168#[derive(Debug)]
169pub struct WeakSignalSubscription(WeakRef<DBusConnection>, Option<SignalSubscriptionId>);
170
171impl WeakSignalSubscription {
172    // rustdoc-stripper-ignore-next
173    /// Upgrade this signal subscription to a strong one.
174    #[must_use]
175    pub fn upgrade(mut self) -> Option<SignalSubscription> {
176        self.0
177            .upgrade()
178            .map(|c| SignalSubscription(c, self.1.take()))
179    }
180}
181
182impl Drop for WeakSignalSubscription {
183    fn drop(&mut self) {
184        if let Some(id) = self.1.take()
185            && let Some(connection) = self.0.upgrade()
186        {
187            #[allow(deprecated)]
188            connection.signal_unsubscribe(id);
189        }
190    }
191}
192
193// rustdoc-stripper-ignore-next
194/// An emitted D-Bus signal.
195#[derive(Debug, Copy, Clone)]
196pub struct DBusSignalRef<'a> {
197    // rustdoc-stripper-ignore-next
198    /// The connection the signal was emitted on.
199    pub connection: &'a DBusConnection,
200    // rustdoc-stripper-ignore-next
201    /// The bus name of the sender which emitted the signal.
202    pub sender_name: &'a str,
203    // rustdoc-stripper-ignore-next
204    /// The path of the object on `sender` the signal was emitted from.
205    pub object_path: &'a str,
206    // rustdoc-stripper-ignore-next
207    /// The interface the signal belongs to.
208    pub interface_name: &'a str,
209    // rustdoc-stripper-ignore-next
210    /// The name of the emitted signal.
211    pub signal_name: &'a str,
212    // rustdoc-stripper-ignore-next
213    /// Parameters the signal was emitted with.
214    pub parameters: &'a glib::Variant,
215}
216
217pin_project! {
218    // rustdoc-stripper-ignore-next
219    /// A subscribed stream.
220    ///
221    /// A stream which wraps an inner stream of type `S` while holding on to a
222    /// subscription handle `H` to keep a subscription alive.
223    #[derive(Debug)]
224    #[must_use = "streams do nothing unless polled"]
225    pub struct SubscribedSignalStream<H, S> {
226        #[pin]
227        stream: S,
228        subscription: H,
229    }
230}
231
232impl<S> SubscribedSignalStream<SignalSubscription, S> {
233    // rustdoc-stripper-ignore-next
234    /// Downgrade the inner signal subscription to a weak one.
235    ///
236    /// See [`SignalSubscription::downgrade`] and [`WeakSignalSubscription`].
237    pub fn downgrade(self) -> SubscribedSignalStream<WeakSignalSubscription, S> {
238        SubscribedSignalStream {
239            subscription: self.subscription.downgrade(),
240            stream: self.stream,
241        }
242    }
243}
244
245impl<S> SubscribedSignalStream<WeakSignalSubscription, S> {
246    // rustdoc-stripper-ignore-next
247    /// Upgrade the inner signal subscription to a strong one.
248    ///
249    /// See [`WeakSignalSubscription::upgrade`] and [`SignalSubscription`].
250    pub fn downgrade(self) -> Option<SubscribedSignalStream<SignalSubscription, S>> {
251        self.subscription
252            .upgrade()
253            .map(|subscription| SubscribedSignalStream {
254                subscription,
255                stream: self.stream,
256            })
257    }
258}
259
260impl<H, S> Stream for SubscribedSignalStream<H, S>
261where
262    S: Stream,
263{
264    type Item = S::Item;
265
266    fn poll_next(
267        self: std::pin::Pin<&mut Self>,
268        cx: &mut std::task::Context<'_>,
269    ) -> std::task::Poll<Option<Self::Item>> {
270        let this = self.project();
271        this.stream.poll_next(cx)
272    }
273
274    fn size_hint(&self) -> (usize, Option<usize>) {
275        self.stream.size_hint()
276    }
277}
278
279impl<H, S> FusedStream for SubscribedSignalStream<H, S>
280where
281    S: FusedStream,
282{
283    fn is_terminated(&self) -> bool {
284        self.stream.is_terminated()
285    }
286}
287
288// rustdoc-stripper-ignore-next
289/// Build a registered DBus object, by handling different parts of DBus.
290#[must_use = "The builder must be built to be used"]
291pub struct RegistrationBuilder<'a> {
292    connection: &'a DBusConnection,
293    object_path: &'a str,
294    interface_info: &'a DBusInterfaceInfo,
295    #[allow(clippy::type_complexity)]
296    method_call: Option<
297        Box_<
298            dyn Fn(
299                DBusConnection,
300                Option<&str>,
301                &str,
302                Option<&str>,
303                &str,
304                glib::Variant,
305                DBusMethodInvocation,
306            ),
307        >,
308    >,
309    #[allow(clippy::type_complexity)]
310    get_property:
311        Option<Box_<dyn Fn(DBusConnection, Option<&str>, &str, &str, &str) -> glib::Variant>>,
312    #[allow(clippy::type_complexity)]
313    set_property:
314        Option<Box_<dyn Fn(DBusConnection, Option<&str>, &str, &str, &str, glib::Variant) -> bool>>,
315}
316
317impl<'a> RegistrationBuilder<'a> {
318    pub fn method_call<
319        F: Fn(
320                DBusConnection,
321                Option<&str>,
322                &str,
323                Option<&str>,
324                &str,
325                glib::Variant,
326                DBusMethodInvocation,
327            ) + 'static,
328    >(
329        mut self,
330        f: F,
331    ) -> Self {
332        self.method_call = Some(Box_::new(f));
333        self
334    }
335
336    // rustdoc-stripper-ignore-next
337    /// Handle method calls on this object.
338    ///
339    /// Return a builder for method calls which parses method names and
340    /// parameters with the given [`DBusMethodCall`] and then allows to dispatch
341    /// the parsed call either synchronously or asynchronously.
342    pub fn typed_method_call<T: DBusMethodCall>(self) -> MethodCallBuilder<'a, T> {
343        MethodCallBuilder {
344            registration: self,
345            capture_type: Default::default(),
346        }
347    }
348
349    #[doc(alias = "get_property")]
350    pub fn property<
351        F: Fn(DBusConnection, Option<&str>, &str, &str, &str) -> glib::Variant + 'static,
352    >(
353        mut self,
354        f: F,
355    ) -> Self {
356        self.get_property = Some(Box_::new(f));
357        self
358    }
359
360    pub fn set_property<
361        F: Fn(DBusConnection, Option<&str>, &str, &str, &str, glib::Variant) -> bool + 'static,
362    >(
363        mut self,
364        f: F,
365    ) -> Self {
366        self.set_property = Some(Box_::new(f));
367        self
368    }
369
370    pub fn build(self) -> Result<RegistrationId, glib::Error> {
371        unsafe {
372            let mut error = std::ptr::null_mut();
373            let id = ffi::g_dbus_connection_register_object_with_closures(
374                self.connection.to_glib_none().0,
375                self.object_path.to_glib_none().0,
376                self.interface_info.to_glib_none().0,
377                self.method_call
378                    .map(|f| {
379                        glib::Closure::new_local(move |args| {
380                            let conn = args[0].get::<DBusConnection>().unwrap();
381                            let sender = args[1].get::<Option<&str>>().unwrap();
382                            let object_path = args[2].get::<&str>().unwrap();
383                            let interface_name = args[3].get::<Option<&str>>().unwrap();
384                            let method_name = args[4].get::<&str>().unwrap();
385                            let parameters = args[5].get::<glib::Variant>().unwrap();
386
387                            // Work around GLib memory leak: Assume that the invocation is passed
388                            // as `transfer full` into the closure.
389                            //
390                            // This workaround is not going to break with future versions of
391                            // GLib as fixing the bug was considered a breaking API change.
392                            //
393                            // See https://gitlab.gnome.org/GNOME/glib/-/merge_requests/4427
394                            let invocation = from_glib_full(glib::gobject_ffi::g_value_get_object(
395                                args[6].as_ptr(),
396                            )
397                                as *mut ffi::GDBusMethodInvocation);
398
399                            f(
400                                conn,
401                                sender,
402                                object_path,
403                                interface_name,
404                                method_name,
405                                parameters,
406                                invocation,
407                            );
408                            None
409                        })
410                    })
411                    .to_glib_none()
412                    .0,
413                self.get_property
414                    .map(|f| {
415                        glib::Closure::new_local(move |args| {
416                            let conn = args[0].get::<DBusConnection>().unwrap();
417                            let sender = args[1].get::<Option<&str>>().unwrap();
418                            let object_path = args[2].get::<&str>().unwrap();
419                            let interface_name = args[3].get::<&str>().unwrap();
420                            let property_name = args[4].get::<&str>().unwrap();
421                            let result =
422                                f(conn, sender, object_path, interface_name, property_name);
423                            Some(result.to_value())
424                        })
425                    })
426                    .to_glib_none()
427                    .0,
428                self.set_property
429                    .map(|f| {
430                        glib::Closure::new_local(move |args| {
431                            let conn = args[0].get::<DBusConnection>().unwrap();
432                            let sender = args[1].get::<Option<&str>>().unwrap();
433                            let object_path = args[2].get::<&str>().unwrap();
434                            let interface_name = args[3].get::<&str>().unwrap();
435                            let property_name = args[4].get::<&str>().unwrap();
436                            let value = args[5].get::<glib::Variant>().unwrap();
437                            let result = f(
438                                conn,
439                                sender,
440                                object_path,
441                                interface_name,
442                                property_name,
443                                value,
444                            );
445                            Some(result.to_value())
446                        })
447                    })
448                    .to_glib_none()
449                    .0,
450                &mut error,
451            );
452
453            if error.is_null() {
454                Ok(RegistrationId(NonZeroU32::new_unchecked(id)))
455            } else {
456                Err(from_glib_full(error))
457            }
458        }
459    }
460}
461
462impl DBusConnection {
463    #[doc(alias = "g_dbus_connection_register_object")]
464    #[doc(alias = "g_dbus_connection_register_object_with_closures")]
465    pub fn register_object<'a>(
466        &'a self,
467        object_path: &'a str,
468        interface_info: &'a DBusInterfaceInfo,
469    ) -> RegistrationBuilder<'a> {
470        RegistrationBuilder {
471            connection: self,
472            object_path,
473            interface_info,
474            method_call: None,
475            get_property: None,
476            set_property: None,
477        }
478    }
479
480    #[doc(alias = "g_dbus_connection_unregister_object")]
481    pub fn unregister_object(
482        &self,
483        registration_id: RegistrationId,
484    ) -> Result<(), glib::error::BoolError> {
485        unsafe {
486            glib::result_from_gboolean!(
487                ffi::g_dbus_connection_unregister_object(
488                    self.to_glib_none().0,
489                    registration_id.0.into()
490                ),
491                "Failed to unregister D-Bus object"
492            )
493        }
494    }
495
496    #[doc(alias = "g_dbus_connection_export_action_group")]
497    pub fn export_action_group<P: IsA<ActionGroup>>(
498        &self,
499        object_path: &str,
500        action_group: &P,
501    ) -> Result<ActionGroupExportId, glib::Error> {
502        unsafe {
503            let mut error = std::ptr::null_mut();
504            let id = ffi::g_dbus_connection_export_action_group(
505                self.to_glib_none().0,
506                object_path.to_glib_none().0,
507                action_group.as_ref().to_glib_none().0,
508                &mut error,
509            );
510            if error.is_null() {
511                Ok(ActionGroupExportId(NonZeroU32::new_unchecked(id)))
512            } else {
513                Err(from_glib_full(error))
514            }
515        }
516    }
517
518    #[doc(alias = "g_dbus_connection_unexport_action_group")]
519    pub fn unexport_action_group(&self, export_id: ActionGroupExportId) {
520        unsafe {
521            ffi::g_dbus_connection_unexport_action_group(self.to_glib_none().0, export_id.0.into());
522        }
523    }
524
525    #[doc(alias = "g_dbus_connection_export_menu_model")]
526    pub fn export_menu_model<P: IsA<MenuModel>>(
527        &self,
528        object_path: &str,
529        menu: &P,
530    ) -> Result<MenuModelExportId, glib::Error> {
531        unsafe {
532            let mut error = std::ptr::null_mut();
533            let id = ffi::g_dbus_connection_export_menu_model(
534                self.to_glib_none().0,
535                object_path.to_glib_none().0,
536                menu.as_ref().to_glib_none().0,
537                &mut error,
538            );
539            if error.is_null() {
540                Ok(MenuModelExportId(NonZeroU32::new_unchecked(id)))
541            } else {
542                Err(from_glib_full(error))
543            }
544        }
545    }
546
547    #[doc(alias = "g_dbus_connection_unexport_menu_model")]
548    pub fn unexport_menu_model(&self, export_id: MenuModelExportId) {
549        unsafe {
550            ffi::g_dbus_connection_unexport_menu_model(self.to_glib_none().0, export_id.0.into());
551        }
552    }
553
554    #[doc(alias = "g_dbus_connection_add_filter")]
555    pub fn add_filter<
556        P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
557    >(
558        &self,
559        filter_function: P,
560    ) -> FilterId {
561        let filter_function_data: Box_<P> = Box_::new(filter_function);
562        unsafe extern "C" fn filter_function_func<
563            P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
564        >(
565            connection: *mut ffi::GDBusConnection,
566            message: *mut ffi::GDBusMessage,
567            incoming: glib::ffi::gboolean,
568            user_data: glib::ffi::gpointer,
569        ) -> *mut ffi::GDBusMessage {
570            unsafe {
571                let connection = from_glib_borrow(connection);
572                let message = from_glib_full(message);
573                let incoming = from_glib(incoming);
574                let callback: &P = &*(user_data as *mut _);
575                let res = (*callback)(&connection, &message, incoming);
576                res.into_glib_ptr()
577            }
578        }
579        let filter_function = Some(filter_function_func::<P> as _);
580        unsafe extern "C" fn user_data_free_func_func<
581            P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
582        >(
583            data: glib::ffi::gpointer,
584        ) {
585            unsafe {
586                let _callback: Box_<P> = Box_::from_raw(data as *mut _);
587            }
588        }
589        let destroy_call3 = Some(user_data_free_func_func::<P> as _);
590        let super_callback0: Box_<P> = filter_function_data;
591        unsafe {
592            let id = ffi::g_dbus_connection_add_filter(
593                self.to_glib_none().0,
594                filter_function,
595                Box_::into_raw(super_callback0) as *mut _,
596                destroy_call3,
597            );
598            FilterId(NonZeroU32::new_unchecked(id))
599        }
600    }
601
602    #[doc(alias = "g_dbus_connection_remove_filter")]
603    pub fn remove_filter(&self, filter_id: FilterId) {
604        unsafe {
605            ffi::g_dbus_connection_remove_filter(self.to_glib_none().0, filter_id.0.into());
606        }
607    }
608
609    // rustdoc-stripper-ignore-next
610    /// Subscribe to a D-Bus signal.
611    ///
612    /// See [`Self::signal_subscribe`] for arguments.
613    ///
614    /// Return a signal subscription which keeps a reference to this D-Bus
615    /// connection and unsubscribes from the signal when dropped.
616    ///
617    /// To avoid reference cycles you may wish to downgrade the returned
618    /// subscription to a weak one with [`SignalSubscription::downgrade`].
619    #[must_use]
620    pub fn subscribe_to_signal<P: Fn(DBusSignalRef) + 'static>(
621        &self,
622        sender: Option<&str>,
623        interface_name: Option<&str>,
624        member: Option<&str>,
625        object_path: Option<&str>,
626        arg0: Option<&str>,
627        flags: DBusSignalFlags,
628        callback: P,
629    ) -> SignalSubscription {
630        #[allow(deprecated)]
631        let id = self.signal_subscribe(
632            sender,
633            interface_name,
634            member,
635            object_path,
636            arg0,
637            flags,
638            move |connection, sender_name, object_path, interface_name, signal_name, parameters| {
639                callback(DBusSignalRef {
640                    connection,
641                    sender_name,
642                    object_path,
643                    interface_name,
644                    signal_name,
645                    parameters,
646                });
647            },
648        );
649        SignalSubscription(self.clone(), Some(id))
650    }
651
652    #[doc(alias = "g_dbus_connection_signal_subscribe")]
653    #[allow(clippy::too_many_arguments)]
654    #[deprecated(note = "Prefer subscribe_to_signal")]
655    pub fn signal_subscribe<
656        P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
657    >(
658        &self,
659        sender: Option<&str>,
660        interface_name: Option<&str>,
661        member: Option<&str>,
662        object_path: Option<&str>,
663        arg0: Option<&str>,
664        flags: DBusSignalFlags,
665        callback: P,
666    ) -> SignalSubscriptionId {
667        let callback_data: Box_<P> = Box_::new(callback);
668        unsafe extern "C" fn callback_func<
669            P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
670        >(
671            connection: *mut ffi::GDBusConnection,
672            sender_name: *const libc::c_char,
673            object_path: *const libc::c_char,
674            interface_name: *const libc::c_char,
675            signal_name: *const libc::c_char,
676            parameters: *mut glib::ffi::GVariant,
677            user_data: glib::ffi::gpointer,
678        ) {
679            unsafe {
680                let connection = from_glib_borrow(connection);
681                let sender_name: Borrowed<glib::GString> = from_glib_borrow(sender_name);
682                let object_path: Borrowed<glib::GString> = from_glib_borrow(object_path);
683                let interface_name: Borrowed<glib::GString> = from_glib_borrow(interface_name);
684                let signal_name: Borrowed<glib::GString> = from_glib_borrow(signal_name);
685                let parameters = from_glib_borrow(parameters);
686                let callback: &P = &*(user_data as *mut _);
687                (*callback)(
688                    &connection,
689                    sender_name.as_str(),
690                    object_path.as_str(),
691                    interface_name.as_str(),
692                    signal_name.as_str(),
693                    &parameters,
694                );
695            }
696        }
697        let callback = Some(callback_func::<P> as _);
698        unsafe extern "C" fn user_data_free_func_func<
699            P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
700        >(
701            data: glib::ffi::gpointer,
702        ) {
703            unsafe {
704                let _callback: Box_<P> = Box_::from_raw(data as *mut _);
705            }
706        }
707        let destroy_call9 = Some(user_data_free_func_func::<P> as _);
708        let super_callback0: Box_<P> = callback_data;
709        unsafe {
710            let id = ffi::g_dbus_connection_signal_subscribe(
711                self.to_glib_none().0,
712                sender.to_glib_none().0,
713                interface_name.to_glib_none().0,
714                member.to_glib_none().0,
715                object_path.to_glib_none().0,
716                arg0.to_glib_none().0,
717                flags.into_glib(),
718                callback,
719                Box_::into_raw(super_callback0) as *mut _,
720                destroy_call9,
721            );
722            SignalSubscriptionId(NonZeroU32::new_unchecked(id))
723        }
724    }
725
726    #[doc(alias = "g_dbus_connection_signal_unsubscribe")]
727    #[deprecated(note = "Prefer subscribe_to_signal")]
728    pub fn signal_unsubscribe(&self, subscription_id: SignalSubscriptionId) {
729        unsafe {
730            ffi::g_dbus_connection_signal_unsubscribe(
731                self.to_glib_none().0,
732                subscription_id.0.into(),
733            );
734        }
735    }
736
737    // rustdoc-stripper-ignore-next
738    /// Subscribe to a D-Bus signal and receive signal emissions as a stream.
739    ///
740    /// See [`Self::signal_subscribe`] for arguments.  `map_signal` maps the
741    /// received signal to the stream's element.
742    ///
743    /// The returned stream holds a strong reference to this D-Bus connection,
744    /// and unsubscribes from the signal when dropped. To avoid reference cycles
745    /// you may wish to downgrade the returned stream to hold only weak
746    /// reference to the connection using [`SubscribedSignalStream::downgrade`].
747    ///
748    /// After invoking `map_signal` the stream threads incoming signals through
749    /// an unbounded channel.  Hence, memory consumption will keep increasing
750    /// as long as the stream consumer does not keep up with signal emissions.
751    /// If you need to perform expensive processing in response to signals it's
752    /// therefore recommended to insert an extra buffering and if the buffer
753    /// overruns, either fail drop the entire stream, or drop individual signal
754    /// emissions until the buffer has space again.
755    pub fn receive_signal<T: 'static, F: Fn(DBusSignalRef) -> T + 'static>(
756        &self,
757        sender: Option<&str>,
758        interface_name: Option<&str>,
759        member: Option<&str>,
760        object_path: Option<&str>,
761        arg0: Option<&str>,
762        flags: DBusSignalFlags,
763        map_signal: F,
764    ) -> SubscribedSignalStream<SignalSubscription, impl Stream<Item = T> + use<T, F>> {
765        let (tx, rx) = mpsc::unbounded();
766        let subscription = self.subscribe_to_signal(
767            sender,
768            interface_name,
769            member,
770            object_path,
771            arg0,
772            flags,
773            move |signal| {
774                // Just ignore send errors: if the receiver is dropped, the
775                // signal subscription is dropped too, so the callback won't
776                // be invoked anymore.
777                let _ = tx.unbounded_send(map_signal(signal));
778            },
779        );
780        SubscribedSignalStream {
781            subscription,
782            stream: rx,
783        }
784    }
785
786    // rustdoc-stripper-ignore-next
787    /// Subscribe to a D-Bus signal and receive signal parameters as a stream.
788    ///
789    /// Like [`Self::receive_signal`] (which see for more information), but
790    /// automatically decodes the emitted signal parameters to type `T`.
791    /// If decoding fails the corresponding variant type error is sent
792    /// downstream.
793    pub fn receive_signal_parameters<T>(
794        &self,
795        sender: Option<&str>,
796        interface_name: Option<&str>,
797        member: Option<&str>,
798        object_path: Option<&str>,
799        arg0: Option<&str>,
800        flags: DBusSignalFlags,
801    ) -> SubscribedSignalStream<
802        SignalSubscription,
803        impl Stream<Item = Result<T, VariantTypeMismatchError>> + use<T>,
804    >
805    where
806        T: FromVariant + 'static,
807    {
808        self.receive_signal(
809            sender,
810            interface_name,
811            member,
812            object_path,
813            arg0,
814            flags,
815            |signal| signal.parameters.try_get(),
816        )
817    }
818}