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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//               Copyright John Nunley, 2022.
// Distributed under the Boost Software License, Version 1.0.
//       (See accompanying file LICENSE or copy at
//         https://www.boost.org/LICENSE_1_0.txt)

#![cfg(feature = "sync_display")]

use super::{Display, DisplayBase, RawReply, RawRequest};
use crate::{mutex::Mutex, Result};
use alloc::sync::Arc;
use x11rb_protocol::protocol::{xproto::Setup, Event};

cfg_async! {
    use super::{AsyncStatus, CanBeAsyncDisplay, AsyncDisplay, Interest};
    use concurrent_queue::ConcurrentQueue;
    use core::task::{Context, Waker, Poll};
}

/// A `Display` that uses a mutex to coordinate access.
pub struct SyncDisplay<Dpy: ?Sized> {
    setup: Arc<Setup>,
    default_screen_index: usize,
    waiters: Waiters,
    inner: Mutex<Dpy>,
}

/// A helper type for `SyncDisplay` that allows us to use `Waker`s to wake up
/// the `SyncDisplay` when a lock is released.
///
/// Basically uses a "thunder lock". Performant for fewer concurrent accesses.
///
/// Is a no-op for non-async targets.
struct Waiters {
    #[cfg(feature = "async")]
    wakers: ConcurrentQueue<Waker>,
}

impl<Dpy: DisplayBase> From<Dpy> for SyncDisplay<Dpy> {
    fn from(bd: Dpy) -> Self {
        let setup = bd.setup().clone();
        Self {
            setup,
            default_screen_index: bd.default_screen_index(),
            inner: Mutex::new(bd),
            waiters: Waiters {
                #[cfg(feature = "async")]
                wakers: make_waker_queue(),
            },
        }
    }
}

#[cfg(all(feature = "async", feature = "std"))]
fn make_waker_queue() -> ConcurrentQueue<Waker> {
    // if the user wants an unbounded queue, oblige them
    if std::env::var_os("BREADX_UNBOUNDED_WAKER_QUEUE")
        .as_ref()
        .and_then(|t| t.to_str())
        == Some("1")
    {
        ConcurrentQueue::unbounded()
    } else {
        ConcurrentQueue::bounded(1024)
    }
}

#[cfg(all(feature = "async", not(feature = "std")))]
fn make_waker_queue() -> ConcurrentQueue<Waker> {
    ConcurrentQueue::bounded(1024)
}

impl<Dpy: ?Sized> SyncDisplay<Dpy> {
    fn with_inner<R>(&self, f: impl FnOnce(&mut Dpy) -> R) -> R {
        let res = f(&mut *self.inner.lock());

        // signal that we have released the mutex
        self.waiters.release();
        res
    }

    fn with_inner_mut<R>(&mut self, f: impl FnOnce(&mut Dpy) -> R) -> R {
        let res = f(self.inner.get_mut());
        // don't need to signal, &mut indicates that no one has an
        // & reference == no wakers
        res
    }

    fn try_with_inner<R>(
        &self,
        f: impl FnOnce(&mut Dpy) -> Result<Option<R>>,
    ) -> Result<Option<R>> {
        match self.inner.try_lock() {
            Some(mut lock) => {
                let res = f(&mut *lock);
                self.waiters.release();
                res
            }
            None => Ok(None),
        }
    }

    #[cfg(feature = "async")]
    fn try_status_inner<R>(
        &self,
        ctx: &mut Context<'_>,
        f: impl FnOnce(&mut Dpy, &mut Context<'_>) -> Result<AsyncStatus<R>>,
    ) -> Result<AsyncStatus<R>> {
        match self.inner.try_lock() {
            Some(mut lock) => {
                let res = f(&mut *lock, ctx);
                self.waiters.release();
                res
            }
            None => {
                self.waiters.push(ctx.waker());
                Ok(AsyncStatus::UserControlled)
            }
        }
    }

    #[cfg(feature = "async")]
    fn poll_inner<R>(
        &self,
        ctx: &mut Context<'_>,
        f: impl FnOnce(&mut Dpy, &mut Context<'_>) -> Poll<Result<R>>,
    ) -> Poll<Result<R>> {
        match self.inner.try_lock() {
            Some(mut lock) => {
                let res = f(&mut *lock, ctx);
                self.waiters.release();
                res
            }
            None => {
                self.waiters.push(ctx.waker());
                Poll::Pending
            }
        }
    }
}

impl Waiters {
    #[cfg(feature = "async")]
    fn push(&self, waker: &Waker) {
        self.wakers.push(waker.clone()).ok();
    }

    fn release(&self) {
        #[cfg(feature = "async")]
        while let Ok(waker) = self.wakers.pop() {
            waker.wake();
        }
    }
}

impl<Dpy: DisplayBase + ?Sized> DisplayBase for SyncDisplay<Dpy> {
    fn setup(&self) -> &Arc<Setup> {
        &self.setup
    }

    fn default_screen_index(&self) -> usize {
        self.default_screen_index
    }

    fn poll_for_event(&mut self) -> Result<Option<Event>> {
        self.with_inner_mut(DisplayBase::poll_for_event)
    }

    fn poll_for_reply_raw(&mut self, seq: u64) -> Result<Option<RawReply>> {
        self.with_inner_mut(move |inner| inner.poll_for_reply_raw(seq))
    }
}

impl<Dpy: DisplayBase + ?Sized> DisplayBase for &SyncDisplay<Dpy> {
    fn setup(&self) -> &Arc<Setup> {
        &self.setup
    }

    fn default_screen_index(&self) -> usize {
        self.default_screen_index
    }

    fn poll_for_event(&mut self) -> Result<Option<Event>> {
        self.try_with_inner(DisplayBase::poll_for_event)
    }

    fn poll_for_reply_raw(&mut self, seq: u64) -> Result<Option<RawReply>> {
        self.try_with_inner(move |inner| inner.poll_for_reply_raw(seq))
    }
}

impl<Dpy: Display + ?Sized> Display for SyncDisplay<Dpy> {
    fn send_request_raw(&mut self, req: RawRequest<'_, '_>) -> Result<u64> {
        self.with_inner_mut(move |inner| inner.send_request_raw(req))
    }

    fn wait_for_event(&mut self) -> Result<Event> {
        self.with_inner_mut(Display::wait_for_event)
    }

    fn wait_for_reply_raw(&mut self, seq: u64) -> Result<RawReply> {
        self.with_inner_mut(move |inner| inner.wait_for_reply_raw(seq))
    }

    fn flush(&mut self) -> Result<()> {
        self.with_inner_mut(Display::flush)
    }

    fn generate_xid(&mut self) -> Result<u32> {
        self.with_inner_mut(Display::generate_xid)
    }

    fn maximum_request_length(&mut self) -> Result<usize> {
        self.with_inner_mut(Display::maximum_request_length)
    }

    fn synchronize(&mut self) -> Result<()> {
        self.with_inner_mut(Display::synchronize)
    }

    fn check_for_error(&mut self, seq: u64) -> Result<()> {
        self.with_inner_mut(move |inner| inner.check_for_error(seq))
    }
}

impl<Dpy: Display + ?Sized> Display for &SyncDisplay<Dpy> {
    fn send_request_raw(&mut self, req: RawRequest<'_, '_>) -> Result<u64> {
        self.with_inner(move |inner| inner.send_request_raw(req))
    }

    fn wait_for_event(&mut self) -> Result<Event> {
        self.with_inner(Display::wait_for_event)
    }

    fn wait_for_reply_raw(&mut self, seq: u64) -> Result<RawReply> {
        self.with_inner(move |inner| inner.wait_for_reply_raw(seq))
    }

    fn flush(&mut self) -> Result<()> {
        self.with_inner(Display::flush)
    }

    fn generate_xid(&mut self) -> Result<u32> {
        self.with_inner(Display::generate_xid)
    }

    fn maximum_request_length(&mut self) -> Result<usize> {
        self.with_inner(Display::maximum_request_length)
    }

    fn synchronize(&mut self) -> Result<()> {
        self.with_inner(Display::synchronize)
    }

    fn check_for_error(&mut self, seq: u64) -> Result<()> {
        self.with_inner(move |inner| inner.check_for_error(seq))
    }
}

cfg_async! {
    impl<Dpy: CanBeAsyncDisplay + ?Sized> CanBeAsyncDisplay for SyncDisplay<Dpy> {
        fn format_request(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<u64>> {
            self.with_inner_mut(move |inner| inner.format_request(req, ctx))
        }

        fn try_send_request_raw(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<()>> {
            self.with_inner_mut(move |inner| inner.try_send_request_raw(req, ctx))
        }

        fn try_wait_for_event(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<Event>> {
            self.with_inner_mut(move |inner| inner.try_wait_for_event(ctx))
        }

        fn try_wait_for_reply_raw(
            &mut self,
            seq: u64,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<RawReply>> {
            self.with_inner_mut(move |inner| inner.try_wait_for_reply_raw(seq, ctx))
        }

        fn try_flush(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
            self.with_inner_mut(move |inner| inner.try_flush(ctx))
        }

        fn try_generate_xid(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<u32>> {
            self.with_inner_mut(move |inner| inner.try_generate_xid(ctx))
        }

        fn try_maximum_request_length(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<usize>> {
            self.with_inner_mut(move |inner| inner.try_maximum_request_length(ctx))
        }

        fn try_check_for_error(
            &mut self,
            seq: u64,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<()>> {
            self.with_inner_mut(move |inner| inner.try_check_for_error(seq, ctx))
        }
    }

    impl<Dpy: CanBeAsyncDisplay + ?Sized> CanBeAsyncDisplay for &SyncDisplay<Dpy> {
        fn format_request(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<u64>> {
            self.try_status_inner(ctx, move |inner, ctx| inner.format_request(req, ctx))
        }

        fn try_send_request_raw(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<()>> {
            self.try_status_inner(ctx, move |inner, ctx| inner.try_send_request_raw(req, ctx))
        }

        fn try_wait_for_reply_raw(
            &mut self,
            seq: u64,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<RawReply>> {
            self.try_status_inner(ctx, move |inner, ctx| {
                inner.try_wait_for_reply_raw(seq, ctx)
            })
        }

        fn try_wait_for_event(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<Event>> {
            self.try_status_inner(ctx, CanBeAsyncDisplay::try_wait_for_event)
        }

        fn try_flush(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>> {
            self.try_status_inner(ctx, CanBeAsyncDisplay::try_flush)
        }

        fn try_generate_xid(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<u32>> {
            self.try_status_inner(ctx, CanBeAsyncDisplay::try_generate_xid)
        }

        fn try_maximum_request_length(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<usize>> {
            self.try_status_inner(ctx, CanBeAsyncDisplay::try_maximum_request_length)
        }

        fn try_check_for_error(
            &mut self,
            seq: u64,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<()>> {
            self.try_status_inner(ctx, move |inner, ctx| inner.try_check_for_error(seq, ctx))
        }
    }

    impl<Dpy: AsyncDisplay + ?Sized> AsyncDisplay for SyncDisplay<Dpy> {
        fn poll_for_interest(
            &mut self,
            interest: Interest,
            callback: &mut dyn FnMut(&mut dyn AsyncDisplay, &mut Context< '_>) -> Result<()>,
            ctx: &mut Context< '_>,
        ) -> Poll<Result<()>> {
            self.poll_inner(ctx, |dpy, ctx| dpy.poll_for_interest(interest, callback, ctx))
        }
    }

    impl<Dpy: AsyncDisplay + ?Sized> AsyncDisplay for &SyncDisplay<Dpy> {
        fn poll_for_interest(
            &mut self,
            interest: Interest,
            callback: &mut dyn FnMut(&mut dyn AsyncDisplay, &mut Context< '_>) -> Result<()>,
            ctx: &mut Context< '_>,
        ) -> Poll<Result<()>> {
            self.poll_inner(ctx, |dpy, ctx| dpy.poll_for_interest(interest, callback, ctx))
        }
    }
}