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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//               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)

//! Displays, used to connect to the X11 server.
//!
//! Communication with the X11 server takes place by sending or receiving
//! requests through the [`Display`] apparatus. These [`Display`]s, which
//! are usually some kind of state coupled with an I/O [`Connection`], are
//! responsible for sending and receiving the data, as well as serializing
//! and deserializing the requests and replies.
//!
//! ## Traits
//!
//! There are three primary traits in this module that define the behavior of
//! these apparati:
//!
//! - [`DisplayBase`] provides the basic functionality that either does not
//!   require I/O, or where blocking is not a consideration. This includes
//!   accessing the [`Setup`] and polling for replies or events.
//! - [`Display`] is a blocking interface that can be used to send requests,
//!   receive replies, and receive events.
//! - [`AsyncDisplay`] (requires the `async` feature) is a non-blocking
//!   version of [`Display`].
//!
//! Most user functionality is implemented in extension traits like
//! [`DisplayFunctionsExt`], and wraps around the methods defined in the
//! above traits.
//!
//! ## Implementations
//!
//! In addition, this module provides implementations of these traits that
//! wrap [`Connection`] implementations, written in pure Rust. All of these
//! types implement [`DisplayBase`] and [`Display`]. If wrapped in the
//! appropriate runtime primitives, they may also implement [`AsyncDisplay`].
//!
//! - [`BasicDisplay`] is the main implementation of [`Display`]. It is a
//!   reasonable default for most applications. The main downside is that it
//!   requires mutable (`&mut`) access.
//! - [`CellDisplay`] allows for concurrent access, but is not thread safe.
//! - [`SyncDisplay`] (requires the `sync_display` feature) allows for
//!   thread-safe concurrent access, but at a minor performance cost.
//!
//! [`Display`]: crate::display::Display
//! [`Connection`]: crate::connection::Connection
//! [`DisplayBase`]: crate::display::DisplayBase
//! [`Setup`]: crate::protocol::xproto::Setup
//! [`AsyncDisplay`]: crate::display::AsyncDisplay
//! [`DisplayFunctionsExt`]: crate::display::DisplayFunctionsExt
//! [`BasicDisplay`]: crate::display::BasicDisplay
//! [`CellDisplay`]: crate::display::CellDisplay
//! [`SyncDisplay`]: crate::display::SyncDisplay

/// `try!()`, but for `Result<AsyncStatus<_>>`.
#[doc(hidden)]
#[macro_export]
macro_rules! mtry {
    ($expr: expr) => {
        match ($expr)? {
            AsyncStatus::Ready(t) => t,
            status => return Ok(status.map(|_| unreachable!())),
        }
    };
}

mod basic;
pub use basic::BasicDisplay;
cfg_std! {
    pub use basic::DisplayConnection;
}

mod cell;
pub use cell::CellDisplay;

mod cookie;
pub use cookie::Cookie;

mod ext;
pub use ext::*;

mod extension_map;
pub(crate) use extension_map::ExtensionMap;

mod sans_io;
pub(crate) use sans_io::X11Core;

mod poison;
pub(crate) use poison::Poisonable;

mod prefetch;
pub(crate) use prefetch::Prefetch;

mod raw_request;
pub use raw_request::{
    from_reply_fds_request, from_reply_request, from_void_request, RawReply, RawRequest,
};

cfg_sync! {
    mod sync;
    pub use sync::SyncDisplay;
}

cfg_test! {
    //mod tests;
}

pub use crate::automatically_generated::DisplayFunctionsExt;
cfg_async! {
    pub use crate::automatically_generated::AsyncDisplayFunctionsExt;
    pub(crate) use raw_request::BufferedRequest;
    use core::task::{Context, Poll};
}

use crate::Result;
use alloc::{boxed::Box, sync::Arc};
use x11rb_protocol::protocol::{
    xproto::{GetInputFocusRequest, Screen, Setup},
    Event,
};

/// An interface to the X11 server, containing functionality that is neither
/// inherently synchronous nor asynchronous.
///
/// This trait is the supertrait for both [`Display`] and [`AsyncDisplay`].
/// It only contains functions for retrieving the setup information and
/// for polling the server in a non-blocking manner.
///
/// These functions should be used if, for instance, you want to fetch an
/// event, but if it is not available you need to do something else instead.
/// In addition, `Setup` information is useful for determining screen
/// parameters, among other things.
///
/// [`Display`]: crate::display::Display
/// [`AsyncDisplay`]: crate::display::AsyncDisplay
pub trait DisplayBase {
    /// Get the [`Setup`] associated with this display.
    ///
    /// The [`Setup`] contains a variety of information that is useful
    /// for determining aspects of the currently available environment.
    /// This includes screen size, the maximum length of a request,
    /// keycodes, and more.
    ///
    /// [`Setup`]: crate::protocol::xproto::Setup
    fn setup(&self) -> &Arc<Setup>;

    /// Get the screen associated with this display.
    ///
    /// At startup time, the default screen to use in the process is
    /// determined by the user. This is the index of that screen.
    fn default_screen_index(&self) -> usize;

    /// Poll to see if a reply matching the sequence number has been received.
    ///
    /// This checks the reply map to see if a reply has been received for the
    /// given sequence number. If it has, it returns the reply. Otherwise, it
    /// tries to fetch it from the server.
    ///
    /// # Blocking
    ///
    /// This function should never block. Non-blocking I/O should be used to
    /// fetch the reply, and `None` should be returned if the call would
    /// block.
    fn poll_for_reply_raw(&mut self, seq: u64) -> Result<Option<RawReply>>;

    /// Poll to see if we have received an event.
    ///
    /// This checks the event queue to see if an event has been received. If
    /// it has, it returns the event. Otherwise, it tries to fetch it from
    /// the server.
    ///
    /// # Blocking
    ///
    /// This function should never block. Non-blocking I/O should be used to
    /// fetch the event, and `None` should be returned if the call would
    /// block.
    fn poll_for_event(&mut self) -> Result<Option<Event>>;

    /* Helper methods */

    /// Get the screens for this display.
    ///
    /// This is equivalent to `self.setup().roots`, but is marginally
    /// more convenient.
    fn screens(&self) -> &[Screen] {
        &self.setup().roots
    }

    /// Get the default screen for this display.
    ///
    /// This is equivalent to `self.setup().roots[self.default_screen_index()]`.
    fn default_screen(&self) -> &Screen {
        self.screens()
            .get(self.default_screen_index())
            .unwrap_or_else(|| {
                panic!(
                    "Default screen index {} is not a valid screen",
                    self.default_screen_index()
                )
            })
    }
}

/// A blocking interface to the X11 server.
///
/// This interface can be used to do everything that [`DisplayBase`]
/// can do, but it is also capable of blocking on I/O. This allows it
/// to send requests, receive replies/events, among other things.
///
/// Objects of this type should never be put into non-blocking mode.
///
/// [`DisplayBase`]: crate::display::DisplayBase
pub trait Display: DisplayBase {
    /// Send a raw request to the X11 server.
    ///
    /// This function formats `req`, sends it to the server, and returns
    /// the sequence number associated with that request.
    ///
    /// # Blocking
    ///
    /// This function should block until the request has been sent to the
    /// server.
    fn send_request_raw(&mut self, req: RawRequest<'_, '_>) -> Result<u64>;

    /// Wait for a reply from the X11 server.
    ///
    /// This function waits for a reply to the given sequence number.
    ///
    /// Note that if the request has no reply, this function will likely
    /// hang forever.
    ///
    /// # Blocking
    ///
    /// This function should block until a reply is received from the
    /// server.
    fn wait_for_reply_raw(&mut self, seq: u64) -> Result<RawReply>;

    /// Wait for an event.
    ///
    /// This function waits for an event to be received from the server.
    ///
    /// # Blocking
    ///
    /// This function should block until an event is received from the
    /// server.
    fn wait_for_event(&mut self) -> Result<Event>;

    /// Get the maximum request length that can be sent.
    ///
    /// Returned in units of 4 bytes.
    ///
    /// # Blocking
    ///
    /// The server may be using the Big Requests extension, which allows
    /// for requests to be larger than the default maximum request length.
    /// If so, this function will block until the server has updated its
    /// maximum request length.
    fn maximum_request_length(&mut self) -> Result<usize>;

    /// Get a unique ID valid for use by the server.
    ///
    /// This function returns a unique ID that can be used by the server
    /// to identify the client's resources.
    ///
    /// # Blocking
    ///
    /// If the client has exhausted its XID range, this function will
    /// block until the server has repopulated it.
    fn generate_xid(&mut self) -> Result<u32>;

    /// Synchronize this display with the server.
    ///
    /// By default, this function sends and receives a low-cost
    /// request. This is useful for ensuring that the server has
    /// "caught up" with the client.
    fn synchronize(&mut self) -> Result<()> {
        let span = tracing::info_span!("synchronize");
        let _enter = span.enter();

        // send the sync request
        let get_input_focus = GetInputFocusRequest {};
        raw_request::from_reply_request(get_input_focus, |req| {
            let seq = self.send_request_raw(req)?;

            // flush the stream
            self.flush()?;

            // wait for the reply
            self.wait_for_reply_raw(seq).map(|_| ())
        })
    }

    /// Check for an error for the given sequence number.
    ///
    /// This is intended to be used for void requests. For all
    /// other requests, either an error will occur or the reply
    /// will be discarded.
    fn check_for_error(&mut self, seq: u64) -> Result<()>;

    /// Flush all pending requests to the server.
    ///
    /// # Blocking
    ///
    /// This function should block until all pending requests have been
    /// sent to the server.
    fn flush(&mut self) -> Result<()>;
}

/// The status of an async function.
///
/// An async function can either be ready, or be unready for a number of
/// reasons. This enum is used to represent the status of an async
/// function.
///
/// It can be thought of as similar to [`Poll`], but instead of returning
/// `Pending`, it returns the exact reason why it is pending.
///
/// [`Poll`]: std::task::Poll
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(not(feature = "async"), doc(hidden))]
pub enum AsyncStatus<T> {
    /// The function's result is ready.
    Ready(T),
    /// We are waiting for a read to be available.
    Read,
    /// We are waiting for a write to be available.
    Write,
    /// We are waiting for something else.
    ///
    /// The implementation is expected to wake the provided waker
    /// once the function is ready to be called again.
    UserControlled,
}

impl<T> AsyncStatus<T> {
    /// Returns `true` if the `AsyncStatus` is `Ready`.
    pub fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    /// Maps the `AsyncStatus` from one type to another, if the
    /// `AsyncStatus` is `Ready`.
    pub fn map<R>(self, f: impl FnOnce(T) -> R) -> AsyncStatus<R> {
        match self {
            Self::Ready(t) => AsyncStatus::Ready(f(t)),
            Self::Read => AsyncStatus::Read,
            Self::Write => AsyncStatus::Write,
            Self::UserControlled => AsyncStatus::UserControlled,
        }
    }

    /// Unwrap the `AsyncStatus`, returning the inner value or
    /// panicking otherwise.
    ///
    /// # Panics
    ///
    /// Panics if the `AsyncStatus` is not `Ready`.
    pub fn unwrap(self) -> T {
        match self {
            Self::Ready(t) => t,
            _ => panic!("unwrap() called on non-ready AsyncStatus"),
        }
    }

    /// Convert the `AsyncStatus` into an `Option`.
    pub fn ready(self) -> Option<T> {
        match self {
            Self::Ready(t) => Some(t),
            _ => None,
        }
    }
}

impl<T: Copy> AsyncStatus<&T> {
    /// Copy the reference in an `AsyncStatus` to a value.
    #[must_use]
    pub fn copied(self) -> AsyncStatus<T> {
        self.map(|&t| t)
    }
}

cfg_async! {
    /// The interest to poll the runtime for.
    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub enum Interest {
        /// We are waiting for the stream to be readable.
        Readable,
        /// We are waiting for the stream to be writable.
        Writable,
    }

    /// A display that *can* be async, if wrapped in an async runtime.
    ///
    /// This trait exposes functions similar to those in [`Display`], but
    /// instead of blocking and returning a value, they return an
    /// [`AsyncStatus`] if the value is available.
    ///
    /// Async runtime hooks should use this trait as the underlying object
    /// for [`AsyncDisplay`] implementations. Objects of this trait can't
    /// be used in the normal way, since an async runtime is needed to
    /// drive the I/O.
    ///
    /// [`Display`]: crate::display::Display
    /// [`AsyncDisplay`]: crate::display::AsyncDisplay
    /// [`AsyncStatus`]: crate::display::AsyncStatus
    pub trait CanBeAsyncDisplay: DisplayBase {
        /// Partially format the request.
        ///
        /// This method tries to format the request in such a way that
        /// it can be passed to [`try_send_request_raw`]. If additional
        /// information is needed to complete the request (e.g. extension
        /// info or bigreq), this method is allowed to return a non-ready
        /// status.
        ///
        /// This method returns the sequence number of the request, which
        /// can be used to wait for the reply.
        fn format_request(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<u64>>;

        /// Partially send the request.
        ///
        /// This function actually sends the request to the server. Note
        /// that the request has to be formatted using [`format_request`]
        /// before this method is called.
        ///
        /// # Cancel Safety
        ///
        /// This function does not have to be cancel safe. In fact, it is
        /// likely impossible to make this cancel safe, since sending a
        /// fragment of a request will corrupt the X11 server.
        fn try_send_request_raw(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<()>>;

        /// Wait for the reply.
        ///
        /// This function waits for the reply to the request with the
        /// given sequence number. If the reply is not yet available,
        /// this function returns a non-ready status.
        ///
        /// # Cancel Safety
        ///
        /// This function should be cancel safe. It should read into some
        /// kind of buffer, and then return a ready status if the buffer
        /// is completed.
        fn try_wait_for_reply_raw(
            &mut self,
            seq: u64,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<RawReply>>;

        /// Wait for an event.
        ///
        /// This function waits for an event to be available. If an event
        /// is not available, this function returns a non-ready status.
        ///
        /// # Cancel Safety
        ///
        /// This function should be cancel safe. It should read into some
        /// kind of buffer, and then return a ready status if the buffer
        /// is completed.
        fn try_wait_for_event(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<Event>>;

        /// Flush the output buffer.
        ///
        /// This function flushes the output buffer. If the output buffer
        /// cannot be emptied, this function returns a non-ready status.
        ///
        /// # Cancel Safety
        ///
        /// This function doesn't have to be cancel safe. It is likely
        /// impossible to make this cancel safe, since flushing the
        /// output buffer only partially will corrupt the X11 server.
        fn try_flush(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>>;

        /// Generate a unique XID.
        ///
        /// This function generates a unique XID. It may involve
        /// `try_send_request_raw`, so it has to be partial.
        ///
        /// # Cancel Safety
        ///
        /// This function doesn't have to be cancel safe.
        fn try_generate_xid(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<u32>>;

        /// Get the maximum length of a request that can be sent.
        ///
        /// This function returns the maximum length of a request that
        /// can be sent.
        ///
        /// # Cancel Safety
        ///
        /// This function doesn't have to be cancel safe.
        fn try_maximum_request_length(&mut self, ctx: &mut Context<'_>) -> Result<AsyncStatus<usize>>;

        /// Try to check for an error.
        fn try_check_for_error(&mut self, seq: u64, ctx: &mut Context<'_>) -> Result<AsyncStatus<()>>;
    }

    /// A non-blocking interface to the X11 server.
    ///
    /// This is an asynchronous version of the [`Display`] trait. It can
    /// do everything that a [`Display`] can do, but it doesn't
    /// block and return values. Instead, it returns a [`Future`] that can
    /// be used to wait for the result.
    ///
    /// [`Display`]: crate::display::Display
    /// [`Future`]: std::future::Future
    pub trait AsyncDisplay: CanBeAsyncDisplay {
        /// Poll for an interest. If the interest if ready, call
        /// the provided callback.
        ///
        /// This function is used to drive I/O. It should be called
        /// whenever the runtime is ready to wait on I/O, and should be
        /// implemented as follows:
        ///
        /// - Poll for the specific interest.
        /// - If the interest is ready, call the given callback.
        /// - Otherwise, return `Pending`.
        fn poll_for_interest(
            &mut self,
            interest: Interest,
            callback: &mut dyn FnMut(&mut dyn AsyncDisplay, &mut Context<'_>) -> Result<()>,
            ctx: &mut Context<'_>,
        ) -> Poll<Result<()>>;
    }
}

/* Mut impls */

impl<D: DisplayBase + ?Sized> DisplayBase for &mut D {
    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).poll_for_event()
    }

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

impl<D: Display + ?Sized> Display for &mut D {
    fn send_request_raw(&mut self, req: RawRequest<'_, '_>) -> Result<u64> {
        (**self).send_request_raw(req)
    }

    fn wait_for_event(&mut self) -> Result<Event> {
        (**self).wait_for_event()
    }

    fn wait_for_reply_raw(&mut self, seq: u64) -> Result<RawReply> {
        (**self).wait_for_reply_raw(seq)
    }

    fn flush(&mut self) -> Result<()> {
        (**self).flush()
    }

    fn synchronize(&mut self) -> Result<()> {
        (**self).synchronize()
    }

    fn generate_xid(&mut self) -> Result<u32> {
        (**self).generate_xid()
    }

    fn maximum_request_length(&mut self) -> Result<usize> {
        (**self).maximum_request_length()
    }

    fn check_for_error(&mut self, seq: u64) -> Result<()> {
        (**self).check_for_error(seq)
    }
}

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

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

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

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

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

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

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

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

    impl<D: AsyncDisplay + ?Sized> AsyncDisplay for &mut D {
        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_for_interest(interest, callback, ctx)
        }
    }
}

/* Box impls */

impl<D: DisplayBase + ?Sized> DisplayBase for Box<D> {
    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).poll_for_event()
    }

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

impl<D: Display + ?Sized> Display for Box<D> {
    fn send_request_raw(&mut self, req: RawRequest<'_, '_>) -> Result<u64> {
        (**self).send_request_raw(req)
    }

    fn maximum_request_length(&mut self) -> Result<usize> {
        (**self).maximum_request_length()
    }

    fn flush(&mut self) -> Result<()> {
        (**self).flush()
    }

    fn generate_xid(&mut self) -> Result<u32> {
        (**self).generate_xid()
    }

    fn synchronize(&mut self) -> Result<()> {
        (**self).synchronize()
    }

    fn wait_for_event(&mut self) -> Result<Event> {
        (**self).wait_for_event()
    }

    fn wait_for_reply_raw(&mut self, seq: u64) -> Result<RawReply> {
        (**self).wait_for_reply_raw(seq)
    }

    fn check_for_error(&mut self, seq: u64) -> Result<()> {
        (**self).check_for_error(seq)
    }
}

cfg_async! {
    impl<D: CanBeAsyncDisplay + ?Sized> CanBeAsyncDisplay for Box<D> {
        fn format_request(
            &mut self,
            req: &mut RawRequest<'_, '_>,
            ctx: &mut Context<'_>,
        ) -> Result<AsyncStatus<u64>> {
            (**self).format_request(req, ctx)
        }

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

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

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

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

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

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

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

    impl<D: AsyncDisplay + ?Sized> AsyncDisplay for Box<D> {
        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_for_interest(interest, callback, ctx)
        }
    }
}