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
//! Cookies are handles to future replies or errors from the X11 server.

use std::convert::{TryFrom, TryInto};
use std::marker::PhantomData;

use crate::connection::{BufWithFds, DiscardMode, RequestConnection, RequestKind, SequenceNumber};
use crate::errors::{ConnectionError, ParseError, ReplyError};
use crate::protocol::xproto::ListFontsWithInfoReply;
use crate::utils::RawFdContainer;

/// A handle to a possible error from the X11 server.
///
/// When sending a request for which no reply is expected, this library returns a `VoidCookie`.
/// This `VoidCookie` can then later be used to check if the X11 server sent an error.
#[derive(Debug)]
pub struct VoidCookie<'a, C>
where
    C: RequestConnection + ?Sized,
{
    connection: &'a C,
    sequence_number: SequenceNumber,
}

impl<'a, C> VoidCookie<'a, C>
where
    C: RequestConnection + ?Sized,
{
    /// Construct a new cookie.
    ///
    /// This function should only be used by implementations of
    /// `Connection::send_request_without_reply`.
    pub fn new(connection: &C, sequence_number: SequenceNumber) -> VoidCookie<'_, C> {
        VoidCookie {
            connection,
            sequence_number,
        }
    }

    /// Get the sequence number of the request that generated this cookie.
    pub fn sequence_number(&self) -> SequenceNumber {
        self.sequence_number
    }

    fn consume(self) -> (&'a C, SequenceNumber) {
        let result = (self.connection, self.sequence_number);
        std::mem::forget(self);
        result
    }

    /// Check if the original request caused an X11 error.
    pub fn check(self) -> Result<(), ReplyError> {
        let (connection, sequence) = self.consume();
        connection.check_for_error(sequence)
    }

    /// Ignore all errors to this request.
    ///
    /// Without calling this method, an error becomes available on the connection as an event after
    /// this cookie was dropped. This function causes errors to be ignored instead.
    pub fn ignore_error(self) {
        let (connection, sequence) = self.consume();
        connection.discard_reply(
            sequence,
            RequestKind::IsVoid,
            DiscardMode::DiscardReplyAndError,
        )
    }
}

impl<C> Drop for VoidCookie<'_, C>
where
    C: RequestConnection + ?Sized,
{
    fn drop(&mut self) {
        self.connection.discard_reply(
            self.sequence_number,
            RequestKind::IsVoid,
            DiscardMode::DiscardReply,
        )
    }
}

/// Internal helper for a cookie with an response
#[derive(Debug)]
struct RawCookie<'a, C>
where
    C: RequestConnection + ?Sized,
{
    connection: &'a C,
    sequence_number: SequenceNumber,
}

impl<C> RawCookie<'_, C>
where
    C: RequestConnection + ?Sized,
{
    /// Construct a new raw cookie.
    ///
    /// This function should only be used by implementations of
    /// `RequestConnection::send_request_with_reply`.
    fn new(connection: &C, sequence_number: SequenceNumber) -> RawCookie<'_, C> {
        RawCookie {
            connection,
            sequence_number,
        }
    }

    /// Consume this instance and get the contained sequence number out.
    fn into_sequence_number(self) -> SequenceNumber {
        let number = self.sequence_number;
        // Prevent drop() from running
        std::mem::forget(self);
        number
    }
}

impl<C> Drop for RawCookie<'_, C>
where
    C: RequestConnection + ?Sized,
{
    fn drop(&mut self) {
        self.connection.discard_reply(
            self.sequence_number,
            RequestKind::HasResponse,
            DiscardMode::DiscardReply,
        );
    }
}

/// A handle to a response from the X11 server.
///
/// When sending a request to the X11 server, this library returns a `Cookie`. This `Cookie` can
/// then later be used to get the response that the server sent.
#[derive(Debug)]
pub struct Cookie<'a, C, R>
where
    C: RequestConnection + ?Sized,
{
    raw_cookie: RawCookie<'a, C>,
    phantom: PhantomData<R>,
}

impl<C, R> Cookie<'_, C, R>
where
    R: for<'a> TryFrom<&'a [u8], Error = ParseError>,
    C: RequestConnection + ?Sized,
{
    /// Construct a new cookie.
    ///
    /// This function should only be used by implementations of
    /// `RequestConnection::send_request_with_reply`.
    pub fn new(connection: &C, sequence_number: SequenceNumber) -> Cookie<'_, C, R> {
        Cookie {
            raw_cookie: RawCookie::new(connection, sequence_number),
            phantom: PhantomData,
        }
    }

    /// Get the sequence number of the request that generated this cookie.
    pub fn sequence_number(&self) -> SequenceNumber {
        self.raw_cookie.sequence_number
    }

    /// Get the raw reply that the server sent.
    pub fn raw_reply(self) -> Result<C::Buf, ReplyError> {
        let conn = self.raw_cookie.connection;
        Ok(conn.wait_for_reply_or_error(self.raw_cookie.into_sequence_number())?)
    }

    /// Get the raw reply that the server sent, but have errors handled as events.
    pub fn raw_reply_unchecked(self) -> Result<Option<C::Buf>, ConnectionError> {
        let conn = self.raw_cookie.connection;
        Ok(conn.wait_for_reply(self.raw_cookie.into_sequence_number())?)
    }

    /// Get the reply that the server sent.
    pub fn reply(self) -> Result<R, ReplyError> {
        Ok(self.raw_reply()?.as_ref().try_into()?)
    }

    /// Get the reply that the server sent, but have errors handled as events.
    pub fn reply_unchecked(self) -> Result<Option<R>, ConnectionError> {
        self.raw_reply_unchecked()?
            .map(|buf| buf.as_ref().try_into())
            .transpose()
            .map_err(Into::into)
    }

    /// Discard all responses to the request this cookie represents, even errors.
    ///
    /// Without this function, errors are treated as events after the cookie is dropped.
    pub fn discard_reply_and_errors(self) {
        let conn = self.raw_cookie.connection;
        conn.discard_reply(
            self.raw_cookie.into_sequence_number(),
            RequestKind::HasResponse,
            DiscardMode::DiscardReplyAndError,
        )
    }

    /// Consume this instance and get the contained sequence number out.
    pub(crate) fn into_sequence_number(self) -> SequenceNumber {
        self.raw_cookie.into_sequence_number()
    }
}

/// A handle to a response containing `RawFd` from the X11 server.
///
/// When sending a request to the X11 server, this library returns a `Cookie`. This `Cookie` can
/// then later be used to get the response that the server sent.
///
/// This variant of `Cookie` represents a response that can contain `RawFd`s.
#[derive(Debug)]
pub struct CookieWithFds<'a, C, R>
where
    C: RequestConnection + ?Sized,
{
    raw_cookie: RawCookie<'a, C>,
    phantom: PhantomData<R>,
}

impl<C, R> CookieWithFds<'_, C, R>
where
    R: for<'a> TryFrom<(&'a [u8], Vec<RawFdContainer>), Error = ParseError>,
    C: RequestConnection + ?Sized,
{
    /// Construct a new cookie.
    ///
    /// This function should only be used by implementations of
    /// `RequestConnection::send_request_with_reply`.
    pub fn new(connection: &C, sequence_number: SequenceNumber) -> CookieWithFds<'_, C, R> {
        CookieWithFds {
            raw_cookie: RawCookie::new(connection, sequence_number),
            phantom: PhantomData,
        }
    }

    /// Get the sequence number of the request that generated this cookie.
    pub fn sequence_number(&self) -> SequenceNumber {
        self.raw_cookie.sequence_number
    }

    /// Get the raw reply that the server sent.
    pub fn raw_reply(self) -> Result<BufWithFds<C::Buf>, ReplyError> {
        let conn = self.raw_cookie.connection;
        Ok(conn.wait_for_reply_with_fds(self.raw_cookie.into_sequence_number())?)
    }

    /// Get the reply that the server sent.
    pub fn reply(self) -> Result<R, ReplyError> {
        let (buffer, fds) = self.raw_reply()?;
        Ok(R::try_from((buffer.as_ref(), fds))?)
    }
}

/// A handle to the replies to a `ListFontsWithInfo` request.
///
/// `ListFontsWithInfo` generated more than one reply, but `Cookie` only allows getting one reply.
/// This structure implements `Iterator` and allows to get all the replies.
#[derive(Debug)]
pub struct ListFontsWithInfoCookie<'a, C: RequestConnection + ?Sized>(Option<RawCookie<'a, C>>);

impl<C> ListFontsWithInfoCookie<'_, C>
where
    C: RequestConnection + ?Sized,
{
    pub(crate) fn new(
        cookie: Cookie<'_, C, ListFontsWithInfoReply>,
    ) -> ListFontsWithInfoCookie<'_, C> {
        ListFontsWithInfoCookie(Some(cookie.raw_cookie))
    }

    /// Get the sequence number of the request that generated this cookie.
    pub fn sequence_number(&self) -> Option<SequenceNumber> {
        self.0.as_ref().map(|x| x.sequence_number)
    }
}

impl<C> Iterator for ListFontsWithInfoCookie<'_, C>
where
    C: RequestConnection + ?Sized,
{
    type Item = Result<ListFontsWithInfoReply, ReplyError>;

    fn next(&mut self) -> Option<Self::Item> {
        let cookie = match self.0.take() {
            None => return None,
            Some(cookie) => cookie,
        };
        let reply = cookie
            .connection
            .wait_for_reply_or_error(cookie.sequence_number);
        let reply = match reply {
            Err(e) => return Some(Err(e)),
            Ok(v) => v,
        };
        let reply = ListFontsWithInfoReply::try_from(reply.as_ref()).map_err(ReplyError::from);
        match reply {
            // Is this an indicator that no more replies follow?
            Ok(ref reply) if reply.name.is_empty() => None,
            Ok(reply) => {
                self.0 = Some(cookie);
                Some(Ok(reply))
            }
            Err(e) => Some(Err(e)),
        }
    }
}