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