### setup() Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Retrieves the setup information from the X11 server, which includes details about screens, visuals, depths, and formats. ```APIDOC ## setup() ### Description Returns the setup information received from the X11 server during connection initialization, containing details about available screens, visuals, depths, and formats. ### Method `pub fn setup(&self) -> &Setup` ### Returns `&Setup` - The X11 server setup data ### Example ```rust let (conn, screen_num) = x11rb::connect(None)?; let setup = conn.setup(); let screen = &setup.roots[screen_num]; println!("Screen width: {}", screen.width_in_pixels); ``` ``` -------------------------------- ### Running Simple Window Example Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md Execute the 'simple_window' example using Cargo. This demonstrates basic window creation. ```bash cargo run --example simple_window ``` -------------------------------- ### Running Window Manager Example Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md Execute the 'simple_window_manager' example using Cargo. This demonstrates the creation of a basic window manager. ```bash cargo run --example simple_window_manager ``` -------------------------------- ### Running Window Example with Features Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md Run the 'simple_window' example with additional features enabled, such as 'cursor' and 'resource_manager'. This showcases advanced window capabilities. ```bash cargo run --example simple_window --features cursor,resource_manager ``` -------------------------------- ### Listing Example Files Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md List all files within the 'x11rb/examples/' directory using the `ls` command. This helps in identifying available example programs. ```bash ls x11rb/examples/ ``` -------------------------------- ### Get X11 Server Setup Information Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Retrieve setup details from the X11 server, such as screen dimensions and available visuals. This is typically done once after establishing a connection. ```rust let (conn, screen_num) = x11rb::connect(None)?; let setup = conn.setup(); let screen = &setup.roots[screen_num]; println!("Screen width: {}", screen.width_in_pixels); ``` -------------------------------- ### X11 Server Setup Information Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md The `Setup` struct contains server configuration details received upon connection. It includes protocol versions, resource ID information, and lists of available pixmap formats and screens. ```rust pub struct Setup { pub status: u8, pub protocol_major_version: u16, pub protocol_minor_version: u16, pub release_number: u32, pub resource_id_base: u32, pub resource_id_mask: u32, pub motion_buffer_size: u32, pub maximum_request_length: u16, pub image_byte_order: u8, pub bitmap_format_bit_order: u8, pub bitmap_format_scanline_unit: u8, pub bitmap_format_scanline_pad: u8, pub min_keycode: u8, pub max_keycode: u8, pub vendor: Vec, pub pixmap_formats: Vec, pub roots: Vec, } ``` ```rust let setup = conn.setup(); let screen = &setup.roots[screen_num]; println!("Server: {}", String::from_utf8_lossy(&setup.vendor)); println!("Protocol: {}.{}", setup.protocol_major_version, setup.protocol_minor_version); ``` -------------------------------- ### X11 Resource File Examples Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Provides examples of common resource settings in X11 resource files, such as font, color, geometry, and boolean values. ```plaintext ! Font specifications appname.font.name: fixed appname.font.size: 12 ! Colors appname.foreground: black appname.background: white appname.button.background: lightgray ! Geometry appname.window.width: 800 appname.window.height: 600 appname.geometry: 800x600+100+100 ! Booleans appname.enableLogging: true appname.debug: false ``` -------------------------------- ### Resource Database Example Usage Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Demonstrates how to obtain a resource database cookie and retrieve the database. ```rust let cookie = new_from_default(conn)?; let db = cookie.reply()?; ``` -------------------------------- ### Setup Cursor Theme from Resources Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Loads cursor theme settings from default resources and initializes a cursor handle. ```rust use x11rb::cursor::Handle as CursorHandle; use x11rb::resource_manager::new_from_default; use x11rb::connection::Connection; fn setup_cursor_theme( conn: &impl Connection, screen_num: usize, ) -> Result> { let resource_db = new_from_default(conn)?.reply()?; // Cursor theme is typically stored in resources let cursor_theme = resource_db.get("xcursor.theme", "XCursor.Theme") .unwrap_or_else(|| "default".to_string()); println!("Using cursor theme: {}", cursor_theme); // Create cursor handle using resource database let cursor_handle = CursorHandle::new(conn, screen_num, &resource_db)? .reply()?; Ok(cursor_handle) } ``` -------------------------------- ### X11 Resource Wildcard Matching Examples Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Illustrates different levels of priority for X11 resource matching using exact matches, wildcards, and class-based fallbacks. ```text ! Exact match (highest priority) myapp.button.background: red ! Wildcard matches (intermediate) myapp*background: blue *background: gray ! Class-based fallback MyApp*Background: yellow ``` -------------------------------- ### CreateWindowAux Usage Example Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md Demonstrates how to instantiate and configure CreateWindowAux for creating a window. Sets background and border colors, and specifies event masks and cursor. ```rust let aux = CreateWindowAux::new() .background_pixel(screen.white_pixel) .border_pixel(screen.black_pixel) .event_mask(EventMask::EXPOSURE | EventMask::KEY_PRESS) .cursor(cursor_id); conn.create_window( screen.root_depth, window_id, screen.root, 0, 0, 100, 100, 1, WindowClass::INPUT_OUTPUT, screen.root_visual, &aux, )?; ``` -------------------------------- ### Example of File Descriptor Passing with Shared Memory Source: https://github.com/psychon/x11rb/blob/master/README.md This example demonstrates file descriptor passing with the X11 server using the shared memory extension. ```rust x11rb/examples/shared_memory.rs // ... code omitted for brevity ... ``` -------------------------------- ### Rust ConnectError Usage Example Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Demonstrates how to handle ConnectError when attempting to connect to an X11 server. ```rust use x11rb::connect; use x11rb::errors::ConnectError; match connect(None) { Ok((conn, screen)) => println!("Connected, screen: {}", screen), Err(ConnectError::IoError(e)) => eprintln!("Cannot connect: {}", e), Err(ConnectError::DisplayParsingError(e)) => eprintln!("Bad display: {:?}", e), Err(e) => eprintln!("Connection failed: {:?}", e), } ``` -------------------------------- ### Example Usage of ExtensionInformation Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/extension_manager.md Demonstrates how to retrieve and use ExtensionInformation for an extension like RANDR, accessing its opcode and event/error IDs. ```rust let info = ext_manager.extension_information(conn, "RANDR")?; if let Some(ext_info) = info { println!("RANDR opcode: {}", ext_info.major_opcode); // Use major_opcode for manual request construction if needed let request = build_extension_request(ext_info.major_opcode); // Use first_event to identify RANDR-specific events if event_type >= ext_info.first_event && event_type < ext_info.first_error { println!("This is a RANDR event"); } } ``` -------------------------------- ### Usage of Atom Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md Shows how to use an `Atom` (e.g., `AtomEnum::WM_NAME`) when getting a property from a window. ```rust conn.get_property(false, window_id, AtomEnum::WM_NAME, AtomEnum::STRING, 0, 1024)?; ``` -------------------------------- ### WmHints Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/properties.md Represents and provides methods to get a window's WM_HINTS property. ```APIDOC ## WmHints::get ### Description Retrieves the WM_HINTS property for a given window. ### Method `WmHints::get(conn, window)` ### Parameters - **conn**: Connection object - **window**: The window ID ### Response - `Result`: A cookie for the asynchronous request. ## WmHints::from_reply ### Description Parses the reply from a WM_HINTS property request. ### Method `WmHints::from_reply(reply)` ### Parameters - **reply**: The reply from the WM_HINTS request. ### Response - `Result>`: An optional WmHints object if the property exists. ``` -------------------------------- ### Get Window Properties Concurrently Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/properties.md Retrieves window class, hints, and normal hints properties concurrently. Requires the `Connection` trait and `Window` type from x11rb. Properties are fetched using `get` methods and their replies are processed. ```rust fn get_window_info( conn: &impl Connection, window: Window, ) -> Result<(), Box> { use x11rb::properties::{WmClass, WmNormalHints, WmHints}; // Get multiple properties concurrently let class_cookie = WmClass::get(conn, window)?; let hints_cookie = WmHints::get(conn, window)?; let normal_hints_cookie = WmNormalHints::get(conn, window)?; // Retrieve all replies if let Some(class) = class_cookie.reply()? { println!("Class: {:?}", std::str::from_utf8(class.class())); } if let Some(hints) = hints_cookie.reply()? { println!("Hints: {:?}", hints); } if let Some(normal_hints) = normal_hints_cookie.reply()? { println!("Normal hints: {:?}", normal_hints); } Ok(()) } ``` -------------------------------- ### Create Window with Custom Cursor Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cursor.md An example of creating an X11 window and setting a custom cursor for it. This snippet shows loading a cursor theme, selecting a specific cursor, and applying it during window creation. ```rust use x11rb::connection::Connection; use x11rb::cursor::Handle as CursorHandle; use x11rb::protocol::xproto::* use x11rb::resource_manager::new_from_default; fn create_window_with_cursor( conn: &impl Connection, screen_num: usize, ) -> Result> { let screen = &conn.setup().roots[screen_num]; // Load cursor theme let resource_db = new_from_default(conn)?; let cursor_handle = CursorHandle::new(conn, screen_num, &resource_db)? .reply()?; // Load specific cursor let wait_cursor = match cursor_handle.load_cursor(conn, "wait") { Ok(cursor) => cursor, Err(_) => 0, // Fallback to default cursor }; // Create window with cursor let window_id = conn.generate_id()?; let aux = CreateWindowAux::new() .background_pixel(screen.white_pixel) .cursor(wait_cursor) .event_mask(EventMask::EXPOSURE); conn.create_window( screen.root_depth, window_id, screen.root, 0, 0, 400, 300, 0, WindowClass::INPUT_OUTPUT, screen.root_visual, &aux, )?; Ok(window_id) } ``` -------------------------------- ### Rust ParseError Usage Example Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Demonstrates how to handle ParseError when parsing X11 protocol data using a match statement. ```rust use x11rb::errors::ParseError; use x11rb::x11_utils::TryParse; match some_bytes.try_parse() { Ok(value) => println!("Parsed: {:?}", value), Err(ParseError::InsufficientData) => eprintln!("Not enough data"), Err(ParseError::InvalidValue) => eprintln!("Invalid value"), Err(e) => eprintln!("Parse error: {:?}", e), } ``` -------------------------------- ### Usage of Drawable Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md Shows how to use a `Drawable` (which can be a `Window` or `Pixmap`) to get image data. ```rust // Can be either a Window or Pixmap let drawable: Drawable = window_id; // or pixmap_id conn.get_image(ImageFormat::ZPIXMAP, drawable, /*...*/)?; ``` -------------------------------- ### WmSizeHints Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/properties.md Represents and provides methods to get a window's WM_SIZE_HINTS property. ```APIDOC ## WmSizeHints::get ### Description Retrieves the WM_SIZE_HINTS property for a given window. ### Method `WmSizeHints::get(conn, window)` ### Parameters - **conn**: Connection object - **window**: The window ID ### Response - `Result`: A cookie for the asynchronous request. ## WmSizeHints::from_reply ### Description Parses the reply from a WM_SIZE_HINTS property request. ### Method `WmSizeHints::from_reply(reply)` ### Parameters - **reply**: The reply from the WM_SIZE_HINTS request. ### Response - `Result>`: An optional WmSizeHints object if the property exists. ``` -------------------------------- ### Establish X11 Connection using RustConnection::connect_to_stream() Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Creates an X11 connection using a custom stream implementation. Useful for integrating with custom I/O or network setups. ```rust let (stream, (family, addr)) = DefaultStream::connect(&address)?; let conn = RustConnection::connect_to_stream(stream, 0)?; ``` -------------------------------- ### Access X11 Window Properties Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md Set and get window properties like titles and hints using `change_property` and `get_property`. ```rust use x11rb::wrapper::ConnectionExt; use x11rb::protocol::xproto::AtomEnum; // Set window title conn.change_property8( PropMode::REPLACE, window_id, AtomEnum::WM_NAME, AtomEnum::STRING, b"My Window", )?; // Get window class use x11rb::properties::WmClass; if let Some(class) = WmClass::get(conn, window_id)?.reply()? { println!("Class: {:?}", std::str::from_utf8(class.class())); } ``` -------------------------------- ### Retrieve ListFontsWithInfoReply using reply() Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Use this method to get the next font reply from the server. It returns a Result which can be Ok(ListFontsWithInfoReply) or Err(ReplyError). ```rust let cookie = conn.list_fonts_with_info("*", 100)?; loop { match cookie.reply() { Ok(font_info) if font_info.properties.is_empty() => break, // End marker Ok(font_info) => println!("Font: {:?}", font_info.name), Err(e) => break, } } ``` -------------------------------- ### Create and manage an X11 window with x11rb in Rust Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md This snippet demonstrates connecting to an X11 server, creating a window, setting up a graphics context, mapping the window, and handling basic events such as expose, configure notify, and client messages. ```rust use x11rb::connection::Connection; use x11rb::protocol::xproto::*; fn main() -> Result<(), Box> { // Connect to X11 server let (conn, screen_num) = x11rb::connect(None)?; let screen = &conn.setup().roots[screen_num]; // Create window ID and graphics context ID let win_id = conn.generate_id()?; let gc_id = conn.generate_id()?; // Create the window conn.create_window( screen.root_depth, win_id, screen.root, 0, 0, 640, 480, 1, WindowClass::INPUT_OUTPUT, screen.root_visual, &CreateWindowAux::new() .background_pixel(screen.white_pixel) .event_mask(EventMask::EXPOSURE | EventMask::STRUCTURE_NOTIFY), )?; // Create graphics context conn.create_gc( gc_id, win_id, &CreateGCAux::new().foreground(screen.black_pixel), )?; // Map (show) the window conn.map_window(win_id)?; conn.flush()?; // Event loop loop { let event = conn.wait_for_event()?; match event { Event::Expose(e) if e.count == 0 => { // Draw on the exposed area let points = vec![ Point { x: 0, y: 0 }, Point { x: 320, y: 240 }, ]; conn.poly_line(CoordMode::ORIGIN, win_id, gc_id, &points)?; conn.flush()?; } Event::ConfigureNotify(e) => { println!("Window resized: {}x{}", e.width, e.height); } Event::ClientMessage(e) => break, _ => {} } } Ok(()) } ``` -------------------------------- ### WmNormalHints Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/properties.md Represents and provides methods to get a window's WM_NORMAL_HINTS property. ```APIDOC ## WmNormalHints::get ### Description Retrieves the WM_NORMAL_HINTS property for a given window. ### Method `WmNormalHints::get(conn, window)` ### Parameters - **conn**: Connection object - **window**: The window ID ### Response - `Result`: A cookie for the asynchronous request. ## WmNormalHints::from_reply ### Description Parses the reply from a WM_NORMAL_HINTS property request. ### Method `WmNormalHints::from_reply(reply)` ### Parameters - **reply**: The reply from the WM_NORMAL_HINTS request. ### Response - `Result>`: An optional WmNormalHints object if the property exists. ``` -------------------------------- ### Connect using Environment Variables Source: https://github.com/psychon/x11rb/blob/master/_autodocs/configuration.md Establishes a connection to the X11 server using default parameters derived from environment variables. ```rust let (conn, screen) = x11rb::connect(None)?; ``` -------------------------------- ### X11 Resource File Basic Syntax Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Illustrates the fundamental syntax for X11 resource files, including comments and assignments. ```plaintext ! Comments start with ! ! Simple assignment appname.resource: value ! Wildcard (matches any intermediate segments) appname*resource: value ! Multiple segments appname.window.title: My Application appname.window.width: 800 appname.window.height: 600 ``` -------------------------------- ### GetInputFocusRequest Source: https://github.com/psychon/x11rb/blob/master/doc/generated_code.md Represents a request to get the current input focus. It includes methods for serialization and parsing. ```APIDOC ## Opcode for GetInputFocus Request `pub const GET_INPUT_FOCUS_REQUEST: u8 = 43;` ### Description This constant represents the opcode for the `GetInputFocus` request in the X11 protocol. ### Method N/A (Constant definition) ### Endpoint N/A (Constant definition) ### Parameters N/A ### Request Example ```rust let request = GetInputFocusRequest; let (bufs, fds) = request.serialize(); ``` ### Response N/A (This section describes the request structure, not the response) ``` -------------------------------- ### Create an X11 Window Source: https://github.com/psychon/x11rb/blob/master/_autodocs/quick-start.md Create a new window on the X11 server. This involves specifying parent, position, size, and attributes. ```rust let aux = CreateWindowAux::new() .background_pixel(screen.white_pixel) .event_mask(EventMask::KEY_PRESS | EventMask::EXPOSURE); conn.create_window( screen.root_depth, // Inherit parent depth window_id, // Window to create screen.root, // Parent window 0, 0, // Position 400, 300, // Size 1, // Border width WindowClass::INPUT_OUTPUT, // Window class screen.root_visual, // Visual &aux, // Attributes )?; ``` -------------------------------- ### Usage of Window ID Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md Demonstrates how to generate a `Window` ID and use it to create a window. ```rust let window_id: Window = conn.generate_id()?; conn.create_window(/*...*/, window_id, /*...*/)?; ``` -------------------------------- ### Load Default Application Resources Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Loads default application resources using `new_from_default` and retrieves settings like background color, font size, and window dimensions. ```rust use x11rb::connection::Connection; use x11rb::resource_manager::new_from_default; fn load_app_resources( conn: &impl Connection, ) -> Result<(), Box> { let db = new_from_default(conn)?.reply()?; // Get application settings let bg_color = db.get("myapp.background", "MyApp.Background") .unwrap_or_else(|| "white".to_string()); let font_size = db.get("myapp.fontSize", "MyApp.FontSize") .and_then(|s| s.parse::().ok()) .unwrap_or(12); let window_width = db.get("myapp.window.width", "MyApp.Window.Width") .and_then(|s| s.parse::().ok()) .unwrap_or(800); let window_height = db.get("myapp.window.height", "MyApp.Window.Height") .and_then(|s| s.parse::().ok()) .unwrap_or(600); println!("Background: {}", bg_color); println!("Font size: {}", font_size); println!("Window: {}x{}", window_width, window_height); Ok(()) } ``` -------------------------------- ### Get Input Focus Request Source: https://github.com/psychon/x11rb/blob/master/doc/generated_code.md Provides a convenient method to call the `get_input_focus` function from an extension trait. ```rust fn get_input_focus(&self) -> Result, ConnectionError> { get_input_focus(self) } ``` -------------------------------- ### Create a New X11 Window Source: https://github.com/psychon/x11rb/blob/master/_autodocs/README.md Creates a new input/output window with specified dimensions and event mask. It sets the background pixel and event mask for the window. ```rust let window_id = conn.generate_id()?; conn.create_window( screen.root_depth, window_id, screen.root, 0, 0, 400, 300, 0, WindowClass::INPUT_OUTPUT, screen.root_visual, &CreateWindowAux::new() .background_pixel(screen.white_pixel) .event_mask(EventMask::EXPOSURE), )?; ``` -------------------------------- ### Get VoidCookie Sequence Number Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Retrieves the sequence number of the request that generated a VoidCookie. This is useful for tracking requests. ```rust let cookie = conn.create_window(/*...*/)?; println!("Request sequence: {}", cookie.sequence_number()); ``` -------------------------------- ### Connect to X11 Display using DISPLAY Environment Variable Source: https://github.com/psychon/x11rb/blob/master/_autodocs/configuration.md Connect to the default X11 display using the DISPLAY environment variable. Alternatively, explicitly provide a display name. ```rust // Uses DISPLAY environment variable let (conn, screen_num) = x11rb::connect(None)?; // Or override with explicit display let (conn, screen_num) = x11rb::connect(Some(":1"))?; ``` -------------------------------- ### Prefetching Multiple Extensions Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/extension_manager.md Shows how to efficiently prefetch information for multiple X11 extensions concurrently and then retrieve their cached results. ```rust use x11rb::connection::RequestConnection; use x11rb::extension_manager::ExtensionManager; fn check_extensions( conn: &impl RequestConnection, ) -> Result<(), Box> { let mut ext_manager = ExtensionManager::default(); // Prefetch multiple extensions concurrently let extensions = ["RANDR", "COMPOSITE", "DAMAGE", "SHAPE", "XFIXES"]; for ext_name in &extensions { ext_manager.prefetch_extension_information(conn, ext_name)?; } // Later, retrieve all cached results for ext_name in &extensions { match ext_manager.extension_information(conn, ext_name)? { Some(info) => println!("{}: opcode={}", ext_name, info.major_opcode), None => println!("{}: not available", ext_name), } } Ok(()) } ``` -------------------------------- ### Establish X11 Connection Source: https://github.com/psychon/x11rb/blob/master/_autodocs/README.md Connects to the X server and retrieves the default screen. This is the first step to interacting with the X11 display. ```rust let (conn, screen_num) = x11rb::connect(None)?; let screen = &conn.setup().roots[screen_num]; ``` -------------------------------- ### Segment Struct Definition Source: https://github.com/psychon/x11rb/blob/master/_autodocs/types.md Defines the structure for representing a line segment with start (x1, y1) and end (x2, y2) coordinates. ```rust pub struct Segment { pub x1: i16, pub y1: i16, pub x2: i16, pub y2: i16, } ``` -------------------------------- ### Query Window Class and Instance Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/properties.md Retrieves and prints the WM_CLASS and instance name for a given window. Handles cases where the property is not set or contains invalid UTF-8 data. ```rust use x11rb::connection::Connection; use x11rb::errors::ConnectionError; use x11rb::properties::WmClass; use x11rb::protocol::xproto::Window; fn print_window_class( conn: &impl Connection, window: Window, ) -> Result<(), Box> { let wm_class = match WmClass::get(conn, window)?.reply()? { Some(class) => class, None => { println!("Window has no WM_CLASS property"); return Ok(()); } }; let class = std::str::from_utf8(wm_class.class()) .unwrap_or(""); let instance = std::str::from_utf8(wm_class.instance()) .unwrap_or(""); println!("Window class: {}, instance: {}", class, instance); Ok(()) } ``` -------------------------------- ### Load Resources from .Xresources File Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Loads X11 resources from the user's home directory's .Xresources file using `ResourceDatabase::new_from_file`. ```rust use std::fs::File; use x11rb::resource_manager::ResourceDatabase; fn load_from_xresources() -> Result<(), Box> { let home = std::env::var("HOME")?; let file = File::open(format!("{}/.Xresources", home))?; let db = ResourceDatabase::new_from_file(file)?; if let Some(value) = db.get("myapp.color", "MyApp.Color") { println!("Color setting: {}", value); } Ok(()) } ``` -------------------------------- ### ReplyOrIdError Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Represents errors from requesting a resource ID or getting a reply. It includes the possibility of ID exhaustion in addition to connection or X11 protocol errors. ```APIDOC ## ReplyOrIdError ### Description Represents errors encountered when attempting to obtain a resource ID or receive a reply from an X11 request. This error type accounts for potential ID exhaustion on the server side, alongside connection and protocol errors. ### Variants - `IdsExhausted`: Indicates that all available X11 resource IDs have been allocated by the server. - `ConnectionError(ConnectionError)`: Signifies a problem with the X11 connection. - `X11Error(X11Error)`: Denotes an X11 protocol error reported by the X11 server. ### Usage Example ```rust use x11rb::errors::ReplyOrIdError; match conn.generate_id() { Ok(id) => println!("Generated ID: {}", id), Err(ReplyOrIdError::IdsExhausted) => eprintln!("Out of X11 IDs"), Err(e) => eprintln!("Error: {}", e), } ``` ``` -------------------------------- ### Create Window Request Serialization Source: https://github.com/psychon/x11rb/blob/master/doc/generated_code.md Demonstrates the serialization process for a `CreateWindowRequest`. This is part of the internal implementation of window creation. ```rust impl<'input> Request for CreateWindowRequest<'input> { const EXTENSION_NAME: Option<&'static str> = None; fn serialize(self, _major_opcode: u8) -> BufWithFds> { let (bufs, fds) = self.serialize(); // Flatten the buffers into a single vector let buf = bufs.iter().flat_map(|buf| buf.iter().copied()).collect(); (buf, fds) } } impl<'input> crate::x11_utils::VoidRequest for CreateWindowRequest<'input> { } ``` -------------------------------- ### Get Image Data Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/image.md Retrieves image data from a drawable (window or pixmap). Use this function when you need to capture a specific region of a window or pixmap. ```rust pub fn get_image( conn: &C, format: ImageFormat, drawable: Drawable, x: i16, y: i16, width: u16, height: u16, ) -> Result, ConnectionError> ``` ```rust use x11rb::image::get_image; use x11rb::protocol::xproto::ImageFormat; let cookie = get_image( conn, ImageFormat::ZPIXMAP, window_id, 0, 0, // x, y 640, 480, // width, height )?; let reply = cookie.reply()?; println!("Got {} bytes of image data", reply.data.len()); ``` -------------------------------- ### x11rb::connect() Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Establishes a new connection to an X11 server and returns the connection object plus the default screen number. It can use the DISPLAY environment variable if no display name is provided. ```APIDOC ## x11rb::connect() ### Description Establishes a new connection to an X11 server and returns the connection object plus the default screen number. ### Method `connect` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **dpy_name** (`Option<&str>`) - Optional - Display name (e.g., `:0`, `localhost:0.0`). If `None`, uses `$DISPLAY` environment variable ### Response #### Success Response - `Result<(RustConnection, usize), ConnectError>` - Connection and screen number #### Response Example ```rust let (conn, screen_num) = x11rb::connect(None)?; let screen = &conn.setup().roots[screen_num]; ``` ### Errors - `ConnectError::DisplayParsingError` - Invalid display name - `ConnectError::IoError` - Cannot connect to server - `ConnectError::InvalidScreen` - Invalid screen number ``` -------------------------------- ### Clone xcb-proto Repository (Developer) Source: https://github.com/psychon/x11rb/blob/master/xcb-proto-1.17.0/README.md Use this command to clone the xcb-proto repository for developers with authenticated access. ```bash git clone git@gitlab.freedesktop.org:xorg/proto/xcbproto.git ``` -------------------------------- ### Implement Custom Stream Trait in Rust Source: https://github.com/psychon/x11rb/blob/master/_autodocs/configuration.md This example demonstrates how to implement the `Stream` trait for a custom type, such as a `std::net::TcpStream`, to handle X11 I/O. ```rust use x11rb::rust_connection::stream::{Stream, PollMode}; use x11rb::utils::RawFdContainer; struct MyStream { socket: std::net::TcpStream, } impl Stream for MyStream { fn poll(&self, mode: PollMode) -> Result<(), std::io::Error> { // Implement polling logic Ok(()) } fn read(&self, buf: &mut [u8], _fds: &mut Vec) -> std::io::Result { use std::io::Read; self.socket.read(buf) } fn write(&self, buf: &[u8], _fds: &mut Vec) -> std::io::Result { use std::io::Write; self.socket.write(buf) } } ``` -------------------------------- ### CursorHandleCookie::reply Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cursor.md Retrieves the actual cursor handle after the initial loading operation has been initiated. This method is used to get the handle from the cookie returned by `Handle::new`. ```APIDOC ## CursorHandleCookie::reply ### Description Retrieves the cursor handle after loading cursor data. ### Method `reply` ### Returns `Result` - The cursor handle or error ### Example ```rust let handle = CursorHandle::new(conn, screen_num, &resource_db)? .reply()?; ``` ``` -------------------------------- ### ConnectError Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Represents errors that can occur when establishing an initial connection to an X11 server. It covers issues like display parsing, I/O errors, invalid screens, and setup failures. ```APIDOC ## ConnectError ### Description Represents errors that can occur when establishing an initial connection to an X11 server. It covers issues like display parsing, I/O errors, invalid screens, and setup failures. ### Common Variants - `DisplayParsingError(DisplayParsingError)`: Could not parse display name (e.g., `:0`, `localhost:0.0`). - `IoError(std::io::Error)`: Cannot connect to X11 server (socket error, no such device, etc.). - `InvalidScreen`: Requested screen number does not exist on the server. - `SetupFailed(String)`: Server rejected connection during setup phase. ### Usage Example ```rust use x11rb::connect; use x11rb::errors::ConnectError; match connect(None) { Ok((conn, screen)) => println!("Connected, screen: {}", screen), Err(ConnectError::IoError(e)) => eprintln!("Cannot connect: {}", e), Err(ConnectError::DisplayParsingError(e)) => eprintln!("Bad display: {:?}", e), Err(e) => eprintln!("Connection failed: {:?}", e), } ``` ``` -------------------------------- ### Establish X11 Connection using RustConnection::connect() Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Connects to an X11 server using the pure-Rust implementation, similar to x11rb::connect(). Allows specifying the display name. ```rust use x11rb::rust_connection::RustConnection; let (conn, screen_num) = RustConnection::connect(Some(":0"))?; ``` -------------------------------- ### Get CookieWithFds Reply Unchecked Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Retrieves the reply and file descriptors (FDs) from an X11 server without checking for X11 errors. Errors are delivered as events on the connection instead. ```rust let (reply, fds) = cookie.reply_unchecked()?; for fd in fds { // Handle each file descriptor } ``` -------------------------------- ### Create Window Extension Trait Method Source: https://github.com/psychon/x11rb/blob/master/doc/generated_code.md An extension trait method that simplifies calling the `create_window` function. It allows creating windows directly on a connection object. ```rust /// [SNIP] fn create_window<'c, 'input>(&'c self, depth: u8, wid: Window, parent: Window, x: i16, y: i16, width: u16, height: u16, border_width: u16, class: WindowClass, visual: Visualid, value_list: &'input CreateWindowAux) -> Result, ConnectionError> { create_window(self, depth, wid, parent, x, y, width, height, border_width, class, visual, value_list) } ``` -------------------------------- ### Get Cookie Reply Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Retrieves the reply from an X11 server for a request that expects a response. This method checks for local errors and returns the parsed reply or an error if one occurred. ```rust let cookie = conn.get_window_attributes(window_id)?; let reply = cookie.reply()?; println!("Window depth: {}", reply.depth); ``` -------------------------------- ### Handle GetWindowAttributes Reply with Event-Based Error Handling Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md This pattern uses reply_unchecked() to get the reply without immediate error checking. Errors are expected to be handled later via conn.wait_for_event(). ```rust let cookie = conn.get_window_attributes(window_id)?; let attrs = cookie.reply_unchecked()?; println!("Depth: {}", attrs.depth); // Errors appear in conn.wait_for_event() ``` -------------------------------- ### Enable All X11 Extensions Source: https://github.com/psychon/x11rb/blob/master/README.md The `all-extensions` feature flag enables all available X11 extensions provided by xcb-proto. ```rust Cargo.toml [dependencies] x11rb = { version = "...", features = ["all-extensions"] } ``` -------------------------------- ### Create a new ExtensionManager Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/extension_manager.md Initializes an empty ExtensionManager. This is useful for custom connection implementations that need to manage X11 extension states. ```rust use x11rb::extension_manager::ExtensionManager; let mut ext_manager = ExtensionManager::default(); ``` -------------------------------- ### Get CookieWithFds Reply Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Retrieves the reply and associated file descriptors (FDs) from an X11 server. This method checks for local errors and returns the parsed reply, the list of FDs, or an error. ```rust #[cfg(feature = "dri3")] { let cookie = conn.open_buffer(buffer_fd)?; let (reply, fds) = cookie.reply()?; println!("Got {} file descriptors", fds.len()); } ``` -------------------------------- ### ResourceDatabaseCookie::reply() Method Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/resource_manager.md Retrieves the resource database after asynchronous loading. Returns the database or a connection error. ```rust pub fn reply(self) -> Result ``` -------------------------------- ### Get Cookie Reply Unchecked Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cookies.md Retrieves the reply from an X11 server without checking for X11 errors. If the server sends an error, it will be delivered as an event on the connection instead of being returned directly. ```rust let cookie = conn.get_window_attributes(window_id)?; let reply = cookie.reply_unchecked()?; println!("Window depth: {}", reply.depth); ``` -------------------------------- ### Tag Release Source: https://github.com/psychon/x11rb/blob/master/doc/making_a_release.md Create an annotated Git tag for the new release version. ```shell git tag -a -m "Version 0.2.0" v0.2.0 ``` -------------------------------- ### Handle X11 Protocol Errors Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Demonstrates how to match and handle specific X11 protocol errors returned by the X11 server, such as BadWindow or BadMatch. This is crucial for robust X11 client development. ```rust use x11rb::x11_utils::X11Error; match cookie.reply() { Err(ReplyError::X11Error(e)) => match e { X11Error::BadWindow => eprintln!("Window does not exist"), X11Error::BadMatch => eprintln!("Incompatible parameters"), _ => eprintln!("X11 error: {:?}", e), } _ => {} } ``` -------------------------------- ### Create a new cursor handle Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cursor.md Creates a new cursor handle for loading cursors. This function returns a cookie that needs to be replied to in order to get the actual handle. Ensure the `cursor` feature is enabled. ```rust use x11rb::cursor::Handle as CursorHandle; use x11rb::resource_manager::new_from_default; let resource_db = new_from_default(conn)?; let cursor_handle = CursorHandle::new(conn, screen_num, &resource_db)?; let cursor_handle = cursor_handle.reply()?; ``` -------------------------------- ### Get Extension Information Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/extension_manager.md Retrieves extension information from the cache or by sending a synchronous QueryExtension request. If the extension was previously prefetched, this method waits for and caches the reply. It returns Some(ExtensionInformation) if supported, None if not available, or an Err(ConnectionError) if the query fails. ```rust match ext_manager.extension_information(conn, "RANDR")? { Some(info) => { println!("RANDR major opcode: {}", info.major_opcode); println!("First event: {}", info.first_event); println!("First error: {}", info.first_error); } None => println!("RANDR extension not available"), } ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/psychon/x11rb/blob/master/_autodocs/COMPLETION_REPORT.md This snippet shows the directory structure for the project's documentation, outlining the purpose of each markdown file and the API reference sub-directory. ```text output/ ├── README.md # Project overview, navigation guide ├── quick-start.md # Minimal examples and core concepts ├── configuration.md # Feature flags, environment, settings ├── types.md # X11 protocol type definitions ├── INDEX.md # Master index with cross-references └── api-reference/ ├── connection.md # Core connection API ├── cookies.md # Async request patterns ├── errors.md # Error handling ├── wrapper.md # Convenience methods ├── extension_manager.md # Extension management ├── properties.md # Window properties ├── cursor.md # Cursor support ├── image.md # Image capture └── resource_manager.md # Resource database ``` -------------------------------- ### Minimal x11rb Dependency Source: https://github.com/psychon/x11rb/blob/master/_autodocs/configuration.md Use this configuration for core X11 functionality only. ```toml [dependencies] x11rb = "0.13" ``` -------------------------------- ### Query Extension Information Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/connection.md Use this method to query the X11 server about the availability of a specific extension. It returns extension information if the extension is supported, otherwise None. The extension name is provided as a string slice. ```rust match conn.extension_information("RANDR")? { Some(ext_info) => println!("RANDR major opcode: {}", ext_info.major_opcode), None => println!("RANDR extension not available"), } ``` -------------------------------- ### Full-Featured Application x11rb Dependency Source: https://github.com/psychon/x11rb/blob/master/_autodocs/configuration.md Enable all X11 extensions for comprehensive functionality. ```toml [dependencies] x11rb = { version = "0.13", features = ["all-extensions", "cursor", "image", "resource_manager"] } ``` -------------------------------- ### Checking for X11 Extensions Source: https://github.com/psychon/x11rb/blob/master/_autodocs/README.md Shows how to check for the availability of X11 extensions, such as RANDR, using `extension_information`. Extensions must be enabled via Cargo features. ```rust #[cfg(feature = "randr")] if let Some(_) = conn.extension_information("RANDR")? { // Use RANDR extension } ``` -------------------------------- ### Load Cursor with Fallback Strategy Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/cursor.md Demonstrates a function to load a preferred cursor, falling back to a default if the preferred cursor is not available. This is useful for ensuring a cursor is always displayed, even if custom themes are missing. ```rust fn load_cursor_with_fallback( handle: &CursorHandle, conn: &impl Connection, preferred: &str, fallback: &str, ) -> Cursor { match handle.load_cursor(conn, preferred) { Ok(cursor) => cursor, Err(_) => { match handle.load_cursor(conn, fallback) { Ok(cursor) => cursor, Err(_) => 0, // Default cursor } } } } // Usage let cursor = load_cursor_with_fallback(&handle, conn, "wait", "default"); ``` -------------------------------- ### Handling Connection Errors Source: https://github.com/psychon/x11rb/blob/master/_autodocs/api-reference/errors.md Demonstrates how to handle different ConnectionError variants when waiting for X11 events. ```rust use x11rb::errors::ConnectionError; match conn.wait_for_event() { Ok(event) => handle_event(event), Err(ConnectionError::IoError(e)) => eprintln!("I/O error: {}", e), Err(ConnectionError::UnsupportedExtension) => eprintln!("Extension not available"), Err(e) => eprintln!("Connection error: {}", e), } ```