gio/auto/
volume.rs

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
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::{
    ffi, AsyncResult, Cancellable, Drive, File, Icon, Mount, MountMountFlags, MountOperation,
    MountUnmountFlags,
};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// The `GVolume` interface represents user-visible objects that can be
    /// mounted. For example, a file system partition on a USB flash drive, or an
    /// optical disc inserted into a disc drive.
    ///
    /// If a `GVolume` is currently mounted, the corresponding [`Mount`][crate::Mount] can
    /// be retrieved using [`VolumeExt::get_mount()`][crate::prelude::VolumeExt::get_mount()].
    ///
    /// Mounting a `GVolume` instance is an asynchronous operation. For more
    /// information about asynchronous operations, see [`AsyncResult`][crate::AsyncResult] and
    /// [`Task`][crate::Task]. To mount a `GVolume`, first call [`VolumeExt::mount()`][crate::prelude::VolumeExt::mount()]
    /// with (at least) the `GVolume` instance, optionally a
    /// [`MountOperation`][crate::MountOperation] object and a [type@Gio.AsyncReadyCallback].
    ///
    /// Typically, one will only want to pass `NULL` for the
    /// [`MountOperation`][crate::MountOperation] if automounting all volumes when a desktop session
    /// starts since it’s not desirable to put up a lot of dialogs asking
    /// for credentials.
    ///
    /// The callback will be fired when the operation has resolved (either
    /// with success or failure), and a [`AsyncResult`][crate::AsyncResult] instance will be
    /// passed to the callback.  That callback should then call
    /// `Gio::Volume::mount_finish()` with the `GVolume` instance and the
    /// [`AsyncResult`][crate::AsyncResult] data to see if the operation was completed
    /// successfully.  If a [type@GLib.Error] is present when
    /// `Gio::Volume::mount_finish()` is called, then it will be filled with any
    /// error information.
    ///
    /// Note, when [porting from GnomeVFS](migrating-gnome-vfs.html),
    /// `GVolume` is the moral equivalent of `GnomeVFSDrive`.
    ///
    /// ## Volume Identifiers
    ///
    /// It is sometimes necessary to directly access the underlying
    /// operating system object behind a volume (e.g. for passing a volume
    /// to an application via the command line). For this purpose, GIO
    /// allows to obtain an ‘identifier’ for the volume. There can be
    /// different kinds of identifiers, such as Hal UDIs, filesystem labels,
    /// traditional Unix devices (e.g. `/dev/sda2`), UUIDs. GIO uses predefined
    /// strings as names for the different kinds of identifiers:
    /// `G_VOLUME_IDENTIFIER_KIND_UUID`, `G_VOLUME_IDENTIFIER_KIND_LABEL`, etc.
    /// Use [`VolumeExt::identifier()`][crate::prelude::VolumeExt::identifier()] to obtain an identifier for a volume.
    ///
    /// Note that `G_VOLUME_IDENTIFIER_KIND_HAL_UDI` will only be available
    /// when the GVFS hal volume monitor is in use. Other volume monitors
    /// will generally be able to provide the `G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE`
    /// identifier, which can be used to obtain a hal device by means of
    /// `libhal_manager_find_device_string_match()`.
    ///
    /// ## Signals
    ///
    ///
    /// #### `changed`
    ///  Emitted when the volume has been changed.
    ///
    ///
    ///
    ///
    /// #### `removed`
    ///  This signal is emitted when the #GVolume have been removed. If
    /// the recipient is holding references to the object they should
    /// release them so the object can be finalized.
    ///
    ///
    ///
    /// # Implements
    ///
    /// [`VolumeExt`][trait@crate::prelude::VolumeExt]
    #[doc(alias = "GVolume")]
    pub struct Volume(Interface<ffi::GVolume, ffi::GVolumeIface>);

    match fn {
        type_ => || ffi::g_volume_get_type(),
    }
}

impl Volume {
    pub const NONE: Option<&'static Volume> = None;
}

/// Trait containing all [`struct@Volume`] methods.
///
/// # Implementors
///
/// [`Volume`][struct@crate::Volume]
pub trait VolumeExt: IsA<Volume> + 'static {
    /// Checks if a volume can be ejected.
    ///
    /// # Returns
    ///
    /// [`true`] if the @self can be ejected. [`false`] otherwise
    #[doc(alias = "g_volume_can_eject")]
    fn can_eject(&self) -> bool {
        unsafe { from_glib(ffi::g_volume_can_eject(self.as_ref().to_glib_none().0)) }
    }

    /// Checks if a volume can be mounted.
    ///
    /// # Returns
    ///
    /// [`true`] if the @self can be mounted. [`false`] otherwise
    #[doc(alias = "g_volume_can_mount")]
    fn can_mount(&self) -> bool {
        unsafe { from_glib(ffi::g_volume_can_mount(self.as_ref().to_glib_none().0)) }
    }

    /// Ejects a volume. This is an asynchronous operation, and is
    /// finished by calling g_volume_eject_with_operation_finish() with the @self
    /// and #GAsyncResult data returned in the @callback.
    /// ## `flags`
    /// flags affecting the unmount if required for eject
    /// ## `mount_operation`
    /// a #GMountOperation or [`None`] to
    ///     avoid user interaction
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore
    /// ## `callback`
    /// a #GAsyncReadyCallback, or [`None`]
    #[doc(alias = "g_volume_eject_with_operation")]
    fn eject_with_operation<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        flags: MountUnmountFlags,
        mount_operation: Option<&impl IsA<MountOperation>>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn eject_with_operation_trampoline<
            P: FnOnce(Result<(), glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let _ = ffi::g_volume_eject_with_operation_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = eject_with_operation_trampoline::<P>;
        unsafe {
            ffi::g_volume_eject_with_operation(
                self.as_ref().to_glib_none().0,
                flags.into_glib(),
                mount_operation.map(|p| p.as_ref()).to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn eject_with_operation_future(
        &self,
        flags: MountUnmountFlags,
        mount_operation: Option<&(impl IsA<MountOperation> + Clone + 'static)>,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        let mount_operation = mount_operation.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.eject_with_operation(
                    flags,
                    mount_operation.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Gets the kinds of [identifiers](#volume-identifiers) that @self has.
    /// Use g_volume_get_identifier() to obtain the identifiers themselves.
    ///
    /// # Returns
    ///
    /// a [`None`]-terminated array
    ///   of strings containing kinds of identifiers. Use g_strfreev() to free.
    #[doc(alias = "g_volume_enumerate_identifiers")]
    fn enumerate_identifiers(&self) -> Vec<glib::GString> {
        unsafe {
            FromGlibPtrContainer::from_glib_full(ffi::g_volume_enumerate_identifiers(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the activation root for a #GVolume if it is known ahead of
    /// mount time. Returns [`None`] otherwise. If not [`None`] and if @self
    /// is mounted, then the result of g_mount_get_root() on the
    /// #GMount object obtained from g_volume_get_mount() will always
    /// either be equal or a prefix of what this function returns. In
    /// other words, in code
    ///
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///   GMount *mount;
    ///   GFile *mount_root
    ///   GFile *volume_activation_root;
    ///
    ///   mount = g_volume_get_mount (volume); // mounted, so never NULL
    ///   mount_root = g_mount_get_root (mount);
    ///   volume_activation_root = g_volume_get_activation_root (volume); // assume not NULL
    /// ```
    /// then the expression
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///   (g_file_has_prefix (volume_activation_root, mount_root) ||
    ///    g_file_equal (volume_activation_root, mount_root))
    /// ```
    /// will always be [`true`].
    ///
    /// Activation roots are typically used in #GVolumeMonitor
    /// implementations to find the underlying mount to shadow, see
    /// g_mount_is_shadowed() for more details.
    ///
    /// # Returns
    ///
    /// the activation root of @self
    ///     or [`None`]. Use g_object_unref() to free.
    #[doc(alias = "g_volume_get_activation_root")]
    #[doc(alias = "get_activation_root")]
    fn activation_root(&self) -> Option<File> {
        unsafe {
            from_glib_full(ffi::g_volume_get_activation_root(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the drive for the @self.
    ///
    /// # Returns
    ///
    /// a #GDrive or [`None`] if @self is not
    ///     associated with a drive. The returned object should be unreffed
    ///     with g_object_unref() when no longer needed.
    #[doc(alias = "g_volume_get_drive")]
    #[doc(alias = "get_drive")]
    fn drive(&self) -> Option<Drive> {
        unsafe { from_glib_full(ffi::g_volume_get_drive(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the icon for @self.
    ///
    /// # Returns
    ///
    /// a #GIcon.
    ///     The returned object should be unreffed with g_object_unref()
    ///     when no longer needed.
    #[doc(alias = "g_volume_get_icon")]
    #[doc(alias = "get_icon")]
    fn icon(&self) -> Icon {
        unsafe { from_glib_full(ffi::g_volume_get_icon(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the identifier of the given kind for @self.
    /// See the [introduction](#volume-identifiers) for more
    /// information about volume identifiers.
    /// ## `kind`
    /// the kind of identifier to return
    ///
    /// # Returns
    ///
    /// a newly allocated string containing the
    ///     requested identifier, or [`None`] if the #GVolume
    ///     doesn't have this kind of identifier
    #[doc(alias = "g_volume_get_identifier")]
    #[doc(alias = "get_identifier")]
    fn identifier(&self, kind: &str) -> Option<glib::GString> {
        unsafe {
            from_glib_full(ffi::g_volume_get_identifier(
                self.as_ref().to_glib_none().0,
                kind.to_glib_none().0,
            ))
        }
    }

    /// Gets the mount for the @self.
    ///
    /// # Returns
    ///
    /// a #GMount or [`None`] if @self isn't mounted.
    ///     The returned object should be unreffed with g_object_unref()
    ///     when no longer needed.
    #[doc(alias = "g_volume_get_mount")]
    fn get_mount(&self) -> Option<Mount> {
        unsafe { from_glib_full(ffi::g_volume_get_mount(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the name of @self.
    ///
    /// # Returns
    ///
    /// the name for the given @self. The returned string should
    ///     be freed with g_free() when no longer needed.
    #[doc(alias = "g_volume_get_name")]
    #[doc(alias = "get_name")]
    fn name(&self) -> glib::GString {
        unsafe { from_glib_full(ffi::g_volume_get_name(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the sort key for @self, if any.
    ///
    /// # Returns
    ///
    /// Sorting key for @self or [`None`] if no such key is available
    #[doc(alias = "g_volume_get_sort_key")]
    #[doc(alias = "get_sort_key")]
    fn sort_key(&self) -> Option<glib::GString> {
        unsafe { from_glib_none(ffi::g_volume_get_sort_key(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the symbolic icon for @self.
    ///
    /// # Returns
    ///
    /// a #GIcon.
    ///     The returned object should be unreffed with g_object_unref()
    ///     when no longer needed.
    #[doc(alias = "g_volume_get_symbolic_icon")]
    #[doc(alias = "get_symbolic_icon")]
    fn symbolic_icon(&self) -> Icon {
        unsafe {
            from_glib_full(ffi::g_volume_get_symbolic_icon(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the UUID for the @self. The reference is typically based on
    /// the file system UUID for the volume in question and should be
    /// considered an opaque string. Returns [`None`] if there is no UUID
    /// available.
    ///
    /// # Returns
    ///
    /// the UUID for @self or [`None`] if no UUID
    ///     can be computed.
    ///     The returned string should be freed with g_free()
    ///     when no longer needed.
    #[doc(alias = "g_volume_get_uuid")]
    #[doc(alias = "get_uuid")]
    fn uuid(&self) -> Option<glib::GString> {
        unsafe { from_glib_full(ffi::g_volume_get_uuid(self.as_ref().to_glib_none().0)) }
    }

    /// Mounts a volume. This is an asynchronous operation, and is
    /// finished by calling g_volume_mount_finish() with the @self
    /// and #GAsyncResult returned in the @callback.
    /// ## `flags`
    /// flags affecting the operation
    /// ## `mount_operation`
    /// a #GMountOperation or [`None`] to avoid user interaction
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore
    /// ## `callback`
    /// a #GAsyncReadyCallback, or [`None`]
    #[doc(alias = "g_volume_mount")]
    fn mount<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        flags: MountMountFlags,
        mount_operation: Option<&impl IsA<MountOperation>>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn mount_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let _ = ffi::g_volume_mount_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = mount_trampoline::<P>;
        unsafe {
            ffi::g_volume_mount(
                self.as_ref().to_glib_none().0,
                flags.into_glib(),
                mount_operation.map(|p| p.as_ref()).to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn mount_future(
        &self,
        flags: MountMountFlags,
        mount_operation: Option<&(impl IsA<MountOperation> + Clone + 'static)>,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        let mount_operation = mount_operation.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.mount(
                    flags,
                    mount_operation.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Returns whether the volume should be automatically mounted.
    ///
    /// # Returns
    ///
    /// [`true`] if the volume should be automatically mounted
    #[doc(alias = "g_volume_should_automount")]
    fn should_automount(&self) -> bool {
        unsafe {
            from_glib(ffi::g_volume_should_automount(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Emitted when the volume has been changed.
    #[doc(alias = "changed")]
    fn connect_changed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn changed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
            this: *mut ffi::GVolume,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Volume::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"changed\0".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    changed_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    /// This signal is emitted when the #GVolume have been removed. If
    /// the recipient is holding references to the object they should
    /// release them so the object can be finalized.
    #[doc(alias = "removed")]
    fn connect_removed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn removed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
            this: *mut ffi::GVolume,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Volume::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"removed\0".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    removed_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl<O: IsA<Volume>> VolumeExt for O {}