gio/auto/
network_monitor.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::{ffi, AsyncResult, Cancellable, Initable, NetworkConnectivity, SocketConnectable};
6use glib::{
7    object::ObjectType as _,
8    prelude::*,
9    signal::{connect_raw, SignalHandlerId},
10    translate::*,
11};
12use std::{boxed::Box as Box_, pin::Pin};
13
14glib::wrapper! {
15    /// `GNetworkMonitor` provides an easy-to-use cross-platform API
16    /// for monitoring network connectivity. On Linux, the available
17    /// implementations are based on the kernel's netlink interface and
18    /// on NetworkManager.
19    ///
20    /// There is also an implementation for use inside Flatpak sandboxes.
21    ///
22    /// ## Properties
23    ///
24    ///
25    /// #### `connectivity`
26    ///  More detailed information about the host's network connectivity.
27    /// See g_network_monitor_get_connectivity() and
28    /// #GNetworkConnectivity for more details.
29    ///
30    /// Readable
31    ///
32    ///
33    /// #### `network-available`
34    ///  Whether the network is considered available. That is, whether the
35    /// system has a default route for at least one of IPv4 or IPv6.
36    ///
37    /// Real-world networks are of course much more complicated than
38    /// this; the machine may be connected to a wifi hotspot that
39    /// requires payment before allowing traffic through, or may be
40    /// connected to a functioning router that has lost its own upstream
41    /// connectivity. Some hosts might only be accessible when a VPN is
42    /// active. Other hosts might only be accessible when the VPN is
43    /// not active. Thus, it is best to use g_network_monitor_can_reach()
44    /// or g_network_monitor_can_reach_async() to test for reachability
45    /// on a host-by-host basis. (On the other hand, when the property is
46    /// [`false`], the application can reasonably expect that no remote
47    /// hosts at all are reachable, and should indicate this to the user
48    /// in its UI.)
49    ///
50    /// See also #GNetworkMonitor::network-changed.
51    ///
52    /// Readable
53    ///
54    ///
55    /// #### `network-metered`
56    ///  Whether the network is considered metered.
57    ///
58    /// That is, whether the
59    /// system has traffic flowing through the default connection that is
60    /// subject to limitations set by service providers. For example, traffic
61    /// might be billed by the amount of data transmitted, or there might be a
62    /// quota on the amount of traffic per month. This is typical with tethered
63    /// connections (3G and 4G) and in such situations, bandwidth intensive
64    /// applications may wish to avoid network activity where possible if it will
65    /// cost the user money or use up their limited quota. Anything more than a
66    /// few hundreds of kilobytes of data usage per hour should be avoided without
67    /// asking permission from the user.
68    ///
69    /// If more information is required about specific devices then the
70    /// system network management API should be used instead (for example,
71    /// NetworkManager or ConnMan).
72    ///
73    /// If this information is not available then no networks will be
74    /// marked as metered.
75    ///
76    /// See also #GNetworkMonitor:network-available.
77    ///
78    /// Readable
79    ///
80    /// ## Signals
81    ///
82    ///
83    /// #### `network-changed`
84    ///  Emitted when the network configuration changes.
85    ///
86    ///
87    ///
88    /// # Implements
89    ///
90    /// [`NetworkMonitorExt`][trait@crate::prelude::NetworkMonitorExt], [`InitableExt`][trait@crate::prelude::InitableExt]
91    #[doc(alias = "GNetworkMonitor")]
92    pub struct NetworkMonitor(Interface<ffi::GNetworkMonitor, ffi::GNetworkMonitorInterface>) @requires Initable;
93
94    match fn {
95        type_ => || ffi::g_network_monitor_get_type(),
96    }
97}
98
99impl NetworkMonitor {
100    pub const NONE: Option<&'static NetworkMonitor> = None;
101
102    /// Gets the default #GNetworkMonitor for the system.
103    ///
104    /// # Returns
105    ///
106    /// a #GNetworkMonitor, which will be
107    ///     a dummy object if no network monitor is available
108    #[doc(alias = "g_network_monitor_get_default")]
109    #[doc(alias = "get_default")]
110    #[allow(clippy::should_implement_trait)]
111    pub fn default() -> NetworkMonitor {
112        unsafe { from_glib_none(ffi::g_network_monitor_get_default()) }
113    }
114}
115
116/// Trait containing all [`struct@NetworkMonitor`] methods.
117///
118/// # Implementors
119///
120/// [`NetworkMonitor`][struct@crate::NetworkMonitor]
121pub trait NetworkMonitorExt: IsA<NetworkMonitor> + 'static {
122    /// Attempts to determine whether or not the host pointed to by
123    /// @connectable can be reached, without actually trying to connect to
124    /// it.
125    ///
126    /// This may return [`true`] even when #GNetworkMonitor:network-available
127    /// is [`false`], if, for example, @self can determine that
128    /// @connectable refers to a host on a local network.
129    ///
130    /// If @self believes that an attempt to connect to @connectable
131    /// will succeed, it will return [`true`]. Otherwise, it will return
132    /// [`false`] and set @error to an appropriate error (such as
133    /// [`IOErrorEnum::HostUnreachable`][crate::IOErrorEnum::HostUnreachable]).
134    ///
135    /// Note that although this does not attempt to connect to
136    /// @connectable, it may still block for a brief period of time (eg,
137    /// trying to do multicast DNS on the local network), so if you do not
138    /// want to block, you should use g_network_monitor_can_reach_async().
139    /// ## `connectable`
140    /// a #GSocketConnectable
141    /// ## `cancellable`
142    /// a #GCancellable, or [`None`]
143    ///
144    /// # Returns
145    ///
146    /// [`true`] if @connectable is reachable, [`false`] if not.
147    #[doc(alias = "g_network_monitor_can_reach")]
148    fn can_reach(
149        &self,
150        connectable: &impl IsA<SocketConnectable>,
151        cancellable: Option<&impl IsA<Cancellable>>,
152    ) -> Result<(), glib::Error> {
153        unsafe {
154            let mut error = std::ptr::null_mut();
155            let is_ok = ffi::g_network_monitor_can_reach(
156                self.as_ref().to_glib_none().0,
157                connectable.as_ref().to_glib_none().0,
158                cancellable.map(|p| p.as_ref()).to_glib_none().0,
159                &mut error,
160            );
161            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
162            if error.is_null() {
163                Ok(())
164            } else {
165                Err(from_glib_full(error))
166            }
167        }
168    }
169
170    /// Asynchronously attempts to determine whether or not the host
171    /// pointed to by @connectable can be reached, without actually
172    /// trying to connect to it.
173    ///
174    /// For more details, see g_network_monitor_can_reach().
175    ///
176    /// When the operation is finished, @callback will be called.
177    /// You can then call g_network_monitor_can_reach_finish()
178    /// to get the result of the operation.
179    /// ## `connectable`
180    /// a #GSocketConnectable
181    /// ## `cancellable`
182    /// a #GCancellable, or [`None`]
183    /// ## `callback`
184    /// a #GAsyncReadyCallback
185    ///     to call when the request is satisfied
186    #[doc(alias = "g_network_monitor_can_reach_async")]
187    fn can_reach_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
188        &self,
189        connectable: &impl IsA<SocketConnectable>,
190        cancellable: Option<&impl IsA<Cancellable>>,
191        callback: P,
192    ) {
193        let main_context = glib::MainContext::ref_thread_default();
194        let is_main_context_owner = main_context.is_owner();
195        let has_acquired_main_context = (!is_main_context_owner)
196            .then(|| main_context.acquire().ok())
197            .flatten();
198        assert!(
199            is_main_context_owner || has_acquired_main_context.is_some(),
200            "Async operations only allowed if the thread is owning the MainContext"
201        );
202
203        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
204            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
205        unsafe extern "C" fn can_reach_async_trampoline<
206            P: FnOnce(Result<(), glib::Error>) + 'static,
207        >(
208            _source_object: *mut glib::gobject_ffi::GObject,
209            res: *mut crate::ffi::GAsyncResult,
210            user_data: glib::ffi::gpointer,
211        ) {
212            let mut error = std::ptr::null_mut();
213            ffi::g_network_monitor_can_reach_finish(_source_object as *mut _, res, &mut error);
214            let result = if error.is_null() {
215                Ok(())
216            } else {
217                Err(from_glib_full(error))
218            };
219            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
220                Box_::from_raw(user_data as *mut _);
221            let callback: P = callback.into_inner();
222            callback(result);
223        }
224        let callback = can_reach_async_trampoline::<P>;
225        unsafe {
226            ffi::g_network_monitor_can_reach_async(
227                self.as_ref().to_glib_none().0,
228                connectable.as_ref().to_glib_none().0,
229                cancellable.map(|p| p.as_ref()).to_glib_none().0,
230                Some(callback),
231                Box_::into_raw(user_data) as *mut _,
232            );
233        }
234    }
235
236    fn can_reach_future(
237        &self,
238        connectable: &(impl IsA<SocketConnectable> + Clone + 'static),
239    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
240        let connectable = connectable.clone();
241        Box_::pin(crate::GioFuture::new(
242            self,
243            move |obj, cancellable, send| {
244                obj.can_reach_async(&connectable, Some(cancellable), move |res| {
245                    send.resolve(res);
246                });
247            },
248        ))
249    }
250
251    /// Gets a more detailed networking state than
252    /// g_network_monitor_get_network_available().
253    ///
254    /// If #GNetworkMonitor:network-available is [`false`], then the
255    /// connectivity state will be [`NetworkConnectivity::Local`][crate::NetworkConnectivity::Local].
256    ///
257    /// If #GNetworkMonitor:network-available is [`true`], then the
258    /// connectivity state will be [`NetworkConnectivity::Full`][crate::NetworkConnectivity::Full] (if there
259    /// is full Internet connectivity), [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] (if
260    /// the host has a default route, but appears to be unable to actually
261    /// reach the full Internet), or [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal] (if the
262    /// host is trapped behind a "captive portal" that requires some sort
263    /// of login or acknowledgement before allowing full Internet access).
264    ///
265    /// Note that in the case of [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] and
266    /// [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal], it is possible that some sites are
267    /// reachable but others are not. In this case, applications can
268    /// attempt to connect to remote servers, but should gracefully fall
269    /// back to their "offline" behavior if the connection attempt fails.
270    ///
271    /// # Returns
272    ///
273    /// the network connectivity state
274    #[doc(alias = "g_network_monitor_get_connectivity")]
275    #[doc(alias = "get_connectivity")]
276    fn connectivity(&self) -> NetworkConnectivity {
277        unsafe {
278            from_glib(ffi::g_network_monitor_get_connectivity(
279                self.as_ref().to_glib_none().0,
280            ))
281        }
282    }
283
284    /// Checks if the network is available. "Available" here means that the
285    /// system has a default route available for at least one of IPv4 or
286    /// IPv6. It does not necessarily imply that the public Internet is
287    /// reachable. See #GNetworkMonitor:network-available for more details.
288    ///
289    /// # Returns
290    ///
291    /// whether the network is available
292    #[doc(alias = "g_network_monitor_get_network_available")]
293    #[doc(alias = "get_network_available")]
294    #[doc(alias = "network-available")]
295    fn is_network_available(&self) -> bool {
296        unsafe {
297            from_glib(ffi::g_network_monitor_get_network_available(
298                self.as_ref().to_glib_none().0,
299            ))
300        }
301    }
302
303    /// Checks if the network is metered.
304    /// See #GNetworkMonitor:network-metered for more details.
305    ///
306    /// # Returns
307    ///
308    /// whether the connection is metered
309    #[doc(alias = "g_network_monitor_get_network_metered")]
310    #[doc(alias = "get_network_metered")]
311    #[doc(alias = "network-metered")]
312    fn is_network_metered(&self) -> bool {
313        unsafe {
314            from_glib(ffi::g_network_monitor_get_network_metered(
315                self.as_ref().to_glib_none().0,
316            ))
317        }
318    }
319
320    /// Emitted when the network configuration changes.
321    /// ## `network_available`
322    /// the current value of #GNetworkMonitor:network-available
323    #[doc(alias = "network-changed")]
324    fn connect_network_changed<F: Fn(&Self, bool) + 'static>(&self, f: F) -> SignalHandlerId {
325        unsafe extern "C" fn network_changed_trampoline<
326            P: IsA<NetworkMonitor>,
327            F: Fn(&P, bool) + 'static,
328        >(
329            this: *mut ffi::GNetworkMonitor,
330            network_available: glib::ffi::gboolean,
331            f: glib::ffi::gpointer,
332        ) {
333            let f: &F = &*(f as *const F);
334            f(
335                NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref(),
336                from_glib(network_available),
337            )
338        }
339        unsafe {
340            let f: Box_<F> = Box_::new(f);
341            connect_raw(
342                self.as_ptr() as *mut _,
343                c"network-changed".as_ptr() as *const _,
344                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
345                    network_changed_trampoline::<Self, F> as *const (),
346                )),
347                Box_::into_raw(f),
348            )
349        }
350    }
351
352    #[doc(alias = "connectivity")]
353    fn connect_connectivity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
354        unsafe extern "C" fn notify_connectivity_trampoline<
355            P: IsA<NetworkMonitor>,
356            F: Fn(&P) + 'static,
357        >(
358            this: *mut ffi::GNetworkMonitor,
359            _param_spec: glib::ffi::gpointer,
360            f: glib::ffi::gpointer,
361        ) {
362            let f: &F = &*(f as *const F);
363            f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
364        }
365        unsafe {
366            let f: Box_<F> = Box_::new(f);
367            connect_raw(
368                self.as_ptr() as *mut _,
369                c"notify::connectivity".as_ptr() as *const _,
370                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
371                    notify_connectivity_trampoline::<Self, F> as *const (),
372                )),
373                Box_::into_raw(f),
374            )
375        }
376    }
377
378    #[doc(alias = "network-available")]
379    fn connect_network_available_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
380        unsafe extern "C" fn notify_network_available_trampoline<
381            P: IsA<NetworkMonitor>,
382            F: Fn(&P) + 'static,
383        >(
384            this: *mut ffi::GNetworkMonitor,
385            _param_spec: glib::ffi::gpointer,
386            f: glib::ffi::gpointer,
387        ) {
388            let f: &F = &*(f as *const F);
389            f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
390        }
391        unsafe {
392            let f: Box_<F> = Box_::new(f);
393            connect_raw(
394                self.as_ptr() as *mut _,
395                c"notify::network-available".as_ptr() as *const _,
396                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
397                    notify_network_available_trampoline::<Self, F> as *const (),
398                )),
399                Box_::into_raw(f),
400            )
401        }
402    }
403
404    #[doc(alias = "network-metered")]
405    fn connect_network_metered_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
406        unsafe extern "C" fn notify_network_metered_trampoline<
407            P: IsA<NetworkMonitor>,
408            F: Fn(&P) + 'static,
409        >(
410            this: *mut ffi::GNetworkMonitor,
411            _param_spec: glib::ffi::gpointer,
412            f: glib::ffi::gpointer,
413        ) {
414            let f: &F = &*(f as *const F);
415            f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
416        }
417        unsafe {
418            let f: Box_<F> = Box_::new(f);
419            connect_raw(
420                self.as_ptr() as *mut _,
421                c"notify::network-metered".as_ptr() as *const _,
422                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
423                    notify_network_metered_trampoline::<Self, F> as *const (),
424                )),
425                Box_::into_raw(f),
426            )
427        }
428    }
429}
430
431impl<O: IsA<NetworkMonitor>> NetworkMonitorExt for O {}