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
130/// Trait containing all [`struct@SocketConnection`] methods.
131///
132/// # Implementors
133///
134/// [`SocketConnection`][struct@crate::SocketConnection], [`TcpConnection`][struct@crate::TcpConnection], [`UnixConnection`][struct@crate::UnixConnection]
135pub trait SocketConnectionExt: IsA<SocketConnection> + 'static {
136    /// Connect @self to the specified remote address.
137    /// ## `address`
138    /// a #GSocketAddress specifying the remote address.
139    /// ## `cancellable`
140    /// a `GCancellable` or [`None`]
141    ///
142    /// # Returns
143    ///
144    /// [`true`] if the connection succeeded, [`false`] on error
145    #[doc(alias = "g_socket_connection_connect")]
146    fn connect(
147        &self,
148        address: &impl IsA<SocketAddress>,
149        cancellable: Option<&impl IsA<Cancellable>>,
150    ) -> Result<(), glib::Error> {
151        unsafe {
152            let mut error = std::ptr::null_mut();
153            let is_ok = ffi::g_socket_connection_connect(
154                self.as_ref().to_glib_none().0,
155                address.as_ref().to_glib_none().0,
156                cancellable.map(|p| p.as_ref()).to_glib_none().0,
157                &mut error,
158            );
159            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
160            if error.is_null() {
161                Ok(())
162            } else {
163                Err(from_glib_full(error))
164            }
165        }
166    }
167
168    /// Asynchronously connect @self to the specified remote address.
169    ///
170    /// This clears the #GSocket:blocking flag on @self's underlying
171    /// socket if it is currently set.
172    ///
173    /// If #GSocket:timeout is set, the operation will time out and return
174    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] after that period. Otherwise, it will continue
175    /// indefinitely until operating system timeouts (if any) are hit.
176    ///
177    /// Use g_socket_connection_connect_finish() to retrieve the result.
178    /// ## `address`
179    /// a #GSocketAddress specifying the remote address.
180    /// ## `cancellable`
181    /// a `GCancellable` or [`None`]
182    /// ## `callback`
183    /// a #GAsyncReadyCallback
184    #[doc(alias = "g_socket_connection_connect_async")]
185    fn connect_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
186        &self,
187        address: &impl IsA<SocketAddress>,
188        cancellable: Option<&impl IsA<Cancellable>>,
189        callback: P,
190    ) {
191        let main_context = glib::MainContext::ref_thread_default();
192        let is_main_context_owner = main_context.is_owner();
193        let has_acquired_main_context = (!is_main_context_owner)
194            .then(|| main_context.acquire().ok())
195            .flatten();
196        assert!(
197            is_main_context_owner || has_acquired_main_context.is_some(),
198            "Async operations only allowed if the thread is owning the MainContext"
199        );
200
201        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
202            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
203        unsafe extern "C" fn connect_async_trampoline<
204            P: FnOnce(Result<(), glib::Error>) + 'static,
205        >(
206            _source_object: *mut glib::gobject_ffi::GObject,
207            res: *mut crate::ffi::GAsyncResult,
208            user_data: glib::ffi::gpointer,
209        ) {
210            let mut error = std::ptr::null_mut();
211            ffi::g_socket_connection_connect_finish(_source_object as *mut _, res, &mut error);
212            let result = if error.is_null() {
213                Ok(())
214            } else {
215                Err(from_glib_full(error))
216            };
217            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
218                Box_::from_raw(user_data as *mut _);
219            let callback: P = callback.into_inner();
220            callback(result);
221        }
222        let callback = connect_async_trampoline::<P>;
223        unsafe {
224            ffi::g_socket_connection_connect_async(
225                self.as_ref().to_glib_none().0,
226                address.as_ref().to_glib_none().0,
227                cancellable.map(|p| p.as_ref()).to_glib_none().0,
228                Some(callback),
229                Box_::into_raw(user_data) as *mut _,
230            );
231        }
232    }
233
234    fn connect_future(
235        &self,
236        address: &(impl IsA<SocketAddress> + Clone + 'static),
237    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
238        let address = address.clone();
239        Box_::pin(crate::GioFuture::new(
240            self,
241            move |obj, cancellable, send| {
242                obj.connect_async(&address, Some(cancellable), move |res| {
243                    send.resolve(res);
244                });
245            },
246        ))
247    }
248
249    /// Try to get the local address of a socket connection.
250    ///
251    /// # Returns
252    ///
253    /// a #GSocketAddress or [`None`] on error.
254    ///     Free the returned object with g_object_unref().
255    #[doc(alias = "g_socket_connection_get_local_address")]
256    #[doc(alias = "get_local_address")]
257    fn local_address(&self) -> Result<SocketAddress, glib::Error> {
258        unsafe {
259            let mut error = std::ptr::null_mut();
260            let ret = ffi::g_socket_connection_get_local_address(
261                self.as_ref().to_glib_none().0,
262                &mut error,
263            );
264            if error.is_null() {
265                Ok(from_glib_full(ret))
266            } else {
267                Err(from_glib_full(error))
268            }
269        }
270    }
271
272    /// Try to get the remote address of a socket connection.
273    ///
274    /// Since GLib 2.40, when used with g_socket_client_connect() or
275    /// g_socket_client_connect_async(), during emission of
276    /// [`SocketClientEvent::Connecting`][crate::SocketClientEvent::Connecting], this function will return the remote
277    /// address that will be used for the connection.  This allows
278    /// applications to print e.g. "Connecting to example.com
279    /// (10.42.77.3)...".
280    ///
281    /// # Returns
282    ///
283    /// a #GSocketAddress or [`None`] on error.
284    ///     Free the returned object with g_object_unref().
285    #[doc(alias = "g_socket_connection_get_remote_address")]
286    #[doc(alias = "get_remote_address")]
287    fn remote_address(&self) -> Result<SocketAddress, glib::Error> {
288        unsafe {
289            let mut error = std::ptr::null_mut();
290            let ret = ffi::g_socket_connection_get_remote_address(
291                self.as_ref().to_glib_none().0,
292                &mut error,
293            );
294            if error.is_null() {
295                Ok(from_glib_full(ret))
296            } else {
297                Err(from_glib_full(error))
298            }
299        }
300    }
301
302    /// Gets the underlying #GSocket object of the connection.
303    /// This can be useful if you want to do something unusual on it
304    /// not supported by the #GSocketConnection APIs.
305    ///
306    /// # Returns
307    ///
308    /// a #GSocket or [`None`] on error.
309    #[doc(alias = "g_socket_connection_get_socket")]
310    #[doc(alias = "get_socket")]
311    fn socket(&self) -> Socket {
312        unsafe {
313            from_glib_none(ffi::g_socket_connection_get_socket(
314                self.as_ref().to_glib_none().0,
315            ))
316        }
317    }
318
319    /// Checks if @self is connected. This is equivalent to calling
320    /// g_socket_is_connected() on @self's underlying #GSocket.
321    ///
322    /// # Returns
323    ///
324    /// whether @self is connected
325    #[doc(alias = "g_socket_connection_is_connected")]
326    fn is_connected(&self) -> bool {
327        unsafe {
328            from_glib(ffi::g_socket_connection_is_connected(
329                self.as_ref().to_glib_none().0,
330            ))
331        }
332    }
333}
334
335impl<O: IsA<SocketConnection>> SocketConnectionExt for O {}