gio/auto/
socket_connection.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::{
6    ffi, AsyncResult, Cancellable, IOStream, Socket, SocketAddress, SocketFamily, SocketType,
7};
8use glib::{prelude::*, translate::*};
9use std::{boxed::Box as Box_, pin::Pin};
10
11glib::wrapper! {
12    /// `GSocketConnection` is a [`IOStream`][crate::IOStream] for a connected socket. They
13    /// can be created either by [`SocketClient`][crate::SocketClient] when connecting to a host,
14    /// or by [`SocketListener`][crate::SocketListener] when accepting a new client.
15    ///
16    /// The type of the `GSocketConnection` object returned from these calls
17    /// depends on the type of the underlying socket that is in use. For
18    /// instance, for a TCP/IP connection it will be a [`TcpConnection`][crate::TcpConnection].
19    ///
20    /// Choosing what type of object to construct is done with the socket
21    /// connection factory, and it is possible for third parties to register
22    /// custom socket connection types for specific combination of socket
23    /// family/type/protocol using [`factory_register_type()`][Self::factory_register_type()].
24    ///
25    /// To close a `GSocketConnection`, use [`IOStreamExt::close()`][crate::prelude::IOStreamExt::close()]. Closing both
26    /// substreams of the [`IOStream`][crate::IOStream] separately will not close the
27    /// underlying [`Socket`][crate::Socket].
28    ///
29    /// ## Properties
30    ///
31    ///
32    /// #### `socket`
33    ///  The underlying [`Socket`][crate::Socket].
34    ///
35    /// Readable | Writeable | Construct Only
36    /// <details><summary><h4>IOStream</h4></summary>
37    ///
38    ///
39    /// #### `closed`
40    ///  Whether the stream is closed.
41    ///
42    /// Readable
43    ///
44    ///
45    /// #### `input-stream`
46    ///  The [`InputStream`][crate::InputStream] to read from.
47    ///
48    /// Readable
49    ///
50    ///
51    /// #### `output-stream`
52    ///  The [`OutputStream`][crate::OutputStream] to write to.
53    ///
54    /// Readable
55    /// </details>
56    ///
57    /// # Implements
58    ///
59    /// [`SocketConnectionExt`][trait@crate::prelude::SocketConnectionExt], [`IOStreamExt`][trait@crate::prelude::IOStreamExt], [`trait@glib::ObjectExt`], [`IOStreamExtManual`][trait@crate::prelude::IOStreamExtManual]
60    #[doc(alias = "GSocketConnection")]
61    pub struct SocketConnection(Object<ffi::GSocketConnection, ffi::GSocketConnectionClass>) @extends IOStream;
62
63    match fn {
64        type_ => || ffi::g_socket_connection_get_type(),
65    }
66}
67
68impl SocketConnection {
69    pub const NONE: Option<&'static SocketConnection> = None;
70
71    /// Looks up the #GType to be used when creating socket connections on
72    /// sockets with the specified @family, @type_ and @protocol_id.
73    ///
74    /// If no type is registered, the #GSocketConnection base type is returned.
75    /// ## `family`
76    /// a #GSocketFamily
77    /// ## `type_`
78    /// a #GSocketType
79    /// ## `protocol_id`
80    /// a protocol id
81    ///
82    /// # Returns
83    ///
84    /// a #GType
85    #[doc(alias = "g_socket_connection_factory_lookup_type")]
86    pub fn factory_lookup_type(
87        family: SocketFamily,
88        type_: SocketType,
89        protocol_id: i32,
90    ) -> glib::types::Type {
91        unsafe {
92            from_glib(ffi::g_socket_connection_factory_lookup_type(
93                family.into_glib(),
94                type_.into_glib(),
95                protocol_id,
96            ))
97        }
98    }
99
100    /// Looks up the #GType to be used when creating socket connections on
101    /// sockets with the specified @family, @type_ and @protocol.
102    ///
103    /// If no type is registered, the #GSocketConnection base type is returned.
104    /// ## `g_type`
105    /// a #GType, inheriting from `G_TYPE_SOCKET_CONNECTION`
106    /// ## `family`
107    /// a #GSocketFamily
108    /// ## `type_`
109    /// a #GSocketType
110    /// ## `protocol`
111    /// a protocol id
112    #[doc(alias = "g_socket_connection_factory_register_type")]
113    pub fn factory_register_type(
114        g_type: glib::types::Type,
115        family: SocketFamily,
116        type_: SocketType,
117        protocol: i32,
118    ) {
119        unsafe {
120            ffi::g_socket_connection_factory_register_type(
121                g_type.into_glib(),
122                family.into_glib(),
123                type_.into_glib(),
124                protocol,
125            );
126        }
127    }
128}
129
130mod sealed {
131    pub trait Sealed {}
132    impl<T: super::IsA<super::SocketConnection>> Sealed for T {}
133}
134
135/// Trait containing all [`struct@SocketConnection`] methods.
136///
137/// # Implementors
138///
139/// [`SocketConnection`][struct@crate::SocketConnection], [`TcpConnection`][struct@crate::TcpConnection], [`UnixConnection`][struct@crate::UnixConnection]
140pub trait SocketConnectionExt: IsA<SocketConnection> + sealed::Sealed + 'static {
141    /// Connect @self to the specified remote address.
142    /// ## `address`
143    /// a #GSocketAddress specifying the remote address.
144    /// ## `cancellable`
145    /// a `GCancellable` or [`None`]
146    ///
147    /// # Returns
148    ///
149    /// [`true`] if the connection succeeded, [`false`] on error
150    #[doc(alias = "g_socket_connection_connect")]
151    fn connect(
152        &self,
153        address: &impl IsA<SocketAddress>,
154        cancellable: Option<&impl IsA<Cancellable>>,
155    ) -> Result<(), glib::Error> {
156        unsafe {
157            let mut error = std::ptr::null_mut();
158            let is_ok = ffi::g_socket_connection_connect(
159                self.as_ref().to_glib_none().0,
160                address.as_ref().to_glib_none().0,
161                cancellable.map(|p| p.as_ref()).to_glib_none().0,
162                &mut error,
163            );
164            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
165            if error.is_null() {
166                Ok(())
167            } else {
168                Err(from_glib_full(error))
169            }
170        }
171    }
172
173    /// Asynchronously connect @self to the specified remote address.
174    ///
175    /// This clears the #GSocket:blocking flag on @self's underlying
176    /// socket if it is currently set.
177    ///
178    /// If #GSocket:timeout is set, the operation will time out and return
179    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] after that period. Otherwise, it will continue
180    /// indefinitely until operating system timeouts (if any) are hit.
181    ///
182    /// Use g_socket_connection_connect_finish() to retrieve the result.
183    /// ## `address`
184    /// a #GSocketAddress specifying the remote address.
185    /// ## `cancellable`
186    /// a `GCancellable` or [`None`]
187    /// ## `callback`
188    /// a #GAsyncReadyCallback
189    #[doc(alias = "g_socket_connection_connect_async")]
190    fn connect_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
191        &self,
192        address: &impl IsA<SocketAddress>,
193        cancellable: Option<&impl IsA<Cancellable>>,
194        callback: P,
195    ) {
196        let main_context = glib::MainContext::ref_thread_default();
197        let is_main_context_owner = main_context.is_owner();
198        let has_acquired_main_context = (!is_main_context_owner)
199            .then(|| main_context.acquire().ok())
200            .flatten();
201        assert!(
202            is_main_context_owner || has_acquired_main_context.is_some(),
203            "Async operations only allowed if the thread is owning the MainContext"
204        );
205
206        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
207            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
208        unsafe extern "C" fn connect_async_trampoline<
209            P: FnOnce(Result<(), glib::Error>) + 'static,
210        >(
211            _source_object: *mut glib::gobject_ffi::GObject,
212            res: *mut crate::ffi::GAsyncResult,
213            user_data: glib::ffi::gpointer,
214        ) {
215            let mut error = std::ptr::null_mut();
216            let _ =
217                ffi::g_socket_connection_connect_finish(_source_object as *mut _, res, &mut error);
218            let result = if error.is_null() {
219                Ok(())
220            } else {
221                Err(from_glib_full(error))
222            };
223            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
224                Box_::from_raw(user_data as *mut _);
225            let callback: P = callback.into_inner();
226            callback(result);
227        }
228        let callback = connect_async_trampoline::<P>;
229        unsafe {
230            ffi::g_socket_connection_connect_async(
231                self.as_ref().to_glib_none().0,
232                address.as_ref().to_glib_none().0,
233                cancellable.map(|p| p.as_ref()).to_glib_none().0,
234                Some(callback),
235                Box_::into_raw(user_data) as *mut _,
236            );
237        }
238    }
239
240    fn connect_future(
241        &self,
242        address: &(impl IsA<SocketAddress> + Clone + 'static),
243    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
244        let address = address.clone();
245        Box_::pin(crate::GioFuture::new(
246            self,
247            move |obj, cancellable, send| {
248                obj.connect_async(&address, Some(cancellable), move |res| {
249                    send.resolve(res);
250                });
251            },
252        ))
253    }
254
255    /// Try to get the local address of a socket connection.
256    ///
257    /// # Returns
258    ///
259    /// a #GSocketAddress or [`None`] on error.
260    ///     Free the returned object with g_object_unref().
261    #[doc(alias = "g_socket_connection_get_local_address")]
262    #[doc(alias = "get_local_address")]
263    fn local_address(&self) -> Result<SocketAddress, glib::Error> {
264        unsafe {
265            let mut error = std::ptr::null_mut();
266            let ret = ffi::g_socket_connection_get_local_address(
267                self.as_ref().to_glib_none().0,
268                &mut error,
269            );
270            if error.is_null() {
271                Ok(from_glib_full(ret))
272            } else {
273                Err(from_glib_full(error))
274            }
275        }
276    }
277
278    /// Try to get the remote address of a socket connection.
279    ///
280    /// Since GLib 2.40, when used with g_socket_client_connect() or
281    /// g_socket_client_connect_async(), during emission of
282    /// [`SocketClientEvent::Connecting`][crate::SocketClientEvent::Connecting], this function will return the remote
283    /// address that will be used for the connection.  This allows
284    /// applications to print e.g. "Connecting to example.com
285    /// (10.42.77.3)...".
286    ///
287    /// # Returns
288    ///
289    /// a #GSocketAddress or [`None`] on error.
290    ///     Free the returned object with g_object_unref().
291    #[doc(alias = "g_socket_connection_get_remote_address")]
292    #[doc(alias = "get_remote_address")]
293    fn remote_address(&self) -> Result<SocketAddress, glib::Error> {
294        unsafe {
295            let mut error = std::ptr::null_mut();
296            let ret = ffi::g_socket_connection_get_remote_address(
297                self.as_ref().to_glib_none().0,
298                &mut error,
299            );
300            if error.is_null() {
301                Ok(from_glib_full(ret))
302            } else {
303                Err(from_glib_full(error))
304            }
305        }
306    }
307
308    /// Gets the underlying #GSocket object of the connection.
309    /// This can be useful if you want to do something unusual on it
310    /// not supported by the #GSocketConnection APIs.
311    ///
312    /// # Returns
313    ///
314    /// a #GSocket or [`None`] on error.
315    #[doc(alias = "g_socket_connection_get_socket")]
316    #[doc(alias = "get_socket")]
317    fn socket(&self) -> Socket {
318        unsafe {
319            from_glib_none(ffi::g_socket_connection_get_socket(
320                self.as_ref().to_glib_none().0,
321            ))
322        }
323    }
324
325    /// Checks if @self is connected. This is equivalent to calling
326    /// g_socket_is_connected() on @self's underlying #GSocket.
327    ///
328    /// # Returns
329    ///
330    /// whether @self is connected
331    #[doc(alias = "g_socket_connection_is_connected")]
332    fn is_connected(&self) -> bool {
333        unsafe {
334            from_glib(ffi::g_socket_connection_is_connected(
335                self.as_ref().to_glib_none().0,
336            ))
337        }
338    }
339}
340
341impl<O: IsA<SocketConnection>> SocketConnectionExt for O {}