### Create an Example Calling a Documented Function Source: https://docs.rs/terminal-colorsaurus/1.0.3/scrape-examples-help.html Create an example file that calls a documented function from your crate. This example will be scraped by Rustdoc and included in the documentation of the called function. ```Rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Enable Example Scraping with Cargo Doc Source: https://docs.rs/terminal-colorsaurus/1.0.3/scrape-examples-help.html Run the cargo doc command with unstable options to enable example scraping. This command analyzes your project's documented items and their usage in examples. ```Shell cargo doc -Zunstable-options -Zrustdoc-scrape-examples ``` -------------------------------- ### and() method examples Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Demonstrates the behavior of the `and` method, which returns the second Result if the first is Ok, otherwise returns the first Err. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Test If the Terminal Uses a Dark Background Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus This example demonstrates how to use the `theme_mode` function to detect if the terminal's background is dark. ```APIDOC ## Example: Test If the Terminal Uses a Dark Background ### Description This example shows how to determine if the terminal background is dark using the `theme_mode` function. ### Function Signature `theme_mode(options: QueryOptions) -> Result` ### Parameters * `options` (QueryOptions) - Options for querying terminal colors. `QueryOptions::default()` is recommended. ### Return Value * `Ok(ThemeMode)` - An enum indicating `ThemeMode::Dark` or `ThemeMode::Light`. * `Err(Error)` - An error if the query fails. ### Example Usage ```rust use terminal_colorsaurus::{theme_mode, ThemeMode, QueryOptions}; let theme_mode = theme_mode(QueryOptions::default()).unwrap(); dbg!(theme_mode == ThemeMode::Dark); ``` ``` -------------------------------- ### Get the Terminal’s Foreground Color Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus This example shows how to retrieve the terminal's foreground color using the `foreground_color` function. ```APIDOC ## Example: Get the Terminal’s Foreground Color ### Description This example demonstrates how to retrieve the terminal's foreground color using the `foreground_color` function and print its RGB values. ### Function Signature `foreground_color(options: QueryOptions) -> Result` ### Parameters * `options` (QueryOptions) - Options for querying terminal colors. `QueryOptions::default()` is recommended. ### Return Value * `Ok(Color)` - A `Color` struct containing the RGB values (r, g, b) of the foreground color. * `Err(Error)` - An error if the query fails. ### Example Usage ```rust use terminal_colorsaurus::{foreground_color, QueryOptions}; let fg = foreground_color(QueryOptions::default()).unwrap(); println!("rgb({}, {}, {})", fg.r, fg.g, fg.b); ``` ``` -------------------------------- ### Define a Public Function for Example Scraping Source: https://docs.rs/terminal-colorsaurus/1.0.3/scrape-examples-help.html Define a public function in your library's source code that you want to document and potentially show examples for. Rustdoc will look for documented items to associate scraped examples with. ```Rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### Test DA1 Support in Terminal Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/terminal_survey/index.html Use this command to test if your terminal supports the Device Attributes (DA1) query. The output will typically start with `^[[?`. ```shell printf '\e[c' && cat -v # Tests for DA1. Example output: ^[[?65;1;9c ``` -------------------------------- ### Get Reference to Ok Value Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `as_ref()` to obtain a `Result<&T, &E>` from a `&Result`. This allows inspecting the contained values without consuming the original Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Detect Terminal Theme Mode Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/theme/theme.rs.html Use `color_palette` with default options to get terminal colors and then check the `theme_mode()` to determine if the terminal is dark or light. Prints the theme mode and perceived lightness of foreground and background colors. ```rust use terminal_colorsaurus::{color_palette, Error, QueryOptions, ThemeMode}; fn main() -> Result<(), display::DisplayAsDebug> { let colors = color_palette(QueryOptions::default())?; let theme = match colors.theme_mode() { ThemeMode::Dark => "dark", ThemeMode::Light => "light", }; println!( "{theme}, fg: {}, bg: {}", colors.foreground.perceived_lightness(), colors.background.perceived_lightness() ); Ok(()) } #[path = "../examples-utils/display.rs"] mod display; ``` -------------------------------- ### theme_mode Function Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.theme_mode.html Detects if the terminal is dark or light. Extra care needs to be taken on Unix if your program might share the terminal with another program. This might be the case if you expect your output to be used with a pager e.g. `your_program` | `less`. In that case, a race condition exists because the pager will also set the terminal to raw mode. The `pager` example shows a heuristic to deal with this issue. ```APIDOC ## theme_mode ### Description Detects if the terminal is dark or light. ### Caveats Extra care needs to be taken on Unix if your program might share the terminal with another program. This might be the case if you expect your output to be used with a pager e.g. `your_program` | `less`. In that case, a race condition exists because the pager will also set the terminal to raw mode. The `pager` example shows a heuristic to deal with this issue. ### Function Signature ```rust pub fn theme_mode(options: QueryOptions) -> Result ``` ### Example Usage ```rust fn main() -> Result<(), display::DisplayAsDebug> { if stdout().is_terminal() { eprintln!( "Here's the theme mode: {:#?}", theme_mode(QueryOptions::default())? ); } else { eprintln!("No theme mode for you today :/"); } Ok(()) } ``` ``` -------------------------------- ### Basic unwrap() usage Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Demonstrates unwrapping an Ok value. Panics if the value is an Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Getting Value or Default with unwrap_or Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `unwrap_or` to get the `Ok` value or a provided default if the `Result` is `Err`. The default value is eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### into_ok() usage Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Safely extracts the Ok value without panicking. This is an experimental nightly-only API. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Any for T Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/struct.Color.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ``` -------------------------------- ### into_ok Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Returns the contained Ok value, but never panics. This is a nightly-only experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Method `into_ok()` ### Parameters None ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response - **T**: The contained `Ok` value. ### Response Example ```rust // If Ok(value), returns value // This method is guaranteed not to panic. ``` ``` -------------------------------- ### Default QueryOptions Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/struct.QueryOptions.html Provides the default configuration for QueryOptions, setting the timeout to 1 second. It is recommended to use this default value unless specific needs dictate otherwise. ```rust fn default() -> Self ``` -------------------------------- ### fn report(self) -> ExitCode Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Is called to get the representation of the value as status code. This status code is returned to the operating system. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Returns An `ExitCode` representing the status of the `Result`. ``` -------------------------------- ### CloneToUninit for T Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/struct.Color.html Provides an unsafe method for cloning data to an uninitialized memory location. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters #### Path Parameters - **dest** (*mut u8) - Required - The destination pointer. ``` -------------------------------- ### fn from_output(output: as Try>::Output) -> Result Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Constructs the type from its `Output` type. ```APIDOC ## fn from_output(output: as Try>::Output) -> Result ### Description Constructs the type from its `Output` type. Read more ``` -------------------------------- ### Unchecked Unwrap for Err Values Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `unwrap_err_unchecked` to get the `Err` value without checking if it's an `Ok`. This is unsafe and requires the caller to guarantee the `Result` is `Err`. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Query Color Palette Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/xterm.rs.html Queries the terminal for both foreground and background colors simultaneously. ```APIDOC ## color_palette ### Description Queries the terminal for both the current foreground and background colors. ### Method ```rust pub(crate) fn color_palette(options: QueryOptions) -> Result ``` ### Parameters - **options** (`QueryOptions`): Options for the query, including timeout settings. ### Response - **Success Response** (`Result`): Returns a `ColorPalette` struct containing foreground and background colors if successful. - **Error** (`Error`): Returns an error if the query times out, is unsupported, or parsing fails. ``` -------------------------------- ### Unchecked Unwrap for Ok Values Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `unwrap_unchecked` to get the `Ok` value without checking if it's an `Err`. This is unsafe and requires the caller to guarantee the `Result` is `Ok`. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Result Implementations Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Provides documentation for various implementations of the Result type, including methods for copying, cloning, transposing, flattening, and checking the status of the result. ```APIDOC ## Result Implementations ### `impl Result<&T, E>` #### `copied(self) -> Result` **Description**: Maps a `Result<&T, E>` to a `Result` by copying the contents of the `Ok` part. Requires `T` to implement `Copy`. **Example**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `cloned(self) -> Result` **Description**: Maps a `Result<&T, E>` to a `Result` by cloning the contents of the `Ok` part. Requires `T` to implement `Clone`. **Example**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ### `impl Result<&mut T, E>` #### `copied(self) -> Result` **Description**: Maps a `Result<&mut T, E>` to a `Result` by copying the contents of the `Ok` part. Requires `T` to implement `Copy`. **Example**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `cloned(self) -> Result` **Description**: Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the `Ok` part. Requires `T` to implement `Clone`. **Example**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ### `impl Result, E>` #### `transpose(self) -> Option>` **Description**: Transposes a `Result` of an `Option` into an `Option` of a `Result`. `Ok(None)` is mapped to `None`. `Ok(Some(_))` and `Err(_)` are mapped to `Some(Ok(_))` and `Some(Err(_))` respectively. **Example**: ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` ### `impl Result, E>` #### `flatten(self) -> Result` **Description**: Converts from `Result, E>` to `Result`, removing one level of nesting. **Example**: ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); // Flattening removes one level at a time: let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` ### `impl Result` #### `is_ok(&self) -> bool` **Description**: Returns `true` if the result is `Ok`. **Example**: ```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); ``` #### `is_ok_and(self, f: F) -> bool` where `F: FnOnce(T) -> bool` **Description**: Returns `true` if the result is `Ok` and the value inside of it matches a predicate. **Example**: ```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); ``` #### `is_err(&self) -> bool` **Description**: Returns `true` if the result is `Err`. **Example**: ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` #### `is_err_and(self, f: F) -> bool` where `F: FnOnce(E) -> bool` **Description**: Returns `true` if the result is `Err` and the value inside of it matches a predicate. ``` -------------------------------- ### Mutably Iterating Over Ok Values with iter_mut Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `iter_mut` to get a mutable iterator over the contained value if the Result is Ok. This allows in-place modification of the Ok value. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### color_palette Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/lib.rs.html Queries the terminal for its color palette, including foreground and background colors. This is more efficient if both colors are needed. ```APIDOC ## color_palette ### Description Queries the terminal for it's color palette (foreground and background color). ### Function Signature `pub fn color_palette(options: QueryOptions) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`QueryOptions`) - Options for querying the terminal, including timeout settings. ### Response #### Success Response - **ColorPalette** - A struct containing the terminal's color palette information. ### Example ```rust use terminal_colorsaurus::{color_palette, QueryOptions}; let options = QueryOptions { timeout: std::time::Duration::from_secs(1) }; match color_palette(options) { Ok(palette) => { println!("Foreground color: {:?}", palette.foreground); println!("Background color: {:?}", palette.background); }, Err(e) => eprintln!("Error querying color palette: {}", e), } ``` ``` -------------------------------- ### Handling File Metadata with Result Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Demonstrates using `Result` to handle potential errors when accessing file metadata, such as checking modification times. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### fn hash<__H>(&self, state: &mut __H) -> () Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Feeds this value into the given `Hasher`. ```APIDOC ## fn hash<__H>(&self, state: &mut __H) -> () ### Description Feeds this value into the given `Hasher`. ### Parameters #### Path Parameters - **state** (__H) - Required - The hasher state. ``` -------------------------------- ### Get Terminal String Terminator Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/quirks.rs.html Returns the appropriate byte slice to terminate a string query for the terminal. Defaults to BEL (0x07) to work around bugs in rxvt-unicode. ```rust pub(crate) fn string_terminator(self) -> &'static [u8] { // The currently released version of rxvt-unicode (urxvt) has a bug where it terminates the response with `ESC` instead of `ST` (`ESC \`). // This causes us to run into the timeout because we get stuck waiting for a `\` that never arrives. // Fixed by revision [1.600](http://cvs.schmorp.de/rxvt-unicode/src/command.C?revision=1.600&view=markup). // The bug can be worked around by sending a query with `BEL` which will result in a `BEL`-terminated response. // // Originally, we used `BEL` only for urxvt. However, after a discussion in delta [1], // I noticed that there are quite a few people who use urxvt with a different `TERM` // env var (e.g. `urxvt`, `xterm`, or even `screen`) [2]. // // [1]: https://github.com/dandavison/delta/issues/1897 // [2]: https://github.com/search?q=URxvt*termName&type=code const BEL: u8 = 0x07; &[BEL] } ``` -------------------------------- ### Computing Default Value with unwrap_or_else Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `unwrap_or_else` to get the `Ok` value or compute a default value using a closure if the `Result` is `Err`. This allows for lazy evaluation of the default. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Default Implementation for QueryOptions Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/struct.QueryOptions.html Provides a default value for QueryOptions, which is recommended for most use cases. ```APIDOC ### impl Default for QueryOptions #### fn default() -> Self Returns the default value for `QueryOptions`, which is `QueryOptions { timeout: Duration::from_secs(1) }`. ``` -------------------------------- ### Get Mutable Reference to Result Values Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use `as_mut()` to obtain a `Result<&mut T, &mut E>` from a `&mut Result`. This allows modifying the contained values in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Get Terminal's Foreground Color Source: https://docs.rs/terminal-colorsaurus Retrieve the terminal's foreground color using the `foreground_color` function with default query options. The output is printed in RGB format. ```rust use terminal_colorsaurus::{foreground_color, QueryOptions}; let fg = foreground_color(QueryOptions::default()).unwrap(); println!("rgb({}, {}, {})", fg.r, fg.g, fg.b); ``` -------------------------------- ### QueryOptions Struct Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/lib.rs.html Options to be used with color querying functions. ```APIDOC ## QueryOptions ### Description Options to be used with [`foreground_color`] and [`background_color`]. You should almost always use the unchanged [`QueryOptions::default`] value. ### Fields - **timeout** (`std::time::Duration`) - The maximum time spent waiting for a response from the terminal. Defaults to 1 s. Consider leaving this on a high value as there might be a lot of latency \ between you and the terminal (e.g. when you're connected via SSH). Terminals that don't support querying for colors will time out and return an error. ``` -------------------------------- ### fn product(iter: I) -> Result Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Takes each element in the Iterator. If it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the product of all elements is returned. ```APIDOC ## fn product(iter: I) -> Result ### Description Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, the product of all elements is returned. ### Parameters * `iter`: An iterator where each item is a `Result`. ### Returns A `Result` containing the product of the elements if successful, or the first encountered `Err`. ### Examples ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` ``` -------------------------------- ### Retrieve Terminal Foreground Color - Rust Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/fg/fg.rs.html Use `foreground_color` with default `QueryOptions` to get the terminal's foreground color. The result can be scaled to 8-bit RGB format for display. ```rust use terminal_colorsaurus::{foreground_color, Error, QueryOptions}; fn main() -> Result<(), display::DisplayAsDebug> { let fg = foreground_color(QueryOptions::default())?; let fg_8bit = fg.scale_to_8bit(); println!("rgb16({}, {}, {})", fg.r, fg.g, fg.b); println!("rgb8({}, {}, {})", fg_8bit.0, fg_8bit.1, fg_8bit.2); Ok(()) } #[path = "../examples-utils/display.rs"] mod display; ``` -------------------------------- ### TermReader Struct Definition Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/io/term_reader.rs.html Defines the TermReader struct, which holds an inner reader, a timeout duration, and the start time of the first read operation. This struct is used for implementing timed reads. ```rust use super::poll_read; use std::io; use std::time::{Duration, Instant}; use terminal_trx::Transceive; #[derive(Debug)] pub(crate) struct TermReader { inner: R, timeout: Duration, first_read: Option, } impl io::Read for TermReader where R: Transceive, { fn read(&mut self, buf: &mut [u8]) -> io::Result { let timeout = self.remaining_timeout(); poll_read(&self.inner, timeout)?; self.inner.read(buf) } } impl TermReader { pub(crate) fn new(inner: R, timeout: Duration) -> Self { Self { inner, timeout, first_read: None, } } fn remaining_timeout(&mut self) -> Duration { let first_read = self.first_read.get_or_insert_with(Instant::now); self.timeout.saturating_sub(first_read.elapsed()) } } ``` -------------------------------- ### Get Terminal Background Color Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.background_color.html Queries the terminal for its background color and prints the RGB values in both 16-bit and 8-bit formats. This function is useful for determining the terminal's background color for styling purposes. ```rust fn main() -> Result<(), display::DisplayAsDebug> { let bg = background_color(QueryOptions::default())?; let bg_8bit = bg.scale_to_8bit(); println!("rgb16({}, {}, {})", bg.r, bg.g, bg.b); println!("rgb8({}, {}, {})", bg_8bit.0, bg_8bit.1, bg_8bit.2); Ok(()) } ``` -------------------------------- ### Initialize Terminal Quirks from Environment Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/quirks.rs.html Initializes terminal quirks based on the TERM environment variable using an `OnceLock` for consistent results across calls. ```rust use std::env; use std::io::{self, Write}; use std::sync::OnceLock; pub(crate) fn terminal_quirks_from_env() -> TerminalQuirks { // This OnceLock is not here for efficiency, it's here so that // we have consistent results in case a consumer uses `set_var`. static TERMINAL_QUIRK: OnceLock = OnceLock::new(); *TERMINAL_QUIRK.get_or_init(terminal_quirk_from_env_eager) } ``` -------------------------------- ### Get Foreground Color Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.foreground_color.html Queries the terminal for its foreground color and prints its RGB values. Use `color_palette` if both foreground and background colors are needed. Be aware of potential race conditions on Unix systems when sharing terminals. ```rust fn main() -> Result<(), display::DisplayAsDebug> { let fg = foreground_color(QueryOptions::default())?; let fg_8bit = fg.scale_to_8bit(); println!("rgb16({}, {}, {})", fg.r, fg.g, fg.b); println!("rgb8({}, {}, {})", fg_8bit.0, fg_8bit.1, fg_8bit.2); Ok(()) } ``` -------------------------------- ### Test Background Color Support in Terminal Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/terminal_survey/index.html Use this command to test for background color support via the OSC 11 query. A successful test will display the current background color. ```shell printf '\e]11;?\e\' && cat -v # Tests for background color support. Example output: ^[]11;rgb:ffff/ffff/ffff^[ ``` -------------------------------- ### theme_mode Source: https://docs.rs/terminal-colorsaurus Detects if the terminal is dark or light. It uses `QueryOptions` to configure the detection process. ```APIDOC ## theme_mode ### Description Detects if the terminal is dark or light. ### Function Signature `pub fn theme_mode(options: QueryOptions) -> Result` ### Parameters * `options` (QueryOptions) - Options to be used with `theme_mode`. ### Returns * `Result` - An enum indicating `ThemeMode::Dark` or `ThemeMode::Light`. ### Example ```rust use terminal_colorsaurus::{theme_mode, ThemeMode, QueryOptions}; let theme_mode = theme_mode(QueryOptions::default()).unwrap(); dbg!(theme_mode == ThemeMode::Dark); ``` ``` -------------------------------- ### ok Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Converts `Result` to `Option`, consuming the `Result` and discarding the error if any. ```APIDOC ## ok ### Description Converts `Result` to `Option`, consuming the `Result` and discarding the error if any. ### Method `ok()` ### Response - `Option`: `Some(T)` if the result was `Ok`, `None` if it was `Err`. ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ``` -------------------------------- ### Querying Terminal Color Palette Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/lib.rs.html Retrieves both the foreground and background colors of the terminal. ```APIDOC ## color_palette ### Description Retrieves both the foreground and background colors of the terminal. ### Function Signature `pub fn color_palette(options: QueryOptions) -> Result` ### Parameters #### Query Options - **options** (`QueryOptions`) - Options to configure the query, such as timeout. ### Returns - `Result` - A `ColorPalette` struct containing the foreground and background colors. ### Example ```no_run use terminal_colorsaurus::{color_palette, QueryOptions}; let palette = color_palette(QueryOptions::default()).unwrap(); println!("Foreground: rgb({}, {}, {})", palette.foreground.r, palette.foreground.g, palette.foreground.b); println!("Background: rgb({}, {}, {})", palette.background.r, palette.background.g, palette.background.b); ``` ``` -------------------------------- ### Error::unsupported() Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/error.rs.html A constructor function to create an `Error::UnsupportedTerminal` variant. ```APIDOC ## `Error::unsupported()` ### Description Creates a new `Error::UnsupportedTerminal` instance. This is a convenience function for indicating that the terminal lacks support for color querying features. ### Returns - `Error::UnsupportedTerminal(UnsupportedTerminalError)` ``` -------------------------------- ### color_palette Source: https://docs.rs/terminal-colorsaurus/1.0.3/index.html Queries the terminal for its color palette, which includes both foreground and background colors. This is more efficient than calling `background_color` and `foreground_color` separately. ```APIDOC ## color_palette ### Description Queries the terminal for it’s color palette (foreground and background color). ### Function Signature `pub fn color_palette(options: QueryOptions) -> Result` ### Parameters #### Path Parameters None #### Query Parameters - **options** (`QueryOptions`) - Options to be used with the query. `QueryOptions::default()` is recommended. ### Request Example ```rust use terminal_colorsaurus::{color_palette, QueryOptions}; let palette = color_palette(QueryOptions::default()).unwrap(); println!("Foreground: rgb({}, {}, {})", palette.foreground.r, palette.foreground.g, palette.foreground.b); println!("Background: rgb({}, {}, {})", palette.background.r, palette.background.g, palette.background.b); ``` ### Response #### Success Response - **ColorPalette** (`ColorPalette`) - A struct containing the terminal's foreground and background colors. - **foreground** (`Color`) - The foreground color. - **background** (`Color`) - The background color. #### Response Example ```rust // Example output // let palette = color_palette(QueryOptions::default()).unwrap(); // println!("Foreground: rgb({}, {}, {})", palette.foreground.r, palette.foreground.g, palette.foreground.b); // Foreground: rgb(240, 240, 240) // println!("Background: rgb({}, {}, {})", palette.background.r, palette.background.g, palette.background.b); // Background: rgb(10, 10, 10) ``` ``` -------------------------------- ### color_palette Function Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.color_palette.html Queries the terminal for its color palette (foreground and background color). ```APIDOC ## color_palette Queries the terminal for it’s color palette (foreground and background color). ### Caveats Extra care needs to be taken on Unix if your program might share the terminal with another program. This might be the case if you expect your output to be used with a pager e.g. `your_program` | `less`. In that case, a race condition exists because the pager will also set the terminal to raw mode. The `pager` example shows a heuristic to deal with this issue. ### Signature ```rust pub fn color_palette(options: QueryOptions) -> Result ``` ### Example Usage ```rust fn main() -> Result<(), display::DisplayAsDebug> { let colors = color_palette(QueryOptions::default())?; let theme = match colors.theme_mode() { ThemeMode::Dark => "dark", ThemeMode::Light => "light", }; println!( "{theme}, fg: {}, bg: {}", colors.foreground.perceived_lightness(), colors.background.perceived_lightness() ); Ok(()) } ``` ``` -------------------------------- ### foreground_color Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.foreground_color.html Queries the terminal for its foreground color. If you also need the foreground color, it is more efficient to use `color_palette` instead. Extra care needs to be taken on Unix if your program might share the terminal with another program. ```APIDOC ## foreground_color Queries the terminal for it’s foreground color. If you also need the foreground color it is more efficient to use `color_palette` instead. ### Caveats Extra care needs to be taken on Unix if your program might share the terminal with another program. This might be the case if you expect your output to be used with a pager e.g. `your_program` | `less`. In that case, a race condition exists because the pager will also set the terminal to raw mode. The `pager` example shows a heuristic to deal with this issue. ### Signature ```rust pub fn foreground_color(options: QueryOptions) -> Result ``` ### Example ```rust fn main() -> Result<(), display::DisplayAsDebug> { let fg = foreground_color(QueryOptions::default())?; let fg_8bit = fg.scale_to_8bit(); println!("rgb16({}, {}, {})", fg.r, fg.g, fg.b); println!("rgb8({}, {}, {})", fg_8bit.0, fg_8bit.1, fg_8bit.2); Ok(()) } ``` ``` -------------------------------- ### color_palette Source: https://docs.rs/terminal-colorsaurus Queries the terminal for its color palette, including foreground and background colors. ```APIDOC ## color_palette ### Description Queries the terminal for it’s color palette (foreground and background color). ### Function Signature `pub fn color_palette(options: QueryOptions) -> Result` ### Parameters * `options` (QueryOptions) - Options to be used with `color_palette`. ### Returns * `Result` - Contains the foreground and background colors of the terminal. ``` -------------------------------- ### Map Ok Value or Return Default (Experimental) Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Use the experimental `map_or_default()` to apply a function to the `Ok` value or return the default value of the target type if the Result is `Err`. Requires nightly Rust. ```rust #![feature(result_option_map_or_default)] let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### fn clamp(self, min: Self, max: Self) -> Self Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Restrict a value to a certain interval. ```APIDOC ## fn clamp(self, min: Self, max: Self) -> Self ### Description Restrict a value to a certain interval. ### Parameters #### Path Parameters - **min** (Self) - Required - The minimum bound. - **max** (Self) - Required - The maximum bound. ### Response - **Self** - The clamped Result value. ``` -------------------------------- ### Implement Display for CaretNotation Source: https://docs.rs/terminal-colorsaurus/1.0.3/src/terminal_colorsaurus/fmt.rs.html Formats a string by replacing control characters with their caret notation. Use this when you need to display strings containing control characters in a human-readable format. ```rust use std::fmt; // Caret notation encodes control characters as ^char. // See: https://en.wikipedia.org/wiki/Caret_notation pub(crate) struct CaretNotation<'a>(pub(crate) &'a str); impl fmt::Display for CaretNotation<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for c in self.0.chars() { if c.is_control() { write!(f, "{}", EscapeCaret(c))?; } else { write!(f, "{c}")?; } } Ok(()) } } struct EscapeCaret(char); impl fmt::Display for EscapeCaret { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(escaped) = char::from_u32(u32::from(self.0) ^ 0x40) { write!(f, "^{escaped}") } else { write!(f, "{}", self.0) } } } ``` -------------------------------- ### foreground_color Source: https://docs.rs/terminal-colorsaurus/1.0.3/index.html Queries the terminal for its foreground color. If you also need the background color, it is more efficient to use `color_palette`. ```APIDOC ## foreground_color ### Description Queries the terminal for it’s foreground color. ### Function Signature `pub fn foreground_color(options: QueryOptions) -> Result` ### Parameters #### Path Parameters None #### Query Parameters - **options** (`QueryOptions`) - Options to be used with the query. `QueryOptions::default()` is recommended. ### Request Example ```rust use terminal_colorsaurus::{foreground_color, QueryOptions}; let fg = foreground_color(QueryOptions::default()).unwrap(); println!("rgb({}, {}, {})", fg.r, fg.g, fg.b); ``` ### Response #### Success Response - **Color** (`Color`) - An RGB color with 16 bits per channel representing the terminal's foreground color. #### Response Example ```rust // Example output for a light foreground color // let fg = foreground_color(QueryOptions::default()).unwrap(); // println!("rgb({}, {}, {})", fg.r, fg.g, fg.b); // rgb(240, 240, 240) ``` ``` -------------------------------- ### background_color Source: https://docs.rs/terminal-colorsaurus/1.0.3/index.html Queries the terminal for its background color. If you also need the foreground color, it is more efficient to use `color_palette`. ```APIDOC ## background_color ### Description Queries the terminal for it’s background color. ### Function Signature `pub fn background_color(options: QueryOptions) -> Result` ### Parameters #### Path Parameters None #### Query Parameters - **options** (`QueryOptions`) - Options to be used with the query. `QueryOptions::default()` is recommended. ### Request Example ```rust use terminal_colorsaurus::{background_color, QueryOptions}; let bg = background_color(QueryOptions::default()).unwrap(); println!("rgb({}, {}, {})", bg.r, bg.g, bg.b); ``` ### Response #### Success Response - **Color** (`Color`) - An RGB color with 16 bits per channel representing the terminal's background color. #### Response Example ```rust // Example output for a dark background // let bg = background_color(QueryOptions::default()).unwrap(); // println!("rgb({}, {}, {})", bg.r, bg.g, bg.b); // rgb(10, 10, 10) ``` ``` -------------------------------- ### background_color Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/fn.background_color.html Queries the terminal for its background color. If you also need the foreground color, it is more efficient to use `color_palette` instead. Extra care needs to be taken on Unix if your program might share the terminal with another program, as a race condition exists because the pager will also set the terminal to raw mode. ```APIDOC ## background_color ### Description Queries the terminal for it’s background color. If you also need the foreground color it is more efficient to use `color_palette` instead. ### §Caveats Extra care needs to be taken on Unix if your program might share the terminal with another program. This might be the case if you expect your output to be used with a pager e.g. `your_program` | `less`. In that case, a race condition exists because the pager will also set the terminal to raw mode. The `pager` example shows a heuristic to deal with this issue. ### Function Signature ```rust pub fn background_color(options: QueryOptions) -> Result ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use terminal_colorsaurus::display; use terminal_colorsaurus::Error; use terminal_colorsaurus::background_color; fn main() -> Result<(), display::DisplayAsDebug> { let bg = background_color(QueryOptions::default())?; let bg_8bit = bg.scale_to_8bit(); println!("rgb16({}, {}, {})", bg.r, bg.g, bg.b); println!("rgb8({}, {}, {})", bg_8bit.0, bg_8bit.1, bg_8bit.2); Ok(()) } ``` ### Response #### Success Response (200) - **Color**: Represents the terminal's background color. #### Response Example (No specific response example provided in the source, but the function returns a `Color` type.) ``` -------------------------------- ### Test Foreground Color Support in Terminal Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/terminal_survey/index.html This command tests for foreground color support using the OSC 10 query. Successful responses will show the current foreground color, often in `rgb:xxxx/xxxx/xxxx` format. ```shell printf '\e]10;?\e\' && cat -v # Tests for foreground color support. Example output: ^[]10;rgb:0000/0000/0000^[ ``` -------------------------------- ### fn cmp(&self, other: &Result) -> Ordering Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html This method returns an `Ordering` between `self` and `other`. ```APIDOC ## fn cmp(&self, other: &Result) -> Ordering ### Description This method returns an `Ordering` between `self` and `other`. ### Parameters #### Path Parameters - **other** (&Result) - Required - The other Result to compare against. ### Response - **Ordering** - The ordering between the two Results. ``` -------------------------------- ### fn from_residual(_ : Yeet) -> Result Source: https://docs.rs/terminal-colorsaurus/1.0.3/terminal_colorsaurus/type.Result.html Constructs the type from a compatible `Residual` type. This is a nightly-only experimental API. ```APIDOC ## fn from_residual(_ : Yeet) -> Result ### Description Constructs the type from a compatible `Residual` type. This is a nightly-only experimental API. ### Parameters #### Path Parameters - **_** (Yeet) - Required - The residual type to construct from. ### Response - **Result** - The constructed Result type. ```