### RunCommand Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the RunCommand type, showing an array of CommandOutcome objects. ```json [ {"success": true}, {"success": true} ] ``` -------------------------------- ### Subscribe Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for a successful Subscribe command. ```json {"success": true} ``` -------------------------------- ### Common Command Examples Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Provides practical examples of how to use the `run_command` method to interact with Sway, such as focusing windows, moving them, changing workspaces, and managing marks. ```APIDOC ## Common Command Examples ```rust conn.run_command("focus left")?; conn.run_command("move right")?; conn.run_command("workspace 1")?; conn.run_command("fullscreen toggle")?; conn.run_command("floating toggle")?; conn.run_command("mark mymark")?; conn.run_command("unmark mymark")?; ``` ``` -------------------------------- ### GetVersion Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the GetVersion command, including version details and configuration file path. ```json { "major": 1, "minor": 8, "patch": 0, "human_readable": "1.8.0 (12345abc master)", "loaded_config_file_name": "/home/user/.config/sway/config" } ``` -------------------------------- ### GetBindingState Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example of a JSON response when retrieving the current binding mode state. ```json { "name": "default" } ``` -------------------------------- ### Common Sway Command Examples Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Demonstrates how to execute various Sway commands using the `run_command` method. These examples cover focus, movement, workspace switching, toggling floating and fullscreen, and marking windows. ```rust conn.run_command("focus left")?; conn.run_command("move right")?; conn.run_command("workspace 1")?; conn.run_command("fullscreen toggle")?; conn.run_command("floating toggle")?; conn.run_command("mark mymark")?; conn.run_command("unmark mymark")?; ``` -------------------------------- ### GetWorkspaces Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the GetWorkspaces command, detailing workspace properties. ```json [ { "id": 1, "num": 1, "name": "1", "visible": true, "focused": false, "urgent": false, "rect": {"x": 0, "y": 0, "width": 1920, "height": 1080}, "output": "HDMI-1" } ] ``` -------------------------------- ### Async Runtime Compatibility Examples Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Shows how to integrate swayipc-rs with different asynchronous runtimes like Tokio and async-std. Also includes an example for using a custom executor with `async-io`. ```rust // tokio #[tokio::main] async fn main() { /* ... */ } ``` ```rust // async-std #[async_std::main] async fn main() { /* ... */ } ``` ```rust // Custom executor fn main() { async_io::block_on(async { let mut conn = Connection::new().await?; // ... Ok::<_, swayipc_async::Error>(()) })?; } ``` -------------------------------- ### GetBindingModes Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the GetBindingModes command, listing available binding mode names. ```json ["default", "resize", "move"] ``` -------------------------------- ### GetConfig Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the GetConfig command, containing the full content of the last loaded sway configuration. ```json { "config": "# Full sway config file content...\nset $mod Mod4\nbindsym $mod+Return exec alacritty\n..." } ``` -------------------------------- ### Async swayipc Usage Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Shows how to establish an asynchronous connection and fetch workspaces. ```rust let mut conn = Connection::new().await?; let workspaces = conn.get_workspaces().await?; ``` -------------------------------- ### GetMarks Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for the GetMarks command, listing mark names as strings. ```json ["mark1", "mark2"] ``` -------------------------------- ### RunCommand Payload Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example of a payload for the RunCommand type, which is a UTF-8 string containing sway commands. ```json "focus left; move right" ``` -------------------------------- ### Async Write Operation Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md An example of performing an asynchronous write operation to a stream using `AsyncWriteExt::write_all`, ensuring the operation completes without blocking the executor. ```rust use futures_lite::AsyncWriteExt; self.0.write_all(command_type.encode().as_slice()).await?; ``` -------------------------------- ### GetBarConfig Payload Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example payload for GetBarConfig when specifying a particular bar ID. ```text bar-0 ``` -------------------------------- ### GetBarConfig Response Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example JSON response for GetBarConfig when a bar ID is provided, detailing the bar's configuration. ```json { "id": "bar-0", "mode": "dock", "position": "bottom", "font": "monospace 10", "workspace_buttons": true } ``` -------------------------------- ### Blocking swayipc Usage Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Demonstrates how to create a new synchronous connection and retrieve workspaces. ```rust let mut conn = Connection::new()?; let workspaces = conn.get_workspaces()?; ``` -------------------------------- ### Subscribe Payload Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example payload for the Subscribe command, specifying event types as a JSON array of strings. ```json ["workspace", "window", "binding"] ``` -------------------------------- ### SendTick Payload Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Example payload for the SendTick command, which is a UTF-8 string broadcast to tick event subscribers. ```text my_tick_payload ``` -------------------------------- ### Connection::get_inputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the list of input devices. ```APIDOC ## Connection::get_inputs ### Description Gets the list of input devices. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible>` - Vector of input devices ### Example ```rust let mut conn = Connection::new()?; let inputs = conn.get_inputs()?; for input in inputs { println!("Input: {} ({})", input.name, input.input_type); } ``` ``` -------------------------------- ### Async API Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Illustrates the asynchronous API for interacting with Sway, including connecting, fetching data, and subscribing to events using async/await. ```rust use swayipc_async::{Connection, EventType}; use futures_lite::stream::StreamExt; #[tokio::main] async fn main() -> swayipc_async::Fallible<()> { let mut conn = Connection::new().await?; let workspaces = conn.get_workspaces().await?; let mut events = conn.subscribe(&[EventType::Window]).await?; while let Some(event) = events.next().await { println!("{:?}", event?); } Ok(()) } ``` -------------------------------- ### Connection::get_version Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the version of sway. ```APIDOC ## Connection::get_version ### Description Asynchronously gets the version of sway. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a general query for version) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Version** - Version information ### Request Example ```rust let mut conn = Connection::new().await?; let version = conn.get_version().await?; ``` ``` -------------------------------- ### Convenient Single Crate Import Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Shows how to import all necessary types (Connection, Node, EventType, Error) from a single crate like `swayipc`. ```rust use swayipc::{Connection, Node, EventType, Error}; ``` -------------------------------- ### Blocking API Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Demonstrates how to use the blocking API to connect to Sway, retrieve workspaces and the node tree, and subscribe to window events. ```rust use swayipc::{Connection, EventType}; let mut conn = Connection::new()?; let workspaces = conn.get_workspaces()?; let tree = conn.get_tree()?; // Subscribe and iterate for event in conn.subscribe(&[EventType::Window])? { println!("{:?}", event?); } ``` -------------------------------- ### Connection::get_inputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the list of input devices. ```APIDOC ## Connection::get_inputs ### Description Asynchronously gets the list of input devices. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a query for input devices) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Vec** - Vector of input devices ### Request Example ```rust let mut conn = Connection::new().await?; let inputs = conn.get_inputs().await?; ``` ``` -------------------------------- ### Get Outputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Fetch a list of all connected outputs (monitors). Displays output name and active status. ```rust let mut conn = Connection::new()?; let outputs = conn.get_outputs()?; for output in outputs { println!("Output: {} (active: {})", output.name, output.active); } ``` -------------------------------- ### Get All Windows with App IDs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Recursively traverses the Sway node tree to collect all windows along with their application IDs. Requires the `swayipc::Node` type. ```rust use swayipc::Node; fn get_all_windows(node: &Node) -> Vec<(i64, String)> { let mut windows = Vec::new(); if let Some(app_id) = &node.app_id { windows.push((node.id, app_id.clone())); } for child in &node.nodes { windows.extend(get_all_windows(child)); } for child in &node.floating_nodes { windows.extend(get_all_windows(child)); } windows } let tree = conn.get_tree()?; let windows = get_all_windows(&tree); for (id, app_id) in windows { println!("[{}] {}", id, app_id); } ``` -------------------------------- ### Connection::get_binding_modes Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the list of binding mode names. ```APIDOC ## Connection::get_binding_modes ### Description Gets the list of binding mode names. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible>` - Vector of binding mode names ### Example ```rust let mut conn = Connection::new()?; let modes = conn.get_binding_modes()?; println!("Binding modes: {:?}", modes); ``` ``` -------------------------------- ### Connection::get_bar_config Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the configuration for a specific bar. ```APIDOC ## Connection::get_bar_config ### Description Gets the configuration for a specific bar. ### Method N/A (Rust method) ### Parameters #### Path Parameters - **id** (T: AsRef) - Required - Bar ID ### Returns `Fallible` - Bar configuration ### Example ```rust let mut conn = Connection::new()?; let config = conn.get_bar_config("bar-0")?; println!("Bar position: {:?}", config.position); ``` ``` -------------------------------- ### Async Event Listening with StreamExt Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Subscribe to window events asynchronously and process them using `StreamExt::next`. This example demonstrates a simplified loop for event handling. ```rust use swayipc_async::{Connection, EventType}; use futures_lite::stream::StreamExt; #[tokio::main] async fn main() -> swayipc_async::Fallible<()> { let conn = Connection::new().await?; let mut events = conn.subscribe(&[EventType::Window]).await?; while let Some(event) = events.next().await { println!("Event: {:?}", event?); } Ok(()) } ``` -------------------------------- ### Get Input Devices Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves a list of input devices connected to Sway. Requires an active connection. ```rust let mut conn = Connection::new().await?; let inputs = conn.get_inputs().await?; ``` -------------------------------- ### Connection::get_bar_ids Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets a list of bar configuration names. ```APIDOC ## Connection::get_bar_ids ### Description Gets a list of bar configuration names. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible>` - Vector of bar IDs ### Example ```rust let mut conn = Connection::new()?; let bar_ids = conn.get_bar_ids()?; for id in bar_ids { println!("Bar ID: {}", id); } ``` ``` -------------------------------- ### Connection::get_binding_modes Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the list of binding mode names. ```APIDOC ## Connection::get_binding_modes ### Description Asynchronously gets the list of binding mode names. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a query for binding modes) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Vec** - Vector of binding mode names ### Request Example ```rust let mut conn = Connection::new().await?; let modes = conn.get_binding_modes().await?; ``` ``` -------------------------------- ### Get Sway Version Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the version information of the Sway window manager. Requires an active connection. ```rust let mut conn = Connection::new().await?; let version = conn.get_version().await?; ``` -------------------------------- ### RunCommand 'focus left' Encoding Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Hexadecimal representation of the raw bytes for the 'RunCommand' with 'focus left' payload. Demonstrates the magic, length, type, and payload bytes. ```hex 69 33 2d 69 70 63 // Magic: i3-ipc 0a 00 00 00 // Length: 10 (little-endian) 00 00 00 00 // Type: 0 (RunCommand, little-endian) 66 6f 63 75 73 20 6c 65 66 74 // Payload: "focus left" ``` -------------------------------- ### Get Workspaces Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieve a list of all current workspaces. Displays workspace name and visibility status. ```rust let mut conn = Connection::new()?; let workspaces = conn.get_workspaces()?; for ws in workspaces { println!("Workspace: {} (visible: {})", ws.name, ws.visible); } ``` -------------------------------- ### Get All Marked Containers Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieves and prints a list of all containers that have been marked in Sway. ```rust let mut conn = Connection::new()?; let marks = conn.get_marks()?; for mark in marks { println!("Mark: {}", mark); } ``` -------------------------------- ### Get Loaded Sway Configuration Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Fetches the currently loaded Sway configuration. The configuration content is provided as a string and can be further processed. ```rust let config = conn.get_config()?; println!("Config size: {} bytes", config.config.len()); // Can be parsed or processed further ``` -------------------------------- ### Get Sway Configuration Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Fetches the entire loaded Sway configuration. This is useful for inspecting the current configuration settings. ```rust let mut conn = Connection::new()?; let config = conn.get_config()?; println!("Config length: {} bytes", config.config.len()); ``` -------------------------------- ### Get Sway Seats Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieves a list of all seats configured in Sway. This is important for multi-seat setups or managing input focus. ```rust let mut conn = Connection::new()?; let seats = conn.get_seats()?; for seat in seats { println!("Seat: {} (devices: {})", seat.name, seat.devices.len()); } ``` -------------------------------- ### Get Sway Configuration Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the currently loaded configuration of Sway. Requires an active connection. ```rust let mut conn = Connection::new().await?; let config = conn.get_config().await?; ``` -------------------------------- ### Get Window Tree Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieves the entire window tree structure from Sway and prints it recursively. Identifies containers by name and ID. ```rust use swayipc::Node; fn print_tree(node: &Node, depth: usize) { let indent = " ".repeat(depth); match node.node_type { NodeType::Con | NodeType::FloatingCon => { println!("{}{} (id: {})", indent, node.name.as_ref().unwrap_or(&"unnamed".to_string()), node.id); } _ => {} } for child in &node.nodes { print_tree(child, depth + 1); } for child in &node.floating_nodes { print_tree(child, depth + 1); } } let mut conn = Connection::new()?; let tree = conn.get_tree()?; print_tree(&tree, 0); ``` -------------------------------- ### Detect Multi-seat Setup Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Checks if the system has multiple seats configured and lists their names and currently focused nodes. Requires a `Connection` object. ```rust let seats = conn.get_seats()?; if seats.len() > 1 { println!("Multi-seat setup detected!"); for seat in seats { println!("Seat: {} (focused node: {})", seat.name, seat.focus); } } ``` -------------------------------- ### Working with Connection and Stream Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md Shows how to convert between UnixStream and Connection, perform a command, and convert back to use the stream directly. ```rust let stream = UnixStream::connect(path)?; let mut conn: Connection = stream.into(); let results = conn.run_command("focus left")?; let stream: UnixStream = conn.into(); // stream can now be used directly ``` -------------------------------- ### Get Tree and Find Focused Window Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieve the Sway layout tree using `get_tree` and then traverse it to find the currently focused window. ```APIDOC ## Get Tree and Find Focused Window ### Description Retrieve the Sway layout tree using `get_tree` and then traverse it to find the currently focused window. ### Example ```rust let mut conn = Connection::new()?; let tree = conn.get_tree()?; fn find_focused(node: &Node) -> Option<&Node> { if node.focused { return Some(node); } for child in &node.nodes { if let Some(found) = find_focused(child) { return Some(found); } } for child in &node.floating_nodes { if let Some(found) = find_focused(child) { return Some(found); } } None } if let Some(window) = find_focused(&tree) { println!("Focused: {:?}", window.app_id); } ``` ``` -------------------------------- ### Get Sway Input Devices Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Fetches a list of all input devices recognized by Sway. Useful for managing input configurations or querying device information. ```rust let mut conn = Connection::new()?; let inputs = conn.get_inputs()?; for input in inputs { println!("Input: {} ({})", input.name, input.input_type); } ``` -------------------------------- ### Example Encoding of RunCommand IPC Message Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md Demonstrates the byte-level encoding for a 'RunCommand' IPC message, including magic bytes, length, type, and payload. ```text Magic: 69 33 2d 69 70 63 (i3-ipc) Length: 0a 00 00 00 (10 as u32 LE) Type: 00 00 00 00 (0 as u32 LE, RunCommand) Payload: 66 6f 63 75 73 20 6c 65 66 74 ("focus left" as bytes) ``` -------------------------------- ### Mutable Self Requirement Example Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md Illustrates the requirement for `&mut self` in Connection methods, enforcing sequential access for thread-safe message ordering. ```rust pub fn get_workspaces(&mut self) -> Fallible> ``` -------------------------------- ### Execute Sway Commands Synchronously Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Run one or more Sway commands sequentially using a synchronous connection. No special setup is required beyond creating a connection. ```rust use swayipc::Connection; let mut conn = Connection::new()?; let results = conn.run_command("focus left; move right")?; ``` -------------------------------- ### Get All Workspaces (Async) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieves a list of all workspaces asynchronously and prints their number and name. Note that visibility is not directly available in this async version's output. ```rust let mut conn = Connection::new().await?; let workspaces = conn.get_workspaces().await?; for ws in workspaces { println!("{}: {}", ws.num, ws.name); } ``` -------------------------------- ### Connection Creation Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Demonstrates how to create a new connection to the Sway IPC socket using both blocking and asynchronous approaches. ```APIDOC ## Connection Creation ### Blocking ```rust let mut conn = Connection::new()?; ``` ### Async ```rust let mut conn = Connection::new().await?; ``` ``` -------------------------------- ### List Keyboard Layouts Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Display the XKB layout names for each detected keyboard. This helps in understanding the current keyboard configurations. ```rust // Assumes 'conn' is an existing swayipc::Connection let inputs = conn.get_inputs()?; for input in inputs { if input.input_type == "keyboard" { if let Some(layouts) = &input.xkb_layout_names { println!("{:?}", layouts); } } } ``` -------------------------------- ### Connection::get_seats Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the list of seats. ```APIDOC ## Connection::get_seats ### Description Gets the list of seats. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible>` - Vector of seats ### Example ```rust let mut conn = Connection::new()?; let seats = conn.get_seats()?; for seat in seats { println!("Seat: {} (devices: {})", seat.name, seat.devices.len()); } ``` ``` -------------------------------- ### Basic Command Execution Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Execute Sway commands directly using the `run_command` method. This is useful for performing actions within Sway. ```APIDOC ## Basic Command Execution ### Description Execute Sway commands directly using the `run_command` method. This is useful for performing actions within Sway. ### Example ```rust use swayipc::Connection; let mut conn = Connection::new()?; let results = conn.run_command("focus left; move right")?; ``` ``` -------------------------------- ### Connection::get_seats Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the list of seats. ```APIDOC ## Connection::get_seats ### Description Asynchronously gets the list of seats. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a query for seats) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Vec** - Vector of seats ### Request Example ```rust let mut conn = Connection::new().await?; let seats = conn.get_seats().await?; ``` ``` -------------------------------- ### Handling IO Errors on Connection Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/errors.md Demonstrates how to catch and handle standard library IO errors that may occur during connection establishment. This is useful for diagnosing issues like network problems or incorrect socket paths. ```rust match Connection::new() { Err(Error::Io(e)) => { eprintln!("Connection error: {}", e); } _ => {} } ``` -------------------------------- ### Connect to Sway (Async with Tokio) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Establishes an asynchronous connection to the Sway IPC interface using tokio. Requires the swayipc-async and tokio crates. ```rust use swayipc_async::Connection; #[tokio::main] async fn main() -> swayipc_async::Fallible<()> { let mut conn = Connection::new().await?; println!("Connected to sway"); Ok(()) } ``` -------------------------------- ### Sync Method (i3 Compatibility) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Demonstrates the `sync` method, which always returns `false` to maintain compatibility with i3. This method is typically used for synchronization purposes. ```rust // Sync always returns false (i3 compatibility) let result = conn.sync()?; // result is false ``` -------------------------------- ### Connection::get_binding_state Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the current binding state. ```APIDOC ## Connection::get_binding_state ### Description Asynchronously gets the current binding state. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a query for binding state) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **String** - Current binding mode name ### Request Example ```rust let mut conn = Connection::new().await?; let mode = conn.get_binding_state().await?; ``` ``` -------------------------------- ### Minimize Connections: Reuse Single Connection Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Illustrates the recommended practice of creating a single `Connection` instance and reusing it for multiple queries to improve performance. Contrasts with creating a new connection for each query. ```rust // Good: Reuse one connection let mut conn = Connection::new()?; let ws = conn.get_workspaces()?; let outputs = conn.get_outputs()?; // Avoid: Creating new connection for each query let ws = Connection::new()?.get_workspaces()?; let outputs = Connection::new()?.get_outputs()?; ``` -------------------------------- ### Connection::get_outputs (async) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves a list of all current outputs connected to Sway, returning a vector of output information. ```APIDOC ## Connection::get_outputs (async) ### Description Asynchronously gets the list of current outputs. Returns a vector of output information. ### Method `async fn get_outputs(&mut self) -> Fallible>` ### Parameters None ### Returns `Fallible>` - Vector of output information. ### Example ```rust let mut conn = Connection::new().await?; let outputs = conn.get_outputs().await?; ``` ``` -------------------------------- ### Async Error Handling with Connection and GetWorkspaces Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/errors.md Demonstrates how to establish an asynchronous connection and handle potential errors when retrieving workspaces. Use this pattern for robust asynchronous operations. ```rust use swayipc_async::Connection; #[tokio::main] async fn main() { match Connection::new().await { Ok(mut conn) => { match conn.get_workspaces().await { Ok(workspaces) => println!("Found {} workspaces", workspaces.len()), Err(e) => eprintln!("Failed to get workspaces: {}", e), } } Err(e) => eprintln!("Connection failed: {}", e), } } ``` -------------------------------- ### Connection::get_bar_config Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously gets the configuration for a specific bar by its ID. ```APIDOC ## Connection::get_bar_config ### Description Asynchronously gets the configuration for a specific bar. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies an operation on a specific bar) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **id** (T: AsRef) - Required - Bar ID ### Response #### Success Response (200) - **BarConfig** - Bar configuration details ### Request Example ```rust let mut conn = Connection::new().await?; let config = conn.get_bar_config("bar-0").await?; ``` ``` -------------------------------- ### Connection::get_version Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the version of sway that owns the IPC socket. ```APIDOC ## Connection::get_version ### Description Gets the version of sway that owns the IPC socket. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible` - Version information ### Example ```rust let mut conn = Connection::new()?; let version = conn.get_version()?; println!("Sway {}.{}.{}", version.major, version.minor, version.patch); println!("Config: {}", version.loaded_config_file_name); ``` ``` -------------------------------- ### Importing Types from Blocking/Async Crates Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/module-overview.md Illustrates how to import core components and types when using either the blocking or async swayipc crate. ```rust use swayipc::*; // or use swayipc_async ::* You get access to: - `Connection` (from connection module) - `EventStream` (from event module) - `CommandType` (from types crate) - `EventType` (from types crate) - `Error` (from types crate, if "error" feature enabled) - `Fallible` (from types crate) - All response types: Workspace, Output, Node, Event, etc. ``` -------------------------------- ### RunCommand Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/protocol.md Executes sway commands. The payload is a UTF-8 string containing sway commands, and the response is a JSON array of CommandOutcome objects. ```APIDOC ## POST /run/
### Description Executes sway commands. ### Method POST ### Endpoint /run ### Parameters #### Request Body - **payload** (string) - Required - UTF-8 string containing sway commands ### Request Example ```json "focus left; move right" ``` ### Response #### Success Response (200) - **success** (boolean) - Description #### Response Example ```json [ {"success": true}, {"success": true} ] ``` ``` -------------------------------- ### Connection::get_binding_state Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the current binding state (active binding mode name). ```APIDOC ## Connection::get_binding_state ### Description Gets the current binding state (active binding mode name). ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible` - Current binding mode name ### Example ```rust let mut conn = Connection::new()?; let mode = conn.get_binding_state()?; println!("Current mode: {}", mode); ``` ``` -------------------------------- ### Subscribe to Window Events (Async) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Use this snippet to asynchronously subscribe to window-related events. It requires the `futures-lite` crate for stream processing. The loop handles both successful event processing and potential errors. ```rust use futures_lite::stream::StreamExt; // EventStream implements Stream> let mut stream = conn.subscribe(&[EventType::Window]).await?; while let Some(event) = stream.next().await { match event { Ok(e) => { /* handle event */ } Err(e) => { /* handle error */ } } } ``` -------------------------------- ### Connection::get_outputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the list of current outputs. Returns a vector of output information. ```APIDOC ## Connection::get_outputs ### Description Gets the list of current outputs. Returns a vector of output information. ### Method `pub fn get_outputs(&mut self) -> Fallible>` ### Parameters None ### Returns `Fallible>` - Vector of output information ### Example ```rust let mut conn = Connection::new()?; let outputs = conn.get_outputs()?; for output in outputs { println!("Output: {} (active: {})", output.name, output.active); } ``` ``` -------------------------------- ### Connection::get_workspaces Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the list of current workspaces. Returns a vector of workspace information. ```APIDOC ## Connection::get_workspaces ### Description Gets the list of current workspaces. Returns a vector of workspace information. ### Method `pub fn get_workspaces(&mut self) -> Fallible>` ### Parameters None ### Returns `Fallible>` - Vector of workspace information ### Example ```rust let mut conn = Connection::new()?; let workspaces = conn.get_workspaces()?; for ws in workspaces { println!("Workspace: {} (visible: {})", ws.name, ws.visible); } ``` ``` -------------------------------- ### Interactive Command Loop Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Creates an interactive loop that accepts user input commands, sends them to Sway, and prints the results. Type 'q' to quit. Requires std::io for input/output. ```rust use std::io::{stdin, stdout, Write}; use swayipc::Connection; fn main() -> swayipc::Fallible<()> { let mut conn = Connection::new()?; let stdin = stdin(); let mut stdout = stdout(); loop { print!("sway> "); stdout.flush()?; let mut cmd = String::new(); stdin.read_line(&mut cmd)?; if cmd.trim() == "q" { break; } for outcome in conn.run_command(cmd.trim())? { match outcome { Ok(_) => println!("OK"), Err(e) => println!("Error: {}", e), } } } Ok(()) } ``` -------------------------------- ### Add Dependencies for SwayIPC Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Lists the necessary dependencies to include in `Cargo.toml` for both blocking (`swayipc`) and asynchronous (`swayipc-async`) usage, along with the shared `swayipc-types`. Also shows required runtimes for async. ```toml [dependencies] swayipc = "4" # for blocking swayipc-async = "3" # for async swayipc-types = "2" # types only # For async, also need a runtime: tokio = { version = "1", features = ["full"] } # OR async-std = "1" # OR any runtime with async-io support ``` -------------------------------- ### Get Seats Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves a list of seats available in Sway. Requires an active connection. ```rust let mut conn = Connection::new().await?; let seats = conn.get_seats().await?; ``` -------------------------------- ### Connection::get_marks Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the names of all currently set marks. Returns a vector of mark names. ```APIDOC ## Connection::get_marks ### Description Gets the names of all currently set marks. Returns a vector of mark names. ### Method `pub fn get_marks(&mut self) -> Fallible>` ### Parameters None ### Returns `Fallible>` - Vector of mark names ### Example ```rust let mut conn = Connection::new()?; let marks = conn.get_marks()?; for mark in marks { println!("Mark: {}", mark); } ``` ``` -------------------------------- ### Get Binding State Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the current binding mode name. Requires an active connection. ```rust let mut conn = Connection::new().await?; let mode = conn.get_binding_state().await?; ``` -------------------------------- ### Subscribe to Window and Workspace Events (Async Tokio) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Subscribe to window and workspace events asynchronously using tokio. This is ideal for applications that need to remain responsive while handling events. ```rust use swayipc_async::{Connection, EventType, Event}; use futures_lite::stream::StreamExt; #[tokio::main] async fn main() -> swayipc_async::Fallible<()> { let conn = Connection::new().await?; let events = [EventType::Window, EventType::Workspace]; let mut stream = conn.subscribe(&events).await?; while let Some(event) = stream.next().await { match event? { Event::Window(e) => println!("Window: {:?}", e.change), Event::Workspace(e) => println!("Workspace: {:?}", e.change), _ => {} } } Ok(()) } ``` -------------------------------- ### Connection::get_tree Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Gets the complete node layout tree. Returns the root node of the layout tree. ```APIDOC ## Connection::get_tree ### Description Gets the complete node layout tree. Returns the root node of the layout tree. ### Method `pub fn get_tree(&mut self) -> Fallible` ### Parameters None ### Returns `Fallible` - Root node of the tree ### Example ```rust let mut conn = Connection::new()?; let tree = conn.get_tree()?; fn print_tree(node: &Node, indent: usize) { println!("{}{:?}", " ".repeat(indent), node.node_type); for child in &node.nodes { print_tree(child, indent + 2); } } print_tree(&tree, 0); ``` ``` -------------------------------- ### Get Binding Modes Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves a list of available binding mode names. Requires an active connection. ```rust let mut conn = Connection::new().await?; let modes = conn.get_binding_modes().await?; ``` -------------------------------- ### Create Connection from UnixStream Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Converts an existing `std::os::unix::net::UnixStream` into a SwayIPC `Connection`. This is useful when you already have a stream established. ```rust use std::os::unix::net::UnixStream; use swayipc::Connection; let stream = UnixStream::connect(socket_path)?; let conn: Connection = stream.into(); ``` -------------------------------- ### Connection::get_config Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously returns the configuration that was last loaded. ```APIDOC ## Connection::get_config ### Description Asynchronously returns the configuration that was last loaded. ### Method GET (implied) ### Endpoint (Not explicitly defined, but implies a query for the current configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Config** - Configuration content ### Request Example ```rust let mut conn = Connection::new().await?; let config = conn.get_config().await?; ``` ``` -------------------------------- ### Get Bar Configuration Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the configuration for a specific bar using its ID. Requires an active connection. ```rust let mut conn = Connection::new().await?; let config = conn.get_bar_config("bar-0").await?; ``` -------------------------------- ### Utility Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/INDEX.md Utility methods for interacting with Sway. ```APIDOC ## Utility ### `send_tick(payload)` Sends a tick payload to Sway. - **Parameters**: - `payload` (any) - The payload to send with the tick. - **Returns**: `bool` - True if the tick was sent successfully, false otherwise. ### `sync()` Synchronizes with Sway. - **Returns**: `bool` - True if synchronization was successful, false otherwise. ``` -------------------------------- ### Get Seat Information Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieve and display information about seats, including the number of devices associated with each seat and their names. ```rust // Assumes 'conn' is an existing swayipc::Connection let seats = conn.get_seats()?; for seat in seats { println!("Seat: {}", seat.name); println!(" Devices: {}", seat.devices.len()); for device in &seat.devices { println!(" - {}", device.name); } } ``` -------------------------------- ### Configuration Queries Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/INDEX.md Methods for querying Sway's configuration, specifically bar-related information. ```APIDOC ## Configuration Queries ### `get_bar_ids()` Retrieves a list of IDs for all configured bars. - **Returns**: `Vec` ### `get_bar_config(id)` Retrieves the configuration for a specific bar by its ID. - **Parameters**: - `id` (String) - The ID of the bar to query. - **Returns**: `BarConfig` ``` -------------------------------- ### Connection::get_config Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Returns the configuration that was last loaded. ```APIDOC ## Connection::get_config ### Description Returns the configuration that was last loaded. ### Method N/A (Rust method) ### Parameters None ### Returns `Fallible` - Configuration content ### Example ```rust let mut conn = Connection::new()?; let config = conn.get_config()?; println!("Config length: {} bytes", config.config.len()); ``` ``` -------------------------------- ### Get All Outputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieves information about all active outputs connected to Sway, including their resolution. Filters for active outputs only. ```rust let mut conn = Connection::new()?; let outputs = conn.get_outputs()?; for output in outputs { if output.active { println!("{} ({}x{})", output.name, output.current_mode.map_or(0, |m| m.width), output.current_mode.map_or(0, |m| m.height)); } } ``` -------------------------------- ### Retrieve Sway/i3 Version Information Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Fetches and prints detailed version information about the running Sway/i3 instance, including major, minor, patch versions, a human-readable string, and the loaded configuration file name. ```rust let v = conn.get_version()?; println!("{}.{}.{}", v.major, v.minor, v.patch); println!("{}", v.human_readable); println!("{}", v.loaded_config_file_name); ``` -------------------------------- ### List Active Outputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/quick-reference.md Iterates through all detected outputs and prints the names of those that are currently active. Useful for multi-monitor setups. ```rust for output in conn.get_outputs()? { if output.active { println!("{}", output.name); } } ``` -------------------------------- ### Listen for Input Changes Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Subscribe to input device events, such as devices being added, removed, or their XKB layout changing. This snippet assumes an existing connection. ```rust use swayipc::{Event, InputChange}; // Assumes 'conn' is an existing swayipc::Connection for event in conn.subscribe(&[EventType::Input])? { if let Ok(Event::Input(e)) = event { match e.change { InputChange::Added => println!("Device added: {}", e.input.name), InputChange::Removed => println!("Device removed: {}", e.input.name), InputChange::XkbLayout => println!("Layout changed for: {}", e.input.name), _ => {} } } } ``` -------------------------------- ### Get Async Bar IDs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves a list of bar configuration names. Returns a vector of bar IDs. ```rust let mut conn = Connection::new().await?; let bar_ids = conn.get_bar_ids().await?; ``` -------------------------------- ### Get Async Marks Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the names of all currently set marks in sway. Returns a vector of mark names. ```rust let mut conn = Connection::new().await?; let marks = conn.get_marks().await?; ``` -------------------------------- ### Connection::get_tree (async) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the complete node layout tree of the Sway environment, returning the root node. ```APIDOC ## Connection::get_tree (async) ### Description Asynchronously gets the complete node layout tree. Returns the root node of the tree. ### Method `async fn get_tree(&mut self) -> Fallible` ### Parameters None ### Returns `Fallible` - Root node of the tree. ### Example ```rust let mut conn = Connection::new().await?; let tree = conn.get_tree().await?; ``` ``` -------------------------------- ### Connection::run_command (async) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously runs a given payload as sway commands and returns a vector of results for each command executed. ```APIDOC ## Connection::run_command (async) ### Description Asynchronously runs the payload as sway commands and returns a vector of results for each command executed. ### Method `async fn run_command>(&mut self, payload: T) -> Fallible>>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **payload** (T: AsRef) - Required - Command string to execute ### Request Example ```rust let mut conn = Connection::new().await?; let results = conn.run_command("focus left").await?; ``` ### Response #### Success Response (200) - **results** (Fallible>>) - Vector of results for each command ### Response Example ```json // Example response structure, actual content depends on commands executed [ null, // Success for a command null // Success for another command ] ``` ``` -------------------------------- ### Get Async Outputs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the list of current outputs connected to sway. Returns a vector of output information. ```rust let mut conn = Connection::new().await?; let outputs = conn.get_outputs().await?; ``` -------------------------------- ### Async-IO Integration with UnixStream Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md Shows how to wrap a synchronous UnixStream with `async_io::Async` for non-blocking I/O operations within an async runtime. ```rust use async_io::Async; use std::os::unix::net::UnixStream; pub struct Connection(Async); ``` -------------------------------- ### Get All Workspaces (Blocking) Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieves a list of all workspaces using the blocking API and prints their number, name, and visibility status. ```rust let mut conn = Connection::new()?; let workspaces = conn.get_workspaces()?; for ws in workspaces { println!("{}: {} (visible: {})", ws.num, ws.name, ws.visible); } ``` -------------------------------- ### Get Async Node Tree Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously retrieves the complete node layout tree of sway. Returns the root node of the tree. ```rust let mut conn = Connection::new().await?; let tree = conn.get_tree().await?; ``` -------------------------------- ### Connection::sync Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Asynchronously sends a sync request for i3 compatibility. ```APIDOC ## Connection::sync ### Description Asynchronously sends a sync request for i3 compatibility. ### Method POST (implied) ### Endpoint (Not explicitly defined, but implies a sync operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **bool** - Sync result ### Request Example ```rust let mut conn = Connection::new().await?; let synced = conn.sync().await?; ``` ``` -------------------------------- ### List All Input Devices Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/examples-and-patterns.md Retrieve and display information about all connected input devices. This includes their names and types. ```rust // Assumes 'conn' is an existing swayipc::Connection let inputs = conn.get_inputs()?; for input in inputs { println!("{}: {}", input.name, input.input_type); } ``` -------------------------------- ### Get Sway Binding State Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieves the name of the currently active binding mode. Use this to check the current keybinding mode. ```rust let mut conn = Connection::new()?; let mode = conn.get_binding_state()?; println!("Current mode: {}", mode); ``` -------------------------------- ### Commands Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/INDEX.md Methods for executing commands within Sway. ```APIDOC ## Commands ### `run_command(cmd)` Executes a Sway command. - **Parameters**: - `cmd` (String) - The command string to execute (e.g., "focus left"). - **Returns**: `Vec>` - A vector of results for each command executed. ``` -------------------------------- ### Get Sway Binding Modes Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Lists all available binding modes in Sway. Useful for understanding or dynamically changing keybinding behaviors. ```rust let mut conn = Connection::new()?; let modes = conn.get_binding_modes()?; println!("Binding modes: {:?}", modes); ``` -------------------------------- ### Get Sway Bar IDs Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieves a list of all configured bar IDs. This is useful for iterating through and managing different bar configurations. ```rust let mut conn = Connection::new()?; let bar_ids = conn.get_bar_ids()?; for id in bar_ids { println!("Bar ID: {}", id); } ``` -------------------------------- ### Custom Serde Configuration for Node Struct Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/advanced-topics.md Illustrates custom Serde configurations for the Node struct, including renaming fields, setting defaults, flattening, and skipping null values during deserialization. ```rust #[non_exhaustive] #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Node { #[serde(rename = "type")] // Sway uses "type", Rust doesn't allow pub node_type: NodeType, #[serde(default)] // Missing fields become default values pub layout: NodeLayout, #[serde(flatten)] // Flattens error object in CommandOutcome pub error: Option, #[serde(deserialize_with = "skip_null_values")] pub xkb_layout_names: Vec, } ``` -------------------------------- ### Get Node Layout Tree Source: https://github.com/jaycefayne/swayipc-rs/blob/master/_autodocs/connection-api.md Retrieve the complete layout tree of sway nodes. Recursively prints the node types and their hierarchy. ```rust let mut conn = Connection::new()?; let tree = conn.get_tree()?; fn print_tree(node: &Node, indent: usize) { println!("{}{:?}", " ".repeat(indent), node.node_type); for child in &node.nodes { print_tree(child, indent + 2); } } print_tree(&tree, 0); ```