1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// This code is dual licensed under MIT OR Apache 2.0.

//! A `Connection` implementation that uses a threadpool to handle requests.

use crate::connection::{Connection, Fut, RequestConnection};
use crate::errors::{ConnectError, ConnectionError, ParseError, ReplyOrIdError};
use crate::x11_utils::X11Error;
use crate::SequenceNumber;

use std::future::Future;
use std::io::IoSlice;
use std::mem;
use std::pin::Pin;
use std::sync::Arc;

use x11rb::connection::{Connection as BlConnection, ReplyOrError, RequestKind};
use x11rb::rust_connection::{RustConnection, Stream};

#[cfg(feature = "allow-unsafe-code")]
use std::ffi::CStr;
#[cfg(feature = "allow-unsafe-code")]
use x11rb::xcb_ffi::XCBConnection;

use x11rb_protocol::DiscardMode;

/// A `Connection` implementation that uses a threadpool to handle requests.
///
/// This type wraps around an existing `x11rb` [`Connection`](x11rb::connection::Connection) type,
/// and makes it non-blocking by pushing all operations to a threadpool. This is good if, for instance,
/// you have a `Connection` type that can't trivially be integrated into a async runtime.
///
/// However, if you have the option of using a `Connection` type that is integrated into a real async
/// reactor, you should use that instead.
///
/// # Implementation
///
/// The [`blocking`] threadpool is used to handle all requests.
///
/// [`blocking`]: https://docs.rs/blocking
pub struct BlockingConnection<C> {
    inner: Arc<C>,
}

impl<C: BlConnection + Send + Sync + 'static> BlockingConnection<C> {
    /// Create a new `BlockingConnection` from an existing `Connection`.
    pub fn new(conn: Arc<C>) -> Self {
        Self { inner: conn }
    }

    /// Run the closure with a reference to the underlying connection.
    fn with_conn<T, F>(&self, f: F) -> blocking::Task<T>
    where
        F: FnOnce(&C) -> T + Send + 'static,
        T: Send + 'static,
    {
        let inner = self.inner.clone();
        blocking::unblock(move || f(&inner))
    }

    /// Get a reference to the underlying connection.
    pub fn get_ref(&self) -> &C {
        &self.inner
    }
}

impl BlockingConnection<RustConnection> {
    /// Connect to the X11 server using this connection.
    pub async fn connect(display: Option<&str>) -> Result<(Self, usize), ConnectError> {
        let display = display.map(|s| s.to_string());

        let (inner, screen) =
            blocking::unblock(move || RustConnection::connect(display.as_deref())).await?;

        Ok((Self::new(Arc::new(inner)), screen))
    }
}

impl<S: Stream + Send + Sync + 'static> BlockingConnection<RustConnection<S>> {
    /// Establish a connection over the given stream.
    pub async fn connect_to_stream(stream: S, screen: usize) -> Result<Self, ConnectError> {
        let inner =
            blocking::unblock(move || RustConnection::connect_to_stream(stream, screen)).await?;

        Ok(Self::new(Arc::new(inner)))
    }

    /// Establish a connection over the given stream using the given auth info
    pub async fn connect_to_stream_with_auth_info(
        stream: S,
        screen: usize,
        auth_name: Vec<u8>,
        auth_data: Vec<u8>,
    ) -> Result<Self, ConnectError> {
        let inner = blocking::unblock(move || {
            RustConnection::connect_to_stream_with_auth_info(stream, screen, auth_name, auth_data)
        })
        .await?;

        Ok(Self::new(Arc::new(inner)))
    }
}

#[cfg(feature = "allow-unsafe-code")]
impl BlockingConnection<XCBConnection> {
    /// Connect to the X11 server using this connection.
    pub async fn connect(display: Option<&CStr>) -> Result<(Self, usize), ConnectError> {
        let display = display.map(|s| s.to_owned());

        let (inner, screen) =
            blocking::unblock(move || XCBConnection::connect(display.as_deref())).await?;

        Ok((Self::new(Arc::new(inner)), screen))
    }
}

impl<C: BlConnection + Send + Sync + 'static> RequestConnection for BlockingConnection<C> {
    type Buf = C::Buf;

    fn check_for_raw_error(
        &self,
        sequence: SequenceNumber,
    ) -> Fut<'_, Option<Self::Buf>, ConnectionError> {
        Box::pin(self.with_conn(move |conn| conn.check_for_raw_error(sequence)))
    }

    fn discard_reply(&self, sequence: SequenceNumber, kind: RequestKind, mode: DiscardMode) {
        // Doesn't block.
        self.inner.discard_reply(sequence, kind, mode);
    }

    fn extension_information(
        &self,
        name: &'static str,
    ) -> Fut<'_, Option<x11rb::x11_utils::ExtensionInformation>, ConnectionError> {
        Box::pin(self.with_conn(move |conn| conn.extension_information(name)))
    }

    fn prefetch_extension_information(&self, name: &'static str) -> Fut<'_, (), ConnectionError> {
        Box::pin(self.with_conn(move |conn| conn.prefetch_extension_information(name)))
    }

    fn maximum_request_bytes(&self) -> Pin<Box<dyn Future<Output = usize> + Send + '_>> {
        Box::pin(self.with_conn(|conn| conn.maximum_request_bytes()))
    }

    fn prefetch_maximum_request_bytes(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        Box::pin(self.with_conn(|conn| conn.prefetch_maximum_request_bytes()))
    }

    fn parse_error(&self, error: &[u8]) -> Result<X11Error, ParseError> {
        // Doesn't block.
        self.inner.parse_error(error)
    }

    fn parse_event(&self, event: &[u8]) -> Result<x11rb::protocol::Event, ParseError> {
        // Doesn't block.
        self.inner.parse_event(event)
    }

    fn send_request_with_reply<'this, 'bufs, 'sl, 're, 'future, R>(
        &'this self,
        bufs: &'bufs [IoSlice<'sl>],
        fds: Vec<x11rb_protocol::RawFdContainer>,
    ) -> Fut<'future, crate::Cookie<'this, Self, R>, ConnectionError>
    where
        'this: 'future,
        'bufs: 'future,
        'sl: 'future,
        're: 'future,
        R: x11rb::x11_utils::TryParse + Send + 're,
    {
        let mut buf = Vec::with_capacity(bufs.iter().map(|b| b.len()).sum());
        for b in bufs {
            buf.extend_from_slice(b);
        }

        Box::pin(async move {
            let res = self
                .with_conn(move |conn| {
                    let slices = [IoSlice::new(&buf)];
                    let cookie = conn.send_request_with_reply::<R>(&slices, fds)?;

                    let sequence = {
                        let sequence = cookie.sequence_number();
                        mem::forget(cookie);
                        sequence
                    };

                    Ok::<_, ConnectionError>(sequence)
                })
                .await?;

            Ok(crate::Cookie::new(self, res))
        })
    }

    fn send_request_with_reply_with_fds<'this, 'bufs, 'sl, 're, 'future, R>(
        &'this self,
        bufs: &'bufs [IoSlice<'sl>],
        fds: Vec<x11rb_protocol::RawFdContainer>,
    ) -> Fut<'future, crate::CookieWithFds<'this, Self, R>, ConnectionError>
    where
        'this: 'future,
        'bufs: 'future,
        'sl: 'future,
        're: 'future,
        R: x11rb::x11_utils::TryParseFd + Send + 're,
    {
        let mut buf = Vec::with_capacity(bufs.iter().map(|b| b.len()).sum());
        for b in bufs {
            buf.extend_from_slice(b);
        }

        Box::pin(async move {
            let res = self
                .with_conn(move |conn| {
                    let slices = [IoSlice::new(&buf)];
                    let cookie = conn.send_request_with_reply_with_fds::<R>(&slices, fds)?;

                    let sequence = {
                        let sequence = cookie.sequence_number();
                        mem::forget(cookie);
                        sequence
                    };

                    Ok::<_, ConnectionError>(sequence)
                })
                .await?;

            Ok(crate::CookieWithFds::new(self, res))
        })
    }

    fn send_request_without_reply<'this, 'bufs, 'sl, 'future>(
        &'this self,
        bufs: &'bufs [IoSlice<'sl>],
        fds: Vec<x11rb_protocol::RawFdContainer>,
    ) -> Fut<'future, crate::VoidCookie<'this, Self>, ConnectionError>
    where
        'this: 'future,
        'bufs: 'future,
        'sl: 'future,
    {
        let mut buf = Vec::with_capacity(bufs.iter().map(|b| b.len()).sum());
        for b in bufs {
            buf.extend_from_slice(b);
        }

        Box::pin(async move {
            let res = self
                .with_conn(move |conn| {
                    let slices = [IoSlice::new(&buf)];
                    let cookie = conn.send_request_without_reply(&slices, fds)?;

                    let sequence = {
                        let sequence = cookie.sequence_number();
                        mem::forget(cookie);
                        sequence
                    };

                    Ok::<_, ConnectionError>(sequence)
                })
                .await?;

            Ok(crate::VoidCookie::new(self, res))
        })
    }

    fn wait_for_reply(
        &self,
        sequence: SequenceNumber,
    ) -> Fut<'_, Option<Self::Buf>, ConnectionError> {
        Box::pin(self.with_conn(move |conn| conn.wait_for_reply(sequence)))
    }

    fn wait_for_reply_or_raw_error(
        &self,
        sequence: SequenceNumber,
    ) -> Fut<'_, ReplyOrError<Self::Buf>, ConnectionError> {
        Box::pin(self.with_conn(move |conn| conn.wait_for_reply_or_raw_error(sequence)))
    }

    fn wait_for_reply_with_fds_raw(
        &self,
        sequence: SequenceNumber,
    ) -> Fut<'_, ReplyOrError<x11rb::connection::BufWithFds<Self::Buf>, Self::Buf>, ConnectionError>
    {
        Box::pin(self.with_conn(move |conn| conn.wait_for_reply_with_fds_raw(sequence)))
    }
}

impl<C: BlConnection + Send + Sync + 'static> Connection for BlockingConnection<C> {
    fn poll_for_raw_event_with_sequence(
        &self,
    ) -> Result<Option<x11rb_protocol::RawEventAndSeqNumber<Self::Buf>>, ConnectionError> {
        // Doesn't block.
        self.inner.poll_for_raw_event_with_sequence()
    }

    fn wait_for_raw_event_with_sequence(
        &self,
    ) -> Fut<'_, x11rb_protocol::RawEventAndSeqNumber<Self::Buf>, ConnectionError> {
        Box::pin(self.with_conn(|conn| conn.wait_for_raw_event_with_sequence()))
    }

    fn generate_id(&self) -> Fut<'_, u32, ReplyOrIdError> {
        Box::pin(self.with_conn(|conn| conn.generate_id()))
    }

    fn flush(&self) -> Fut<'_, (), ConnectionError> {
        Box::pin(self.with_conn(|conn| conn.flush()))
    }

    fn setup(&self) -> &x11rb::protocol::xproto::Setup {
        self.inner.setup()
    }
}