Skip to main content

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::{AsyncResult, Cancellable, Initable, NetworkConnectivity, SocketConnectable, ffi};
6use glib::{
7    object::ObjectType as _,
8    prelude::*,
9    signal::{SignalHandlerId, connect_raw},
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    /// Some implementations complete their initialization asynchronously:
105    /// properties such as #GNetworkMonitor:network-available may start at their
106    /// default values and update shortly afterwards, with notify emissions, once
107    /// the state is resolved from the thread-default main context of this first
108    /// call.
109    ///
110    /// # Returns
111    ///
112    /// a #GNetworkMonitor, which will be
113    ///     a dummy object if no network monitor is available
114    #[doc(alias = "g_network_monitor_get_default")]
115    #[doc(alias = "get_default")]
116    #[allow(clippy::should_implement_trait)]
117    pub fn default() -> NetworkMonitor {
118        unsafe { from_glib_none(ffi::g_network_monitor_get_default()) }
119    }
120}
121
122/// Trait containing all [`struct@NetworkMonitor`] methods.
123///
124/// # Implementors
125///
126/// [`NetworkMonitor`][struct@crate::NetworkMonitor]
127pub trait NetworkMonitorExt: IsA<NetworkMonitor> + 'static {
128    /// Attempts to determine whether or not the host pointed to by
129    /// @connectable can be reached, without actually trying to connect to
130    /// it.
131    ///
132    /// This may return [`true`] even when #GNetworkMonitor:network-available
133    /// is [`false`], if, for example, @self can determine that
134    /// @connectable refers to a host on a local network.
135    ///
136    /// If @self believes that an attempt to connect to @connectable
137    /// will succeed, it will return [`true`]. Otherwise, it will return
138    /// [`false`] and set @error to an appropriate error (such as
139    /// [`IOErrorEnum::HostUnreachable`][crate::IOErrorEnum::HostUnreachable]).
140    ///
141    /// Note that although this does not attempt to connect to
142    /// @connectable, it may still block for a brief period of time (eg,
143    /// trying to do multicast DNS on the local network), so if you do not
144    /// want to block, you should use g_network_monitor_can_reach_async().
145    /// ## `connectable`
146    /// a #GSocketConnectable
147    /// ## `cancellable`
148    /// a #GCancellable, or [`None`]
149    ///
150    /// # Returns
151    ///
152    /// [`true`] if @connectable is reachable, [`false`] if not.
153    #[doc(alias = "g_network_monitor_can_reach")]
154    fn can_reach(
155        &self,
156        connectable: &impl IsA<SocketConnectable>,
157        cancellable: Option<&impl IsA<Cancellable>>,
158    ) -> Result<(), glib::Error> {
159        unsafe {
160            let mut error = std::ptr::null_mut();
161            let is_ok = ffi::g_network_monitor_can_reach(
162                self.as_ref().to_glib_none().0,
163                connectable.as_ref().to_glib_none().0,
164                cancellable.map(|p| p.as_ref()).to_glib_none().0,
165                &mut error,
166            );
167            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
168            if error.is_null() {
169                Ok(())
170            } else {
171                Err(from_glib_full(error))
172            }
173        }
174    }
175
176    /// Asynchronously attempts to determine whether or not the host
177    /// pointed to by @connectable can be reached, without actually
178    /// trying to connect to it.
179    ///
180    /// For more details, see g_network_monitor_can_reach().
181    ///
182    /// When the operation is finished, @callback will be called.
183    /// You can then call g_network_monitor_can_reach_finish()
184    /// to get the result of the operation.
185    /// ## `connectable`
186    /// a #GSocketConnectable
187    /// ## `cancellable`
188    /// a #GCancellable, or [`None`]
189    /// ## `callback`
190    /// a #GAsyncReadyCallback
191    ///     to call when the request is satisfied
192    #[doc(alias = "g_network_monitor_can_reach_async")]
193    fn can_reach_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
194        &self,
195        connectable: &impl IsA<SocketConnectable>,
196        cancellable: Option<&impl IsA<Cancellable>>,
197        callback: P,
198    ) {
199        let main_context = glib::MainContext::ref_thread_default();
200        let is_main_context_owner = main_context.is_owner();
201        let has_acquired_main_context = (!is_main_context_owner)
202            .then(|| main_context.acquire().ok())
203            .flatten();
204        assert!(
205            is_main_context_owner || has_acquired_main_context.is_some(),
206            "Async operations only allowed if the thread is owning the MainContext"
207        );
208
209        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
210            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
211        unsafe extern "C" fn can_reach_async_trampoline<
212            P: FnOnce(Result<(), glib::Error>) + 'static,
213        >(
214            _source_object: *mut glib::gobject_ffi::GObject,
215            res: *mut crate::ffi::GAsyncResult,
216            user_data: glib::ffi::gpointer,
217        ) {
218            unsafe {
219                let mut error = std::ptr::null_mut();
220                ffi::g_network_monitor_can_reach_finish(_source_object as *mut _, res, &mut error);
221                let result = if error.is_null() {
222                    Ok(())
223                } else {
224                    Err(from_glib_full(error))
225                };
226                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
227                    Box_::from_raw(user_data as *mut _);
228                let callback: P = callback.into_inner();
229                callback(result);
230            }
231        }
232        let callback = can_reach_async_trampoline::<P>;
233        unsafe {
234            ffi::g_network_monitor_can_reach_async(
235                self.as_ref().to_glib_none().0,
236                connectable.as_ref().to_glib_none().0,
237                cancellable.map(|p| p.as_ref()).to_glib_none().0,
238                Some(callback),
239                Box_::into_raw(user_data) as *mut _,
240            );
241        }
242    }
243
244    fn can_reach_future(
245        &self,
246        connectable: &(impl IsA<SocketConnectable> + Clone + 'static),
247    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
248        let connectable = connectable.clone();
249        Box_::pin(crate::GioFuture::new(
250            self,
251            move |obj, cancellable, send| {
252                obj.can_reach_async(&connectable, Some(cancellable), move |res| {
253                    send.resolve(res);
254                });
255            },
256        ))
257    }
258
259    /// Gets a more detailed networking state than
260    /// g_network_monitor_get_network_available().
261    ///
262    /// If #GNetworkMonitor:network-available is [`false`], then the
263    /// connectivity state will be [`NetworkConnectivity::Local`][crate::NetworkConnectivity::Local].
264    ///
265    /// If #GNetworkMonitor:network-available is [`true`], then the
266    /// connectivity state will be [`NetworkConnectivity::Full`][crate::NetworkConnectivity::Full] (if there
267    /// is full Internet connectivity), [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] (if
268    /// the host has a default route, but appears to be unable to actually
269    /// reach the full Internet), or [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal] (if the
270    /// host is trapped behind a "captive portal" that requires some sort
271    /// of login or acknowledgement before allowing full Internet access).
272    ///
273    /// Note that in the case of [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] and
274    /// [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal], it is possible that some sites are
275    /// reachable but others are not. In this case, applications can
276    /// attempt to connect to remote servers, but should gracefully fall
277    /// back to their "offline" behavior if the connection attempt fails.
278    ///
279    /// # Returns
280    ///
281    /// the network connectivity state
282    #[doc(alias = "g_network_monitor_get_connectivity")]
283    #[doc(alias = "get_connectivity")]
284    fn connectivity(&self) -> NetworkConnectivity {
285        unsafe {
286            from_glib(ffi::g_network_monitor_get_connectivity(
287                self.as_ref().to_glib_none().0,
288            ))
289        }
290    }
291
292    /// Checks if the network is available. "Available" here means that the
293    /// system has a default route available for at least one of IPv4 or
294    /// IPv6. It does not necessarily imply that the public Internet is
295    /// reachable. See #GNetworkMonitor:network-available for more details.
296    ///
297    /// # Returns
298    ///
299    /// whether the network is available
300    #[doc(alias = "g_network_monitor_get_network_available")]
301    #[doc(alias = "get_network_available")]
302    #[doc(alias = "network-available")]
303    fn is_network_available(&self) -> bool {
304        unsafe {
305            from_glib(ffi::g_network_monitor_get_network_available(
306                self.as_ref().to_glib_none().0,
307            ))
308        }
309    }
310
311    /// Checks if the network is metered.
312    /// See #GNetworkMonitor:network-metered for more details.
313    ///
314    /// # Returns
315    ///
316    /// whether the connection is metered
317    #[doc(alias = "g_network_monitor_get_network_metered")]
318    #[doc(alias = "get_network_metered")]
319    #[doc(alias = "network-metered")]
320    fn is_network_metered(&self) -> bool {
321        unsafe {
322            from_glib(ffi::g_network_monitor_get_network_metered(
323                self.as_ref().to_glib_none().0,
324            ))
325        }
326    }
327
328    /// Emitted when the network configuration changes.
329    /// ## `network_available`
330    /// the current value of #GNetworkMonitor:network-available
331    #[doc(alias = "network-changed")]
332    fn connect_network_changed<F: Fn(&Self, bool) + 'static>(&self, f: F) -> SignalHandlerId {
333        unsafe extern "C" fn network_changed_trampoline<
334            P: IsA<NetworkMonitor>,
335            F: Fn(&P, bool) + 'static,
336        >(
337            this: *mut ffi::GNetworkMonitor,
338            network_available: glib::ffi::gboolean,
339            f: glib::ffi::gpointer,
340        ) {
341            unsafe {
342                let f: &F = &*(f as *const F);
343                f(
344                    NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref(),
345                    from_glib(network_available),
346                )
347            }
348        }
349        unsafe {
350            let f: Box_<F> = Box_::new(f);
351            connect_raw(
352                self.as_ptr() as *mut _,
353                c"network-changed".as_ptr(),
354                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
355                    network_changed_trampoline::<Self, F> as *const (),
356                )),
357                Box_::into_raw(f),
358            )
359        }
360    }
361
362    #[doc(alias = "connectivity")]
363    fn connect_connectivity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
364        unsafe extern "C" fn notify_connectivity_trampoline<
365            P: IsA<NetworkMonitor>,
366            F: Fn(&P) + 'static,
367        >(
368            this: *mut ffi::GNetworkMonitor,
369            _param_spec: glib::ffi::gpointer,
370            f: glib::ffi::gpointer,
371        ) {
372            unsafe {
373                let f: &F = &*(f as *const F);
374                f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
375            }
376        }
377        unsafe {
378            let f: Box_<F> = Box_::new(f);
379            connect_raw(
380                self.as_ptr() as *mut _,
381                c"notify::connectivity".as_ptr(),
382                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
383                    notify_connectivity_trampoline::<Self, F> as *const (),
384                )),
385                Box_::into_raw(f),
386            )
387        }
388    }
389
390    #[doc(alias = "network-available")]
391    fn connect_network_available_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
392        unsafe extern "C" fn notify_network_available_trampoline<
393            P: IsA<NetworkMonitor>,
394            F: Fn(&P) + 'static,
395        >(
396            this: *mut ffi::GNetworkMonitor,
397            _param_spec: glib::ffi::gpointer,
398            f: glib::ffi::gpointer,
399        ) {
400            unsafe {
401                let f: &F = &*(f as *const F);
402                f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
403            }
404        }
405        unsafe {
406            let f: Box_<F> = Box_::new(f);
407            connect_raw(
408                self.as_ptr() as *mut _,
409                c"notify::network-available".as_ptr(),
410                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
411                    notify_network_available_trampoline::<Self, F> as *const (),
412                )),
413                Box_::into_raw(f),
414            )
415        }
416    }
417
418    #[doc(alias = "network-metered")]
419    fn connect_network_metered_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
420        unsafe extern "C" fn notify_network_metered_trampoline<
421            P: IsA<NetworkMonitor>,
422            F: Fn(&P) + 'static,
423        >(
424            this: *mut ffi::GNetworkMonitor,
425            _param_spec: glib::ffi::gpointer,
426            f: glib::ffi::gpointer,
427        ) {
428            unsafe {
429                let f: &F = &*(f as *const F);
430                f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
431            }
432        }
433        unsafe {
434            let f: Box_<F> = Box_::new(f);
435            connect_raw(
436                self.as_ptr() as *mut _,
437                c"notify::network-metered".as_ptr(),
438                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
439                    notify_network_metered_trampoline::<Self, F> as *const (),
440                )),
441                Box_::into_raw(f),
442            )
443        }
444    }
445}
446
447impl<O: IsA<NetworkMonitor>> NetworkMonitorExt for O {}