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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::BusNameOwnerFlags;
use crate::BusNameWatcherFlags;
use crate::BusType;
use crate::DBusConnection;
use glib::translate::*;
use std::num::NonZeroU32;

#[derive(Debug, Eq, PartialEq)]
pub struct OwnerId(NonZeroU32);
#[derive(Debug, Eq, PartialEq)]
pub struct WatcherId(NonZeroU32);

fn own_closure<F>(f: F) -> glib::Closure
where
    F: Fn(DBusConnection, &str) + Send + Sync + 'static,
{
    glib::Closure::new(move |args| {
        let conn = args[0].get::<DBusConnection>().unwrap();
        let name = args[1].get::<&str>().unwrap();
        f(conn, name);
        None
    })
}

fn appeared_closure<F>(f: F) -> glib::Closure
where
    F: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,
{
    glib::Closure::new(move |args| {
        let conn = args[0].get::<DBusConnection>().unwrap();
        let name = args[1].get::<&str>().unwrap();
        let name_owner = args[2].get::<&str>().unwrap();
        f(conn, name, name_owner);
        None
    })
}

fn vanished_closure<F>(f: F) -> glib::Closure
where
    F: Fn(DBusConnection, &str) + Send + Sync + 'static,
{
    glib::Closure::new(move |args| {
        let conn = args[0].get::<DBusConnection>().unwrap();
        let name = args[1].get::<&str>().unwrap();
        f(conn, name);
        None
    })
}

/// Like `g_bus_own_name()` but takes a [`DBusConnection`][crate::DBusConnection] instead of a
/// [`BusType`][crate::BusType].
/// ## `connection`
/// a [`DBusConnection`][crate::DBusConnection]
/// ## `name`
/// the well-known name to own
/// ## `flags`
/// a set of flags from the [`BusNameOwnerFlags`][crate::BusNameOwnerFlags] enumeration
/// ## `name_acquired_handler`
/// handler to invoke when `name` is acquired or [`None`]
/// ## `name_lost_handler`
/// handler to invoke when `name` is lost or [`None`]
///
/// # Returns
///
/// an identifier (never 0) that can be used with
///  `g_bus_unown_name()` to stop owning the name
#[doc(alias = "g_bus_own_name_on_connection_with_closures")]
pub fn bus_own_name_on_connection<NameAcquired, NameLost>(
    connection: &DBusConnection,
    name: &str,
    flags: BusNameOwnerFlags,
    name_acquired: NameAcquired,
    name_lost: NameLost,
) -> OwnerId
where
    NameAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,
    NameLost: Fn(DBusConnection, &str) + Send + Sync + 'static,
{
    unsafe {
        let id = ffi::g_bus_own_name_on_connection_with_closures(
            connection.to_glib_none().0,
            name.to_glib_none().0,
            flags.into_glib(),
            own_closure(name_acquired).to_glib_none().0,
            own_closure(name_lost).to_glib_none().0,
        );
        OwnerId(NonZeroU32::new_unchecked(id))
    }
}

/// Starts acquiring `name` on the bus specified by `bus_type` and calls
/// `name_acquired_handler` and `name_lost_handler` when the name is
/// acquired respectively lost. Callbacks will be invoked in the
/// [thread-default main context][g-main-context-push-thread-default]
/// of the thread you are calling this function from.
///
/// You are guaranteed that one of the `name_acquired_handler` and `name_lost_handler`
/// callbacks will be invoked after calling this function - there are three
/// possible cases:
///
/// - `name_lost_handler` with a [`None`] connection (if a connection to the bus
///  can't be made).
///
/// - `bus_acquired_handler` then `name_lost_handler` (if the name can't be
///  obtained)
///
/// - `bus_acquired_handler` then `name_acquired_handler` (if the name was
///  obtained).
///
/// When you are done owning the name, just call `g_bus_unown_name()`
/// with the owner id this function returns.
///
/// If the name is acquired or lost (for example another application
/// could acquire the name if you allow replacement or the application
/// currently owning the name exits), the handlers are also invoked.
/// If the [`DBusConnection`][crate::DBusConnection] that is used for attempting to own the name
/// closes, then `name_lost_handler` is invoked since it is no longer
/// possible for other processes to access the process.
///
/// You cannot use `g_bus_own_name()` several times for the same name (unless
/// interleaved with calls to `g_bus_unown_name()`) - only the first call
/// will work.
///
/// Another guarantee is that invocations of `name_acquired_handler`
/// and `name_lost_handler` are guaranteed to alternate; that
/// is, if `name_acquired_handler` is invoked then you are
/// guaranteed that the next time one of the handlers is invoked, it
/// will be `name_lost_handler`. The reverse is also true.
///
/// If you plan on exporting objects (using e.g.
/// `g_dbus_connection_register_object()`), note that it is generally too late
/// to export the objects in `name_acquired_handler`. Instead, you can do this
/// in `bus_acquired_handler` since you are guaranteed that this will run
/// before `name` is requested from the bus.
///
/// This behavior makes it very simple to write applications that wants
/// to [own names][gdbus-owning-names] and export objects.
/// Simply register objects to be exported in `bus_acquired_handler` and
/// unregister the objects (if any) in `name_lost_handler`.
/// ## `bus_type`
/// the type of bus to own a name on
/// ## `name`
/// the well-known name to own
/// ## `flags`
/// a set of flags from the [`BusNameOwnerFlags`][crate::BusNameOwnerFlags] enumeration
/// ## `bus_acquired_handler`
/// handler to invoke when connected to the bus of type `bus_type` or [`None`]
/// ## `name_acquired_handler`
/// handler to invoke when `name` is acquired or [`None`]
/// ## `name_lost_handler`
/// handler to invoke when `name` is lost or [`None`]
///
/// # Returns
///
/// an identifier (never 0) that can be used with
///  `g_bus_unown_name()` to stop owning the name.
#[doc(alias = "g_bus_own_name_with_closures")]
pub fn bus_own_name<BusAcquired, NameAcquired, NameLost>(
    bus_type: BusType,
    name: &str,
    flags: BusNameOwnerFlags,
    bus_acquired: BusAcquired,
    name_acquired: NameAcquired,
    name_lost: NameLost,
) -> OwnerId
where
    BusAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,
    NameAcquired: Fn(DBusConnection, &str) + Send + Sync + 'static,
    NameLost: Fn(Option<DBusConnection>, &str) + Send + Sync + 'static,
{
    unsafe {
        let id = ffi::g_bus_own_name_with_closures(
            bus_type.into_glib(),
            name.to_glib_none().0,
            flags.into_glib(),
            own_closure(bus_acquired).to_glib_none().0,
            own_closure(name_acquired).to_glib_none().0,
            glib::Closure::new(move |args| {
                let conn = args[0].get::<Option<DBusConnection>>().unwrap();
                let name = args[1].get::<&str>().unwrap();
                name_lost(conn, name);
                None
            })
            .to_glib_none()
            .0,
        );
        OwnerId(NonZeroU32::new_unchecked(id))
    }
}

#[doc(alias = "g_bus_unown_name")]
pub fn bus_unown_name(owner_id: OwnerId) {
    unsafe {
        ffi::g_bus_unown_name(owner_id.0.into());
    }
}

/// Like `g_bus_watch_name()` but takes a [`DBusConnection`][crate::DBusConnection] instead of a
/// [`BusType`][crate::BusType].
/// ## `connection`
/// A [`DBusConnection`][crate::DBusConnection].
/// ## `name`
/// The name (well-known or unique) to watch.
/// ## `flags`
/// Flags from the [`BusNameWatcherFlags`][crate::BusNameWatcherFlags] enumeration.
/// ## `name_appeared_handler`
/// Handler to invoke when `name` is known to exist or [`None`].
/// ## `name_vanished_handler`
/// Handler to invoke when `name` is known to not exist or [`None`].
///
/// # Returns
///
/// An identifier (never 0) that can be used with
/// `g_bus_unwatch_name()` to stop watching the name.
#[doc(alias = "g_bus_watch_name_on_connection_with_closures")]
pub fn bus_watch_name_on_connection<NameAppeared, NameVanished>(
    connection: &DBusConnection,
    name: &str,
    flags: BusNameWatcherFlags,
    name_appeared: NameAppeared,
    name_vanished: NameVanished,
) -> WatcherId
where
    NameAppeared: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,
    NameVanished: Fn(DBusConnection, &str) + Send + Sync + 'static,
{
    unsafe {
        let id = ffi::g_bus_watch_name_on_connection_with_closures(
            connection.to_glib_none().0,
            name.to_glib_none().0,
            flags.into_glib(),
            appeared_closure(name_appeared).to_glib_none().0,
            vanished_closure(name_vanished).to_glib_none().0,
        );
        WatcherId(NonZeroU32::new_unchecked(id))
    }
}

/// Starts watching `name` on the bus specified by `bus_type` and calls
/// `name_appeared_handler` and `name_vanished_handler` when the name is
/// known to have an owner respectively known to lose its
/// owner. Callbacks will be invoked in the
/// [thread-default main context][g-main-context-push-thread-default]
/// of the thread you are calling this function from.
///
/// You are guaranteed that one of the handlers will be invoked after
/// calling this function. When you are done watching the name, just
/// call `g_bus_unwatch_name()` with the watcher id this function
/// returns.
///
/// If the name vanishes or appears (for example the application owning
/// the name could restart), the handlers are also invoked. If the
/// [`DBusConnection`][crate::DBusConnection] that is used for watching the name disconnects, then
/// `name_vanished_handler` is invoked since it is no longer
/// possible to access the name.
///
/// Another guarantee is that invocations of `name_appeared_handler`
/// and `name_vanished_handler` are guaranteed to alternate; that
/// is, if `name_appeared_handler` is invoked then you are
/// guaranteed that the next time one of the handlers is invoked, it
/// will be `name_vanished_handler`. The reverse is also true.
///
/// This behavior makes it very simple to write applications that want
/// to take action when a certain [name exists][gdbus-watching-names].
/// Basically, the application should create object proxies in
/// `name_appeared_handler` and destroy them again (if any) in
/// `name_vanished_handler`.
/// ## `bus_type`
/// The type of bus to watch a name on.
/// ## `name`
/// The name (well-known or unique) to watch.
/// ## `flags`
/// Flags from the [`BusNameWatcherFlags`][crate::BusNameWatcherFlags] enumeration.
/// ## `name_appeared_handler`
/// Handler to invoke when `name` is known to exist or [`None`].
/// ## `name_vanished_handler`
/// Handler to invoke when `name` is known to not exist or [`None`].
///
/// # Returns
///
/// An identifier (never 0) that can be used with
/// `g_bus_unwatch_name()` to stop watching the name.
#[doc(alias = "g_bus_watch_name_with_closures")]
pub fn bus_watch_name<NameAppeared, NameVanished>(
    bus_type: BusType,
    name: &str,
    flags: BusNameWatcherFlags,
    name_appeared: NameAppeared,
    name_vanished: NameVanished,
) -> WatcherId
where
    NameAppeared: Fn(DBusConnection, &str, &str) + Send + Sync + 'static,
    NameVanished: Fn(DBusConnection, &str) + Send + Sync + 'static,
{
    unsafe {
        let id = ffi::g_bus_watch_name_with_closures(
            bus_type.into_glib(),
            name.to_glib_none().0,
            flags.into_glib(),
            appeared_closure(name_appeared).to_glib_none().0,
            vanished_closure(name_vanished).to_glib_none().0,
        );
        WatcherId(NonZeroU32::new_unchecked(id))
    }
}

#[doc(alias = "g_bus_unwatch_name")]
pub fn bus_unwatch_name(watcher_id: WatcherId) {
    unsafe {
        ffi::g_bus_unwatch_name(watcher_id.0.into());
    }
}