1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
// Take a look at the license at the top of the repository in the LICENSE file.
use std::{boxed::Box as Box_, num::NonZeroU32};
use glib::{prelude::*, translate::*};
use crate::{
ActionGroup, DBusConnection, DBusInterfaceInfo, DBusMessage, DBusMethodInvocation,
DBusSignalFlags, MenuModel,
};
#[derive(Debug, Eq, PartialEq)]
pub struct RegistrationId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct WatcherId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct ActionGroupExportId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct MenuModelExportId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct FilterId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct SignalSubscriptionId(NonZeroU32);
impl DBusConnection {
/// Registers callbacks for exported objects at `object_path` with the
/// D-Bus interface that is described in `interface_info`.
///
/// Calls to functions in `vtable` (and `user_data_free_func`) will happen
/// in the
/// [thread-default main context][g-main-context-push-thread-default]
/// of the thread you are calling this method from.
///
/// Note that all [`glib::Variant`][struct@crate::glib::Variant] values passed to functions in `vtable` will match
/// the signature given in `interface_info` - if a remote caller passes
/// incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
/// is returned to the remote caller.
///
/// Additionally, if the remote caller attempts to invoke methods or
/// access properties not mentioned in `interface_info` the
/// `org.freedesktop.DBus.Error.UnknownMethod` resp.
/// `org.freedesktop.DBus.Error.InvalidArgs` errors
/// are returned to the caller.
///
/// It is considered a programming error if the
/// `GDBusInterfaceGetPropertyFunc` function in `vtable` returns a
/// [`glib::Variant`][struct@crate::glib::Variant] of incorrect type.
///
/// If an existing callback is already registered at `object_path` and
/// `interface_name`, then `error` is set to [`IOErrorEnum::Exists`][crate::IOErrorEnum::Exists].
///
/// GDBus automatically implements the standard D-Bus interfaces
/// org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
/// and org.freedesktop.Peer, so you don't have to implement those for the
/// objects you export. You can implement org.freedesktop.DBus.Properties
/// yourself, e.g. to handle getting and setting of properties asynchronously.
///
/// Note that the reference count on `interface_info` will be
/// incremented by 1 (unless allocated statically, e.g. if the
/// reference count is -1, see `g_dbus_interface_info_ref()`) for as long
/// as the object is exported. Also note that `vtable` will be copied.
///
/// See this [server][gdbus-server] for an example of how to use this method.
/// ## `object_path`
/// the object path to register at
/// ## `interface_info`
/// introspection data for the interface
/// ## `vtable`
/// a `GDBusInterfaceVTable` to call into or [`None`]
///
/// # Returns
///
/// 0 if `error` is set, otherwise a registration id (never 0)
/// that can be used with [`unregister_object()`][Self::unregister_object()]
#[doc(alias = "g_dbus_connection_register_object_with_closures")]
pub fn register_object<MethodCall, SetProperty, GetProperty>(
&self,
object_path: &str,
interface_info: &DBusInterfaceInfo,
method_call: MethodCall,
get_property: GetProperty,
set_property: SetProperty,
) -> Result<RegistrationId, glib::Error>
where
MethodCall: Fn(DBusConnection, &str, &str, &str, &str, glib::Variant, DBusMethodInvocation)
+ Send
+ Sync
+ 'static,
GetProperty:
Fn(DBusConnection, &str, &str, &str, &str) -> glib::Variant + Send + Sync + 'static,
SetProperty: Fn(DBusConnection, &str, &str, &str, &str, glib::Variant) -> bool
+ Send
+ Sync
+ 'static,
{
unsafe {
let mut error = std::ptr::null_mut();
let id = ffi::g_dbus_connection_register_object_with_closures(
self.to_glib_none().0,
object_path.to_glib_none().0,
interface_info.to_glib_none().0,
glib::Closure::new(move |args| {
let conn = args[0].get::<DBusConnection>().unwrap();
let sender = args[1].get::<&str>().unwrap();
let object_path = args[2].get::<&str>().unwrap();
let interface_name = args[3].get::<&str>().unwrap();
let method_name = args[4].get::<&str>().unwrap();
let parameters = args[5].get::<glib::Variant>().unwrap();
let invocation = args[6].get::<DBusMethodInvocation>().unwrap();
method_call(
conn,
sender,
object_path,
interface_name,
method_name,
parameters,
invocation,
);
None
})
.to_glib_none()
.0,
glib::Closure::new(move |args| {
let conn = args[0].get::<DBusConnection>().unwrap();
let sender = args[1].get::<&str>().unwrap();
let object_path = args[2].get::<&str>().unwrap();
let interface_name = args[3].get::<&str>().unwrap();
let property_name = args[4].get::<&str>().unwrap();
let result =
get_property(conn, sender, object_path, interface_name, property_name);
Some(result.to_value())
})
.to_glib_none()
.0,
glib::Closure::new(move |args| {
let conn = args[0].get::<DBusConnection>().unwrap();
let sender = args[1].get::<&str>().unwrap();
let object_path = args[2].get::<&str>().unwrap();
let interface_name = args[3].get::<&str>().unwrap();
let property_name = args[4].get::<&str>().unwrap();
let value = args[5].get::<glib::Variant>().unwrap();
let result = set_property(
conn,
sender,
object_path,
interface_name,
property_name,
value,
);
Some(result.to_value())
})
.to_glib_none()
.0,
&mut error,
);
if error.is_null() {
Ok(RegistrationId(NonZeroU32::new_unchecked(id)))
} else {
Err(from_glib_full(error))
}
}
}
/// Unregisters an object.
/// ## `registration_id`
/// a registration id obtained from
/// `g_dbus_connection_register_object()`
///
/// # Returns
///
/// [`true`] if the object was unregistered, [`false`] otherwise
#[doc(alias = "g_dbus_connection_unregister_object")]
pub fn unregister_object(
&self,
registration_id: RegistrationId,
) -> Result<(), glib::error::BoolError> {
unsafe {
glib::result_from_gboolean!(
ffi::g_dbus_connection_unregister_object(
self.to_glib_none().0,
registration_id.0.into()
),
"Failed to unregister D-Bus object"
)
}
}
/// Exports `action_group` on `self` at `object_path`.
///
/// The implemented D-Bus API should be considered private. It is
/// subject to change in the future.
///
/// A given object path can only have one action group exported on it.
/// If this constraint is violated, the export will fail and 0 will be
/// returned (with `error` set accordingly).
///
/// You can unexport the action group using
/// [`unexport_action_group()`][Self::unexport_action_group()] with the return value of
/// this function.
///
/// The thread default main context is taken at the time of this call.
/// All incoming action activations and state change requests are
/// reported from this context. Any changes on the action group that
/// cause it to emit signals must also come from this same context.
/// Since incoming action activations and state change requests are
/// rather likely to cause changes on the action group, this effectively
/// limits a given action group to being exported from only one main
/// context.
/// ## `object_path`
/// a D-Bus object path
/// ## `action_group`
/// a [`ActionGroup`][crate::ActionGroup]
///
/// # Returns
///
/// the ID of the export (never zero), or 0 in case of failure
#[doc(alias = "g_dbus_connection_export_action_group")]
pub fn export_action_group<P: IsA<ActionGroup>>(
&self,
object_path: &str,
action_group: &P,
) -> Result<ActionGroupExportId, glib::Error> {
unsafe {
let mut error = std::ptr::null_mut();
let id = ffi::g_dbus_connection_export_action_group(
self.to_glib_none().0,
object_path.to_glib_none().0,
action_group.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(ActionGroupExportId(NonZeroU32::new_unchecked(id)))
} else {
Err(from_glib_full(error))
}
}
}
/// Reverses the effect of a previous call to
/// [`export_action_group()`][Self::export_action_group()].
///
/// It is an error to call this function with an ID that wasn't returned
/// from [`export_action_group()`][Self::export_action_group()] or to call it with the
/// same ID more than once.
/// ## `export_id`
/// the ID from [`export_action_group()`][Self::export_action_group()]
#[doc(alias = "g_dbus_connection_unexport_action_group")]
pub fn unexport_action_group(&self, export_id: ActionGroupExportId) {
unsafe {
ffi::g_dbus_connection_unexport_action_group(self.to_glib_none().0, export_id.0.into());
}
}
/// Exports `menu` on `self` at `object_path`.
///
/// The implemented D-Bus API should be considered private.
/// It is subject to change in the future.
///
/// An object path can only have one menu model exported on it. If this
/// constraint is violated, the export will fail and 0 will be
/// returned (with `error` set accordingly).
///
/// Exporting menus with sections containing more than
/// `G_MENU_EXPORTER_MAX_SECTION_SIZE` items is not supported and results in
/// undefined behavior.
///
/// You can unexport the menu model using
/// [`unexport_menu_model()`][Self::unexport_menu_model()] with the return value of
/// this function.
/// ## `object_path`
/// a D-Bus object path
/// ## `menu`
/// a [`MenuModel`][crate::MenuModel]
///
/// # Returns
///
/// the ID of the export (never zero), or 0 in case of failure
#[doc(alias = "g_dbus_connection_export_menu_model")]
pub fn export_menu_model<P: IsA<MenuModel>>(
&self,
object_path: &str,
menu: &P,
) -> Result<MenuModelExportId, glib::Error> {
unsafe {
let mut error = std::ptr::null_mut();
let id = ffi::g_dbus_connection_export_menu_model(
self.to_glib_none().0,
object_path.to_glib_none().0,
menu.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(MenuModelExportId(NonZeroU32::new_unchecked(id)))
} else {
Err(from_glib_full(error))
}
}
}
/// Reverses the effect of a previous call to
/// [`export_menu_model()`][Self::export_menu_model()].
///
/// It is an error to call this function with an ID that wasn't returned
/// from [`export_menu_model()`][Self::export_menu_model()] or to call it with the
/// same ID more than once.
/// ## `export_id`
/// the ID from [`export_menu_model()`][Self::export_menu_model()]
#[doc(alias = "g_dbus_connection_unexport_menu_model")]
pub fn unexport_menu_model(&self, export_id: MenuModelExportId) {
unsafe {
ffi::g_dbus_connection_unexport_menu_model(self.to_glib_none().0, export_id.0.into());
}
}
/// Adds a message filter. Filters are handlers that are run on all
/// incoming and outgoing messages, prior to standard dispatch. Filters
/// are run in the order that they were added. The same handler can be
/// added as a filter more than once, in which case it will be run more
/// than once. Filters added during a filter callback won't be run on
/// the message being processed. Filter functions are allowed to modify
/// and even drop messages.
///
/// Note that filters are run in a dedicated message handling thread so
/// they can't block and, generally, can't do anything but signal a
/// worker thread. Also note that filters are rarely needed - use API
/// such as [`send_message_with_reply()`][Self::send_message_with_reply()],
/// [`signal_subscribe()`][Self::signal_subscribe()] or [`call()`][Self::call()] instead.
///
/// If a filter consumes an incoming message the message is not
/// dispatched anywhere else - not even the standard dispatch machinery
/// (that API such as [`signal_subscribe()`][Self::signal_subscribe()] and
/// [`send_message_with_reply()`][Self::send_message_with_reply()] relies on) will see the
/// message. Similarly, if a filter consumes an outgoing message, the
/// message will not be sent to the other peer.
///
/// If `user_data_free_func` is non-[`None`], it will be called (in the
/// thread-default main context of the thread you are calling this
/// method from) at some point after `user_data` is no longer
/// needed. (It is not guaranteed to be called synchronously when the
/// filter is removed, and may be called after `self` has been
/// destroyed.)
/// ## `filter_function`
/// a filter function
///
/// # Returns
///
/// a filter identifier that can be used with
/// [`remove_filter()`][Self::remove_filter()]
#[doc(alias = "g_dbus_connection_add_filter")]
pub fn add_filter<
P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
>(
&self,
filter_function: P,
) -> FilterId {
let filter_function_data: Box_<P> = Box_::new(filter_function);
unsafe extern "C" fn filter_function_func<
P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
>(
connection: *mut ffi::GDBusConnection,
message: *mut ffi::GDBusMessage,
incoming: glib::ffi::gboolean,
user_data: glib::ffi::gpointer,
) -> *mut ffi::GDBusMessage {
let connection = from_glib_borrow(connection);
let message = from_glib_full(message);
let incoming = from_glib(incoming);
let callback: &P = &*(user_data as *mut _);
let res = (*callback)(&connection, &message, incoming);
res.into_glib_ptr()
}
let filter_function = Some(filter_function_func::<P> as _);
unsafe extern "C" fn user_data_free_func_func<
P: Fn(&DBusConnection, &DBusMessage, bool) -> Option<DBusMessage> + 'static,
>(
data: glib::ffi::gpointer,
) {
let _callback: Box_<P> = Box_::from_raw(data as *mut _);
}
let destroy_call3 = Some(user_data_free_func_func::<P> as _);
let super_callback0: Box_<P> = filter_function_data;
unsafe {
let id = ffi::g_dbus_connection_add_filter(
self.to_glib_none().0,
filter_function,
Box_::into_raw(super_callback0) as *mut _,
destroy_call3,
);
FilterId(NonZeroU32::new_unchecked(id))
}
}
/// Removes a filter.
///
/// Note that since filters run in a different thread, there is a race
/// condition where it is possible that the filter will be running even
/// after calling [`remove_filter()`][Self::remove_filter()], so you cannot just
/// free data that the filter might be using. Instead, you should pass
/// a `GDestroyNotify` to [`add_filter()`][Self::add_filter()], which will be
/// called when it is guaranteed that the data is no longer needed.
/// ## `filter_id`
/// an identifier obtained from [`add_filter()`][Self::add_filter()]
#[doc(alias = "g_dbus_connection_remove_filter")]
pub fn remove_filter(&self, filter_id: FilterId) {
unsafe {
ffi::g_dbus_connection_remove_filter(self.to_glib_none().0, filter_id.0.into());
}
}
/// Subscribes to signals on `self` and invokes `callback` whenever
/// the signal is received. Note that `callback` will be invoked in the
/// [thread-default main context][g-main-context-push-thread-default]
/// of the thread you are calling this method from.
///
/// If `self` is not a message bus connection, `sender` must be
/// [`None`].
///
/// If `sender` is a well-known name note that `callback` is invoked with
/// the unique name for the owner of `sender`, not the well-known name
/// as one would expect. This is because the message bus rewrites the
/// name. As such, to avoid certain race conditions, users should be
/// tracking the name owner of the well-known name and use that when
/// processing the received signal.
///
/// If one of [`DBusSignalFlags::MATCH_ARG0_NAMESPACE`][crate::DBusSignalFlags::MATCH_ARG0_NAMESPACE] or
/// [`DBusSignalFlags::MATCH_ARG0_PATH`][crate::DBusSignalFlags::MATCH_ARG0_PATH] are given, `arg0` is
/// interpreted as part of a namespace or path. The first argument
/// of a signal is matched against that part as specified by D-Bus.
///
/// If `user_data_free_func` is non-[`None`], it will be called (in the
/// thread-default main context of the thread you are calling this
/// method from) at some point after `user_data` is no longer
/// needed. (It is not guaranteed to be called synchronously when the
/// signal is unsubscribed from, and may be called after `self`
/// has been destroyed.)
///
/// As `callback` is potentially invoked in a different thread from where it’s
/// emitted, it’s possible for this to happen after
/// [`signal_unsubscribe()`][Self::signal_unsubscribe()] has been called in another thread.
/// Due to this, `user_data` should have a strong reference which is freed with
/// `user_data_free_func`, rather than pointing to data whose lifecycle is tied
/// to the signal subscription. For example, if a [`glib::Object`][crate::glib::Object] is used to store the
/// subscription ID from [`signal_subscribe()`][Self::signal_subscribe()], a strong reference
/// to that [`glib::Object`][crate::glib::Object] must be passed to `user_data`, and `g_object_unref()` passed to
/// `user_data_free_func`. You are responsible for breaking the resulting
/// reference count cycle by explicitly unsubscribing from the signal when
/// dropping the last external reference to the [`glib::Object`][crate::glib::Object]. Alternatively, a weak
/// reference may be used.
///
/// It is guaranteed that if you unsubscribe from a signal using
/// [`signal_unsubscribe()`][Self::signal_unsubscribe()] from the same thread which made the
/// corresponding [`signal_subscribe()`][Self::signal_subscribe()] call, `callback` will not
/// be invoked after [`signal_unsubscribe()`][Self::signal_unsubscribe()] returns.
///
/// The returned subscription identifier is an opaque value which is guaranteed
/// to never be zero.
///
/// This function can never fail.
/// ## `sender`
/// sender name to match on (unique or well-known name)
/// or [`None`] to listen from all senders
/// ## `interface_name`
/// D-Bus interface name to match on or [`None`] to
/// match on all interfaces
/// ## `member`
/// D-Bus signal name to match on or [`None`] to match on
/// all signals
/// ## `object_path`
/// object path to match on or [`None`] to match on
/// all object paths
/// ## `arg0`
/// contents of first string argument to match on or [`None`]
/// to match on all kinds of arguments
/// ## `flags`
/// [`DBusSignalFlags`][crate::DBusSignalFlags] describing how arg0 is used in subscribing to the
/// signal
/// ## `callback`
/// callback to invoke when there is a signal matching the requested data
///
/// # Returns
///
/// a subscription identifier that can be used with [`signal_unsubscribe()`][Self::signal_unsubscribe()]
#[doc(alias = "g_dbus_connection_signal_subscribe")]
#[allow(clippy::too_many_arguments)]
pub fn signal_subscribe<
P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
>(
&self,
sender: Option<&str>,
interface_name: Option<&str>,
member: Option<&str>,
object_path: Option<&str>,
arg0: Option<&str>,
flags: DBusSignalFlags,
callback: P,
) -> SignalSubscriptionId {
let callback_data: Box_<P> = Box_::new(callback);
unsafe extern "C" fn callback_func<
P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
>(
connection: *mut ffi::GDBusConnection,
sender_name: *const libc::c_char,
object_path: *const libc::c_char,
interface_name: *const libc::c_char,
signal_name: *const libc::c_char,
parameters: *mut glib::ffi::GVariant,
user_data: glib::ffi::gpointer,
) {
let connection = from_glib_borrow(connection);
let sender_name: Borrowed<glib::GString> = from_glib_borrow(sender_name);
let object_path: Borrowed<glib::GString> = from_glib_borrow(object_path);
let interface_name: Borrowed<glib::GString> = from_glib_borrow(interface_name);
let signal_name: Borrowed<glib::GString> = from_glib_borrow(signal_name);
let parameters = from_glib_borrow(parameters);
let callback: &P = &*(user_data as *mut _);
(*callback)(
&connection,
sender_name.as_str(),
object_path.as_str(),
interface_name.as_str(),
signal_name.as_str(),
¶meters,
);
}
let callback = Some(callback_func::<P> as _);
unsafe extern "C" fn user_data_free_func_func<
P: Fn(&DBusConnection, &str, &str, &str, &str, &glib::Variant) + 'static,
>(
data: glib::ffi::gpointer,
) {
let _callback: Box_<P> = Box_::from_raw(data as *mut _);
}
let destroy_call9 = Some(user_data_free_func_func::<P> as _);
let super_callback0: Box_<P> = callback_data;
unsafe {
let id = ffi::g_dbus_connection_signal_subscribe(
self.to_glib_none().0,
sender.to_glib_none().0,
interface_name.to_glib_none().0,
member.to_glib_none().0,
object_path.to_glib_none().0,
arg0.to_glib_none().0,
flags.into_glib(),
callback,
Box_::into_raw(super_callback0) as *mut _,
destroy_call9,
);
SignalSubscriptionId(NonZeroU32::new_unchecked(id))
}
}
/// Unsubscribes from signals.
///
/// Note that there may still be D-Bus traffic to process (relating to this
/// signal subscription) in the current thread-default [`glib::MainContext`][crate::glib::MainContext] after this
/// function has returned. You should continue to iterate the [`glib::MainContext`][crate::glib::MainContext]
/// until the `GDestroyNotify` function passed to
/// [`signal_subscribe()`][Self::signal_subscribe()] is called, in order to avoid memory
/// leaks through callbacks queued on the [`glib::MainContext`][crate::glib::MainContext] after it’s stopped being
/// iterated.
/// Alternatively, any idle source with a priority lower than `G_PRIORITY_DEFAULT`
/// that was scheduled after unsubscription, also indicates that all resources
/// of this subscription are released.
/// ## `subscription_id`
/// a subscription id obtained from
/// [`signal_subscribe()`][Self::signal_subscribe()]
#[doc(alias = "g_dbus_connection_signal_unsubscribe")]
pub fn signal_unsubscribe(&self, subscription_id: SignalSubscriptionId) {
unsafe {
ffi::g_dbus_connection_signal_unsubscribe(
self.to_glib_none().0,
subscription_id.0.into(),
);
}
}
}