Skip to main content

retch_cli/
logo.rs

1// SPDX-FileCopyrightText: 2026 Ken Tobias
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4//! ASCII and graphical logo definitions and rendering.
5//!
6//! Contains embedded distro logos and logic for rendering them
7//! as text or images (e.g., Sixel, Kitty, iTerm).
8
9// Exact Fastfetch ASCII logos (intact, unmodified)
10// Source: https://github.com/fastfetch-cli/fastfetch/src/logo/ascii/
11
12// Embedded distro logos (PNG)
13// Place real logos in assets/logos/<distro>.png
14// Example: assets/logos/arch.png, assets/logos/fedora.png, assets/logos/tux.png
15
16/// Returns the raw PNG bytes for an embedded distro logo.
17///
18/// If the distro is not recognized, it falls back to the Tux (Linux) logo.
19/// Only available when the `graphics` feature is enabled.
20#[cfg(feature = "graphics")]
21pub fn get_embedded_logo(distro: Option<&str>) -> Option<&'static [u8]> {
22    let d = distro.map(|s| s.to_lowercase());
23    match d.as_deref() {
24        Some("arch") => Some(include_bytes!("../assets/logos/arch.png")),
25        Some("debian") => Some(include_bytes!("../assets/logos/debian.png")),
26        Some("fedora") => Some(include_bytes!("../assets/logos/fedora.png")),
27        Some("nixos") => Some(include_bytes!("../assets/logos/nixos.png")),
28        Some("ubuntu") => Some(include_bytes!("../assets/logos/ubuntu.png")),
29        Some("pop") => Some(include_bytes!("../assets/logos/pop.png")),
30        Some("manjaro") => Some(include_bytes!("../assets/logos/manjaro.png")),
31        Some("endeavouros") => Some(include_bytes!("../assets/logos/endeavouros.png")),
32        Some("opensuse") | Some("opensuse-leap") | Some("opensuse-tumbleweed") => {
33            Some(include_bytes!("../assets/logos/opensuse.png"))
34        }
35        Some("mx") => Some(include_bytes!("../assets/logos/mx.png")),
36        Some("linuxmint") => Some(include_bytes!("../assets/logos/linuxmint.png")),
37        Some("kali") => Some(include_bytes!("../assets/logos/kali.png")),
38        Some("zorin") => Some(include_bytes!("../assets/logos/zorin.png")),
39        Some("garuda") => Some(include_bytes!("../assets/logos/garuda.png")),
40        Some("macos") => Some(include_bytes!("../assets/logos/macos.png")),
41        Some("windows") => Some(include_bytes!("../assets/logos/windows.png")),
42        _ => Some(include_bytes!("../assets/logos/tux.png")),
43    }
44}
45
46/// Fallback for non-graphics build to provide Tux bytes for Chafa if needed.
47#[cfg(not(feature = "graphics"))]
48pub fn get_embedded_logo(_distro: Option<&str>) -> Option<&'static [u8]> {
49    Some(include_bytes!("../assets/logos/tux.png"))
50}
51
52/// Attempts to detect the current operating system distribution.
53pub fn detect_distro() -> Option<String> {
54    #[cfg(target_os = "macos")]
55    {
56        Some("macos".to_string())
57    }
58    #[cfg(target_os = "windows")]
59    {
60        Some("windows".to_string())
61    }
62    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
63    {
64        if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
65            for line in content.lines() {
66                if line.starts_with("ID=") {
67                    let id = line.trim_start_matches("ID=").trim_matches('"');
68                    return Some(id.to_string());
69                }
70            }
71        }
72        None
73    }
74}
75
76///// Returns a list of strings representing the ASCII art for a given distro with color placeholders.
77///
78/// All ASCII logos are sourced from or compatible with Fastfetch.
79pub fn get_ascii_logo(distro: Option<&str>) -> Vec<String> {
80    let d = distro.map(|s| s.to_lowercase());
81
82    match d.as_deref() {
83        Some("arch") => {
84            let logo = include_str!("../assets/logos/arch.txt");
85            logo.lines().map(|s| s.to_string()).collect()
86        }
87        Some("debian") => {
88            let logo = include_str!("../assets/logos/debian.txt");
89            logo.lines().map(|s| s.to_string()).collect()
90        }
91        Some("fedora") => {
92            let logo = include_str!("../assets/logos/fedora.txt");
93            logo.lines().map(|s| s.to_string()).collect()
94        }
95        Some("nixos") => {
96            let logo = include_str!("../assets/logos/nixos.txt");
97            logo.lines().map(|s| s.to_string()).collect()
98        }
99        Some("ubuntu") => {
100            let logo = include_str!("../assets/logos/ubuntu.txt");
101            logo.lines().map(|s| s.to_string()).collect()
102        }
103        Some("pop") => {
104            let logo = include_str!("../assets/logos/pop.txt");
105            logo.lines().map(|s| s.to_string()).collect()
106        }
107        Some("manjaro") => {
108            let logo = include_str!("../assets/logos/manjaro.txt");
109            logo.lines().map(|s| s.to_string()).collect()
110        }
111        Some("endeavouros") => {
112            let logo = include_str!("../assets/logos/endeavouros.txt");
113            logo.lines().map(|s| s.to_string()).collect()
114        }
115        Some("opensuse") | Some("opensuse-leap") | Some("opensuse-tumbleweed") => {
116            let logo = include_str!("../assets/logos/opensuse.txt");
117            logo.lines().map(|s| s.to_string()).collect()
118        }
119        Some("mx") => {
120            let logo = include_str!("../assets/logos/mx.txt");
121            logo.lines().map(|s| s.to_string()).collect()
122        }
123        Some("linuxmint") => {
124            let logo = include_str!("../assets/logos/linuxmint.txt");
125            logo.lines().map(|s| s.to_string()).collect()
126        }
127        Some("kali") => {
128            let logo = include_str!("../assets/logos/kali.txt");
129            logo.lines().map(|s| s.to_string()).collect()
130        }
131        Some("zorin") => {
132            let logo = include_str!("../assets/logos/zorin.txt");
133            logo.lines().map(|s| s.to_string()).collect()
134        }
135        Some("garuda") => {
136            let logo = include_str!("../assets/logos/garuda.txt");
137            logo.lines().map(|s| s.to_string()).collect()
138        }
139        Some("macos") => {
140            let logo = include_str!("../assets/logos/macos.txt");
141            logo.lines().map(|s| s.to_string()).collect()
142        }
143        Some("windows") => {
144            let logo = include_str!("../assets/logos/windows.txt");
145            logo.lines().map(|s| s.to_string()).collect()
146        }
147
148        // Fallback: Tux (Linux)
149        _ => {
150            let logo = include_str!("../assets/logos/tux.txt");
151            logo.lines().map(|s| s.to_string()).collect()
152        }
153    }
154}
155
156/// Returns dynamic ANSI color arrays for a given distribution.
157pub fn get_distro_colors(distro: Option<&str>) -> Vec<&'static str> {
158    let d = distro.map(|s| s.to_lowercase());
159    match d.as_deref() {
160        Some("arch") => vec!["\x1b[36m", "\x1b[37m"],
161        Some("debian") => vec!["\x1b[31m", "\x1b[37m"],
162        Some("fedora") => vec!["\x1b[34m", "\x1b[37m"],
163        Some("nixos") => vec![
164            "\x1b[34m", "\x1b[36m", "\x1b[34m", "\x1b[36m", "\x1b[34m", "\x1b[36m",
165        ],
166        Some("ubuntu") => vec!["\x1b[33m", "\x1b[31m"],
167        Some("pop") => vec!["\x1b[36m", "\x1b[37m"],
168        Some("manjaro") => vec!["\x1b[32m"],
169        Some("endeavouros") => vec!["\x1b[35m", "\x1b[31m", "\x1b[34m"],
170        Some("opensuse") | Some("opensuse-leap") | Some("opensuse-tumbleweed") => {
171            vec!["\x1b[32m", "\x1b[37m"]
172        }
173        Some("mx") => vec!["\x1b[34m", "\x1b[37m"],
174        Some("linuxmint") => vec!["\x1b[32m", "\x1b[37m"],
175        Some("kali") => vec!["\x1b[34m", "\x1b[37m"],
176        Some("zorin") => vec!["\x1b[36m", "\x1b[37m"],
177        Some("garuda") => vec!["\x1b[35m", "\x1b[36m"],
178        Some("macos") => vec!["\x1b[32m", "\x1b[33m", "\x1b[31m", "\x1b[35m", "\x1b[34m"],
179        Some("windows") => vec!["\x1b[36m"],
180        _ => vec!["\x1b[30m", "\x1b[37m", "\x1b[33m"], // Tux
181    }
182}
183
184/// Interpolates placeholders `${1}`...`${9}` or `$1`...`$9` with dynamic ANSI colors and appends a reset at the end.
185pub fn get_distro_logo_lines(distro: Option<&str>) -> Vec<String> {
186    let raw_lines = get_ascii_logo(distro);
187    let colors = get_distro_colors(distro);
188    let default_color = colors.first().copied().unwrap_or("\x1b[0m");
189
190    raw_lines
191        .into_iter()
192        .map(|line| {
193            let mut formatted = line;
194            for i in 1..=9 {
195                let color_val = colors.get(i - 1).copied().unwrap_or("\x1b[0m");
196                let placeholder = format!("${{{}}}", i);
197                formatted = formatted.replace(&placeholder, color_val);
198                let placeholder_short = format!("${}", i);
199                formatted = formatted.replace(&placeholder_short, color_val);
200            }
201            if !formatted.is_empty() {
202                format!("{}{}\x1b[0m", default_color, formatted)
203            } else {
204                formatted
205            }
206        })
207        .collect()
208}
209
210/// Checks if the terminal supports the Kitty inline image protocol.
211pub fn supports_kitty() -> bool {
212    std::env::var("TERM")
213        .map(|t| t == "xterm-kitty")
214        .unwrap_or(false)
215        || std::env::var("TERMINAL_EMULATOR")
216            .map(|t| t == "iterm-kitty" || t == "iTerm.app")
217            .unwrap_or(false)
218        || std::env::var("TERM_PROGRAM")
219            .map(|t| t == "rio")
220            .unwrap_or(false)
221}
222
223/// Checks if the terminal supports the iTerm2 inline image protocol.
224pub fn supports_iterm2() -> bool {
225    if let Ok(prog) = std::env::var("TERM_PROGRAM") {
226        if prog == "iTerm.app" || prog == "WezTerm" || prog == "rio" {
227            return true;
228        }
229    }
230    false
231}
232
233/// Checks if the terminal supports Sixel graphics (heuristic based on environment).
234pub fn supports_sixel() -> bool {
235    if let Ok(term) = std::env::var("TERM") {
236        let term = term.to_lowercase();
237        if term.contains("sixel") || term.contains("foot") || term.contains("mlterm") {
238            return true;
239        }
240    }
241
242    if let Ok(prog) = std::env::var("TERM_PROGRAM") {
243        if prog == "WezTerm" || prog == "iTerm.app" || prog == "rio" {
244            return true;
245        }
246    }
247
248    if std::env::var("WT_SESSION").is_ok() {
249        return true;
250    }
251
252    false
253}
254
255static CHAFA_SUPPORTS_PROBE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
256
257/// Checks if the `chafa` command-line tool supports the `--probe` option.
258pub fn chafa_supports_probe() -> bool {
259    *CHAFA_SUPPORTS_PROBE.get_or_init(|| {
260        std::process::Command::new("chafa")
261            .args(["--probe", "off", "--version"])
262            .output()
263            .map(|o| o.status.success())
264            .unwrap_or(false)
265    })
266}
267
268/// Checks if the `chafa` command-line tool is available in the system path.
269pub fn chafa_available() -> bool {
270    std::process::Command::new("chafa")
271        .arg("--version")
272        .output()
273        .map(|o| o.status.success())
274        .unwrap_or(false)
275}
276
277/// Write embedded logo bytes to a temporary file and return the path.
278fn write_temp_logo(bytes: &[u8]) -> std::io::Result<std::path::PathBuf> {
279    let temp_path = std::env::temp_dir().join(format!("retch_logo_{}.png", std::process::id()));
280    std::fs::write(&temp_path, bytes)?;
281    Ok(temp_path)
282}
283
284/// Attempts to render an image using the `chafa` utility.
285///
286/// Chafa renders images using high-quality Unicode symbols, providing a
287/// good graphical fallback for many terminal emulators.
288pub fn print_with_chafa(path: &std::path::Path) -> bool {
289    let mut cmd = std::process::Command::new("chafa");
290    cmd.arg("--format")
291        .arg("symbols")
292        .arg("--size")
293        .arg("40x20");
294
295    if chafa_supports_probe() {
296        cmd.arg("--probe").arg("off");
297    }
298
299    let output = cmd.arg(path).output();
300
301    match output {
302        Ok(out) if out.status.success() => {
303            print!("{}", String::from_utf8_lossy(&out.stdout));
304            true
305        }
306        Ok(out) => {
307            eprintln!("warning: chafa failed with status: {}", out.status);
308            false
309        }
310        Err(e) => {
311            eprintln!("warning: failed to execute chafa: {}", e);
312            false
313        }
314    }
315}
316
317/// Attempts to get Chafa output as a list of lines.
318pub fn get_chafa_logo_lines(path: &std::path::Path) -> Option<Vec<String>> {
319    let mut cmd = std::process::Command::new("chafa");
320    cmd.arg("--format")
321        .arg("symbols")
322        .arg("--size")
323        .arg("40x20");
324
325    if chafa_supports_probe() {
326        cmd.arg("--probe").arg("off");
327    }
328
329    let output = cmd.arg(path).output().ok()?;
330    if output.status.success() {
331        let content = String::from_utf8_lossy(&output.stdout);
332        Some(content.lines().map(|s| s.to_string()).collect())
333    } else {
334        None
335    }
336}
337
338/// Print logo for a distro following the strict priority:
339/// 1. Real graphic logo (if terminal supports it and embedded logo exists)
340/// 2. Chafa high-quality symbols (if chafa is available)
341/// 3. Real Fastfetch ASCII logo (always available)
342pub fn print_distro_logo(distro: Option<&str>) {
343    print_distro_logo_with_ascii(distro, false, false);
344}
345
346/// Renders the distribution logo with options to force ASCII or Chafa mode.
347///
348/// This is the primary entry point for logo rendering, handling the entire
349/// priority chain from high-res graphics down to text-based ASCII.
350/// - `ascii_only`: skip all graphical protocols and render the ASCII art directly.
351/// - `chafa_only`: skip Kitty/iTerm2/Sixel and go straight to Chafa (falls back
352///   to ASCII if Chafa is unavailable). `ascii_only` takes precedence.
353pub fn print_distro_logo_with_ascii(distro: Option<&str>, ascii_only: bool, chafa_only: bool) {
354    if ascii_only {
355        // Force ASCII path
356        let art = get_distro_logo_lines(distro);
357        for line in art {
358            println!("{}", line);
359        }
360        return;
361    }
362
363    let has_chafa = chafa_available();
364
365    if !chafa_only {
366        let supports_kitty = supports_kitty();
367        let supports_iterm2 = supports_iterm2();
368        let supports_sixel = supports_sixel();
369
370        // 1. Try embedded graphical logo (Kitty)
371        #[cfg(feature = "graphics")]
372        if supports_kitty {
373            if let Some(bytes) = get_embedded_logo(distro) {
374                if !bytes.is_empty() {
375                    print_graphical_logo(bytes);
376                    return;
377                }
378            }
379        }
380
381        // 2. Try embedded graphical logo (iTerm2)
382        #[cfg(feature = "graphics")]
383        if supports_iterm2 {
384            if let Some(bytes) = get_embedded_logo(distro) {
385                if !bytes.is_empty() {
386                    print_iterm2_logo(bytes);
387                    return;
388                }
389            }
390        }
391
392        // 3. Try embedded graphical logo (Sixel)
393        #[cfg(feature = "graphics")]
394        if supports_sixel {
395            if let Some(bytes) = get_embedded_logo(distro) {
396                if !bytes.is_empty() {
397                    print_sixel_logo(bytes);
398                    return;
399                }
400            }
401        }
402    }
403
404    // 4. Try chafa using embedded distro logo
405    if has_chafa {
406        if let Some(bytes) = get_embedded_logo(distro) {
407            if bytes.len() > 100 {
408                if let Ok(temp_path) = write_temp_logo(bytes) {
409                    if print_with_chafa(&temp_path) {
410                        let _ = std::fs::remove_file(&temp_path);
411                        return;
412                    }
413                    let _ = std::fs::remove_file(&temp_path);
414                }
415            }
416        }
417    }
418
419    // 5. Final fallback: Real Fastfetch ASCII logo
420    let art = get_distro_logo_lines(distro);
421    for line in art {
422        println!("{}", line);
423    }
424}
425
426/// Renders a raw image buffer using the iTerm2 inline image protocol.
427#[cfg(feature = "graphics")]
428pub fn print_iterm2_logo(image_data: &[u8]) {
429    use base64::Engine;
430    let encoded = base64::engine::general_purpose::STANDARD.encode(image_data);
431    print!(
432        "\x1b]1337;File=inline=1;preserveAspectRatio=1:{}\x07",
433        encoded
434    );
435    println!(); // iTerm2 typically needs a newline after the logo
436}
437
438/// Loads an image from a file and prints it using the iTerm2 protocol.
439#[cfg(feature = "graphics")]
440pub fn print_iterm2_logo_from_path(path: &std::path::Path) {
441    if let Ok(bytes) = std::fs::read(path) {
442        print_iterm2_logo(&bytes);
443    } else {
444        println!("[Could not read logo for iTerm2 from {}]", path.display());
445    }
446}
447
448/// Placeholder for iTerm2 logo rendering when the `graphics` feature is disabled.
449#[cfg(not(feature = "graphics"))]
450pub fn print_iterm2_logo(_image_data: &[u8]) {
451    println!("[iTerm2 logo support requires --features graphics]");
452}
453
454/// Renders a raw image buffer using the Kitty graphics protocol.
455#[cfg(feature = "graphics")]
456pub fn print_graphical_logo(image_data: &[u8]) {
457    use base64::Engine;
458
459    let (width, height) = image::load_from_memory(image_data)
460        .map(|img| (img.width(), img.height()))
461        .unwrap_or((0, 0));
462
463    let encoded = base64::engine::general_purpose::STANDARD.encode(image_data);
464
465    if width > 0 && height > 0 {
466        println!("\x1b_Gf=100,s={},v={},a=T;{}\x1b\\", width, height, encoded);
467    } else {
468        println!("\x1b_Gf=100,a=T;{}", encoded);
469    }
470}
471
472/// Renders a raw image buffer (e.g. PNG bytes) using the Sixel graphics protocol.
473#[cfg(feature = "graphics")]
474pub fn print_sixel_logo(image_data: &[u8]) {
475    if let Ok(img) = image::load_from_memory(image_data) {
476        let rgba = img.to_rgba8();
477        let (width, height) = rgba.dimensions();
478        print_sixel_rgba(rgba.as_raw(), width, height);
479    }
480}
481
482/// Renders raw RGBA pixels using the Sixel graphics protocol.
483#[cfg(feature = "graphics")]
484pub fn print_sixel_rgba(rgba: &[u8], width: u32, height: u32) {
485    use icy_sixel::SixelImage;
486
487    match SixelImage::try_from_rgba(rgba.to_vec(), width as usize, height as usize) {
488        Ok(sixel_img) => match sixel_img.encode() {
489            Ok(sixel_str) => {
490                print!("{}", sixel_str);
491            }
492            Err(e) => eprintln!("[Sixel Encoding Error: {}]", e),
493        },
494        Err(e) => eprintln!("[Sixel Creation Error: {}]", e),
495    }
496}
497
498/// Placeholder for graphical logo rendering when the `graphics` feature is disabled.
499#[cfg(not(feature = "graphics"))]
500pub fn print_graphical_logo(_image_data: &[u8]) {
501    println!("[Graphical logo support requires --features graphics]");
502}
503
504/// Placeholder for sixel logo rendering when the `graphics` feature is disabled.
505#[cfg(not(feature = "graphics"))]
506pub fn print_sixel_logo(_image_data: &[u8]) {
507    println!("[Sixel logo support requires --features graphics]");
508}
509
510/// Loads an image from a file, resizes it, and prints it using the graphics protocol.
511#[cfg(feature = "graphics")]
512pub fn print_graphical_logo_from_path(path: &std::path::Path) {
513    use image::ImageFormat;
514    match image::open(path) {
515        Ok(img) => {
516            let resized = img.resize(128, 128, image::imageops::FilterType::Lanczos3);
517            let mut png_data = Vec::new();
518            if resized
519                .write_to(&mut std::io::Cursor::new(&mut png_data), ImageFormat::Png)
520                .is_ok()
521            {
522                print_graphical_logo(&png_data);
523            } else {
524                println!("[Failed to encode logo as PNG]");
525            }
526        }
527        Err(_) => {
528            println!("[Could not load graphical logo from {}]", path.display());
529        }
530    }
531}
532
533/// Loads an image from a file, resizes it, and prints it using the Sixel protocol.
534#[cfg(feature = "graphics")]
535pub fn print_sixel_logo_from_path(path: &std::path::Path) {
536    match image::open(path) {
537        Ok(img) => {
538            let resized = img.resize(128, 128, image::imageops::FilterType::Lanczos3);
539            let rgba = resized.to_rgba8();
540            let (width, height) = rgba.dimensions();
541            print_sixel_rgba(rgba.as_raw(), width, height);
542        }
543        Err(_) => {
544            println!("[Could not load logo for Sixel from {}]", path.display());
545        }
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    #[test]
554    fn test_get_ascii_logo_arch() {
555        let logo = get_ascii_logo(Some("arch"));
556        assert!(!logo.is_empty());
557        assert!(logo[0].contains("`"));
558    }
559
560    #[test]
561    fn test_get_ascii_logo_unknown() {
562        let logo = get_ascii_logo(Some("unknown_distro"));
563        assert!(!logo.is_empty());
564        // Should fall back to Tux
565        assert!(logo
566            .iter()
567            .any(|line| line.contains("o${2}_${3}o") || line.contains("o_o")));
568    }
569
570    #[test]
571    fn test_get_ascii_logo_none() {
572        let logo = get_ascii_logo(None);
573        assert!(!logo.is_empty());
574    }
575
576    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
577
578    struct EnvGuard {
579        _mutex_guard: std::sync::MutexGuard<'static, ()>,
580        old_vars: std::collections::HashMap<&'static str, Option<String>>,
581    }
582
583    impl EnvGuard {
584        fn new(vars_to_mock: &[&'static str]) -> Self {
585            let guard = ENV_LOCK.lock().unwrap();
586            let mut old_vars = std::collections::HashMap::new();
587            for var in vars_to_mock {
588                old_vars.insert(*var, std::env::var(var).ok());
589            }
590            EnvGuard {
591                _mutex_guard: guard,
592                old_vars,
593            }
594        }
595    }
596
597    impl Drop for EnvGuard {
598        fn drop(&mut self) {
599            for (var, value) in &self.old_vars {
600                if let Some(val) = value {
601                    std::env::set_var(var, val);
602                } else {
603                    std::env::remove_var(var);
604                }
605            }
606        }
607    }
608
609    #[test]
610    fn test_supports_kitty_heuristics() {
611        let _guard = EnvGuard::new(&["TERM", "TERMINAL_EMULATOR", "TERM_PROGRAM"]);
612
613        // Test TERM=xterm-kitty
614        std::env::set_var("TERM", "xterm-kitty");
615        std::env::remove_var("TERMINAL_EMULATOR");
616        std::env::remove_var("TERM_PROGRAM");
617        assert!(supports_kitty());
618
619        // Test TERMINAL_EMULATOR=iterm-kitty
620        std::env::remove_var("TERM");
621        std::env::set_var("TERMINAL_EMULATOR", "iterm-kitty");
622        assert!(supports_kitty());
623
624        // Test TERMINAL_EMULATOR=iTerm.app
625        std::env::set_var("TERMINAL_EMULATOR", "iTerm.app");
626        assert!(supports_kitty());
627
628        // Test TERM_PROGRAM=rio
629        std::env::remove_var("TERMINAL_EMULATOR");
630        std::env::set_var("TERM_PROGRAM", "rio");
631        assert!(supports_kitty());
632
633        // Test clear env -> false
634        std::env::remove_var("TERM_PROGRAM");
635        assert!(!supports_kitty());
636    }
637
638    #[test]
639    fn test_supports_iterm2_heuristics() {
640        let _guard = EnvGuard::new(&["TERM_PROGRAM"]);
641
642        // Test TERM_PROGRAM=iTerm.app
643        std::env::set_var("TERM_PROGRAM", "iTerm.app");
644        assert!(supports_iterm2());
645
646        // Test TERM_PROGRAM=WezTerm
647        std::env::set_var("TERM_PROGRAM", "WezTerm");
648        assert!(supports_iterm2());
649
650        // Test TERM_PROGRAM=rio
651        std::env::set_var("TERM_PROGRAM", "rio");
652        assert!(supports_iterm2());
653
654        // Test TERM_PROGRAM=Apple_Terminal
655        std::env::set_var("TERM_PROGRAM", "Apple_Terminal");
656        assert!(!supports_iterm2());
657
658        // Test clear env -> false
659        std::env::remove_var("TERM_PROGRAM");
660        assert!(!supports_iterm2());
661    }
662
663    #[test]
664    fn test_supports_sixel_heuristics() {
665        let _guard = EnvGuard::new(&["TERM", "TERM_PROGRAM", "WT_SESSION"]);
666
667        // Clear all to start fresh
668        std::env::remove_var("TERM");
669        std::env::remove_var("TERM_PROGRAM");
670        std::env::remove_var("WT_SESSION");
671        assert!(!supports_sixel());
672
673        // Test TERM=xterm-sixel
674        std::env::set_var("TERM", "xterm-sixel");
675        assert!(supports_sixel());
676
677        // Test TERM=foot
678        std::env::set_var("TERM", "foot");
679        assert!(supports_sixel());
680
681        // Test TERM=mlterm (case variations)
682        std::env::set_var("TERM", "MLTerm");
683        assert!(supports_sixel());
684
685        // Reset TERM, test TERM_PROGRAM=WezTerm
686        std::env::remove_var("TERM");
687        std::env::set_var("TERM_PROGRAM", "WezTerm");
688        assert!(supports_sixel());
689
690        // Test TERM_PROGRAM=iTerm.app
691        std::env::set_var("TERM_PROGRAM", "iTerm.app");
692        assert!(supports_sixel());
693
694        // Test TERM_PROGRAM=rio
695        std::env::set_var("TERM_PROGRAM", "rio");
696        assert!(supports_sixel());
697
698        // Reset TERM_PROGRAM, test WT_SESSION
699        std::env::remove_var("TERM_PROGRAM");
700        std::env::set_var("WT_SESSION", "active");
701        assert!(supports_sixel());
702    }
703
704    #[test]
705    fn test_get_embedded_logo() {
706        let logo = get_embedded_logo(Some("arch"));
707        assert!(logo.is_some());
708        let logo = get_embedded_logo(Some("pop"));
709        assert!(logo.is_some());
710        let logo = get_embedded_logo(Some("manjaro"));
711        assert!(logo.is_some());
712        let logo = get_embedded_logo(Some("endeavouros"));
713        assert!(logo.is_some());
714        let logo = get_embedded_logo(Some("opensuse"));
715        assert!(logo.is_some());
716        let logo = get_embedded_logo(Some("opensuse-leap"));
717        assert!(logo.is_some());
718        let logo = get_embedded_logo(Some("opensuse-tumbleweed"));
719        assert!(logo.is_some());
720        let logo = get_embedded_logo(Some("mx"));
721        assert!(logo.is_some());
722        let logo = get_embedded_logo(Some("linuxmint"));
723        assert!(logo.is_some());
724        let logo = get_embedded_logo(Some("kali"));
725        assert!(logo.is_some());
726        let logo = get_embedded_logo(Some("zorin"));
727        assert!(logo.is_some());
728        let logo = get_embedded_logo(Some("garuda"));
729        assert!(logo.is_some());
730        let logo = get_embedded_logo(Some("macos"));
731        assert!(logo.is_some());
732        let logo = get_embedded_logo(Some("windows"));
733        assert!(logo.is_some());
734        let logo = get_embedded_logo(None);
735        assert!(logo.is_some());
736    }
737
738    #[test]
739    fn test_get_ascii_logo_new_distros() {
740        let pop = get_ascii_logo(Some("pop"));
741        assert!(!pop.is_empty());
742        assert!(pop.iter().any(|line| line.contains("767")));
743
744        let manjaro = get_ascii_logo(Some("manjaro"));
745        assert!(!manjaro.is_empty());
746        assert!(manjaro.iter().any(|line| line.contains("████████")));
747
748        let endeavouros = get_ascii_logo(Some("endeavouros"));
749        assert!(!endeavouros.is_empty());
750        assert!(endeavouros.iter().any(|line| line.contains("ssso")));
751
752        let opensuse = get_ascii_logo(Some("opensuse"));
753        assert!(!opensuse.is_empty());
754        assert!(opensuse.iter().any(|line| line.contains("O0000Ok")));
755
756        let macos = get_ascii_logo(Some("macos"));
757        assert!(!macos.is_empty());
758        assert!(macos
759            .iter()
760            .any(|line| line.contains("cKMMMMMMMMMMNWMMMMMMMMMM0")));
761
762        let windows = get_ascii_logo(Some("windows"));
763        assert!(!windows.is_empty());
764        assert!(windows
765            .iter()
766            .any(|line| line.contains("AEEEtttt::::ztF") || line.contains("tt:::tt333EE3")));
767
768        let mx = get_ascii_logo(Some("mx"));
769        assert!(!mx.is_empty());
770        assert!(mx
771            .iter()
772            .any(|line| line.contains("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMM")));
773
774        let linuxmint = get_ascii_logo(Some("linuxmint"));
775        assert!(!linuxmint.is_empty());
776        assert!(linuxmint.iter().any(|line| line.contains("oOOOOOOOOOOo")));
777
778        let kali = get_ascii_logo(Some("kali"));
779        assert!(!kali.is_empty());
780        assert!(kali.iter().any(|line| line.contains(":ccc")));
781
782        let zorin = get_ascii_logo(Some("zorin"));
783        assert!(!zorin.is_empty());
784        assert!(zorin
785            .iter()
786            .any(|line| line.contains("osssssssssssssssssssso")));
787
788        let garuda = get_ascii_logo(Some("garuda"));
789        assert!(!garuda.is_empty());
790        assert!(garuda.iter().any(|line| line.contains("888:8898898")));
791    }
792}