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
use std::convert::{TryFrom, TryInto};

use crate::errors::ParseError;

/// Common information on events and errors.
///
/// This trait exists to share some code between `GenericEvent` and `GenericError`.
pub trait Event {
    /// Provide the raw data of the event as a slice.
    fn raw_bytes(&self) -> &[u8];

    /// The raw type of this response.
    ///
    /// Response types have seven bits in X11. The eight bit indicates whether this packet was
    /// generated through the `SendEvent` request.
    ///
    /// See also the `response_type()` and `server_generated()` methods which decompose this field
    /// into the contained information.
    fn raw_response_type(&self) -> u8 {
        self.raw_bytes()[0]
    }

    /// The type of this response.
    ///
    /// All errors have a response type of 0. Replies have a response type of 1, but you should
    /// never see their raw bytes in your code. Other response types are provided as constants in
    /// the generated code. Note that extensions have their response type dynamically assigned.
    fn response_type(&self) -> u8 {
        self.raw_response_type() & 0x7f
    }

    /// Was this packet generated by the server?
    ///
    /// If this function returns true, then this event comes from the X11 server. Otherwise, it was
    /// sent from another client via the `SendEvent` request.
    fn server_generated(&self) -> bool {
        self.raw_response_type() & 0x80 == 0
    }

    /// Get the sequence number of this packet.
    ///
    /// Not all packets contain a sequence number, so this function returns an `Option`.
    fn raw_sequence_number(&self) -> Option<u16> {
        use crate::generated::xproto::KEYMAP_NOTIFY_EVENT;
        match self.response_type() {
            KEYMAP_NOTIFY_EVENT => None,
            _ => {
                let bytes = self.raw_bytes();
                Some(u16::from_ne_bytes([bytes[2], bytes[3]]))
            }
        }
    }
}

/// A generic event.
///
/// Examine the event's `response_type()` and use `TryInto::try_into()` to convert the event to the
/// desired type.
#[derive(Debug, Clone)]
pub struct GenericEvent<B: AsRef<[u8]>>(B);

impl<B: AsRef<[u8]>> GenericEvent<B> {
    pub fn new(value: B) -> Result<Self, ParseError> {
        use super::generated::xproto::GE_GENERIC_EVENT;
        let value_slice = value.as_ref();
        if value_slice.len() < 32 {
            return Err(ParseError::ParseError);
        }
        let length_field = u32::from_ne_bytes([
            value_slice[4],
            value_slice[5],
            value_slice[6],
            value_slice[7],
        ]);
        let length_field: usize = length_field.try_into()?;
        let actual_length = value_slice.len();
        let event = GenericEvent(value);
        let expected_length = match event.response_type() {
            GE_GENERIC_EVENT | REPLY => 32 + 4 * length_field,
            _ => 32,
        };
        if actual_length != expected_length {
            return Err(ParseError::ParseError);
        }
        Ok(event)
    }

    pub fn into_buffer(self) -> B {
        self.0
    }
}

impl<B: AsRef<[u8]>> Event for GenericEvent<B> {
    fn raw_bytes(&self) -> &[u8] {
        self.0.as_ref()
    }
}

const REPLY: u8 = 1;

impl<B: AsRef<[u8]>> From<GenericError<B>> for GenericEvent<B> {
    fn from(value: GenericError<B>) -> Self {
        GenericEvent(value.into_buffer())
    }
}

/// A generic error.
///
/// This struct is similar to `GenericEvent`, but is specific to error packets. It allows access to
/// the contained error code. This error code allows you to pick the right error type for
/// conversion via `TryInto::try_into()`.
#[derive(Debug, Clone)]
pub struct GenericError<B: AsRef<[u8]>>(B);

impl<B: AsRef<[u8]>> GenericError<B> {
    pub fn new(value: B) -> Result<Self, ParseError> {
        GenericEvent::new(value)?.try_into()
    }

    pub fn into_buffer(self) -> B {
        self.0
    }

    /// Get the error code of this error.
    ///
    /// The error code identifies what kind of error this packet contains. Note that extensions
    /// have their error codes dynamically assigned.
    pub fn error_code(&self) -> u8 {
        self.raw_bytes()[1]
    }
}

impl<B: AsRef<[u8]>> Event for GenericError<B> {
    fn raw_bytes(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl<B: AsRef<[u8]>> TryFrom<GenericEvent<B>> for GenericError<B> {
    type Error = ParseError;

    fn try_from(event: GenericEvent<B>) -> Result<Self, Self::Error> {
        if event.response_type() != 0 {
            return Err(ParseError::ParseError);
        }
        Ok(GenericError(event.into_buffer()))
    }
}

/// A type implementing this trait can be parsed from some raw bytes.
pub trait TryParse: Sized {
    /// Try to parse the given values into an instance of this type.
    ///
    /// If parsing is successful, an instance of the type and a slice for the remaining data should
    /// be returned. Otherwise, an error is returned.
    fn try_parse(value: &[u8]) -> Result<(Self, &[u8]), ParseError>;
}

/// A type implementing this trait can be serialized into X11 raw bytes.
pub trait Serialize {
    /// The value returned by `serialize`.
    ///
    /// This should be `Vec<u8>` in most cases. However, arrays like `[u8; 4]` should also be
    /// allowed and thus this is an associated type.
    ///
    /// If generic associated types were available, implementing `AsRef<[u8]>` would be required.
    type Bytes;

    /// Serialize this value into X11 raw bytes.
    fn serialize(&self) -> Self::Bytes;

    /// Serialize this value into X11 raw bytes,
    /// appending the result into `bytes`.
    fn serialize_into(&self, bytes: &mut Vec<u8>);
}

// Now implement TryParse and Serialize for some primitive data types that we need.

macro_rules! implement_try_parse {
    ($t:ty) => {
        impl TryParse for $t {
            fn try_parse(value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
                let len = std::mem::size_of::<$t>();
                let bytes = value
                    .get(..len)
                    .ok_or(ParseError::ParseError)?
                    .try_into() // TryInto<[u8; len]>
                    .unwrap();
                Ok((<$t>::from_ne_bytes(bytes), &value[len..]))
            }
        }
    };
}

macro_rules! implement_serialize {
    ($t:ty: $size:expr) => {
        impl Serialize for $t {
            type Bytes = [u8; $size];
            fn serialize(&self) -> Self::Bytes {
                self.to_ne_bytes()
            }
            fn serialize_into(&self, bytes: &mut Vec<u8>) {
                bytes.extend_from_slice(&self.to_ne_bytes());
            }
        }
    };
}

macro_rules! forward_float {
    ($from:ty: $to:ty) => {
        impl TryParse for $from {
            fn try_parse(value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
                let (data, remaining) = <$to>::try_parse(value)?;
                Ok((<$from>::from_bits(data), remaining))
            }
        }
        impl Serialize for $from {
            type Bytes = <$to as Serialize>::Bytes;
            fn serialize(&self) -> Self::Bytes {
                self.to_bits().serialize()
            }
            fn serialize_into(&self, bytes: &mut Vec<u8>) {
                self.to_bits().serialize_into(bytes);
            }
        }
    };
}

implement_try_parse!(u8);
implement_try_parse!(i8);
implement_try_parse!(u16);
implement_try_parse!(i16);
implement_try_parse!(u32);
implement_try_parse!(i32);
implement_try_parse!(u64);
implement_try_parse!(i64);

implement_serialize!(u8: 1);
implement_serialize!(i8: 1);
implement_serialize!(u16: 2);
implement_serialize!(i16: 2);
implement_serialize!(u32: 4);
implement_serialize!(i32: 4);
implement_serialize!(u64: 8);
implement_serialize!(i64: 8);

forward_float!(f32: u32);
forward_float!(f64: u64);

impl TryParse for bool {
    fn try_parse(value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let (data, remaining) = u8::try_parse(value)?;
        Ok((data != 0, remaining))
    }
}

impl Serialize for bool {
    type Bytes = [u8; 1];
    fn serialize(&self) -> Self::Bytes {
        [u8::from(*self)]
    }
    fn serialize_into(&self, bytes: &mut Vec<u8>) {
        bytes.push(u8::from(*self));
    }
}

/// Parse a list of objects from the given data.
///
/// This function parses a list of objects where the length of the list was specified externally.
/// The wire format for `list_length` instances of `T` will be read from the given data.
pub fn parse_list<T>(data: &[u8], list_length: usize) -> Result<(Vec<T>, &[u8]), ParseError>
where
    T: TryParse,
{
    let mut remaining = data;
    let mut result = Vec::with_capacity(list_length);
    for _ in 0..list_length {
        let (entry, new_remaining) = T::try_parse(remaining)?;
        result.push(entry);
        remaining = new_remaining;
    }
    Ok((result, remaining))
}

impl<T: Serialize> Serialize for [T] {
    type Bytes = Vec<u8>;
    fn serialize(&self) -> Self::Bytes {
        let mut result = Vec::new();
        self.serialize_into(&mut result);
        result
    }
    fn serialize_into(&self, bytes: &mut Vec<u8>) {
        for item in self {
            item.serialize_into(bytes);
        }
    }
}

// This macro is used by the generated code to implement `std::ops::BitOr` and
// `std::ops::BitOrAssign`.
macro_rules! bitmask_binop {
    ($t:ty, $u:ty) => {
        impl std::ops::BitOr for $t {
            type Output = $u;
            fn bitor(self, other: Self) -> Self::Output {
                Into::<Self::Output>::into(self) | Into::<Self::Output>::into(other)
            }
        }
        impl std::ops::BitOr<$u> for $t {
            type Output = $u;
            fn bitor(self, other: $u) -> Self::Output {
                Into::<Self::Output>::into(self) | other
            }
        }
        impl std::ops::BitOr<$t> for $u {
            type Output = $u;
            fn bitor(self, other: $t) -> Self::Output {
                self | Into::<Self::Output>::into(other)
            }
        }
        impl std::ops::BitOrAssign<$t> for $u {
            fn bitor_assign(&mut self, other: $t) {
                *self |= Into::<Self>::into(other)
            }
        }
    };
}

/// A helper macro for managing atoms
///
/// If we need to use multiple atoms, one would normally write code such as
/// ```
/// # use x11rb::generated::xproto::{ATOM, ConnectionExt, InternAtomReply};
/// # use x11rb::errors::{ConnectionError, ReplyError};
/// # use x11rb::cookie::Cookie;
/// #[allow(non_snake_case)]
/// pub struct AtomCollection {
///     pub _NET_WM_NAME: ATOM,
///     pub _NET_WM_ICON: ATOM,
///     pub ATOM_WITH_SPACES: ATOM,
///     pub WHATEVER: ATOM,
/// }
///
/// #[allow(non_snake_case)]
/// struct AtomCollectionCookie<'c, C: ConnectionExt>
/// {
///     _NET_WM_NAME: Cookie<'c, C, InternAtomReply>,
///     _NET_WM_ICON: Cookie<'c, C, InternAtomReply>,
///     ATOM_WITH_SPACES: Cookie<'c, C, InternAtomReply>,
///     WHATEVER: Cookie<'c, C, InternAtomReply>,
/// }
///
/// impl AtomCollection {
///     pub fn new<C: ConnectionExt>(conn: &C) -> Result<AtomCollectionCookie<'_, C>, ConnectionError>
///     {
///         Ok(AtomCollectionCookie {
///             _NET_WM_NAME: conn.intern_atom(false, b"_NET_WM_NAME")?,
///             _NET_WM_ICON: conn.intern_atom(false, b"_NET_WM_ICON")?,
///             ATOM_WITH_SPACES: conn.intern_atom(false, b"ATOM WITH SPACES")?,
///             WHATEVER: conn.intern_atom(false, b"WHATEVER")?,
///         })
///     }
/// }
///
/// impl<'c, C> AtomCollectionCookie<'c, C>
/// where C: ConnectionExt
/// {
///     pub fn reply(self) -> Result<AtomCollection, ReplyError<C::Buf>> {
///         Ok(AtomCollection {
///             _NET_WM_NAME: self._NET_WM_NAME.reply()?.atom,
///             _NET_WM_ICON: self._NET_WM_ICON.reply()?.atom,
///             ATOM_WITH_SPACES: self.ATOM_WITH_SPACES.reply()?.atom,
///             WHATEVER: self.WHATEVER.reply()?.atom,
///         })
///     }
/// }
/// ```
/// This macro automatically produces this code with
/// ```
/// # use x11rb::atom_manager;
/// atom_manager! {
///     pub AtomCollection: AtomCollectionCookie {
///         _NET_WM_NAME,
///         _NET_WM_ICON,
///         ATOM_WITH_SPACES: b"ATOM WITH SPACES",
///         WHATEVER,
///     }
/// }
/// ```
#[macro_export]
macro_rules! atom_manager {
    {
        $vis:vis $struct_name:ident: $cookie_name:ident {
            $($field_name:ident$(: $atom_value:expr)?,)*
        }
    } => {
        // Cookie version
        #[allow(non_snake_case)]
        #[derive(Debug)]
        $vis struct $cookie_name<'a, C: $crate::generated::xproto::ConnectionExt> {
            $(
                $field_name: $crate::cookie::Cookie<'a, C, $crate::generated::xproto::InternAtomReply>,
            )*
        }

        // Replies
        #[allow(non_snake_case)]
        #[derive(Debug, Clone, Copy)]
        $vis struct $struct_name {
            $(
                $vis $field_name: $crate::generated::xproto::ATOM,
            )*
        }

        impl $struct_name {
            $vis fn new<C: $crate::generated::xproto::ConnectionExt>(
                conn: &C,
            ) -> ::std::result::Result<$cookie_name<'_, C>, $crate::errors::ConnectionError> {
                Ok($cookie_name {
                    $(
                        $field_name: conn.intern_atom(
                            false,
                            $crate::__atom_manager_atom_value!($field_name$(: $atom_value)?),
                        )?,
                    )*
                })
            }
        }

        impl<'a, C: $crate::generated::xproto::ConnectionExt> $cookie_name<'a, C> {
            $vis fn reply(self) -> ::std::result::Result<$struct_name, $crate::errors::ReplyError<C::Buf>> {
                Ok($struct_name {
                    $(
                        $field_name: self.$field_name.reply()?.atom,
                    )*
                })
            }
        }
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! __atom_manager_atom_value {
    ($field_name:ident) => {
        stringify!($field_name).as_bytes()
    };
    ($field_name:ident: $atom_value:expr) => {
        $atom_value
    };
}