Struct xcb::Connection

source ·
pub struct Connection { /* private fields */ }
Expand description

Connection is the central object of XCB.

It handles all communications with the X server. It dispatches the requests, receives the replies, poll/wait the events. It also resolves the errors and events from X server.

Connection is thread safe.

It internally wraps an xcb_connection_t object and will call xcb_disconnect when the Connection goes out of scope.

Implementations§

source§

impl Connection

source

pub fn connect(display_name: Option<&str>) -> ConnResult<(Connection, i32)>

Connects to the X server.

Connects to the X server specified by display_name. If display_name is None, uses the value of the DISPLAY environment variable.

If no screen is preferred, the second member of the tuple is set to 0.

§Example
fn main() -> xcb::Result<()> {
    let (conn, screen) = xcb::Connection::connect(None)?;
    Ok(())
}
source

pub fn connect_with_extensions( display_name: Option<&str>, mandatory: &[Extension], optional: &[Extension] ) -> ConnResult<(Connection, i32)>

Connects to the X server and cache extension data.

Connects to the X server specified by display_name. If display_name is None, uses the value of the DISPLAY environment variable.

Extension data specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

If no screen is preferred, the second member of the tuple is set to 0.

§Panics

Panics if one of the mandatory extension is not present.

§Example
fn main() -> xcb::Result<()> {
    let (conn, screen) = xcb::Connection::connect_with_extensions(
        None, &[xcb::Extension::Input, xcb::Extension::Xkb], &[]
    )?;
    Ok(())
}
source

pub fn connect_with_xlib_display() -> ConnResult<(Connection, i32)>

Open a new connection with Xlib.

The event queue owner defaults to Xlib. One would need to open an XCB connection with Xlib in order to use OpenGL.

This function is behind the xlib_xcb cargo feature.

source

pub fn connect_with_xlib_display_and_extensions( mandatory: &[Extension], optional: &[Extension] ) -> ConnResult<(Connection, i32)>

Open a new connection with Xlib and cache the provided extensions data.

Data of extensions specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

The event queue owner defaults to Xlib. One would need to open an XCB connection with Xlib in order to use OpenGL.

This function is behind the xlib_xcb cargo feature.

§Panics

Panics if one of the mandatory extension is not present.

source

pub fn connect_to_fd( fd: RawFd, auth_info: Option<AuthInfo<'_>> ) -> ConnResult<Self>

Connects to the X server with an open socket file descriptor and optional authentification info.

Connects to an X server, given the open socket fd and the auth_info. The file descriptor fd is bidirectionally connected to an X server. If the connection should be unauthenticated, auth_info must be None.

source

pub fn connect_to_fd_with_extensions( fd: RawFd, auth_info: Option<AuthInfo<'_>>, mandatory: &[Extension], optional: &[Extension] ) -> ConnResult<Self>

Connects to the X server with an open socket file descriptor and optional authentification info.

Extension data specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

Connects to an X server, given the open socket fd and the auth_info. The file descriptor fd is bidirectionally connected to an X server. If the connection should be unauthenticated, auth_info must be None.

§Panics

Panics if one of the mandatory extension is not present.

source

pub fn connect_to_display_with_auth_info( display_name: Option<&str>, auth_info: AuthInfo<'_> ) -> ConnResult<(Connection, i32)>

Connects to the X server, using an authorization information.

Connects to the X server specified by display_name, using the authorization auth_info. If a particular screen on that server, it is returned in the second tuple member, which is otherwise set to 0.

source

pub fn connect_to_display_with_auth_info_and_extensions( display_name: Option<&str>, auth_info: AuthInfo<'_>, mandatory: &[Extension], optional: &[Extension] ) -> ConnResult<(Connection, i32)>

Connects to the X server, using an authorization information.

Extension data specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

Connects to the X server specified by display_name, using the authorization auth_info. If a particular screen on that server, it is returned in the second tuple member, which is otherwise set to 0.

§Panics

Panics if one of the mandatory extension is not present.

source

pub unsafe fn from_raw_conn(conn: *mut xcb_connection_t) -> Connection

builds a new Connection object from an available connection

§Safety

The conn pointer must point to a valid xcb_connection_t

source

pub unsafe fn from_raw_conn_and_extensions( conn: *mut xcb_connection_t, mandatory: &[Extension], optional: &[Extension] ) -> Connection

Builds a new Connection object from an available connection and cache the extension data

Extension data specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

§Panics

Panics if the connection is null or in error state. Panics if one of the mandatory extension is not present.

§Safety

The conn pointer must point to a valid xcb_connection_t

source

pub unsafe fn from_xlib_display(dpy: *mut Display) -> Connection

Initialize a new Connection from an existing Xlib display.

Wraps a xlib::Display and get an XCB connection from an exisiting object xlib::XCloseDisplay will be called when the returned object is dropped.

This function is behind the xlib_xcb cargo feature.

§Safety

The dpy pointer must be a pointer to a valid xlib::Display

source

pub unsafe fn from_xlib_display_and_extensions( dpy: *mut Display, mandatory: &[Extension], optional: &[Extension] ) -> Connection

Initialize a new Connection from an existing Xlib display.

Wraps a xlib::Display and get an XCB connection from an exisiting object xlib::XCloseDisplay will be called when the returned object is dropped.

Extension data specified by mandatory and optional is cached to allow the resolution of events and errors in these extensions.

This function is behind the xlib_xcb cargo feature.

§Panics

Panics if the connection is null or in error state.

§Safety

The dpy pointer must be a pointer to a valid xlib::Display.

source

pub fn active_extensions(&self) -> impl Iterator<Item = Extension> + '_

Get the extensions activated for this connection.

You may use this to check if an optional extension is present or not.

§Example
    // Xkb is mandatory, Input is optional
    let (conn, screen) = xcb::Connection::connect_with_extensions(
        None, &[xcb::Extension::Xkb], &[xcb::Extension::Input]
    )?;
    // now we check if Input is present or not
    let has_input_ext = conn.active_extensions().any(|e| e == xcb::Extension::Input);
source

pub fn get_raw_conn(&self) -> *mut xcb_connection_t

Returns the inner ffi xcb_connection_t pointer

source

pub fn into_raw_conn(self) -> *mut xcb_connection_t

Consumes this object, returning the inner ffi xcb_connection_t pointer

source

pub fn get_raw_dpy(&self) -> *mut Display

Returns the inner ffi xlib::Display pointer.

This function is behind the xlib_xcb cargo feature.

source

pub fn set_event_queue_owner(&self, owner: EventQueueOwner)

Sets the owner of the event queue in the case if the connection is opened with the Xlib interface. In that case, the default owner is Xlib.

This function is behind the xlib_xcb cargo feature.

source

pub fn get_maximum_request_length(&self) -> u32

Returns the maximum request length that this server accepts.

In the absence of the BIG-REQUESTS extension, returns the maximum request length field from the connection setup data, which may be as much as 65535. If the server supports BIG-REQUESTS, then the maximum request length field from the reply to the BigRequestsEnable request will be returned instead.

Note that this length is measured in four-byte units, making the theoretical maximum lengths roughly 256kB without BIG-REQUESTS and 16GB with.

source

pub fn prefetch_maximum_request_length(&self)

Prefetch the maximum request length without blocking.

Without blocking, does as much work as possible toward computing the maximum request length accepted by the X server.

Invoking this function may send the crate::bigreq::Enable request, but will not block waiting for the reply. Connection::get_maximum_request_length will return the prefetched data after possibly blocking while the reply is retrieved.

Note that in order for this function to be fully non-blocking, the application must previously have called crate::bigreq::prefetch_extension_data.

source

pub fn generate_id<T: XidNew>(&self) -> T

Allocates an XID for a new object.

Returned value is typically used in requests such as CreateWindow.

§Example
let window: x::Window = conn.generate_id();
source

pub fn flush(&self) -> ConnResult<()>

Forces any buffered output to be written to the server.

Forces any buffered output to be written to the server. Blocks until the write is complete.

There are several occasions ones want to flush the connection. One of them is before entering or re-entering the event loop after performing unchecked requests.

The main difference between flush and check_request is that flush will not report protocol errors. If a protocol error is emitted by an unchecked void request, it will be reported through the event loop.

See also: wait_for_event, check_request, send_and_check_request.

source

pub unsafe fn resolve_event(&self, ev: &mut xcb_generic_event_t) -> Event

Resolve an xcb_generic_event_t pointer into an Event.

§Safety

The caller is repsonsible to ensure that the ev pointer is not NULL. The ownership of the pointer is effectively transferred to the returned Event and it will be destroyed when the Event is dropped.

source

pub fn wait_for_event(&self) -> Result<Event>

Blocks and returns the next event or error from the server.

§Example
use xcb::x;
fn main() -> xcb::Result<()> {
    // ...
    loop {
        let event = match conn.wait_for_event() {
            Err(xcb::Error::Connection(err)) => {
                panic!("unexpected I/O error: {}", err);
            }
            Err(xcb::Error::Protocol(xcb::ProtocolError::X(x::Error::Font(err), _req_name))) => {
                // may be this particular error is fine?
                continue;
            }
            Err(xcb::Error::Protocol(err)) => {
                panic!("unexpected protocol error: {:#?}", err);
            }
            Ok(event) => event,
        };
        match event {
            xcb::Event::X(x::Event::KeyPress(ev)) => {
                // do stuff with the key press
            }
            // handle other events
            _ => {
                break Ok(());
            }
        }
    }
 }
source

pub fn poll_for_event(&self) -> Result<Option<Event>>

Returns the next event or error from the server without blocking.

Returns the next event or error from the server, if one is available. If no event is available, that might be because an I/O error like connection close occurred while attempting to read the next event, in which case the connection is shut down when this function returns.

source

pub fn poll_for_queued_event(&self) -> ProtocolResult<Option<Event>>

Returns the next event without reading from the connection.

This is a version of Connection::poll_for_event that only examines the event queue for new events. The function doesn’t try to read new events from the connection if no queued events are found.

This function is useful for callers that know in advance that all interesting events have already been read from the connection. For example, callers might use Connection::wait_for_reply and be interested only of events that preceded a specific reply.

source

pub fn register_for_special_xge<XGE: GeEvent>(&self) -> SpecialEventId

👎Deprecated: Broken API: use register_for_special_event instead

Start listening for a special event.

Effectively creates an internal special queue for this event XGE events are only defined in the xinput and present extensions

This function is present only if either of the xinput or present cargo features are active.

source

pub fn unregister_for_special_xge(&self, se: SpecialEventId)

👎Deprecated: use unregister_for_special_event instead

Stop listening to a special event

source

pub fn wait_for_special_event(&self, se: SpecialEventId) -> Result<Event>

👎Deprecated: Broken API: use wait_for_special_event2 instead

Returns the next event from a special queue, blocking until one arrives

source

pub fn poll_for_special_event( &self, se: SpecialEventId ) -> Result<Option<Event>>

👎Deprecated: Broken API: use poll_for_special_event2 instead

Returns the next event from a special queue

source

pub fn register_for_special_event<EID: Xid>( &self, extension: Extension, eid: EID ) -> SpecialEvent

Start listening for a special event.

Effectively creates an internal special queue for this event XGE events are only defined in the xinput and present extensions

This function is present only if either of the xinput or present cargo features are active.

source

pub fn unregister_for_special_event(&self, se: SpecialEvent)

Stop listening to a special event

source

pub fn wait_for_special_event2(&self, se: &SpecialEvent) -> Result<Event>

Returns the next event from a special queue, blocking until one arrives

source

pub fn poll_for_special_event2( &self, se: &SpecialEvent ) -> Result<Option<Event>>

Returns the next event from a special queue

source

pub fn get_setup(&self) -> &Setup

Access the data returned by the server.

Accessor for the data returned by the server when the connection was initialized. This data includes

  • the server’s required format for images,
  • a list of available visuals,
  • a list of available screens,
  • the server’s maximum request length (in the absence of the BIG-REQUESTS extension),
  • and other assorted information.

See the X protocol specification for more details.

source

pub fn has_error(&self) -> ConnResult<()>

Test whether the connection has shut down due to a fatal error.

Some errors that occur in the context of a connection are unrecoverable. When such an error occurs, the connection is shut down and further operations on the connection have no effect.

source

pub fn send_request<R>(&self, req: &R) -> R::Cookie
where R: Request,

Send a request to the X server.

This function never blocks. A cookie is returned to keep track of the request. If the request expect a reply, the cookie can be used to retrieve the reply with Connection::wait_for_reply.

§Example
    // Example of void request.
    // Error (if any) will be sent to the event loop (see `wait_for_event`).
    // In this case, the cookie can be discarded.
    conn.send_request(&x::CreateWindow {
        depth: x::COPY_FROM_PARENT as u8,
        wid: window,
        parent: screen.root(),
        x: 0,
        y: 0,
        width: 150,
        height: 150,
        border_width: 10,
        class: x::WindowClass::InputOutput,
        visual: screen.root_visual(),
        value_list: &[
            x::Cw::BackPixel(screen.white_pixel()),
            x::Cw::EventMask(x::EventMask::EXPOSURE | x::EventMask::KEY_PRESS),
        ],
    });

    // Example of request with reply. The error (if any) is obtained with the reply.
    let cookie = conn.send_request(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    });
    let wm_protocols_atom: x::Atom = conn
            .wait_for_reply(cookie)?
            .atom();
source

pub fn send_request_checked<R>(&self, req: &R) -> VoidCookieChecked

Send a checked request to the X server.

Checked requests do not expect a reply, but the returned cookie can be used to check for errors using Connection::check_request.

§Example
    let cookie = conn.send_request_checked(&x::MapWindow { window });
    conn.check_request(cookie)?;
source

pub fn send_request_unchecked<R>(&self, req: &R) -> R::CookieUnchecked

Send an unchecked request to the X server.

Unchecked requests expect a reply that is to be retrieved by Connection::wait_for_reply_unchecked. Unchecked means that the error is not checked when the reply is fetched. Instead, the error will be sent to the event loop

§Example
    let cookie = conn.send_request_unchecked(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    });
    let wm_protocols_atom: Option<x::Atom> = conn
            .wait_for_reply_unchecked(cookie)?
            .map(|rep| rep.atom());
source

pub fn check_request(&self, cookie: VoidCookieChecked) -> ProtocolResult<()>

Check a checked request for errors.

The cookie supplied to this function must have resulted from a call to Connection::send_request_checked. This function will block until one of two conditions happens. If an error is received, it will be returned. If a reply to a subsequent request has already arrived, no error can arrive for this request, so this function will return Ok(()).

Note that this function will perform a sync if needed to ensure that the sequence number will advance beyond that provided in cookie; this is a convenience to avoid races in determining whether the sync is needed.

§Example
    conn.check_request(conn.send_request_checked(&x::MapWindow { window }))?;
source

pub fn send_and_check_request<R>(&self, req: &R) -> ProtocolResult<()>

Send the request to the server and check it.

This is a sugar for conn.check_request(conn.send_request_checked(req))

This method is useful as well in place of code sending a void request and flushing the connection right after. Checking the request effectively flushes the connection, but in addition reports possible protocol errors at the calling site instead of reporting them through the event loop.

§Example
    conn.send_and_check_request(&x::MapWindow { window })?;
source

pub fn wait_for_reply<C>(&self, cookie: C) -> Result<C::Reply>

Gets the reply of a previous request, or an error if one occurred.

This is blocking; it does not return until the reply has been received. For the non-blocking version, see poll_for_reply.

§Example
    let cookie = conn.send_request(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    });
    let wm_protocols_atom: x::Atom = conn
            .wait_for_reply(cookie)?
            .atom();
source

pub fn wait_for_reply_unchecked<C>( &self, cookie: C ) -> ConnResult<Option<C::Reply>>

Get the reply of a previous unchecked request.

If an error occurred, None is returned and the error will be delivered to the event loop.

This is blocking; it does not return until the reply has been received. For the non-blocking version, see poll_for_reply_unchecked.

§Example
    let cookie = conn.send_request_unchecked(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    });
    let wm_protocols_atom: Option<x::Atom> = conn
            .wait_for_reply_unchecked(cookie)?  // connection error may happen
            .map(|rep| rep.atom());
source

pub fn poll_for_reply<C>(&self, cookie: &C) -> Option<Result<C::Reply>>

Gets the reply of a previous request if it has been received, or an error if one occurred.

This is non-blocking; if no reply has been received yet, it returns None. For the blocking version, see wait_for_reply.

§Examples
let (wm_protocols_cookie, wm_name_cookie) = (
    conn.send_request(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    }),
    conn.send_request(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_NAME",
    }),
);
let (wm_protocols_atom, wm_name_atom) = {
    let (
        mut wm_protocols_atom,
        mut wm_name_atom,
    ) = (None, None);

    loop {
        // If `wm_protocols_atom` is yet to be received, poll for it.
        if wm_protocols_atom.is_none() {
            wm_protocols_atom = conn
                .poll_for_reply(&wm_protocols_cookie)
                .transpose()?
                .map(|reply| reply.atom());
        }
        // If `wm_name_atom` is yet to be received, poll for it.
        if wm_name_atom.is_none() {
            wm_name_atom = conn
                .poll_for_reply(&wm_name_cookie)
                .transpose()?
                .map(|reply| reply.atom());
        }

        // If both `wm_protocols_atom` and `wm_name_atom` have been
        // received, break from the loop.
        if let (
            Some(wm_protocols_atom),
            Some(wm_name_atom),
        ) = (wm_protocols_atom, wm_name_atom) {
            break (wm_protocols_atom, wm_name_atom);
        }
    }
};
source

pub fn poll_for_reply_unchecked<C>( &self, cookie: &C ) -> Option<ConnResult<Option<C::Reply>>>

Gets the reply of a previous unchecked request if it has been received.

If an error occurred, None is returned and the error is delivered to the event loop.

This is non-blocking; if no reply has been received yet, it returns Some(None). For the blocking version, see wait_for_reply_unchecked.

§Examples
let (wm_protocols_cookie, wm_name_cookie) = (
    conn.send_request_unchecked(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_PROTOCOLS",
    }),
    conn.send_request_unchecked(&x::InternAtom {
        only_if_exists: true,
        name: b"WM_NAME",
    }),
);
let (wm_protocols_atom, wm_name_atom) = {
    let (
        mut wm_protocols_atom,
        mut wm_name_atom,
    ) = (Some(None), Some(None));

    loop {
        // If `wm_protocols_atom` is yet to be received, poll for it.
        if let Some(None) = wm_protocols_atom {
            wm_protocols_atom = conn
                // connection error may happen
                .poll_for_reply_unchecked(&wm_protocols_cookie)
                .transpose()?
                .map(|result| result.map(|reply| reply.atom()));
        }
        // If `wm_name_atom` is yet to be received, poll for it.
        if let Some(None) = wm_name_atom {
            wm_name_atom = conn
                // connection error may happen
                .poll_for_reply_unchecked(&wm_name_cookie)
                .transpose()?
                .map(|result| result.map(|reply| reply.atom()));
        }

        match (wm_protocols_atom, wm_name_atom) {
            // If either `wm_protocols_atom` or `wm_name_atom` hasn't
            // been received, continue the loop.
            (Some(None), _) | (_, Some(None)) => continue,

            // Otherwise, if both have been received, break from the
            // loop.
            (
                wm_protocols_atom,
                wm_name_atom,
            ) => break (
                wm_protocols_atom.flatten(),
                wm_name_atom.flatten(),
            ),
        }
    }
};
source

pub fn total_read(&self) -> usize

Obtain number of bytes read from the connection.

Returns cumulative number of bytes received from the connection.

This retrieves the total number of bytes read from this connection, to be used for diagnostic/monitoring/informative purposes.

Since: libxcb 1.14

source

pub fn total_written(&self) -> usize

Obtain number of bytes written to the connection.

Returns cumulative number of bytes sent to the connection.

This retrieves the total number of bytes written to this connection, to be used for diagnostic/monitoring/informative purposes.

Since: libxcb 1.14

Trait Implementations§

source§

impl AsRawFd for Connection

source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
source§

impl AsRawXcbConnection for Connection

source§

fn as_raw_xcb_connection(&self) -> *mut xcb_connection_t

Get a raw xcb connection pointer from this object.
source§

impl AsRef<Connection> for Connection

source§

fn as_ref(&self) -> &Connection

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Drop for Connection

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl Send for Connection

source§

impl Sync for Connection

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.