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