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 ffi::g_socket_connection_connect_finish(_source_object as *mut _, res, &mut error);
217 let result = if error.is_null() {
218 Ok(())
219 } else {
220 Err(from_glib_full(error))
221 };
222 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
223 Box_::from_raw(user_data as *mut _);
224 let callback: P = callback.into_inner();
225 callback(result);
226 }
227 let callback = connect_async_trampoline::<P>;
228 unsafe {
229 ffi::g_socket_connection_connect_async(
230 self.as_ref().to_glib_none().0,
231 address.as_ref().to_glib_none().0,
232 cancellable.map(|p| p.as_ref()).to_glib_none().0,
233 Some(callback),
234 Box_::into_raw(user_data) as *mut _,
235 );
236 }
237 }
238
239 fn connect_future(
240 &self,
241 address: &(impl IsA<SocketAddress> + Clone + 'static),
242 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
243 let address = address.clone();
244 Box_::pin(crate::GioFuture::new(
245 self,
246 move |obj, cancellable, send| {
247 obj.connect_async(&address, Some(cancellable), move |res| {
248 send.resolve(res);
249 });
250 },
251 ))
252 }
253
254 /// Try to get the local address of a socket connection.
255 ///
256 /// # Returns
257 ///
258 /// a #GSocketAddress or [`None`] on error.
259 /// Free the returned object with g_object_unref().
260 #[doc(alias = "g_socket_connection_get_local_address")]
261 #[doc(alias = "get_local_address")]
262 fn local_address(&self) -> Result<SocketAddress, glib::Error> {
263 unsafe {
264 let mut error = std::ptr::null_mut();
265 let ret = ffi::g_socket_connection_get_local_address(
266 self.as_ref().to_glib_none().0,
267 &mut error,
268 );
269 if error.is_null() {
270 Ok(from_glib_full(ret))
271 } else {
272 Err(from_glib_full(error))
273 }
274 }
275 }
276
277 /// Try to get the remote address of a socket connection.
278 ///
279 /// Since GLib 2.40, when used with g_socket_client_connect() or
280 /// g_socket_client_connect_async(), during emission of
281 /// [`SocketClientEvent::Connecting`][crate::SocketClientEvent::Connecting], this function will return the remote
282 /// address that will be used for the connection. This allows
283 /// applications to print e.g. "Connecting to example.com
284 /// (10.42.77.3)...".
285 ///
286 /// # Returns
287 ///
288 /// a #GSocketAddress or [`None`] on error.
289 /// Free the returned object with g_object_unref().
290 #[doc(alias = "g_socket_connection_get_remote_address")]
291 #[doc(alias = "get_remote_address")]
292 fn remote_address(&self) -> Result<SocketAddress, glib::Error> {
293 unsafe {
294 let mut error = std::ptr::null_mut();
295 let ret = ffi::g_socket_connection_get_remote_address(
296 self.as_ref().to_glib_none().0,
297 &mut error,
298 );
299 if error.is_null() {
300 Ok(from_glib_full(ret))
301 } else {
302 Err(from_glib_full(error))
303 }
304 }
305 }
306
307 /// Gets the underlying #GSocket object of the connection.
308 /// This can be useful if you want to do something unusual on it
309 /// not supported by the #GSocketConnection APIs.
310 ///
311 /// # Returns
312 ///
313 /// a #GSocket or [`None`] on error.
314 #[doc(alias = "g_socket_connection_get_socket")]
315 #[doc(alias = "get_socket")]
316 fn socket(&self) -> Socket {
317 unsafe {
318 from_glib_none(ffi::g_socket_connection_get_socket(
319 self.as_ref().to_glib_none().0,
320 ))
321 }
322 }
323
324 /// Checks if @self is connected. This is equivalent to calling
325 /// g_socket_is_connected() on @self's underlying #GSocket.
326 ///
327 /// # Returns
328 ///
329 /// whether @self is connected
330 #[doc(alias = "g_socket_connection_is_connected")]
331 fn is_connected(&self) -> bool {
332 unsafe {
333 from_glib(ffi::g_socket_connection_is_connected(
334 self.as_ref().to_glib_none().0,
335 ))
336 }
337 }
338}
339
340impl<O: IsA<SocketConnection>> SocketConnectionExt for O {}