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 /// # 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 unsafe {
213 let mut error = std::ptr::null_mut();
214 ffi::g_network_monitor_can_reach_finish(_source_object as *mut _, res, &mut error);
215 let result = if error.is_null() {
216 Ok(())
217 } else {
218 Err(from_glib_full(error))
219 };
220 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
221 Box_::from_raw(user_data as *mut _);
222 let callback: P = callback.into_inner();
223 callback(result);
224 }
225 }
226 let callback = can_reach_async_trampoline::<P>;
227 unsafe {
228 ffi::g_network_monitor_can_reach_async(
229 self.as_ref().to_glib_none().0,
230 connectable.as_ref().to_glib_none().0,
231 cancellable.map(|p| p.as_ref()).to_glib_none().0,
232 Some(callback),
233 Box_::into_raw(user_data) as *mut _,
234 );
235 }
236 }
237
238 fn can_reach_future(
239 &self,
240 connectable: &(impl IsA<SocketConnectable> + Clone + 'static),
241 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
242 let connectable = connectable.clone();
243 Box_::pin(crate::GioFuture::new(
244 self,
245 move |obj, cancellable, send| {
246 obj.can_reach_async(&connectable, Some(cancellable), move |res| {
247 send.resolve(res);
248 });
249 },
250 ))
251 }
252
253 /// Gets a more detailed networking state than
254 /// g_network_monitor_get_network_available().
255 ///
256 /// If #GNetworkMonitor:network-available is [`false`], then the
257 /// connectivity state will be [`NetworkConnectivity::Local`][crate::NetworkConnectivity::Local].
258 ///
259 /// If #GNetworkMonitor:network-available is [`true`], then the
260 /// connectivity state will be [`NetworkConnectivity::Full`][crate::NetworkConnectivity::Full] (if there
261 /// is full Internet connectivity), [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] (if
262 /// the host has a default route, but appears to be unable to actually
263 /// reach the full Internet), or [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal] (if the
264 /// host is trapped behind a "captive portal" that requires some sort
265 /// of login or acknowledgement before allowing full Internet access).
266 ///
267 /// Note that in the case of [`NetworkConnectivity::Limited`][crate::NetworkConnectivity::Limited] and
268 /// [`NetworkConnectivity::Portal`][crate::NetworkConnectivity::Portal], it is possible that some sites are
269 /// reachable but others are not. In this case, applications can
270 /// attempt to connect to remote servers, but should gracefully fall
271 /// back to their "offline" behavior if the connection attempt fails.
272 ///
273 /// # Returns
274 ///
275 /// the network connectivity state
276 #[doc(alias = "g_network_monitor_get_connectivity")]
277 #[doc(alias = "get_connectivity")]
278 fn connectivity(&self) -> NetworkConnectivity {
279 unsafe {
280 from_glib(ffi::g_network_monitor_get_connectivity(
281 self.as_ref().to_glib_none().0,
282 ))
283 }
284 }
285
286 /// Checks if the network is available. "Available" here means that the
287 /// system has a default route available for at least one of IPv4 or
288 /// IPv6. It does not necessarily imply that the public Internet is
289 /// reachable. See #GNetworkMonitor:network-available for more details.
290 ///
291 /// # Returns
292 ///
293 /// whether the network is available
294 #[doc(alias = "g_network_monitor_get_network_available")]
295 #[doc(alias = "get_network_available")]
296 #[doc(alias = "network-available")]
297 fn is_network_available(&self) -> bool {
298 unsafe {
299 from_glib(ffi::g_network_monitor_get_network_available(
300 self.as_ref().to_glib_none().0,
301 ))
302 }
303 }
304
305 /// Checks if the network is metered.
306 /// See #GNetworkMonitor:network-metered for more details.
307 ///
308 /// # Returns
309 ///
310 /// whether the connection is metered
311 #[doc(alias = "g_network_monitor_get_network_metered")]
312 #[doc(alias = "get_network_metered")]
313 #[doc(alias = "network-metered")]
314 fn is_network_metered(&self) -> bool {
315 unsafe {
316 from_glib(ffi::g_network_monitor_get_network_metered(
317 self.as_ref().to_glib_none().0,
318 ))
319 }
320 }
321
322 /// Emitted when the network configuration changes.
323 /// ## `network_available`
324 /// the current value of #GNetworkMonitor:network-available
325 #[doc(alias = "network-changed")]
326 fn connect_network_changed<F: Fn(&Self, bool) + 'static>(&self, f: F) -> SignalHandlerId {
327 unsafe extern "C" fn network_changed_trampoline<
328 P: IsA<NetworkMonitor>,
329 F: Fn(&P, bool) + 'static,
330 >(
331 this: *mut ffi::GNetworkMonitor,
332 network_available: glib::ffi::gboolean,
333 f: glib::ffi::gpointer,
334 ) {
335 unsafe {
336 let f: &F = &*(f as *const F);
337 f(
338 NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref(),
339 from_glib(network_available),
340 )
341 }
342 }
343 unsafe {
344 let f: Box_<F> = Box_::new(f);
345 connect_raw(
346 self.as_ptr() as *mut _,
347 c"network-changed".as_ptr() as *const _,
348 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
349 network_changed_trampoline::<Self, F> as *const (),
350 )),
351 Box_::into_raw(f),
352 )
353 }
354 }
355
356 #[doc(alias = "connectivity")]
357 fn connect_connectivity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
358 unsafe extern "C" fn notify_connectivity_trampoline<
359 P: IsA<NetworkMonitor>,
360 F: Fn(&P) + 'static,
361 >(
362 this: *mut ffi::GNetworkMonitor,
363 _param_spec: glib::ffi::gpointer,
364 f: glib::ffi::gpointer,
365 ) {
366 unsafe {
367 let f: &F = &*(f as *const F);
368 f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
369 }
370 }
371 unsafe {
372 let f: Box_<F> = Box_::new(f);
373 connect_raw(
374 self.as_ptr() as *mut _,
375 c"notify::connectivity".as_ptr() as *const _,
376 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
377 notify_connectivity_trampoline::<Self, F> as *const (),
378 )),
379 Box_::into_raw(f),
380 )
381 }
382 }
383
384 #[doc(alias = "network-available")]
385 fn connect_network_available_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
386 unsafe extern "C" fn notify_network_available_trampoline<
387 P: IsA<NetworkMonitor>,
388 F: Fn(&P) + 'static,
389 >(
390 this: *mut ffi::GNetworkMonitor,
391 _param_spec: glib::ffi::gpointer,
392 f: glib::ffi::gpointer,
393 ) {
394 unsafe {
395 let f: &F = &*(f as *const F);
396 f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
397 }
398 }
399 unsafe {
400 let f: Box_<F> = Box_::new(f);
401 connect_raw(
402 self.as_ptr() as *mut _,
403 c"notify::network-available".as_ptr() as *const _,
404 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
405 notify_network_available_trampoline::<Self, F> as *const (),
406 )),
407 Box_::into_raw(f),
408 )
409 }
410 }
411
412 #[doc(alias = "network-metered")]
413 fn connect_network_metered_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
414 unsafe extern "C" fn notify_network_metered_trampoline<
415 P: IsA<NetworkMonitor>,
416 F: Fn(&P) + 'static,
417 >(
418 this: *mut ffi::GNetworkMonitor,
419 _param_spec: glib::ffi::gpointer,
420 f: glib::ffi::gpointer,
421 ) {
422 unsafe {
423 let f: &F = &*(f as *const F);
424 f(NetworkMonitor::from_glib_borrow(this).unsafe_cast_ref())
425 }
426 }
427 unsafe {
428 let f: Box_<F> = Box_::new(f);
429 connect_raw(
430 self.as_ptr() as *mut _,
431 c"notify::network-metered".as_ptr() as *const _,
432 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
433 notify_network_metered_trampoline::<Self, F> as *const (),
434 )),
435 Box_::into_raw(f),
436 )
437 }
438 }
439}
440
441impl<O: IsA<NetworkMonitor>> NetworkMonitorExt for O {}