### Get Sway IPC Socket Path Source: https://docs.rs/swayipc/latest/src/swayipc/socket.rs.html Retrieves the sway IPC socket path by checking the SWAYSOCK and I3SOCK environment variables. If not found, it attempts to spawn 'i3' or 'sway' to get the path. Ensure the window manager is installed and accessible in your PATH. ```rust use std::env; use std::io::Read; use std::path::PathBuf; use std::process::{Command, Stdio}; use swayipc_types::{Error, Fallible}; pub fn get_socketpath() -> Fallible { env::var("I3SOCK") .or_else(|_| env::var("SWAYSOCK")) .or_else(|_| spawn("i3")) .or_else(|_| spawn("sway")), .map_err(|_| Error::SocketNotFound) .map(PathBuf::from) } fn spawn(wm: &str) -> Fallible { let mut child = Command::new(wm) .arg("--get-socketpath") .stdout(Stdio::piped()) .spawn()?; let mut buf = String::new(); if let Some(mut stdout) = child.stdout.take() { stdout.read_to_string(&mut buf)?; buf.pop(); } child.wait()?; Ok(buf) } ``` -------------------------------- ### Node Searching Utilities Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/utils/node.rs.html Provides methods to find nodes within the Sway window tree based on a predicate. Includes functions to find any node, or specifically the focused node, with options to get a reference or consume the node. ```APIDOC ## Node Searching Utilities This section details the methods available on the `Node` struct for searching within the Sway window tree. ### `find_as_ref` Searches the node and its children for a node that satisfies the given predicate. Returns an optional reference to the found node. - **Method**: `find_as_ref` - **Parameters**: - `predicate` (Fn(&Node) -> bool) - A closure that returns true if the node matches the search criteria. ### `find` Searches the node and its children for a node that satisfies the given predicate. Returns an optional owned `Node`. - **Method**: `find` - **Parameters**: - `predicate` (Fn(&Node) -> bool) - A closure that returns true if the node matches the search criteria. ### `find_focused_as_ref` Searches the currently focused node and its descendants for a node that satisfies the given predicate. Returns an optional reference to the found node. - **Method**: `find_focused_as_ref` - **Parameters**: - `predicate` (Fn(&Node) -> bool) - A closure that returns true if the node matches the search criteria. ### `find_focused` Searches the currently focused node and its descendants for a node that satisfies the given predicate. Returns an optional owned `Node`. - **Method**: `find_focused` - **Parameters**: - `predicate` (Fn(&Node) -> bool) - A closure that returns true if the node matches the search criteria. ``` -------------------------------- ### CommandOutcome Implementations Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.CommandOutcome.html Details various implementations for the CommandOutcome struct, including decoding, cloning, debugging, serialization, and deserialization. ```APIDOC ### impl CommandOutcome #### pub fn decode(command_outcome: CommandOutcome) -> Fallible<()> Decodes a CommandOutcome from a given input. ### impl Clone for CommandOutcome #### fn clone(&self) -> CommandOutcome Returns a duplicate of the value. #### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. ### impl Debug for CommandOutcome #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. ### impl<'de> Deserialize<'de> for CommandOutcome #### fn deserialize<__D>(__deserializer: __D) -> Result where __D: Deserializer<'de> Deserialize this value from the given Serde deserializer. ### impl Serialize for CommandOutcome #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer Serialize this value into the given Serde serializer. ``` -------------------------------- ### Create Node Iterator Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/utils/node.rs.html Returns a new `NodeIterator` for traversing the node tree starting from the current node. ```rust pub fn iter(&self) -> NodeIterator<'_> { NodeIterator { queue: vec![self] } } ``` -------------------------------- ### Implement CloneToUninit (Nightly) Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.WindowChange.html An experimental nightly-only API that performs copy-assignment from a source value to an uninitialized destination. Use with caution. ```rust impl CloneToUninit for T where T: Clone, Source unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.NodeBorder.html An experimental, nightly-only API that performs copy-assignment from `self` to a mutable pointer `dest`. Use with caution as it is unstable. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. Read more ``` -------------------------------- ### Unwrap Error Value in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `unwrap_err()` to get the contained `Err` value. Panics if the value is an `Ok`. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Implement PartialEq for OutputChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html Provides methods for comparing OutputChange values for equality. ```rust impl PartialEq for OutputChange { fn eq(&self, other: &OutputChange) -> bool { // ... implementation details ... } fn ne(&self, other: &Rhs) -> bool { // ... implementation details ... } } ``` -------------------------------- ### Unwrap Ok Value in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `unwrap()` to get the contained `Ok` value. Panics if the value is an `Err`. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Implement CloneToUninit for T (Nightly) Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.BarMode.html An experimental nightly-only API for performing copy-assignment from self to an uninitialized memory location. ```rust impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation details ... } } ``` -------------------------------- ### Expect Error with Custom Message in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `expect_err()` to get the contained `Err` value. Panics with a custom message if the value is an `Ok`. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Blanket Implementations for Workspace Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Workspace.html Details blanket implementations provided for the Workspace struct, such as Any, Borrow, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto. ```APIDOC ## Blanket Implementations ### impl Any for T - `fn type_id(&self) -> TypeId`: Gets the `TypeId` of `self`. ### impl Borrow for T - `fn borrow(&self) -> &T`: Immutably borrows from an owned value. ### impl BorrowMut for T - `fn borrow_mut(&mut self) -> &mut T`: Mutably borrows from an owned value. ### impl CloneToUninit for T - `unsafe fn clone_to_uninit(&self, dest: *mut u8)`: Performs copy-assignment from `self` to `dest`. ### impl From for T - `fn from(t: T) -> T`: Returns the argument unchanged. ### impl Into for T - `fn into(self) -> U`: Calls `U::from(self)`. ### impl ToOwned for T - `type Owned = T` - `fn to_owned(&self) -> T`: Creates owned data from borrowed data, usually by cloning. - `fn clone_into(&self, target: &mut T)`: Uses borrowed data to replace owned data, usually by cloning. ### impl TryFrom for T - `type Error = Infallible` - `fn try_from(value: U) -> Result>::Error>`: Performs the conversion. ### impl TryInto for T - `type Error = >::Error` - `fn try_into(self) -> Result>::Error>`: Performs the conversion. ### impl DeserializeOwned for T - (No methods defined for this blanket implementation in the provided text) ``` -------------------------------- ### Into Err Value (Never Panics) in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `into_err()` to get the contained `Err` value. This method is guaranteed not to panic, serving as a compile-time safeguard against potential panics. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Test Helper: Node Creation Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/utils/node.rs.html Constructs a `Node` with specified parameters, useful for setting up test scenarios. ```rust fn mk_node(name: Option, node_type: NodeType, nodes: Vec) -> Node { Node { id: 1, name, node_type, border: NodeBorder::Normal, current_border_width: 0, layout: NodeLayout::Tabbed, percent: None, rect: rect(), window_rect: rect(), deco_rect: rect(), geometry: rect(), urgent: false, focused: false, focus: Vec::new(), nodes, floating_nodes: Vec::new(), sticky: false, representation: None, fullscreen_mode: None, floating: None, scratchpad_state: None, app_id: None, pid: None, window: None, num: None, window_properties: None, marks: Vec::new(), inhibit_idle: None, idle_inhibitors: None, shell: None, visible: None, output: None, sandbox_engine: None, } } ``` -------------------------------- ### Into Ok Value (Never Panics) in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `into_ok()` to get the contained `Ok` value. This method is guaranteed not to panic, making it a compile-time safeguard against potential panics. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Unwrap or Default Value in Rust Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Use `unwrap_or_default()` to get the contained `Ok` value or the default value for the type if it's an `Err`. This is useful for providing fallback values. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Implement Any trait Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Provides runtime type information for ButtonMapping. This is a blanket implementation for any type. ```rust impl Any for T where T: 'static + ?Sized, ``` -------------------------------- ### into_ok Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Returns the contained Ok value, never panics (nightly-only). ```APIDOC ## GET /api/into_ok ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ### Method GET ### Endpoint /api/into_ok ### Request Example ```json { "example": "fn only_good_news() -> Result { Ok(\"this is fine\".into()) }\nlet s: String = only_good_news().into_ok();" } ``` ### Response #### Success Response (200) - **value** (T) - The value contained within the Ok variant. #### Response Example ```json { "example": "this is fine" } ``` ``` -------------------------------- ### Implement PartialEq for WindowChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.WindowChange.html Enables comparison between WindowChange variants for equality. This is crucial for checking if a window change matches a specific expected type. ```rust impl PartialEq for WindowChange Source fn eq(&self, other: &WindowChange) -> bool ``` -------------------------------- ### Libinput Structure Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/reply.rs.html Configuration details for libinput devices, including event sending and tap-to-click settings. ```rust #[non_exhaustive] #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub struct Libinput { /// Whether events are being sent by the device. It can be enabled, /// disabled, or disabled_on_external_mouse. pub send_events: Option, /// Whether tap to click is enabled. It can be enabled or disabled. pub tap: Option, } ``` -------------------------------- ### Implement PartialEq for ButtonMapping Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Allows comparison of ButtonMapping values for equality. This is essential for checking if two button mappings are the same. ```rust impl PartialEq for ButtonMapping ``` -------------------------------- ### Implement CloneToUninit for T (Nightly) Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html An experimental nightly-only API for cloning a value into uninitialized memory. ```rust unsafe impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation details ... } } ``` -------------------------------- ### Version Trait Implementations Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Version.html Overview of the standard library and external traits implemented for the Version struct. ```APIDOC ## Trait Implementations for Version ### `Clone` - `clone(&self) -> Version`: Returns a duplicate of the `Version` value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from a source `Version`. ### `Debug` - `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the `Version` struct for debugging purposes. ### `Deserialize` (from Serde) - `deserialize<__D>(__deserializer: __D) -> Result`: Deserializes a `Version` struct from a Serde deserializer. ### `Serialize` (from Serde) - `serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>`: Serializes the `Version` struct into a Serde serializer. ### Auto Trait Implementations - `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe` ### Blanket Implementations (Generic) - `Any` - `Borrow` - `BorrowMut` - `CloneToUninit` (Nightly-only experimental) - `From` - `Into` - `ToOwned` - `TryFrom` - `TryInto` - `DeserializeOwned` ``` -------------------------------- ### Generic Trait Implementations Source: https://docs.rs/swayipc/latest/swayipc/struct.Input.html Demonstrates common generic trait implementations such as Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto, showcasing Input's interoperability and data handling capabilities. ```rust impl Any for T where T: 'static + ?Sized, ``` ```rust fn type_id(&self) -> TypeId ``` ```rust impl Borrow for T where T: ?Sized, ``` ```rust fn borrow(&self) -> &T ``` ```rust impl BorrowMut for T where T: ?Sized, ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust impl CloneToUninit for T where T: Clone, ``` ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` ```rust impl From for T ``` ```rust fn from(t: T) -> T ``` ```rust impl Into for T where U: From, ``` ```rust fn into(self) -> U ``` ```rust impl ToOwned for T where T: Clone, ``` ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` ```rust fn clone_into(&self, target: &mut T) ``` ```rust impl TryFrom for T where U: Into, ``` ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` ```rust impl TryInto for T where U: TryFrom, ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` ```rust impl DeserializeOwned for T where T: for<'de> Deserialize<'de>, ``` -------------------------------- ### Implement From trait Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Allows conversion into ButtonMapping from the same type. This is a standard blanket implementation. ```rust impl From for T ``` -------------------------------- ### Connection Implementation in Rust Source: https://docs.rs/swayipc/latest/src/swayipc/connection.rs.html The core implementation of the Connection struct, including methods for establishing a connection and executing various IPC commands. ```rust 1use super::common::receive_from_stream; 2use super::socket::get_socketpath; 3use crate::{CommandType::*, Error::SubscriptionFailed, *}; 4use serde::de::DeserializeOwned as Deserialize; 5use std::io::Write; 6use std::os::unix::net::UnixStream; 7 8#[derive(Debug)] 9pub struct Connection(UnixStream); 10 11impl Connection { 12 /// Creates a new `Connection` to sway-ipc. 13 pub fn new() -> Fallible { 14 let socketpath = get_socketpath()?; 15 let unix_stream = UnixStream::connect(socketpath)?; 16 Ok(Self(unix_stream)) 17 } 18 19 fn raw_command(&mut self, command_type: CommandType) -> Fallible { 20 self.0.write_all(command_type.encode().as_slice())?; 21 command_type.decode(receive_from_stream(&mut self.0)?) 22 } 23 24 fn raw_command_with>( 25 &mut self, 26 command_type: CommandType, 27 payload: T, 28 ) -> Fallible { 29 self.0 30 .write_all(command_type.encode_with(payload).as_slice())?; 31 command_type.decode(receive_from_stream(&mut self.0)?) 32 } 33 34 /// Runs the payload as sway commands. 35 pub fn run_command>(&mut self, payload: T) -> Fallible>> { 36 let outcome: Vec = self.raw_command_with(RunCommand, payload.as_ref())?; 37 Ok(outcome.into_iter().map(CommandOutcome::decode).collect()) 38 } 39 40 /// Get the list of current workspaces. 41 pub fn get_workspaces(&mut self) -> Fallible> { 42 self.raw_command(GetWorkspaces) 43 } 44 45 /// Subscribe the IPC connection to the events listed in the payload. 46 pub fn subscribe>(mut self, events: T) -> Fallible { 47 let events = serde_json::ser::to_string(events.as_ref())?; 48 let res: Success = self.raw_command_with(Subscribe, events.as_bytes())?; 49 if !res.success { 50 return Err(SubscriptionFailed(events)); 51 } 52 Ok(EventStream::new(self.0)) 53 } 54 55 /// Get the list of current outputs. 56 pub fn get_outputs(&mut self) -> Fallible> { 57 self.raw_command(GetOutputs) 58 } 59 60 /// Get the node layout tree. 61 pub fn get_tree(&mut self) -> Fallible { 62 self.raw_command(GetTree) 63 } 64 65 /// Get the names of all the marks currently set. 66 pub fn get_marks(&mut self) -> Fallible> { 67 self.raw_command(GetMarks) 68 } 69 70 /// Get a list of bar config names. 71 pub fn get_bar_ids(&mut self) -> Fallible> { 72 self.raw_command(GetBarConfig) 73 } 74 75 /// Get the specified bar config. 76 pub fn get_bar_config>(&mut self, id: T) -> Fallible { 77 self.raw_command_with(GetBarConfig, id.as_ref()) 78 } 79 80 /// Get the version of sway that owns the IPC socket. 81 pub fn get_version(&mut self) -> Fallible { 82 self.raw_command(GetVersion) 83 } 84 85 /// Get the list of binding mode names. 86 pub fn get_binding_modes(&mut self) -> Fallible> { 87 self.raw_command(GetBindingModes) 88 } 89 90 /// Returns the config that was last loaded. 91 pub fn get_config(&mut self) -> Fallible { 92 self.raw_command(GetConfig) 93 } 94 95 /// Sends a tick event with the specified payload. 96 pub fn send_tick>(&mut self, payload: T) -> Fallible { 97 let res: Success = self.raw_command_with(SendTick, payload.as_ref())?; 98 Ok(res.success) 99 } 100 101 /// Replies failure object for i3 compatibility. 102 pub fn sync(&mut self) -> Fallible { 103 let res: Success = self.raw_command::(Sync)?; 104 Ok(res.success) 105 } 106 107 /// Request the current binding state, e.g. the currently active binding 108 /// mode name. 109 pub fn get_binding_state(&mut self) -> Fallible { 110 let state: BindingState = self.raw_command(GetBindingState)?; 111 Ok(state.name) 112 } 113 114 /// Get the list of input devices. 115 pub fn get_inputs(&mut self) -> Fallible> { 116 self.raw_command(GetInputs) 117 } 118 119 /// Get the list of seats. 120 pub fn get_seats(&mut self) -> Fallible> { 121 self.raw_command(GetSeats) 122 } 123} 124 125impl From for Connection { 126 fn from(unix_stream: UnixStream) -> Self { 127 Self(unix_stream) 128 } 129} 130 131impl From for UnixStream { 132 fn from(connection: Connection) -> Self { 133 connection.0 134 } 135} ``` -------------------------------- ### Command Execution Source: https://docs.rs/swayipc/latest/src/swayipc/connection.rs.html Methods for sending commands to sway and receiving responses. ```APIDOC ## Command Execution ### Description Provides methods to execute various commands against the sway IPC. ### Methods #### `run_command>(&mut self, payload: T)` Runs the payload as sway commands. - **Parameters**: - `payload` (T) - The command string to execute. - **Returns**: `Fallible>>` - A vector of outcomes for each command or an error. #### `get_workspaces(&mut self)` Gets the list of current workspaces. - **Returns**: `Fallible>` - A list of workspaces or an error. #### `get_outputs(&mut self)` Gets the list of current outputs. - **Returns**: `Fallible>` - A list of outputs or an error. #### `get_tree(&mut self)` Gets the node layout tree. - **Returns**: `Fallible` - The node tree structure or an error. #### `get_marks(&mut self)` Gets the names of all the marks currently set. - **Returns**: `Fallible>` - A list of mark names or an error. #### `get_bar_ids(&mut self)` Gets a list of bar config names. - **Returns**: `Fallible>` - A list of bar IDs or an error. #### `get_bar_config>(&mut self, id: T)` Gets the specified bar config. - **Parameters**: - `id` (T) - The ID of the bar configuration to retrieve. - **Returns**: `Fallible` - The bar configuration or an error. #### `get_version(&mut self)` Gets the version of sway that owns the IPC socket. - **Returns**: `Fallible` - The sway version information or an error. #### `get_binding_modes(&mut self)` Gets the list of binding mode names. - **Returns**: `Fallible>` - A list of binding mode names or an error. #### `get_config(&mut self)` Returns the config that was last loaded. - **Returns**: `Fallible` - The sway configuration or an error. #### `send_tick>(&mut self, payload: T)` Sends a tick event with the specified payload. - **Parameters**: - `payload` (T) - The payload for the tick event. - **Returns**: `Fallible` - `true` if the tick was sent successfully, `false` otherwise, or an error. #### `sync(&mut self)` Replies failure object for i3 compatibility. - **Returns**: `Fallible` - `true` if sync was successful, `false` otherwise, or an error. #### `get_binding_state(&mut self)` Requests the current binding state, e.g., the currently active binding mode name. - **Returns**: `Fallible` - The name of the current binding state or an error. #### `get_inputs(&mut self)` Gets the list of input devices. - **Returns**: `Fallible>` - A list of input devices or an error. #### `get_seats(&mut self)` Gets the list of seats. - **Returns**: `Fallible>` - A list of seats or an error. ``` -------------------------------- ### Implement StructuralPartialEq for OutputChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html Provides structural equality comparison for OutputChange. ```rust impl StructuralPartialEq for OutputChange {} ``` -------------------------------- ### Implement CloneToUninit for T Source: https://docs.rs/swayipc/latest/swayipc/enum.NodeBorder.html Nightly-only experimental API for performing copy-assignment from `self` to an uninitialized memory location `dest`. Requires `T` to implement `Clone`. ```rust unsafe impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation details ... } } ``` -------------------------------- ### Implement CloneToUninit trait (Nightly) Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Provides an experimental, nightly-only API for copying ButtonMapping values to uninitialized memory. Use with caution. ```rust impl CloneToUninit for T where T: Clone, ``` -------------------------------- ### Trait Implementations Overview Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Output.html Documentation for standard Rust trait implementations used for data conversion and deserialization. ```APIDOC ## Trait Implementations ### CloneInto - **fn clone_into(&self, target: &mut T)**: Uses borrowed data to replace owned data, usually by cloning. ### TryFrom - **type Error = Infallible**: The type returned in the event of a conversion error. - **fn try_from(value: U) -> Result>::Error>**: Performs the conversion. ### TryInto - **type Error = >::Error**: The type returned in the event of a conversion error. - **fn try_into(self) -> Result>::Error>**: Performs the conversion. ### DeserializeOwned - **impl DeserializeOwned for T**: Implemented where T: for<'de> Deserialize<'de>. ``` -------------------------------- ### Standard Trait Implementations Source: https://docs.rs/swayipc/latest/swayipc/struct.Libinput.html Overview of common trait implementations for data conversion and ownership management. ```APIDOC ## Trait Implementations ### From - **fn from(t: T) -> T**: Returns the argument unchanged. ### Into - **fn into(self) -> U**: Calls U::from(self). ### ToOwned - **type Owned = T**: The resulting type after obtaining ownership. - **fn to_owned(&self) -> T**: Creates owned data from borrowed data, usually by cloning. - **fn clone_into(&self, target: &mut T)**: Uses borrowed data to replace owned data, usually by cloning. ### TryFrom - **type Error = Infallible**: The type returned in the event of a conversion error. - **fn try_from(value: U) -> Result>::Error>**: Performs the conversion. ### TryInto - **type Error = >::Error**: The type returned in the event of a conversion error. - **fn try_into(self) -> Result>::Error>**: Performs the conversion. ### DeserializeOwned - **Constraint**: T where T: for<'de> Deserialize<'de> ``` -------------------------------- ### Libinput Configuration Structure Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/reply.rs.html Defines the configuration options for libinput devices, including tap-to-click, tap-and-drag, and scroll methods. Use this struct to set or retrieve libinput-specific settings. ```rust pub struct Libinput { /// Whether tap-to-click is enabled. It can be enabled or disabled. pub tap: Option, /// The finger to button mapping in use. It can be lmr or lrm. pub tap_button_mapping: Option, /// Whether tap-and-drag is enabled. It can be enabled or disabled. pub tap_drag: Option, /// Whether drag-lock is enabled. It can be enabled, disabled or enabled_sticky. pub tap_drag_lock: Option, /// The pointer-acceleration in use. pub accel_speed: Option, /// Whether natural scrolling is enabled. It can be enabled or disabled. pub natural_scroll: Option, /// Whether left-handed mode is enabled. It can be enabled or disabled. pub left_handed: Option, /// The click method in use. It can be none, button_areas, or clickfinger. pub click_method: Option, /// The finger to button mapping in use for clickfinger. pub click_button_map: Option, /// Whether middle emulation is enabled. It can be enabled or disabled. pub middle_emulation: Option, /// The scroll method in use. It can be none, two_finger, edge, or /// on_button_down. pub scroll_method: Option, /// The scroll button to use when scroll_method is on_button_down. This /// will be given as an input event code. pub scroll_button: Option, /// Whether scroll button lock is enabled. pub scroll_button_lock: Option, /// Whether disable-while-typing is enabled. It can be enabled or disabled. pub dwt: Option, /// An array of 6 floats representing the calibration matrix for absolute /// devices such as touchscreens. pub calibration_matrix: Option<[f32; 6]>, } ``` -------------------------------- ### Implement Serialize for ButtonMapping Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Enables serialization of ButtonMapping values into formats like JSON or other Serde-compatible data structures. Requires the 'serde' feature. ```rust impl Serialize for ButtonMapping ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.BarMode.html Provides runtime type information for any type T. ```rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId { // ... implementation details ... } } ``` -------------------------------- ### CloneToUninit for Generic Type T (Nightly) Source: https://docs.rs/swayipc/latest/swayipc/struct.WorkspaceEvent.html Nightly-only experimental API for clone_to_uninit. Performs copy-assignment from self to a raw pointer destination. Requires T to implement Clone. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Input Device Configuration Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/reply.rs.html Data structure representing an input device and its associated libinput settings. ```APIDOC ## Input Device Structure ### Description Represents an input device, including its identifier, type, and specific configurations for keyboards and libinput-managed devices. ### Request Body - **identifier** (String) - The identifier for the input device. - **name** (String) - The human readable name for the device. - **type** (String) - The device type (keyboard, pointer, touch, tablet_tool, tablet_pad, or switch). - **xkb_active_layout_name** (String) - Optional - The name of the active keyboard layout. - **xkb_layout_names** (Array) - A list of layout names configured for the keyboard. - **xkb_active_layout_index** (Integer) - Optional - The index of the active keyboard layout. - **scroll_factor** (Float) - Multiplier applied on scroll event values. - **libinput** (Object) - Optional - An object describing current device settings. - **vendor** (Integer) - Optional - The vendor code for the input device. - **product** (Integer) - Optional - The product code for the input device. ``` -------------------------------- ### Implement StructuralPartialEq for ButtonMapping Source: https://docs.rs/swayipc/latest/swayipc/enum.ButtonMapping.html Provides structural equality comparison for ButtonMapping. This is often derived automatically. ```rust impl StructuralPartialEq for ButtonMapping ``` -------------------------------- ### Implement Clone for Success Source: https://docs.rs/swayipc/latest/swayipc/struct.Success.html Provides methods to duplicate and copy-assign Success structs. ```rust fn clone(&self) -> Success ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Generic Implementations for Input Source: https://docs.rs/swayipc/latest/swayipc/struct.Input.html Shows blanket implementations for traits like Any, Freeze, Send, Sync, Unpin, and UnwindSafe, indicating Input's compatibility with standard Rust concurrency and type system features. ```rust impl Freeze for Input ``` ```rust impl RefUnwindSafe for Input ``` ```rust impl Send for Input ``` ```rust impl Sync for Input ``` ```rust impl Unpin for Input ``` ```rust impl UnwindSafe for Input ``` -------------------------------- ### Generic Implementations for Output Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Output.html Demonstrates various auto-trait and blanket implementations for the `Output` struct, including `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe`, `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `From`, `Into`, and `ToOwned`. These traits enable common Rust patterns and interoperability. ```rust impl Freeze for Output ``` ```rust impl RefUnwindSafe for Output ``` ```rust impl Send for Output ``` ```rust impl Sync for Output ``` ```rust impl Unpin for Output ``` ```rust impl UnwindSafe for Output ``` ```rust impl Any for T where T: 'static + ?Sized ``` ```rust impl Borrow where T: ?Sized ``` ```rust fn borrow(&self) -> &T ``` ```rust impl BorrowMut where T: ?Sized ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust impl CloneToUninit for T where T: Clone ``` ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` ```rust impl From for T ``` ```rust fn from(t: T) -> T ``` ```rust impl Into for T where U: From ``` ```rust fn into(self) -> U ``` ```rust impl ToOwned for T where T: Clone ``` ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` -------------------------------- ### Config Trait Implementations Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Config.html Overview of the trait implementations available for the Config struct. ```APIDOC ### Trait Implementations #### `impl Clone for Config` - `fn clone(&self) -> Config`: Returns a duplicate of the value. - `fn clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. #### `impl Debug for Config` - `fn fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. #### `impl<'de> Deserialize<'de> for Config` - `fn deserialize<__D>(__deserializer: __D) -> Result`: Deserialize this value from the given Serde deserializer. #### `impl Serialize for Config` - `fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>`: Serialize this value into the given Serde serializer. ``` -------------------------------- ### Config Structure Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/reply.rs.html Represents the contents of the Sway configuration file. ```APIDOC ## Config Structure ### Description Holds the entire content of the Sway configuration file as a single string. ### Fields - **config** (String) - The complete configuration content. ``` -------------------------------- ### Version Information Source: https://docs.rs/swayipc-types/2.0.1/src/swayipc_types/reply.rs.html Provides detailed version information about the Sway process. ```APIDOC ## Version Structure ### Description Contains detailed version information for the running Sway process. ### Fields - **major** (i32) - The major version number. - **minor** (i32) - The minor version number. - **patch** (i32) - The patch version number. - **human_readable** (String) - A human-readable version string, often including git information. - **loaded_config_file_name** (String) - The name of the currently loaded configuration file. ``` -------------------------------- ### Implement Serialize for OutputChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html Enables serialization of OutputChange values into a Serde serializer. ```rust impl Serialize for OutputChange { fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, { // ... implementation details ... } } ``` -------------------------------- ### Implement Copy for OutputChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html Indicates that OutputChange values can be copied implicitly. ```rust impl Copy for OutputChange {} ``` -------------------------------- ### Clone Implementation for Input Source: https://docs.rs/swayipc/latest/swayipc/struct.Input.html Provides methods to duplicate an Input struct instance. `clone` creates a new instance, while `clone_from` copies data from another instance. ```rust fn clone(&self) -> Input ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Trait Implementations for Success Source: https://docs.rs/swayipc/latest/swayipc/struct.Success.html Overview of the trait implementations available for the Success struct. ```APIDOC ### Trait Implementations for Success #### `impl Clone for Success` - `fn clone(&self) -> Success`: Returns a duplicate of the value. - `fn clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. #### `impl Debug for Success` - `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>`: Formats the value using the given formatter. #### `impl<'de> Deserialize<'de> for Success` - `fn deserialize<__D>(__deserializer: __D) -> Result>::Error>`: Deserialize this value from the given Serde deserializer. #### `impl Serialize for Success` - `fn serialize<__S>(&self, __serializer: __S) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>`: Serialize this value into the given Serde serializer. #### `impl Copy for Success` ``` -------------------------------- ### Connection Management Source: https://docs.rs/swayipc/latest/src/swayipc/connection.rs.html Methods for creating and managing a connection to the sway IPC. ```APIDOC ## Connection ### Description Represents a connection to the sway IPC socket. ### Methods #### `new()` Creates a new `Connection` to sway-ipc. - **Returns**: `Fallible` - A new connection object or an error. #### `from(UnixStream)` Creates a `Connection` from an existing `UnixStream`. - **Parameters**: - `unix_stream` (UnixStream) - The Unix stream to wrap. - **Returns**: `Connection` #### `into()` Consumes the `Connection` and returns the underlying `UnixStream`. - **Returns**: `UnixStream` ``` -------------------------------- ### ScratchpadState Trait Implementations Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.ScratchpadState.html Details the various trait implementations for the ScratchpadState enum, including Clone, Debug, Deserialize, PartialEq, Serialize, Copy, and others, which define its behavior and capabilities. ```APIDOC ## Trait Implementations for ScratchpadState ### `Clone` Allows creating a duplicate of a `ScratchpadState` value. * `clone(&self) -> ScratchpadState`: Returns a copy of the value. * `clone_from(&mut self, source: &Self)`: Copies the value from `source` into `self`. ### `Debug` Enables formatting the `ScratchpadState` for debugging purposes. * `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the provided formatter. ### `Deserialize<'de>` (from Serde) Allows deserializing a `ScratchpadState` from a data format (e.g., JSON). * `deserialize<__D>(__deserializer: __D) -> Result`: Deserializes the enum from a Serde deserializer. ### `PartialEq` Enables comparison of two `ScratchpadState` values for equality. * `eq(&self, other: &ScratchpadState) -> bool`: Tests if `self` is equal to `other`. * `ne(&self, other: &Rhs) -> bool`: Tests if `self` is not equal to `other`. ### `Serialize` (from Serde) Allows serializing a `ScratchpadState` into a data format (e.g., JSON). * `serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>`: Serializes the enum using a Serde serializer. ### `Copy` Indicates that `ScratchpadState` can be copied implicitly (like primitive types). ### `StructuralPartialEq` Provides structural equality comparison. ### Auto Trait Implementations * `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe`: These indicate thread safety and memory management characteristics. ``` -------------------------------- ### Implement StructuralPartialEq for WindowChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.WindowChange.html Provides structural equality comparison for WindowChange, which is often used in conjunction with other trait implementations for complex types. ```rust impl StructuralPartialEq for WindowChange ``` -------------------------------- ### Implement PartialEq for NodeLayout Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.NodeLayout.html Enables equality comparison between NodeLayout values. ```rust fn eq(&self, other: &NodeLayout) -> bool ``` -------------------------------- ### Implement Debug for OutputChange Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/enum.OutputChange.html Allows OutputChange values to be formatted for debugging purposes. ```rust impl Debug for OutputChange { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // ... implementation details ... } } ``` -------------------------------- ### Conversion Traits (Into, TryFrom, TryInto) Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/struct.Libinput.html Documentation for standard Rust conversion traits implemented for generic types. ```APIDOC ## Into for T ### Description Converts a value into another type U, where U implements From. ### Method fn into(self) -> U ## TryFrom for T ### Description Performs a fallible conversion from U to T. ### Method fn try_from(value: U) -> Result>::Error> ## TryInto for T ### Description Performs a fallible conversion into U, where U implements TryFrom. ### Method fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Implement Serialize for InputChange Source: https://docs.rs/swayipc/latest/swayipc/enum.InputChange.html Enables serialization of InputChange to a Serde serializer. ```rust impl Serialize for InputChange { fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error> where __S: Serializer { // ... implementation details ... } } ``` -------------------------------- ### swayipc API Overview Source: https://docs.rs/swayipc/latest/index.html Overview of the primary structures and event types available in the swayipc crate for IPC communication. ```APIDOC ## swayipc Crate Overview ### Description The swayipc crate allows Rust applications to communicate with the Sway window manager using its IPC protocol. It provides structured access to window properties, workspace states, and event streams. ### Key Structs - **Connection**: The primary interface for sending commands and receiving events from Sway. - **EventStream**: Used to subscribe to and process events from the window manager. - **Node**: Represents a container or window within the Sway tree. - **Workspace**: Represents a workspace within the Sway environment. ### Key Enums - **Event**: Represents the various types of events that can be emitted by Sway (e.g., WindowEvent, WorkspaceEvent, BindingEvent). - **CommandType**: Defines the types of commands that can be sent to the IPC interface. ### Type Aliases - **Fallible**: A type alias for handling results from IPC operations. ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/swayipc-types/2.0.1/swayipc_types/type.Fallible.html Returns the contained Ok value or a default value if Err. ```APIDOC ## GET /api/unwrap_or_default ### Description Returns the contained `Ok` value or a default value for the type if the Result is an `Err`. This consumes the `self` argument. ### Method GET ### Endpoint /api/unwrap_or_default ### Request Example ```json { "example": "let x: Result = Err(\"error\");\nassert_eq!(x.unwrap_or_default(), 0);" } ``` ### Response #### Success Response (200) - **value** (T) - The value contained within the Ok variant or the default value. #### Response Example ```json { "example": "0" } ``` ```