13 releases

0.5.0 Mar 6, 2024
0.4.4 Dec 6, 2023
0.4.3 Mar 2, 2023
0.4.1 May 25, 2022
0.2.0 Nov 10, 2020

#67 in Command-line interface

Download history 388/week @ 2023-12-18 303/week @ 2023-12-25 471/week @ 2024-01-01 475/week @ 2024-01-08 340/week @ 2024-01-15 406/week @ 2024-01-22 372/week @ 2024-01-29 388/week @ 2024-02-05 362/week @ 2024-02-12 850/week @ 2024-02-19 460/week @ 2024-02-26 2046/week @ 2024-03-04 3711/week @ 2024-03-11 3011/week @ 2024-03-18 2884/week @ 2024-03-25 3278/week @ 2024-04-01

13,174 downloads per month
Used in 8 crates (6 directly)

MIT/Apache

18KB
344 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.0"

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–17MB
~215K SLoC