17 unstable releases (5 breaking)

0.6.1 Nov 15, 2024
0.5.2 Oct 11, 2024
0.5.0 Mar 6, 2024
0.4.4 Dec 6, 2023
0.2.0 Nov 10, 2020

#38 in Command-line interface

Download history 2510/week @ 2024-08-16 2910/week @ 2024-08-23 3564/week @ 2024-08-30 3724/week @ 2024-09-06 3848/week @ 2024-09-13 3728/week @ 2024-09-20 4198/week @ 2024-09-27 3877/week @ 2024-10-04 4515/week @ 2024-10-11 5380/week @ 2024-10-18 4030/week @ 2024-10-25 2513/week @ 2024-11-01 2756/week @ 2024-11-08 3288/week @ 2024-11-15 2744/week @ 2024-11-22 3018/week @ 2024-11-29

12,250 downloads per month
Used in 16 crates (12 directly)

MIT/Apache

39KB
717 lines

termbg

A Rust library for terminal background color detection. The detected color is provided by RGB or theme ( dark or light ).

Actions Status Crates.io Docs.rs

Verified terminals

If you check other terminals, please report through issue.

Unsupported terminals

"Windows Terminal" may be supported in a future release: https://github.com/microsoft/terminal/issues/3718.

Usage

[dependencies]
termbg = "0.6.1"

Example

fn main() {
    let timeout = std::time::Duration::from_millis(100);

    println!("Check terminal background color");
    let term = termbg::terminal();
    let rgb = termbg::rgb(timeout);
    let theme = termbg::theme(timeout);

    println!("  Term : {:?}", term);

    match rgb {
        Ok(rgb) => {
            println!("  Color: R={:x}, G={:x}, B={:x}", rgb.r, rgb.g, rgb.b);
        }
        Err(e) => {
            println!("  Color: detection failed {:?}", e);
        }
    }

    match theme {
        Ok(theme) => {
            println!("  Theme: {:?}", theme);
        }
        Err(e) => {
            println!("  Theme: detection failed {:?}", e);
        }
    }
}

Check program

This crate provides a simple program to check.

$ cargo run
Check terminal background color
  Term : Tmux
  Color: R=0, G=0, B=0
  Theme: Dark

Detecting mechanism

If the terminal is win32 console, WIN32API is used for detection. If the terminal is xterm compatible, "Xterm Control Sequences" is used. When these method was failed, COLORFGBG environment variable is used.

The detected RGB is converted to YCbCr. If Y > 0.5, the theme is detected as "light", otherwise "dark".

Dependencies

~4–13MB
~169K SLoC