Skip to main content

gio/auto/
volume.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
5use crate::{
6    AsyncResult, Cancellable, Drive, File, Icon, Mount, MountMountFlags, MountOperation,
7    MountUnmountFlags, ffi,
8};
9use glib::{
10    object::ObjectType as _,
11    prelude::*,
12    signal::{SignalHandlerId, connect_raw},
13    translate::*,
14};
15use std::{boxed::Box as Box_, pin::Pin};
16
17glib::wrapper! {
18    /// The `GVolume` interface represents user-visible objects that can be
19    /// mounted. For example, a file system partition on a USB flash drive, or an
20    /// optical disc inserted into a disc drive.
21    ///
22    /// If a `GVolume` is currently mounted, the corresponding [`Mount`][crate::Mount] can
23    /// be retrieved using [`VolumeExt::get_mount()`][crate::prelude::VolumeExt::get_mount()].
24    ///
25    /// Mounting a `GVolume` instance is an asynchronous operation. For more
26    /// information about asynchronous operations, see [`AsyncResult`][crate::AsyncResult] and
27    /// [`Task`][crate::Task]. To mount a `GVolume`, first call [`VolumeExt::mount()`][crate::prelude::VolumeExt::mount()]
28    /// with (at least) the `GVolume` instance, optionally a
29    /// [`MountOperation`][crate::MountOperation] object and a [type@Gio.AsyncReadyCallback].
30    ///
31    /// Typically, one will only want to pass `NULL` for the
32    /// [`MountOperation`][crate::MountOperation] if automounting all volumes when a desktop session
33    /// starts since it’s not desirable to put up a lot of dialogs asking
34    /// for credentials.
35    ///
36    /// The callback will be fired when the operation has resolved (either
37    /// with success or failure), and a [`AsyncResult`][crate::AsyncResult] instance will be
38    /// passed to the callback.  That callback should then call
39    /// `Gio::Volume::mount_finish()` with the `GVolume` instance and the
40    /// [`AsyncResult`][crate::AsyncResult] data to see if the operation was completed
41    /// successfully.  If a [type@GLib.Error] is present when
42    /// `Gio::Volume::mount_finish()` is called, then it will be filled with any
43    /// error information.
44    ///
45    /// Note, when [porting from GnomeVFS](migrating-gnome-vfs.html),
46    /// `GVolume` is the moral equivalent of `GnomeVFSDrive`.
47    ///
48    /// ## Volume Identifiers
49    ///
50    /// It is sometimes necessary to directly access the underlying
51    /// operating system object behind a volume (e.g. for passing a volume
52    /// to an application via the command line). For this purpose, GIO
53    /// allows to obtain an ‘identifier’ for the volume. There can be
54    /// different kinds of identifiers, such as Hal UDIs, filesystem labels,
55    /// traditional Unix devices (e.g. `/dev/sda2`), UUIDs. GIO uses predefined
56    /// strings as names for the different kinds of identifiers:
57    /// `G_VOLUME_IDENTIFIER_KIND_UUID`, `G_VOLUME_IDENTIFIER_KIND_LABEL`, etc.
58    /// Use [`VolumeExt::identifier()`][crate::prelude::VolumeExt::identifier()] to obtain an identifier for a volume.
59    ///
60    /// Note that `G_VOLUME_IDENTIFIER_KIND_HAL_UDI` will only be available
61    /// when the GVFS hal volume monitor is in use. Other volume monitors
62    /// will generally be able to provide the `G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE`
63    /// identifier, which can be used to obtain a hal device by means of
64    /// `libhal_manager_find_device_string_match()`.
65    ///
66    /// ## Signals
67    ///
68    ///
69    /// #### `changed`
70    ///  Emitted when the volume has been changed.
71    ///
72    ///
73    ///
74    ///
75    /// #### `removed`
76    ///  This signal is emitted when the #GVolume have been removed. If
77    /// the recipient is holding references to the object they should
78    /// release them so the object can be finalized.
79    ///
80    ///
81    ///
82    /// # Implements
83    ///
84    /// [`VolumeExt`][trait@crate::prelude::VolumeExt]
85    #[doc(alias = "GVolume")]
86    pub struct Volume(Interface<ffi::GVolume, ffi::GVolumeIface>);
87
88    match fn {
89        type_ => || ffi::g_volume_get_type(),
90    }
91}
92
93impl Volume {
94    pub const NONE: Option<&'static Volume> = None;
95}
96
97/// Trait containing all [`struct@Volume`] methods.
98///
99/// # Implementors
100///
101/// [`Volume`][struct@crate::Volume]
102pub trait VolumeExt: IsA<Volume> + 'static {
103    /// Checks if a volume can be ejected.
104    ///
105    /// # Returns
106    ///
107    /// [`true`] if the @self can be ejected. [`false`] otherwise
108    #[doc(alias = "g_volume_can_eject")]
109    fn can_eject(&self) -> bool {
110        unsafe { from_glib(ffi::g_volume_can_eject(self.as_ref().to_glib_none().0)) }
111    }
112
113    /// Checks if a volume can be mounted.
114    ///
115    /// # Returns
116    ///
117    /// [`true`] if the @self can be mounted. [`false`] otherwise
118    #[doc(alias = "g_volume_can_mount")]
119    fn can_mount(&self) -> bool {
120        unsafe { from_glib(ffi::g_volume_can_mount(self.as_ref().to_glib_none().0)) }
121    }
122
123    /// Ejects a volume. This is an asynchronous operation, and is
124    /// finished by calling g_volume_eject_with_operation_finish() with the @self
125    /// and #GAsyncResult data returned in the @callback.
126    /// ## `flags`
127    /// flags affecting the unmount if required for eject
128    /// ## `mount_operation`
129    /// a #GMountOperation or [`None`] to
130    ///     avoid user interaction
131    /// ## `cancellable`
132    /// optional #GCancellable object, [`None`] to ignore
133    /// ## `callback`
134    /// a #GAsyncReadyCallback, or [`None`]
135    #[doc(alias = "g_volume_eject_with_operation")]
136    fn eject_with_operation<P: FnOnce(Result<(), glib::Error>) + 'static>(
137        &self,
138        flags: MountUnmountFlags,
139        mount_operation: Option<&impl IsA<MountOperation>>,
140        cancellable: Option<&impl IsA<Cancellable>>,
141        callback: P,
142    ) {
143        let main_context = glib::MainContext::ref_thread_default();
144        let is_main_context_owner = main_context.is_owner();
145        let has_acquired_main_context = (!is_main_context_owner)
146            .then(|| main_context.acquire().ok())
147            .flatten();
148        assert!(
149            is_main_context_owner || has_acquired_main_context.is_some(),
150            "Async operations only allowed if the thread is owning the MainContext"
151        );
152
153        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
154            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
155        unsafe extern "C" fn eject_with_operation_trampoline<
156            P: FnOnce(Result<(), glib::Error>) + 'static,
157        >(
158            _source_object: *mut glib::gobject_ffi::GObject,
159            res: *mut crate::ffi::GAsyncResult,
160            user_data: glib::ffi::gpointer,
161        ) {
162            unsafe {
163                let mut error = std::ptr::null_mut();
164                ffi::g_volume_eject_with_operation_finish(
165                    _source_object as *mut _,
166                    res,
167                    &mut error,
168                );
169                let result = if error.is_null() {
170                    Ok(())
171                } else {
172                    Err(from_glib_full(error))
173                };
174                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
175                    Box_::from_raw(user_data as *mut _);
176                let callback: P = callback.into_inner();
177                callback(result);
178            }
179        }
180        let callback = eject_with_operation_trampoline::<P>;
181        unsafe {
182            ffi::g_volume_eject_with_operation(
183                self.as_ref().to_glib_none().0,
184                flags.into_glib(),
185                mount_operation.map(|p| p.as_ref()).to_glib_none().0,
186                cancellable.map(|p| p.as_ref()).to_glib_none().0,
187                Some(callback),
188                Box_::into_raw(user_data) as *mut _,
189            );
190        }
191    }
192
193    fn eject_with_operation_future(
194        &self,
195        flags: MountUnmountFlags,
196        mount_operation: Option<&(impl IsA<MountOperation> + Clone + 'static)>,
197    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
198        let mount_operation = mount_operation.map(ToOwned::to_owned);
199        Box_::pin(crate::GioFuture::new(
200            self,
201            move |obj, cancellable, send| {
202                obj.eject_with_operation(
203                    flags,
204                    mount_operation.as_ref().map(::std::borrow::Borrow::borrow),
205                    Some(cancellable),
206                    move |res| {
207                        send.resolve(res);
208                    },
209                );
210            },
211        ))
212    }
213
214    /// Gets the kinds of [identifiers](#volume-identifiers) that @self has.
215    /// Use g_volume_get_identifier() to obtain the identifiers themselves.
216    ///
217    /// # Returns
218    ///
219    /// a [`None`]-terminated array
220    ///   of strings containing kinds of identifiers. Use g_strfreev() to free.
221    #[doc(alias = "g_volume_enumerate_identifiers")]
222    fn enumerate_identifiers(&self) -> Vec<glib::GString> {
223        unsafe {
224            FromGlibPtrContainer::from_glib_full(ffi::g_volume_enumerate_identifiers(
225                self.as_ref().to_glib_none().0,
226            ))
227        }
228    }
229
230    /// Gets the activation root for a #GVolume if it is known ahead of
231    /// mount time. Returns [`None`] otherwise. If not [`None`] and if @self
232    /// is mounted, then the result of g_mount_get_root() on the
233    /// #GMount object obtained from g_volume_get_mount() will always
234    /// either be equal or a prefix of what this function returns. In
235    /// other words, in code
236    ///
237    ///
238    ///
239    /// **⚠️ The following code is in C ⚠️**
240    ///
241    /// ```C
242    ///   GMount *mount;
243    ///   GFile *mount_root
244    ///   GFile *volume_activation_root;
245    ///
246    ///   mount = g_volume_get_mount (volume); // mounted, so never NULL
247    ///   mount_root = g_mount_get_root (mount);
248    ///   volume_activation_root = g_volume_get_activation_root (volume); // assume not NULL
249    /// ```
250    /// then the expression
251    ///
252    ///
253    /// **⚠️ The following code is in C ⚠️**
254    ///
255    /// ```C
256    ///   (g_file_has_prefix (volume_activation_root, mount_root) ||
257    ///    g_file_equal (volume_activation_root, mount_root))
258    /// ```
259    /// will always be [`true`].
260    ///
261    /// Activation roots are typically used in #GVolumeMonitor
262    /// implementations to find the underlying mount to shadow, see
263    /// g_mount_is_shadowed() for more details.
264    ///
265    /// # Returns
266    ///
267    /// the activation root of @self
268    ///     or [`None`]. Use g_object_unref() to free.
269    #[doc(alias = "g_volume_get_activation_root")]
270    #[doc(alias = "get_activation_root")]
271    fn activation_root(&self) -> Option<File> {
272        unsafe {
273            from_glib_full(ffi::g_volume_get_activation_root(
274                self.as_ref().to_glib_none().0,
275            ))
276        }
277    }
278
279    /// Gets the drive for the @self.
280    ///
281    /// # Returns
282    ///
283    /// a #GDrive or [`None`] if @self is not
284    ///     associated with a drive. The returned object should be unreffed
285    ///     with g_object_unref() when no longer needed.
286    #[doc(alias = "g_volume_get_drive")]
287    #[doc(alias = "get_drive")]
288    fn drive(&self) -> Option<Drive> {
289        unsafe { from_glib_full(ffi::g_volume_get_drive(self.as_ref().to_glib_none().0)) }
290    }
291
292    /// Gets the icon for @self.
293    ///
294    /// # Returns
295    ///
296    /// a #GIcon.
297    ///     The returned object should be unreffed with g_object_unref()
298    ///     when no longer needed.
299    #[doc(alias = "g_volume_get_icon")]
300    #[doc(alias = "get_icon")]
301    fn icon(&self) -> Icon {
302        unsafe { from_glib_full(ffi::g_volume_get_icon(self.as_ref().to_glib_none().0)) }
303    }
304
305    /// Gets the identifier of the given kind for @self.
306    /// See the [introduction](#volume-identifiers) for more
307    /// information about volume identifiers.
308    /// ## `kind`
309    /// the kind of identifier to return
310    ///
311    /// # Returns
312    ///
313    /// a newly allocated string containing the
314    ///     requested identifier, or [`None`] if the #GVolume
315    ///     doesn't have this kind of identifier
316    #[doc(alias = "g_volume_get_identifier")]
317    #[doc(alias = "get_identifier")]
318    fn identifier(&self, kind: &str) -> Option<glib::GString> {
319        unsafe {
320            from_glib_full(ffi::g_volume_get_identifier(
321                self.as_ref().to_glib_none().0,
322                kind.to_glib_none().0,
323            ))
324        }
325    }
326
327    /// Gets the mount for the @self.
328    ///
329    /// # Returns
330    ///
331    /// a #GMount or [`None`] if @self isn't mounted.
332    ///     The returned object should be unreffed with g_object_unref()
333    ///     when no longer needed.
334    #[doc(alias = "g_volume_get_mount")]
335    fn get_mount(&self) -> Option<Mount> {
336        unsafe { from_glib_full(ffi::g_volume_get_mount(self.as_ref().to_glib_none().0)) }
337    }
338
339    /// Gets the name of @self.
340    ///
341    /// # Returns
342    ///
343    /// the name for the given @self. The returned string should
344    ///     be freed with g_free() when no longer needed.
345    #[doc(alias = "g_volume_get_name")]
346    #[doc(alias = "get_name")]
347    fn name(&self) -> glib::GString {
348        unsafe { from_glib_full(ffi::g_volume_get_name(self.as_ref().to_glib_none().0)) }
349    }
350
351    /// Gets the sort key for @self, if any.
352    ///
353    /// # Returns
354    ///
355    /// Sorting key for @self or [`None`] if no such key is available
356    #[doc(alias = "g_volume_get_sort_key")]
357    #[doc(alias = "get_sort_key")]
358    fn sort_key(&self) -> Option<glib::GString> {
359        unsafe { from_glib_none(ffi::g_volume_get_sort_key(self.as_ref().to_glib_none().0)) }
360    }
361
362    /// Gets the symbolic icon for @self.
363    ///
364    /// # Returns
365    ///
366    /// a #GIcon.
367    ///     The returned object should be unreffed with g_object_unref()
368    ///     when no longer needed.
369    #[doc(alias = "g_volume_get_symbolic_icon")]
370    #[doc(alias = "get_symbolic_icon")]
371    fn symbolic_icon(&self) -> Icon {
372        unsafe {
373            from_glib_full(ffi::g_volume_get_symbolic_icon(
374                self.as_ref().to_glib_none().0,
375            ))
376        }
377    }
378
379    /// Gets the UUID for the @self. The reference is typically based on
380    /// the file system UUID for the volume in question and should be
381    /// considered an opaque string. Returns [`None`] if there is no UUID
382    /// available.
383    ///
384    /// # Returns
385    ///
386    /// the UUID for @self or [`None`] if no UUID
387    ///     can be computed.
388    ///     The returned string should be freed with g_free()
389    ///     when no longer needed.
390    #[doc(alias = "g_volume_get_uuid")]
391    #[doc(alias = "get_uuid")]
392    fn uuid(&self) -> Option<glib::GString> {
393        unsafe { from_glib_full(ffi::g_volume_get_uuid(self.as_ref().to_glib_none().0)) }
394    }
395
396    /// Mounts a volume. This is an asynchronous operation, and is
397    /// finished by calling g_volume_mount_finish() with the @self
398    /// and #GAsyncResult returned in the @callback.
399    /// ## `flags`
400    /// flags affecting the operation
401    /// ## `mount_operation`
402    /// a #GMountOperation or [`None`] to avoid user interaction
403    /// ## `cancellable`
404    /// optional #GCancellable object, [`None`] to ignore
405    /// ## `callback`
406    /// a #GAsyncReadyCallback, or [`None`]
407    #[doc(alias = "g_volume_mount")]
408    fn mount<P: FnOnce(Result<(), glib::Error>) + 'static>(
409        &self,
410        flags: MountMountFlags,
411        mount_operation: Option<&impl IsA<MountOperation>>,
412        cancellable: Option<&impl IsA<Cancellable>>,
413        callback: P,
414    ) {
415        let main_context = glib::MainContext::ref_thread_default();
416        let is_main_context_owner = main_context.is_owner();
417        let has_acquired_main_context = (!is_main_context_owner)
418            .then(|| main_context.acquire().ok())
419            .flatten();
420        assert!(
421            is_main_context_owner || has_acquired_main_context.is_some(),
422            "Async operations only allowed if the thread is owning the MainContext"
423        );
424
425        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
426            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
427        unsafe extern "C" fn mount_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
428            _source_object: *mut glib::gobject_ffi::GObject,
429            res: *mut crate::ffi::GAsyncResult,
430            user_data: glib::ffi::gpointer,
431        ) {
432            unsafe {
433                let mut error = std::ptr::null_mut();
434                ffi::g_volume_mount_finish(_source_object as *mut _, res, &mut error);
435                let result = if error.is_null() {
436                    Ok(())
437                } else {
438                    Err(from_glib_full(error))
439                };
440                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
441                    Box_::from_raw(user_data as *mut _);
442                let callback: P = callback.into_inner();
443                callback(result);
444            }
445        }
446        let callback = mount_trampoline::<P>;
447        unsafe {
448            ffi::g_volume_mount(
449                self.as_ref().to_glib_none().0,
450                flags.into_glib(),
451                mount_operation.map(|p| p.as_ref()).to_glib_none().0,
452                cancellable.map(|p| p.as_ref()).to_glib_none().0,
453                Some(callback),
454                Box_::into_raw(user_data) as *mut _,
455            );
456        }
457    }
458
459    fn mount_future(
460        &self,
461        flags: MountMountFlags,
462        mount_operation: Option<&(impl IsA<MountOperation> + Clone + 'static)>,
463    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
464        let mount_operation = mount_operation.map(ToOwned::to_owned);
465        Box_::pin(crate::GioFuture::new(
466            self,
467            move |obj, cancellable, send| {
468                obj.mount(
469                    flags,
470                    mount_operation.as_ref().map(::std::borrow::Borrow::borrow),
471                    Some(cancellable),
472                    move |res| {
473                        send.resolve(res);
474                    },
475                );
476            },
477        ))
478    }
479
480    /// Returns whether the volume should be automatically mounted.
481    ///
482    /// # Returns
483    ///
484    /// [`true`] if the volume should be automatically mounted
485    #[doc(alias = "g_volume_should_automount")]
486    fn should_automount(&self) -> bool {
487        unsafe {
488            from_glib(ffi::g_volume_should_automount(
489                self.as_ref().to_glib_none().0,
490            ))
491        }
492    }
493
494    /// Emitted when the volume has been changed.
495    #[doc(alias = "changed")]
496    fn connect_changed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
497        unsafe extern "C" fn changed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
498            this: *mut ffi::GVolume,
499            f: glib::ffi::gpointer,
500        ) {
501            unsafe {
502                let f: &F = &*(f as *const F);
503                f(Volume::from_glib_borrow(this).unsafe_cast_ref())
504            }
505        }
506        unsafe {
507            let f: Box_<F> = Box_::new(f);
508            connect_raw(
509                self.as_ptr() as *mut _,
510                c"changed".as_ptr() as *const _,
511                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
512                    changed_trampoline::<Self, F> as *const (),
513                )),
514                Box_::into_raw(f),
515            )
516        }
517    }
518
519    /// This signal is emitted when the #GVolume have been removed. If
520    /// the recipient is holding references to the object they should
521    /// release them so the object can be finalized.
522    #[doc(alias = "removed")]
523    fn connect_removed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
524        unsafe extern "C" fn removed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
525            this: *mut ffi::GVolume,
526            f: glib::ffi::gpointer,
527        ) {
528            unsafe {
529                let f: &F = &*(f as *const F);
530                f(Volume::from_glib_borrow(this).unsafe_cast_ref())
531            }
532        }
533        unsafe {
534            let f: Box_<F> = Box_::new(f);
535            connect_raw(
536                self.as_ptr() as *mut _,
537                c"removed".as_ptr() as *const _,
538                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
539                    removed_trampoline::<Self, F> as *const (),
540                )),
541                Box_::into_raw(f),
542            )
543        }
544    }
545}
546
547impl<O: IsA<Volume>> VolumeExt for O {}