#terminal #console #cli #background-color

bin+lib termbg-with-async-stdin

Terminal background color detection

2 releases

0.1.1 Oct 11, 2024
0.1.0 Sep 24, 2024

#157 in Command-line interface

Download history 311/week @ 2024-09-21 367/week @ 2024-09-28 359/week @ 2024-10-05 310/week @ 2024-10-12 17/week @ 2024-10-19 168/week @ 2024-10-26 560/week @ 2024-11-02 426/week @ 2024-11-09 500/week @ 2024-11-16 544/week @ 2024-11-23 301/week @ 2024-11-30

1,802 downloads per month
Used in 3 crates (via oma-console)

MIT/Apache

21KB
421 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.5.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

~6–16MB
~220K SLoC