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    ///
231    ///   (g_file_has_prefix (volume_activation_root, mount_root) ||
232    ///    g_file_equal (volume_activation_root, mount_root))
233    /// ]|
234    /// will always be [`true`].
235    ///
236    /// Activation roots are typically used in #GVolumeMonitor
237    /// implementations to find the underlying mount to shadow, see
238    /// g_mount_is_shadowed() for more details.
239    ///
240    /// # Returns
241    ///
242    /// the activation root of @self
243    ///     or [`None`]. Use g_object_unref() to free.
244    #[doc(alias = "g_volume_get_activation_root")]
245    #[doc(alias = "get_activation_root")]
246    fn activation_root(&self) -> Option<File> {
247        unsafe {
248            from_glib_full(ffi::g_volume_get_activation_root(
249                self.as_ref().to_glib_none().0,
250            ))
251        }
252    }
253
254    /// Gets the drive for the @self.
255    ///
256    /// # Returns
257    ///
258    /// a #GDrive or [`None`] if @self is not
259    ///     associated with a drive. The returned object should be unreffed
260    ///     with g_object_unref() when no longer needed.
261    #[doc(alias = "g_volume_get_drive")]
262    #[doc(alias = "get_drive")]
263    fn drive(&self) -> Option<Drive> {
264        unsafe { from_glib_full(ffi::g_volume_get_drive(self.as_ref().to_glib_none().0)) }
265    }
266
267    /// Gets the icon for @self.
268    ///
269    /// # Returns
270    ///
271    /// a #GIcon.
272    ///     The returned object should be unreffed with g_object_unref()
273    ///     when no longer needed.
274    #[doc(alias = "g_volume_get_icon")]
275    #[doc(alias = "get_icon")]
276    fn icon(&self) -> Icon {
277        unsafe { from_glib_full(ffi::g_volume_get_icon(self.as_ref().to_glib_none().0)) }
278    }
279
280    /// Gets the identifier of the given kind for @self.
281    /// See the [introduction](#volume-identifiers) for more
282    /// information about volume identifiers.
283    /// ## `kind`
284    /// the kind of identifier to return
285    ///
286    /// # Returns
287    ///
288    /// a newly allocated string containing the
289    ///     requested identifier, or [`None`] if the #GVolume
290    ///     doesn't have this kind of identifier
291    #[doc(alias = "g_volume_get_identifier")]
292    #[doc(alias = "get_identifier")]
293    fn identifier(&self, kind: &str) -> Option<glib::GString> {
294        unsafe {
295            from_glib_full(ffi::g_volume_get_identifier(
296                self.as_ref().to_glib_none().0,
297                kind.to_glib_none().0,
298            ))
299        }
300    }
301
302    /// Gets the mount for the @self.
303    ///
304    /// # Returns
305    ///
306    /// a #GMount or [`None`] if @self isn't mounted.
307    ///     The returned object should be unreffed with g_object_unref()
308    ///     when no longer needed.
309    #[doc(alias = "g_volume_get_mount")]
310    fn get_mount(&self) -> Option<Mount> {
311        unsafe { from_glib_full(ffi::g_volume_get_mount(self.as_ref().to_glib_none().0)) }
312    }
313
314    /// Gets the name of @self.
315    ///
316    /// # Returns
317    ///
318    /// the name for the given @self. The returned string should
319    ///     be freed with g_free() when no longer needed.
320    #[doc(alias = "g_volume_get_name")]
321    #[doc(alias = "get_name")]
322    fn name(&self) -> glib::GString {
323        unsafe { from_glib_full(ffi::g_volume_get_name(self.as_ref().to_glib_none().0)) }
324    }
325
326    /// Gets the sort key for @self, if any.
327    ///
328    /// # Returns
329    ///
330    /// Sorting key for @self or [`None`] if no such key is available
331    #[doc(alias = "g_volume_get_sort_key")]
332    #[doc(alias = "get_sort_key")]
333    fn sort_key(&self) -> Option<glib::GString> {
334        unsafe { from_glib_none(ffi::g_volume_get_sort_key(self.as_ref().to_glib_none().0)) }
335    }
336
337    /// Gets the symbolic icon for @self.
338    ///
339    /// # Returns
340    ///
341    /// a #GIcon.
342    ///     The returned object should be unreffed with g_object_unref()
343    ///     when no longer needed.
344    #[doc(alias = "g_volume_get_symbolic_icon")]
345    #[doc(alias = "get_symbolic_icon")]
346    fn symbolic_icon(&self) -> Icon {
347        unsafe {
348            from_glib_full(ffi::g_volume_get_symbolic_icon(
349                self.as_ref().to_glib_none().0,
350            ))
351        }
352    }
353
354    /// Gets the UUID for the @self. The reference is typically based on
355    /// the file system UUID for the volume in question and should be
356    /// considered an opaque string. Returns [`None`] if there is no UUID
357    /// available.
358    ///
359    /// # Returns
360    ///
361    /// the UUID for @self or [`None`] if no UUID
362    ///     can be computed.
363    ///     The returned string should be freed with g_free()
364    ///     when no longer needed.
365    #[doc(alias = "g_volume_get_uuid")]
366    #[doc(alias = "get_uuid")]
367    fn uuid(&self) -> Option<glib::GString> {
368        unsafe { from_glib_full(ffi::g_volume_get_uuid(self.as_ref().to_glib_none().0)) }
369    }
370
371    /// Mounts a volume. This is an asynchronous operation, and is
372    /// finished by calling g_volume_mount_finish() with the @self
373    /// and #GAsyncResult returned in the @callback.
374    /// ## `flags`
375    /// flags affecting the operation
376    /// ## `mount_operation`
377    /// a #GMountOperation or [`None`] to avoid user interaction
378    /// ## `cancellable`
379    /// optional #GCancellable object, [`None`] to ignore
380    /// ## `callback`
381    /// a #GAsyncReadyCallback, or [`None`]
382    #[doc(alias = "g_volume_mount")]
383    fn mount<P: FnOnce(Result<(), glib::Error>) + 'static>(
384        &self,
385        flags: MountMountFlags,
386        mount_operation: Option<&impl IsA<MountOperation>>,
387        cancellable: Option<&impl IsA<Cancellable>>,
388        callback: P,
389    ) {
390        let main_context = glib::MainContext::ref_thread_default();
391        let is_main_context_owner = main_context.is_owner();
392        let has_acquired_main_context = (!is_main_context_owner)
393            .then(|| main_context.acquire().ok())
394            .flatten();
395        assert!(
396            is_main_context_owner || has_acquired_main_context.is_some(),
397            "Async operations only allowed if the thread is owning the MainContext"
398        );
399
400        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
401            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
402        unsafe extern "C" fn mount_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
403            _source_object: *mut glib::gobject_ffi::GObject,
404            res: *mut crate::ffi::GAsyncResult,
405            user_data: glib::ffi::gpointer,
406        ) {
407            unsafe {
408                let mut error = std::ptr::null_mut();
409                ffi::g_volume_mount_finish(_source_object as *mut _, res, &mut error);
410                let result = if error.is_null() {
411                    Ok(())
412                } else {
413                    Err(from_glib_full(error))
414                };
415                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
416                    Box_::from_raw(user_data as *mut _);
417                let callback: P = callback.into_inner();
418                callback(result);
419            }
420        }
421        let callback = mount_trampoline::<P>;
422        unsafe {
423            ffi::g_volume_mount(
424                self.as_ref().to_glib_none().0,
425                flags.into_glib(),
426                mount_operation.map(|p| p.as_ref()).to_glib_none().0,
427                cancellable.map(|p| p.as_ref()).to_glib_none().0,
428                Some(callback),
429                Box_::into_raw(user_data) as *mut _,
430            );
431        }
432    }
433
434    fn mount_future(
435        &self,
436        flags: MountMountFlags,
437        mount_operation: Option<&(impl IsA<MountOperation> + Clone + 'static)>,
438    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
439        let mount_operation = mount_operation.map(ToOwned::to_owned);
440        Box_::pin(crate::GioFuture::new(
441            self,
442            move |obj, cancellable, send| {
443                obj.mount(
444                    flags,
445                    mount_operation.as_ref().map(::std::borrow::Borrow::borrow),
446                    Some(cancellable),
447                    move |res| {
448                        send.resolve(res);
449                    },
450                );
451            },
452        ))
453    }
454
455    /// Returns whether the volume should be automatically mounted.
456    ///
457    /// # Returns
458    ///
459    /// [`true`] if the volume should be automatically mounted
460    #[doc(alias = "g_volume_should_automount")]
461    fn should_automount(&self) -> bool {
462        unsafe {
463            from_glib(ffi::g_volume_should_automount(
464                self.as_ref().to_glib_none().0,
465            ))
466        }
467    }
468
469    /// Emitted when the volume has been changed.
470    #[doc(alias = "changed")]
471    fn connect_changed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
472        unsafe extern "C" fn changed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
473            this: *mut ffi::GVolume,
474            f: glib::ffi::gpointer,
475        ) {
476            unsafe {
477                let f: &F = &*(f as *const F);
478                f(Volume::from_glib_borrow(this).unsafe_cast_ref())
479            }
480        }
481        unsafe {
482            let f: Box_<F> = Box_::new(f);
483            connect_raw(
484                self.as_ptr() as *mut _,
485                c"changed".as_ptr(),
486                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
487                    changed_trampoline::<Self, F> as *const (),
488                )),
489                Box_::into_raw(f),
490            )
491        }
492    }
493
494    /// This signal is emitted when the #GVolume have been removed. If
495    /// the recipient is holding references to the object they should
496    /// release them so the object can be finalized.
497    #[doc(alias = "removed")]
498    fn connect_removed<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
499        unsafe extern "C" fn removed_trampoline<P: IsA<Volume>, F: Fn(&P) + 'static>(
500            this: *mut ffi::GVolume,
501            f: glib::ffi::gpointer,
502        ) {
503            unsafe {
504                let f: &F = &*(f as *const F);
505                f(Volume::from_glib_borrow(this).unsafe_cast_ref())
506            }
507        }
508        unsafe {
509            let f: Box_<F> = Box_::new(f);
510            connect_raw(
511                self.as_ptr() as *mut _,
512                c"removed".as_ptr(),
513                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
514                    removed_trampoline::<Self, F> as *const (),
515                )),
516                Box_::into_raw(f),
517            )
518        }
519    }
520}
521
522impl<O: IsA<Volume>> VolumeExt for O {}