#console #terminal #cli

bin+lib termbg

Terminal background color detection

9 releases

0.4.1 May 25, 2022
0.4.0 Jan 25, 2022
0.3.0 May 28, 2021
0.2.4 May 20, 2021
0.1.0 Nov 9, 2020

#160 in Command-line interface

Download history 500/week @ 2022-04-21 557/week @ 2022-04-28 675/week @ 2022-05-05 528/week @ 2022-05-12 751/week @ 2022-05-19 799/week @ 2022-05-26 554/week @ 2022-06-02 589/week @ 2022-06-09 514/week @ 2022-06-16 605/week @ 2022-06-23 643/week @ 2022-06-30 650/week @ 2022-07-07 767/week @ 2022-07-14 622/week @ 2022-07-21 582/week @ 2022-07-28 549/week @ 2022-08-04

2,639 downloads per month
Used in 2 crates

MIT/Apache

16KB
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.4.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.

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

Dependencies

~2–3MB
~61K SLoC