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 ActionGroupExportId(NonZeroU32);
117#[derive(Debug, Eq, PartialEq)]
118pub struct MenuModelExportId(NonZeroU32);
119#[derive(Debug, Eq, PartialEq)]
120pub struct FilterId(NonZeroU32);
121
122#[derive(Debug, Eq, PartialEq)]
123pub struct SignalSubscriptionId(NonZeroU32);
124
125// rustdoc-stripper-ignore-next
126/// A strong subscription to a D-Bus signal.
127///
128/// Keep a reference to a D-Bus connection to maintain a subscription on a
129/// D-Bus signal even if the connection has no other strong reference.
130///
131/// When dropped, unsubscribes from signal on the connection, and then drop the
132/// reference on the connection. If no other strong reference on the connection
133/// exists the connection is closed and destroyed.
134#[derive(Debug)]
135pub struct SignalSubscription(DBusConnection, Option<SignalSubscriptionId>);
136
137impl SignalSubscription {
138 // rustdoc-stripper-ignore-next
139 /// Downgrade this signal subscription to a weak one.
140 #[must_use]
141 pub fn downgrade(mut self) -> WeakSignalSubscription {
142 WeakSignalSubscription(self.0.downgrade(), self.1.take())
143 }
144}
145
146impl Drop for SignalSubscription {
147 fn drop(&mut self) {
148 if let Some(id) = self.1.take() {
149 #[allow(deprecated)]
150 self.0.signal_unsubscribe(id);
151 }
152 }
153}
154
155// rustdoc-stripper-ignore-next
156/// A weak subscription to a D-Bus signal.
157///
158/// Like [`SignalSubscription`] but hold only a weak reference to the D-Bus
159/// connection the signal is subscribed on, i.e. maintain the subscription on
160/// the D-Bus signal only as long as some strong reference exists on the
161/// corresponding D-Bus connection.
162///
163/// When dropped, unsubscribes from signal on the connection if it still exists,
164/// and then drop the reference on the connection. If no other strong reference
165/// on the connection exists the connection is closed and destroyed.
166#[derive(Debug)]
167pub struct WeakSignalSubscription(WeakRef<DBusConnection>, Option<SignalSubscriptionId>);
168
169impl WeakSignalSubscription {
170 // rustdoc-stripper-ignore-next
171 /// Upgrade this signal subscription to a strong one.
172 #[must_use]
173 pub fn upgrade(mut self) -> Option<SignalSubscription> {
174 self.0
175 .upgrade()
176 .map(|c| SignalSubscription(c, self.1.take()))
177 }
178}
179
180impl Drop for WeakSignalSubscription {
181 fn drop(&mut self) {
182 if let Some(id) = self.1.take()
183 && let Some(connection) = self.0.upgrade()
184 {
185 #[allow(deprecated)]
186 connection.signal_unsubscribe(id);
187 }
188 }
189}
190
191// rustdoc-stripper-ignore-next
192/// An emitted D-Bus signal.
193#[derive(Debug, Copy, Clone)]
194pub struct DBusSignalRef<'a> {
195 // rustdoc-stripper-ignore-next
196 /// The connection the signal was emitted on.
197 pub connection: &'a DBusConnection,
198 // rustdoc-stripper-ignore-next
199 /// The bus name of the sender which emitted the signal.
200 pub sender_name: &'a str,
201 // rustdoc-stripper-ignore-next
202 /// The path of the object on `sender` the signal was emitted from.
203 pub object_path: &'a str,
204 // rustdoc-stripper-ignore-next
205 /// The interface the signal belongs to.
206 pub interface_name: &'a str,
207 // rustdoc-stripper-ignore-next
208 /// The name of the emitted signal.
209 pub signal_name: &'a str,
210 // rustdoc-stripper-ignore-next
211 /// Parameters the signal was emitted with.
212 pub parameters: &'a glib::Variant,
213}
214
215pin_project! {
216 // rustdoc-stripper-ignore-next
217 /// A subscribed stream.
218 ///
219 /// A stream which wraps an inner stream of type `S` while holding on to a
220 /// subscription handle `H` to keep a subscription alive.
221 #[derive(Debug)]
222 #[must_use = "streams do nothing unless polled"]
223 pub struct SubscribedSignalStream<H, S> {
224 #[pin]
225 stream: S,
226 subscription: H,
227 }
228}
229
230impl<S> SubscribedSignalStream<SignalSubscription, S> {
231 // rustdoc-stripper-ignore-next
232 /// Downgrade the inner signal subscription to a weak one.
233 ///
234 /// See [`SignalSubscription::downgrade`] and [`WeakSignalSubscription`].
235 pub fn downgrade(self) -> SubscribedSignalStream<WeakSignalSubscription, S> {
236 SubscribedSignalStream {
237 subscription: self.subscription.downgrade(),
238 stream: self.stream,
239 }
240 }
241}
242
243impl<S> SubscribedSignalStream<WeakSignalSubscription, S> {
244 // rustdoc-stripper-ignore-next
245 /// Upgrade the inner signal subscription to a strong one.
246 ///
247 /// See [`WeakSignalSubscription::upgrade`] and [`SignalSubscription`].
248 pub fn downgrade(self) -> Option<SubscribedSignalStream<SignalSubscription, S>> {
249 self.subscription
250 .upgrade()
251 .map(|subscription| SubscribedSignalStream {
252 subscription,
253 stream: self.stream,
254 })
255 }
256}
257
258impl<H, S> Stream for SubscribedSignalStream<H, S>
259where
260 S: Stream,
261{
262 type Item = S::Item;
263
264 fn poll_next(
265 self: std::pin::Pin<&mut Self>,
266 cx: &mut std::task::Context<'_>,
267 ) -> std::task::Poll<Option<Self::Item>> {
268 let this = self.project();
269 this.stream.poll_next(cx)
270 }
271
272 fn size_hint(&self) -> (usize, Option<usize>) {
273 self.stream.size_hint()
274 }
275}
276
277impl<H, S> FusedStream for SubscribedSignalStream<H, S>
278where
279 S: FusedStream,
280{
281 fn is_terminated(&self) -> bool {
282 self.stream.is_terminated()
283 }
284}
285
286// rustdoc-stripper-ignore-next
287/// Build a registered DBus object, by handling different parts of DBus.
288#[must_use = "The builder must be built to be used"]
289pub struct RegistrationBuilder<'a> {
290 connection: &'a DBusConnection,
291 object_path: &'a str,
292 interface_info: &'a DBusInterfaceInfo,
293 #[allow(clippy::type_complexity)]
294 method_call: Option<
295 Box_<
296 dyn Fn(
297 DBusConnection,
298 Option<&str>,
299 &str,
300 Option<&str>,
301 &str,
302 glib::Variant,
303 DBusMethodInvocation,
304 ),
305 >,
306 >,
307 #[allow(clippy::type_complexity)]
308 get_property:
309 Option<Box_<dyn Fn(DBusConnection, Option<&str>, &str, &str, &str) -> glib::Variant>>,
310 #[allow(clippy::type_complexity)]
311 set_property:
312 Option<Box_<dyn Fn(DBusConnection, Option<&str>, &str, &str, &str, glib::Variant) -> bool>>,
313}
314
315impl<'a> RegistrationBuilder<'a> {
316 pub fn method_call<
317 F: Fn(
318 DBusConnection,
319 Option<&str>,
320 &str,
321 Option<&str>,
322 &str,
323 glib::Variant,
324 DBusMethodInvocation,
325 ) + 'static,
326 >(
327 mut self,
328 f: F,
329 ) -> Self {
330 self.method_call = Some(Box_::new(f));
331 self
332 }
333
334 // rustdoc-stripper-ignore-next
335 /// Handle method calls on this object.
336 ///
337 /// Return a builder for method calls which parses method names and
338 /// parameters with the given [`DBusMethodCall`] and then allows to dispatch
339 /// the parsed call either synchronously or asynchronously.
340 pub fn typed_method_call<T: DBusMethodCall>(self) -> MethodCallBuilder<'a, T> {
341 MethodCallBuilder {
342 registration: self,
343 capture_type: Default::default(),
344 }
345 }
346
347 #[doc(alias = "get_property")]
348 pub fn property<
349 F: Fn(DBusConnection, Option<&str>, &str, &str, &str) -> glib::Variant + 'static,
350 >(
351 mut self,
352 f: F,
353 ) -> Self {
354 self.get_property = Some(Box_::new(f));
355 self
356 }
357
358 pub fn set_property<
359 F: Fn(DBusConnection, Option<&str>, &str, &str, &str, glib::Variant) -> bool + 'static,
360 >(
361 mut self,
362 f: F,
363 ) -> Self {
364 self.set_property = Some(Box_::new(f));
365 self
366 }
367
368 pub fn build(self) -> Result<RegistrationId, glib::Error> {
369 unsafe {
370 let mut error = std::ptr::null_mut();
371 let id = ffi::g_dbus_connection_register_object_with_closures(
372 self.connection.to_glib_none().0,
373 self.object_path.to_glib_none().0,
374 self.interface_info.to_glib_none().0,
375 self.method_call
376 .map(|f| {
377 glib::Closure::new_local(move |args| {
378 let conn = args[0].get::<DBusConnection>().unwrap();
379 let sender = args[1].get::<Option<&str>>().unwrap();
380 let object_path = args[2].get::<&str>().unwrap();
381 let interface_name = args[3].get::<Option<&str>>().unwrap();
382 let method_name = args[4].get::<&str>().unwrap();
383 let parameters = args[5].get::<glib::Variant>().unwrap();
384
385 // Work around GLib memory leak: Assume that the invocation is passed
386 // as `transfer full` into the closure.
387 //
388 // This workaround is not going to break with future versions of
389 // GLib as fixing the bug was considered a breaking API change.
390 //
391 // See https://gitlab.gnome.org/GNOME/glib/-/merge_requests/4427
392 let invocation = from_glib_full(glib::gobject_ffi::g_value_get_object(
393 args[6].as_ptr(),
394 )
395 as *mut ffi::GDBusMethodInvocation);
396
397 f(
398 conn,
399 sender,
400 object_path,
401 interface_name,
402 method_name,
403 parameters,
404 invocation,
405 );
406 None
407 })
408 })
409 .to_glib_none()
410 .0,
411 self.get_property
412 .map(|f| {
413 glib::Closure::new_local(move |args| {
414 let conn = args[0].get::<DBusConnection>().unwrap();
415 let sender = args[1].get::<Option<&str>>().unwrap();
416 let object_path = args[2].get::<&str>().unwrap();
417 let interface_name = args[3].get::<&str>().unwrap();
418 let property_name = args[4].get::<&str>().unwrap();
419 let result =
420 f(conn, sender, object_path, interface_name, property_name);
421 Some(result.to_value())
422 })
423 })
424 .to_glib_none()
425 .0,
426 self.set_property
427 .map(|f| {
428 glib::Closure::new_local(move |args| {
429 let conn = args[0].get::<DBusConnection>().unwrap();
430 let sender = args[1].get::<Option<&str>>().unwrap();
431 let object_path = args[2].get::<&str>().unwrap();
432 let interface_name = args[3].get::<&str>().unwrap();
433 let property_name = args[4].get::<&str>().unwrap();
434 let value = args[5].get::<glib::Variant>().unwrap();
435 let result = f(
436 conn,
437 sender,
438 object_path,
439 interface_name,
440 property_name,
441 value,
442 );
443 Some(result.to_value())
444 })
445 })
446 .to_glib_none()
447 .0,
448 &mut error,
449 );
450
451 if error.is_null() {
452 Ok(RegistrationId(NonZeroU32::new_unchecked(id)))
453 } else {
454 Err(from_glib_full(error))
455 }
456 }
457 }
458}
459
460impl DBusConnection {
461 /// Registers callbacks for exported objects at @object_path with the
462 /// D-Bus interface that is described in @interface_info.
463 ///
464 /// Calls to functions in @vtable (and @user_data_free_func) will happen
465 /// in the thread-default main context
466 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
467 /// of the thread you are calling this method from.
468 ///
469 /// Note that all #GVariant values passed to functions in @vtable will match
470 /// the signature given in @interface_info - if a remote caller passes
471 /// incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
472 /// is returned to the remote caller.
473 ///
474 /// Additionally, if the remote caller attempts to invoke methods or
475 /// access properties not mentioned in @interface_info the
476 /// `org.freedesktop.DBus.Error.UnknownMethod` resp.
477 /// `org.freedesktop.DBus.Error.InvalidArgs` errors
478 /// are returned to the caller.
479 ///
480 /// It is considered a programming error if the
481 /// #GDBusInterfaceGetPropertyFunc function in @vtable returns a
482 /// #GVariant of incorrect type.
483 ///
484 /// If an existing callback is already registered at @object_path and
485 /// @interface_name, then @error is set to [`IOErrorEnum::Exists`][crate::IOErrorEnum::Exists].
486 ///
487 /// GDBus automatically implements the standard D-Bus interfaces
488 /// org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
489 /// and org.freedesktop.Peer, so you don't have to implement those for the
490 /// objects you export. You can implement org.freedesktop.DBus.Properties
491 /// yourself, e.g. to handle getting and setting of properties asynchronously.
492 ///
493 /// Note that the reference count on @interface_info will be
494 /// incremented by 1 (unless allocated statically, e.g. if the
495 /// reference count is -1, see g_dbus_interface_info_ref()) for as long
496 /// as the object is exported. Also note that @vtable will be copied.
497 ///
498 /// See this [server][`DBusConnection`][crate::DBusConnection]#an-example-d-bus-server]
499 /// for an example of how to use this method.
500 /// ## `object_path`
501 /// the object path to register at
502 /// ## `interface_info`
503 /// introspection data for the interface
504 /// ## `vtable`
505 /// a #GDBusInterfaceVTable to call into or [`None`]
506 ///
507 /// # Returns
508 ///
509 /// 0 if @error is set, otherwise a registration id (never 0)
510 /// that can be used with g_dbus_connection_unregister_object()
511 #[doc(alias = "g_dbus_connection_register_object")]
512 #[doc(alias = "g_dbus_connection_register_object_with_closures")]
513 pub fn register_object<'a>(
514 &'a self,
515 object_path: &'a str,
516 interface_info: &'a DBusInterfaceInfo,
517 ) -> RegistrationBuilder<'a> {
518 RegistrationBuilder {
519 connection: self,
520 object_path,
521 interface_info,
522 method_call: None,
523 get_property: None,
524 set_property: None,
525 }
526 }
527
528 /// Unregisters an object.
529 /// ## `registration_id`
530 /// a registration id obtained from
531 /// g_dbus_connection_register_object()
532 ///
533 /// # Returns
534 ///
535 /// [`true`] if the object was unregistered, [`false`] otherwise
536 #[doc(alias = "g_dbus_connection_unregister_object")]
537 pub fn unregister_object(
538 &self,
539 registration_id: RegistrationId,
540 ) -> Result<(), glib::error::BoolError> {
541 unsafe {
542 glib::result_from_gboolean!(
543 ffi::g_dbus_connection_unregister_object(
544 self.to_glib_none().0,
545 registration_id.0.into()
546 ),
547 "Failed to unregister D-Bus object"
548 )
549 }
550 }
551
552 /// Exports @action_group on @self at @object_path.
553 ///
554 /// The implemented D-Bus API should be considered private. It is
555 /// subject to change in the future.
556 ///
557 /// A given object path can only have one action group exported on it.
558 /// If this constraint is violated, the export will fail and 0 will be
559 /// returned (with @error set accordingly).
560 ///
561 /// You can unexport the action group using
562 /// [`unexport_action_group()`][Self::unexport_action_group()] with the return value of
563 /// this function.
564 ///
565 /// The thread default main context is taken at the time of this call.
566 /// All incoming action activations and state change requests are
567 /// reported from this context. Any changes on the action group that
568 /// cause it to emit signals must also come from this same context.
569 /// Since incoming action activations and state change requests are
570 /// rather likely to cause changes on the action group, this effectively
571 /// limits a given action group to being exported from only one main
572 /// context.
573 /// ## `object_path`
574 /// a D-Bus object path
575 /// ## `action_group`
576 /// an action group
577 ///
578 /// # Returns
579 ///
580 /// the ID of the export (never zero), or 0 in case of failure
581 #[doc(alias = "g_dbus_connection_export_action_group")]
582 pub fn export_action_group<P: IsA<ActionGroup>>(
583 &self,
584 object_path: &str,
585 action_group: &P,
586 ) -> Result<ActionGroupExportId, glib::Error> {
587 unsafe {
588 let mut error = std::ptr::null_mut();
589 let id = ffi::g_dbus_connection_export_action_group(
590 self.to_glib_none().0,
591 object_path.to_glib_none().0,
592 action_group.as_ref().to_glib_none().0,
593 &mut error,
594 );
595 if error.is_null() {
596 Ok(ActionGroupExportId(NonZeroU32::new_unchecked(id)))
597 } else {
598 Err(from_glib_full(error))
599 }
600 }
601 }
602
603 /// Reverses the effect of a previous call to
604 /// [`export_action_group()`][Self::export_action_group()].
605 ///
606 /// It is an error to call this function with an ID that wasn’t returned from
607 /// [`export_action_group()`][Self::export_action_group()] or to call it with the same
608 /// ID more than once.
609 /// ## `export_id`
610 /// the ID from [`export_action_group()`][Self::export_action_group()]
611 #[doc(alias = "g_dbus_connection_unexport_action_group")]
612 pub fn unexport_action_group(&self, export_id: ActionGroupExportId) {
613 unsafe {
614 ffi::g_dbus_connection_unexport_action_group(self.to_glib_none().0, export_id.0.into());
615 }
616 }
617
618 /// Exports @menu on @self at @object_path.
619 ///
620 /// The implemented D-Bus API should be considered private.
621 /// It is subject to change in the future.
622 ///
623 /// An object path can only have one menu model exported on it. If this
624 /// constraint is violated, the export will fail and 0 will be
625 /// returned (with @error set accordingly).
626 ///
627 /// Exporting menus with sections containing more than
628 /// `G_MENU_EXPORTER_MAX_SECTION_SIZE` items is not supported and results in
629 /// undefined behavior.
630 ///
631 /// You can unexport the menu model using
632 /// g_dbus_connection_unexport_menu_model() with the return value of
633 /// this function.
634 /// ## `object_path`
635 /// a D-Bus object path
636 /// ## `menu`
637 /// a #GMenuModel
638 ///
639 /// # Returns
640 ///
641 /// the ID of the export (never zero), or 0 in case of failure
642 #[doc(alias = "g_dbus_connection_export_menu_model")]
643 pub fn export_menu_model<P: IsA<MenuModel>>(
644 &self,
645 object_path: &str,
646 menu: &P,
647 ) -> Result<MenuModelExportId, glib::Error> {
648 unsafe {
649 let mut error = std::ptr::null_mut();
650 let id = ffi::g_dbus_connection_export_menu_model(
651 self.to_glib_none().0,
652 object_path.to_glib_none().0,
653 menu.as_ref().to_glib_none().0,
654 &mut error,
655 );
656 if error.is_null() {
657 Ok(MenuModelExportId(NonZeroU32::new_unchecked(id)))
658 } else {
659 Err(from_glib_full(error))
660 }
661 }
662 }
663
664 /// Reverses the effect of a previous call to
665 /// g_dbus_connection_export_menu_model().
666 ///
667 /// It is an error to call this function with an ID that wasn't returned
668 /// from g_dbus_connection_export_menu_model() or to call it with the
669 /// same ID more than once.
670 /// ## `export_id`
671 /// the ID from g_dbus_connection_export_menu_model()
672 #[doc(alias = "g_dbus_connection_unexport_menu_model")]
673 pub fn unexport_menu_model(&self, export_id: MenuModelExportId) {
674 unsafe {
675 ffi::g_dbus_connection_unexport_menu_model(self.to_glib_none().0, export_id.0.into());
676 }
677 }
678
679 /// Adds a message filter. Filters are handlers that are run on all
680 /// incoming and outgoing messages, prior to standard dispatch. Filters
681 /// are run in the order that they were added. The same handler can be
682 /// added as a filter more than once, in which case it will be run more
683 /// than once. Filters added during a filter callback won't be run on
684 /// the message being processed. Filter functions are allowed to modify
685 /// and even drop messages.
686 ///
687 /// Note that filters are run in a dedicated message handling thread so
688 /// they can't block and, generally, can't do anything but signal a
689 /// worker thread. Also note that filters are rarely needed - use API
690 /// such as g_dbus_connection_send_message_with_reply(),
691 /// g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
692 ///
693 /// If a filter consumes an incoming message the message is not
694 /// dispatched anywhere else - not even the standard dispatch machinery
695 /// (that API such as g_dbus_connection_signal_subscribe() and
696 /// g_dbus_connection_send_message_with_reply() relies on) will see the
697 /// message. Similarly, if a filter consumes an outgoing message, the
698 /// message will not be sent to the other peer.
699 ///
700 /// If @user_data_free_func is non-[`None`], it will be called (in the
701 /// thread-default main context of the thread you are calling this
702 /// method from) at some point after @user_data is no longer
703 /// needed. (It is not guaranteed to be called synchronously when the
704 /// filter is removed, and may be called after @self has been
705 /// destroyed.)
706 /// ## `filter_function`
707 /// a filter function
708 ///
709 /// # Returns
710 ///
711 /// a filter identifier that can be used with
712 /// g_dbus_connection_remove_filter()
713 #[doc(alias = "g_dbus_connection_add_filter")]
714 pub fn add_filter<
715 P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
716 >(
717 &self,
718 filter_function: P,
719 ) -> FilterId {
720 let filter_function_data: Box_<P> = Box_::new(filter_function);
721 unsafe extern "C" fn filter_function_func<
722 P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
723 >(
724 connection: *mut ffi::GDBusConnection,
725 message: *mut ffi::GDBusMessage,
726 incoming: glib::ffi::gboolean,
727 user_data: glib::ffi::gpointer,
728 ) -> *mut ffi::GDBusMessage {
729 unsafe {
730 let connection = from_glib_borrow(connection);
731 let message = from_glib_full(message);
732 let incoming = from_glib(incoming);
733 let callback: &P = &*(user_data as *mut _);
734 let res = (*callback)(&connection, &message, incoming);
735 res.into_glib_ptr()
736 }
737 }
738 let filter_function = Some(filter_function_func::<P> as _);
739 unsafe extern "C" fn user_data_free_func_func<
740 P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
741 >(
742 data: glib::ffi::gpointer,
743 ) {
744 unsafe {
745 let _callback: Box_<P> = Box_::from_raw(data as *mut _);
746 }
747 }
748 let destroy_call3 = Some(user_data_free_func_func::<P> as _);
749 let super_callback0: Box_<P> = filter_function_data;
750 unsafe {
751 let id = ffi::g_dbus_connection_add_filter(
752 self.to_glib_none().0,
753 filter_function,
754 Box_::into_raw(super_callback0) as *mut _,
755 destroy_call3,
756 );
757 FilterId(NonZeroU32::new_unchecked(id))
758 }
759 }
760
761 /// Removes a filter.
762 ///
763 /// Note that since filters run in a different thread, there is a race
764 /// condition where it is possible that the filter will be running even
765 /// after calling g_dbus_connection_remove_filter(), so you cannot just
766 /// free data that the filter might be using. Instead, you should pass
767 /// a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
768 /// called when it is guaranteed that the data is no longer needed.
769 /// ## `filter_id`
770 /// an identifier obtained from g_dbus_connection_add_filter()
771 #[doc(alias = "g_dbus_connection_remove_filter")]
772 pub fn remove_filter(&self, filter_id: FilterId) {
773 unsafe {
774 ffi::g_dbus_connection_remove_filter(self.to_glib_none().0, filter_id.0.into());
775 }
776 }
777
778 // rustdoc-stripper-ignore-next
779 /// Subscribe to a D-Bus signal.
780 ///
781 /// See [`Self::signal_subscribe`] for arguments.
782 ///
783 /// Return a signal subscription which keeps a reference to this D-Bus
784 /// connection and unsubscribes from the signal when dropped.
785 ///
786 /// To avoid reference cycles you may wish to downgrade the returned
787 /// subscription to a weak one with [`SignalSubscription::downgrade`].
788 #[must_use]
789 pub fn subscribe_to_signal<P: Fn(DBusSignalRef) + 'static>(
790 &self,
791 sender: Option<&str>,
792 interface_name: Option<&str>,
793 member: Option<&str>,
794 object_path: Option<&str>,
795 arg0: Option<&str>,
796 flags: DBusSignalFlags,
797 callback: P,
798 ) -> SignalSubscription {
799 #[allow(deprecated)]
800 let id = self.signal_subscribe(
801 sender,
802 interface_name,
803 member,
804 object_path,
805 arg0,
806 flags,
807 move |connection, sender_name, object_path, interface_name, signal_name, parameters| {
808 callback(DBusSignalRef {
809 connection,
810 sender_name,
811 object_path,
812 interface_name,
813 signal_name,
814 parameters,
815 });
816 },
817 );
818 SignalSubscription(self.clone(), Some(id))
819 }
820
821 /// Subscribes to signals on @self and invokes @callback whenever
822 /// the signal is received. Note that @callback will be invoked in the
823 /// thread-default main context (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
824 /// of the thread you are calling this method from.
825 ///
826 /// If @self is not a message bus connection, @sender must be
827 /// [`None`].
828 ///
829 /// If @sender is a well-known name note that @callback is invoked with
830 /// the unique name for the owner of @sender, not the well-known name
831 /// as one would expect. This is because the message bus rewrites the
832 /// name. As such, to avoid certain race conditions, users should be
833 /// tracking the name owner of the well-known name and use that when
834 /// processing the received signal.
835 ///
836 /// If one of [`DBusSignalFlags::MATCH_ARG0_NAMESPACE`][crate::DBusSignalFlags::MATCH_ARG0_NAMESPACE] or
837 /// [`DBusSignalFlags::MATCH_ARG0_PATH`][crate::DBusSignalFlags::MATCH_ARG0_PATH] are given, @arg0 is
838 /// interpreted as part of a namespace or path. The first argument
839 /// of a signal is matched against that part as specified by D-Bus.
840 ///
841 /// If @user_data_free_func is non-[`None`], it will be called (in the
842 /// thread-default main context of the thread you are calling this
843 /// method from) at some point after @user_data is no longer
844 /// needed. (It is not guaranteed to be called synchronously when the
845 /// signal is unsubscribed from, and may be called after @self
846 /// has been destroyed.)
847 ///
848 /// As @callback is potentially invoked in a different thread from where it’s
849 /// emitted, it’s possible for this to happen after
850 /// g_dbus_connection_signal_unsubscribe() has been called in another thread.
851 /// Due to this, @user_data should have a strong reference which is freed with
852 /// @user_data_free_func, rather than pointing to data whose lifecycle is tied
853 /// to the signal subscription. For example, if a #GObject is used to store the
854 /// subscription ID from g_dbus_connection_signal_subscribe(), a strong reference
855 /// to that #GObject must be passed to @user_data, and g_object_unref() passed to
856 /// @user_data_free_func. You are responsible for breaking the resulting
857 /// reference count cycle by explicitly unsubscribing from the signal when
858 /// dropping the last external reference to the #GObject. Alternatively, a weak
859 /// reference may be used.
860 ///
861 /// It is guaranteed that if you unsubscribe from a signal using
862 /// g_dbus_connection_signal_unsubscribe() from the same thread which made the
863 /// corresponding g_dbus_connection_signal_subscribe() call, @callback will not
864 /// be invoked after g_dbus_connection_signal_unsubscribe() returns.
865 ///
866 /// The returned subscription identifier is an opaque value which is guaranteed
867 /// to never be zero.
868 ///
869 /// This function can never fail.
870 /// ## `sender`
871 /// sender name to match on (unique or well-known name)
872 /// or [`None`] to listen from all senders
873 /// ## `interface_name`
874 /// D-Bus interface name to match on or [`None`] to
875 /// match on all interfaces
876 /// ## `member`
877 /// D-Bus signal name to match on or [`None`] to match on
878 /// all signals
879 /// ## `object_path`
880 /// object path to match on or [`None`] to match on
881 /// all object paths
882 /// ## `arg0`
883 /// contents of first string argument to match on or [`None`]
884 /// to match on all kinds of arguments
885 /// ## `flags`
886 /// #GDBusSignalFlags describing how arg0 is used in subscribing to the
887 /// signal
888 /// ## `callback`
889 /// callback to invoke when there is a signal matching the requested data
890 ///
891 /// # Returns
892 ///
893 /// a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
894 #[doc(alias = "g_dbus_connection_signal_subscribe")]
895 #[allow(clippy::too_many_arguments)]
896 #[deprecated(note = "Prefer subscribe_to_signal")]
897 pub fn signal_subscribe<
898 P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
899 >(
900 &self,
901 sender: Option<&str>,
902 interface_name: Option<&str>,
903 member: Option<&str>,
904 object_path: Option<&str>,
905 arg0: Option<&str>,
906 flags: DBusSignalFlags,
907 callback: P,
908 ) -> SignalSubscriptionId {
909 let callback_data: Box_<P> = Box_::new(callback);
910 unsafe extern "C" fn callback_func<
911 P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
912 >(
913 connection: *mut ffi::GDBusConnection,
914 sender_name: *const libc::c_char,
915 object_path: *const libc::c_char,
916 interface_name: *const libc::c_char,
917 signal_name: *const libc::c_char,
918 parameters: *mut glib::ffi::GVariant,
919 user_data: glib::ffi::gpointer,
920 ) {
921 unsafe {
922 let connection = from_glib_borrow(connection);
923 let sender_name: Borrowed<glib::GString> = from_glib_borrow(sender_name);
924 let object_path: Borrowed<glib::GString> = from_glib_borrow(object_path);
925 let interface_name: Borrowed<glib::GString> = from_glib_borrow(interface_name);
926 let signal_name: Borrowed<glib::GString> = from_glib_borrow(signal_name);
927 let parameters = from_glib_borrow(parameters);
928 let callback: &P = &*(user_data as *mut _);
929 (*callback)(
930 &connection,
931 sender_name.as_str(),
932 object_path.as_str(),
933 interface_name.as_str(),
934 signal_name.as_str(),
935 ¶meters,
936 );
937 }
938 }
939 let callback = Some(callback_func::<P> as _);
940 unsafe extern "C" fn user_data_free_func_func<
941 P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
942 >(
943 data: glib::ffi::gpointer,
944 ) {
945 unsafe {
946 let _callback: Box_<P> = Box_::from_raw(data as *mut _);
947 }
948 }
949 let destroy_call9 = Some(user_data_free_func_func::<P> as _);
950 let super_callback0: Box_<P> = callback_data;
951 unsafe {
952 let id = ffi::g_dbus_connection_signal_subscribe(
953 self.to_glib_none().0,
954 sender.to_glib_none().0,
955 interface_name.to_glib_none().0,
956 member.to_glib_none().0,
957 object_path.to_glib_none().0,
958 arg0.to_glib_none().0,
959 flags.into_glib(),
960 callback,
961 Box_::into_raw(super_callback0) as *mut _,
962 destroy_call9,
963 );
964 SignalSubscriptionId(NonZeroU32::new_unchecked(id))
965 }
966 }
967
968 /// Unsubscribes from signals.
969 ///
970 /// Note that there may still be D-Bus traffic to process (relating to this
971 /// signal subscription) in the current thread-default #GMainContext after this
972 /// function has returned. You should continue to iterate the #GMainContext
973 /// until the #GDestroyNotify function passed to
974 /// g_dbus_connection_signal_subscribe() is called, in order to avoid memory
975 /// leaks through callbacks queued on the #GMainContext after it’s stopped being
976 /// iterated.
977 /// Alternatively, any idle source with a priority lower than `G_PRIORITY_DEFAULT`
978 /// that was scheduled after unsubscription, also indicates that all resources
979 /// of this subscription are released.
980 /// ## `subscription_id`
981 /// a subscription id obtained from
982 /// g_dbus_connection_signal_subscribe()
983 #[doc(alias = "g_dbus_connection_signal_unsubscribe")]
984 #[deprecated(note = "Prefer subscribe_to_signal")]
985 pub fn signal_unsubscribe(&self, subscription_id: SignalSubscriptionId) {
986 unsafe {
987 ffi::g_dbus_connection_signal_unsubscribe(
988 self.to_glib_none().0,
989 subscription_id.0.into(),
990 );
991 }
992 }
993
994 // rustdoc-stripper-ignore-next
995 /// Subscribe to a D-Bus signal and receive signal emissions as a stream.
996 ///
997 /// See [`Self::signal_subscribe`] for arguments. `map_signal` maps the
998 /// received signal to the stream's element.
999 ///
1000 /// The returned stream holds a strong reference to this D-Bus connection,
1001 /// and unsubscribes from the signal when dropped. To avoid reference cycles
1002 /// you may wish to downgrade the returned stream to hold only weak
1003 /// reference to the connection using [`SubscribedSignalStream::downgrade`].
1004 ///
1005 /// After invoking `map_signal` the stream threads incoming signals through
1006 /// an unbounded channel. Hence, memory consumption will keep increasing
1007 /// as long as the stream consumer does not keep up with signal emissions.
1008 /// If you need to perform expensive processing in response to signals it's
1009 /// therefore recommended to insert an extra buffering and if the buffer
1010 /// overruns, either fail drop the entire stream, or drop individual signal
1011 /// emissions until the buffer has space again.
1012 pub fn receive_signal<T: 'static, F: Fn(DBusSignalRef) -> T + 'static>(
1013 &self,
1014 sender: Option<&str>,
1015 interface_name: Option<&str>,
1016 member: Option<&str>,
1017 object_path: Option<&str>,
1018 arg0: Option<&str>,
1019 flags: DBusSignalFlags,
1020 map_signal: F,
1021 ) -> SubscribedSignalStream<SignalSubscription, impl Stream<Item = T> + use<T, F>> {
1022 let (tx, rx) = mpsc::unbounded();
1023 let subscription = self.subscribe_to_signal(
1024 sender,
1025 interface_name,
1026 member,
1027 object_path,
1028 arg0,
1029 flags,
1030 move |signal| {
1031 // Just ignore send errors: if the receiver is dropped, the
1032 // signal subscription is dropped too, so the callback won't
1033 // be invoked anymore.
1034 let _ = tx.unbounded_send(map_signal(signal));
1035 },
1036 );
1037 SubscribedSignalStream {
1038 subscription,
1039 stream: rx,
1040 }
1041 }
1042
1043 // rustdoc-stripper-ignore-next
1044 /// Subscribe to a D-Bus signal and receive signal parameters as a stream.
1045 ///
1046 /// Like [`Self::receive_signal`] (which see for more information), but
1047 /// automatically decodes the emitted signal parameters to type `T`.
1048 /// If decoding fails the corresponding variant type error is sent
1049 /// downstream.
1050 pub fn receive_signal_parameters<T>(
1051 &self,
1052 sender: Option<&str>,
1053 interface_name: Option<&str>,
1054 member: Option<&str>,
1055 object_path: Option<&str>,
1056 arg0: Option<&str>,
1057 flags: DBusSignalFlags,
1058 ) -> SubscribedSignalStream<
1059 SignalSubscription,
1060 impl Stream<Item = Result<T, VariantTypeMismatchError>> + use<T>,
1061 >
1062 where
1063 T: FromVariant + 'static,
1064 {
1065 self.receive_signal(
1066 sender,
1067 interface_name,
1068 member,
1069 object_path,
1070 arg0,
1071 flags,
1072 |signal| signal.parameters.try_get(),
1073 )
1074 }
1075}