Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 20:53:56 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions
+377
View File
@@ -0,0 +1,377 @@
//! Contains utilities for connection to the X11 server.
use crate::errors::{ConnectError, ParseError};
use crate::protocol::xproto::{Setup, SetupAuthenticate, SetupFailed, SetupRequest};
use crate::x11_utils::{Serialize, TryParse};
#[cfg(feature = "std")]
use crate::xauth::{get_auth, Family};
use alloc::{vec, vec::Vec};
use core::fmt;
/// The connection handshake used to connect to the X11 server.
///
/// In order to connect to the X11 server, the client must send the
/// server a request containing important pieces of client data. In
/// response, the server sends the client a response containing one
/// of the following:
///
/// - An error indicating that the setup request is malformed, or the
/// setup otherwise failed.
/// - A request for further authorization data.
/// - The [`Setup`](protocol/xproto/struct.Setup.html) for the connection,
/// which contains server-specific information and is necessary for
/// the client's ability to communicate with the server.
///
/// This handshake contains four relevant methods:
///
/// - `new`, which creates the handshake and also returns the setup request
/// to send to the server.
/// - `buffer`, which returns an `&mut [u8]` containing the buffer
/// which is intended to hold the bytes received from the server.
/// - `advance`, which takes a `usize` indicating how many bytes
/// were received from the server and advances the buffer.
/// - `into_setup`, which consumes this `Connect` and returns the
/// full `Setup`.
///
/// # Examples
///
/// Let's say you have an object `stream` which implements `Read`
/// and `Write`. In addition, you already have the connection family,
/// the address of the connection, and the display. You can use the `Connect`
/// to establish an X11 connection like so:
///
/// ```rust,no_run
/// # #[cfg(feature = "std")]
/// # {
/// # use x11rb_protocol::connect::Connect;
/// # use x11rb_protocol::xauth::Family;
/// # use std::{error::Error, io::prelude::*};
/// # fn main() -> Result<(), Box<dyn Error>> {
/// # struct Stream;
/// # impl Read for Stream {
/// # fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
/// # Ok(buf.len())
/// # }
/// # }
/// # impl Write for Stream {
/// # fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
/// # Ok(buf.len())
/// # }
/// # fn flush(&mut self) -> std::io::Result<()> {
/// # Ok(())
/// # }
/// # }
/// # let mut stream = Stream;
/// let family = Family::INTERNET;
/// let address = b"foobar";
/// let display = 0;
///
/// let (mut connect, setup_request) = Connect::new(family, address, display)?;
///
/// // send the setup request to the server
/// stream.write_all(&setup_request)?;
///
/// // receive the setup response from the server
/// loop {
/// let adv = stream.read(connect.buffer())?;
///
/// // if we've completed the setup, break out of the loop
/// if connect.advance(adv) {
/// break;
/// }
/// }
///
/// // get the setup used for our connection
/// let setup = connect.into_setup()?;
/// # Ok(())
/// # }
/// # }
/// ```
///
/// If, instead, `stream` implements `AsyncRead` and `AsyncWrite`, the code
/// would be identical, but with `.await` after `read` and `write_all`.
pub struct Connect {
// input buffer
buffer: Vec<u8>,
// position in the buffer that has been filled
advanced: usize,
}
const INITIAL_CAPACITY: usize = 8;
// X11 interprets capital B as big endian, and lowercase l as little endian.
#[cfg(target_endian = "little")]
const BYTE_ORDER: u8 = b'l';
#[cfg(not(target_endian = "little"))]
const BYTE_ORDER: u8 = b'B';
// protocol version
const PROTOCOL_MAJOR_VERSION: u16 = 11;
const PROTOCOL_MINOR_VERSION: u16 = 0;
impl Connect {
/// The initial state of a `Connect`.
fn blank() -> Self {
Self {
buffer: vec![0; INITIAL_CAPACITY],
advanced: 0,
}
}
/// Create a new `Connect` from the given authorization data.
///
/// This uses the provided protocol name and data to establish the connection,
/// rather than the default protocol name and data found in `Xauthority`.
///
/// # Example
///
/// ```rust
/// # use x11rb_protocol::connect::Connect;
///
/// let (connect, setup_request) = Connect::with_authorization(
/// b"MIT-MAGIC-COOKIE-1".to_vec(),
/// b"my_secret_password".to_vec(),
/// );
/// ```
pub fn with_authorization(protocol_name: Vec<u8>, protocol_data: Vec<u8>) -> (Self, Vec<u8>) {
// craft the setup request
let sr = SetupRequest {
byte_order: BYTE_ORDER,
protocol_major_version: PROTOCOL_MAJOR_VERSION,
protocol_minor_version: PROTOCOL_MINOR_VERSION,
authorization_protocol_name: protocol_name,
authorization_protocol_data: protocol_data,
};
// return it
(Self::blank(), sr.serialize())
}
/// Create a new `Connect` from the information necessary to connect to the X11 server.
///
/// This returns the connection handshake object as well as the setup request to send to the server.
#[cfg(feature = "std")]
pub fn new(
family: Family,
address: &[u8],
display: u16,
) -> Result<(Self, Vec<u8>), ConnectError> {
match get_auth(family, address, display)? {
Some((name, data)) => Ok(Self::with_authorization(name, data)),
None => {
// fall through to no authorization
Ok(Self::with_authorization(Vec::new(), Vec::new()))
}
}
}
/// Returns the buffer that needs to be filled with incoming data from the server.
///
/// After filling this buffer (using a method like `Read::read`), call [`Self::advance`] with
/// the number of bytes read to indicate that the buffer has been filled.
pub fn buffer(&mut self) -> &mut [u8] {
&mut self.buffer[self.advanced..]
}
/// Advance the internal buffer, given the number of bytes that have been read.
pub fn advance(&mut self, bytes: usize) -> bool {
self.advanced += bytes;
debug_assert!(self.buffer.len() >= self.advanced);
// if we've read up to the initial capacity, tell how many more bytes
// we need to read
if self.advanced == INITIAL_CAPACITY {
// remaining length is at byte range 6-7 in 4-bytes
let length = u16::from_ne_bytes([self.buffer[6], self.buffer[7]]);
let length = length as usize * 4;
// allocate more room
// use reserve_exact because this will be the final
// length of the vector
self.buffer.reserve_exact(length);
self.buffer.resize(length + self.buffer.len(), 0);
false
} else {
self.advanced == self.buffer.len()
}
}
/// Returns the setup provided by the server.
///
/// # Errors
///
/// - If this method is called before the server returns all of the required data,
/// it returns `ConnectError::NotEnoughData`.
/// - If the server fails to establish the X11 connection, the `ConnectError::SetupFailed`
/// variant is returned.
/// - If the server failed to authenticate the user, the `ConnectError::SetupAuthenticate`
/// error is returned.
/// - If the server failed to parse any of the above responses, the
/// `ConnectError::ParseError` error is returned.
pub fn into_setup(self) -> Result<Setup, ConnectError> {
// if we aren't full yet, panic
if self.advanced != self.buffer.len() {
return Err(ConnectError::Incomplete {
expected: self.buffer.len(),
received: self.advanced,
});
}
// parse the setup response
match self.buffer[0] {
0 => {
// an error has occurred
let (failed, _) = SetupFailed::try_parse(&self.buffer)?;
Err(ConnectError::SetupFailed(failed))
}
1 => {
// the setup is valid!
let (success, _) = Setup::try_parse(&self.buffer)?;
Ok(success)
}
2 => {
// we need further authentication
let (more_auth, _) = SetupAuthenticate::try_parse(&self.buffer)?;
Err(ConnectError::SetupAuthenticate(more_auth))
}
_ => {
// this is undefined
Err(ParseError::InvalidValue.into())
}
}
}
}
impl fmt::Debug for Connect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connect")
.field(
"buffer",
&format_args!("{}/{}", self.advanced, self.buffer.len()),
)
.finish()
}
}
impl TryFrom<Connect> for Setup {
type Error = ConnectError;
fn try_from(connect: Connect) -> Result<Self, Self::Error> {
connect.into_setup()
}
}
#[cfg(test)]
#[cfg(all(feature = "extra-traits", feature = "std"))]
mod tests {
use super::Connect;
use crate::errors::ConnectError;
use crate::protocol::xproto::{ImageOrder, Setup, SetupAuthenticate, SetupFailed};
use crate::x11_utils::Serialize;
use alloc::vec;
fn test_setup() -> Setup {
let mut s = Setup {
status: 1,
protocol_major_version: 11,
protocol_minor_version: 0,
length: 0,
release_number: 0,
resource_id_base: 1,
resource_id_mask: 1,
motion_buffer_size: 0,
maximum_request_length: 0,
image_byte_order: ImageOrder::LSB_FIRST,
bitmap_format_bit_order: ImageOrder::LSB_FIRST,
bitmap_format_scanline_unit: 32,
bitmap_format_scanline_pad: 32,
min_keycode: 0,
max_keycode: 0,
vendor: b"Testing Setup".to_vec(),
pixmap_formats: vec![],
roots: vec![],
};
// +3 so it rounds up
s.length = ((s.serialize().len() - 8 + 3) / 4) as u16;
s
}
fn try_receive_bytes(item: &impl Serialize) -> Result<Setup, ConnectError> {
let mut connect = Connect::blank();
// feed in a setup
let mut item_bytes = vec![];
item.serialize_into(&mut item_bytes);
let mut i = 0;
loop {
i += 1;
if i > 500 {
panic!("too many iterations");
}
// copy bytes to connect
let buffer = connect.buffer();
let bytes_to_copy = std::cmp::min(item_bytes.len(), buffer.len());
buffer[..bytes_to_copy].copy_from_slice(&item_bytes[..bytes_to_copy]);
// drain the bytes that we've already copied
drop(item_bytes.drain(..bytes_to_copy));
// check advance
if connect.advance(bytes_to_copy) {
break;
}
}
connect.into_setup()
}
#[test]
fn test_connect_receive_setup() {
let setup = test_setup();
let b = try_receive_bytes(&setup);
match b {
Ok(s) => assert_eq!(s, setup),
Err(e) => panic!("{:?}", e),
}
}
#[test]
fn test_connect_receive_setup_authenticate() {
let setup = SetupAuthenticate {
status: 2,
reason: b"Needs more auth.".to_vec(),
};
let b = try_receive_bytes(&setup);
match b {
Ok(s) => panic!("{:?}", s),
Err(ConnectError::SetupAuthenticate(e)) => assert_eq!(e, setup),
Err(e) => panic!("{:?}", e),
}
}
#[test]
fn test_connect_receive_setup_failed() {
let mut setup = SetupFailed {
status: 0,
protocol_major_version: 11,
protocol_minor_version: 0,
length: 0,
reason: b"whatever".to_vec(),
};
setup.length = ((setup.serialize().len() - 8) / 4) as _;
let b = try_receive_bytes(&setup);
match b {
Ok(s) => panic!("{:?}", s),
Err(ConnectError::SetupFailed(e)) => assert_eq!(e, setup),
Err(e) => panic!("{:?}", e),
}
}
}
+444
View File
@@ -0,0 +1,444 @@
//! Helper types for implementing an X11 client.
use alloc::collections::VecDeque;
use alloc::vec::Vec;
use crate::utils::RawFdContainer;
use crate::{DiscardMode, SequenceNumber};
/// A combination of a buffer and a list of file descriptors.
pub type BufWithFds = crate::BufWithFds<Vec<u8>>;
/// The raw bytes of an X11 event and its sequence number.
pub type RawEventAndSeqNumber = crate::RawEventAndSeqNumber<Vec<u8>>;
/// Information about the reply to an X11 request.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ReplyFdKind {
/// The request does not have a reply.
NoReply,
/// The request has a reply and that reply does *not* contain any file descriptors.
ReplyWithoutFDs,
/// The request has a reply and that reply *does* contain file descriptor(s).
ReplyWithFDs,
}
/// Information about the result of polling for a reply packet.
#[derive(Debug, Clone)]
pub enum PollReply {
/// It is not clear yet what the result will be; try again later.
TryAgain,
/// There will be no reply; polling is done.
NoReply,
/// Here is the result of the polling; polling is done.
Reply(Vec<u8>),
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct SentRequest {
seqno: SequenceNumber,
discard_mode: Option<DiscardMode>,
has_fds: bool,
}
/// A pure-rust, sans-I/O implementation of the X11 protocol.
///
/// This object is designed to be used in combination with an I/O backend, in
/// order to keep state for the X11 protocol.
#[derive(Debug)]
pub struct Connection {
// The sequence number of the last request that was written
last_sequence_written: SequenceNumber,
// Sorted(!) list with information on requests that were written, but no answer received yet.
sent_requests: VecDeque<SentRequest>,
// The sequence number of the next reply that is expected to come in
next_reply_expected: SequenceNumber,
// The sequence number of the last reply/error/event that was read
last_sequence_read: SequenceNumber,
// Events that were read, but not yet returned to the API user
pending_events: VecDeque<(SequenceNumber, Vec<u8>)>,
// Replies that were read, but not yet returned to the API user
pending_replies: VecDeque<(SequenceNumber, BufWithFds)>,
// FDs that were read, but not yet assigned to any reply
pending_fds: VecDeque<RawFdContainer>,
}
impl Default for Connection {
fn default() -> Self {
Self::new()
}
}
impl Connection {
/// Create a new `Connection`.
///
/// It is assumed that the connection was just established. This means that the next request
/// that is sent will have sequence number one.
pub fn new() -> Self {
Connection {
last_sequence_written: 0,
next_reply_expected: 0,
last_sequence_read: 0,
sent_requests: VecDeque::new(),
pending_events: VecDeque::new(),
pending_replies: VecDeque::new(),
pending_fds: VecDeque::new(),
}
}
/// Send a request to the X11 server.
///
/// When this returns `None`, a sync with the server is necessary. Afterwards, the caller
/// should try again.
pub fn send_request(&mut self, kind: ReplyFdKind) -> Option<SequenceNumber> {
let has_response = match kind {
ReplyFdKind::NoReply => false,
ReplyFdKind::ReplyWithoutFDs => true,
ReplyFdKind::ReplyWithFDs => true,
};
if self.next_reply_expected + SequenceNumber::from(u16::MAX) - 1
<= self.last_sequence_written
&& !has_response
{
// The caller need to call send_sync(). Otherwise, we might not be able to reconstruct
// full sequence numbers for received packets.
return None;
}
self.last_sequence_written += 1;
let seqno = self.last_sequence_written;
if has_response {
self.next_reply_expected = self.last_sequence_written;
}
let sent_request = SentRequest {
seqno,
discard_mode: None,
has_fds: kind == ReplyFdKind::ReplyWithFDs,
};
self.sent_requests.push_back(sent_request);
Some(seqno)
}
/// Ignore the reply for a request that was previously sent.
pub fn discard_reply(&mut self, seqno: SequenceNumber, mode: DiscardMode) {
if let Ok(index) = self.sent_requests.binary_search_by_key(&seqno, |r| r.seqno) {
self.sent_requests[index].discard_mode = Some(mode);
}
match mode {
DiscardMode::DiscardReplyAndError => self.pending_replies.retain(|r| r.0 != seqno),
DiscardMode::DiscardReply => {
if let Some(index) = self.pending_replies.iter().position(|r| r.0 == seqno) {
while self
.pending_replies
.get(index)
.filter(|r| r.0 == seqno)
.is_some()
{
if let Some((_, packet)) = self.pending_replies.remove(index) {
if packet.0[0] == 0 {
// This is an error
self.pending_events.push_back((seqno, packet.0));
}
}
}
}
}
}
}
// Extract the sequence number from a packet read from the X11 server. The packet must be a
// reply, an event, or an error. All of these have a u16 sequence number in bytes 2 and 3...
// except for KeymapNotify events.
fn extract_sequence_number(&mut self, buffer: &[u8]) -> Option<SequenceNumber> {
use crate::protocol::xproto::KEYMAP_NOTIFY_EVENT;
if buffer[0] == KEYMAP_NOTIFY_EVENT {
return None;
}
// We get the u16 from the wire...
let number = u16::from_ne_bytes([buffer[2], buffer[3]]);
// ...and use our state to reconstruct the high bytes
let high_bytes = self.last_sequence_read & !SequenceNumber::from(u16::MAX);
let mut full_number = SequenceNumber::from(number) | high_bytes;
if full_number < self.last_sequence_read {
full_number += SequenceNumber::from(u16::MAX) + 1;
}
// Update our state
self.last_sequence_read = full_number;
if self.next_reply_expected < full_number {
// This is most likely an event/error that allows us to update our sequence number
// implicitly. Normally, only requests with a reply update this (in send_request()).
self.next_reply_expected = full_number;
}
Some(full_number)
}
/// Add FDs that were received to the internal state.
///
/// This must be called before the corresponding packets are enqueued.
pub fn enqueue_fds(&mut self, fds: Vec<RawFdContainer>) {
self.pending_fds.extend(fds);
}
/// An X11 packet was received from the connection and is now enqueued into our state.
///
/// Any FDs that were received must already be enqueued before this can be called.
pub fn enqueue_packet(&mut self, packet: Vec<u8>) {
let kind = packet[0];
// extract_sequence_number() updates our state and is thus important to call even when we
// do not need the sequence number
let seqno = self
.extract_sequence_number(&packet)
.unwrap_or(self.last_sequence_read);
// Remove all entries for older requests
while let Some(request) = self.sent_requests.front() {
if request.seqno >= seqno {
break;
}
let _ = self.sent_requests.pop_front();
}
let request = self.sent_requests.front().filter(|r| r.seqno == seqno);
if kind == 0 {
// It is an error. Let's see where we have to send it to.
if let Some(request) = request {
match request.discard_mode {
Some(DiscardMode::DiscardReplyAndError) => { /* This error should be ignored */
}
Some(DiscardMode::DiscardReply) => {
self.pending_events.push_back((seqno, packet))
}
None => self
.pending_replies
.push_back((seqno, (packet, Vec::new()))),
}
} else {
// Unexpected error, send to main loop
self.pending_events.push_back((seqno, packet));
}
} else if kind == 1 {
let fds = if request.filter(|r| r.has_fds).is_some() {
// This reply has FDs, the number of FDs is always in the second byte
let num_fds = usize::from(packet[1]);
// FIXME Turn this into some kind of "permanent error state" (so that
// everything fails with said error) instead of using a panic (this panic will
// likely poison some Mutex and produce an error state that way).
assert!(
num_fds <= self.pending_fds.len(),
"FIXME: The server sent us too few FDs. The connection is now unusable \
since we will never be sure again which FD belongs to which reply."
);
self.pending_fds.drain(..num_fds).collect()
} else {
Vec::new()
};
// It is a reply
if request.filter(|r| r.discard_mode.is_some()).is_some() {
// This reply should be discarded
} else {
self.pending_replies.push_back((seqno, (packet, fds)));
}
} else {
// It is an event
self.pending_events.push_back((seqno, packet));
}
}
/// Check if the server already sent an answer to the request with the given sequence number.
///
/// This function is meant to be used for requests that have a reply. Such requests always
/// cause a reply or an error to be sent.
pub fn poll_for_reply_or_error(&mut self, sequence: SequenceNumber) -> Option<BufWithFds> {
for (index, (seqno, _packet)) in self.pending_replies.iter().enumerate() {
if *seqno == sequence {
return Some(self.pending_replies.remove(index).unwrap().1);
}
}
None
}
/// Prepare for calling `poll_check_for_reply_or_error()`.
///
/// To check if a request with a reply caused an error, one simply has to wait for the error or
/// reply to be received. However, this approach does not work for requests without errors:
/// Success is indicated by the absence of an error.
///
/// Thus, this function returns true if a sync is necessary to ensure that a reply with a
/// higher sequence number will be received. Since the X11 server handles requests in-order,
/// if the reply to a later request is received, this means that the earlier request did not
/// fail.
pub fn prepare_check_for_reply_or_error(&mut self, sequence: SequenceNumber) -> bool {
self.next_reply_expected < sequence
}
/// Check if the request with the given sequence number was already handled by the server.
///
/// Before calling this function, you must call `prepare_check_for_reply_or_error()` with the
/// sequence number.
///
/// This function can be used for requests with and without a reply.
pub fn poll_check_for_reply_or_error(&mut self, sequence: SequenceNumber) -> PollReply {
if let Some(result) = self.poll_for_reply_or_error(sequence) {
return PollReply::Reply(result.0);
}
if self.last_sequence_read > sequence {
// We can be sure that there will be no reply/error
PollReply::NoReply
} else {
// Hm, we cannot be sure yet. Perhaps there will still be a reply/error
PollReply::TryAgain
}
}
/// Find the reply for the request with the given sequence number.
///
/// If the request caused an error, that error will be handled as an event. This means that a
/// latter call to `poll_for_event()` will return it.
pub fn poll_for_reply(&mut self, sequence: SequenceNumber) -> PollReply {
if let Some(reply) = self.poll_for_reply_or_error(sequence) {
if reply.0[0] == 0 {
self.pending_events.push_back((sequence, reply.0));
PollReply::NoReply
} else {
PollReply::Reply(reply.0)
}
} else {
PollReply::TryAgain
}
}
/// Get a pending event.
pub fn poll_for_event_with_sequence(&mut self) -> Option<RawEventAndSeqNumber> {
self.pending_events
.pop_front()
.map(|(seqno, event)| (event, seqno))
}
}
#[cfg(test)]
mod test {
use super::{Connection, ReplyFdKind};
#[test]
fn insert_sync_no_reply() {
// The connection must send a sync (GetInputFocus) request every 2^16-1 requests (that do not
// have a reply). Thus, this test sends more than that and tests for the sync to appear.
let mut connection = Connection::new();
for num in 1..0xffff {
let seqno = connection.send_request(ReplyFdKind::NoReply);
assert_eq!(Some(num), seqno);
}
// request 0xffff should be a sync, hence the next one is 0x10000
let seqno = connection.send_request(ReplyFdKind::NoReply);
assert_eq!(None, seqno);
let seqno = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
assert_eq!(Some(0xffff), seqno);
let seqno = connection.send_request(ReplyFdKind::NoReply);
assert_eq!(Some(0x10000), seqno);
}
#[test]
fn insert_no_sync_with_reply() {
// Compared to the previous test, this uses ReplyFdKind::ReplyWithoutFDs, so no sync needs to
// be inserted.
let mut connection = Connection::new();
for num in 1..=0x10001 {
let seqno = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
assert_eq!(Some(num), seqno);
}
}
#[test]
fn insert_no_sync_when_already_syncing() {
// This test sends enough ReplyFdKind::NoReply requests that a sync becomes necessary on
// the next request. Then it sends a ReplyFdKind::ReplyWithoutFDs request so that no sync is
// necessary. This is a regression test: Once upon a time, an unnecessary sync was done.
let mut connection = Connection::new();
for num in 1..0xffff {
let seqno = connection.send_request(ReplyFdKind::NoReply);
assert_eq!(Some(num), seqno);
}
let seqno = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
assert_eq!(Some(0xffff), seqno);
}
#[test]
fn get_sync_replies() {
// This sends requests with a reply with seqno 1 and 1+2^16 and then checks that their
// replies are correctly mapped to the requests.
let mut connection = Connection::new();
let first_reply = 1;
let second_reply = 0x10001;
// First, send all the requests
// First request is one with a reply
let seqno = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
assert_eq!(Some(first_reply), seqno);
// Then, there should be enough requests so that the next request will end up with sequence
// number 'second_reply'
for num in (first_reply + 1)..(second_reply - 1) {
let seqno = connection.send_request(ReplyFdKind::NoReply);
assert_eq!(Some(num), seqno);
}
// Send one more request. This needs to be a sync request so that sequence numbers can be
// reconstructed correctly. The bug that we testing was that no sync was required, so this
// test handles both cases correctly.
let requested_extra_sync = connection.send_request(ReplyFdKind::NoReply).is_none();
if requested_extra_sync {
let _ = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
}
let seqno = connection.send_request(ReplyFdKind::ReplyWithoutFDs);
assert_eq!(Some(second_reply), seqno);
// Prepare a reply packet
let mut packet = [0; 32];
// It is a reply
packet[0] = 1;
// Set the sequence number to 1
packet[2..4].copy_from_slice(&1u16.to_ne_bytes());
// Enqueue the first reply.
connection.enqueue_packet(packet.to_vec());
// Send an extra reply if the code wanted one. This extra reply allows to detect that all
// replies to the first request were received (remember, there can be multiple replies to a
// single request!)
if requested_extra_sync {
packet[2..4].copy_from_slice(&((second_reply - 1) as u16).to_ne_bytes());
connection.enqueue_packet(packet.to_vec());
}
// Set the sequence number for the second reply
packet[2..4].copy_from_slice(&(second_reply as u16).to_ne_bytes());
connection.enqueue_packet(packet.to_vec());
// Now check that the sequence number for the last packet was reconstructed correctly.
assert!(connection.poll_for_reply_or_error(second_reply).is_some());
}
}
+226
View File
@@ -0,0 +1,226 @@
//! This module contains the current mess that is error handling.
use crate::protocol::xproto::{SetupAuthenticate, SetupFailed};
pub use crate::id_allocator::IdsExhausted;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
/// An error occurred while parsing some data
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseError {
/// Not enough data was provided.
InsufficientData,
/// A value did not fit.
///
/// This error can e.g. happen when a value that was received from the X11 server does not fit
/// into an `usize`.
ConversionFailed,
/// The value of an expression could not be computed.
///
/// As an example, the length of the data in `xproto`'s `GetPropertyReply` is described by
/// `value_len * (format / 8)`. The multiplication could cause an overflow, which would be
/// represented by this error.
InvalidExpression,
/// A value was outside of its valid range.
///
/// There are two kinds of situations where this error can happen:
///
/// 1. The protocol was violated and a nonsensical value was found.
/// 2. The user of the API called the wrong parsing function.
///
/// Examples for the first kind of error:
///
/// - One of a set of values should be present (a `<switch>` in xcb-proto-speak), but none of
/// the `<cases>` matched. This can e.g. happen when parsing
/// [`crate::protocol::xinput::InputInfo`].
/// - Parsing a request with a length field that is too small for the request header to fit.
///
/// Examples for the second kind of error:
///
/// - Parsing an X11 error with `response_type != 0`.
/// - Parsing an X11 reply with `response_type != 1`.
/// - Parsing an X11 request with the wrong value for its `minor_opcode`.
InvalidValue,
/// Some file descriptors were expected, but not enough were received.
MissingFileDescriptors,
}
#[cfg(feature = "std")]
impl Error for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::InsufficientData => write!(f, "Insufficient data was provided"),
ParseError::ConversionFailed => {
write!(f, "A value conversion failed due to out of range data")
}
ParseError::InvalidExpression => write!(
f,
"An expression could not be computed, e.g. due to overflow"
),
ParseError::InvalidValue => {
write!(f, "A value could not be parsed into an enumeration")
}
ParseError::MissingFileDescriptors => write!(f, "Missing file descriptors"),
}
}
}
/// An error that occurred while parsing the `$DISPLAY` environment variable
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DisplayParsingError {
/// No explicit display was provided and the `$DISPLAY` environment variable is not set.
DisplayNotSet,
/// The given value could not be parsed. The input to parsing is provided.
MalformedValue(alloc::boxed::Box<str>),
/// The value of `$DISPLAY` is not valid unicode
NotUnicode,
/// An unknown error occurred during display parsing.
///
/// This is `XCB_CONN_CLOSED_PARSE_ERR`.
Unknown,
}
#[cfg(feature = "std")]
impl Error for DisplayParsingError {}
impl fmt::Display for DisplayParsingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DisplayParsingError::DisplayNotSet => {
write!(
f,
"$DISPLAY variable not set and no value was provided explicitly"
)
}
DisplayParsingError::MalformedValue(dpy) => {
write!(f, "Failed to parse value '{dpy}'")
}
DisplayParsingError::NotUnicode => {
write!(f, "The value of $DISPLAY is not valid unicode")
}
DisplayParsingError::Unknown => {
write!(f, "Unknown error while parsing a $DISPLAY address")
}
}
}
}
/// An error that occurred while connecting to an X11 server
#[derive(Debug)]
#[non_exhaustive]
pub enum ConnectError {
/// An unknown error occurred.
///
/// One situation were this error is used when libxcb indicates an error that does not match
/// any of the defined error conditions. Thus, libxcb is violating its own API (or new error
/// cases were defined, but are not yet handled by x11rb).
UnknownError,
/// Error while parsing some data, see `ParseError`.
ParseError(ParseError),
/// Out of memory.
///
/// This is `XCB_CONN_CLOSED_MEM_INSUFFICIENT`.
InsufficientMemory,
/// Error during parsing of display string.
///
/// This is `XCB_CONN_CLOSED_PARSE_ERR`.
DisplayParsingError(DisplayParsingError),
/// Server does not have a screen matching the display.
///
/// This is `XCB_CONN_CLOSED_INVALID_SCREEN`.
InvalidScreen,
/// An I/O error occurred on the connection.
#[cfg(feature = "std")]
IoError(std::io::Error),
/// Invalid ID mask provided by the server.
///
/// The value of `resource_id_mask` in the `Setup` provided by the server was zero.
ZeroIdMask,
/// The server rejected the connection with a `SetupAuthenticate` message.
SetupAuthenticate(SetupAuthenticate),
/// The server rejected the connection with a `SetupFailed` message.
SetupFailed(SetupFailed),
/// The client did not receive enough data from the server to complete
/// the handshake.
Incomplete {
/// The number of bytes that were expected.
expected: usize,
/// The number of bytes that were received.
received: usize,
},
}
#[cfg(feature = "std")]
impl Error for ConnectError {}
impl fmt::Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn display(f: &mut fmt::Formatter<'_>, prefix: &str, value: &[u8]) -> fmt::Result {
match core::str::from_utf8(value).ok() {
Some(value) => write!(f, "{prefix}: '{value}'"),
None => write!(f, "{prefix}: {value:?} [message is not utf8]"),
}
}
match self {
ConnectError::UnknownError => write!(f, "Unknown connection error"),
ConnectError::InsufficientMemory => write!(f, "Insufficient memory"),
ConnectError::DisplayParsingError(err) => err.fmt(f),
ConnectError::InvalidScreen => write!(f, "Invalid screen"),
ConnectError::ParseError(err) => err.fmt(f),
#[cfg(feature = "std")]
ConnectError::IoError(err) => err.fmt(f),
ConnectError::ZeroIdMask => write!(f, "XID mask was zero"),
ConnectError::SetupFailed(err) => display(f, "X11 setup failed", &err.reason),
ConnectError::SetupAuthenticate(err) => {
display(f, "X11 authentication failed", &err.reason)
}
ConnectError::Incomplete { expected, received } => write!(
f,
"Not enough data received to complete the handshake. Expected {expected}, received {received}"
),
}
}
}
impl From<ParseError> for ConnectError {
fn from(err: ParseError) -> Self {
ConnectError::ParseError(err)
}
}
impl From<DisplayParsingError> for ConnectError {
fn from(err: DisplayParsingError) -> Self {
ConnectError::DisplayParsingError(err)
}
}
#[cfg(feature = "std")]
impl From<std::io::Error> for ConnectError {
fn from(err: std::io::Error) -> Self {
ConnectError::IoError(err)
}
}
+158
View File
@@ -0,0 +1,158 @@
//! A mechanism for allocating XIDs.
use crate::errors::ConnectError;
use crate::protocol::xc_misc::GetXIDRangeReply;
#[cfg(feature = "std")]
use std::error::Error;
use core::fmt;
/// An allocator for X11 IDs.
///
/// This struct handles the client-side generation of X11 IDs. The ID allocation is based on a
/// range of IDs that the server assigned us. This range is described by a base and a mask. From
/// the X11 protocol reference manual:
///
/// > The resource-id-mask contains a single contiguous set of bits (at least 18). The client
/// > allocates resource IDs [..] by choosing a value with only some subset of these bits set and
/// > ORing it with resource-id-base.
#[derive(Debug, Clone, Copy)]
pub struct IdAllocator {
next_id: u32,
max_id: u32,
increment: u32,
}
impl IdAllocator {
/// Create a new instance of an ID allocator.
///
/// The arguments should be the `resource_id_base` and `resource_id_mask` values that the X11
/// server sent in a `Setup` response.
pub fn new(id_base: u32, id_mask: u32) -> Result<Self, ConnectError> {
if id_mask == 0 {
return Err(ConnectError::ZeroIdMask);
}
// Find the right-most set bit in id_mask, e.g. for 0b110, this results in 0b010.
let increment = id_mask & (1 + !id_mask);
Ok(Self {
next_id: id_base,
max_id: id_base | id_mask,
increment,
})
}
/// Update the available range of IDs based on a GetXIDRangeReply
pub fn update_xid_range(&mut self, xidrange: &GetXIDRangeReply) -> Result<(), IdsExhausted> {
let (start, count) = (xidrange.start_id, xidrange.count);
// Apparently (0, 1) is how the server signals "I am out of IDs".
// The second case avoids an underflow below and should never happen.
if (start, count) == (0, 1) || count == 0 {
return Err(IdsExhausted);
}
self.next_id = start;
self.max_id = start + (count - 1) * self.increment;
Ok(())
}
/// Generate the next ID.
pub fn generate_id(&mut self) -> Option<u32> {
if self.next_id > self.max_id {
None
} else {
let id = self.next_id;
self.next_id += self.increment;
Some(id)
}
}
}
/// The XID range has been exhausted.
#[derive(Debug, Copy, Clone)]
pub struct IdsExhausted;
impl fmt::Display for IdsExhausted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "XID range has been exhausted")
}
}
#[cfg(feature = "std")]
impl Error for IdsExhausted {}
#[cfg(test)]
mod test {
use super::{GetXIDRangeReply, IdAllocator, IdsExhausted};
#[test]
fn exhaustive() {
let mut allocator = IdAllocator::new(0x2800, 0x1ff).unwrap();
for expected in 0x2800..=0x29ff {
assert_eq!(Some(expected), allocator.generate_id());
}
assert_eq!(None, allocator.generate_id());
}
#[test]
fn increment() {
let mut allocator = IdAllocator::new(0, 0b1100).unwrap();
assert_eq!(Some(0b0000), allocator.generate_id());
assert_eq!(Some(0b0100), allocator.generate_id());
assert_eq!(Some(0b1000), allocator.generate_id());
assert_eq!(Some(0b1100), allocator.generate_id());
assert_eq!(None, allocator.generate_id());
}
#[test]
fn new_range() {
let mut allocator = IdAllocator::new(0x420, 2).unwrap();
assert_eq!(Some(0x420), allocator.generate_id());
assert_eq!(Some(0x422), allocator.generate_id());
// At this point the range is exhausted and a GetXIDRange request needs to be sent
assert_eq!(None, allocator.generate_id());
allocator
.update_xid_range(&generate_get_xid_range_reply(0x13370, 3))
.unwrap();
assert_eq!(Some(0x13370), allocator.generate_id());
assert_eq!(Some(0x13372), allocator.generate_id());
assert_eq!(Some(0x13374), allocator.generate_id());
// At this point the range is exhausted and a GetXIDRange request needs to be sent
assert_eq!(None, allocator.generate_id());
allocator
.update_xid_range(&generate_get_xid_range_reply(0x13370, 3))
.unwrap();
assert_eq!(Some(0x13370), allocator.generate_id());
}
#[test]
fn invalid_new_arg() {
let err = IdAllocator::new(1234, 0).unwrap_err();
if let super::ConnectError::ZeroIdMask = err {
} else {
panic!("Wrong error: {:?}", err);
}
}
#[test]
fn invalid_update_arg() {
fn check_ids_exhausted(arg: &Result<(), IdsExhausted>) {
if let Err(IdsExhausted) = arg {
} else {
panic!("Expected IdsExhausted, got {:?}", arg);
}
}
let mut allocator = IdAllocator::new(0x420, 2).unwrap();
check_ids_exhausted(&allocator.update_xid_range(&generate_get_xid_range_reply(0, 1)));
check_ids_exhausted(&allocator.update_xid_range(&generate_get_xid_range_reply(1, 0)));
}
fn generate_get_xid_range_reply(start_id: u32, count: u32) -> GetXIDRangeReply {
GetXIDRangeReply {
sequence: 0,
length: 0,
start_id,
count,
}
}
}
+122
View File
@@ -0,0 +1,122 @@
//! X11 rust bindings.
//!
//! This crate provides a representation of the X11 protocol in Rust. With this protocol, raw X11
//! bytes can be parsed into a structured representation or raw bytes can be produces.
//!
//! This protocol does not do any I/O. If you need an X11 client library, look at
//! <https://docs.rs/x11rb/latest/x11rb/>.
//!
//! # Feature flags
//!
//! This crate uses [feature
//! flags](https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section) to reduce
//! the amount of compiled code. There are two kinds of feature flags available:
//!
//! * Feature flags for specific X11 extensions
//! * Feature flags for additional functionality
//!
//! ## Feature flags for specific X11 extensions
//!
//! By default, only the core X11 protocol and some small, commonly needed X11 extensions are
//! enabled. These are the `bigreq`, `ge` and `xc_misc` extensions. Further extensions need to be
//! explicitly enabled via their feature flag:
//!
//! `composite`, `damage`, `dpms`, `dri2`, `dri3`, `glx`, `present`, `randr`, `record`, `render`,
//! `res`, `screensaver`, `shape`, `shm`, `sync`, `xevie`, `xf86dri`, `xf86vidmode`, `xfixes`,
//! `xinerama`, `xinput`, `xkb`, `xprint`, `xselinux`, `xtest`, `xv`, `xvmc`.
//!
//! If you want to take the "I do not want to think about this"-approach, you can enable the
//! `all-extensions` feature to just enable, well, all extensions.
//!
//! ## Feature flags for additional functionality
//!
//! Additionally, the following flags exist:
//! * `std` (enabled by default): Enable functionality needing the std library, e.g. environment
//! variables or [`std::os::unix::io::OwnedFd`].
//! * `resource_manager`: Enable the code in [resource_manager] for loading and querying the
//! X11 resource database.
//! * `serde`: Implement [`serde::Serialize`] and [`serde::Deserialize`] for all objects.
//! * `request-parsing`: Add the ability to parse X11 requests. Not normally needed.
//! * `extra-traits`: Implement extra traits for types. This improves the output of the `Debug`
//! impl and adds `PartialEq`, `Eq`, `PartialOrd`, `Ord`, and `Hash` where possible.
// A list of lints that are only #![deny] and not the stronger #![forbid]. Each one has a comment
// explaining why it gets the weaker treatment.
#![deny(
// Contains unreachable_code and "?" generates an #[allow] for this
unused,
// #[derive] generates an #[allow] for this; not part of "unused"
unused_qualifications,
// serde's Deserialize/Serialize impls add allows for this
rust_2018_idioms,
// Not everything in x11rb_protocol::protocol has doc comments
missing_docs,
)]
#![forbid(
missing_copy_implementations,
missing_debug_implementations,
rustdoc::private_doc_tests,
//single_use_lifetimes,
trivial_casts,
trivial_numeric_casts,
unreachable_pub,
unsafe_code,
unused_must_use,
unused_results,
clippy::cast_lossless,
clippy::needless_pass_by_value,
)]
#![no_std]
// std crate imports
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
use alloc::vec::Vec;
pub mod connect;
pub mod connection;
#[macro_use]
pub mod x11_utils;
pub mod errors;
pub mod id_allocator;
pub mod packet_reader;
pub mod parse_display;
#[rustfmt::skip]
#[allow(missing_docs)]
pub mod protocol;
#[cfg(feature = "resource_manager")]
pub mod resource_manager;
#[cfg(test)]
mod test;
mod utils;
pub mod wrapper;
pub mod xauth;
pub use utils::RawFdContainer;
// Used to avoid too-complex types.
/// A combination of a buffer and a list of file descriptors.
pub type BufWithFds<B> = (B, Vec<RawFdContainer>);
/// Number type used for referring to things that were sent to the server in responses from the
/// server.
///
/// Each request sent to the X11 server is implicitly assigned a monotonically increasing sequence
/// number. Replies, events, and errors contain the sequence number of the last request that the
/// server received. This allows to map replies to their requests and to figure out which request
/// caused an error.
pub type SequenceNumber = u64;
/// The raw bytes of an event and its sequence number.
pub type RawEventAndSeqNumber<B> = (B, SequenceNumber);
/// Variants describing which responses to a request should be discarded.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DiscardMode {
/// Only discard the actual reply. Errors go to the main loop.
DiscardReply,
/// Ignore any kind of response that this request generates.
DiscardReplyAndError,
}
+280
View File
@@ -0,0 +1,280 @@
//! Collects X11 data into "packets" to be parsed by a display.
use core::fmt;
use core::mem::replace;
use alloc::{vec, vec::Vec};
/// Minimal length of an X11 packet.
const MINIMAL_PACKET_LENGTH: usize = 32;
/// A wrapper around a buffer used to read X11 packets.
pub struct PacketReader {
/// A partially-read packet.
pending_packet: Vec<u8>,
/// The point at which the packet is already read.
already_read: usize,
}
impl fmt::Debug for PacketReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PacketReader")
.field(&format_args!(
"{}/{}",
self.already_read,
self.pending_packet.len()
))
.finish()
}
}
impl Default for PacketReader {
fn default() -> Self {
Self::new()
}
}
impl PacketReader {
/// Create a new, empty `PacketReader`.
///
/// # Example
///
/// ```rust
/// # use x11rb_protocol::packet_reader::PacketReader;
/// let reader = PacketReader::new();
/// ```
pub fn new() -> Self {
Self {
pending_packet: vec![0; MINIMAL_PACKET_LENGTH],
already_read: 0,
}
}
/// Get the buffer that the reader should fill with data.
///
/// # Example
///
/// ```rust
/// # use x11rb_protocol::packet_reader::PacketReader;
/// # use x11rb_protocol::protocol::xproto::{GetInputFocusReply, InputFocus, Window};
/// let mut reader = PacketReader::new();
/// let buffer: [u8; 32] = read_in_buffer();
///
/// reader.buffer().copy_from_slice(&buffer);
///
/// # fn read_in_buffer() -> [u8; 32] { [0; 32] }
/// ```
pub fn buffer(&mut self) -> &mut [u8] {
&mut self.pending_packet[self.already_read..]
}
/// The remaining capacity that needs to be filled.
pub fn remaining_capacity(&self) -> usize {
self.pending_packet.len() - self.already_read
}
/// Advance this buffer by the given amount.
///
/// This will return the packet that was read, if enough bytes were read in order
/// to form a complete packet.
pub fn advance(&mut self, amount: usize) -> Option<Vec<u8>> {
self.already_read += amount;
debug_assert!(self.already_read <= self.pending_packet.len());
if self.already_read == MINIMAL_PACKET_LENGTH {
// we've read in the minimal packet, compute the amount of data we need to read
// to form a complete packet
let extra_length = extra_length(&self.pending_packet);
// tell if we need to read more
if extra_length > 0 {
let total_length = MINIMAL_PACKET_LENGTH + extra_length;
self.pending_packet.resize(total_length, 0);
return None;
}
} else if self.already_read != self.pending_packet.len() {
// we haven't read the full packet yet, return
return None;
}
// we've read in the full packet, return it
self.already_read = 0;
Some(replace(
&mut self.pending_packet,
vec![0; MINIMAL_PACKET_LENGTH],
))
}
}
/// Compute the length of the data we need to read, beyond the `MINIMAL_PACKET_LENGTH`.
fn extra_length(buffer: &[u8]) -> usize {
use crate::protocol::xproto::GE_GENERIC_EVENT;
const REPLY: u8 = 1;
let response_type = buffer[0];
if response_type == REPLY || response_type & 0x7f == GE_GENERIC_EVENT {
let length_field = buffer[4..8].try_into().unwrap();
let length_field = u32::from_ne_bytes(length_field) as usize;
4 * length_field
} else {
// Fixed size packet: error or event that is not GE_GENERIC_EVENT
0
}
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::PacketReader;
use alloc::{vec, vec::Vec};
fn test_packets(packets: Vec<Vec<u8>>) {
// Combine all packet data into one big chunk and test that the packet reader splits things
let mut all_data = packets.iter().flatten().copied().collect::<Vec<u8>>();
let mut reader = PacketReader::default();
for (i, packet) in packets.into_iter().enumerate() {
std::println!("Checking packet {i}");
loop {
let buffer = reader.buffer();
let amount = std::cmp::min(buffer.len(), all_data.len());
buffer.copy_from_slice(&all_data[..amount]);
let _ = all_data.drain(..amount);
if let Some(read_packet) = reader.advance(amount) {
assert_eq!(read_packet, packet);
break;
}
}
}
}
fn make_reply_with_length(len: usize) -> Vec<u8> {
let mut packet = vec![0; len];
let len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packet
}
#[test]
fn fixed_size_packet() {
// packet with a fixed size
let packet = vec![0; 32];
test_packets(vec![packet]);
}
#[test]
fn variable_size_packet() {
// packet with a variable size
let packet = make_reply_with_length(1200);
test_packets(vec![packet]);
}
#[test]
fn test_many_fixed_size_packets() {
let mut packets = vec![];
for _ in 0..100 {
packets.push(vec![0; 32]);
}
test_packets(packets);
}
#[test]
fn test_many_variable_size_packets() {
let mut packets = vec![];
for i in 0..100 {
// for maximum variation, increase packet size in a curved parabola
// defined by -1/25 (x - 50)^2 + 100
let variation = ((i - 50) * (i - 50)) as f32;
let variation = -1.0 / 25.0 * variation + 100.0;
let variation = variation as usize;
// round to a multiple of 4
let variation = variation / 4 * 4;
let mut len = 1200 + variation;
let mut packet = vec![0; len];
assert_eq!(0, len % 4);
len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packets.push(packet);
}
test_packets(packets);
}
#[test]
fn test_many_size_packets_mixed() {
let mut packets = vec![];
for i in 0..100 {
// on odds, do a varsize packet
let mut len = if i & 1 == 1 {
// for maximum variation, increase packet size in a curved parabola
// defined by -1/25 (x - 50)^2 + 100
let variation = ((i - 50) * (i - 50)) as f32;
let variation = -1.0 / 25.0 * variation + 100.0;
let variation = variation as usize;
// round to a multiple of 4
let variation = variation / 4 * 4;
1200 + variation
} else {
32
};
assert_eq!(0, len % 4);
let mut packet = vec![0; len];
len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packets.push(packet);
}
test_packets(packets);
}
#[test]
fn test_debug_fixed_size_packet() {
// The debug output includes the length of the packet of the packet and how much was
// already read
let mut reader = PacketReader::new();
assert_eq!(std::format!("{reader:?}"), "PacketReader(0/32)");
let _ = reader.advance(15);
assert_eq!(std::format!("{reader:?}"), "PacketReader(15/32)");
let _ = reader.advance(15);
assert_eq!(std::format!("{reader:?}"), "PacketReader(30/32)");
let _ = reader.advance(2);
assert_eq!(std::format!("{reader:?}"), "PacketReader(0/32)");
}
#[test]
fn test_debug_variable_size_packet() {
let packet = make_reply_with_length(1200);
let mut reader = PacketReader::new();
let first_len = 32;
let second_len = 3;
reader.buffer()[..first_len].copy_from_slice(&packet[..first_len]);
let _ = reader.advance(first_len);
reader.buffer()[..second_len].copy_from_slice(&packet[..second_len]);
let _ = reader.advance(second_len);
assert_eq!(std::format!("{reader:?}"), "PacketReader(35/1200)");
}
}
@@ -0,0 +1,97 @@
//! Provides the `ConnectInstruction` structure, which allows for a `ParsedDisplay`
//! to be transformed into a server connection.
use super::ParsedDisplay;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
/// A possible address for an X11 server.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConnectAddress<'a> {
/// Connect to this hostname and port over TCP.
Hostname(&'a str, u16),
/// Connect to this Unix socket.
///
/// First, the given path should be attempted in the abstract namespace. Only if that fails,
/// then the named socket with the given name should be tried.
Socket(String),
}
/// Get an iterator over all of the addresses we should target with a
/// `ParsedDisplay`.
pub(super) fn connect_addresses(p: &ParsedDisplay) -> impl Iterator<Item = ConnectAddress<'_>> {
const TCP_PORT_BASE: u16 = 6000;
let ParsedDisplay {
host,
protocol,
display,
..
} = p;
let mut targets = Vec::new();
if (protocol.is_none() || protocol.as_deref() != Some("unix"))
&& !host.is_empty()
&& host != "unix"
{
targets.push(ConnectAddress::Hostname(host, TCP_PORT_BASE + display));
} else {
if protocol.is_none() || protocol.as_deref() == Some("unix") {
let file_name = format!("/tmp/.X11-unix/X{display}");
targets.push(ConnectAddress::Socket(file_name));
}
if protocol.is_none() && host.is_empty() {
targets.push(ConnectAddress::Hostname(
"localhost",
TCP_PORT_BASE + display,
));
}
}
targets.into_iter()
}
#[cfg(all(test, feature = "std"))]
mod tests {
// make sure iterator properties are clean
use super::{super::parse_display, ConnectAddress};
use alloc::{vec, vec::Vec};
#[test]
fn basic_test() {
let pd = parse_display(Some(":0")).unwrap();
let ci = pd.connect_instruction();
let ci = ci.collect::<Vec<_>>();
assert_eq!(
ci,
vec![
ConnectAddress::Socket("/tmp/.X11-unix/X0".into()),
ConnectAddress::Hostname("localhost", 6000),
]
);
}
#[test]
fn try_over_hostname() {
let pd = parse_display(Some("192.168.1.111:0")).unwrap();
let ci = pd.connect_instruction();
let ci = ci.collect::<Vec<_>>();
assert_eq!(ci, vec![ConnectAddress::Hostname("192.168.1.111", 6000),]);
}
#[test]
fn try_over_unix_hostname() {
let pd = parse_display(Some("unix/host:0")).unwrap();
let ci = pd.connect_instruction();
let ci = ci.collect::<Vec<_>>();
assert_eq!(ci, vec![ConnectAddress::Socket("/tmp/.X11-unix/X0".into())]);
}
}
+641
View File
@@ -0,0 +1,641 @@
//! Utilities for parsing X11 display strings.
mod connect_instruction;
pub use connect_instruction::ConnectAddress;
use crate::errors::DisplayParsingError;
use alloc::string::{String, ToString};
/// A parsed X11 display string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedDisplay {
/// The hostname of the computer we nned to connect to.
///
/// This is an empty string if we are connecting to the
/// local host.
pub host: String,
/// The protocol we are communicating over.
///
/// This is `None` if the protocol may be determined
/// automatically.
pub protocol: Option<String>,
/// The index of the display we are connecting to.
pub display: u16,
/// The index of the screen that we are using as the
/// default screen.
pub screen: u16,
}
impl ParsedDisplay {
/// Get an iterator over `ConnectAddress`es from this parsed display for connecting
/// to the server.
pub fn connect_instruction(&self) -> impl Iterator<Item = ConnectAddress<'_>> {
connect_instruction::connect_addresses(self)
}
}
/// Parse an X11 display string.
///
/// If `dpy_name` is `None`, the display is parsed from the environment variable `DISPLAY`.
///
/// This function is only available when the `std` feature is enabled.
#[cfg(feature = "std")]
pub fn parse_display(dpy_name: Option<&str>) -> Result<ParsedDisplay, DisplayParsingError> {
fn file_exists(path: &str) -> bool {
std::path::Path::new(path).exists()
}
match dpy_name {
Some(dpy_name) => parse_display_with_file_exists_callback(dpy_name, file_exists),
// If no dpy name was provided, use the env var. If no env var exists, return an error.
None => match std::env::var("DISPLAY") {
Ok(dpy_name) => parse_display_with_file_exists_callback(&dpy_name, file_exists),
Err(std::env::VarError::NotPresent) => Err(DisplayParsingError::DisplayNotSet),
Err(std::env::VarError::NotUnicode(_)) => Err(DisplayParsingError::NotUnicode),
},
}
}
/// Parse an X11 display string.
///
/// If `dpy_name` is `None`, the display is parsed from the environment variable `DISPLAY`.
///
/// The parameter `file_exists` is called to check whether a given string refers to an existing
/// file. This function does not need to check the file type.
pub fn parse_display_with_file_exists_callback(
dpy_name: &str,
file_exists: impl Fn(&str) -> bool,
) -> Result<ParsedDisplay, DisplayParsingError> {
let malformed = || DisplayParsingError::MalformedValue(dpy_name.to_string().into());
let map_malformed = |_| malformed();
if dpy_name.starts_with('/') {
return parse_display_direct_path(dpy_name, file_exists);
}
if let Some(remaining) = dpy_name.strip_prefix("unix:") {
return parse_display_direct_path(remaining, file_exists);
}
// Everything up to the last '/' is the protocol. This part is optional.
let (protocol, remaining) = if let Some(pos) = dpy_name.rfind('/') {
(Some(&dpy_name[..pos]), &dpy_name[pos + 1..])
} else {
(None, dpy_name)
};
// Everything up to the last ':' is the host. This part is required.
let pos = remaining.rfind(':').ok_or_else(malformed)?;
let (host, remaining) = (&remaining[..pos], &remaining[pos + 1..]);
// The remaining part is display.screen. The display is required and the screen optional.
let (display, screen) = match remaining.find('.') {
Some(pos) => (&remaining[..pos], &remaining[pos + 1..]),
None => (remaining, "0"),
};
// Parse the display and screen number
let (display, screen) = (
display.parse().map_err(map_malformed)?,
screen.parse().map_err(map_malformed)?,
);
let host = host.to_string();
let protocol = protocol.map(|p| p.to_string());
Ok(ParsedDisplay {
host,
protocol,
display,
screen,
})
}
// Check for "launchd mode" where we get the full path to a unix socket
fn parse_display_direct_path(
dpy_name: &str,
file_exists: impl Fn(&str) -> bool,
) -> Result<ParsedDisplay, DisplayParsingError> {
if file_exists(dpy_name) {
return Ok(ParsedDisplay {
host: dpy_name.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: 0,
});
}
// Optionally, a screen number may be appended as ".n".
if let Some((path, screen)) = dpy_name.rsplit_once('.') {
if file_exists(path) {
return Ok(ParsedDisplay {
host: path.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: screen.parse().map_err(|_| {
DisplayParsingError::MalformedValue(dpy_name.to_string().into())
})?,
});
}
}
Err(DisplayParsingError::MalformedValue(
dpy_name.to_string().into(),
))
}
#[cfg(all(test, feature = "std"))]
mod test {
use super::{
parse_display, parse_display_with_file_exists_callback, DisplayParsingError, ParsedDisplay,
};
use alloc::string::ToString;
use core::cell::RefCell;
fn do_parse_display(input: &str) -> Result<ParsedDisplay, DisplayParsingError> {
std::env::set_var("DISPLAY", input);
let result1 = parse_display(None);
std::env::remove_var("DISPLAY");
let result2 = parse_display(Some(input));
assert_eq!(result1, result2);
result1
}
// The tests modify environment variables. This is process-global. Thus, the tests in this
// module cannot be run concurrently. We achieve this by having only a single test functions
// that calls all other functions.
#[test]
fn test_parsing() {
test_missing_input();
xcb_good_cases();
xcb_bad_cases();
own_good_cases();
own_bad_cases();
}
fn test_missing_input() {
std::env::remove_var("DISPLAY");
assert_eq!(parse_display(None), Err(DisplayParsingError::DisplayNotSet));
}
fn own_good_cases() {
// The XCB test suite does not test protocol parsing
for (input, output) in &[
(
"foo/bar:1",
ParsedDisplay {
host: "bar".to_string(),
protocol: Some("foo".to_string()),
display: 1,
screen: 0,
},
),
(
"foo/bar:1.2",
ParsedDisplay {
host: "bar".to_string(),
protocol: Some("foo".to_string()),
display: 1,
screen: 2,
},
),
(
"a:b/c/foo:bar:1.2",
ParsedDisplay {
host: "foo:bar".to_string(),
protocol: Some("a:b/c".to_string()),
display: 1,
screen: 2,
},
),
] {
assert_eq!(
do_parse_display(input).as_ref(),
Ok(output),
"Failed parsing correctly: {input}"
);
}
}
fn own_bad_cases() {
let non_existing_file = concat!(env!("CARGO_MANIFEST_DIR"), "/this_file_does_not_exist");
assert_eq!(
do_parse_display(non_existing_file),
Err(DisplayParsingError::MalformedValue(
non_existing_file.to_string().into()
)),
"Unexpectedly parsed: {non_existing_file}"
);
}
// Based on libxcb's test suite; (C) 2001-2006 Bart Massey, Jamey Sharp, and Josh Triplett
fn xcb_good_cases() {
// The libxcb code creates a temporary file. We can just use a known-to-exist file.
let existing_file = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
for (input, output) in &[
// unix in "launchd mode"
(
existing_file,
ParsedDisplay {
host: existing_file.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: 0,
},
),
(
&alloc::format!("unix:{existing_file}"),
ParsedDisplay {
host: existing_file.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: 0,
},
),
(
&alloc::format!("unix:{existing_file}.1"),
ParsedDisplay {
host: existing_file.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: 1,
},
),
(
&alloc::format!("{existing_file}.1"),
ParsedDisplay {
host: existing_file.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen: 1,
},
),
// unix
(
":0",
ParsedDisplay {
host: "".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
":1",
ParsedDisplay {
host: "".to_string(),
protocol: None,
display: 1,
screen: 0,
},
),
(
":0.1",
ParsedDisplay {
host: "".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
// ip
(
"x.org:0",
ParsedDisplay {
host: "x.org".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"expo:0",
ParsedDisplay {
host: "expo".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"bigmachine:1",
ParsedDisplay {
host: "bigmachine".to_string(),
protocol: None,
display: 1,
screen: 0,
},
),
(
"hydra:0.1",
ParsedDisplay {
host: "hydra".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
// ipv4
(
"198.112.45.11:0",
ParsedDisplay {
host: "198.112.45.11".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"198.112.45.11:0.1",
ParsedDisplay {
host: "198.112.45.11".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
// ipv6
(
":::0",
ParsedDisplay {
host: "::".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"1:::0",
ParsedDisplay {
host: "1::".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"::1:0",
ParsedDisplay {
host: "::1".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"::1:0.1",
ParsedDisplay {
host: "::1".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
(
"::127.0.0.1:0",
ParsedDisplay {
host: "::127.0.0.1".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"::ffff:127.0.0.1:0",
ParsedDisplay {
host: "::ffff:127.0.0.1".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"2002:83fc:3052::1:0",
ParsedDisplay {
host: "2002:83fc:3052::1".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"2002:83fc:3052::1:0.1",
ParsedDisplay {
host: "2002:83fc:3052::1".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
(
"[::]:0",
ParsedDisplay {
host: "[::]".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"[1::]:0",
ParsedDisplay {
host: "[1::]".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"[::1]:0",
ParsedDisplay {
host: "[::1]".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"[::1]:0.1",
ParsedDisplay {
host: "[::1]".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
(
"[::127.0.0.1]:0",
ParsedDisplay {
host: "[::127.0.0.1]".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"[2002:83fc:d052::1]:0",
ParsedDisplay {
host: "[2002:83fc:d052::1]".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"[2002:83fc:d052::1]:0.1",
ParsedDisplay {
host: "[2002:83fc:d052::1]".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
// decnet
(
"myws::0",
ParsedDisplay {
host: "myws:".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"big::0",
ParsedDisplay {
host: "big:".to_string(),
protocol: None,
display: 0,
screen: 0,
},
),
(
"hydra::0.1",
ParsedDisplay {
host: "hydra:".to_string(),
protocol: None,
display: 0,
screen: 1,
},
),
] {
assert_eq!(
do_parse_display(input).as_ref(),
Ok(output),
"Failed parsing correctly: {input}"
);
}
}
// Based on libxcb's test suite; (C) 2001-2006 Bart Massey, Jamey Sharp, and Josh Triplett
fn xcb_bad_cases() {
for input in &[
"",
":",
"::",
":::",
":.",
":a",
":a.",
":0.",
":.a",
":.0",
":0.a",
":0.0.",
"127.0.0.1",
"127.0.0.1:",
"127.0.0.1::",
"::127.0.0.1",
"::127.0.0.1:",
"::127.0.0.1::",
"::ffff:127.0.0.1",
"::ffff:127.0.0.1:",
"::ffff:127.0.0.1::",
"localhost",
"localhost:",
"localhost::",
] {
assert_eq!(
do_parse_display(input),
Err(DisplayParsingError::MalformedValue(
input.to_string().into()
)),
"Unexpectedly parsed: {input}"
);
}
}
fn make_unix_path(host: &str, screen: u16) -> Result<ParsedDisplay, DisplayParsingError> {
Ok(ParsedDisplay {
host: host.to_string(),
protocol: Some("unix".to_string()),
display: 0,
screen,
})
}
#[test]
fn test_file_exists_callback_direct_path() {
fn run_test(display: &str, expected_path: &str) {
let called = RefCell::new(0);
let callback = |path: &_| {
assert_eq!(path, expected_path);
let mut called = called.borrow_mut();
assert_eq!(*called, 0);
*called += 1;
true
};
let result = parse_display_with_file_exists_callback(display, callback);
assert_eq!(*called.borrow(), 1);
assert_eq!(result, make_unix_path(expected_path, 0));
}
run_test("/path/to/file", "/path/to/file");
run_test("/path/to/file.123", "/path/to/file.123");
run_test("unix:whatever", "whatever");
run_test("unix:whatever.123", "whatever.123");
}
#[test]
fn test_file_exists_callback_direct_path_with_screen() {
fn run_test(display: &str, expected_path: &str) {
let called = RefCell::new(0);
let callback = |path: &_| {
let mut called = called.borrow_mut();
*called += 1;
match *called {
1 => {
assert_eq!(path, alloc::format!("{expected_path}.42"));
false
}
2 => {
assert_eq!(path, expected_path);
true
}
_ => panic!("Unexpected call count {}", *called),
}
};
let result = parse_display_with_file_exists_callback(display, callback);
assert_eq!(*called.borrow(), 2);
assert_eq!(result, make_unix_path(expected_path, 42));
}
run_test("/path/to/file.42", "/path/to/file");
run_test("unix:whatever.42", "whatever");
}
#[test]
fn test_file_exists_callback_not_called_without_path() {
let callback = |path: &str| unreachable!("Called with {path}");
let result = parse_display_with_file_exists_callback("foo/bar:1.2", callback);
assert_eq!(
result,
Ok(ParsedDisplay {
host: "bar".to_string(),
protocol: Some("foo".to_string()),
display: 1,
screen: 2,
},)
);
}
}
+153
View File
@@ -0,0 +1,153 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `BigRequests` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "BIG-REQUESTS";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (0, 0);
/// Opcode for the Enable request
pub const ENABLE_REQUEST: u8 = 0;
/// Enable the BIG-REQUESTS extension.
///
/// This enables the BIG-REQUESTS extension, which allows for requests larger than
/// 262140 bytes in length. When enabled, if the 16-bit length field is zero, it
/// is immediately followed by a 32-bit length field specifying the length of the
/// request in 4-byte units.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EnableRequest;
impl_debug_if_no_extra_traits!(EnableRequest, "EnableRequest");
impl EnableRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let mut request0 = vec![
major_opcode,
ENABLE_REQUEST,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != ENABLE_REQUEST {
return Err(ParseError::InvalidValue);
}
let _ = value;
Ok(EnableRequest
)
}
}
impl Request for EnableRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for EnableRequest {
type Reply = EnableReply;
}
/// # Fields
///
/// * `maximum_request_length` - The maximum length of requests supported by the server, in 4-byte units.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EnableReply {
pub sequence: u16,
pub length: u32,
pub maximum_request_length: u32,
}
impl_debug_if_no_extra_traits!(EnableReply, "EnableReply");
impl TryParse for EnableReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (maximum_request_length, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = EnableReply { sequence, length, maximum_request_length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for EnableReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let maximum_request_length_bytes = self.maximum_request_length.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
maximum_request_length_bytes[0],
maximum_request_length_bytes[1],
maximum_request_length_bytes[2],
maximum_request_length_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.maximum_request_length.serialize_into(bytes);
}
}
+905
View File
@@ -0,0 +1,905 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Composite` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
#[allow(unused_imports)]
use super::xfixes;
#[allow(unused_imports)]
use super::xproto;
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "Composite";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (0, 4);
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Redirect(u8);
impl Redirect {
pub const AUTOMATIC: Self = Self(0);
pub const MANUAL: Self = Self(1);
}
impl From<Redirect> for u8 {
#[inline]
fn from(input: Redirect) -> Self {
input.0
}
}
impl From<Redirect> for Option<u8> {
#[inline]
fn from(input: Redirect) -> Self {
Some(input.0)
}
}
impl From<Redirect> for u16 {
#[inline]
fn from(input: Redirect) -> Self {
u16::from(input.0)
}
}
impl From<Redirect> for Option<u16> {
#[inline]
fn from(input: Redirect) -> Self {
Some(u16::from(input.0))
}
}
impl From<Redirect> for u32 {
#[inline]
fn from(input: Redirect) -> Self {
u32::from(input.0)
}
}
impl From<Redirect> for Option<u32> {
#[inline]
fn from(input: Redirect) -> Self {
Some(u32::from(input.0))
}
}
impl From<u8> for Redirect {
#[inline]
fn from(value: u8) -> Self {
Self(value)
}
}
impl core::fmt::Debug for Redirect {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let variants = [
(Self::AUTOMATIC.0.into(), "AUTOMATIC", "Automatic"),
(Self::MANUAL.0.into(), "MANUAL", "Manual"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
/// Negotiate the version of Composite.
///
/// This negotiates the version of the Composite extension. It must be precede all
/// other requests using Composite. Failure to do so will cause a BadRequest error.
///
/// # Fields
///
/// * `client_major_version` - The major version supported by the client.
/// * `client_minor_version` - The minor version supported by the client.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionRequest {
pub client_major_version: u32,
pub client_minor_version: u32,
}
impl_debug_if_no_extra_traits!(QueryVersionRequest, "QueryVersionRequest");
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let client_major_version_bytes = self.client_major_version.serialize();
let client_minor_version_bytes = self.client_minor_version.serialize();
let mut request0 = vec![
major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
client_major_version_bytes[0],
client_major_version_bytes[1],
client_major_version_bytes[2],
client_major_version_bytes[3],
client_minor_version_bytes[0],
client_minor_version_bytes[1],
client_minor_version_bytes[2],
client_minor_version_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (client_major_version, remaining) = u32::try_parse(value)?;
let (client_minor_version, remaining) = u32::try_parse(remaining)?;
let _ = remaining;
Ok(QueryVersionRequest {
client_major_version,
client_minor_version,
})
}
}
impl Request for QueryVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryVersionRequest {
type Reply = QueryVersionReply;
}
/// The negotiated version of Composite.
///
/// This indicates the version of Composite chosen by the server. It will always be
/// less than or equal to the version offered by the client.
///
/// # Fields
///
/// * `major_version` - The major version chosen by the server.
/// * `minor_version` - The minor version chosen by the server.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub major_version: u32,
pub minor_version: u32,
}
impl_debug_if_no_extra_traits!(QueryVersionReply, "QueryVersionReply");
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (major_version, remaining) = u32::try_parse(remaining)?;
let (minor_version, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(16..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, major_version, minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryVersionReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let major_version_bytes = self.major_version.serialize();
let minor_version_bytes = self.minor_version.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
major_version_bytes[0],
major_version_bytes[1],
major_version_bytes[2],
major_version_bytes[3],
minor_version_bytes[0],
minor_version_bytes[1],
minor_version_bytes[2],
minor_version_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.major_version.serialize_into(bytes);
self.minor_version.serialize_into(bytes);
bytes.extend_from_slice(&[0; 16]);
}
}
/// Opcode for the RedirectWindow request
pub const REDIRECT_WINDOW_REQUEST: u8 = 1;
/// Redirect the hierarchy starting at "window" to off-screen storage..
///
/// The hierarchy starting at 'window' is directed to off-screen
/// storage. When all clients enabling redirection terminate,
/// the redirection will automatically be disabled.
///
/// The root window may not be redirected. Doing so results in a Match
/// error.
///
/// # Fields
///
/// * `window` - The root of the hierarchy to redirect to off-screen storage.
/// * `update` - Whether contents are automatically mirrored to the parent window. If one client
/// already specifies an update type of Manual, any attempt by another to specify a
/// mode of Manual so will result in an Access error.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RedirectWindowRequest {
pub window: xproto::Window,
pub update: Redirect,
}
impl_debug_if_no_extra_traits!(RedirectWindowRequest, "RedirectWindowRequest");
impl RedirectWindowRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let update_bytes = u8::from(self.update).serialize();
let mut request0 = vec![
major_opcode,
REDIRECT_WINDOW_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
update_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != REDIRECT_WINDOW_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (update, remaining) = u8::try_parse(remaining)?;
let update = update.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(RedirectWindowRequest {
window,
update,
})
}
}
impl Request for RedirectWindowRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for RedirectWindowRequest {
}
/// Opcode for the RedirectSubwindows request
pub const REDIRECT_SUBWINDOWS_REQUEST: u8 = 2;
/// Redirect all current and future children of ‘window’.
///
/// Hierarchies starting at all current and future children of window
/// will be redirected as in RedirectWindow. If update is Manual,
/// then painting of the window background during window manipulation
/// and ClearArea requests is inhibited.
///
/// # Fields
///
/// * `window` - The root of the hierarchy to redirect to off-screen storage.
/// * `update` - Whether contents are automatically mirrored to the parent window. If one client
/// already specifies an update type of Manual, any attempt by another to specify a
/// mode of Manual so will result in an Access error.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RedirectSubwindowsRequest {
pub window: xproto::Window,
pub update: Redirect,
}
impl_debug_if_no_extra_traits!(RedirectSubwindowsRequest, "RedirectSubwindowsRequest");
impl RedirectSubwindowsRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let update_bytes = u8::from(self.update).serialize();
let mut request0 = vec![
major_opcode,
REDIRECT_SUBWINDOWS_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
update_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != REDIRECT_SUBWINDOWS_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (update, remaining) = u8::try_parse(remaining)?;
let update = update.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(RedirectSubwindowsRequest {
window,
update,
})
}
}
impl Request for RedirectSubwindowsRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for RedirectSubwindowsRequest {
}
/// Opcode for the UnredirectWindow request
pub const UNREDIRECT_WINDOW_REQUEST: u8 = 3;
/// Terminate redirection of the specified window..
///
/// Redirection of the specified window will be terminated. This cannot be
/// used if the window was redirected with RedirectSubwindows.
///
/// # Fields
///
/// * `window` - The window to terminate redirection of. Must be redirected by the
/// current client, or a Value error results.
/// * `update` - The update type passed to RedirectWindows. If this does not match the
/// previously requested update type, a Value error results.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnredirectWindowRequest {
pub window: xproto::Window,
pub update: Redirect,
}
impl_debug_if_no_extra_traits!(UnredirectWindowRequest, "UnredirectWindowRequest");
impl UnredirectWindowRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let update_bytes = u8::from(self.update).serialize();
let mut request0 = vec![
major_opcode,
UNREDIRECT_WINDOW_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
update_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != UNREDIRECT_WINDOW_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (update, remaining) = u8::try_parse(remaining)?;
let update = update.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(UnredirectWindowRequest {
window,
update,
})
}
}
impl Request for UnredirectWindowRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for UnredirectWindowRequest {
}
/// Opcode for the UnredirectSubwindows request
pub const UNREDIRECT_SUBWINDOWS_REQUEST: u8 = 4;
/// Terminate redirection of the specified window’s children.
///
/// Redirection of all children of window will be terminated.
///
/// # Fields
///
/// * `window` - The window to terminate redirection of. Must have previously been
/// selected for sub-redirection by the current client, or a Value error
/// results.
/// * `update` - The update type passed to RedirectSubWindows. If this does not match
/// the previously requested update type, a Value error results.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnredirectSubwindowsRequest {
pub window: xproto::Window,
pub update: Redirect,
}
impl_debug_if_no_extra_traits!(UnredirectSubwindowsRequest, "UnredirectSubwindowsRequest");
impl UnredirectSubwindowsRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let update_bytes = u8::from(self.update).serialize();
let mut request0 = vec![
major_opcode,
UNREDIRECT_SUBWINDOWS_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
update_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != UNREDIRECT_SUBWINDOWS_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (update, remaining) = u8::try_parse(remaining)?;
let update = update.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(UnredirectSubwindowsRequest {
window,
update,
})
}
}
impl Request for UnredirectSubwindowsRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for UnredirectSubwindowsRequest {
}
/// Opcode for the CreateRegionFromBorderClip request
pub const CREATE_REGION_FROM_BORDER_CLIP_REQUEST: u8 = 5;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CreateRegionFromBorderClipRequest {
pub region: xfixes::Region,
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(CreateRegionFromBorderClipRequest, "CreateRegionFromBorderClipRequest");
impl CreateRegionFromBorderClipRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let region_bytes = self.region.serialize();
let window_bytes = self.window.serialize();
let mut request0 = vec![
major_opcode,
CREATE_REGION_FROM_BORDER_CLIP_REQUEST,
0,
0,
region_bytes[0],
region_bytes[1],
region_bytes[2],
region_bytes[3],
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != CREATE_REGION_FROM_BORDER_CLIP_REQUEST {
return Err(ParseError::InvalidValue);
}
let (region, remaining) = xfixes::Region::try_parse(value)?;
let (window, remaining) = xproto::Window::try_parse(remaining)?;
let _ = remaining;
Ok(CreateRegionFromBorderClipRequest {
region,
window,
})
}
}
impl Request for CreateRegionFromBorderClipRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for CreateRegionFromBorderClipRequest {
}
/// Opcode for the NameWindowPixmap request
pub const NAME_WINDOW_PIXMAP_REQUEST: u8 = 6;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NameWindowPixmapRequest {
pub window: xproto::Window,
pub pixmap: xproto::Pixmap,
}
impl_debug_if_no_extra_traits!(NameWindowPixmapRequest, "NameWindowPixmapRequest");
impl NameWindowPixmapRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let pixmap_bytes = self.pixmap.serialize();
let mut request0 = vec![
major_opcode,
NAME_WINDOW_PIXMAP_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
pixmap_bytes[0],
pixmap_bytes[1],
pixmap_bytes[2],
pixmap_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != NAME_WINDOW_PIXMAP_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (pixmap, remaining) = xproto::Pixmap::try_parse(remaining)?;
let _ = remaining;
Ok(NameWindowPixmapRequest {
window,
pixmap,
})
}
}
impl Request for NameWindowPixmapRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for NameWindowPixmapRequest {
}
/// Opcode for the GetOverlayWindow request
pub const GET_OVERLAY_WINDOW_REQUEST: u8 = 7;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetOverlayWindowRequest {
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetOverlayWindowRequest, "GetOverlayWindowRequest");
impl GetOverlayWindowRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let mut request0 = vec![
major_opcode,
GET_OVERLAY_WINDOW_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_OVERLAY_WINDOW_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(GetOverlayWindowRequest {
window,
})
}
}
impl Request for GetOverlayWindowRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetOverlayWindowRequest {
type Reply = GetOverlayWindowReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetOverlayWindowReply {
pub sequence: u16,
pub length: u32,
pub overlay_win: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetOverlayWindowReply, "GetOverlayWindowReply");
impl TryParse for GetOverlayWindowReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (overlay_win, remaining) = xproto::Window::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetOverlayWindowReply { sequence, length, overlay_win };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetOverlayWindowReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let overlay_win_bytes = self.overlay_win.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
overlay_win_bytes[0],
overlay_win_bytes[1],
overlay_win_bytes[2],
overlay_win_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.overlay_win.serialize_into(bytes);
bytes.extend_from_slice(&[0; 20]);
}
}
/// Opcode for the ReleaseOverlayWindow request
pub const RELEASE_OVERLAY_WINDOW_REQUEST: u8 = 8;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReleaseOverlayWindowRequest {
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(ReleaseOverlayWindowRequest, "ReleaseOverlayWindowRequest");
impl ReleaseOverlayWindowRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let mut request0 = vec![
major_opcode,
RELEASE_OVERLAY_WINDOW_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != RELEASE_OVERLAY_WINDOW_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(ReleaseOverlayWindowRequest {
window,
})
}
}
impl Request for ReleaseOverlayWindowRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for ReleaseOverlayWindowRequest {
}
+764
View File
@@ -0,0 +1,764 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Damage` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
#[allow(unused_imports)]
use super::xfixes;
#[allow(unused_imports)]
use super::xproto;
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "DAMAGE";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 1);
pub type Damage = u32;
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReportLevel(u8);
impl ReportLevel {
pub const RAW_RECTANGLES: Self = Self(0);
pub const DELTA_RECTANGLES: Self = Self(1);
pub const BOUNDING_BOX: Self = Self(2);
pub const NON_EMPTY: Self = Self(3);
}
impl From<ReportLevel> for u8 {
#[inline]
fn from(input: ReportLevel) -> Self {
input.0
}
}
impl From<ReportLevel> for Option<u8> {
#[inline]
fn from(input: ReportLevel) -> Self {
Some(input.0)
}
}
impl From<ReportLevel> for u16 {
#[inline]
fn from(input: ReportLevel) -> Self {
u16::from(input.0)
}
}
impl From<ReportLevel> for Option<u16> {
#[inline]
fn from(input: ReportLevel) -> Self {
Some(u16::from(input.0))
}
}
impl From<ReportLevel> for u32 {
#[inline]
fn from(input: ReportLevel) -> Self {
u32::from(input.0)
}
}
impl From<ReportLevel> for Option<u32> {
#[inline]
fn from(input: ReportLevel) -> Self {
Some(u32::from(input.0))
}
}
impl From<u8> for ReportLevel {
#[inline]
fn from(value: u8) -> Self {
Self(value)
}
}
impl core::fmt::Debug for ReportLevel {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let variants = [
(Self::RAW_RECTANGLES.0.into(), "RAW_RECTANGLES", "RawRectangles"),
(Self::DELTA_RECTANGLES.0.into(), "DELTA_RECTANGLES", "DeltaRectangles"),
(Self::BOUNDING_BOX.0.into(), "BOUNDING_BOX", "BoundingBox"),
(Self::NON_EMPTY.0.into(), "NON_EMPTY", "NonEmpty"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
/// Opcode for the BadDamage error
pub const BAD_DAMAGE_ERROR: u8 = 0;
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
/// Negotiate the version of the DAMAGE extension.
///
/// This negotiates the version of the DAMAGE extension. It must precede any other
/// request using the DAMAGE extension. Failure to do so will cause a BadRequest
/// error for those requests.
///
/// # Fields
///
/// * `client_major_version` - The major version supported by the client.
/// * `client_minor_version` - The minor version supported by the client.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionRequest {
pub client_major_version: u32,
pub client_minor_version: u32,
}
impl_debug_if_no_extra_traits!(QueryVersionRequest, "QueryVersionRequest");
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let client_major_version_bytes = self.client_major_version.serialize();
let client_minor_version_bytes = self.client_minor_version.serialize();
let mut request0 = vec![
major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
client_major_version_bytes[0],
client_major_version_bytes[1],
client_major_version_bytes[2],
client_major_version_bytes[3],
client_minor_version_bytes[0],
client_minor_version_bytes[1],
client_minor_version_bytes[2],
client_minor_version_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (client_major_version, remaining) = u32::try_parse(value)?;
let (client_minor_version, remaining) = u32::try_parse(remaining)?;
let _ = remaining;
Ok(QueryVersionRequest {
client_major_version,
client_minor_version,
})
}
}
impl Request for QueryVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryVersionRequest {
type Reply = QueryVersionReply;
}
/// The negotiated version of the DAMAGE extension.
///
/// This indicates the version of the DAMAGE extension chosen by the server.
/// It will always be less than or equal to the version offered by the client.
///
/// # Fields
///
/// * `major_version` - The major version chosen by the server.
/// * `minor_version` - The minor version chosen by the server.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub major_version: u32,
pub minor_version: u32,
}
impl_debug_if_no_extra_traits!(QueryVersionReply, "QueryVersionReply");
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (major_version, remaining) = u32::try_parse(remaining)?;
let (minor_version, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(16..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, major_version, minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryVersionReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let major_version_bytes = self.major_version.serialize();
let minor_version_bytes = self.minor_version.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
major_version_bytes[0],
major_version_bytes[1],
major_version_bytes[2],
major_version_bytes[3],
minor_version_bytes[0],
minor_version_bytes[1],
minor_version_bytes[2],
minor_version_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.major_version.serialize_into(bytes);
self.minor_version.serialize_into(bytes);
bytes.extend_from_slice(&[0; 16]);
}
}
/// Opcode for the Create request
pub const CREATE_REQUEST: u8 = 1;
/// Creates a Damage object to monitor changes to a drawable..
///
/// This creates a Damage object to monitor changes to a drawable, and specifies
/// the level of detail to be reported for changes.
///
/// We call changes made to pixel contents of windows and pixmaps 'damage'
/// throughout this extension.
///
/// Damage accumulates as drawing occurs in the drawable. Each drawing operation
/// 'damages' one or more rectangular areas within the drawable. The rectangles
/// are guaranteed to include the set of pixels modified by each operation, but
/// may include significantly more than just those pixels. The desire is for
/// the damage to strike a balance between the number of rectangles reported and
/// the extraneous area included. A reasonable goal is for each primitive
/// object drawn (line, string, rectangle) to be represented as a single
/// rectangle and for the damage area of the operation to be the union of these
/// rectangles.
///
/// The DAMAGE extension allows applications to either receive the raw
/// rectangles as a stream of events, or to have them partially processed within
/// the X server to reduce the amount of data transmitted as well as reduce the
/// processing latency once the repaint operation has started.
///
/// The Damage object holds any accumulated damage region and reflects the
/// relationship between the drawable selected for damage notification and the
/// drawable for which damage is tracked.
///
/// # Fields
///
/// * `damage` - The ID with which you will refer to the new Damage object, created by
/// `xcb_generate_id`.
/// * `drawable` - The ID of the drawable to be monitored.
/// * `level` - The level of detail to be provided in Damage events.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CreateRequest {
pub damage: Damage,
pub drawable: xproto::Drawable,
pub level: ReportLevel,
}
impl_debug_if_no_extra_traits!(CreateRequest, "CreateRequest");
impl CreateRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let damage_bytes = self.damage.serialize();
let drawable_bytes = self.drawable.serialize();
let level_bytes = u8::from(self.level).serialize();
let mut request0 = vec![
major_opcode,
CREATE_REQUEST,
0,
0,
damage_bytes[0],
damage_bytes[1],
damage_bytes[2],
damage_bytes[3],
drawable_bytes[0],
drawable_bytes[1],
drawable_bytes[2],
drawable_bytes[3],
level_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != CREATE_REQUEST {
return Err(ParseError::InvalidValue);
}
let (damage, remaining) = Damage::try_parse(value)?;
let (drawable, remaining) = xproto::Drawable::try_parse(remaining)?;
let (level, remaining) = u8::try_parse(remaining)?;
let level = level.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(CreateRequest {
damage,
drawable,
level,
})
}
}
impl Request for CreateRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for CreateRequest {
}
/// Opcode for the Destroy request
pub const DESTROY_REQUEST: u8 = 2;
/// Destroys a previously created Damage object..
///
/// This destroys a Damage object and requests the X server stop reporting
/// the changes it was tracking.
///
/// # Fields
///
/// * `damage` - The ID you provided to `xcb_create_damage`.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DestroyRequest {
pub damage: Damage,
}
impl_debug_if_no_extra_traits!(DestroyRequest, "DestroyRequest");
impl DestroyRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let damage_bytes = self.damage.serialize();
let mut request0 = vec![
major_opcode,
DESTROY_REQUEST,
0,
0,
damage_bytes[0],
damage_bytes[1],
damage_bytes[2],
damage_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != DESTROY_REQUEST {
return Err(ParseError::InvalidValue);
}
let (damage, remaining) = Damage::try_parse(value)?;
let _ = remaining;
Ok(DestroyRequest {
damage,
})
}
}
impl Request for DestroyRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for DestroyRequest {
}
/// Opcode for the Subtract request
pub const SUBTRACT_REQUEST: u8 = 3;
/// Remove regions from a previously created Damage object..
///
/// This updates the regions of damage recorded in a a Damage object.
/// See <https://www.x.org/releases/current/doc/damageproto/damageproto.txt>
/// for details.
///
/// # Fields
///
/// * `damage` - The ID you provided to `xcb_create_damage`.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SubtractRequest {
pub damage: Damage,
pub repair: xfixes::Region,
pub parts: xfixes::Region,
}
impl_debug_if_no_extra_traits!(SubtractRequest, "SubtractRequest");
impl SubtractRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let damage_bytes = self.damage.serialize();
let repair_bytes = self.repair.serialize();
let parts_bytes = self.parts.serialize();
let mut request0 = vec![
major_opcode,
SUBTRACT_REQUEST,
0,
0,
damage_bytes[0],
damage_bytes[1],
damage_bytes[2],
damage_bytes[3],
repair_bytes[0],
repair_bytes[1],
repair_bytes[2],
repair_bytes[3],
parts_bytes[0],
parts_bytes[1],
parts_bytes[2],
parts_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != SUBTRACT_REQUEST {
return Err(ParseError::InvalidValue);
}
let (damage, remaining) = Damage::try_parse(value)?;
let (repair, remaining) = xfixes::Region::try_parse(remaining)?;
let (parts, remaining) = xfixes::Region::try_parse(remaining)?;
let _ = remaining;
Ok(SubtractRequest {
damage,
repair,
parts,
})
}
}
impl Request for SubtractRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for SubtractRequest {
}
/// Opcode for the Add request
pub const ADD_REQUEST: u8 = 4;
/// Add a region to a previously created Damage object..
///
/// This updates the regions of damage recorded in a a Damage object.
/// See <https://www.x.org/releases/current/doc/damageproto/damageproto.txt>
/// for details.
///
/// # Fields
///
/// * `damage` - The ID you provided to `xcb_create_damage`.
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AddRequest {
pub drawable: xproto::Drawable,
pub region: xfixes::Region,
}
impl_debug_if_no_extra_traits!(AddRequest, "AddRequest");
impl AddRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let drawable_bytes = self.drawable.serialize();
let region_bytes = self.region.serialize();
let mut request0 = vec![
major_opcode,
ADD_REQUEST,
0,
0,
drawable_bytes[0],
drawable_bytes[1],
drawable_bytes[2],
drawable_bytes[3],
region_bytes[0],
region_bytes[1],
region_bytes[2],
region_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != ADD_REQUEST {
return Err(ParseError::InvalidValue);
}
let (drawable, remaining) = xproto::Drawable::try_parse(value)?;
let (region, remaining) = xfixes::Region::try_parse(remaining)?;
let _ = remaining;
Ok(AddRequest {
drawable,
region,
})
}
}
impl Request for AddRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for AddRequest {
}
/// Opcode for the Notify event
pub const NOTIFY_EVENT: u8 = 0;
/// the contents of the monitored drawable have changed.
///
/// # Fields
///
/// * `level` - The level of the damage being reported.
/// If the 0x80 bit is set, indicates there are subsequent Damage events
/// being delivered immediately as part of a larger Damage region.
/// * `drawable` - The drawable for which damage is being reported.
/// * `damage` - The Damage object being used to track the damage.
/// * `timestamp` - Time when the event was generated (in milliseconds).
/// * `area` - Damaged area of the drawable.
/// * `geometry` - Total area of the drawable.
///
/// # See
///
/// * `Create`: request
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NotifyEvent {
pub response_type: u8,
pub level: ReportLevel,
pub sequence: u16,
pub drawable: xproto::Drawable,
pub damage: Damage,
pub timestamp: xproto::Timestamp,
pub area: xproto::Rectangle,
pub geometry: xproto::Rectangle,
}
impl_debug_if_no_extra_traits!(NotifyEvent, "NotifyEvent");
impl TryParse for NotifyEvent {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (level, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (drawable, remaining) = xproto::Drawable::try_parse(remaining)?;
let (damage, remaining) = Damage::try_parse(remaining)?;
let (timestamp, remaining) = xproto::Timestamp::try_parse(remaining)?;
let (area, remaining) = xproto::Rectangle::try_parse(remaining)?;
let (geometry, remaining) = xproto::Rectangle::try_parse(remaining)?;
let level = level.into();
let result = NotifyEvent { response_type, level, sequence, drawable, damage, timestamp, area, geometry };
let _ = remaining;
let remaining = initial_value.get(32..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for NotifyEvent {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = self.response_type.serialize();
let level_bytes = u8::from(self.level).serialize();
let sequence_bytes = self.sequence.serialize();
let drawable_bytes = self.drawable.serialize();
let damage_bytes = self.damage.serialize();
let timestamp_bytes = self.timestamp.serialize();
let area_bytes = self.area.serialize();
let geometry_bytes = self.geometry.serialize();
[
response_type_bytes[0],
level_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
drawable_bytes[0],
drawable_bytes[1],
drawable_bytes[2],
drawable_bytes[3],
damage_bytes[0],
damage_bytes[1],
damage_bytes[2],
damage_bytes[3],
timestamp_bytes[0],
timestamp_bytes[1],
timestamp_bytes[2],
timestamp_bytes[3],
area_bytes[0],
area_bytes[1],
area_bytes[2],
area_bytes[3],
area_bytes[4],
area_bytes[5],
area_bytes[6],
area_bytes[7],
geometry_bytes[0],
geometry_bytes[1],
geometry_bytes[2],
geometry_bytes[3],
geometry_bytes[4],
geometry_bytes[5],
geometry_bytes[6],
geometry_bytes[7],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
self.response_type.serialize_into(bytes);
u8::from(self.level).serialize_into(bytes);
self.sequence.serialize_into(bytes);
self.drawable.serialize_into(bytes);
self.damage.serialize_into(bytes);
self.timestamp.serialize_into(bytes);
self.area.serialize_into(bytes);
self.geometry.serialize_into(bytes);
}
}
impl From<&NotifyEvent> for [u8; 32] {
fn from(input: &NotifyEvent) -> Self {
let response_type_bytes = input.response_type.serialize();
let level_bytes = u8::from(input.level).serialize();
let sequence_bytes = input.sequence.serialize();
let drawable_bytes = input.drawable.serialize();
let damage_bytes = input.damage.serialize();
let timestamp_bytes = input.timestamp.serialize();
let area_bytes = input.area.serialize();
let geometry_bytes = input.geometry.serialize();
[
response_type_bytes[0],
level_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
drawable_bytes[0],
drawable_bytes[1],
drawable_bytes[2],
drawable_bytes[3],
damage_bytes[0],
damage_bytes[1],
damage_bytes[2],
damage_bytes[3],
timestamp_bytes[0],
timestamp_bytes[1],
timestamp_bytes[2],
timestamp_bytes[3],
area_bytes[0],
area_bytes[1],
area_bytes[2],
area_bytes[3],
area_bytes[4],
area_bytes[5],
area_bytes[6],
area_bytes[7],
geometry_bytes[0],
geometry_bytes[1],
geometry_bytes[2],
geometry_bytes[3],
geometry_bytes[4],
geometry_bytes[5],
geometry_bytes[6],
geometry_bytes[7],
]
}
}
impl From<NotifyEvent> for [u8; 32] {
fn from(input: NotifyEvent) -> Self {
Self::from(&input)
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+183
View File
@@ -0,0 +1,183 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `GenericEvent` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "Generic Event Extension";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 0);
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionRequest {
pub client_major_version: u16,
pub client_minor_version: u16,
}
impl_debug_if_no_extra_traits!(QueryVersionRequest, "QueryVersionRequest");
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let client_major_version_bytes = self.client_major_version.serialize();
let client_minor_version_bytes = self.client_minor_version.serialize();
let mut request0 = vec![
major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
client_major_version_bytes[0],
client_major_version_bytes[1],
client_minor_version_bytes[0],
client_minor_version_bytes[1],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (client_major_version, remaining) = u16::try_parse(value)?;
let (client_minor_version, remaining) = u16::try_parse(remaining)?;
let _ = remaining;
Ok(QueryVersionRequest {
client_major_version,
client_minor_version,
})
}
}
impl Request for QueryVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryVersionRequest {
type Reply = QueryVersionReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub major_version: u16,
pub minor_version: u16,
}
impl_debug_if_no_extra_traits!(QueryVersionReply, "QueryVersionReply");
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (major_version, remaining) = u16::try_parse(remaining)?;
let (minor_version, remaining) = u16::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, major_version, minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryVersionReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let major_version_bytes = self.major_version.serialize();
let minor_version_bytes = self.minor_version.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
major_version_bytes[0],
major_version_bytes[1],
minor_version_bytes[0],
minor_version_bytes[1],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.major_version.serialize_into(bytes);
self.minor_version.serialize_into(bytes);
bytes.extend_from_slice(&[0; 20]);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+399
View File
@@ -0,0 +1,399 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `XCMisc` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "XC-MISC";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 1);
/// Opcode for the GetVersion request
pub const GET_VERSION_REQUEST: u8 = 0;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetVersionRequest {
pub client_major_version: u16,
pub client_minor_version: u16,
}
impl_debug_if_no_extra_traits!(GetVersionRequest, "GetVersionRequest");
impl GetVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let client_major_version_bytes = self.client_major_version.serialize();
let client_minor_version_bytes = self.client_minor_version.serialize();
let mut request0 = vec![
major_opcode,
GET_VERSION_REQUEST,
0,
0,
client_major_version_bytes[0],
client_major_version_bytes[1],
client_minor_version_bytes[0],
client_minor_version_bytes[1],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (client_major_version, remaining) = u16::try_parse(value)?;
let (client_minor_version, remaining) = u16::try_parse(remaining)?;
let _ = remaining;
Ok(GetVersionRequest {
client_major_version,
client_minor_version,
})
}
}
impl Request for GetVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetVersionRequest {
type Reply = GetVersionReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetVersionReply {
pub sequence: u16,
pub length: u32,
pub server_major_version: u16,
pub server_minor_version: u16,
}
impl_debug_if_no_extra_traits!(GetVersionReply, "GetVersionReply");
impl TryParse for GetVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (server_major_version, remaining) = u16::try_parse(remaining)?;
let (server_minor_version, remaining) = u16::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetVersionReply { sequence, length, server_major_version, server_minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetVersionReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let server_major_version_bytes = self.server_major_version.serialize();
let server_minor_version_bytes = self.server_minor_version.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
server_major_version_bytes[0],
server_major_version_bytes[1],
server_minor_version_bytes[0],
server_minor_version_bytes[1],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.server_major_version.serialize_into(bytes);
self.server_minor_version.serialize_into(bytes);
}
}
/// Opcode for the GetXIDRange request
pub const GET_XID_RANGE_REQUEST: u8 = 1;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetXIDRangeRequest;
impl_debug_if_no_extra_traits!(GetXIDRangeRequest, "GetXIDRangeRequest");
impl GetXIDRangeRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let mut request0 = vec![
major_opcode,
GET_XID_RANGE_REQUEST,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_XID_RANGE_REQUEST {
return Err(ParseError::InvalidValue);
}
let _ = value;
Ok(GetXIDRangeRequest
)
}
}
impl Request for GetXIDRangeRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetXIDRangeRequest {
type Reply = GetXIDRangeReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetXIDRangeReply {
pub sequence: u16,
pub length: u32,
pub start_id: u32,
pub count: u32,
}
impl_debug_if_no_extra_traits!(GetXIDRangeReply, "GetXIDRangeReply");
impl TryParse for GetXIDRangeReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (start_id, remaining) = u32::try_parse(remaining)?;
let (count, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetXIDRangeReply { sequence, length, start_id, count };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetXIDRangeReply {
type Bytes = [u8; 16];
fn serialize(&self) -> [u8; 16] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let start_id_bytes = self.start_id.serialize();
let count_bytes = self.count.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
start_id_bytes[0],
start_id_bytes[1],
start_id_bytes[2],
start_id_bytes[3],
count_bytes[0],
count_bytes[1],
count_bytes[2],
count_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(16);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.start_id.serialize_into(bytes);
self.count.serialize_into(bytes);
}
}
/// Opcode for the GetXIDList request
pub const GET_XID_LIST_REQUEST: u8 = 2;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetXIDListRequest {
pub count: u32,
}
impl_debug_if_no_extra_traits!(GetXIDListRequest, "GetXIDListRequest");
impl GetXIDListRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let count_bytes = self.count.serialize();
let mut request0 = vec![
major_opcode,
GET_XID_LIST_REQUEST,
0,
0,
count_bytes[0],
count_bytes[1],
count_bytes[2],
count_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_XID_LIST_REQUEST {
return Err(ParseError::InvalidValue);
}
let (count, remaining) = u32::try_parse(value)?;
let _ = remaining;
Ok(GetXIDListRequest {
count,
})
}
}
impl Request for GetXIDListRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetXIDListRequest {
type Reply = GetXIDListReply;
}
#[derive(Clone, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetXIDListReply {
pub sequence: u16,
pub length: u32,
pub ids: Vec<u32>,
}
impl_debug_if_no_extra_traits!(GetXIDListReply, "GetXIDListReply");
impl TryParse for GetXIDListReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (ids_len, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
let (ids, remaining) = crate::x11_utils::parse_list::<u32>(remaining, ids_len.try_to_usize()?)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetXIDListReply { sequence, length, ids };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetXIDListReply {
type Bytes = Vec<u8>;
fn serialize(&self) -> Vec<u8> {
let mut result = Vec::new();
self.serialize_into(&mut result);
result
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
let ids_len = u32::try_from(self.ids.len()).expect("`ids` has too many elements");
ids_len.serialize_into(bytes);
bytes.extend_from_slice(&[0; 20]);
self.ids.serialize_into(bytes);
}
}
impl GetXIDListReply {
/// Get the value of the `ids_len` field.
///
/// The `ids_len` field is used as the length field of the `ids` field.
/// This function computes the field's value again based on the length of the list.
///
/// # Panics
///
/// Panics if the value cannot be represented in the target type. This
/// cannot happen with values of the struct received from the X11 server.
pub fn ids_len(&self) -> u32 {
self.ids.len()
.try_into().unwrap()
}
}
+952
View File
@@ -0,0 +1,952 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Xevie` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "XEVIE";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 0);
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionRequest {
pub client_major_version: u16,
pub client_minor_version: u16,
}
impl_debug_if_no_extra_traits!(QueryVersionRequest, "QueryVersionRequest");
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let client_major_version_bytes = self.client_major_version.serialize();
let client_minor_version_bytes = self.client_minor_version.serialize();
let mut request0 = vec![
major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
client_major_version_bytes[0],
client_major_version_bytes[1],
client_minor_version_bytes[0],
client_minor_version_bytes[1],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (client_major_version, remaining) = u16::try_parse(value)?;
let (client_minor_version, remaining) = u16::try_parse(remaining)?;
let _ = remaining;
Ok(QueryVersionRequest {
client_major_version,
client_minor_version,
})
}
}
impl Request for QueryVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryVersionRequest {
type Reply = QueryVersionReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub server_major_version: u16,
pub server_minor_version: u16,
}
impl_debug_if_no_extra_traits!(QueryVersionReply, "QueryVersionReply");
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (server_major_version, remaining) = u16::try_parse(remaining)?;
let (server_minor_version, remaining) = u16::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, server_major_version, server_minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryVersionReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let server_major_version_bytes = self.server_major_version.serialize();
let server_minor_version_bytes = self.server_minor_version.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
server_major_version_bytes[0],
server_major_version_bytes[1],
server_minor_version_bytes[0],
server_minor_version_bytes[1],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.server_major_version.serialize_into(bytes);
self.server_minor_version.serialize_into(bytes);
bytes.extend_from_slice(&[0; 20]);
}
}
/// Opcode for the Start request
pub const START_REQUEST: u8 = 1;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StartRequest {
pub screen: u32,
}
impl_debug_if_no_extra_traits!(StartRequest, "StartRequest");
impl StartRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let screen_bytes = self.screen.serialize();
let mut request0 = vec![
major_opcode,
START_REQUEST,
0,
0,
screen_bytes[0],
screen_bytes[1],
screen_bytes[2],
screen_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != START_REQUEST {
return Err(ParseError::InvalidValue);
}
let (screen, remaining) = u32::try_parse(value)?;
let _ = remaining;
Ok(StartRequest {
screen,
})
}
}
impl Request for StartRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for StartRequest {
type Reply = StartReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StartReply {
pub sequence: u16,
pub length: u32,
}
impl_debug_if_no_extra_traits!(StartReply, "StartReply");
impl TryParse for StartReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(24..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = StartReply { sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for StartReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
bytes.extend_from_slice(&[0; 24]);
}
}
/// Opcode for the End request
pub const END_REQUEST: u8 = 2;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EndRequest {
pub cmap: u32,
}
impl_debug_if_no_extra_traits!(EndRequest, "EndRequest");
impl EndRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let cmap_bytes = self.cmap.serialize();
let mut request0 = vec![
major_opcode,
END_REQUEST,
0,
0,
cmap_bytes[0],
cmap_bytes[1],
cmap_bytes[2],
cmap_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != END_REQUEST {
return Err(ParseError::InvalidValue);
}
let (cmap, remaining) = u32::try_parse(value)?;
let _ = remaining;
Ok(EndRequest {
cmap,
})
}
}
impl Request for EndRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for EndRequest {
type Reply = EndReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EndReply {
pub sequence: u16,
pub length: u32,
}
impl_debug_if_no_extra_traits!(EndReply, "EndReply");
impl TryParse for EndReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(24..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = EndReply { sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for EndReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
bytes.extend_from_slice(&[0; 24]);
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Datatype(bool);
impl Datatype {
pub const UNMODIFIED: Self = Self(false);
pub const MODIFIED: Self = Self(true);
}
impl From<Datatype> for bool {
#[inline]
fn from(input: Datatype) -> Self {
input.0
}
}
impl From<Datatype> for Option<bool> {
#[inline]
fn from(input: Datatype) -> Self {
Some(input.0)
}
}
impl From<Datatype> for u8 {
#[inline]
fn from(input: Datatype) -> Self {
u8::from(input.0)
}
}
impl From<Datatype> for Option<u8> {
#[inline]
fn from(input: Datatype) -> Self {
Some(u8::from(input.0))
}
}
impl From<Datatype> for u16 {
#[inline]
fn from(input: Datatype) -> Self {
u16::from(input.0)
}
}
impl From<Datatype> for Option<u16> {
#[inline]
fn from(input: Datatype) -> Self {
Some(u16::from(input.0))
}
}
impl From<Datatype> for u32 {
#[inline]
fn from(input: Datatype) -> Self {
u32::from(input.0)
}
}
impl From<Datatype> for Option<u32> {
#[inline]
fn from(input: Datatype) -> Self {
Some(u32::from(input.0))
}
}
impl From<bool> for Datatype {
#[inline]
fn from(value: bool) -> Self {
Self(value)
}
}
impl core::fmt::Debug for Datatype {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let variants = [
(Self::UNMODIFIED.0.into(), "UNMODIFIED", "Unmodified"),
(Self::MODIFIED.0.into(), "MODIFIED", "Modified"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Event {
}
impl_debug_if_no_extra_traits!(Event, "Event");
impl TryParse for Event {
fn try_parse(remaining: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = remaining.get(32..).ok_or(ParseError::InsufficientData)?;
let result = Event { };
Ok((result, remaining))
}
}
impl Serialize for Event {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
bytes.extend_from_slice(&[0; 32]);
}
}
/// Opcode for the Send request
pub const SEND_REQUEST: u8 = 3;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SendRequest {
pub event: Event,
pub data_type: u32,
}
impl_debug_if_no_extra_traits!(SendRequest, "SendRequest");
impl SendRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let event_bytes = self.event.serialize();
let data_type_bytes = self.data_type.serialize();
let mut request0 = vec![
major_opcode,
SEND_REQUEST,
0,
0,
event_bytes[0],
event_bytes[1],
event_bytes[2],
event_bytes[3],
event_bytes[4],
event_bytes[5],
event_bytes[6],
event_bytes[7],
event_bytes[8],
event_bytes[9],
event_bytes[10],
event_bytes[11],
event_bytes[12],
event_bytes[13],
event_bytes[14],
event_bytes[15],
event_bytes[16],
event_bytes[17],
event_bytes[18],
event_bytes[19],
event_bytes[20],
event_bytes[21],
event_bytes[22],
event_bytes[23],
event_bytes[24],
event_bytes[25],
event_bytes[26],
event_bytes[27],
event_bytes[28],
event_bytes[29],
event_bytes[30],
event_bytes[31],
data_type_bytes[0],
data_type_bytes[1],
data_type_bytes[2],
data_type_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != SEND_REQUEST {
return Err(ParseError::InvalidValue);
}
let (event, remaining) = Event::try_parse(value)?;
let (data_type, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(64..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(SendRequest {
event,
data_type,
})
}
}
impl Request for SendRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for SendRequest {
type Reply = SendReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SendReply {
pub sequence: u16,
pub length: u32,
}
impl_debug_if_no_extra_traits!(SendReply, "SendReply");
impl TryParse for SendReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(24..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = SendReply { sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for SendReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
bytes.extend_from_slice(&[0; 24]);
}
}
/// Opcode for the SelectInput request
pub const SELECT_INPUT_REQUEST: u8 = 4;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SelectInputRequest {
pub event_mask: u32,
}
impl_debug_if_no_extra_traits!(SelectInputRequest, "SelectInputRequest");
impl SelectInputRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let event_mask_bytes = self.event_mask.serialize();
let mut request0 = vec![
major_opcode,
SELECT_INPUT_REQUEST,
0,
0,
event_mask_bytes[0],
event_mask_bytes[1],
event_mask_bytes[2],
event_mask_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != SELECT_INPUT_REQUEST {
return Err(ParseError::InvalidValue);
}
let (event_mask, remaining) = u32::try_parse(value)?;
let _ = remaining;
Ok(SelectInputRequest {
event_mask,
})
}
}
impl Request for SelectInputRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for SelectInputRequest {
type Reply = SelectInputReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SelectInputReply {
pub sequence: u16,
pub length: u32,
}
impl_debug_if_no_extra_traits!(SelectInputReply, "SelectInputReply");
impl TryParse for SelectInputReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(24..).ok_or(ParseError::InsufficientData)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = SelectInputReply { sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for SelectInputReply {
type Bytes = [u8; 32];
fn serialize(&self) -> [u8; 32] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
bytes.extend_from_slice(&[0; 24]);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+818
View File
@@ -0,0 +1,818 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Xinerama` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
#[allow(unused_imports)]
use super::xproto;
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "XINERAMA";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 1);
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ScreenInfo {
pub x_org: i16,
pub y_org: i16,
pub width: u16,
pub height: u16,
}
impl_debug_if_no_extra_traits!(ScreenInfo, "ScreenInfo");
impl TryParse for ScreenInfo {
fn try_parse(remaining: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let (x_org, remaining) = i16::try_parse(remaining)?;
let (y_org, remaining) = i16::try_parse(remaining)?;
let (width, remaining) = u16::try_parse(remaining)?;
let (height, remaining) = u16::try_parse(remaining)?;
let result = ScreenInfo { x_org, y_org, width, height };
Ok((result, remaining))
}
}
impl Serialize for ScreenInfo {
type Bytes = [u8; 8];
fn serialize(&self) -> [u8; 8] {
let x_org_bytes = self.x_org.serialize();
let y_org_bytes = self.y_org.serialize();
let width_bytes = self.width.serialize();
let height_bytes = self.height.serialize();
[
x_org_bytes[0],
x_org_bytes[1],
y_org_bytes[0],
y_org_bytes[1],
width_bytes[0],
width_bytes[1],
height_bytes[0],
height_bytes[1],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(8);
self.x_org.serialize_into(bytes);
self.y_org.serialize_into(bytes);
self.width.serialize_into(bytes);
self.height.serialize_into(bytes);
}
}
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionRequest {
pub major: u8,
pub minor: u8,
}
impl_debug_if_no_extra_traits!(QueryVersionRequest, "QueryVersionRequest");
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let major_bytes = self.major.serialize();
let minor_bytes = self.minor.serialize();
let mut request0 = vec![
major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
major_bytes[0],
minor_bytes[0],
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (major, remaining) = u8::try_parse(value)?;
let (minor, remaining) = u8::try_parse(remaining)?;
let _ = remaining;
Ok(QueryVersionRequest {
major,
minor,
})
}
}
impl Request for QueryVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryVersionRequest {
type Reply = QueryVersionReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub major: u16,
pub minor: u16,
}
impl_debug_if_no_extra_traits!(QueryVersionReply, "QueryVersionReply");
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (major, remaining) = u16::try_parse(remaining)?;
let (minor, remaining) = u16::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, major, minor };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryVersionReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let major_bytes = self.major.serialize();
let minor_bytes = self.minor.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
major_bytes[0],
major_bytes[1],
minor_bytes[0],
minor_bytes[1],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.major.serialize_into(bytes);
self.minor.serialize_into(bytes);
}
}
/// Opcode for the GetState request
pub const GET_STATE_REQUEST: u8 = 1;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetStateRequest {
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetStateRequest, "GetStateRequest");
impl GetStateRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let mut request0 = vec![
major_opcode,
GET_STATE_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_STATE_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(GetStateRequest {
window,
})
}
}
impl Request for GetStateRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetStateRequest {
type Reply = GetStateReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetStateReply {
pub state: u8,
pub sequence: u16,
pub length: u32,
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetStateReply, "GetStateReply");
impl TryParse for GetStateReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (state, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (window, remaining) = xproto::Window::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetStateReply { state, sequence, length, window };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetStateReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let state_bytes = self.state.serialize();
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let window_bytes = self.window.serialize();
[
response_type_bytes[0],
state_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
self.state.serialize_into(bytes);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.window.serialize_into(bytes);
}
}
/// Opcode for the GetScreenCount request
pub const GET_SCREEN_COUNT_REQUEST: u8 = 2;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetScreenCountRequest {
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetScreenCountRequest, "GetScreenCountRequest");
impl GetScreenCountRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let mut request0 = vec![
major_opcode,
GET_SCREEN_COUNT_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_SCREEN_COUNT_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(GetScreenCountRequest {
window,
})
}
}
impl Request for GetScreenCountRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetScreenCountRequest {
type Reply = GetScreenCountReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetScreenCountReply {
pub screen_count: u8,
pub sequence: u16,
pub length: u32,
pub window: xproto::Window,
}
impl_debug_if_no_extra_traits!(GetScreenCountReply, "GetScreenCountReply");
impl TryParse for GetScreenCountReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (screen_count, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (window, remaining) = xproto::Window::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetScreenCountReply { screen_count, sequence, length, window };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetScreenCountReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let screen_count_bytes = self.screen_count.serialize();
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let window_bytes = self.window.serialize();
[
response_type_bytes[0],
screen_count_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
self.screen_count.serialize_into(bytes);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.window.serialize_into(bytes);
}
}
/// Opcode for the GetScreenSize request
pub const GET_SCREEN_SIZE_REQUEST: u8 = 3;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetScreenSizeRequest {
pub window: xproto::Window,
pub screen: u32,
}
impl_debug_if_no_extra_traits!(GetScreenSizeRequest, "GetScreenSizeRequest");
impl GetScreenSizeRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let screen_bytes = self.screen.serialize();
let mut request0 = vec![
major_opcode,
GET_SCREEN_SIZE_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
screen_bytes[0],
screen_bytes[1],
screen_bytes[2],
screen_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_SCREEN_SIZE_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (screen, remaining) = u32::try_parse(remaining)?;
let _ = remaining;
Ok(GetScreenSizeRequest {
window,
screen,
})
}
}
impl Request for GetScreenSizeRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetScreenSizeRequest {
type Reply = GetScreenSizeReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetScreenSizeReply {
pub sequence: u16,
pub length: u32,
pub width: u32,
pub height: u32,
pub window: xproto::Window,
pub screen: u32,
}
impl_debug_if_no_extra_traits!(GetScreenSizeReply, "GetScreenSizeReply");
impl TryParse for GetScreenSizeReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (width, remaining) = u32::try_parse(remaining)?;
let (height, remaining) = u32::try_parse(remaining)?;
let (window, remaining) = xproto::Window::try_parse(remaining)?;
let (screen, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetScreenSizeReply { sequence, length, width, height, window, screen };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetScreenSizeReply {
type Bytes = [u8; 24];
fn serialize(&self) -> [u8; 24] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let width_bytes = self.width.serialize();
let height_bytes = self.height.serialize();
let window_bytes = self.window.serialize();
let screen_bytes = self.screen.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
width_bytes[0],
width_bytes[1],
width_bytes[2],
width_bytes[3],
height_bytes[0],
height_bytes[1],
height_bytes[2],
height_bytes[3],
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
screen_bytes[0],
screen_bytes[1],
screen_bytes[2],
screen_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(24);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.width.serialize_into(bytes);
self.height.serialize_into(bytes);
self.window.serialize_into(bytes);
self.screen.serialize_into(bytes);
}
}
/// Opcode for the IsActive request
pub const IS_ACTIVE_REQUEST: u8 = 4;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IsActiveRequest;
impl_debug_if_no_extra_traits!(IsActiveRequest, "IsActiveRequest");
impl IsActiveRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let mut request0 = vec![
major_opcode,
IS_ACTIVE_REQUEST,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != IS_ACTIVE_REQUEST {
return Err(ParseError::InvalidValue);
}
let _ = value;
Ok(IsActiveRequest
)
}
}
impl Request for IsActiveRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for IsActiveRequest {
type Reply = IsActiveReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IsActiveReply {
pub sequence: u16,
pub length: u32,
pub state: u32,
}
impl_debug_if_no_extra_traits!(IsActiveReply, "IsActiveReply");
impl TryParse for IsActiveReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (state, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = IsActiveReply { sequence, length, state };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for IsActiveReply {
type Bytes = [u8; 12];
fn serialize(&self) -> [u8; 12] {
let response_type_bytes = &[1];
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let state_bytes = self.state.serialize();
[
response_type_bytes[0],
0,
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
state_bytes[0],
state_bytes[1],
state_bytes[2],
state_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(12);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.state.serialize_into(bytes);
}
}
/// Opcode for the QueryScreens request
pub const QUERY_SCREENS_REQUEST: u8 = 5;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryScreensRequest;
impl_debug_if_no_extra_traits!(QueryScreensRequest, "QueryScreensRequest");
impl QueryScreensRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let mut request0 = vec![
major_opcode,
QUERY_SCREENS_REQUEST,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_SCREENS_REQUEST {
return Err(ParseError::InvalidValue);
}
let _ = value;
Ok(QueryScreensRequest
)
}
}
impl Request for QueryScreensRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for QueryScreensRequest {
type Reply = QueryScreensReply;
}
#[derive(Clone, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QueryScreensReply {
pub sequence: u16,
pub length: u32,
pub screen_info: Vec<ScreenInfo>,
}
impl_debug_if_no_extra_traits!(QueryScreensReply, "QueryScreensReply");
impl TryParse for QueryScreensReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (number, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
let (screen_info, remaining) = crate::x11_utils::parse_list::<ScreenInfo>(remaining, number.try_to_usize()?)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryScreensReply { sequence, length, screen_info };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for QueryScreensReply {
type Bytes = Vec<u8>;
fn serialize(&self) -> Vec<u8> {
let mut result = Vec::new();
self.serialize_into(&mut result);
result
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(32);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
bytes.extend_from_slice(&[0; 1]);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
let number = u32::try_from(self.screen_info.len()).expect("`screen_info` has too many elements");
number.serialize_into(bytes);
bytes.extend_from_slice(&[0; 20]);
self.screen_info.serialize_into(bytes);
}
}
impl QueryScreensReply {
/// Get the value of the `number` field.
///
/// The `number` field is used as the length field of the `screen_info` field.
/// This function computes the field's value again based on the length of the list.
///
/// # Panics
///
/// Panics if the value cannot be represented in the target type. This
/// cannot happen with values of the struct received from the X11 server.
pub fn number(&self) -> u32 {
self.screen_info.len()
.try_into().unwrap()
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+518
View File
@@ -0,0 +1,518 @@
// This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Test` X11 extension.
#![allow(clippy::too_many_arguments)]
// The code generator is simpler if it can always use conversions
#![allow(clippy::useless_conversion)]
#[allow(unused_imports)]
use alloc::borrow::Cow;
#[allow(unused_imports)]
use core::convert::TryInto;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use crate::errors::ParseError;
#[allow(unused_imports)]
use crate::x11_utils::TryIntoUSize;
use crate::BufWithFds;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
#[allow(unused_imports)]
use super::xproto;
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "XTEST";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (2, 2);
/// Opcode for the GetVersion request
pub const GET_VERSION_REQUEST: u8 = 0;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetVersionRequest {
pub major_version: u8,
pub minor_version: u16,
}
impl_debug_if_no_extra_traits!(GetVersionRequest, "GetVersionRequest");
impl GetVersionRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let major_version_bytes = self.major_version.serialize();
let minor_version_bytes = self.minor_version.serialize();
let mut request0 = vec![
major_opcode,
GET_VERSION_REQUEST,
0,
0,
major_version_bytes[0],
0,
minor_version_bytes[0],
minor_version_bytes[1],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let (major_version, remaining) = u8::try_parse(value)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (minor_version, remaining) = u16::try_parse(remaining)?;
let _ = remaining;
Ok(GetVersionRequest {
major_version,
minor_version,
})
}
}
impl Request for GetVersionRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for GetVersionRequest {
type Reply = GetVersionReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GetVersionReply {
pub major_version: u8,
pub sequence: u16,
pub length: u32,
pub minor_version: u16,
}
impl_debug_if_no_extra_traits!(GetVersionReply, "GetVersionReply");
impl TryParse for GetVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (major_version, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (minor_version, remaining) = u16::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = GetVersionReply { major_version, sequence, length, minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for GetVersionReply {
type Bytes = [u8; 10];
fn serialize(&self) -> [u8; 10] {
let response_type_bytes = &[1];
let major_version_bytes = self.major_version.serialize();
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
let minor_version_bytes = self.minor_version.serialize();
[
response_type_bytes[0],
major_version_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
minor_version_bytes[0],
minor_version_bytes[1],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(10);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
self.major_version.serialize_into(bytes);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
self.minor_version.serialize_into(bytes);
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Cursor(bool);
impl Cursor {
pub const NONE: Self = Self(false);
pub const CURRENT: Self = Self(true);
}
impl From<Cursor> for bool {
#[inline]
fn from(input: Cursor) -> Self {
input.0
}
}
impl From<Cursor> for Option<bool> {
#[inline]
fn from(input: Cursor) -> Self {
Some(input.0)
}
}
impl From<Cursor> for u8 {
#[inline]
fn from(input: Cursor) -> Self {
u8::from(input.0)
}
}
impl From<Cursor> for Option<u8> {
#[inline]
fn from(input: Cursor) -> Self {
Some(u8::from(input.0))
}
}
impl From<Cursor> for u16 {
#[inline]
fn from(input: Cursor) -> Self {
u16::from(input.0)
}
}
impl From<Cursor> for Option<u16> {
#[inline]
fn from(input: Cursor) -> Self {
Some(u16::from(input.0))
}
}
impl From<Cursor> for u32 {
#[inline]
fn from(input: Cursor) -> Self {
u32::from(input.0)
}
}
impl From<Cursor> for Option<u32> {
#[inline]
fn from(input: Cursor) -> Self {
Some(u32::from(input.0))
}
}
impl From<bool> for Cursor {
#[inline]
fn from(value: bool) -> Self {
Self(value)
}
}
impl core::fmt::Debug for Cursor {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let variants = [
(Self::NONE.0.into(), "NONE", "None"),
(Self::CURRENT.0.into(), "CURRENT", "Current"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
/// Opcode for the CompareCursor request
pub const COMPARE_CURSOR_REQUEST: u8 = 1;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CompareCursorRequest {
pub window: xproto::Window,
pub cursor: xproto::Cursor,
}
impl_debug_if_no_extra_traits!(CompareCursorRequest, "CompareCursorRequest");
impl CompareCursorRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let window_bytes = self.window.serialize();
let cursor_bytes = self.cursor.serialize();
let mut request0 = vec![
major_opcode,
COMPARE_CURSOR_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
cursor_bytes[0],
cursor_bytes[1],
cursor_bytes[2],
cursor_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != COMPARE_CURSOR_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (cursor, remaining) = xproto::Cursor::try_parse(remaining)?;
let _ = remaining;
Ok(CompareCursorRequest {
window,
cursor,
})
}
}
impl Request for CompareCursorRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::ReplyRequest for CompareCursorRequest {
type Reply = CompareCursorReply;
}
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CompareCursorReply {
pub same: bool,
pub sequence: u16,
pub length: u32,
}
impl_debug_if_no_extra_traits!(CompareCursorReply, "CompareCursorReply");
impl TryParse for CompareCursorReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (same, remaining) = bool::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = CompareCursorReply { same, sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl Serialize for CompareCursorReply {
type Bytes = [u8; 8];
fn serialize(&self) -> [u8; 8] {
let response_type_bytes = &[1];
let same_bytes = self.same.serialize();
let sequence_bytes = self.sequence.serialize();
let length_bytes = self.length.serialize();
[
response_type_bytes[0],
same_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
length_bytes[0],
length_bytes[1],
length_bytes[2],
length_bytes[3],
]
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
bytes.reserve(8);
let response_type_bytes = &[1];
bytes.push(response_type_bytes[0]);
self.same.serialize_into(bytes);
self.sequence.serialize_into(bytes);
self.length.serialize_into(bytes);
}
}
/// Opcode for the FakeInput request
pub const FAKE_INPUT_REQUEST: u8 = 2;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FakeInputRequest {
pub type_: u8,
pub detail: u8,
pub time: u32,
pub root: xproto::Window,
pub root_x: i16,
pub root_y: i16,
pub deviceid: u8,
}
impl_debug_if_no_extra_traits!(FakeInputRequest, "FakeInputRequest");
impl FakeInputRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let type_bytes = self.type_.serialize();
let detail_bytes = self.detail.serialize();
let time_bytes = self.time.serialize();
let root_bytes = self.root.serialize();
let root_x_bytes = self.root_x.serialize();
let root_y_bytes = self.root_y.serialize();
let deviceid_bytes = self.deviceid.serialize();
let mut request0 = vec![
major_opcode,
FAKE_INPUT_REQUEST,
0,
0,
type_bytes[0],
detail_bytes[0],
0,
0,
time_bytes[0],
time_bytes[1],
time_bytes[2],
time_bytes[3],
root_bytes[0],
root_bytes[1],
root_bytes[2],
root_bytes[3],
0,
0,
0,
0,
0,
0,
0,
0,
root_x_bytes[0],
root_x_bytes[1],
root_y_bytes[0],
root_y_bytes[1],
0,
0,
0,
0,
0,
0,
0,
deviceid_bytes[0],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != FAKE_INPUT_REQUEST {
return Err(ParseError::InvalidValue);
}
let (type_, remaining) = u8::try_parse(value)?;
let (detail, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(2..).ok_or(ParseError::InsufficientData)?;
let (time, remaining) = u32::try_parse(remaining)?;
let (root, remaining) = xproto::Window::try_parse(remaining)?;
let remaining = remaining.get(8..).ok_or(ParseError::InsufficientData)?;
let (root_x, remaining) = i16::try_parse(remaining)?;
let (root_y, remaining) = i16::try_parse(remaining)?;
let remaining = remaining.get(7..).ok_or(ParseError::InsufficientData)?;
let (deviceid, remaining) = u8::try_parse(remaining)?;
let _ = remaining;
Ok(FakeInputRequest {
type_,
detail,
time,
root,
root_x,
root_y,
deviceid,
})
}
}
impl Request for FakeInputRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for FakeInputRequest {
}
/// Opcode for the GrabControl request
pub const GRAB_CONTROL_REQUEST: u8 = 3;
#[derive(Clone, Copy, Default)]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GrabControlRequest {
pub impervious: bool,
}
impl_debug_if_no_extra_traits!(GrabControlRequest, "GrabControlRequest");
impl GrabControlRequest {
/// Serialize this request into bytes for the provided connection
pub fn serialize(self, major_opcode: u8) -> BufWithFds<[Cow<'static, [u8]>; 1]> {
let length_so_far = 0;
let impervious_bytes = self.impervious.serialize();
let mut request0 = vec![
major_opcode,
GRAB_CONTROL_REQUEST,
0,
0,
impervious_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
([request0.into()], vec![])
}
/// Parse this request given its header, its body, and any fds that go along with it
#[cfg(feature = "request-parsing")]
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GRAB_CONTROL_REQUEST {
return Err(ParseError::InvalidValue);
}
let (impervious, remaining) = bool::try_parse(value)?;
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(GrabControlRequest {
impervious,
})
}
}
impl Request for GrabControlRequest {
const EXTENSION_NAME: Option<&'static str> = Some(X11_EXTENSION_NAME);
fn serialize(self, major_opcode: u8) -> BufWithFds<Vec<u8>> {
let (bufs, fds) = self.serialize(major_opcode);
// Flatten the buffers into a single vector
let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect();
(buf, fds)
}
}
impl crate::x11_utils::VoidRequest for GrabControlRequest {
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+618
View File
@@ -0,0 +1,618 @@
//! Match Xrm entries against a query.
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use std::cmp::Ordering;
use super::parser::parse_query;
use super::{Binding, Component, Entry};
mod zip_longest {
/// Given two slices, produce an iterator that zips the two slices.
///
/// Compared to std::iter::Iterator::zip(), this iterator does not stop at the end of the
/// shorter of the two slices, but instead continues to the end of the longer slice. To make
/// this possible, the individual items are wrapped in `Option`.
///
/// See tests below to make this clearer.
pub(super) fn zip_longest<'a, T>(
a: &'a [T],
b: &'a [T],
) -> impl Iterator<Item = (Option<&'a T>, Option<&'a T>)> + 'a {
ZipLongest {
a: a.iter(),
b: b.iter(),
}
}
#[derive(Debug)]
struct ZipLongest<A, B> {
a: A,
b: B,
}
impl<A, B> Iterator for ZipLongest<A, B>
where
A: Iterator,
B: Iterator,
{
type Item = (Option<A::Item>, Option<B::Item>);
fn next(&mut self) -> Option<Self::Item> {
match (self.a.next(), self.b.next()) {
(None, None) => None,
(a, b) => Some((a, b)),
}
}
}
#[cfg(test)]
mod test_zip_longest {
use super::zip_longest;
use alloc::vec::Vec;
#[test]
fn empty() {
let (a, b): ([u8; 0], [u8; 0]) = ([], []);
let res = zip_longest(&a, &b).collect::<Vec<_>>();
assert_eq!(res, []);
}
#[test]
fn same_length() {
let a = [0, 1, 2];
let b = [4, 5, 6];
let expected = [
(Some(&0), Some(&4)),
(Some(&1), Some(&5)),
(Some(&2), Some(&6)),
];
let res = zip_longest(&a, &b).collect::<Vec<_>>();
assert_eq!(res, expected);
}
#[test]
fn first_shorter() {
let a = [0, 1];
let b = [4, 5, 6, 7];
let expected = [
(Some(&0), Some(&4)),
(Some(&1), Some(&5)),
(None, Some(&6)),
(None, Some(&7)),
];
let res = zip_longest(&a, &b).collect::<Vec<_>>();
assert_eq!(res, expected);
}
#[test]
fn second_shorter() {
let a = [0, 1, 2, 3];
let b = [4, 5];
let expected = [
(Some(&0), Some(&4)),
(Some(&1), Some(&5)),
(Some(&2), None),
(Some(&3), None),
];
let res = zip_longest(&a, &b).collect::<Vec<_>>();
assert_eq!(res, expected);
}
}
}
/// Info how a specific component was matched.
///
/// This information is used to decide which of two matches is "better" in `compare_matches()`.
#[derive(Debug, Copy, Clone)]
enum HowMatched {
/// The component matched the instance of the query
Instance,
/// The component matched the class of the query
Class,
/// The component is a wildcard and thus matched by default
Wildcard,
}
/// Info on how an (unskipped) component of the query was matched
///
/// This information is used to decide which of two matches is "better" in `compare_matches()`.
#[derive(Debug, Copy, Clone)]
struct MatchComponent {
preceding_binding: Binding,
how_matched: HowMatched,
}
/// Info how a (possibly skipped) component of the query was matched
///
/// This information is used to decide which of two matches is "better" in `compare_matches()`.
#[derive(Debug, Copy, Clone)]
enum MatchKind {
/// The component was skipped via a loose binding ("*")
SkippedViaLooseBinding,
/// The component was matched against the entry.
Matched(MatchComponent),
}
impl MatchKind {
/// Create a new `MatchKind::Match` with the given entries.
fn new_match(preceding_binding: Binding, how_matched: HowMatched) -> Self {
Self::Matched(MatchComponent {
preceding_binding,
how_matched,
})
}
}
fn check_match(entry: &Entry, resource: &[String], class: &[String]) -> Vec<Vec<MatchKind>> {
/// Current state of the matching machinery
#[derive(Debug, Default)]
struct MatchState {
/// Index into the entry on where we have to continue matching
index: usize,
/// How did we get to this state?
history: Vec<MatchKind>,
}
impl MatchState {
/// Record that a component was skipped via a loose binding (`*`).
fn skip_loose(&self) -> Self {
let mut history = self.history.clone();
history.push(MatchKind::SkippedViaLooseBinding);
Self {
index: self.index,
history,
}
}
/// Record that a component was matched in the given way.
fn step(mut self, kind: MatchKind) -> Self {
self.history.push(kind);
self.index += 1;
self
}
}
// The idea is to check if a nondeterministic finite automaton accepts a given
// word. We have a set of current states. This describes where in the
// entry we are while trying to match. When we match a component, we go to the next
// component in the entry (index + 1, `MatchState::step()`). When we have a loose binding, we
// can accept the current component by staying in the same state (index,
// `MatchState::skip_loose()`).
let mut states = vec![MatchState::default()];
// Go through the components and match them against the query
for (resource, class) in zip_longest::zip_longest(resource, class) {
let mut next_states = Vec::new();
for state in states.into_iter() {
if state.index == entry.components.len() {
// We are at the end of the entry and thus cannot continue this match.
// We drop this match state.
continue;
}
let binding = entry.components[state.index].0;
match binding {
// We have to match here, no way around that.
Binding::Tight => {}
// We could "eat" this with the loose binding by staying in the state
Binding::Loose => next_states.push(state.skip_loose()),
}
// Does the component match?
let kind = match entry.components[state.index].1 {
Component::Wildcard => Some(MatchKind::new_match(binding, HowMatched::Wildcard)),
Component::Normal(ref s) => {
if Some(s) == resource {
Some(MatchKind::new_match(binding, HowMatched::Instance))
} else if Some(s) == class {
Some(MatchKind::new_match(binding, HowMatched::Class))
} else {
None
}
}
};
if let Some(kind) = kind {
// Yes, the component matches and we go to the next state
next_states.push(state.step(kind));
}
}
states = next_states;
}
// We have a match if we reached the end of the components
states
.into_iter()
.filter(|s| s.index == entry.components.len())
.map(|s| s.history)
.collect()
}
/// Compare two matches and decide which one of the two is better (`Ordering::Greater`)
fn compare_matches(match1: &[MatchKind], match2: &[MatchKind]) -> Ordering {
use Binding::*;
use HowMatched::*;
use MatchKind::*;
fn rule1(match1: &MatchKind, match2: &MatchKind) -> Ordering {
// Precedence rule #1: Matching components (including wildcard '?') outweighs loose bindings ('*')
if let Matched(_) = match1 {
if let SkippedViaLooseBinding = match2 {
return Ordering::Greater;
}
}
Ordering::Equal
}
fn rule2(match1: &MatchKind, match2: &MatchKind) -> Ordering {
// Precedence rule #2a: Matching instance outweighs both matching class and wildcard
if let Matched(MatchComponent {
how_matched: Instance,
preceding_binding: _,
}) = match1
{
if let Matched(MatchComponent {
how_matched: Class,
preceding_binding: _,
}) = match2
{
return Ordering::Greater;
}
if let Matched(MatchComponent {
how_matched: Wildcard,
..
}) = match2
{
return Ordering::Greater;
}
}
// Precedence rule #2b: Matching class outweighs wildcard
if let Matched(MatchComponent {
how_matched: Class, ..
}) = match1
{
if let Matched(MatchComponent {
how_matched: Wildcard,
..
}) = match2
{
return Ordering::Greater;
}
}
Ordering::Equal
}
fn rule3(match1: &MatchKind, match2: &MatchKind) -> Ordering {
// Precedence rule #3: A preceding exact match outweights a preceding '*'
if let Matched(MatchComponent {
preceding_binding: Tight,
..
}) = match1
{
if let Matched(MatchComponent {
preceding_binding: Loose,
..
}) = match2
{
return Ordering::Greater;
}
}
Ordering::Equal
}
assert_eq!(
match1.len(),
match2.len(),
"Both matches should have the same length (which is guaranteed by the current \
implementation of check_match())"
);
for (m1, m2) in match1.iter().zip(match2.iter()) {
let ordering = rule1(m1, m2)
.then_with(|| rule1(m2, m1).reverse())
.then_with(|| rule2(m1, m2))
.then_with(|| rule2(m2, m1).reverse())
.then_with(|| rule3(m1, m2))
.then_with(|| rule3(m2, m1).reverse());
if ordering != Ordering::Equal {
return ordering;
}
}
Ordering::Equal
}
/// Find the best match for the given query in the database, returning `None` when nothing matches.
pub(crate) fn match_entry<'a>(
database: &'a [Entry],
resource: &str,
class: &str,
) -> Option<&'a [u8]> {
let resource = parse_query(resource.as_bytes())?;
let class = parse_query(class.as_bytes())?;
database
.iter()
// Filter for entries that match the query (and record some info on how they match)
.flat_map(|entry| {
let matches = check_match(entry, &resource, &class);
let best_match = matches
.into_iter()
.max_by(|match1, match2| compare_matches(match1, match2));
best_match.map(|m| (entry, m))
})
.max_by(|(_, match1), (_, match2)| compare_matches(match1, match2))
.map(|(entry, _)| &entry.value[..])
}
#[cfg(test)]
mod test {
use super::super::parser::parse_database;
use super::match_entry;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use std::eprintln;
// Most tests in here are based on [1], which is: Copyright © 2016 Ingo Bürk
// [1]: https://github.com/Airblader/xcb-util-xrm/blob/master/tests/tests_match.c
#[test]
fn test_matches() {
let tests = [
// Non-matches / Errors
(&b""[..], "", "", None),
// Xlib returns the match here, despite the query violating the specs (different number
// of components in the query)
(
b"First.second: 1",
"First.second",
"First.second.third",
None,
),
(b"", "First.second", "", None),
(b"First.second: 1", "First.third", "", None),
(b"First.second: 1", "First", "", None),
(b"First: 1", "First.second", "", None),
(b"First.?.fourth: 1", "First.second.third.fourth", "", None),
(b"First*?.third: 1", "First.third", "", None),
(b"First: 1", "first", "", None),
(b"First: 1", "", "first", None),
// Duplicate entries
(
b"First: 1\nFirst: 2\nFirst: 3\n",
"First",
"",
Some(&b"3"[..]),
),
(
b"First: 1\nSecond: 2\nSecond: 3\nThird: 4\n",
"Second",
"",
Some(b"3"),
),
// Basic matching
(b"First: 1", "First", "", Some(b"1")),
(b"First.second: 1", "First.second", "", Some(b"1")),
(b"?.second: 1", "First.second", "", Some(b"1")),
(b"First.?.third: 1", "First.second.third", "", Some(b"1")),
(
b"First.?.?.fourth: 1",
"First.second.third.fourth",
"",
Some(b"1"),
),
(b"*second: 1", "First.second", "", Some(b"1")),
(b".second: 1", "First.second", "", None),
(b"*third: 1", "First.second.third", "", Some(b"1")),
(b"First*second: 1", "First.second", "", Some(b"1")),
(b"First*third: 1", "First.second.third", "", Some(b"1")),
(
b"First*fourth: 1",
"First.second.third.fourth",
"",
Some(b"1"),
),
(b"First*?.third: 1", "First.second.third", "", Some(b"1")),
(b"First: 1", "Second", "First", Some(b"1")),
(
b"First.second: 1",
"First.third",
"first.second",
Some(b"1"),
),
(
b"First.second.third: 1",
"First.third.third",
"first.second.fourth",
Some(b"1"),
),
(
b"First*third*fifth: 1",
"First.second.third.fourth.third.fifth",
"",
Some(b"1"),
),
(b"First: x\\\ny", "First", "", Some(b"xy")),
(b"! First: x", "First", "", None),
(b"# First: x", "First", "", None),
(b"First:", "First", "", Some(b"")),
(b"First: ", "First", "", Some(b"")),
(b"First: \t ", "First", "", Some(b"")),
// Consecutive bindings
(b"*.bar: 1", "foo.foo.bar", "", Some(b"1")),
(b"...bar: 1", "foo.bar", "", None),
(b"...bar: 1", "foo.foo.foo.bar", "", None),
(b"***bar: 1", "foo.bar", "", Some(b"1")),
(b".*.bar: 1", "foo.bar", "", Some(b"1")),
(b".*.bar: 1", "foo.foo.bar", "", Some(b"1")),
(b"..*bar: 1", "foo.foo.foo.foo.bar", "", Some(b"1")),
(b"a.*.z: 1", "a.b.c.d.e.f.z", "", Some(b"1")),
(b"a...z: 1", "a.z", "", Some(b"1")),
(b"a...z: 1", "a.b.z", "", None),
// Matching among multiple entries
(b"First: 1\nSecond: 2\n", "First", "", Some(b"1")),
(b"First: 1\nSecond: 2\n", "Second", "", Some(b"2")),
// Greediness
(b"a*c.e: 1", "a.b.c.d.c.e", "", Some(b"1")),
(b"a*c.e: 1", "a.b.c.c.e", "", Some(b"1")),
(b"a*?.e: 1", "a.b.c.e", "", Some(b"1")),
(b"a*c*e: 1", "a.b.c.d.c.d.e.d.e", "", Some(b"1")),
// Precedence rules
// Rule 1
(
b"First.second.third: 1\nFirst*third: 2\n",
"First.second.third",
"",
Some(b"1"),
),
(
b"First*third: 2\nFirst.second.third: 1\n",
"First.second.third",
"",
Some(b"1"),
),
(
b"First.second.third: 1\nFirst*third: 2\n",
"x.x.x",
"First.second.third",
Some(b"1"),
),
(
b"First*third: 2\nFirst.second.third: 1\n",
"x.x.x",
"First.second.third",
Some(b"1"),
),
// Rule 2
(
b"First.second: 1\nFirst.third: 2\n",
"First.second",
"First.third",
Some(b"1"),
),
(
b"First.third: 2\nFirst.second: 1\n",
"First.second",
"First.third",
Some(b"1"),
),
(
b"First.second.third: 1\nFirst.?.third: 2\n",
"First.second.third",
"",
Some(b"1"),
),
(
b"First.?.third: 2\nFirst.second.third: 1\n",
"First.second.third",
"",
Some(b"1"),
),
(
b"First.second.third: 1\nFirst.?.third: 2\n",
"x.x.x",
"First.second.third",
Some(b"1"),
),
(
b"First.?.third: 2\nFirst.second.third: 1\n",
"x.x.x",
"First.second.third",
Some(b"1"),
),
// Rule 3
(
b"First.second: 1\nFirst*second: 2\n",
"First.second",
"",
Some(b"1"),
),
(
b"First*second: 2\nFirst.second: 1\n",
"First.second",
"",
Some(b"1"),
),
// Some real world examples. May contain duplicates to the above tests.
// From the specification:
// https://tronche.com/gui/x/xlib/resource-manager/matching-rules.html
(
b"xmh*Paned*activeForeground: red\n\
*incorporate.Foreground: blue\n\
xmh.toc*Command*activeForeground: green\n\
xmh.toc*?.Foreground: white\n\
xmh.toc*Command.activeForeground: black",
"xmh.toc.messagefunctions.incorporate.activeForeground",
"Xmh.Paned.Box.Command.Foreground",
Some(b"black"),
),
(
b"urxvt*background: [95]#000",
"urxvt.background",
"",
Some(b"[95]#000"),
),
(
b"urxvt*scrollBar_right:true",
"urxvt.scrollBar_right",
"",
Some(b"true"),
),
(
b"urxvt*cutchars: '\"'()*<>[]{|}",
"urxvt.cutchars",
"",
Some(b"'\"'()*<>[]{|}"),
),
(
b"urxvt.keysym.Control-Shift-Up: perl:font:increment",
"urxvt.keysym.Control-Shift-Up",
"",
Some(b"perl:font:increment"),
),
(
b"rofi.normal: #000000, #000000, #000000, #000000",
"rofi.normal",
"",
Some(b"#000000, #000000, #000000, #000000"),
),
// Own tests
(b"*foo.bar: 1", "bar", "", None),
(
b"First.Second.Third: 1\nFirst.Second: 2",
"First.Second.Third",
"First.Second",
Some(b"1"),
),
(
b"First.Second.Third: 1\nFirst.Second: 2",
"First.Second",
"First.Second.Third",
Some(b"1"),
),
];
let mut failures = 0;
for &(data, resource, class, expected) in tests.iter() {
let mut entries = Vec::new();
parse_database(data, &mut entries, |_, _| unreachable!());
let result = match_entry(&entries, resource, class);
if result != expected {
eprintln!(
"While testing resource '{resource}' and class '{class}' with the following input:"
);
eprintln!("{}", print_string(data));
eprintln!("Expected: {:?}", expected.map(print_string));
eprintln!("Got: {:?}", result.map(print_string));
eprintln!();
failures += 1;
}
}
if failures != 0 {
panic!("Had {} failures", failures)
}
}
fn print_string(data: &[u8]) -> String {
std::str::from_utf8(data)
.map(|s| s.to_string())
.unwrap_or_else(|_| format!("{data:?}"))
}
}
+408
View File
@@ -0,0 +1,408 @@
//! X11 resource manager library.
//!
//! To open a database, it is recommended to use [`Database::new_from_default`], but that function
//! needs to do I/O. A wrapper to simplify usage is e.g. provided in the x11rb crate.
//!
//! This functionality is similar to what is available to C code through xcb-util-xrm and Xlib's
//! `Xrm*` function family. Not all their functionality is available in this library. Please open a
//! feature request if you need something that is not available.
//!
//! The code in this module is only available when the `resource_manager` feature of the library is
//! enabled.
#![cfg(feature = "std")]
use std::env::var_os;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use alloc::string::String;
use alloc::vec::Vec;
use crate::protocol::xproto::{GetPropertyReply, GetPropertyRequest};
mod matcher;
mod parser;
/// Maximum nesting of #include directives, same value as Xlib uses.
/// After following this many `#include` directives, further includes are ignored.
const MAX_INCLUSION_DEPTH: u8 = 100;
/// How tightly does the component of an entry match a query?
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Binding {
/// We have a tight match, meaning that the next component of the entry must match the query.
Tight,
/// We have a loose match, meaning that any number of components can be skipped before the next
/// match.
Loose,
}
/// A component of a database entry.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Component {
/// A string component
Normal(String), // Actually just a-z, A-Z, 0-9 and _ or - is allowed
/// A wildcard component ("?") that matches anything
Wildcard,
}
/// A single entry in the resource manager database.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Entry {
/// The components of the entry describe which queries it matches
components: Vec<(Binding, Component)>,
/// The value of the entry is what the caller gets after a match.
value: Vec<u8>,
}
mod work_around_constant_limitations {
// For GET_RESOURCE_DATABASE, we need Into::into() to use AtomEnum, but that is not const.
// This module exists to work around that.
pub(super) const ATOM_RESOURCE_MANAGER: u32 = 23;
pub(super) const ATOM_STRING: u32 = 31;
#[test]
fn constants_are_correct() {
use crate::protocol::xproto::AtomEnum;
assert_eq!(u32::from(AtomEnum::RESOURCE_MANAGER), ATOM_RESOURCE_MANAGER);
assert_eq!(u32::from(AtomEnum::STRING), ATOM_STRING);
}
}
/// A X11 resource database.
///
/// The recommended way to load a database is through [`Database::new_from_default`].
#[derive(Debug, Default, Clone)]
pub struct Database {
entries: Vec<Entry>,
}
impl Database {
/// The GetPropertyRequest to load the X11 resource database from the root window.
///
/// Copy this struct, set its `window` field to the root window of the first screen send the
/// resulting request to the X11 server. The reply can be passed to
/// [`Self::new_from_default`].
pub const GET_RESOURCE_DATABASE: GetPropertyRequest = GetPropertyRequest {
delete: false,
window: 0,
property: work_around_constant_limitations::ATOM_RESOURCE_MANAGER,
type_: work_around_constant_limitations::ATOM_STRING,
long_offset: 0,
// This is what Xlib does, so it must be correct (tm)
long_length: 100_000_000,
};
/// Create a new X11 resource database from the default locations.
///
/// The `reply` argument should come from [`Self::GET_RESOURCE_DATABASE`] with its `window`
/// field set to the window ID of the first root window. The `hostname` argument should be the
/// hostname of the running system.
///
/// The default location is a combination of two places. First, the following places are
/// searched for data:
/// - The `RESOURCE_MANAGER` property of the first screen's root window (See
/// [`Self::GET_RESOURCE_DATABASE`] and [`Self::new_from_get_property_reply`]).
/// - If not found, the file `$HOME/.Xresources` is loaded.
/// - If not found, the file `$HOME/.Xdefaults` is loaded.
///
/// The result of the above search of the above search is combined with:
/// - The contents of the file `$XENVIRONMENT`, if this environment variable is set.
/// - Otherwise, the contents of `$HOME/.Xdefaults-[hostname]`.
///
/// This function only returns an error if communication with the X11 server fails. All other
/// errors are ignored. It might be that an empty database is returned.
///
/// The behaviour of this function is mostly equivalent to Xlib's `XGetDefault()`. The
/// exception is that `XGetDefault()` does not load `$HOME/.Xresources`.
///
/// The behaviour of this function is equivalent to xcb-util-xrm's
/// `xcb_xrm_database_from_default()`.
pub fn new_from_default(reply: &GetPropertyReply, hostname: OsString) -> Self {
let cur_dir = Path::new(".");
// 1. Try to load the RESOURCE_MANAGER property
let mut entries = if let Some(db) = Self::new_from_get_property_reply(reply) {
db.entries
} else {
let mut entries = Vec::new();
if let Some(home) = var_os("HOME") {
// 2. Otherwise, try to load $HOME/.Xresources
let mut path = PathBuf::from(&home);
path.push(".Xresources");
let read_something = if let Ok(data) = std::fs::read(&path) {
parse_data_with_base_directory(&mut entries, &data, Path::new(&home), 0);
true
} else {
false
};
// Restore the path so it refers to $HOME again
let _ = path.pop();
if !read_something {
// 3. Otherwise, try to load $HOME/.Xdefaults
path.push(".Xdefaults");
if let Ok(data) = std::fs::read(&path) {
parse_data_with_base_directory(&mut entries, &data, Path::new(&home), 0);
}
}
}
entries
};
// 4. If XENVIRONMENT is specified, merge the database defined by that file
if let Some(xenv) = var_os("XENVIRONMENT") {
if let Ok(data) = std::fs::read(&xenv) {
let base = Path::new(&xenv).parent().unwrap_or(cur_dir);
parse_data_with_base_directory(&mut entries, &data, base, 0);
}
} else {
// 5. Load `$HOME/.Xdefaults-[hostname]`
let mut file = OsString::from(".Xdefaults-");
file.push(hostname);
let mut path = match var_os("HOME") {
Some(home) => PathBuf::from(home),
None => PathBuf::new(),
};
path.push(file);
if let Ok(data) = std::fs::read(&path) {
let base = path.parent().unwrap_or(cur_dir);
parse_data_with_base_directory(&mut entries, &data, base, 0);
}
}
Self { entries }
}
/// Construct a new X11 resource database from a [`GetPropertyReply`].
///
/// The reply should come from [`Self::GET_RESOURCE_DATABASE`] with its `window` field set to
/// the window ID of the first root window.
pub fn new_from_get_property_reply(reply: &GetPropertyReply) -> Option<Database> {
if reply.format == 8 && !reply.value.is_empty() {
Some(Database::new_from_data(&reply.value))
} else {
None
}
}
/// Construct a new X11 resource database from raw data.
///
/// This function parses data like `Some.Entry: Value\n#include "some_file"\n` and returns the
/// resulting resource database. Parsing cannot fail since unparsable lines are simply ignored.
///
/// See [`Self::new_from_data_with_base_directory`] for a version that allows to provide a path that
/// is used for resolving relative `#include` statements.
pub fn new_from_data(data: &[u8]) -> Self {
let mut entries = Vec::new();
parse_data_with_base_directory(&mut entries, data, Path::new("."), 0);
Self { entries }
}
/// Construct a new X11 resource database from raw data.
///
/// This function parses data like `Some.Entry: Value\n#include "some_file"\n` and returns the
/// resulting resource database. Parsing cannot fail since unparsable lines are simply ignored.
///
/// When a relative `#include` statement is encountered, the file to include is searched
/// relative to the given `base_path`.
pub fn new_from_data_with_base_directory(data: &[u8], base_path: impl AsRef<Path>) -> Self {
fn helper(data: &[u8], base_path: &Path) -> Database {
let mut entries = Vec::new();
parse_data_with_base_directory(&mut entries, data, base_path, 0);
Database { entries }
}
helper(data, base_path.as_ref())
}
/// Get a value from the resource database as a byte slice.
///
/// The given values describe a query to the resource database. `resource_class` can be an
/// empty string, but otherwise must contain the same number of components as `resource_name`.
/// Both strings may only contain alphanumeric characters or '-', '_', and '.'.
///
/// For example, this is how Xterm could query one of its settings if it where written in Rust
/// (see `man xterm`):
/// ```
/// use x11rb_protocol::resource_manager::Database;
/// fn get_pointer_shape(db: &Database) -> &[u8] {
/// db.get_bytes("XTerm.vt100.pointerShape", "XTerm.VT100.Cursor").unwrap_or(b"xterm")
/// }
/// ```
pub fn get_bytes(&self, resource_name: &str, resource_class: &str) -> Option<&[u8]> {
matcher::match_entry(&self.entries, resource_name, resource_class)
}
/// Get a value from the resource database as a byte slice.
///
/// The given values describe a query to the resource database. `resource_class` can be an
/// empty string, but otherwise must contain the same number of components as `resource_name`.
/// Both strings may only contain alphanumeric characters or '-', '_', and '.'.
///
/// If an entry is found that is not a valid utf8 `str`, `None` is returned.
///
/// For example, this is how Xterm could query one of its settings if it where written in Rust
/// (see `man xterm`):
/// ```
/// use x11rb_protocol::resource_manager::Database;
/// fn get_pointer_shape(db: &Database) -> &str {
/// db.get_string("XTerm.vt100.pointerShape", "XTerm.VT100.Cursor").unwrap_or("xterm")
/// }
/// ```
pub fn get_string(&self, resource_name: &str, resource_class: &str) -> Option<&str> {
std::str::from_utf8(self.get_bytes(resource_name, resource_class)?).ok()
}
/// Get a value from the resource database as a byte slice.
///
/// The given values describe a query to the resource database. `resource_class` can be an
/// empty string, but otherwise must contain the same number of components as `resource_name`.
/// Both strings may only contain alphanumeric characters or '-', '_', and '.'.
///
/// This function interprets "true", "on", "yes" as true-ish and "false", "off", "no" als
/// false-ish. Numbers are parsed and are true if they are not zero. Unknown values are mapped
/// to `None`.
///
/// For example, this is how Xterm could query one of its settings if it where written in Rust
/// (see `man xterm`):
/// ```
/// use x11rb_protocol::resource_manager::Database;
/// fn get_bell_is_urgent(db: &Database) -> bool {
/// db.get_bool("XTerm.vt100.bellIsUrgent", "XTerm.VT100.BellIsUrgent").unwrap_or(false)
/// }
/// ```
pub fn get_bool(&self, resource_name: &str, resource_class: &str) -> Option<bool> {
to_bool(self.get_string(resource_name, resource_class)?)
}
/// Get a value from the resource database and parse it.
///
/// The given values describe a query to the resource database. `resource_class` can be an
/// empty string, but otherwise must contain the same number of components as `resource_name`.
/// Both strings may only contain alphanumeric characters or '-', '_', and '.'.
///
/// If no value is found, `Ok(None)` is returned. Otherwise, the result from
/// [`FromStr::from_str]` is returned with `Ok(value)` replaced with `Ok(Some(value))`.
///
/// For example, this is how Xterm could query one of its settings if it where written in Rust
/// (see `man xterm`):
/// ```
/// use x11rb_protocol::resource_manager::Database;
/// fn get_print_attributes(db: &Database) -> u8 {
/// db.get_value("XTerm.vt100.printAttributes", "XTerm.VT100.PrintAttributes")
/// .ok().flatten().unwrap_or(1)
/// }
/// ```
pub fn get_value<T>(
&self,
resource_name: &str,
resource_class: &str,
) -> Result<Option<T>, T::Err>
where
T: FromStr,
{
self.get_string(resource_name, resource_class)
.map(T::from_str)
.transpose()
}
}
/// Parse the given data as a resource database.
///
/// The parsed entries are appended to `result`. `#include`s are resolved relative to the given
/// `base_path`. `depth` is the number of includes that we are already handling. This value is used
/// to prevent endless loops when a file (directly or indirectly) includes itself.
fn parse_data_with_base_directory(
result: &mut Vec<Entry>,
data: &[u8],
base_path: &Path,
depth: u8,
) {
if depth > MAX_INCLUSION_DEPTH {
return;
}
parser::parse_database(data, result, |path, entries| {
// Construct the name of the file to include
if let Ok(path) = std::str::from_utf8(path) {
let mut path_buf = PathBuf::from(base_path);
path_buf.push(path);
// Read the file contents
if let Ok(new_data) = std::fs::read(&path_buf) {
// Parse the file contents with the new base path
let new_base = path_buf.parent().unwrap_or(base_path);
parse_data_with_base_directory(entries, &new_data, new_base, depth + 1);
}
}
});
}
/// Parse a value to a boolean, returning `None` if this is not possible.
fn to_bool(data: &str) -> Option<bool> {
if let Ok(num) = i64::from_str(data) {
return Some(num != 0);
}
match data.to_lowercase().as_bytes() {
b"true" => Some(true),
b"on" => Some(true),
b"yes" => Some(true),
b"false" => Some(false),
b"off" => Some(false),
b"no" => Some(false),
_ => None,
}
}
#[cfg(test)]
mod test {
use super::{to_bool, Database};
#[test]
fn test_bool_true() {
let data = ["1", "10", "true", "TRUE", "on", "ON", "yes", "YES"];
for input in &data {
assert_eq!(Some(true), to_bool(input));
}
}
#[test]
fn test_bool_false() {
let data = ["0", "false", "FALSE", "off", "OFF", "no", "NO"];
for input in &data {
assert_eq!(Some(false), to_bool(input));
}
}
#[test]
fn test_bool_none() {
let data = ["", "abc"];
for input in &data {
assert_eq!(None, to_bool(input));
}
}
#[test]
fn test_parse_i32_fail() {
let db = Database::new_from_data(b"a:");
assert_eq!(db.get_string("a", "a"), Some(""));
assert!(db.get_value::<i32>("a", "a").is_err());
}
#[test]
fn test_parse_i32_success() {
let data = [
(&b"a: 0"[..], 0),
(b"a: 1", 1),
(b"a: -1", -1),
(b"a: 100", 100),
];
for (input, expected) in data.iter() {
let db = Database::new_from_data(input);
let result = db.get_value::<i32>("a", "a");
assert_eq!(result.unwrap().unwrap(), *expected);
}
}
}
+697
View File
@@ -0,0 +1,697 @@
//! Code for parsing resource management things
use super::{Binding, Component, Entry};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
// =======================
// Common helper functions
// =======================
/// Check if a character (well, u8) is an octal digit
fn is_octal_digit(c: u8) -> bool {
matches!(c, b'0' | b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7')
}
/// Find the longest prefix of the given data where the given callback returns true
fn parse_with_matcher<M>(data: &[u8], matcher: M) -> (&[u8], &[u8])
where
M: Fn(u8) -> bool,
{
let end = data
.iter()
.enumerate()
.find(|(_, &c)| !matcher(c))
.map(|(idx, _)| idx)
.unwrap_or(data.len());
(&data[..end], &data[end..])
}
/// Check if a character is allowed in a quark name
fn allowed_in_quark_name(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'-' || c == b'_'
}
/// Find the longest prefix satisfying allowed_in_quark_name().
/// This returns (Some(prefix), remaining) if a prefix is found, else (None, data).
fn next_component(data: &[u8]) -> (Option<&[u8]>, &[u8]) {
let (prefix, remaining) = parse_with_matcher(data, allowed_in_quark_name);
match prefix {
[] => (None, remaining),
prefix => (Some(prefix), remaining),
}
}
// =========================
// Parser for resource files
// =========================
/// Skip to the next end of line in the given data
fn skip_to_eol(data: &[u8]) -> &[u8] {
parse_with_matcher(data, |c| c != b'\n').1
}
/// Skip all spaces in the given data
fn skip_spaces(data: &[u8]) -> &[u8] {
parse_with_matcher(data, |c| c == b' ').1
}
/// Skip the given text. Returns `None` if the text was not found
fn skip_text<'a>(data: &'a [u8], text: &[u8]) -> Option<&'a [u8]> {
if data.starts_with(text) {
Some(&data[text.len()..])
} else {
None
}
}
/// Parse a single `Component` from the data. This can either be a wildcard ("?") or a
/// component made up of characters accepted by `allowed_in_quark_name`.
fn next_component_name(data: &[u8]) -> (Option<Component>, &[u8]) {
if data.first() == Some(&b'?') {
(Some(Component::Wildcard), &data[1..])
} else {
let (comp, remaining) = next_component(data);
let comp = comp.map(|s| {
let s = std::str::from_utf8(s).expect("ascii-only");
Component::Normal(s.to_string())
});
(comp, remaining)
}
}
/// Parse a resource like "foo.?*baz" (wildcards allowed)
fn parse_components(data: &[u8]) -> (Vec<(Binding, Component)>, &[u8]) {
fn parse_binding(mut data: &[u8]) -> (Binding, &[u8]) {
let mut binding = Binding::Tight;
loop {
match data.first() {
Some(&b'*') => binding = Binding::Loose,
Some(&b'.') => {}
_ => break,
}
data = &data[1..];
}
(binding, data)
}
let mut data = data;
let mut result = Vec::new();
loop {
let (binding, remaining) = parse_binding(data);
if let (Some(component), remaining) = next_component_name(remaining) {
data = remaining;
result.push((binding, component));
} else {
break;
}
}
(result, data)
}
/// Parse a full entry from the data. This begins with components (see `parse_components()`),
/// then after a colon (":") comes the value. The value may contain escape sequences.
fn parse_entry(data: &[u8]) -> (Result<Entry, ()>, &[u8]) {
let (components, data) = parse_components(data);
match components.last() {
// Empty components are not allowed
None => return (Err(()), skip_to_eol(data)),
// The last component may not be a wildcard
Some((_, Component::Wildcard)) => return (Err(()), skip_to_eol(data)),
_ => {}
}
let data = skip_spaces(data);
// next comes a colon
let data = match data.split_first() {
Some((&b':', data)) => data,
_ => return (Err(()), skip_to_eol(data)),
};
// skip more spaces and let \ escape line breaks
let mut data = data;
loop {
let (_, remaining) = parse_with_matcher(data, |c| c == b' ' || c == b'\t');
if remaining.get(..2) == Some(&b"\\\n"[..]) {
data = &remaining[2..];
} else {
data = remaining;
break;
}
}
// Parse the value, decoding escape sequences. The most complicated case are octal escape
// sequences like \123.
let mut value = Vec::new();
let mut index = 0;
let mut octal = None;
while let Some(&b) = data.get(index) {
index += 1;
if b == b'\n' {
break;
}
if let Some(oct) = octal {
if is_octal_digit(b) {
// We are currently parsing an octal; add the new character
match oct {
(x, None) => octal = Some((x, Some(b))),
(x, Some(y)) => {
let (x, y, z) = (x - b'0', y - b'0', b - b'0');
let decoded = (x * 8 + y) * 8 + z;
value.push(decoded);
octal = None;
}
}
continue;
} else {
// Not an octal sequence; add the collected characters to the output
value.push(b'\\');
value.push(oct.0);
if let Some(oct2) = oct.1 {
value.push(oct2);
}
octal = None;
// Fall through to the parsing code below
}
}
if b != b'\\' {
value.push(b);
} else {
match data.get(index) {
None => {
value.push(b);
// Keep index as-is. This is to counter the += 1 below.
index -= 1;
}
Some(b' ') => value.push(b' '),
Some(b'\t') => value.push(b'\t'),
Some(b'n') => value.push(b'\n'),
Some(b'\\') => value.push(b'\\'),
Some(b'\n') => { /* Continue parsing next line */ }
Some(&x) if is_octal_digit(x) => octal = Some((x, None)),
Some(&x) => {
value.push(b);
value.push(x);
}
}
index += 1;
}
}
let entry = Entry { components, value };
(Ok(entry), &data[index..])
}
/// Parse the contents of a database
pub(crate) fn parse_database<F>(mut data: &[u8], result: &mut Vec<Entry>, mut include_callback: F)
where
for<'r> F: FnMut(&'r [u8], &mut Vec<Entry>),
{
// Iterate over lines
while let Some(first) = data.first() {
match first {
// Skip empty lines
b'\n' => data = &data[1..],
// Comment, skip the line
b'!' => data = skip_to_eol(data),
b'#' => {
let remaining = skip_spaces(&data[1..]);
// Skip to the next line for the next loop iteration. The rest of the code here
// tried to parse the line.
data = skip_to_eol(remaining);
// Only #include is defined
if let Some(remaining) = skip_text(remaining, b"include") {
let (_, remaining) = parse_with_matcher(remaining, |c| c == b' ');
// Find the text enclosed in quotation marks
if let Some(b'\"') = remaining.first() {
let (file, remaining) =
parse_with_matcher(&remaining[1..], |c| c != b'"' && c != b'\n');
if let Some(b'\"') = remaining.first() {
// Okay, we found a well-formed include directive.
include_callback(file, result);
}
}
}
}
_ => {
let (entry, remaining) = parse_entry(data);
data = remaining;
// Add the entry to the result if we parsed one; ignore errors
result.extend(entry.ok());
}
}
}
}
/// Parse a resource query like "foo.bar.baz" (no wildcards allowed, no bindings allowed)
pub(crate) fn parse_query(data: &[u8]) -> Option<Vec<String>> {
let mut data = data;
let mut result = Vec::new();
while let (Some(component), remaining) = next_component(data) {
data = remaining;
while let Some(&b'.') = data.first() {
data = &data[1..];
}
let component = std::str::from_utf8(component).expect("ascii-only");
result.push(component.to_string());
}
if data.is_empty() {
Some(result)
} else {
None
}
}
#[cfg(test)]
mod test {
use super::{parse_database, parse_entry, parse_query, Binding, Component, Entry};
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use std::eprintln;
// Most tests in here are based on [1], which is: Copyright © 2016 Ingo Bürk
// [1]: https://github.com/Airblader/xcb-util-xrm/blob/master/tests/tests_parser.c
#[test]
fn test_parse_query_success() {
let tests = [
(
&b"First.second"[..],
vec!["First".to_string(), "second".to_string()],
),
(b"", Vec::new()),
(
b"urxvt.scrollBar_right",
vec!["urxvt".to_string(), "scrollBar_right".to_string()],
),
(
b"urxvt.Control-Shift-Up",
vec!["urxvt".to_string(), "Control-Shift-Up".to_string()],
),
];
for (data, expected) in tests.iter() {
let result = parse_query(data);
assert_eq!(result.as_ref(), Some(expected), "while parsing {data:?}");
}
}
#[test]
fn test_parse_query_error() {
let tests = [
&b"First.second: on"[..],
b"First*second",
b"First.?.second",
b"*second",
b"?.second",
];
for data in tests.iter() {
let result = parse_query(data);
assert!(
result.is_none(),
"Unexpected success parsing '{data:?}': {result:?}"
);
}
}
#[test]
fn test_parse_entry_success() {
let tests = [
// Basics
(
&b"First: 1"[..],
vec![(Binding::Tight, Component::Normal("First".to_string()))],
&b"1"[..],
),
(
b"First.second: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Tight, Component::Normal("second".to_string())),
],
b"1",
),
(
b"First..second: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Tight, Component::Normal("second".to_string())),
],
b"1",
),
// Wildcards
(
b"?.second: 1",
vec![
(Binding::Tight, Component::Wildcard),
(Binding::Tight, Component::Normal("second".to_string())),
],
b"1",
),
(
b"First.?.third: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Tight, Component::Wildcard),
(Binding::Tight, Component::Normal("third".to_string())),
],
b"1",
),
// Loose bindings
(
b"*second: 1",
vec![(Binding::Loose, Component::Normal("second".to_string()))],
b"1",
),
(
b"First*third: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Loose, Component::Normal("third".to_string())),
],
b"1",
),
(
b"First**third: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Loose, Component::Normal("third".to_string())),
],
b"1",
),
// Combinations
(
b"First*?.fourth: 1",
vec![
(Binding::Tight, Component::Normal("First".to_string())),
(Binding::Loose, Component::Wildcard),
(Binding::Tight, Component::Normal("fourth".to_string())),
],
b"1",
),
// Values
(
b"First: 1337",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"1337",
),
(
b"First: -1337",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"-1337",
),
(
b"First: 13.37",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"13.37",
),
(
b"First: value",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"value",
),
(
b"First: #abcdef",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"#abcdef",
),
(
b"First: { key: 'value' }",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"{ key: 'value' }",
),
(
b"First: x?y",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x?y",
),
(
b"First: x*y",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x*y",
),
// Whitespace
(
b"First: x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x",
),
(
b"First: x ",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x ",
),
(
b"First: x ",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x ",
),
(
b"First:x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x",
),
(
b"First: \t x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x",
),
(
b"First: \t x \t",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x \t",
),
// Special characters
(
b"First: \\ x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b" x",
),
(
b"First: x\\ x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x x",
),
(
b"First: \\\tx",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\tx",
),
(
b"First: \\011x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\tx",
),
(
b"First: x\\\\x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x\\x",
),
(
b"First: x\\nx",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"x\nx",
),
(
b"First: \\080",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\080",
),
(
b"First: \\00a",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\00a",
),
// Own tests
// Some more escape tests, e.g. escape at end of input
(
b"First: \\",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\",
),
(
b"First: \\xxx",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\xxx",
),
(
b"First: \\1xx",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\1xx",
),
(
b"First: \\10x",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\\10x",
),
(
b"First: \\100",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"@",
),
(
b"First: \\n",
vec![(Binding::Tight, Component::Normal("First".to_string()))],
b"\n",
),
];
for (data, resource, value) in tests.iter() {
run_entry_test(data, resource, value);
}
}
#[test]
fn test_parse_entry_error() {
let tests = [
&b": 1"[..],
b"?: 1",
b"First",
b"First second",
b"First.?: 1",
b"F\xc3\xb6rst: 1",
b"F~rst: 1",
];
for data in tests.iter() {
match parse_entry(data) {
(Ok(v), _) => panic!("Unexpected success parsing '{:?}': {:?}", data, v),
(Err(_), b"") => {}
(Err(_), remaining) => panic!(
"Unexpected remaining data parsing '{:?}': {:?}",
data, remaining
),
}
}
}
#[test]
fn test_parse_large_value() {
let value = vec![b'x'; 1025];
let mut data = b"First: ".to_vec();
data.extend(&value);
let resource = (Binding::Tight, Component::Normal("First".to_string()));
run_entry_test(&data, &[resource], &value);
}
#[test]
fn test_parse_large_resource() {
let x = vec![b'x'; 1025];
let y = vec![b'y'; 1025];
let mut data = x.clone();
data.push(b'.');
data.extend(&y);
data.extend(b": 1");
let resource = [
(
Binding::Tight,
Component::Normal(String::from_utf8(x).unwrap()),
),
(
Binding::Tight,
Component::Normal(String::from_utf8(y).unwrap()),
),
];
run_entry_test(&data, &resource, b"1");
}
#[test]
fn test_parse_database() {
let expected_entry = Entry {
components: vec![(Binding::Tight, Component::Normal("First".to_string()))],
value: b"1".to_vec(),
};
let tests = [
(&b"First: 1\n\n\n"[..], vec![expected_entry.clone()]),
(b"First: 1\n!Foo", vec![expected_entry.clone()]),
(b"!First: 1\nbar\n\n\n", Vec::new()),
(b"!bar\nFirst: 1\nbaz", vec![expected_entry.clone()]),
(b"First :\\\n \\\n\\\n1\n", vec![expected_entry]),
(
b"First: \\\n 1\\\n2\n",
vec![Entry {
components: vec![(Binding::Tight, Component::Normal("First".to_string()))],
value: b"12".to_vec(),
}],
),
];
let mut success = true;
for (data, expected) in tests.iter() {
let mut result = Vec::new();
parse_database(data, &mut result, |_, _| unreachable!());
if &result != expected {
eprintln!("While testing {data:?}");
eprintln!("Expected: {expected:?}");
eprintln!("Got: {result:?}");
eprintln!();
success = false;
}
}
if !success {
panic!()
}
}
#[test]
fn test_include_parsing() {
let tests = [
(&b"#include\"test\""[..], vec![&b"test"[..]]),
(b"#include\"test", Vec::new()),
(b"#include\"", Vec::new()),
(b"#include", Vec::new()),
(b"#includ", Vec::new()),
(b"#in", Vec::new()),
(b"# foo", Vec::new()),
(
b"# include \" test \" \n#include \"foo\"",
vec![b" test ", b"foo"],
),
];
let mut success = true;
for (data, expected) in tests.iter() {
let mut result = Vec::new();
let mut calls = Vec::new();
parse_database(data, &mut result, |file, _| calls.push(file.to_vec()));
if &calls != expected {
eprintln!("While testing {data:?}");
eprintln!("Expected: {expected:?}");
eprintln!("Got: {calls:?}");
eprintln!();
success = false;
}
}
if !success {
panic!()
}
}
#[test]
fn test_include_additions() {
let entry = Entry {
components: Vec::new(),
value: b"42".to_vec(),
};
let mut result = Vec::new();
parse_database(b"#include\"test\"", &mut result, |file, result| {
assert_eq!(file, b"test");
result.push(entry.clone());
});
assert_eq!(result, [entry]);
}
fn run_entry_test(data: &[u8], resource: &[(Binding, Component)], value: &[u8]) {
match parse_entry(data) {
(Ok(result), remaining) => {
assert_eq!(remaining, b"", "failed to parse {data:?}");
assert_eq!(
result.components, resource,
"incorrect components when parsing {data:?}",
);
assert_eq!(result.value, value, "incorrect value when parsing {data:?}");
}
(Err(err), _) => panic!("Failed to parse '{:?}': {:?}", data, err),
}
}
}
+160
View File
@@ -0,0 +1,160 @@
#![cfg(feature = "std")]
use std::borrow::Cow;
use crate::protocol::{get_request_name, request_name};
use crate::x11_utils::{ExtInfoProvider, ExtensionInformation};
struct ExtInfo<'a> {
extension: Option<&'a str>,
major_opcode: u8,
}
impl ExtInfoProvider for ExtInfo<'_> {
fn get_from_major_opcode(&self, major_opcode: u8) -> Option<(&str, ExtensionInformation)> {
assert_eq!(self.major_opcode, major_opcode);
self.extension.map(|ext_name| {
(
ext_name,
ExtensionInformation {
major_opcode,
first_event: 0,
first_error: 0,
},
)
})
}
fn get_from_event_code(&self, _event_code: u8) -> Option<(&str, ExtensionInformation)> {
unimplemented!()
}
fn get_from_error_code(&self, _error_code: u8) -> Option<(&str, ExtensionInformation)> {
unimplemented!()
}
}
/// Test whether request_name() and get_request_name() provide the correct information for the
/// given request.
fn get_request_names(
extension: Option<&str>,
major_opcode: u8,
minor_opcode: u8,
) -> (Option<&'static str>, Cow<'static, str>) {
let ext_info = ExtInfo {
extension,
major_opcode,
};
let (ext_name, name) = request_name(&ext_info, major_opcode, minor_opcode.into());
let get_name = get_request_name(&ext_info, major_opcode, minor_opcode);
assert_eq!(ext_name.as_deref(), extension);
(name, get_name)
}
#[test]
fn test_core_request_names() {
assert_eq!(
get_request_names(None, 1, 0),
(Some("CreateWindow"), Cow::from("CreateWindow"))
);
// Test that the minor opcode (which is actually the depth in CreateWindow) does not influence
// the result
assert_eq!(
get_request_names(None, 1, 1),
(Some("CreateWindow"), Cow::from("CreateWindow"))
);
assert_eq!(
get_request_names(None, 1, 255),
(Some("CreateWindow"), Cow::from("CreateWindow"))
);
// Special case: minor_opcode does not fit into u8.
assert_eq!(
request_name(
&ExtInfo {
extension: None,
major_opcode: 42
},
1,
54321
),
(None, Some("CreateWindow"))
);
assert_eq!(
get_request_names(None, 100, 0),
(
Some("ChangeKeyboardMapping"),
Cow::from("ChangeKeyboardMapping")
)
);
assert_eq!(
get_request_names(None, 120, 0),
(None, Cow::from("xproto::opcode 120"))
);
assert_eq!(
get_request_names(None, 127, 0),
(Some("NoOperation"), Cow::from("NoOperation"))
);
}
#[test]
fn test_bigreq_request_names() {
assert_eq!(
get_request_names(Some("BIG-REQUESTS"), 130, 0),
(Some("Enable"), Cow::from("BigRequests::Enable"))
);
assert_eq!(
get_request_names(Some("BIG-REQUESTS"), 200, 0),
(Some("Enable"), Cow::from("BigRequests::Enable"))
);
assert_eq!(
get_request_names(Some("BIG-REQUESTS"), 130, 1),
(None, Cow::from("BigRequests::opcode 1"))
);
assert_eq!(
get_request_names(Some("BIG-REQUESTS"), 130, 255),
(None, Cow::from("BigRequests::opcode 255"))
);
}
#[test]
fn test_xc_misc_request_names() {
assert_eq!(
get_request_names(Some("XC-MISC"), 130, 0),
(Some("GetVersion"), Cow::from("XCMisc::GetVersion"))
);
assert_eq!(
get_request_names(Some("XC-MISC"), 200, 0),
(Some("GetVersion"), Cow::from("XCMisc::GetVersion"))
);
assert_eq!(
get_request_names(Some("XC-MISC"), 200, 1),
(Some("GetXIDRange"), Cow::from("XCMisc::GetXIDRange"))
);
assert_eq!(
get_request_names(Some("XC-MISC"), 200, 2),
(Some("GetXIDList"), Cow::from("XCMisc::GetXIDList"))
);
assert_eq!(
get_request_names(Some("XC-MISC"), 200, 3),
(None, Cow::from("XCMisc::opcode 3"))
);
assert_eq!(
get_request_names(Some("XC-MISC"), 200, 100),
(None, Cow::from("XCMisc::opcode 100"))
);
}
#[test]
fn test_unknown_extension_request_names() {
assert_eq!(
get_request_names(None, 210, 123),
(None, Cow::from("ext 210::opcode 123"))
);
assert_eq!(
get_request_names(Some("FOO-BAR"), 210, 123),
(None, Cow::from("ext FOO-BAR::opcode 123"))
);
}
+197
View File
@@ -0,0 +1,197 @@
//! Utility functions that are not specific to X11.
//!
//! # RawFdContainer
//!
//! [`RawFdContainer`] is a variant of [`std::os::unix::io::RawFd`] with ownership semantics. This
//! means that the `RawFd` will be closed when the `RawFdContainer` is dropped.
//!
//! On non-`cfg(unix)`-systems, this is an empty type without methods. It still exists as a type so
//! that it can appear in interfaces, but it is not actually possible to construct an instance of
//! `RawFdContainer`.
#[cfg(all(feature = "std", unix))]
mod raw_fd_container {
use std::os::unix::io::OwnedFd;
pub(crate) type RawFdContainer = OwnedFd;
}
#[cfg(not(all(feature = "std", unix)))]
mod raw_fd_container {
use core::convert::Infallible;
#[derive(Debug)]
#[doc(hidden)]
pub struct RawFdContainer(Infallible);
impl Drop for RawFdContainer {
fn drop(&mut self) {
// This function exists for symmetry with cfg(unix)
match self.0 {}
}
}
}
/// A type representative of the file descriptors as they are sent to and from the X server.
///
/// On `cfg(unix)` platforms, this is a type alias for [`std::os::unix::io::OwnedFd`]. See the
/// documentation for that type for more information on how it should be used. In most cases it
/// can be cast into a [`File`] or [`UnixStream`], or otherwise downgraded into the actual
/// underlying file descriptor.
///
/// On non-Unix platforms, this is an uninhabited type in the same vogue as [`Void`]. As handle
/// passing is an undefined operation on non-Unix implementations of the X11 protocol, instances
/// of this type cannot exist. No operations can be called on this type. If handle passing is ever
/// added to any reference implementation of the X11 protocol, this type will be changed to
/// something that can be used to represent the file descriptors.
///
/// Consumers of this type should be careful to check for `cfg(unix)` before using it in any
/// meaningful way. Otherwise, the program will not compile on non-Unix platforms.
///
/// [`File`]: std::fs::File
/// [`UnixStream`]: std::os::unix::net::UnixStream
/// [`Void`]: https://docs.rs/void/latest/void/enum.Void.html
pub type RawFdContainer = raw_fd_container::RawFdContainer;
mod pretty_printer {
use core::fmt::{Debug, Formatter, Result};
/// A helper to pretty-print an enumeration value.
///
/// This function prints the given number. If it matches one of the provided variants, that
/// match is used. Otherwise, the number is printed as a decimal.
///
/// In alternate mode, the second string in the given array is used, else the first.
pub(crate) fn pretty_print_enum(
fmt: &mut Formatter<'_>,
value: u32,
cases: &[(u32, &str, &str)],
) -> Result {
for (variant, name1, name2) in cases {
if &value == variant {
if fmt.alternate() {
return fmt.write_str(name2);
} else {
return fmt.write_str(name1);
}
}
}
Debug::fmt(&value, fmt)
}
/// A helper to pretty-print a bitmask.
///
/// This function prints the given number. All bit-matches with the given variants are printed.
/// Any left-over number is printed as a decimal.
///
/// In alternate mode, the second string in the given array is used, else the first.
pub(crate) fn pretty_print_bitmask(
fmt: &mut Formatter<'_>,
value: u32,
cases: &[(u32, &str, &str)],
) -> Result {
// First, figure out if there are any bits not covered by any case
let known_bits = cases.iter().fold(0, |acc, (value, _, _)| acc | value);
let remaining = value & !known_bits;
let mut already_printed = if value == 0 || remaining != 0 {
Debug::fmt(&remaining, fmt)?;
true
} else {
false
};
for (variant, name1, name2) in cases {
if variant & value != 0 {
if already_printed {
fmt.write_str(" | ")?;
}
already_printed = true;
if fmt.alternate() {
fmt.write_str(name2)?;
} else {
fmt.write_str(name1)?;
}
}
}
Ok(())
}
#[cfg(test)]
mod test {
use super::{pretty_print_bitmask, pretty_print_enum};
use alloc::format;
use core::fmt::{Display, Formatter, Result};
type CallbackType = fn(&mut Formatter<'_>, u32, &[(u32, &str, &str)]) -> Result;
struct CallbackFormating<'a, 'b> {
callback: CallbackType,
value: u32,
cases: &'a [(u32, &'b str, &'b str)],
}
fn new_enum<'a, 'b>(
value: u32,
cases: &'a [(u32, &'b str, &'b str)],
) -> CallbackFormating<'a, 'b> {
CallbackFormating {
callback: pretty_print_enum,
value,
cases,
}
}
fn new_bitmask<'a, 'b>(
value: u32,
cases: &'a [(u32, &'b str, &'b str)],
) -> CallbackFormating<'a, 'b> {
CallbackFormating {
callback: pretty_print_bitmask,
value,
cases,
}
}
impl Display for CallbackFormating<'_, '_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
(self.callback)(f, self.value, self.cases)
}
}
#[test]
fn test_enum() {
let cases = [(0, "zero", "ZERO"), (42, "the answer", "ANSWER")];
let printer = new_enum(0, &cases);
assert_eq!(&format!("{printer}"), "zero");
assert_eq!(&format!("{printer:#}"), "ZERO");
let printer = new_enum(1, &cases);
assert_eq!(&format!("{printer}"), "1");
assert_eq!(&format!("{printer:#}"), "1");
let printer = new_enum(42, &cases);
assert_eq!(&format!("{printer}"), "the answer");
assert_eq!(&format!("{printer:#}"), "ANSWER");
}
#[test]
fn test_bitmask() {
let bits = [
(1 << 5, "b5", "B5"),
(1 << 1, "b1", "B1"),
(1 << 0, "unused", "UNUSED"),
];
let printer = new_bitmask(8, &bits);
assert_eq!(&format!("{printer}"), "8");
assert_eq!(&format!("{printer:#}"), "8");
let printer = new_bitmask(32, &bits);
assert_eq!(&format!("{printer}"), "b5");
assert_eq!(&format!("{printer:#}"), "B5");
let printer = new_bitmask(34, &bits);
assert_eq!(&format!("{printer}"), "b5 | b1");
assert_eq!(&format!("{printer:#}"), "B5 | B1");
let printer = new_bitmask(42, &bits);
assert_eq!(&format!("{printer}"), "8 | b5 | b1");
assert_eq!(&format!("{printer:#}"), "8 | B5 | B1");
}
}
}
pub(crate) use pretty_printer::{pretty_print_bitmask, pretty_print_enum};
+91
View File
@@ -0,0 +1,91 @@
//! Helpers for the generated code
use super::x11_utils::TryParse;
use core::marker::PhantomData;
/// Iterator implementation used by [GetPropertyReply].
///
/// This is the actual type returned by [GetPropertyReply::value8], [GetPropertyReply::value16],
/// and [GetPropertyReply::value32]. This type needs to be public due to Rust's visibility rules.
///
/// [GetPropertyReply]: crate::protocol::xproto::GetPropertyReply
/// [GetPropertyReply::value8]: crate::protocol::xproto::GetPropertyReply::value8
/// [GetPropertyReply::value16]: crate::protocol::xproto::GetPropertyReply::value16
/// [GetPropertyReply::value32]: crate::protocol::xproto::GetPropertyReply::value32
#[derive(Debug, Clone)]
pub struct PropertyIterator<'a, T>(&'a [u8], PhantomData<T>);
impl<'a, T> PropertyIterator<'a, T> {
pub(crate) fn new(value: &'a [u8]) -> Self {
PropertyIterator(value, PhantomData)
}
}
impl<T> Iterator for PropertyIterator<'_, T>
where
T: TryParse,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
match T::try_parse(self.0) {
Ok((value, remaining)) => {
self.0 = remaining;
Some(value)
}
Err(_) => {
self.0 = &[];
None
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
use core::mem::size_of;
let size = self.0.len() / size_of::<T>();
(size, Some(size))
}
}
impl<T: TryParse> core::iter::FusedIterator for PropertyIterator<'_, T> {}
#[cfg(test)]
mod tests {
use super::PropertyIterator;
use alloc::vec::Vec;
#[test]
fn test_parse_u8() {
let input = [0u8, 1, 2, 3, 4, 5];
let output = PropertyIterator::new(&input).collect::<Vec<u8>>();
assert_eq!(&input[..], output);
}
#[test]
fn test_parse_u32() {
let expected = [0u32, 1, 2, 3, 4, 5];
let input = {
let mut input = Vec::new();
for value in &expected {
input.extend_from_slice(&value.to_ne_bytes());
}
input
};
let output = PropertyIterator::new(&input).collect::<Vec<u32>>();
assert_eq!(&expected[..], output);
}
#[test]
fn test_size_hint() {
let hint = PropertyIterator::<u32>::new(&[0; 0]).size_hint();
assert_eq!(hint, (0, Some(0)));
let hint = PropertyIterator::<u32>::new(&[0; 8]).size_hint();
assert_eq!(hint, (2, Some(2)));
// In this case, the data is not an exact multiple of the element size
let hint = PropertyIterator::<u32>::new(&[0; 30]).size_hint();
assert_eq!(hint, (7, Some(7)));
}
}
+767
View File
@@ -0,0 +1,767 @@
//! Utility functions for X11 things.
//!
//! The most important definitions in this module are the [`TryParse`], [`TryParseFd`] and
//! [`Serialize`] traits. These traits are used internally for parsing incoming data and producing
//! outgoing data when talking with the X11 server.
use alloc::string::String;
use alloc::vec::Vec;
use crate::errors::ParseError;
use crate::protocol::{request_name, ErrorKind};
use crate::utils::RawFdContainer;
use crate::BufWithFds;
/// Representation of an X11 error packet that was sent by the server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct X11Error {
/// The kind of error that occurred.
pub error_kind: ErrorKind,
/// The kind of error that occurred as it appears "on the wire".
pub error_code: u8,
/// The sequence number of the request that caused this error.
pub sequence: u16,
/// The value in the request that caused the error.
pub bad_value: u32,
/// The minor opcode of the request that caused this error.
pub minor_opcode: u16,
/// The major opcode of the request that caused this error.
pub major_opcode: u8,
/// Name of the extension that caused this error, if known.
pub extension_name: Option<String>,
/// Name of the request that caused this error, if known.
pub request_name: Option<&'static str>,
}
impl X11Error {
/// Parse an X11 error.
pub fn try_parse(
data: &[u8],
ext_info_provider: &dyn ExtInfoProvider,
) -> Result<Self, ParseError> {
let (response_type, remaining) = u8::try_parse(data)?;
let (error_code, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (bad_value, remaining) = u32::try_parse(remaining)?;
let (minor_opcode, remaining) = u16::try_parse(remaining)?;
let (major_opcode, _) = u8::try_parse(remaining)?;
if response_type != 0 {
Err(ParseError::InvalidValue)
} else {
let error_kind = ErrorKind::from_wire_error_code(error_code, ext_info_provider);
let (extension_name, request_name) =
request_name(ext_info_provider, major_opcode, minor_opcode);
Ok(X11Error {
error_kind,
error_code,
sequence,
bad_value,
minor_opcode,
major_opcode,
extension_name,
request_name,
})
}
}
}
#[cfg(test)]
mod tryparse_x11error_test {
use super::{ErrorKind, ExtInfoProvider, ParseError, X11Error};
use crate::x11_utils::ExtensionInformation;
struct Provider;
impl ExtInfoProvider for Provider {
fn get_from_major_opcode(&self, major_opcode: u8) -> Option<(&str, ExtensionInformation)> {
assert_eq!(major_opcode, 10);
None
}
fn get_from_event_code(&self, _event_code: u8) -> Option<(&str, ExtensionInformation)> {
unimplemented!()
}
fn get_from_error_code(&self, _error_code: u8) -> Option<(&str, ExtensionInformation)> {
unimplemented!()
}
}
#[test]
fn try_parse_error() {
let input = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
];
let error = X11Error::try_parse(&input, &Provider);
let expected = X11Error {
error_kind: ErrorKind::Request,
error_code: 1,
sequence: u16::from_ne_bytes([2, 3]),
bad_value: u32::from_ne_bytes([4, 5, 6, 7]),
minor_opcode: u16::from_ne_bytes([8, 9]),
major_opcode: 10,
extension_name: None,
request_name: Some("UnmapWindow"),
};
assert_eq!(error, Ok(expected));
}
#[test]
fn reject_invalid_response_type() {
let result = X11Error::try_parse(&[1; 32], &Provider);
assert_eq!(Err(ParseError::InvalidValue), result);
}
}
impl From<&X11Error> for [u8; 32] {
fn from(input: &X11Error) -> Self {
let sequence_bytes = input.sequence.serialize();
let bad_value_bytes = input.bad_value.serialize();
let minor_opcode_bytes = input.minor_opcode.serialize();
[
0,
input.error_code,
sequence_bytes[0],
sequence_bytes[1],
bad_value_bytes[0],
bad_value_bytes[1],
bad_value_bytes[2],
bad_value_bytes[3],
minor_opcode_bytes[0],
minor_opcode_bytes[1],
input.major_opcode,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
}
impl From<X11Error> for [u8; 32] {
fn from(input: X11Error) -> Self {
Self::from(&input)
}
}
#[cfg(test)]
mod serialise_x11error_test {
use super::{ErrorKind, X11Error};
#[test]
fn test_serialise() {
let error = X11Error {
error_kind: ErrorKind::Request,
error_code: 1,
sequence: u16::from_ne_bytes([2, 3]),
bad_value: u32::from_ne_bytes([4, 5, 6, 7]),
minor_opcode: u16::from_ne_bytes([8, 9]),
major_opcode: 10,
extension_name: None,
request_name: None,
};
let expected = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
];
assert_eq!(expected, <[u8; 32]>::from(error));
}
}
/// Information about a X11 extension.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ExtensionInformation {
/// Major opcode used in request
pub major_opcode: u8,
/// Lowest event number used by the extension.
pub first_event: u8,
/// Lowest error number used by the extension.
pub first_error: u8,
}
/// Trait to provide information about extensions.
pub trait ExtInfoProvider {
/// Returns the information of the extension that whose
/// opcode is `major_opcode`.
fn get_from_major_opcode(&self, major_opcode: u8) -> Option<(&str, ExtensionInformation)>;
/// Returns the information of the extension that whose
/// event number range includes `event_number`.
fn get_from_event_code(&self, event_code: u8) -> Option<(&str, ExtensionInformation)>;
/// Returns the information of the extension that whose
/// error number range includes `error_number`.
fn get_from_error_code(&self, error_code: u8) -> Option<(&str, ExtensionInformation)>;
}
/// 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 parsed from some raw bytes and a list of fds.
pub trait TryParseFd: Sized {
/// Try to parse the given values into an instance of this type.
///
/// File descriptors are consumed by removing them from the beginning of the given `fds` `Vec`.
/// If a file descriptor is expected, but missing, a `ParseError` should be returned. If more file
/// descriptors are provided than expected, this is not an error and the remaining descriptors
/// should be left in the `Vec`.
///
/// 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_fd<'a>(
value: &'a [u8],
fds: &mut Vec<RawFdContainer>,
) -> Result<(Self, &'a [u8]), ParseError>;
}
impl<T: TryParse> TryParseFd for T {
fn try_parse_fd<'a>(
value: &'a [u8],
_: &mut Vec<RawFdContainer>,
) -> Result<(Self, &'a [u8]), ParseError> {
T::try_parse(value)
}
}
/// A representation of the header of a request.
#[derive(Debug, Clone, Copy)]
pub struct RequestHeader {
/// The major opcode of the request.
pub major_opcode: u8,
/// The minor opcode of the request (which, for some requests, may not be an
/// opcode at all).
pub minor_opcode: u8,
/// The remaining length of the request, measured in 4 bytes units. Unlike the wire format,
/// this does *not* include the header itself, which is 1 unit (or 2 if BigRequests is
/// enabled and the length in the first unit is zero). If the BigRequests extension is
/// enabled this can be greater than u16::max_value - 1.
pub remaining_length: u32,
}
/// A type implementing this trait is an X11 request.
pub trait Request {
/// The protocol name of the extension that this request belongs to, or None for core requests
const EXTENSION_NAME: Option<&'static str>;
/// Serialize this request into its X11 protocol wire representation.
///
/// The argument is the major opcode of the extension that this request belongs to. For core
/// requests, the argument may not have any influence
fn serialize(self, extension_opcode: u8) -> BufWithFds<Vec<u8>>;
}
/// A type alias for reply parsers (matches the signature of TryParseFd).
pub type ReplyParsingFunction =
for<'a> fn(
&'a [u8],
&mut Vec<RawFdContainer>,
) -> Result<(crate::protocol::Reply, &'a [u8]), ParseError>;
/// A X11 request that does not have a reply
pub trait VoidRequest: Request {}
/// A X11 request that has a reply without FDs
pub trait ReplyRequest: Request {
/// The kind of reply that this request generates.
type Reply: Into<crate::protocol::Reply> + TryParse;
}
/// A X11 request that has a reply with FDs
pub trait ReplyFDsRequest: Request {
/// The kind of reply that this request generates.
type Reply: Into<crate::protocol::Reply> + TryParseFd;
}
/// 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`.
///
/// When calling this method, the given vector must satisfy `assert_eq!(bytes.len() % 4, 0);`.
/// In words: Its length must be a multiple of four.
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 = core::mem::size_of::<$t>();
let bytes = value
.get(..len)
.ok_or(ParseError::InsufficientData)?
.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);
#[cfg(all(test, feature = "std"))]
mod float_tests {
use super::{Serialize, TryParse};
fn test_round_trip<F>(value: F)
where
F: TryParse + Serialize + PartialEq + core::fmt::Debug + Copy,
<F as Serialize>::Bytes: AsRef<[u8]>,
{
let empty = &[][..];
// Test using serialize()
assert_eq!(Ok((value, empty)), F::try_parse(value.serialize().as_ref()));
// Test using serialize_into()
let mut output = alloc::vec::Vec::new();
value.serialize_into(&mut output);
assert_eq!(Ok((value, empty)), F::try_parse(&output));
}
#[test]
fn test_f32_round_trips() {
for &f in &[0f32, 1., std::f32::consts::PI, 42., 1337., 1e7] {
test_round_trip(f);
test_round_trip(-f);
}
}
#[test]
fn test_f64_round_trips() {
for &f in &[0f64, 1., std::f64::consts::PI, 42., 1337., 1e7] {
test_round_trip(f);
test_round_trip(-f);
}
}
#[test]
fn test_parse_known_value() {
let bytes = 0x42280000u32.to_ne_bytes();
let value = f32::try_parse(&bytes);
let empty = &[][..];
assert_eq!(Ok((42., empty)), value);
}
#[test]
fn test_serialize_known_value() {
assert_eq!(0x42280000u32.to_ne_bytes(), 42f32.serialize());
}
}
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));
}
}
// Tuple handling
macro_rules! tuple_try_parse {
($($name:ident)*) => {
impl<$($name,)*> TryParse for ($($name,)*)
where $($name: TryParse,)*
{
#[allow(non_snake_case)]
fn try_parse(remaining: &[u8]) -> Result<(($($name,)*), &[u8]), ParseError> {
$(let ($name, remaining) = $name::try_parse(remaining)?;)*
Ok((($($name,)*), remaining))
}
}
}
}
macro_rules! tuple_serialize {
($($name:ident:$idx:tt)*) => {
impl<$($name,)*> Serialize for ($($name,)*)
where $($name: Serialize,)*
{
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>) {
$(self.$idx.serialize_into(bytes);)*
}
}
}
}
macro_rules! tuple_impls {
($($name:ident:$idx:tt)*) => {
tuple_try_parse!($($name)*);
tuple_serialize!($($name:$idx)*);
}
}
// We can optimise serialisation of empty tuples or one-element-tuples with different Bytes type
impl Serialize for () {
type Bytes = [u8; 0];
fn serialize(&self) -> Self::Bytes {
[]
}
fn serialize_into(&self, _bytes: &mut Vec<u8>) {}
}
impl<T: Serialize> Serialize for (T,) {
type Bytes = T::Bytes;
fn serialize(&self) -> Self::Bytes {
self.0.serialize()
}
fn serialize_into(&self, bytes: &mut Vec<u8>) {
self.0.serialize_into(bytes)
}
}
tuple_try_parse!();
tuple_try_parse!(A);
tuple_impls!(A:0 B:1);
tuple_impls!(A:0 B:1 C:2);
tuple_impls!(A:0 B:1 C:2 D:3);
tuple_impls!(A:0 B:1 C:2 D:3 E:4);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9 K:10);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9 K:10 L:11);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9 K:10 L:11 M:12);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9 K:10 L:11 M:12 N:13);
tuple_impls!(A:0 B:1 C:2 D:3 E:4 F:5 G:6 H:7 I:8 J:9 K:10 L:11 M:12 N:13 O:14);
/// 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(crate) 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))
}
/// Parse a list of `u8` from the given data.
#[inline]
pub(crate) fn parse_u8_list(data: &[u8], list_length: usize) -> Result<(&[u8], &[u8]), ParseError> {
if data.len() < list_length {
Err(ParseError::InsufficientData)
} else {
Ok(data.split_at(list_length))
}
}
/// Parse an array of `u8` from the given data.
#[inline]
pub(crate) fn parse_u8_array_ref<const N: usize>(
data: &[u8],
) -> Result<(&[u8; N], &[u8]), ParseError> {
let (slice, remaining) = parse_u8_list(data, N)?;
let slice = slice
.try_into()
.expect("Cannot fail since slice has expected length");
Ok((slice, remaining))
}
/// Parse an array of `u8` from the given data.
#[inline]
pub(crate) fn parse_u8_array<const N: usize>(data: &[u8]) -> Result<([u8; N], &[u8]), ParseError> {
let (array, remaining) = parse_u8_array_ref(data)?;
Ok((*array, 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 e.g. `std::ops::BitOr` and
// `std::ops::BitOrAssign`.
macro_rules! bitmask_binop {
($t:ty, $u:ty) => {
impl core::ops::BitOr for $t {
type Output = $t;
fn bitor(self, other: Self) -> Self::Output {
Self::from(<$u>::from(self) | <$u>::from(other))
}
}
impl core::ops::BitOr<$u> for $t {
type Output = $t;
fn bitor(self, other: $u) -> Self::Output {
self | Self::from(other)
}
}
impl core::ops::BitOr<$t> for $u {
type Output = $t;
fn bitor(self, other: $t) -> Self::Output {
<$t>::from(self) | other
}
}
impl core::ops::BitOrAssign for $t {
fn bitor_assign(&mut self, other: $t) {
*self = *self | Self::from(other)
}
}
impl core::ops::BitOrAssign<$t> for $u {
fn bitor_assign(&mut self, other: $t) {
*self |= Self::from(other)
}
}
impl core::ops::BitOrAssign<$u> for $t {
fn bitor_assign(&mut self, other: $u) {
self.0 |= other
}
}
impl core::ops::BitAnd for $t {
type Output = $t;
fn bitand(self, other: Self) -> Self::Output {
Self::from(<$u>::from(self) & <$u>::from(other))
}
}
impl core::ops::BitAnd<$u> for $t {
type Output = $t;
fn bitand(self, other: $u) -> Self::Output {
self & Self::from(other)
}
}
impl core::ops::BitAnd<$t> for $u {
type Output = $t;
fn bitand(self, other: $t) -> Self::Output {
<$t>::from(self) & other
}
}
impl core::ops::BitAndAssign for $t {
fn bitand_assign(&mut self, other: $t) {
self.0 &= other
}
}
impl core::ops::BitAndAssign<$t> for $u {
fn bitand_assign(&mut self, other: $t) {
*self &= Self::from(other)
}
}
impl core::ops::BitAndAssign<$u> for $t {
fn bitand_assign(&mut self, other: $u) {
self.0 &= other
}
}
impl $t {
/// Check if this object has all bits set that are also set in `flag`.
///
/// `flag` can be a single enum variant or a whole other mask.
pub fn contains(self, flag: impl Into<$u>) -> bool {
let flag = flag.into();
(<$u>::from(self) & flag) == flag
}
/// Check if this object has some bits set that are also set in `flag`.
///
/// `flag` can be a single enum variant or a whole other mask.
pub fn intersects(self, flag: impl Into<$u>) -> bool {
let flag = flag.into();
(<$u>::from(self) & flag) != 0
}
/// Remove some flags.
///
/// All bits that are set in the given flags are removed from the `self` instance, if
/// they are present.
pub fn remove(self, flags: impl Into<$u>) -> Self {
Self::from(self.bits() & !flags.into())
}
/// Returns the internal value of the object.
pub fn bits(self) -> $u {
self.0
}
}
};
}
macro_rules! impl_debug_if_no_extra_traits {
($type:ty, $name:literal) => {
#[cfg(not(feature = "extra-traits"))]
impl core::fmt::Debug for $type {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct($name).finish_non_exhaustive()
}
}
};
}
/// Wrapper around TryInto that produces a ParseError.
///
/// This trait shortens `x.try_into().or(Err(ParseError::ConversionFailed))` to `x.try_to_usize()`.
pub(crate) trait TryIntoUSize: TryInto<usize> {
/// Attempt the conversion
fn try_to_usize(self) -> Result<usize, ParseError> {
self.try_into().or(Err(ParseError::ConversionFailed))
}
}
impl TryIntoUSize for u8 {}
impl TryIntoUSize for u16 {}
impl TryIntoUSize for u32 {}
impl TryIntoUSize for u64 {}
impl TryIntoUSize for i8 {}
impl TryIntoUSize for i16 {}
impl TryIntoUSize for i32 {}
impl TryIntoUSize for i64 {}
/// Has the BigRequests extension been enabled?
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BigRequests {
/// The BigRequests extension has been enabled.
Enabled,
/// The BigRequests extension has not been enabled.
NotEnabled,
}
/// Parse the given input for a RequestHeader and the remaining input.
pub fn parse_request_header(
input: &[u8],
big_requests_enabled: BigRequests,
) -> Result<(RequestHeader, &[u8]), ParseError> {
let (major_opcode, remaining) = u8::try_parse(input)?;
let (minor_opcode, remaining) = u8::try_parse(remaining)?;
let (length, remaining) = u16::try_parse(remaining)?;
let (remaining_length, finally_remaining) = if length == 0 {
if big_requests_enabled == BigRequests::NotEnabled {
return Err(ParseError::InvalidValue);
}
let (length, remaining) = u32::try_parse(remaining)?;
if length < 2 {
return Err(ParseError::InvalidValue);
}
// Adjust length for the size of this header (two 4 byte units).
(length - 2, remaining)
} else {
// Adjust length for the size of this header (one 4 byte unit).
(u32::from(length) - 1, remaining)
};
Ok((
RequestHeader {
major_opcode,
minor_opcode,
remaining_length,
},
finally_remaining,
))
}
+397
View File
@@ -0,0 +1,397 @@
//! Helpers for working with `~/.Xauthority`.
#![cfg(feature = "std")]
use alloc::string::ToString;
use alloc::vec::Vec;
use std::io::Error;
use crate::protocol::xproto::Family as X11Family;
const MIT_MAGIC_COOKIE_1: &[u8] = b"MIT-MAGIC-COOKIE-1";
/// A family describes how to interpret some bytes as an address in an `AuthEntry`.
///
/// Compared to [`super::protocol::xproto::Family`], this is a `u16` and not an `u8` since
/// that's what is used in `~/.Xauthority` files.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Family(u16);
impl Family {
/// IPv4 connection to the server
pub const INTERNET: Self = Self(0);
/// DECnet
pub const DEC_NET: Self = Self(1);
/// Chaosnet connection
pub const CHAOS: Self = Self(2);
/// Family without predefined meaning, but interpreted by the server, for example a user name
pub const SERVER_INTERPRETED: Self = Self(5);
/// IPv6 connection to the server
pub const INTERNET6: Self = Self(6);
/// Wildcard matching any protocol family
pub const WILD: Self = Self(65535);
/// For local non-net authentication
pub const LOCAL: Self = Self(256);
/// TODO: No idea what this means exactly
pub const NETNAME: Self = Self(254);
/// Kerberos 5 principal name
pub const KRB5_PRINCIPAL: Self = Self(253);
/// For local non-net authentication
pub const LOCAL_HOST: Self = Self(252);
}
impl From<X11Family> for Family {
fn from(value: X11Family) -> Self {
Self(value.into())
}
}
impl From<u16> for Family {
fn from(value: u16) -> Self {
Self(value)
}
}
/// A single entry of an `.Xauthority` file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AuthEntry {
/// The protocol family to which the entry applies
family: Family,
/// The address of the peer in a family-specific format
address: Vec<u8>,
/// The display number
number: Vec<u8>,
/// The name of the authentication method to use for the X11 server described by the previous
/// fields.
name: Vec<u8>,
/// Extra data for the authentication method.
data: Vec<u8>,
}
mod file {
//! Code for actually reading `~/.Xauthority`.
use alloc::{vec, vec::Vec};
use std::env::var_os;
use std::fs::File;
use std::io::{BufReader, Error, ErrorKind, Read};
use std::path::PathBuf;
use super::AuthEntry;
/// Read a single `u16` from an `~/.Xauthority` file.
///
/// The file stores these entries in big endian.
fn read_u16<R: Read>(read: &mut R) -> Result<u16, Error> {
let mut buffer = [0; 2];
read.read_exact(&mut buffer)?;
Ok(u16::from_be_bytes(buffer))
}
/// Read a single "byte array" from an `~/.Xauthority` file.
///
/// The file stores these as a length field followed by a number of bytes that contain the
/// actual data.
fn read_string<R: Read>(read: &mut R) -> Result<Vec<u8>, Error> {
let length = read_u16(read)?;
let mut result = vec![0; length.into()];
read.read_exact(&mut result[..])?;
Ok(result)
}
/// Read a single entry from an `~/.Xauthority` file.
///
/// This function tries to return `Ok(None)` when the end of the file is reached. However, the
/// code also treats a single byte as 'end of file', because things were simpler to implement
/// like this.
fn read_entry<R: Read>(read: &mut R) -> Result<Option<AuthEntry>, Error> {
let family = match read_u16(read) {
Ok(family) => family,
Err(ref e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
.into();
let address = read_string(read)?;
let number = read_string(read)?;
let name = read_string(read)?;
let data = read_string(read)?;
Ok(Some(AuthEntry {
family,
address,
number,
name,
data,
}))
}
/// Get the file name for `~/.Xauthority` based on environment variables.
///
/// The code in libXau contains a special case for Windows (looks like cygwin) that is not
/// handled here (yet?).
fn get_xauthority_file_name() -> Option<PathBuf> {
if let Some(name) = var_os("XAUTHORITY") {
return Some(name.into());
}
var_os("HOME").map(|prefix| {
let mut result = PathBuf::new();
result.push(prefix);
result.push(".Xauthority");
result
})
}
/// An iterator over the entries of an `.Xauthority` file
#[derive(Debug)]
pub(crate) struct XAuthorityEntries(BufReader<File>);
impl XAuthorityEntries {
/// Open `~/.Xauthority` for reading.
///
/// This function returns `Ok(None)` when the location of the `.Xauthority` file could not
/// be determined. If opening the file failed (for example, because it does not exist),
/// that error is returned.
pub(crate) fn new() -> Result<Option<XAuthorityEntries>, Error> {
get_xauthority_file_name()
.map(File::open)
.transpose()?
// At this point we have Option<File> and errors while opening the file were
// returned to the caller.
.map(|file| Ok(XAuthorityEntries(BufReader::new(file))))
.transpose()
}
}
impl Iterator for XAuthorityEntries {
type Item = Result<AuthEntry, Error>;
fn next(&mut self) -> Option<Self::Item> {
read_entry(&mut self.0).transpose()
}
}
#[cfg(test)]
mod test {
use super::super::{AuthEntry, Family};
use super::read_entry;
use alloc::vec;
use std::io::Cursor;
#[test]
fn test_read() {
// Data generated via xauth -f /tmp/file add :1 bar deadbeef
let data = [
0x01, 0x00, 0x00, 0x07, 0x5a, 0x77, 0x65, 0x69, 0x4c, 0x45, 0x44, 0x00, 0x01, 0x31,
0x00, 0x03, 0x62, 0x61, 0x72, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef,
];
let mut cursor = Cursor::new(&data[..]);
let entry = read_entry(&mut cursor).unwrap();
assert_eq!(
entry,
Some(AuthEntry {
family: Family::LOCAL,
address: b"ZweiLED".to_vec(),
number: b"1".to_vec(),
name: b"bar".to_vec(),
data: u32::to_be_bytes(0xdead_beef).to_vec(),
})
);
}
#[test]
fn test_read_iterate() {
// Data generated via:
// xauth -f /tmp/file add :1 bar deadbeef
// xauth -f /tmp/file add 1.2.3.4:2 baz aabbccdd
let data = [
0x01, 0x00, 0x00, 0x07, 0x5a, 0x77, 0x65, 0x69, 0x4c, 0x45, 0x44, 0x00, 0x01, 0x31,
0x00, 0x03, 0x62, 0x61, 0x72, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x00,
0x04, 0x01, 0x02, 0x03, 0x04, 0x00, 0x01, 0x32, 0x00, 0x03, 0x62, 0x61, 0x7a, 0x00,
0x04, 0xaa, 0xbb, 0xcc, 0xdd,
];
let mut cursor = Cursor::new(&data[..]);
for expected in &[
AuthEntry {
family: Family::LOCAL,
address: b"ZweiLED".to_vec(),
number: b"1".to_vec(),
name: b"bar".to_vec(),
data: u32::to_be_bytes(0xdead_beef).to_vec(),
},
AuthEntry {
family: Family::INTERNET,
address: vec![1, 2, 3, 4],
number: b"2".to_vec(),
name: b"baz".to_vec(),
data: u32::to_be_bytes(0xaabb_ccdd).to_vec(),
},
] {
let entry = read_entry(&mut cursor).unwrap();
assert_eq!(entry.as_ref(), Some(expected));
}
let entry = read_entry(&mut cursor).unwrap();
assert_eq!(entry, None);
}
}
}
pub(crate) type AuthInfo = (Vec<u8>, Vec<u8>);
/// Get the authentication information necessary for connecting to the given display.
///
/// - `family` is the protocol family that is used for connecting; this describes how to interpret
/// the `address`.
/// - `address` is the raw bytes describing the address that is being connected to.
/// - `display` is the display number.
///
/// If successful, this function returns that can be written to the X11 server as authorization
/// protocol name and data, respectively.
pub fn get_auth(family: Family, address: &[u8], display: u16) -> Result<Option<AuthInfo>, Error> {
match file::XAuthorityEntries::new()? {
None => Ok(None),
Some(entries) => get_auth_impl(entries, family, address, display),
}
}
fn get_auth_impl(
entries: impl Iterator<Item = Result<AuthEntry, Error>>,
family: Family,
address: &[u8],
display: u16,
) -> Result<Option<AuthInfo>, Error> {
fn address_matches(
(family1, address1): (Family, &[u8]),
(family2, address2): (Family, &[u8]),
) -> bool {
if family1 == Family::WILD || family2 == Family::WILD {
true
} else if family1 != family2 {
false
} else {
address1 == address2
}
}
fn display_number_matches(entry_number: &[u8], display_number: &[u8]) -> bool {
debug_assert!(!display_number.is_empty()); // This case is not handled here and would be a match
entry_number.is_empty() || entry_number == display_number
}
let display = display.to_string();
let display = display.as_bytes();
for entry in entries {
let entry = entry?;
if address_matches((family, address), (entry.family, &entry.address))
&& display_number_matches(&entry.number, display)
&& entry.name == MIT_MAGIC_COOKIE_1
{
return Ok(Some((entry.name, entry.data)));
}
}
Ok(None)
}
#[cfg(test)]
mod test {
use super::{get_auth_impl, AuthEntry, Family, MIT_MAGIC_COOKIE_1};
use alloc::vec;
// Call the given function on a matching auth entry. The function can change the entry.
// Afterwards, it should still be a match.
fn expect_match<F>(f: F)
where
F: FnOnce(&mut AuthEntry),
{
let mut entry = AuthEntry {
family: Family::LOCAL,
address: b"whatever".to_vec(),
number: b"42".to_vec(),
name: MIT_MAGIC_COOKIE_1.to_vec(),
data: b"1234".to_vec(),
};
f(&mut entry);
let entries = vec![Ok(entry)];
assert_eq!(
get_auth_impl(entries.into_iter(), Family::LOCAL, b"whatever", 42)
.unwrap()
.unwrap(),
(MIT_MAGIC_COOKIE_1.to_vec(), b"1234".to_vec())
);
}
// Call the given function on a matching auth entry. The function can change the entry.
// Afterwards, it should no longer match.
fn expect_mismatch<F>(f: F)
where
F: FnOnce(&mut AuthEntry),
{
let mut entry = AuthEntry {
family: Family::LOCAL,
address: b"whatever".to_vec(),
number: b"42".to_vec(),
name: MIT_MAGIC_COOKIE_1.to_vec(),
data: b"1234".to_vec(),
};
f(&mut entry);
let entries = vec![Ok(entry)];
assert_eq!(
get_auth_impl(entries.into_iter(), Family::LOCAL, b"whatever", 42).unwrap(),
None
);
}
#[test]
fn direct_match() {
// This checks that an auth entry where all members match, really matches
expect_match(|_| {});
}
#[test]
fn display_wildcard() {
expect_match(|entry| entry.number = vec![]);
}
#[test]
fn address_wildcard_match1() {
expect_match(|entry| entry.family = Family::WILD);
}
#[test]
fn address_wildcard_match2() {
let entry = AuthEntry {
family: Family::LOCAL,
address: b"whatever".to_vec(),
number: b"42".to_vec(),
name: MIT_MAGIC_COOKIE_1.to_vec(),
data: b"1234".to_vec(),
};
let entries = vec![Ok(entry)];
assert_eq!(
get_auth_impl(entries.into_iter(), Family::WILD, &[], 42)
.unwrap()
.unwrap(),
(MIT_MAGIC_COOKIE_1.to_vec(), b"1234".to_vec())
);
}
#[test]
fn family_mismatch() {
expect_mismatch(|entry| entry.family = Family::KRB5_PRINCIPAL);
}
#[test]
fn address_mismatch() {
expect_mismatch(|entry| entry.address = b"something else".to_vec());
}
#[test]
fn number_mismatch() {
expect_mismatch(|entry| entry.number = b"1337".to_vec());
}
#[test]
fn protocol_mismatch() {
expect_mismatch(|entry| entry.name = b"XDM-AUTHORIZATION-1".to_vec());
}
}