### Example: Initialize Clipboard and Get Formats in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=u32+-%3E+bool A basic example demonstrating the initialization of ClipboardContext and retrieving the available formats from the clipboard. It prints the formats to the console. ```rust fn main() { let ctx = ClipboardContext::new().unwrap(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let buffer = ctx.get_buffer("public.html").unwrap(); let string = String::from_utf8(buffer).unwrap(); println!("{}", string); } ``` -------------------------------- ### Create and Use ClipboardWatcherContext in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardWatcherContext_search= Demonstrates how to create a new `ClipboardWatcherContext`, add a handler to it, and start watching for clipboard changes. It also shows how to obtain a shutdown channel to stop the watcher. This example is intended to be run in a separate thread due to the blocking nature of `start_watch`. ```rust fn main() { let manager = Manager::new(); let mut watcher = ClipboardWatcherContext::new().unwrap(); let watcher_shutdown: clipboard_rs::WatcherShutdown = watcher.add_handler(manager).get_shutdown_channel(); thread::spawn(move || { thread::sleep(Duration::from_secs(5)); println!("stop watch!"); watcher_shutdown.stop(); }); println!("start watch!"); watcher.start_watch(); } ``` -------------------------------- ### Example: Set and Get Multiple Content Types in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=u32+-%3E+bool Illustrates setting multiple content types (Text, Rtf, Html) to the clipboard and then retrieving them. It iterates through the retrieved content and prints it. ```rust fn main() { let ctx = ClipboardContext::new().unwrap(); let contents: Vec = vec![ ClipboardContent::Text("hell@$#%^&U都98好的😊o Rust!!!".to_string()), ClipboardContent::Rtf("\x1b[1m\x1b[4m\x1b[31mHello, Rust!\x1b[0m".to_string()), ClipboardContent::Html("

Hello, Rust!

".to_string()), ]; ctx.set(contents).unwrap(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let read = ctx .get(&[ContentFormat::Text, ContentFormat::Rtf, ContentFormat::Html]) .unwrap(); for c in read { println!("{}", c.as_str().unwrap()); } } ``` -------------------------------- ### Example: Check and Get Rich Text and HTML in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=u32+-%3E+bool Demonstrates checking for and retrieving rich text (RTF) and HTML content from the clipboard. It also retrieves plain text content. ```rust fn main() { let ctx = ClipboardContext::new().unwrap(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let has_rtf = ctx.has(ContentFormat::Rtf); println!("has_rtf={}", has_rtf); let rtf = ctx.get_rich_text().unwrap_or("".to_string()); println!("rtf={}", rtf); let has_html = ctx.has(ContentFormat::Html); println!("has_html={}", has_html); let html = ctx.get_html().unwrap_or("".to_string()); println!("html={}", html); let content = ctx.get_text().unwrap_or("".to_string()); println!("txt={}", content); } ``` -------------------------------- ### Start Clipboard Watching in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardWatcherContext_search=u32+-%3E+bool Illustrates how to start monitoring clipboard changes using `start_watch()`. This method is blocking and should ideally be called in a separate thread to avoid freezing the main application thread. It continues until monitoring is stopped manually. ```rust watcher.start_watch(); ``` -------------------------------- ### Enabling scraped examples with Cargo and Rustdoc Source: https://docs.rs/clipboard-rs/0.3.1/scrape-examples-help Shows the command to enable the scraping of examples by Rustdoc. This command analyzes documented crates for uses of documented items and includes their source code in the generated documentation. ```bash cargo doc -Zunstable-options -Zrustdoc-scrape-examples ``` -------------------------------- ### Documenting a function with scraped examples in Rust Source: https://docs.rs/clipboard-rs/0.3.1/scrape-examples-help Demonstrates how Rustdoc includes examples that call documented items. If a crate has a public function and an example calls it, that example code will be embedded in the function's documentation. ```rust // src/lib.rs pub fn a_func() {} ``` ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Rust: Example of Result.is_ok() Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/common/type.Result_search=std%3A%3Avec Provides examples of using the `is_ok` method to check if a `Result` instance contains an `Ok` variant. It returns `true` if the `Result` is `Ok` and `false` otherwise. ```Rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Set and Get Clipboard Content in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/multi/multi.rs_search=std%3A%3Avec Demonstrates how to set and get various content types (Text, Rtf, Html) from the system clipboard using the clipboard-rs crate. It initializes a clipboard context, sets multiple content types, retrieves available formats, and then reads content in specified formats. ```rust use clipboard_rs::{ common::ContentData, Clipboard, ClipboardContent, ClipboardContext, ContentFormat, }; fn main() { let ctx = ClipboardContext::new().unwrap(); let contents: Vec = vec![ ClipboardContent::Text("hell@$#%^&U都98好的😊o Rust!!!".to_string()), ClipboardContent::Rtf("\x1b[1m\x1b[4m\x1b[31mHello, Rust!\x1b[0m".to_string()), ClipboardContent::Html("

Hello, Rust!

".to_string()), ]; ctx.set(contents).unwrap(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let read = ctx .get(&[ContentFormat::Text, ContentFormat::Rtf, ContentFormat::Html]) .unwrap(); for c in read { println!("{}", c.as_str().unwrap()); } } ``` -------------------------------- ### Rust: Example of Result.is_ok_and() Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/common/type.Result_search=std%3A%3Avec Shows how to use the `is_ok_and` method, which checks if a `Result` is `Ok` and if its contained value satisfies a given predicate. It takes a closure as an argument and returns a boolean. ```Rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Watch Clipboard Changes with Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/watch_change/watch_change.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This Rust code snippet demonstrates how to use the clipboard-rs crate to monitor clipboard content for changes. It defines a `Manager` struct that implements the `ClipboardHandler` trait to process clipboard updates and a `main` function to initialize and start the watcher. The watcher is configured to stop after 5 seconds. ```rust use clipboard_rs::{ Clipboard, ClipboardContext, ClipboardHandler, ClipboardWatcher, ClipboardWatcherContext, }; use std::{thread, time::Duration}; struct Manager { ctx: ClipboardContext, } impl Manager { pub fn new() -> Self { let ctx = ClipboardContext::new().unwrap(); Manager { ctx } } } impl ClipboardHandler for Manager { fn on_clipboard_change(&mut self) { println!( "on_clipboard_change, txt = {}", self.ctx.get_text().unwrap_or("".to_string()) ); } } fn main() { let manager = Manager::new(); let mut watcher = ClipboardWatcherContext::new().unwrap(); let watcher_shutdown: clipboard_rs::WatcherShutdown = watcher.add_handler(manager).get_shutdown_channel(); thread::spawn(move || { thread::sleep(Duration::from_secs(5)); println!("stop watch!"); watcher_shutdown.stop(); }); println!("start watch!"); watcher.start_watch(); } ``` -------------------------------- ### Watch Clipboard Changes with Rust clipboard-rs Source: https://docs.rs/clipboard-rs/0.3.1/src/watch_change/watch_change.rs_search= This Rust code snippet demonstrates how to use the clipboard-rs crate to monitor clipboard content for changes. It sets up a watcher that triggers a callback function whenever the clipboard's text content is modified. The example includes a shutdown mechanism to stop the watcher after a specified duration. ```rust use clipboard_rs::{ Clipboard, ClipboardContext, ClipboardHandler, ClipboardWatcher, ClipboardWatcherContext, }; use std::{thread, time::Duration}; struct Manager { ctx: ClipboardContext, } impl Manager { pub fn new() -> Self { let ctx = ClipboardContext::new().unwrap(); Manager { ctx } } } impl ClipboardHandler for Manager { fn on_clipboard_change(&mut self) { println!( "on_clipboard_change, txt = {}", self.ctx.get_text().unwrap_or("".to_string()) ); } } fn main() { let manager = Manager::new(); let mut watcher = ClipboardWatcherContext::new().unwrap(); let watcher_shutdown: clipboard_rs::WatcherShutdown = watcher.add_handler(manager).get_shutdown_channel(); thread::spawn(move || { thread::sleep(Duration::from_secs(5)); println!("stop watch!"); watcher_shutdown.stop(); }); println!("start watch!"); watcher.start_watch(); } ``` -------------------------------- ### Start Clipboard Monitoring in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/trait.ClipboardWatcher The `start_watch` method initiates clipboard change monitoring. This is a blocking operation and is recommended to be called in a separate thread. ```rust fn start_watch(&mut self); ``` -------------------------------- ### Get Available Clipboard Formats in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search= Retrieves a list of all available content formats currently present in the clipboard. This is useful for determining what kind of data can be read from the clipboard. ```rust let types = ctx.available_formats().unwrap(); ``` -------------------------------- ### Handling File System Operations with Result Source: https://docs.rs/clipboard-rs/latest/clipboard_rs/common/type.Result Illustrates using `Result` to handle fallible file system operations like getting metadata, with examples of both success and failure cases. ```APIDOC ## GET /api/file_metadata ### Description Retrieves metadata for a given file path, handling potential errors like file not found. ### Method GET ### Endpoint /api/file_metadata ### Parameters #### Query Parameters - **path** (string) - Required - The path to the file. ### Response #### Success Response (200) - **metadata** (object) - An object containing file metadata (e.g., modified time). #### Error Response (404) - **error** (string) - A message indicating the error, such as "file not found". #### Response Example ```json { "metadata": { "modified": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Setup Clipboard Context and Handle Images in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/image/image.rs_search=std%3A%3Avec This Rust code snippet demonstrates setting up a clipboard context, which is platform-dependent, and then retrieving an image from the clipboard. It includes functionality to save the original image and a resized thumbnail to a temporary path. Dependencies include the 'clipboard-rs' crate. ```rust #[cfg(target_os = "linux")] use clipboard_rs::ClipboardContextX11Options; use clipboard_rs::{common::RustImage, Clipboard, ClipboardContext}; #[cfg(target_os = "macos")] const TMP_PATH: &str = "/tmp/"; #[cfg(target_os = "windows")] const TMP_PATH: &str = "C:\\Windows\\Temp\\\\"; #[cfg(all( unix, not(any( target_os = "macos", target_os = "ios", target_os = "android", target_os = "emscripten" )) ))] const TMP_PATH: &str = "/tmp/"; // ios #[cfg(any(target_os = "ios", target_os = "android"))] const TMP_PATH: &str = "/tmp/"; #[cfg(target_os = "linux")] fn setup_clipboard() -> ClipboardContext { ClipboardContext::new_with_options(ClipboardContextX11Options { read_timeout: None }).unwrap() } #[cfg(not(target_os = "linux"))] fn setup_clipboard() -> ClipboardContext { ClipboardContext::new().unwrap() } fn main() { let ctx = setup_clipboard(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let img = ctx.get_image(); match img { Ok(img) => { let _ = img .save_to_path(format!("{}\\"test.png"", TMP_PATH).as_str()) .map_err(|e| println!("save test.png err={}", e)); let resize_img = img .thumbnail(300, 300) .map_err(|e| println!("thumbnail err={}", e)) .unwrap(); let _ = resize_img .save_to_path(format!("{}\\"test_thumbnail.png"", TMP_PATH).as_str()) .map_err(|e| println!("save test_thumbnail.png err={}", e)); } Err(err) => { println!("err={}", err); } } } ``` -------------------------------- ### Initialize ClipboardContext in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a new ClipboardContext instance. This is the primary way to interact with the clipboard functionality provided by the library. It returns a Result, so error handling is necessary. ```rust pub struct ClipboardContext { /* private fields */ } ``` ```rust pub fn new() -> Result ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` ```rust let ctx = ClipboardContext::new().unwrap(); ``` -------------------------------- ### Create ClipboardContext with Options in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search= Shows how to initialize ClipboardContext with specific options, such as setting a read timeout for X11. This allows for more fine-grained control over clipboard interactions. ```rust ClipboardContext::new_with_options(ClipboardContextX11Options { read_timeout: None }).unwrap() ``` -------------------------------- ### Define ClipboardWatcher Trait in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/trait.ClipboardWatcher Defines the `ClipboardWatcher` trait for monitoring clipboard changes. It requires handlers to implement the `ClipboardHandler` trait and provides methods to add handlers, start watching, and get a shutdown channel. ```rust pub trait ClipboardWatcher: Send { // Required methods fn add_handler(&mut self, handler: T) -> &mut Self; fn start_watch(&mut self); fn get_shutdown_channel(&self) -> WatcherShutdown; } ``` -------------------------------- ### Create X Server Context (Rust) Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search=std%3A%3Avec Initializes a new XServerContext by connecting to the X server, generating a window ID, creating an input window, and retrieving necessary atoms. This is a prerequisite for interacting with the X11 clipboard. ```rust impl XServerContext { fn new() -> Result { let (conn, screen) = x11rb::connect(None)?; let win_id = conn.generate_id()?; { let screen = conn.setup().roots.get(screen).unwrap(); conn.create_window( COPY_DEPTH_FROM_PARENT, win_id, screen.root, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, screen.root_visual, &CreateWindowAux::new() .event_mask(EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE) )? .check()?; } let atoms = Atoms::new(&conn)?.reply()?; Ok(Self { conn, win_id, _screen: screen, atoms, }) } } ``` -------------------------------- ### Get Clipboard Files in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search=std%3A%3Avec Retrieves a list of file paths from the clipboard. It reads the file list data, converts it to a string, and filters lines that start with a specific prefix. Returns an empty vector if no file list data is found. ```rust fn get_files(&self) -> Result> { let atoms = self.inner.server.atoms; let file_list_data = self.read(&atoms.FILE_LIST); file_list_data.map_or_else( |_| Ok(vec![]), |data| { let file_list_str = String::from_utf8_lossy(&data).to_string(); let mut list = Vec::new(); for line in file_list_str.lines() { if !line.starts_with(FILE_PATH_PREFIX) { continue; } list.push(line.to_string()) } Ok(list) }, ) } ``` -------------------------------- ### Type Conversion Implementations Source: https://docs.rs/clipboard-rs/latest/clipboard_rs/struct.ClipboardContext_search=std%3A%3Avec Covers `From`, `Into`, `TryFrom`, and `TryInto` for various type conversions. ```APIDOC ## POST /api/convert/from ### Description Converts a value from one type to another using the `From` trait. ### Method POST ### Endpoint /api/convert/from ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The desired target type (e.g., "String", "i32"). ### Response #### Success Response (200) - **converted_value** (any) - The converted value. #### Response Example ```json { "converted_value": "converted_string" } ``` ## POST /api/convert/into ### Description Converts a value into another type using the `Into` trait. ### Method POST ### Endpoint /api/convert/into ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The desired target type (e.g., "String", "i32"). ### Response #### Success Response (200) - **converted_value** (any) - The converted value. #### Response Example ```json { "converted_value": "converted_string" } ``` ## POST /api/convert/try_from ### Description Attempts to convert a value from one type to another using the `TryFrom` trait. ### Method POST ### Endpoint /api/convert/try_from ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The desired target type (e.g., "String", "i32"). ### Response #### Success Response (200) - **converted_value** (any) - The successfully converted value. #### Error Response (400) - **error** (string) - Description of the conversion error. #### Response Example ```json { "converted_value": "converted_string" } ``` ## POST /api/convert/try_into ### Description Attempts to convert a value into another type using the `TryInto` trait. ### Method POST ### Endpoint /api/convert/try_into ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The desired target type (e.g., "String", "i32"). ### Response #### Success Response (200) - **converted_value** (any) - The successfully converted value. #### Error Response (400) - **error** (string) - Description of the conversion error. #### Response Example ```json { "converted_value": "converted_string" } ``` ``` -------------------------------- ### Get Clipboard Files - Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs Retrieves a list of file paths from the clipboard. It reads data associated with the FILE_LIST atom, converts it to a string, and filters lines that start with a specific prefix. Returns an empty vector if no file list data is found or if an error occurs. ```Rust fn get_files(&self) -> Result> { let atoms = self.inner.server.atoms; let file_list_data = self.read(&atoms.FILE_LIST); file_list_data.map_or_else( |_| Ok(vec![]), |data| { let file_list_str = String::from_utf8_lossy(&data).to_string(); let mut list = Vec::new(); for line in file_list_str.lines() { if !line.starts_with(FILE_PATH_PREFIX) { continue; } list.push(line.to_string()) } Ok(list) } ) } ``` -------------------------------- ### ClipboardContext Initialization Source: https://docs.rs/clipboard-rs/latest/clipboard_rs/struct.ClipboardContext_search= Provides methods to create a new ClipboardContext, with or without specific options. ```APIDOC ## POST /clipboard/context/new ### Description Initializes a new ClipboardContext. This is the primary way to interact with the clipboard. ### Method POST ### Endpoint /clipboard/context/new ### Parameters #### Query Parameters - **options** (ClipboardContextX11Options) - Optional - Configuration options for the clipboard context, specific to X11 environments. ### Request Example ```json { "options": { "read_timeout": null } } ``` ### Response #### Success Response (200) - **ClipboardContext** (object) - An instance of the ClipboardContext. #### Response Example ```json { "clipboard_context": {} } ``` ``` -------------------------------- ### ClipboardContext Initialization Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext Provides methods to create a new ClipboardContext, either with default options or custom X11 options. ```APIDOC ## POST /clipboard/context/new ### Description Initializes a new ClipboardContext with default settings. ### Method POST ### Endpoint /clipboard/context/new ### Parameters None ### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **ClipboardContext** (object) - An object representing the initialized clipboard context. #### Response Example ```json { "message": "ClipboardContext initialized successfully" } ``` --- ## POST /clipboard/context/new_with_options ### Description Initializes a new ClipboardContext with specified X11 options. ### Method POST ### Endpoint /clipboard/context/new_with_options ### Parameters None #### Request Body - **options** (object) - Required - Options for initializing the X11 clipboard context. - **read_timeout** (integer) - Optional - The read timeout in milliseconds for X11 operations. ### Request Example ```json { "options": { "read_timeout": 5000 } } ``` ### Response #### Success Response (200) - **ClipboardContext** (object) - An object representing the initialized clipboard context. #### Response Example ```json { "message": "ClipboardContext initialized successfully with options" } ``` ``` -------------------------------- ### Get Type ID with Blanket Implementation Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/common/struct.RustImageData Demonstrates the blanket implementation of the `Any` trait, providing a `type_id` method to get the unique identifier of a type at runtime. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Create X Server Context (Rust) Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search= Initializes a new XServerContext by connecting to the X server, generating a window ID, creating an input-only window, and retrieving necessary atoms. This is essential for interacting with the X11 display server. ```rust impl XServerContext { fn new() -> Result { let (conn, screen) = x11rb::connect(None)?; let win_id = conn.generate_id()?; { let screen = conn.setup().roots.get(screen).unwrap(); conn.create_window( COPY_DEPTH_FROM_PARENT, win_id, screen.root, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, screen.root_visual, &CreateWindowAux::new() .event_mask(EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE), )? .check()?; } let atoms = Atoms::new(&conn)?.reply()?; Ok(Self { conn, win_id, _screen: screen, atoms, }) } } ``` -------------------------------- ### Rust: Get TypeId using `Any` Trait Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=u32+-%3E+bool Demonstrates how to get the `TypeId` of a type using the `Any` trait. This is useful for runtime type identification. It requires the type `T` to be `'static` and `?Sized`. ```rust impl Any for T where T: 'static + ?Sized, { fn type_id(&self) -> TypeId; } ``` -------------------------------- ### Conversion Implementations Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardContext_search=std%3A%3Avec Covers `From`, `Into`, `TryFrom`, and `TryInto` traits for type conversions, including error handling for fallible conversions. ```APIDOC ## POST /api/convert/from ### Description Performs a conversion from one type to another using the `From` trait. ### Method POST ### Endpoint /api/convert/from ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The type to convert to. ### Request Example ```json { "source_value": 10, "target_type": "string" } ``` ### Response #### Success Response (200) - **converted_value** (any) - The converted value. #### Response Example ```json { "converted_value": "10" } ``` ## POST /api/convert/into ### Description Performs a conversion from one type to another using the `Into` trait. ### Method POST ### Endpoint /api/convert/into ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The type to convert to. ### Request Example ```json { "source_value": "hello", "target_type": "string_length" } ``` ### Response #### Success Response (200) - **converted_value** (integer) - The converted value (e.g., string length). #### Response Example ```json { "converted_value": 5 } ``` ## POST /api/convert/try_from ### Description Performs a fallible conversion from one type to another using the `TryFrom` trait. ### Method POST ### Endpoint /api/convert/try_from ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The type to convert to. ### Request Example ```json { "source_value": "123", "target_type": "integer" } ``` ### Response #### Success Response (200) - **converted_value** (any) - The successfully converted value. #### Error Response (400) - **error** (string) - Description of the conversion error. #### Response Example ```json { "converted_value": 123 } ``` ## POST /api/convert/try_into ### Description Performs a fallible conversion from one type to another using the `TryInto` trait. ### Method POST ### Endpoint /api/convert/try_into ### Parameters #### Request Body - **source_value** (any) - Required - The value to convert. - **target_type** (string) - Required - The type to convert to. ### Request Example ```json { "source_value": 10, "target_type": "string_representation" } ``` ### Response #### Success Response (200) - **converted_value** (string) - The successfully converted value. #### Error Response (400) - **error** (string) - Description of the conversion error. #### Response Example ```json { "converted_value": "10" } ``` ``` -------------------------------- ### Rust: Get TypeId using `Any` trait Source: https://docs.rs/clipboard-rs/latest/clipboard_rs/struct.ClipboardContext_search=std%3A%3Avec Demonstrates how to get the `TypeId` of a value using the `Any` trait's `type_id` method. This is useful for runtime type checks and dynamic dispatch. ```rust impl Any for T where T: 'static + ?Sized, fn type_id(&self) -> TypeId ``` -------------------------------- ### Clipboard Image Operations in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/image/image.rs_search=u32+-%3E+bool Demonstrates how to set up a clipboard context, retrieve an image from the clipboard, save it to a file, and create a thumbnail. It includes platform-specific configurations for different operating systems. ```rust #[cfg(target_os = "linux")] use clipboard_rs::ClipboardContextX11Options; use clipboard_rs::{common::RustImage, Clipboard, ClipboardContext}; #[cfg(target_os = "macos")] const TMP_PATH: &str = "/tmp/"; #[cfg(target_os = "windows")] const TMP_PATH: &str = "C:\\Windows\\Temp\\”; #[cfg(all( unix, not(any( target_os = "macos", target_os = "ios", target_os = "android", target_os = "emscripten" )) ))] const TMP_PATH: &str = "/tmp/"; // ios #[cfg(any(target_os = "ios", target_os = "android"))] const TMP_PATH: &str = "/tmp/"; #[cfg(target_os = "linux")] fn setup_clipboard() -> ClipboardContext { ClipboardContext::new_with_options(ClipboardContextX11Options { read_timeout: None }).unwrap() } #[cfg(not(target_os = "linux"))] fn setup_clipboard() -> ClipboardContext { ClipboardContext::new().unwrap() } fn main() { let ctx = setup_clipboard(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let img = ctx.get_image(); match img { Ok(img) => { let _ = img .save_to_path(format!("{} est.png", TMP_PATH).as_str()) .map_err(|e| println!("save test.png err={}", e)); let resize_img = img .thumbnail(300, 300) .map_err(|e| println!("thumbnail err={}", e)) .unwrap(); let _ = resize_img .save_to_path(format!("{} test_thumbnail.png", TMP_PATH).as_str()) .map_err(|e| println!("save test_thumbnail.png err={}", e)); } Err(err) => { println!("err={}", err); } } } ``` -------------------------------- ### Initialize X Server Context (Rust) Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Establishes a connection to the X server, generates a window ID, creates an input-only window, and retrieves necessary atoms. This context is essential for interacting with the X11 clipboard and events. ```rust impl XServerContext { fn new() -> Result { let (conn, screen) = x11rb::connect(None)?; let win_id = conn.generate_id()?; { let screen = conn.setup().roots.get(screen).unwrap(); conn.create_window( COPY_DEPTH_FROM_PARENT, win_id, screen.root, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, screen.root_visual, &CreateWindowAux::new() .event_mask(EventMask::STRUCTURE_NOTIFY | EventMask::PROPERTY_CHANGE), )? .check()?; } let atoms = Atoms::new(&conn)?.reply()?; Ok(Self { conn, win_id, _screen: screen, atoms, }) } } ``` -------------------------------- ### Initialize Clipboard Context with Options in Rust Source: https://docs.rs/clipboard-rs/latest/clipboard_rs/struct.ClipboardContext_search=std%3A%3Avec Shows how to create a ClipboardContext with specific X11 options, such as setting a read timeout. This allows for more fine-grained control over clipboard operations, particularly in environments where X11 is used. The `read_timeout` field can be set to `None` to disable timeouts. ```rust pub fn new_with_options(options: ClipboardContextX11Options) -> Result ``` ```rust fn setup_clipboard() -> ClipboardContext { ClipboardContext::new_with_options(ClipboardContextX11Options { read_timeout: None }).unwrap() } ``` -------------------------------- ### Clipboard File Operations in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/files/files.rs Demonstrates how to set, check for, and get file paths from the system clipboard using the clipboard-rs crate. Requires the 'files' feature flag to be enabled. It initializes a clipboard context, optionally sets file paths, checks for the availability of file content, and retrieves the file paths. ```rust use clipboard_rs::{Clipboard, ClipboardContext, ContentFormat}; fn main() { let ctx = ClipboardContext::new().unwrap(); // change the file paths to your own // let files = vec![ // "file:///home/parallels/clipboard-rs/Cargo.toml".to_string(), // "file:///home/parallels/clipboard-rs/CHANGELOG.md".to_string(), // ]; // ctx.set_files(files).unwrap(); let types = ctx.available_formats().unwrap(); println!("{:?}", types); let has = ctx.has(ContentFormat::Files); println!("has_files={}", has); let files = ctx.get_files().unwrap_or_default(); println!("{:?}", files); } ``` -------------------------------- ### Get Available Clipboard Formats in Rust Source: https://docs.rs/clipboard-rs/latest/src/clipboard_rs/platform/x11.rs_search=std%3A%3Avec This Rust function retrieves a list of all available formats currently supported by the clipboard. It interacts with the X11 server to get the atom list for targets and then maps these atoms to human-readable format names. Unsupported formats or errors during atom name retrieval are handled gracefully. ```rust fn available_formats(&self) -> Result> { let ctx = &self.inner.server; let atoms = ctx.atoms; self.read(&atoms.TARGETS).map(|data| { let mut formats = Vec::new(); let atom_list: Vec = parse_atom_list(&data); for atom in atom_list { if self.inner.ignore_formats.contains(&atom) { continue; } let atom_name = ctx.get_atom_name(atom).unwrap_or("Unknown".to_string()); formats.push(atom_name); } formats }) ``` -------------------------------- ### Get Raw Clipboard Data by Format in Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search=std%3A%3Avec This Rust function retrieves raw clipboard data for a specified format. It first gets the X11 atom for the given format string and then attempts to read the data associated with that atom. It returns an error if the format string is invalid or if reading the data fails. ```rust fn get_buffer(&self, format: &str) -> Result> { let atom = self.inner.server.get_atom(format); match atom { Ok(atom) => self.read(&atom), Err(_) => Err("Invalid format".into()), } } ``` -------------------------------- ### Initialize Clipboard Context (Rust) Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to create a new clipboard context. `new()` uses default read timeout, while `new_with_options()` allows customization. It establishes a connection to the X server and spawns a thread to process server requests. ```rust impl ClipboardContext { pub fn new() -> Result { Self::new_with_options(ClipboardContextX11Options { read_timeout: Some(Duration::from_millis(DEFAULT_READ_TIMEOUT)), }) } pub fn new_with_options(options: ClipboardContextX11Options) -> Result { // build connection to X server let ctx = InnerContext::new()?; let ctx_arc = Arc::new(ctx); let ctx_clone = ctx_arc.clone(); thread::spawn(move || { let res = process_server_req(&ctx_clone); if let Err(e) = res { println!("process_server_req error: {e:?}"); } }); Ok(Self { inner: ctx_arc, read_timeout: options.read_timeout, }) } ``` -------------------------------- ### Get Clipboard Contents - Rust Source: https://docs.rs/clipboard-rs/0.3.1/src/clipboard_rs/platform/x11.rs Retrieves clipboard content in specified formats. It iterates through a list of requested `ContentFormat`s and attempts to get the corresponding data from the clipboard. Supported formats include Text, Rtf, Html, Image (if enabled), Files, and Other custom formats. Errors during retrieval for a specific format are ignored, and the function proceeds to the next. ```Rust fn get(&self, formats: &[ContentFormat]) -> Result> { let mut contents = Vec::new(); for format in formats { match format { ContentFormat::Text => match self.get_text() { Ok(text) => contents.push(ClipboardContent::Text(text)), Err(_) => continue, }, ContentFormat::Rtf => match self.get_rich_text() { Ok(rtf) => contents.push(ClipboardContent::Rtf(rtf)), Err(_) => continue, }, ContentFormat::Html => match self.get_html() { Ok(html) => contents.push(ClipboardContent::Html(html)), Err(_) => continue, }, #[cfg(feature = "image")] ContentFormat::Image => match self.get_image() { Ok(image) => contents.push(ClipboardContent::Image(image)), Err(_) => continue, }, ContentFormat::Files => match self.get_files() { Ok(files) => contents.push(ClipboardContent::Files(files)), Err(_) => continue, }, ContentFormat::Other(format_name) => match self.get_buffer(format_name) { Ok(buffer) => { contents.push(ClipboardContent::Other(format_name.clone(), buffer)) } Err(_) => continue, }, } } Ok(contents) } ``` -------------------------------- ### Initialize ClipboardWatcherContext in Rust Source: https://docs.rs/clipboard-rs/0.3.1/clipboard_rs/struct.ClipboardWatcherContext_search=u32+-%3E+bool Demonstrates the creation of a new `ClipboardWatcherContext` instance. The `new()` function returns a `Result` which can be unwrapped to get the context. This is a common pattern for initializing resources that might fail. ```rust let mut watcher = ClipboardWatcherContext::new().unwrap(); ```