Skip to main content

gtk4/auto/
uri_launcher.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::{Window, ffi};
6use glib::{
7    prelude::*,
8    signal::{SignalHandlerId, connect_raw},
9    translate::*,
10};
11use std::{boxed::Box as Box_, pin::Pin};
12
13glib::wrapper! {
14    /// Asynchronous API to open a uri with an application.
15    ///
16    /// [`UriLauncher`][crate::UriLauncher] collects the arguments that are needed to open the uri.
17    ///
18    /// Depending on system configuration, user preferences and available APIs, this
19    /// may or may not show an app chooser dialog or launch the default application
20    /// right away.
21    ///
22    /// The operation is started with the [`launch()`][Self::launch()] function.
23    ///
24    /// To launch a file, use [`FileLauncher`][crate::FileLauncher].
25    ///
26    /// ## Properties
27    ///
28    ///
29    /// #### `uri`
30    ///  The uri to launch.
31    ///
32    /// Readable | Writeable
33    ///
34    /// # Implements
35    ///
36    /// [`trait@glib::ObjectExt`]
37    #[doc(alias = "GtkUriLauncher")]
38    pub struct UriLauncher(Object<ffi::GtkUriLauncher, ffi::GtkUriLauncherClass>);
39
40    match fn {
41        type_ => || ffi::gtk_uri_launcher_get_type(),
42    }
43}
44
45impl UriLauncher {
46    /// Creates a new [`UriLauncher`][crate::UriLauncher] object.
47    /// ## `uri`
48    /// the uri to open
49    ///
50    /// # Returns
51    ///
52    /// the new [`UriLauncher`][crate::UriLauncher]
53    #[doc(alias = "gtk_uri_launcher_new")]
54    pub fn new(uri: &str) -> UriLauncher {
55        assert_initialized_main_thread!();
56        unsafe { from_glib_full(ffi::gtk_uri_launcher_new(uri.to_glib_none().0)) }
57    }
58
59    // rustdoc-stripper-ignore-next
60    /// Creates a new builder-pattern struct instance to construct [`UriLauncher`] objects.
61    ///
62    /// This method returns an instance of [`UriLauncherBuilder`](crate::builders::UriLauncherBuilder) which can be used to create [`UriLauncher`] objects.
63    pub fn builder() -> UriLauncherBuilder {
64        UriLauncherBuilder::new()
65    }
66
67    /// Returns whether the launcher is likely to succeed
68    /// in launching an application for its uri.
69    ///
70    /// This can be used to disable controls that trigger
71    /// the launcher when they are known not to work.
72    /// ## `parent`
73    /// the parent window
74    ///
75    /// # Returns
76    ///
77    /// false if the launcher is known not to support
78    ///   the uri, true otherwise
79    #[cfg(feature = "v4_20")]
80    #[cfg_attr(docsrs, doc(cfg(feature = "v4_20")))]
81    #[doc(alias = "gtk_uri_launcher_can_launch")]
82    pub fn can_launch(&self, parent: Option<&impl IsA<Window>>) -> bool {
83        unsafe {
84            from_glib(ffi::gtk_uri_launcher_can_launch(
85                self.to_glib_none().0,
86                parent.map(|p| p.as_ref()).to_glib_none().0,
87            ))
88        }
89    }
90
91    /// Gets the uri that will be opened.
92    ///
93    /// # Returns
94    ///
95    /// the uri
96    #[doc(alias = "gtk_uri_launcher_get_uri")]
97    #[doc(alias = "get_uri")]
98    pub fn uri(&self) -> Option<glib::GString> {
99        unsafe { from_glib_none(ffi::gtk_uri_launcher_get_uri(self.to_glib_none().0)) }
100    }
101
102    /// Launches an application to open the uri.
103    ///
104    /// This may present an app chooser dialog to the user.
105    /// ## `parent`
106    /// the parent window
107    /// ## `cancellable`
108    /// a cancellable to cancel the operation
109    /// ## `callback`
110    /// a callback to call when the
111    ///   operation is complete
112    #[doc(alias = "gtk_uri_launcher_launch")]
113    pub fn launch<P: FnOnce(Result<(), glib::Error>) + 'static>(
114        &self,
115        parent: Option<&impl IsA<Window>>,
116        cancellable: Option<&impl IsA<gio::Cancellable>>,
117        callback: P,
118    ) {
119        let main_context = glib::MainContext::ref_thread_default();
120        let is_main_context_owner = main_context.is_owner();
121        let has_acquired_main_context = (!is_main_context_owner)
122            .then(|| main_context.acquire().ok())
123            .flatten();
124        assert!(
125            is_main_context_owner || has_acquired_main_context.is_some(),
126            "Async operations only allowed if the thread is owning the MainContext"
127        );
128
129        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
130            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
131        unsafe extern "C" fn launch_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
132            _source_object: *mut glib::gobject_ffi::GObject,
133            res: *mut gio::ffi::GAsyncResult,
134            user_data: glib::ffi::gpointer,
135        ) {
136            unsafe {
137                let mut error = std::ptr::null_mut();
138                ffi::gtk_uri_launcher_launch_finish(_source_object as *mut _, res, &mut error);
139                let result = if error.is_null() {
140                    Ok(())
141                } else {
142                    Err(from_glib_full(error))
143                };
144                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
145                    Box_::from_raw(user_data as *mut _);
146                let callback: P = callback.into_inner();
147                callback(result);
148            }
149        }
150        let callback = launch_trampoline::<P>;
151        unsafe {
152            ffi::gtk_uri_launcher_launch(
153                self.to_glib_none().0,
154                parent.map(|p| p.as_ref()).to_glib_none().0,
155                cancellable.map(|p| p.as_ref()).to_glib_none().0,
156                Some(callback),
157                Box_::into_raw(user_data) as *mut _,
158            );
159        }
160    }
161
162    pub fn launch_future(
163        &self,
164        parent: Option<&(impl IsA<Window> + Clone + 'static)>,
165    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
166        let parent = parent.map(ToOwned::to_owned);
167        Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
168            obj.launch(
169                parent.as_ref().map(::std::borrow::Borrow::borrow),
170                Some(cancellable),
171                move |res| {
172                    send.resolve(res);
173                },
174            );
175        }))
176    }
177
178    /// Sets the uri that will be opened.
179    /// ## `uri`
180    /// the uri
181    #[doc(alias = "gtk_uri_launcher_set_uri")]
182    #[doc(alias = "uri")]
183    pub fn set_uri(&self, uri: Option<&str>) {
184        unsafe {
185            ffi::gtk_uri_launcher_set_uri(self.to_glib_none().0, uri.to_glib_none().0);
186        }
187    }
188
189    #[cfg(feature = "v4_10")]
190    #[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
191    #[doc(alias = "uri")]
192    pub fn connect_uri_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
193        unsafe extern "C" fn notify_uri_trampoline<F: Fn(&UriLauncher) + 'static>(
194            this: *mut ffi::GtkUriLauncher,
195            _param_spec: glib::ffi::gpointer,
196            f: glib::ffi::gpointer,
197        ) {
198            unsafe {
199                let f: &F = &*(f as *const F);
200                f(&from_glib_borrow(this))
201            }
202        }
203        unsafe {
204            let f: Box_<F> = Box_::new(f);
205            connect_raw(
206                self.as_ptr() as *mut _,
207                c"notify::uri".as_ptr() as *const _,
208                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
209                    notify_uri_trampoline::<F> as *const (),
210                )),
211                Box_::into_raw(f),
212            )
213        }
214    }
215}
216
217#[cfg(feature = "v4_10")]
218#[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
219impl Default for UriLauncher {
220    fn default() -> Self {
221        glib::object::Object::new::<Self>()
222    }
223}
224
225// rustdoc-stripper-ignore-next
226/// A [builder-pattern] type to construct [`UriLauncher`] objects.
227///
228/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
229#[must_use = "The builder must be built to be used"]
230pub struct UriLauncherBuilder {
231    builder: glib::object::ObjectBuilder<'static, UriLauncher>,
232}
233
234impl UriLauncherBuilder {
235    fn new() -> Self {
236        Self {
237            builder: glib::object::Object::builder(),
238        }
239    }
240
241    /// The uri to launch.
242    #[cfg(feature = "v4_10")]
243    #[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
244    pub fn uri(self, uri: impl Into<glib::GString>) -> Self {
245        Self {
246            builder: self.builder.property("uri", uri.into()),
247        }
248    }
249
250    // rustdoc-stripper-ignore-next
251    /// Build the [`UriLauncher`].
252    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
253    pub fn build(self) -> UriLauncher {
254        assert_initialized_main_thread!();
255        self.builder.build()
256    }
257}