gio/auto/dbus_connection.rs
1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4#![allow(deprecated)]
5
6#[cfg(unix)]
7#[cfg_attr(docsrs, doc(cfg(unix)))]
8use crate::UnixFDList;
9use crate::{
10 AsyncInitable, AsyncResult, Cancellable, Credentials, DBusAuthObserver, DBusCallFlags,
11 DBusCapabilityFlags, DBusConnectionFlags, DBusMessage, DBusSendMessageFlags, IOStream,
12 Initable, ffi,
13};
14use glib::{
15 object::ObjectType as _,
16 prelude::*,
17 signal::{SignalHandlerId, connect_raw},
18 translate::*,
19};
20use std::{boxed::Box as Box_, pin::Pin};
21
22glib::wrapper! {
23 /// The `GDBusConnection` type is used for D-Bus connections to remote
24 /// peers such as a message buses.
25 ///
26 /// It is a low-level API that offers a lot of flexibility. For instance,
27 /// it lets you establish a connection over any transport that can by represented
28 /// as a [`IOStream`][crate::IOStream].
29 ///
30 /// This class is rarely used directly in D-Bus clients. If you are writing
31 /// a D-Bus client, it is often easier to use the `bus_own_name()`,
32 /// `bus_watch_name()` or [`DBusProxy::for_bus()`][crate::DBusProxy::for_bus()] APIs.
33 ///
34 /// As an exception to the usual GLib rule that a particular object must not
35 /// be used by two threads at the same time, `GDBusConnection`s methods may be
36 /// called from any thread. This is so that [`bus_get()`][crate::bus_get()] and
37 /// [`bus_get_sync()`][crate::bus_get_sync()] can safely return the same `GDBusConnection` when
38 /// called from any thread.
39 ///
40 /// Most of the ways to obtain a `GDBusConnection` automatically initialize it
41 /// (i.e. connect to D-Bus): for instance, [`new()`][Self::new()] and
42 /// [`bus_get()`][crate::bus_get()], and the synchronous versions of those methods, give you
43 /// an initialized connection. Language bindings for GIO should use
44 /// [`Initable::new()`][crate::Initable::new()] or [`AsyncInitable::new_async()`][crate::AsyncInitable::new_async()], which also
45 /// initialize the connection.
46 ///
47 /// If you construct an uninitialized `GDBusConnection`, such as via
48 /// [`glib::Object::new()`][crate::glib::Object::new()], you must initialize it via [`InitableExt::init()`][crate::prelude::InitableExt::init()] or
49 /// [`AsyncInitableExt::init_async()`][crate::prelude::AsyncInitableExt::init_async()] before using its methods or properties.
50 /// Calling methods or accessing properties on a `GDBusConnection` that has not
51 /// completed initialization successfully is considered to be invalid, and leads
52 /// to undefined behaviour. In particular, if initialization fails with a
53 /// `GError`, the only valid thing you can do with that `GDBusConnection` is to
54 /// free it with `GObject::Object::unref()`.
55 ///
56 /// ## An example D-Bus server
57 ///
58 /// Here is an example for a D-Bus server:
59 /// [gdbus-example-server.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-server.c)
60 ///
61 /// ## An example for exporting a subtree
62 ///
63 /// Here is an example for exporting a subtree:
64 /// [gdbus-example-subtree.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-subtree.c)
65 ///
66 /// ## An example for file descriptor passing
67 ///
68 /// Here is an example for passing UNIX file descriptors:
69 /// [gdbus-unix-fd-client.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-unix-fd-client.c)
70 ///
71 /// ## An example for exporting a GObject
72 ///
73 /// Here is an example for exporting a #GObject:
74 /// [gdbus-example-export.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-export.c)
75 ///
76 /// ## Properties
77 ///
78 ///
79 /// #### `address`
80 /// A D-Bus address specifying potential endpoints that can be used
81 /// when establishing the connection.
82 ///
83 /// Writable | Construct Only
84 ///
85 ///
86 /// #### `authentication-observer`
87 /// A #GDBusAuthObserver object to assist in the authentication process or [`None`].
88 ///
89 /// Writable | Construct Only
90 ///
91 ///
92 /// #### `capabilities`
93 /// Flags from the #GDBusCapabilityFlags enumeration
94 /// representing connection features negotiated with the other peer.
95 ///
96 /// Readable
97 ///
98 ///
99 /// #### `closed`
100 /// A boolean specifying whether the connection has been closed.
101 ///
102 /// Readable
103 ///
104 ///
105 /// #### `exit-on-close`
106 /// A boolean specifying whether the process will be terminated (by
107 /// calling `raise(SIGTERM)`) if the connection is closed by the
108 /// remote peer.
109 ///
110 /// Note that #GDBusConnection objects returned by g_bus_get_finish()
111 /// and g_bus_get_sync() will (usually) have this property set to [`true`].
112 ///
113 /// Readable | Writable
114 ///
115 ///
116 /// #### `flags`
117 /// Flags from the #GDBusConnectionFlags enumeration.
118 ///
119 /// Readable | Writable | Construct Only
120 ///
121 ///
122 /// #### `guid`
123 /// The GUID of the peer performing the role of server when
124 /// authenticating.
125 ///
126 /// If you are constructing a #GDBusConnection and pass
127 /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER] in the
128 /// #GDBusConnection:flags property then you **must** also set this
129 /// property to a valid guid.
130 ///
131 /// If you are constructing a #GDBusConnection and pass
132 /// [`DBusConnectionFlags::AUTHENTICATION_CLIENT`][crate::DBusConnectionFlags::AUTHENTICATION_CLIENT] in the
133 /// #GDBusConnection:flags property you will be able to read the GUID
134 /// of the other peer here after the connection has been successfully
135 /// initialized.
136 ///
137 /// Note that the
138 /// [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses)
139 /// uses the term ‘UUID’ to refer to this, whereas GLib consistently uses the
140 /// term ‘GUID’ for historical reasons.
141 ///
142 /// Despite its name, the format of #GDBusConnection:guid does not follow
143 /// [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) or the Microsoft
144 /// GUID format.
145 ///
146 /// Readable | Writable | Construct Only
147 ///
148 ///
149 /// #### `max-message-unix-fds`
150 /// The maximum number of Unix file descriptors that may be received in a
151 /// single D-Bus message.
152 ///
153 /// Readable | Writable | Construct Only
154 ///
155 ///
156 /// #### `stream`
157 /// The underlying #GIOStream used for I/O.
158 ///
159 /// If this is passed on construction and is a #GSocketConnection,
160 /// then the corresponding #GSocket will be put into non-blocking mode.
161 ///
162 /// While the #GDBusConnection is active, it will interact with this
163 /// stream from a worker thread, so it is not safe to interact with
164 /// the stream directly.
165 ///
166 /// Readable | Writable | Construct Only
167 ///
168 ///
169 /// #### `unique-name`
170 /// The unique name as assigned by the message bus or [`None`] if the
171 /// connection is not open or not a message bus connection.
172 ///
173 /// Readable
174 ///
175 /// ## Signals
176 ///
177 ///
178 /// #### `closed`
179 /// Emitted when the connection is closed.
180 ///
181 /// The cause of this event can be
182 ///
183 /// - If g_dbus_connection_close() is called. In this case
184 /// @remote_peer_vanished is set to [`false`] and @error is [`None`].
185 ///
186 /// - If the remote peer closes the connection. In this case
187 /// @remote_peer_vanished is set to [`true`] and @error is set.
188 ///
189 /// - If the remote peer sends invalid or malformed data. In this
190 /// case @remote_peer_vanished is set to [`false`] and @error is set.
191 ///
192 /// Upon receiving this signal, you should give up your reference to
193 /// @connection. You are guaranteed that this signal is emitted only
194 /// once.
195 ///
196 ///
197 ///
198 /// # Implements
199 ///
200 /// [`trait@glib::ObjectExt`], [`AsyncInitableExt`][trait@crate::prelude::AsyncInitableExt], [`InitableExt`][trait@crate::prelude::InitableExt]
201 #[doc(alias = "GDBusConnection")]
202 pub struct DBusConnection(Object<ffi::GDBusConnection>) @implements AsyncInitable, Initable;
203
204 match fn {
205 type_ => || ffi::g_dbus_connection_get_type(),
206 }
207}
208
209impl DBusConnection {
210 /// Synchronously connects and sets up a D-Bus client connection for
211 /// exchanging D-Bus messages with an endpoint specified by @address
212 /// which must be in the
213 /// [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
214 ///
215 /// This constructor can only be used to initiate client-side
216 /// connections - use g_dbus_connection_new_sync() if you need to act
217 /// as the server. In particular, @flags cannot contain the
218 /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER],
219 /// [`DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS`][crate::DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS] or
220 /// [`DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER`][crate::DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER] flags.
221 ///
222 /// This is a synchronous failable constructor. See
223 /// g_dbus_connection_new_for_address() for the asynchronous version.
224 ///
225 /// If @observer is not [`None`] it may be used to control the
226 /// authentication process.
227 /// ## `address`
228 /// a D-Bus address
229 /// ## `flags`
230 /// flags describing how to make the connection
231 /// ## `observer`
232 /// a #GDBusAuthObserver or [`None`]
233 /// ## `cancellable`
234 /// a #GCancellable or [`None`]
235 ///
236 /// # Returns
237 ///
238 /// a #GDBusConnection or [`None`] if @error is set.
239 /// Free with g_object_unref().
240 #[doc(alias = "g_dbus_connection_new_for_address_sync")]
241 #[doc(alias = "new_for_address_sync")]
242 pub fn for_address_sync(
243 address: &str,
244 flags: DBusConnectionFlags,
245 observer: Option<&DBusAuthObserver>,
246 cancellable: Option<&impl IsA<Cancellable>>,
247 ) -> Result<DBusConnection, glib::Error> {
248 unsafe {
249 let mut error = std::ptr::null_mut();
250 let ret = ffi::g_dbus_connection_new_for_address_sync(
251 address.to_glib_none().0,
252 flags.into_glib(),
253 observer.to_glib_none().0,
254 cancellable.map(|p| p.as_ref()).to_glib_none().0,
255 &mut error,
256 );
257 if error.is_null() {
258 Ok(from_glib_full(ret))
259 } else {
260 Err(from_glib_full(error))
261 }
262 }
263 }
264
265 /// Synchronously sets up a D-Bus connection for exchanging D-Bus messages
266 /// with the end represented by @stream.
267 ///
268 /// If @stream is a #GSocketConnection, then the corresponding #GSocket
269 /// will be put into non-blocking mode.
270 ///
271 /// The D-Bus connection will interact with @stream from a worker thread.
272 /// As a result, the caller should not interact with @stream after this
273 /// method has been called, except by calling g_object_unref() on it.
274 ///
275 /// If @observer is not [`None`] it may be used to control the
276 /// authentication process.
277 ///
278 /// This is a synchronous failable constructor. See
279 /// g_dbus_connection_new() for the asynchronous version.
280 /// ## `stream`
281 /// a #GIOStream
282 /// ## `guid`
283 /// the GUID to use if authenticating as a server or [`None`]
284 /// ## `flags`
285 /// flags describing how to make the connection
286 /// ## `observer`
287 /// a #GDBusAuthObserver or [`None`]
288 /// ## `cancellable`
289 /// a #GCancellable or [`None`]
290 ///
291 /// # Returns
292 ///
293 /// a #GDBusConnection or [`None`] if @error is set.
294 /// Free with g_object_unref().
295 #[doc(alias = "g_dbus_connection_new_sync")]
296 pub fn new_sync(
297 stream: &impl IsA<IOStream>,
298 guid: Option<&str>,
299 flags: DBusConnectionFlags,
300 observer: Option<&DBusAuthObserver>,
301 cancellable: Option<&impl IsA<Cancellable>>,
302 ) -> Result<DBusConnection, glib::Error> {
303 unsafe {
304 let mut error = std::ptr::null_mut();
305 let ret = ffi::g_dbus_connection_new_sync(
306 stream.as_ref().to_glib_none().0,
307 guid.to_glib_none().0,
308 flags.into_glib(),
309 observer.to_glib_none().0,
310 cancellable.map(|p| p.as_ref()).to_glib_none().0,
311 &mut error,
312 );
313 if error.is_null() {
314 Ok(from_glib_full(ret))
315 } else {
316 Err(from_glib_full(error))
317 }
318 }
319 }
320
321 /// Asynchronously invokes the @method_name method on the
322 /// @interface_name D-Bus interface on the remote object at
323 /// @object_path owned by @bus_name.
324 ///
325 /// If @self is closed then the operation will fail with
326 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If @cancellable is canceled, the operation will
327 /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If @parameters contains a value
328 /// not compatible with the D-Bus protocol, the operation fails with
329 /// [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
330 ///
331 /// If @reply_type is non-[`None`] then the reply will be checked for having this type and an
332 /// error will be raised if it does not match. Said another way, if you give a @reply_type
333 /// then any non-[`None`] return value will be of this type. Unless it’s
334 /// `G_VARIANT_TYPE_UNIT`, the @reply_type will be a tuple containing one or more
335 /// values.
336 ///
337 /// If the @parameters #GVariant is floating, it is consumed. This allows
338 /// convenient 'inline' use of g_variant_new(), e.g.:
339 ///
340 ///
341 /// **⚠️ The following code is in C ⚠️**
342 ///
343 /// ```C
344 /// g_dbus_connection_call (connection,
345 /// "org.freedesktop.StringThings",
346 /// "/org/freedesktop/StringThings",
347 /// "org.freedesktop.StringThings",
348 /// "TwoStrings",
349 /// g_variant_new ("(ss)",
350 /// "Thing One",
351 /// "Thing Two"),
352 /// NULL,
353 /// G_DBUS_CALL_FLAGS_NONE,
354 /// -1,
355 /// NULL,
356 /// (GAsyncReadyCallback) two_strings_done,
357 /// NULL);
358 /// ```
359 ///
360 /// This is an asynchronous method. When the operation is finished,
361 /// @callback will be invoked in the thread-default main context
362 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
363 /// of the thread you are calling this method from. You can then call
364 /// g_dbus_connection_call_finish() to get the result of the operation.
365 /// See g_dbus_connection_call_sync() for the synchronous version of this
366 /// function.
367 ///
368 /// If @callback is [`None`] then the D-Bus method call message will be sent with
369 /// the [`DBusMessageFlags::NO_REPLY_EXPECTED`][crate::DBusMessageFlags::NO_REPLY_EXPECTED] flag set.
370 /// ## `bus_name`
371 /// a unique or well-known bus name or [`None`] if
372 /// @self is not a message bus connection
373 /// ## `object_path`
374 /// path of remote object
375 /// ## `interface_name`
376 /// D-Bus interface to invoke method on
377 /// ## `method_name`
378 /// the name of the method to invoke
379 /// ## `parameters`
380 /// a #GVariant tuple with parameters for the method
381 /// or [`None`] if not passing parameters
382 /// ## `reply_type`
383 /// the expected type of the reply (which will be a
384 /// tuple), or [`None`]
385 /// ## `flags`
386 /// flags from the #GDBusCallFlags enumeration
387 /// ## `timeout_msec`
388 /// the timeout in milliseconds, -1 to use the default
389 /// timeout or `G_MAXINT` for no timeout
390 /// ## `cancellable`
391 /// a #GCancellable or [`None`]
392 /// ## `callback`
393 /// a #GAsyncReadyCallback to call when the request
394 /// is satisfied or [`None`] if you don't care about the result of the
395 /// method invocation
396 #[doc(alias = "g_dbus_connection_call")]
397 pub fn call<P: FnOnce(Result<glib::Variant, glib::Error>) + 'static>(
398 &self,
399 bus_name: Option<&str>,
400 object_path: &str,
401 interface_name: &str,
402 method_name: &str,
403 parameters: Option<&glib::Variant>,
404 reply_type: Option<&glib::VariantTy>,
405 flags: DBusCallFlags,
406 timeout_msec: i32,
407 cancellable: Option<&impl IsA<Cancellable>>,
408 callback: P,
409 ) {
410 let main_context = glib::MainContext::ref_thread_default();
411 let is_main_context_owner = main_context.is_owner();
412 let has_acquired_main_context = (!is_main_context_owner)
413 .then(|| main_context.acquire().ok())
414 .flatten();
415 assert!(
416 is_main_context_owner || has_acquired_main_context.is_some(),
417 "Async operations only allowed if the thread is owning the MainContext"
418 );
419
420 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
421 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
422 unsafe extern "C" fn call_trampoline<
423 P: FnOnce(Result<glib::Variant, glib::Error>) + 'static,
424 >(
425 _source_object: *mut glib::gobject_ffi::GObject,
426 res: *mut crate::ffi::GAsyncResult,
427 user_data: glib::ffi::gpointer,
428 ) {
429 unsafe {
430 let mut error = std::ptr::null_mut();
431 let ret =
432 ffi::g_dbus_connection_call_finish(_source_object as *mut _, res, &mut error);
433 let result = if error.is_null() {
434 Ok(from_glib_full(ret))
435 } else {
436 Err(from_glib_full(error))
437 };
438 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
439 Box_::from_raw(user_data as *mut _);
440 let callback: P = callback.into_inner();
441 callback(result);
442 }
443 }
444 let callback = call_trampoline::<P>;
445 unsafe {
446 ffi::g_dbus_connection_call(
447 self.to_glib_none().0,
448 bus_name.to_glib_none().0,
449 object_path.to_glib_none().0,
450 interface_name.to_glib_none().0,
451 method_name.to_glib_none().0,
452 parameters.to_glib_none().0,
453 reply_type.to_glib_none().0,
454 flags.into_glib(),
455 timeout_msec,
456 cancellable.map(|p| p.as_ref()).to_glib_none().0,
457 Some(callback),
458 Box_::into_raw(user_data) as *mut _,
459 );
460 }
461 }
462
463 pub fn call_future(
464 &self,
465 bus_name: Option<&str>,
466 object_path: &str,
467 interface_name: &str,
468 method_name: &str,
469 parameters: Option<&glib::Variant>,
470 reply_type: Option<&glib::VariantTy>,
471 flags: DBusCallFlags,
472 timeout_msec: i32,
473 ) -> Pin<Box_<dyn std::future::Future<Output = Result<glib::Variant, glib::Error>> + 'static>>
474 {
475 let bus_name = bus_name.map(ToOwned::to_owned);
476 let object_path = String::from(object_path);
477 let interface_name = String::from(interface_name);
478 let method_name = String::from(method_name);
479 let parameters = parameters.map(ToOwned::to_owned);
480 let reply_type = reply_type.map(ToOwned::to_owned);
481 Box_::pin(crate::GioFuture::new(
482 self,
483 move |obj, cancellable, send| {
484 obj.call(
485 bus_name.as_ref().map(::std::borrow::Borrow::borrow),
486 &object_path,
487 &interface_name,
488 &method_name,
489 parameters.as_ref().map(::std::borrow::Borrow::borrow),
490 reply_type.as_ref().map(::std::borrow::Borrow::borrow),
491 flags,
492 timeout_msec,
493 Some(cancellable),
494 move |res| {
495 send.resolve(res);
496 },
497 );
498 },
499 ))
500 }
501
502 /// Synchronously invokes the @method_name method on the
503 /// @interface_name D-Bus interface on the remote object at
504 /// @object_path owned by @bus_name.
505 ///
506 /// If @self is closed then the operation will fail with
507 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If @cancellable is canceled, the
508 /// operation will fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If @parameters
509 /// contains a value not compatible with the D-Bus protocol, the operation
510 /// fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
511 ///
512 /// If @reply_type is non-[`None`] then the reply will be checked for having
513 /// this type and an error will be raised if it does not match. Said
514 /// another way, if you give a @reply_type then any non-[`None`] return
515 /// value will be of this type.
516 ///
517 /// If the @parameters #GVariant is floating, it is consumed.
518 /// This allows convenient 'inline' use of g_variant_new(), e.g.:
519 ///
520 ///
521 /// **⚠️ The following code is in C ⚠️**
522 ///
523 /// ```C
524 /// g_dbus_connection_call_sync (connection,
525 /// "org.freedesktop.StringThings",
526 /// "/org/freedesktop/StringThings",
527 /// "org.freedesktop.StringThings",
528 /// "TwoStrings",
529 /// g_variant_new ("(ss)",
530 /// "Thing One",
531 /// "Thing Two"),
532 /// NULL,
533 /// G_DBUS_CALL_FLAGS_NONE,
534 /// -1,
535 /// NULL,
536 /// &error);
537 /// ```
538 ///
539 /// The calling thread is blocked until a reply is received. See
540 /// g_dbus_connection_call() for the asynchronous version of
541 /// this method.
542 /// ## `bus_name`
543 /// a unique or well-known bus name or [`None`] if
544 /// @self is not a message bus connection
545 /// ## `object_path`
546 /// path of remote object
547 /// ## `interface_name`
548 /// D-Bus interface to invoke method on
549 /// ## `method_name`
550 /// the name of the method to invoke
551 /// ## `parameters`
552 /// a #GVariant tuple with parameters for the method
553 /// or [`None`] if not passing parameters
554 /// ## `reply_type`
555 /// the expected type of the reply, or [`None`]
556 /// ## `flags`
557 /// flags from the #GDBusCallFlags enumeration
558 /// ## `timeout_msec`
559 /// the timeout in milliseconds, -1 to use the default
560 /// timeout or `G_MAXINT` for no timeout
561 /// ## `cancellable`
562 /// a #GCancellable or [`None`]
563 ///
564 /// # Returns
565 ///
566 /// [`None`] if @error is set. Otherwise a non-floating
567 /// #GVariant tuple with return values. Free with g_variant_unref().
568 #[doc(alias = "g_dbus_connection_call_sync")]
569 pub fn call_sync(
570 &self,
571 bus_name: Option<&str>,
572 object_path: &str,
573 interface_name: &str,
574 method_name: &str,
575 parameters: Option<&glib::Variant>,
576 reply_type: Option<&glib::VariantTy>,
577 flags: DBusCallFlags,
578 timeout_msec: i32,
579 cancellable: Option<&impl IsA<Cancellable>>,
580 ) -> Result<glib::Variant, glib::Error> {
581 unsafe {
582 let mut error = std::ptr::null_mut();
583 let ret = ffi::g_dbus_connection_call_sync(
584 self.to_glib_none().0,
585 bus_name.to_glib_none().0,
586 object_path.to_glib_none().0,
587 interface_name.to_glib_none().0,
588 method_name.to_glib_none().0,
589 parameters.to_glib_none().0,
590 reply_type.to_glib_none().0,
591 flags.into_glib(),
592 timeout_msec,
593 cancellable.map(|p| p.as_ref()).to_glib_none().0,
594 &mut error,
595 );
596 if error.is_null() {
597 Ok(from_glib_full(ret))
598 } else {
599 Err(from_glib_full(error))
600 }
601 }
602 }
603
604 /// Like g_dbus_connection_call() but also takes a #GUnixFDList object.
605 ///
606 /// The file descriptors normally correspond to `G_VARIANT_TYPE_HANDLE`
607 /// values in the body of the message. For example, if a message contains
608 /// two file descriptors, @fd_list would have length 2, and
609 /// `g_variant_new_handle (0)` and `g_variant_new_handle (1)` would appear
610 /// somewhere in the body of the message (not necessarily in that order!)
611 /// to represent the file descriptors at indexes 0 and 1 respectively.
612 ///
613 /// When designing D-Bus APIs that are intended to be interoperable,
614 /// please note that non-GDBus implementations of D-Bus can usually only
615 /// access file descriptors if they are referenced in this way by a
616 /// value of type `G_VARIANT_TYPE_HANDLE` in the body of the message.
617 ///
618 /// This method is only available on UNIX.
619 /// ## `bus_name`
620 /// a unique or well-known bus name or [`None`] if
621 /// @self is not a message bus connection
622 /// ## `object_path`
623 /// path of remote object
624 /// ## `interface_name`
625 /// D-Bus interface to invoke method on
626 /// ## `method_name`
627 /// the name of the method to invoke
628 /// ## `parameters`
629 /// a #GVariant tuple with parameters for the method
630 /// or [`None`] if not passing parameters
631 /// ## `reply_type`
632 /// the expected type of the reply, or [`None`]
633 /// ## `flags`
634 /// flags from the #GDBusCallFlags enumeration
635 /// ## `timeout_msec`
636 /// the timeout in milliseconds, -1 to use the default
637 /// timeout or `G_MAXINT` for no timeout
638 /// ## `fd_list`
639 /// a #GUnixFDList or [`None`]
640 /// ## `cancellable`
641 /// a #GCancellable or [`None`]
642 /// ## `callback`
643 /// a #GAsyncReadyCallback to call when the request is
644 /// satisfied or [`None`] if you don't * care about the result of the
645 /// method invocation
646 #[cfg(unix)]
647 #[cfg_attr(docsrs, doc(cfg(unix)))]
648 #[doc(alias = "g_dbus_connection_call_with_unix_fd_list")]
649 pub fn call_with_unix_fd_list<
650 P: FnOnce(Result<(glib::Variant, Option<UnixFDList>), glib::Error>) + 'static,
651 >(
652 &self,
653 bus_name: Option<&str>,
654 object_path: &str,
655 interface_name: &str,
656 method_name: &str,
657 parameters: Option<&glib::Variant>,
658 reply_type: Option<&glib::VariantTy>,
659 flags: DBusCallFlags,
660 timeout_msec: i32,
661 fd_list: Option<&impl IsA<UnixFDList>>,
662 cancellable: Option<&impl IsA<Cancellable>>,
663 callback: P,
664 ) {
665 let main_context = glib::MainContext::ref_thread_default();
666 let is_main_context_owner = main_context.is_owner();
667 let has_acquired_main_context = (!is_main_context_owner)
668 .then(|| main_context.acquire().ok())
669 .flatten();
670 assert!(
671 is_main_context_owner || has_acquired_main_context.is_some(),
672 "Async operations only allowed if the thread is owning the MainContext"
673 );
674
675 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
676 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
677 unsafe extern "C" fn call_with_unix_fd_list_trampoline<
678 P: FnOnce(Result<(glib::Variant, Option<UnixFDList>), glib::Error>) + 'static,
679 >(
680 _source_object: *mut glib::gobject_ffi::GObject,
681 res: *mut crate::ffi::GAsyncResult,
682 user_data: glib::ffi::gpointer,
683 ) {
684 unsafe {
685 let mut error = std::ptr::null_mut();
686 let mut out_fd_list = std::ptr::null_mut();
687 let ret = ffi::g_dbus_connection_call_with_unix_fd_list_finish(
688 _source_object as *mut _,
689 &mut out_fd_list,
690 res,
691 &mut error,
692 );
693 let result = if error.is_null() {
694 Ok((from_glib_full(ret), from_glib_full(out_fd_list)))
695 } else {
696 Err(from_glib_full(error))
697 };
698 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
699 Box_::from_raw(user_data as *mut _);
700 let callback: P = callback.into_inner();
701 callback(result);
702 }
703 }
704 let callback = call_with_unix_fd_list_trampoline::<P>;
705 unsafe {
706 ffi::g_dbus_connection_call_with_unix_fd_list(
707 self.to_glib_none().0,
708 bus_name.to_glib_none().0,
709 object_path.to_glib_none().0,
710 interface_name.to_glib_none().0,
711 method_name.to_glib_none().0,
712 parameters.to_glib_none().0,
713 reply_type.to_glib_none().0,
714 flags.into_glib(),
715 timeout_msec,
716 fd_list.map(|p| p.as_ref()).to_glib_none().0,
717 cancellable.map(|p| p.as_ref()).to_glib_none().0,
718 Some(callback),
719 Box_::into_raw(user_data) as *mut _,
720 );
721 }
722 }
723
724 #[cfg(unix)]
725 #[cfg_attr(docsrs, doc(cfg(unix)))]
726 pub fn call_with_unix_fd_list_future(
727 &self,
728 bus_name: Option<&str>,
729 object_path: &str,
730 interface_name: &str,
731 method_name: &str,
732 parameters: Option<&glib::Variant>,
733 reply_type: Option<&glib::VariantTy>,
734 flags: DBusCallFlags,
735 timeout_msec: i32,
736 fd_list: Option<&(impl IsA<UnixFDList> + Clone + 'static)>,
737 ) -> Pin<
738 Box_<
739 dyn std::future::Future<
740 Output = Result<(glib::Variant, Option<UnixFDList>), glib::Error>,
741 > + 'static,
742 >,
743 > {
744 let bus_name = bus_name.map(ToOwned::to_owned);
745 let object_path = String::from(object_path);
746 let interface_name = String::from(interface_name);
747 let method_name = String::from(method_name);
748 let parameters = parameters.map(ToOwned::to_owned);
749 let reply_type = reply_type.map(ToOwned::to_owned);
750 let fd_list = fd_list.map(ToOwned::to_owned);
751 Box_::pin(crate::GioFuture::new(
752 self,
753 move |obj, cancellable, send| {
754 obj.call_with_unix_fd_list(
755 bus_name.as_ref().map(::std::borrow::Borrow::borrow),
756 &object_path,
757 &interface_name,
758 &method_name,
759 parameters.as_ref().map(::std::borrow::Borrow::borrow),
760 reply_type.as_ref().map(::std::borrow::Borrow::borrow),
761 flags,
762 timeout_msec,
763 fd_list.as_ref().map(::std::borrow::Borrow::borrow),
764 Some(cancellable),
765 move |res| {
766 send.resolve(res);
767 },
768 );
769 },
770 ))
771 }
772
773 /// Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
774 /// See g_dbus_connection_call_with_unix_fd_list() and
775 /// g_dbus_connection_call_with_unix_fd_list_finish() for more details.
776 ///
777 /// This method is only available on UNIX.
778 /// ## `bus_name`
779 /// a unique or well-known bus name or [`None`]
780 /// if @self is not a message bus connection
781 /// ## `object_path`
782 /// path of remote object
783 /// ## `interface_name`
784 /// D-Bus interface to invoke method on
785 /// ## `method_name`
786 /// the name of the method to invoke
787 /// ## `parameters`
788 /// a #GVariant tuple with parameters for
789 /// the method or [`None`] if not passing parameters
790 /// ## `reply_type`
791 /// the expected type of the reply, or [`None`]
792 /// ## `flags`
793 /// flags from the #GDBusCallFlags enumeration
794 /// ## `timeout_msec`
795 /// the timeout in milliseconds, -1 to use the default
796 /// timeout or `G_MAXINT` for no timeout
797 /// ## `fd_list`
798 /// a #GUnixFDList or [`None`]
799 /// ## `cancellable`
800 /// a #GCancellable or [`None`]
801 ///
802 /// # Returns
803 ///
804 /// [`None`] if @error is set. Otherwise a non-floating
805 /// #GVariant tuple with return values. Free with g_variant_unref().
806 ///
807 /// ## `out_fd_list`
808 /// return location for a #GUnixFDList or [`None`]
809 #[cfg(unix)]
810 #[cfg_attr(docsrs, doc(cfg(unix)))]
811 #[doc(alias = "g_dbus_connection_call_with_unix_fd_list_sync")]
812 pub fn call_with_unix_fd_list_sync(
813 &self,
814 bus_name: Option<&str>,
815 object_path: &str,
816 interface_name: &str,
817 method_name: &str,
818 parameters: Option<&glib::Variant>,
819 reply_type: Option<&glib::VariantTy>,
820 flags: DBusCallFlags,
821 timeout_msec: i32,
822 fd_list: Option<&impl IsA<UnixFDList>>,
823 cancellable: Option<&impl IsA<Cancellable>>,
824 ) -> Result<(glib::Variant, Option<UnixFDList>), glib::Error> {
825 unsafe {
826 let mut out_fd_list = std::ptr::null_mut();
827 let mut error = std::ptr::null_mut();
828 let ret = ffi::g_dbus_connection_call_with_unix_fd_list_sync(
829 self.to_glib_none().0,
830 bus_name.to_glib_none().0,
831 object_path.to_glib_none().0,
832 interface_name.to_glib_none().0,
833 method_name.to_glib_none().0,
834 parameters.to_glib_none().0,
835 reply_type.to_glib_none().0,
836 flags.into_glib(),
837 timeout_msec,
838 fd_list.map(|p| p.as_ref()).to_glib_none().0,
839 &mut out_fd_list,
840 cancellable.map(|p| p.as_ref()).to_glib_none().0,
841 &mut error,
842 );
843 if error.is_null() {
844 Ok((from_glib_full(ret), from_glib_full(out_fd_list)))
845 } else {
846 Err(from_glib_full(error))
847 }
848 }
849 }
850
851 /// Closes @self. Note that this never causes the process to
852 /// exit (this might only happen if the other end of a shared message
853 /// bus connection disconnects, see #GDBusConnection:exit-on-close).
854 ///
855 /// Once the connection is closed, operations such as sending a message
856 /// will return with the error [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. Closing a connection
857 /// will not automatically flush the connection so queued messages may
858 /// be lost. Use g_dbus_connection_flush() if you need such guarantees.
859 ///
860 /// If @self is already closed, this method fails with
861 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
862 ///
863 /// When @self has been closed, the #GDBusConnection::closed
864 /// signal is emitted in the thread-default main context
865 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
866 /// of the thread that @self was constructed in.
867 ///
868 /// This is an asynchronous method. When the operation is finished,
869 /// @callback will be invoked in the thread-default main context
870 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
871 /// of the thread you are calling this method from. You can
872 /// then call g_dbus_connection_close_finish() to get the result of the
873 /// operation. See g_dbus_connection_close_sync() for the synchronous
874 /// version.
875 /// ## `cancellable`
876 /// a #GCancellable or [`None`]
877 /// ## `callback`
878 /// a #GAsyncReadyCallback to call when the request is
879 /// satisfied or [`None`] if you don't care about the result
880 #[doc(alias = "g_dbus_connection_close")]
881 pub fn close<P: FnOnce(Result<(), glib::Error>) + 'static>(
882 &self,
883 cancellable: Option<&impl IsA<Cancellable>>,
884 callback: P,
885 ) {
886 let main_context = glib::MainContext::ref_thread_default();
887 let is_main_context_owner = main_context.is_owner();
888 let has_acquired_main_context = (!is_main_context_owner)
889 .then(|| main_context.acquire().ok())
890 .flatten();
891 assert!(
892 is_main_context_owner || has_acquired_main_context.is_some(),
893 "Async operations only allowed if the thread is owning the MainContext"
894 );
895
896 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
897 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
898 unsafe extern "C" fn close_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
899 _source_object: *mut glib::gobject_ffi::GObject,
900 res: *mut crate::ffi::GAsyncResult,
901 user_data: glib::ffi::gpointer,
902 ) {
903 unsafe {
904 let mut error = std::ptr::null_mut();
905 ffi::g_dbus_connection_close_finish(_source_object as *mut _, res, &mut error);
906 let result = if error.is_null() {
907 Ok(())
908 } else {
909 Err(from_glib_full(error))
910 };
911 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
912 Box_::from_raw(user_data as *mut _);
913 let callback: P = callback.into_inner();
914 callback(result);
915 }
916 }
917 let callback = close_trampoline::<P>;
918 unsafe {
919 ffi::g_dbus_connection_close(
920 self.to_glib_none().0,
921 cancellable.map(|p| p.as_ref()).to_glib_none().0,
922 Some(callback),
923 Box_::into_raw(user_data) as *mut _,
924 );
925 }
926 }
927
928 pub fn close_future(
929 &self,
930 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
931 Box_::pin(crate::GioFuture::new(
932 self,
933 move |obj, cancellable, send| {
934 obj.close(Some(cancellable), move |res| {
935 send.resolve(res);
936 });
937 },
938 ))
939 }
940
941 /// Synchronously closes @self. The calling thread is blocked
942 /// until this is done. See g_dbus_connection_close() for the
943 /// asynchronous version of this method and more details about what it
944 /// does.
945 /// ## `cancellable`
946 /// a #GCancellable or [`None`]
947 ///
948 /// # Returns
949 ///
950 /// [`true`] if the operation succeeded, [`false`] if @error is set
951 #[doc(alias = "g_dbus_connection_close_sync")]
952 pub fn close_sync(
953 &self,
954 cancellable: Option<&impl IsA<Cancellable>>,
955 ) -> Result<(), glib::Error> {
956 unsafe {
957 let mut error = std::ptr::null_mut();
958 let is_ok = ffi::g_dbus_connection_close_sync(
959 self.to_glib_none().0,
960 cancellable.map(|p| p.as_ref()).to_glib_none().0,
961 &mut error,
962 );
963 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
964 if error.is_null() {
965 Ok(())
966 } else {
967 Err(from_glib_full(error))
968 }
969 }
970 }
971
972 /// Emits a signal.
973 ///
974 /// If the parameters GVariant is floating, it is consumed.
975 ///
976 /// This can only fail if @parameters is not compatible with the D-Bus protocol
977 /// ([`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument]), or if @self has been closed
978 /// ([`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]).
979 /// ## `destination_bus_name`
980 /// the unique bus name for the destination
981 /// for the signal or [`None`] to emit to all listeners
982 /// ## `object_path`
983 /// path of remote object
984 /// ## `interface_name`
985 /// D-Bus interface to emit a signal on
986 /// ## `signal_name`
987 /// the name of the signal to emit
988 /// ## `parameters`
989 /// a #GVariant tuple with parameters for the signal
990 /// or [`None`] if not passing parameters
991 ///
992 /// # Returns
993 ///
994 /// [`true`] unless @error is set
995 #[doc(alias = "g_dbus_connection_emit_signal")]
996 pub fn emit_signal(
997 &self,
998 destination_bus_name: Option<&str>,
999 object_path: &str,
1000 interface_name: &str,
1001 signal_name: &str,
1002 parameters: Option<&glib::Variant>,
1003 ) -> Result<(), glib::Error> {
1004 unsafe {
1005 let mut error = std::ptr::null_mut();
1006 let is_ok = ffi::g_dbus_connection_emit_signal(
1007 self.to_glib_none().0,
1008 destination_bus_name.to_glib_none().0,
1009 object_path.to_glib_none().0,
1010 interface_name.to_glib_none().0,
1011 signal_name.to_glib_none().0,
1012 parameters.to_glib_none().0,
1013 &mut error,
1014 );
1015 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1016 if error.is_null() {
1017 Ok(())
1018 } else {
1019 Err(from_glib_full(error))
1020 }
1021 }
1022 }
1023
1024 /// Asynchronously flushes @self, that is, writes all queued
1025 /// outgoing messages to the transport and then flushes the transport
1026 /// (using g_output_stream_flush_async()). This is useful in programs
1027 /// that want to emit a D-Bus signal and then exit immediately. Without
1028 /// flushing the connection, there is no guarantee that the message has
1029 /// been sent to the networking buffers in the OS kernel.
1030 ///
1031 /// This is an asynchronous method. When the operation is finished,
1032 /// @callback will be invoked in the thread-default main context
1033 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
1034 /// of the thread you are calling this method from. You can
1035 /// then call g_dbus_connection_flush_finish() to get the result of the
1036 /// operation. See g_dbus_connection_flush_sync() for the synchronous
1037 /// version.
1038 /// ## `cancellable`
1039 /// a #GCancellable or [`None`]
1040 /// ## `callback`
1041 /// a #GAsyncReadyCallback to call when the
1042 /// request is satisfied or [`None`] if you don't care about the result
1043 #[doc(alias = "g_dbus_connection_flush")]
1044 pub fn flush<P: FnOnce(Result<(), glib::Error>) + 'static>(
1045 &self,
1046 cancellable: Option<&impl IsA<Cancellable>>,
1047 callback: P,
1048 ) {
1049 let main_context = glib::MainContext::ref_thread_default();
1050 let is_main_context_owner = main_context.is_owner();
1051 let has_acquired_main_context = (!is_main_context_owner)
1052 .then(|| main_context.acquire().ok())
1053 .flatten();
1054 assert!(
1055 is_main_context_owner || has_acquired_main_context.is_some(),
1056 "Async operations only allowed if the thread is owning the MainContext"
1057 );
1058
1059 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
1060 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
1061 unsafe extern "C" fn flush_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
1062 _source_object: *mut glib::gobject_ffi::GObject,
1063 res: *mut crate::ffi::GAsyncResult,
1064 user_data: glib::ffi::gpointer,
1065 ) {
1066 unsafe {
1067 let mut error = std::ptr::null_mut();
1068 ffi::g_dbus_connection_flush_finish(_source_object as *mut _, res, &mut error);
1069 let result = if error.is_null() {
1070 Ok(())
1071 } else {
1072 Err(from_glib_full(error))
1073 };
1074 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
1075 Box_::from_raw(user_data as *mut _);
1076 let callback: P = callback.into_inner();
1077 callback(result);
1078 }
1079 }
1080 let callback = flush_trampoline::<P>;
1081 unsafe {
1082 ffi::g_dbus_connection_flush(
1083 self.to_glib_none().0,
1084 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1085 Some(callback),
1086 Box_::into_raw(user_data) as *mut _,
1087 );
1088 }
1089 }
1090
1091 pub fn flush_future(
1092 &self,
1093 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
1094 Box_::pin(crate::GioFuture::new(
1095 self,
1096 move |obj, cancellable, send| {
1097 obj.flush(Some(cancellable), move |res| {
1098 send.resolve(res);
1099 });
1100 },
1101 ))
1102 }
1103
1104 /// Synchronously flushes @self. The calling thread is blocked
1105 /// until this is done. See g_dbus_connection_flush() for the
1106 /// asynchronous version of this method and more details about what it
1107 /// does.
1108 /// ## `cancellable`
1109 /// a #GCancellable or [`None`]
1110 ///
1111 /// # Returns
1112 ///
1113 /// [`true`] if the operation succeeded, [`false`] if @error is set
1114 #[doc(alias = "g_dbus_connection_flush_sync")]
1115 pub fn flush_sync(
1116 &self,
1117 cancellable: Option<&impl IsA<Cancellable>>,
1118 ) -> Result<(), glib::Error> {
1119 unsafe {
1120 let mut error = std::ptr::null_mut();
1121 let is_ok = ffi::g_dbus_connection_flush_sync(
1122 self.to_glib_none().0,
1123 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1124 &mut error,
1125 );
1126 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1127 if error.is_null() {
1128 Ok(())
1129 } else {
1130 Err(from_glib_full(error))
1131 }
1132 }
1133 }
1134
1135 /// Gets the capabilities negotiated with the remote peer
1136 ///
1137 /// # Returns
1138 ///
1139 /// zero or more flags from the #GDBusCapabilityFlags enumeration
1140 #[doc(alias = "g_dbus_connection_get_capabilities")]
1141 #[doc(alias = "get_capabilities")]
1142 pub fn capabilities(&self) -> DBusCapabilityFlags {
1143 unsafe {
1144 from_glib(ffi::g_dbus_connection_get_capabilities(
1145 self.to_glib_none().0,
1146 ))
1147 }
1148 }
1149
1150 /// Gets whether the process is terminated when @self is
1151 /// closed by the remote peer. See
1152 /// #GDBusConnection:exit-on-close for more details.
1153 ///
1154 /// # Returns
1155 ///
1156 /// whether the process is terminated when @self is
1157 /// closed by the remote peer
1158 #[doc(alias = "g_dbus_connection_get_exit_on_close")]
1159 #[doc(alias = "get_exit_on_close")]
1160 #[doc(alias = "exit-on-close")]
1161 pub fn exits_on_close(&self) -> bool {
1162 unsafe {
1163 from_glib(ffi::g_dbus_connection_get_exit_on_close(
1164 self.to_glib_none().0,
1165 ))
1166 }
1167 }
1168
1169 /// Gets the flags used to construct this connection
1170 ///
1171 /// # Returns
1172 ///
1173 /// zero or more flags from the #GDBusConnectionFlags enumeration
1174 #[cfg(feature = "v2_60")]
1175 #[cfg_attr(docsrs, doc(cfg(feature = "v2_60")))]
1176 #[doc(alias = "g_dbus_connection_get_flags")]
1177 #[doc(alias = "get_flags")]
1178 pub fn flags(&self) -> DBusConnectionFlags {
1179 unsafe { from_glib(ffi::g_dbus_connection_get_flags(self.to_glib_none().0)) }
1180 }
1181
1182 /// The GUID of the peer performing the role of server when
1183 /// authenticating. See #GDBusConnection:guid for more details.
1184 ///
1185 /// # Returns
1186 ///
1187 /// The GUID. Do not free this string, it is owned by
1188 /// @self.
1189 #[doc(alias = "g_dbus_connection_get_guid")]
1190 #[doc(alias = "get_guid")]
1191 pub fn guid(&self) -> glib::GString {
1192 unsafe { from_glib_none(ffi::g_dbus_connection_get_guid(self.to_glib_none().0)) }
1193 }
1194
1195 /// Retrieves the last serial number assigned to a #GDBusMessage on
1196 /// the current thread. This includes messages sent via both low-level
1197 /// API such as g_dbus_connection_send_message() as well as
1198 /// high-level API such as g_dbus_connection_emit_signal(),
1199 /// g_dbus_connection_call() or g_dbus_proxy_call().
1200 ///
1201 /// # Returns
1202 ///
1203 /// the last used serial or zero when no message has been sent
1204 /// within the current thread
1205 #[doc(alias = "g_dbus_connection_get_last_serial")]
1206 #[doc(alias = "get_last_serial")]
1207 pub fn last_serial(&self) -> u32 {
1208 unsafe { ffi::g_dbus_connection_get_last_serial(self.to_glib_none().0) }
1209 }
1210
1211 /// Gets the credentials of the authenticated peer. This will always
1212 /// return [`None`] unless @self acted as a server
1213 /// (e.g. [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER] was passed)
1214 /// when set up and the client passed credentials as part of the
1215 /// authentication process.
1216 ///
1217 /// In a message bus setup, the message bus is always the server and
1218 /// each application is a client. So this method will always return
1219 /// [`None`] for message bus clients.
1220 ///
1221 /// # Returns
1222 ///
1223 /// a #GCredentials or [`None`] if not
1224 /// available. Do not free this object, it is owned by @self.
1225 #[doc(alias = "g_dbus_connection_get_peer_credentials")]
1226 #[doc(alias = "get_peer_credentials")]
1227 pub fn peer_credentials(&self) -> Option<Credentials> {
1228 unsafe {
1229 from_glib_none(ffi::g_dbus_connection_get_peer_credentials(
1230 self.to_glib_none().0,
1231 ))
1232 }
1233 }
1234
1235 /// Gets the underlying stream used for IO.
1236 ///
1237 /// While the #GDBusConnection is active, it will interact with this
1238 /// stream from a worker thread, so it is not safe to interact with
1239 /// the stream directly.
1240 ///
1241 /// # Returns
1242 ///
1243 /// the stream used for IO
1244 #[doc(alias = "g_dbus_connection_get_stream")]
1245 #[doc(alias = "get_stream")]
1246 pub fn stream(&self) -> IOStream {
1247 unsafe { from_glib_none(ffi::g_dbus_connection_get_stream(self.to_glib_none().0)) }
1248 }
1249
1250 /// Gets the unique name of @self as assigned by the message
1251 /// bus. This can also be used to figure out if @self is a
1252 /// message bus connection.
1253 ///
1254 /// # Returns
1255 ///
1256 /// the unique name or [`None`] if @self is not a message
1257 /// bus connection. Do not free this string, it is owned by
1258 /// @self.
1259 #[doc(alias = "g_dbus_connection_get_unique_name")]
1260 #[doc(alias = "get_unique_name")]
1261 #[doc(alias = "unique-name")]
1262 pub fn unique_name(&self) -> Option<glib::GString> {
1263 unsafe {
1264 from_glib_none(ffi::g_dbus_connection_get_unique_name(
1265 self.to_glib_none().0,
1266 ))
1267 }
1268 }
1269
1270 /// Gets whether @self is closed.
1271 ///
1272 /// # Returns
1273 ///
1274 /// [`true`] if the connection is closed, [`false`] otherwise
1275 #[doc(alias = "g_dbus_connection_is_closed")]
1276 #[doc(alias = "closed")]
1277 pub fn is_closed(&self) -> bool {
1278 unsafe { from_glib(ffi::g_dbus_connection_is_closed(self.to_glib_none().0)) }
1279 }
1280
1281 /// Asynchronously sends @message to the peer represented by @self.
1282 ///
1283 /// Unless @flags contain the
1284 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
1285 /// will be assigned by @self and set on @message via
1286 /// g_dbus_message_set_serial(). If @out_serial is not [`None`], then the
1287 /// serial number used will be written to this location prior to
1288 /// submitting the message to the underlying transport. While it has a `volatile`
1289 /// qualifier, this is a historical artifact and the argument passed to it should
1290 /// not be `volatile`.
1291 ///
1292 /// If @self is closed then the operation will fail with
1293 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If @message is not well-formed,
1294 /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
1295 ///
1296 /// See this [server][`DBusConnection`][crate::DBusConnection]#an-example-d-bus-server]
1297 /// and [client][`DBusConnection`][crate::DBusConnection]#an-example-for-file-descriptor-passing]
1298 /// for an example of how to use this low-level API to send and receive
1299 /// UNIX file descriptors.
1300 ///
1301 /// Note that @message must be unlocked, unless @flags contain the
1302 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
1303 /// ## `message`
1304 /// a #GDBusMessage
1305 /// ## `flags`
1306 /// flags affecting how the message is sent
1307 ///
1308 /// # Returns
1309 ///
1310 /// [`true`] if the message was well-formed and queued for
1311 /// transmission, [`false`] if @error is set
1312 ///
1313 /// ## `out_serial`
1314 /// return location for serial number assigned
1315 /// to @message when sending it or [`None`]
1316 #[doc(alias = "g_dbus_connection_send_message")]
1317 pub fn send_message(
1318 &self,
1319 message: &DBusMessage,
1320 flags: DBusSendMessageFlags,
1321 ) -> Result<u32, glib::Error> {
1322 unsafe {
1323 let mut out_serial = std::mem::MaybeUninit::uninit();
1324 let mut error = std::ptr::null_mut();
1325 let is_ok = ffi::g_dbus_connection_send_message(
1326 self.to_glib_none().0,
1327 message.to_glib_none().0,
1328 flags.into_glib(),
1329 out_serial.as_mut_ptr(),
1330 &mut error,
1331 );
1332 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1333 if error.is_null() {
1334 Ok(out_serial.assume_init())
1335 } else {
1336 Err(from_glib_full(error))
1337 }
1338 }
1339 }
1340
1341 /// Asynchronously sends @message to the peer represented by @self.
1342 ///
1343 /// Unless @flags contain the
1344 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
1345 /// will be assigned by @self and set on @message via
1346 /// g_dbus_message_set_serial(). If @out_serial is not [`None`], then the
1347 /// serial number used will be written to this location prior to
1348 /// submitting the message to the underlying transport. While it has a `volatile`
1349 /// qualifier, this is a historical artifact and the argument passed to it should
1350 /// not be `volatile`.
1351 ///
1352 /// If @self is closed then the operation will fail with
1353 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If @cancellable is canceled, the operation will
1354 /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If @message is not well-formed,
1355 /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
1356 ///
1357 /// This is an asynchronous method. When the operation is finished, @callback
1358 /// will be invoked in the thread-default main context
1359 /// (see [`glib::MainContext::push_thread_default()`][crate::glib::MainContext::push_thread_default()])
1360 /// of the thread you are calling this method from. You can then call
1361 /// g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1362 /// See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1363 ///
1364 /// Note that @message must be unlocked, unless @flags contain the
1365 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
1366 ///
1367 /// See this [server][`DBusConnection`][crate::DBusConnection]#an-example-d-bus-server]
1368 /// and [client][`DBusConnection`][crate::DBusConnection]#an-example-for-file-descriptor-passing]
1369 /// for an example of how to use this low-level API to send and receive
1370 /// UNIX file descriptors.
1371 /// ## `message`
1372 /// a #GDBusMessage
1373 /// ## `flags`
1374 /// flags affecting how the message is sent
1375 /// ## `timeout_msec`
1376 /// the timeout in milliseconds, -1 to use the default
1377 /// timeout or `G_MAXINT` for no timeout
1378 /// ## `cancellable`
1379 /// a #GCancellable or [`None`]
1380 /// ## `callback`
1381 /// a #GAsyncReadyCallback to call when the request
1382 /// is satisfied or [`None`] if you don't care about the result
1383 ///
1384 /// # Returns
1385 ///
1386 ///
1387 /// ## `out_serial`
1388 /// return location for serial number assigned
1389 /// to @message when sending it or [`None`]
1390 #[doc(alias = "g_dbus_connection_send_message_with_reply")]
1391 pub fn send_message_with_reply<P: FnOnce(Result<DBusMessage, glib::Error>) + 'static>(
1392 &self,
1393 message: &DBusMessage,
1394 flags: DBusSendMessageFlags,
1395 timeout_msec: i32,
1396 cancellable: Option<&impl IsA<Cancellable>>,
1397 callback: P,
1398 ) -> u32 {
1399 let main_context = glib::MainContext::ref_thread_default();
1400 let is_main_context_owner = main_context.is_owner();
1401 let has_acquired_main_context = (!is_main_context_owner)
1402 .then(|| main_context.acquire().ok())
1403 .flatten();
1404 assert!(
1405 is_main_context_owner || has_acquired_main_context.is_some(),
1406 "Async operations only allowed if the thread is owning the MainContext"
1407 );
1408
1409 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
1410 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
1411 unsafe extern "C" fn send_message_with_reply_trampoline<
1412 P: FnOnce(Result<DBusMessage, glib::Error>) + 'static,
1413 >(
1414 _source_object: *mut glib::gobject_ffi::GObject,
1415 res: *mut crate::ffi::GAsyncResult,
1416 user_data: glib::ffi::gpointer,
1417 ) {
1418 unsafe {
1419 let mut error = std::ptr::null_mut();
1420 let ret = ffi::g_dbus_connection_send_message_with_reply_finish(
1421 _source_object as *mut _,
1422 res,
1423 &mut error,
1424 );
1425 let result = if error.is_null() {
1426 Ok(from_glib_full(ret))
1427 } else {
1428 Err(from_glib_full(error))
1429 };
1430 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
1431 Box_::from_raw(user_data as *mut _);
1432 let callback: P = callback.into_inner();
1433 callback(result);
1434 }
1435 }
1436 let callback = send_message_with_reply_trampoline::<P>;
1437 unsafe {
1438 let mut out_serial = std::mem::MaybeUninit::uninit();
1439 ffi::g_dbus_connection_send_message_with_reply(
1440 self.to_glib_none().0,
1441 message.to_glib_none().0,
1442 flags.into_glib(),
1443 timeout_msec,
1444 out_serial.as_mut_ptr(),
1445 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1446 Some(callback),
1447 Box_::into_raw(user_data) as *mut _,
1448 );
1449 out_serial.assume_init()
1450 }
1451 }
1452
1453 pub fn send_message_with_reply_future(
1454 &self,
1455 message: &DBusMessage,
1456 flags: DBusSendMessageFlags,
1457 timeout_msec: i32,
1458 ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusMessage, glib::Error>> + 'static>>
1459 {
1460 let message = message.clone();
1461 Box_::pin(crate::GioFuture::new(
1462 self,
1463 move |obj, cancellable, send| {
1464 obj.send_message_with_reply(
1465 &message,
1466 flags,
1467 timeout_msec,
1468 Some(cancellable),
1469 move |res| {
1470 send.resolve(res);
1471 },
1472 );
1473 },
1474 ))
1475 }
1476
1477 /// Synchronously sends @message to the peer represented by @self
1478 /// and blocks the calling thread until a reply is received or the
1479 /// timeout is reached. See g_dbus_connection_send_message_with_reply()
1480 /// for the asynchronous version of this method.
1481 ///
1482 /// Unless @flags contain the
1483 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
1484 /// will be assigned by @self and set on @message via
1485 /// g_dbus_message_set_serial(). If @out_serial is not [`None`], then the
1486 /// serial number used will be written to this location prior to
1487 /// submitting the message to the underlying transport. While it has a `volatile`
1488 /// qualifier, this is a historical artifact and the argument passed to it should
1489 /// not be `volatile`.
1490 ///
1491 /// If @self is closed then the operation will fail with
1492 /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If @cancellable is canceled, the operation will
1493 /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If @message is not well-formed,
1494 /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
1495 ///
1496 /// Note that @error is only set if a local in-process error
1497 /// occurred. That is to say that the returned #GDBusMessage object may
1498 /// be of type [`DBusMessageType::Error`][crate::DBusMessageType::Error]. Use
1499 /// g_dbus_message_to_gerror() to transcode this to a #GError.
1500 ///
1501 /// See this [server][`DBusConnection`][crate::DBusConnection]#an-example-d-bus-server]
1502 /// and [client][`DBusConnection`][crate::DBusConnection]#an-example-for-file-descriptor-passing]
1503 /// for an example of how to use this low-level API to send and receive
1504 /// UNIX file descriptors.
1505 ///
1506 /// Note that @message must be unlocked, unless @flags contain the
1507 /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
1508 /// ## `message`
1509 /// a #GDBusMessage
1510 /// ## `flags`
1511 /// flags affecting how the message is sent.
1512 /// ## `timeout_msec`
1513 /// the timeout in milliseconds, -1 to use the default
1514 /// timeout or `G_MAXINT` for no timeout
1515 /// ## `cancellable`
1516 /// a #GCancellable or [`None`]
1517 ///
1518 /// # Returns
1519 ///
1520 /// a locked #GDBusMessage that is the reply
1521 /// to @message or [`None`] if @error is set
1522 ///
1523 /// ## `out_serial`
1524 /// return location for serial number
1525 /// assigned to @message when sending it or [`None`]
1526 #[doc(alias = "g_dbus_connection_send_message_with_reply_sync")]
1527 pub fn send_message_with_reply_sync(
1528 &self,
1529 message: &DBusMessage,
1530 flags: DBusSendMessageFlags,
1531 timeout_msec: i32,
1532 cancellable: Option<&impl IsA<Cancellable>>,
1533 ) -> Result<(DBusMessage, u32), glib::Error> {
1534 unsafe {
1535 let mut out_serial = std::mem::MaybeUninit::uninit();
1536 let mut error = std::ptr::null_mut();
1537 let ret = ffi::g_dbus_connection_send_message_with_reply_sync(
1538 self.to_glib_none().0,
1539 message.to_glib_none().0,
1540 flags.into_glib(),
1541 timeout_msec,
1542 out_serial.as_mut_ptr(),
1543 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1544 &mut error,
1545 );
1546 if error.is_null() {
1547 Ok((from_glib_full(ret), out_serial.assume_init()))
1548 } else {
1549 Err(from_glib_full(error))
1550 }
1551 }
1552 }
1553
1554 /// Sets whether the process should be terminated when @self is
1555 /// closed by the remote peer. See #GDBusConnection:exit-on-close for
1556 /// more details.
1557 ///
1558 /// Note that this function should be used with care. Most modern UNIX
1559 /// desktops tie the notion of a user session with the session bus, and expect
1560 /// all of a user's applications to quit when their bus connection goes away.
1561 /// If you are setting @exit_on_close to [`false`] for the shared session
1562 /// bus connection, you should make sure that your application exits
1563 /// when the user session ends.
1564 /// ## `exit_on_close`
1565 /// whether the process should be terminated
1566 /// when @self is closed by the remote peer
1567 #[doc(alias = "g_dbus_connection_set_exit_on_close")]
1568 #[doc(alias = "exit-on-close")]
1569 pub fn set_exit_on_close(&self, exit_on_close: bool) {
1570 unsafe {
1571 ffi::g_dbus_connection_set_exit_on_close(
1572 self.to_glib_none().0,
1573 exit_on_close.into_glib(),
1574 );
1575 }
1576 }
1577
1578 /// If @self was created with
1579 /// [`DBusConnectionFlags::DELAY_MESSAGE_PROCESSING`][crate::DBusConnectionFlags::DELAY_MESSAGE_PROCESSING], this method
1580 /// starts processing messages. Does nothing on if @self wasn't
1581 /// created with this flag or if the method has already been called.
1582 #[doc(alias = "g_dbus_connection_start_message_processing")]
1583 pub fn start_message_processing(&self) {
1584 unsafe {
1585 ffi::g_dbus_connection_start_message_processing(self.to_glib_none().0);
1586 }
1587 }
1588
1589 #[cfg(not(feature = "v2_60"))]
1590 #[cfg_attr(docsrs, doc(cfg(not(feature = "v2_60"))))]
1591 pub fn flags(&self) -> DBusConnectionFlags {
1592 ObjectExt::property(self, "flags")
1593 }
1594
1595 /// The maximum number of Unix file descriptors that may be received in a
1596 /// single D-Bus message.
1597 #[cfg(feature = "v2_92")]
1598 #[cfg_attr(docsrs, doc(cfg(feature = "v2_92")))]
1599 #[doc(alias = "max-message-unix-fds")]
1600 pub fn max_message_unix_fds(&self) -> u32 {
1601 ObjectExt::property(self, "max-message-unix-fds")
1602 }
1603
1604 /// Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1605 /// with the end represented by @stream.
1606 ///
1607 /// If @stream is a #GSocketConnection, then the corresponding #GSocket
1608 /// will be put into non-blocking mode.
1609 ///
1610 /// The D-Bus connection will interact with @stream from a worker thread.
1611 /// As a result, the caller should not interact with @stream after this
1612 /// method has been called, except by calling g_object_unref() on it.
1613 ///
1614 /// If @observer is not [`None`] it may be used to control the
1615 /// authentication process.
1616 ///
1617 /// When the operation is finished, @callback will be invoked. You can
1618 /// then call g_dbus_connection_new_finish() to get the result of the
1619 /// operation.
1620 ///
1621 /// This is an asynchronous failable constructor. See
1622 /// g_dbus_connection_new_sync() for the synchronous
1623 /// version.
1624 /// ## `stream`
1625 /// a #GIOStream
1626 /// ## `guid`
1627 /// the GUID to use if authenticating as a server or [`None`]
1628 /// ## `flags`
1629 /// flags describing how to make the connection
1630 /// ## `observer`
1631 /// a #GDBusAuthObserver or [`None`]
1632 /// ## `cancellable`
1633 /// a #GCancellable or [`None`]
1634 /// ## `callback`
1635 /// a #GAsyncReadyCallback to call when the request is satisfied
1636 #[doc(alias = "g_dbus_connection_new")]
1637 pub fn new<P: FnOnce(Result<DBusConnection, glib::Error>) + 'static>(
1638 stream: &impl IsA<IOStream>,
1639 guid: Option<&str>,
1640 flags: DBusConnectionFlags,
1641 observer: Option<&DBusAuthObserver>,
1642 cancellable: Option<&impl IsA<Cancellable>>,
1643 callback: P,
1644 ) {
1645 let main_context = glib::MainContext::ref_thread_default();
1646 let is_main_context_owner = main_context.is_owner();
1647 let has_acquired_main_context = (!is_main_context_owner)
1648 .then(|| main_context.acquire().ok())
1649 .flatten();
1650 assert!(
1651 is_main_context_owner || has_acquired_main_context.is_some(),
1652 "Async operations only allowed if the thread is owning the MainContext"
1653 );
1654
1655 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
1656 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
1657 unsafe extern "C" fn new_trampoline<
1658 P: FnOnce(Result<DBusConnection, glib::Error>) + 'static,
1659 >(
1660 _source_object: *mut glib::gobject_ffi::GObject,
1661 res: *mut crate::ffi::GAsyncResult,
1662 user_data: glib::ffi::gpointer,
1663 ) {
1664 unsafe {
1665 let mut error = std::ptr::null_mut();
1666 let ret = ffi::g_dbus_connection_new_finish(res, &mut error);
1667 let result = if error.is_null() {
1668 Ok(from_glib_full(ret))
1669 } else {
1670 Err(from_glib_full(error))
1671 };
1672 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
1673 Box_::from_raw(user_data as *mut _);
1674 let callback: P = callback.into_inner();
1675 callback(result);
1676 }
1677 }
1678 let callback = new_trampoline::<P>;
1679 unsafe {
1680 ffi::g_dbus_connection_new(
1681 stream.as_ref().to_glib_none().0,
1682 guid.to_glib_none().0,
1683 flags.into_glib(),
1684 observer.to_glib_none().0,
1685 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1686 Some(callback),
1687 Box_::into_raw(user_data) as *mut _,
1688 );
1689 }
1690 }
1691
1692 pub fn new_future(
1693 stream: &(impl IsA<IOStream> + Clone + 'static),
1694 guid: Option<&str>,
1695 flags: DBusConnectionFlags,
1696 observer: Option<&DBusAuthObserver>,
1697 ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusConnection, glib::Error>> + 'static>>
1698 {
1699 let stream = stream.clone();
1700 let guid = guid.map(ToOwned::to_owned);
1701 let observer = observer.map(ToOwned::to_owned);
1702 Box_::pin(crate::GioFuture::new(
1703 &(),
1704 move |_obj, cancellable, send| {
1705 Self::new(
1706 &stream,
1707 guid.as_ref().map(::std::borrow::Borrow::borrow),
1708 flags,
1709 observer.as_ref().map(::std::borrow::Borrow::borrow),
1710 Some(cancellable),
1711 move |res| {
1712 send.resolve(res);
1713 },
1714 );
1715 },
1716 ))
1717 }
1718
1719 /// Asynchronously connects and sets up a D-Bus client connection for
1720 /// exchanging D-Bus messages with an endpoint specified by @address
1721 /// which must be in the
1722 /// [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1723 ///
1724 /// This constructor can only be used to initiate client-side
1725 /// connections - use g_dbus_connection_new() if you need to act as the
1726 /// server. In particular, @flags cannot contain the
1727 /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER],
1728 /// [`DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS`][crate::DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS] or
1729 /// [`DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER`][crate::DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER] flags.
1730 ///
1731 /// When the operation is finished, @callback will be invoked. You can
1732 /// then call g_dbus_connection_new_for_address_finish() to get the result of
1733 /// the operation.
1734 ///
1735 /// If @observer is not [`None`] it may be used to control the
1736 /// authentication process.
1737 ///
1738 /// This is an asynchronous failable constructor. See
1739 /// g_dbus_connection_new_for_address_sync() for the synchronous
1740 /// version.
1741 /// ## `address`
1742 /// a D-Bus address
1743 /// ## `flags`
1744 /// flags describing how to make the connection
1745 /// ## `observer`
1746 /// a #GDBusAuthObserver or [`None`]
1747 /// ## `cancellable`
1748 /// a #GCancellable or [`None`]
1749 /// ## `callback`
1750 /// a #GAsyncReadyCallback to call when the request is satisfied
1751 #[doc(alias = "g_dbus_connection_new_for_address")]
1752 #[doc(alias = "new_for_address")]
1753 pub fn for_address<P: FnOnce(Result<DBusConnection, glib::Error>) + 'static>(
1754 address: &str,
1755 flags: DBusConnectionFlags,
1756 observer: Option<&DBusAuthObserver>,
1757 cancellable: Option<&impl IsA<Cancellable>>,
1758 callback: P,
1759 ) {
1760 let main_context = glib::MainContext::ref_thread_default();
1761 let is_main_context_owner = main_context.is_owner();
1762 let has_acquired_main_context = (!is_main_context_owner)
1763 .then(|| main_context.acquire().ok())
1764 .flatten();
1765 assert!(
1766 is_main_context_owner || has_acquired_main_context.is_some(),
1767 "Async operations only allowed if the thread is owning the MainContext"
1768 );
1769
1770 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
1771 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
1772 unsafe extern "C" fn for_address_trampoline<
1773 P: FnOnce(Result<DBusConnection, glib::Error>) + 'static,
1774 >(
1775 _source_object: *mut glib::gobject_ffi::GObject,
1776 res: *mut crate::ffi::GAsyncResult,
1777 user_data: glib::ffi::gpointer,
1778 ) {
1779 unsafe {
1780 let mut error = std::ptr::null_mut();
1781 let ret = ffi::g_dbus_connection_new_for_address_finish(res, &mut error);
1782 let result = if error.is_null() {
1783 Ok(from_glib_full(ret))
1784 } else {
1785 Err(from_glib_full(error))
1786 };
1787 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
1788 Box_::from_raw(user_data as *mut _);
1789 let callback: P = callback.into_inner();
1790 callback(result);
1791 }
1792 }
1793 let callback = for_address_trampoline::<P>;
1794 unsafe {
1795 ffi::g_dbus_connection_new_for_address(
1796 address.to_glib_none().0,
1797 flags.into_glib(),
1798 observer.to_glib_none().0,
1799 cancellable.map(|p| p.as_ref()).to_glib_none().0,
1800 Some(callback),
1801 Box_::into_raw(user_data) as *mut _,
1802 );
1803 }
1804 }
1805
1806 pub fn for_address_future(
1807 address: &str,
1808 flags: DBusConnectionFlags,
1809 observer: Option<&DBusAuthObserver>,
1810 ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusConnection, glib::Error>> + 'static>>
1811 {
1812 let address = String::from(address);
1813 let observer = observer.map(ToOwned::to_owned);
1814 Box_::pin(crate::GioFuture::new(
1815 &(),
1816 move |_obj, cancellable, send| {
1817 Self::for_address(
1818 &address,
1819 flags,
1820 observer.as_ref().map(::std::borrow::Borrow::borrow),
1821 Some(cancellable),
1822 move |res| {
1823 send.resolve(res);
1824 },
1825 );
1826 },
1827 ))
1828 }
1829
1830 /// Emitted when the connection is closed.
1831 ///
1832 /// The cause of this event can be
1833 ///
1834 /// - If g_dbus_connection_close() is called. In this case
1835 /// @remote_peer_vanished is set to [`false`] and @error is [`None`].
1836 ///
1837 /// - If the remote peer closes the connection. In this case
1838 /// @remote_peer_vanished is set to [`true`] and @error is set.
1839 ///
1840 /// - If the remote peer sends invalid or malformed data. In this
1841 /// case @remote_peer_vanished is set to [`false`] and @error is set.
1842 ///
1843 /// Upon receiving this signal, you should give up your reference to
1844 /// @connection. You are guaranteed that this signal is emitted only
1845 /// once.
1846 /// ## `remote_peer_vanished`
1847 /// [`true`] if @connection is closed because the
1848 /// remote peer closed its end of the connection
1849 /// ## `error`
1850 /// a #GError with more details about the event or [`None`]
1851 #[doc(alias = "closed")]
1852 pub fn connect_closed<F: Fn(&Self, bool, Option<&glib::Error>) + Send + Sync + 'static>(
1853 &self,
1854 f: F,
1855 ) -> SignalHandlerId {
1856 unsafe extern "C" fn closed_trampoline<
1857 F: Fn(&DBusConnection, bool, Option<&glib::Error>) + Send + Sync + 'static,
1858 >(
1859 this: *mut ffi::GDBusConnection,
1860 remote_peer_vanished: glib::ffi::gboolean,
1861 error: *mut glib::ffi::GError,
1862 f: glib::ffi::gpointer,
1863 ) {
1864 unsafe {
1865 let f: &F = &*(f as *const F);
1866 f(
1867 &from_glib_borrow(this),
1868 from_glib(remote_peer_vanished),
1869 Option::<glib::Error>::from_glib_borrow(error)
1870 .as_ref()
1871 .as_ref(),
1872 )
1873 }
1874 }
1875 unsafe {
1876 let f: Box_<F> = Box_::new(f);
1877 connect_raw(
1878 self.as_ptr() as *mut _,
1879 c"closed".as_ptr(),
1880 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1881 closed_trampoline::<F> as *const (),
1882 )),
1883 Box_::into_raw(f),
1884 )
1885 }
1886 }
1887
1888 #[doc(alias = "capabilities")]
1889 pub fn connect_capabilities_notify<F: Fn(&Self) + Send + Sync + 'static>(
1890 &self,
1891 f: F,
1892 ) -> SignalHandlerId {
1893 unsafe extern "C" fn notify_capabilities_trampoline<
1894 F: Fn(&DBusConnection) + Send + Sync + 'static,
1895 >(
1896 this: *mut ffi::GDBusConnection,
1897 _param_spec: glib::ffi::gpointer,
1898 f: glib::ffi::gpointer,
1899 ) {
1900 unsafe {
1901 let f: &F = &*(f as *const F);
1902 f(&from_glib_borrow(this))
1903 }
1904 }
1905 unsafe {
1906 let f: Box_<F> = Box_::new(f);
1907 connect_raw(
1908 self.as_ptr() as *mut _,
1909 c"notify::capabilities".as_ptr(),
1910 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1911 notify_capabilities_trampoline::<F> as *const (),
1912 )),
1913 Box_::into_raw(f),
1914 )
1915 }
1916 }
1917
1918 #[doc(alias = "closed")]
1919 pub fn connect_closed_notify<F: Fn(&Self) + Send + Sync + 'static>(
1920 &self,
1921 f: F,
1922 ) -> SignalHandlerId {
1923 unsafe extern "C" fn notify_closed_trampoline<
1924 F: Fn(&DBusConnection) + Send + Sync + 'static,
1925 >(
1926 this: *mut ffi::GDBusConnection,
1927 _param_spec: glib::ffi::gpointer,
1928 f: glib::ffi::gpointer,
1929 ) {
1930 unsafe {
1931 let f: &F = &*(f as *const F);
1932 f(&from_glib_borrow(this))
1933 }
1934 }
1935 unsafe {
1936 let f: Box_<F> = Box_::new(f);
1937 connect_raw(
1938 self.as_ptr() as *mut _,
1939 c"notify::closed".as_ptr(),
1940 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1941 notify_closed_trampoline::<F> as *const (),
1942 )),
1943 Box_::into_raw(f),
1944 )
1945 }
1946 }
1947
1948 #[doc(alias = "exit-on-close")]
1949 pub fn connect_exit_on_close_notify<F: Fn(&Self) + Send + Sync + 'static>(
1950 &self,
1951 f: F,
1952 ) -> SignalHandlerId {
1953 unsafe extern "C" fn notify_exit_on_close_trampoline<
1954 F: Fn(&DBusConnection) + Send + Sync + 'static,
1955 >(
1956 this: *mut ffi::GDBusConnection,
1957 _param_spec: glib::ffi::gpointer,
1958 f: glib::ffi::gpointer,
1959 ) {
1960 unsafe {
1961 let f: &F = &*(f as *const F);
1962 f(&from_glib_borrow(this))
1963 }
1964 }
1965 unsafe {
1966 let f: Box_<F> = Box_::new(f);
1967 connect_raw(
1968 self.as_ptr() as *mut _,
1969 c"notify::exit-on-close".as_ptr(),
1970 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1971 notify_exit_on_close_trampoline::<F> as *const (),
1972 )),
1973 Box_::into_raw(f),
1974 )
1975 }
1976 }
1977
1978 #[doc(alias = "unique-name")]
1979 pub fn connect_unique_name_notify<F: Fn(&Self) + Send + Sync + 'static>(
1980 &self,
1981 f: F,
1982 ) -> SignalHandlerId {
1983 unsafe extern "C" fn notify_unique_name_trampoline<
1984 F: Fn(&DBusConnection) + Send + Sync + 'static,
1985 >(
1986 this: *mut ffi::GDBusConnection,
1987 _param_spec: glib::ffi::gpointer,
1988 f: glib::ffi::gpointer,
1989 ) {
1990 unsafe {
1991 let f: &F = &*(f as *const F);
1992 f(&from_glib_borrow(this))
1993 }
1994 }
1995 unsafe {
1996 let f: Box_<F> = Box_::new(f);
1997 connect_raw(
1998 self.as_ptr() as *mut _,
1999 c"notify::unique-name".as_ptr(),
2000 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
2001 notify_unique_name_trampoline::<F> as *const (),
2002 )),
2003 Box_::into_raw(f),
2004 )
2005 }
2006 }
2007}
2008
2009unsafe impl Send for DBusConnection {}
2010unsafe impl Sync for DBusConnection {}