convert/
convert.rs

1use std::io::stdout;
2
3use anstyle::{Ansi256Color, Color, RgbColor, Style};
4use anstyle_owo_colors::to_owo_style;
5use owo_colors::OwoColorize;
6use termprofile::{DetectorSettings, TermProfile};
7
8fn main() {
9    let color = parse_input();
10    let profile = TermProfile::detect(&stdout(), DetectorSettings::with_query().unwrap());
11    println!("Detected profile: {profile:?}");
12    print!("Adapted: ");
13    print_color(profile, color);
14    if profile > TermProfile::Ansi256 {
15        print!("ANSI 256: ");
16        print_color(TermProfile::Ansi256, color);
17    }
18    if profile > TermProfile::Ansi16 {
19        print!("ANSI 16: ");
20        print_color(TermProfile::Ansi16, color);
21    }
22}
23
24fn print_color(profile: TermProfile, color: Color) {
25    let color = profile.adapt_color(color);
26    if let Some(color) = color {
27        let style = to_owo_style(Style::new().fg_color(Some(color)));
28        println!("{}", color_to_str(&color).style(style));
29    } else {
30        println!("No color");
31    }
32}
33
34fn rand_rgb() -> u8 {
35    rand::random_range(0..256) as u8
36}
37
38fn color_to_str(color: &Color) -> String {
39    match color {
40        Color::Ansi(ansi) => format!("{ansi:?}"),
41        Color::Ansi256(color) => color.0.to_string(),
42        Color::Rgb(color) => format!("rgb({},{},{})", color.0, color.1, color.2),
43    }
44}
45
46fn parse_input() -> Color {
47    let args: Vec<String> = std::env::args().collect();
48    if args.len() == 4 {
49        let rgb = (
50            args[1].parse::<u8>().unwrap(),
51            args[2].parse::<u8>().unwrap(),
52            args[3].parse::<u8>().unwrap(),
53        );
54        RgbColor(rgb.0, rgb.1, rgb.2).into()
55    } else if args.len() == 2 {
56        let parts: Vec<_> = args[1].split(",").collect();
57        if parts.len() == 3 {
58            let rgb = (
59                parts[0].parse::<u8>().unwrap(),
60                parts[1].parse::<u8>().unwrap(),
61                parts[2].parse::<u8>().unwrap(),
62            );
63            RgbColor(rgb.0, rgb.1, rgb.2).into()
64        } else {
65            let i: u8 = args[1].parse().unwrap();
66            Ansi256Color(i).into()
67        }
68    } else {
69        RgbColor(rand_rgb(), rand_rgb(), rand_rgb()).into()
70    }
71}