#![allow(clippy::collapsible_if, clippy::useless_vec)]
use image::{ImageFormat, ImageReader};
use std::{
collections::HashMap,
env, fs,
io::{Cursor, Write},
path::Path,
};
use super::{ascii::get_builtin_ascii_art, colors::get_builtin_distro_colors};
pub const DEFAULT_ANSI_ALL_COLORS: [&str; 16] = [
"\x1b[1;30m", "\x1b[1;31m", "\x1b[1;32m", "\x1b[1;33m", "\x1b[1;34m", "\x1b[1;35m", "\x1b[1;36m", "\x1b[1;37m", "\x1b[1;90m", "\x1b[1;91m", "\x1b[1;92m", "\x1b[1;93m", "\x1b[1;94m", "\x1b[1;95m", "\x1b[1;96m", "\x1b[1;97m", ];
pub fn get_bar(percent: u8) -> String {
let total_blocks = 14;
let filled_blocks = (percent as usize * total_blocks) / 100;
let empty_blocks = total_blocks - filled_blocks;
const BLOCKS: &[&str] = &[
"",
"█",
"██",
"███",
"████",
"█████",
"██████",
"███████",
"████████",
"█████████",
"██████████",
"███████████",
"████████████",
"█████████████",
"██████████████",
];
const EMPTY_BLOCKS: &[&str] = &[
"",
"░",
"░░",
"░░░",
"░░░░",
"░░░░░",
"░░░░░░",
"░░░░░░░",
"░░░░░░░░",
"░░░░░░░░░",
"░░░░░░░░░░",
"░░░░░░░░░░░",
"░░░░░░░░░░░░",
"░░░░░░░░░░░░░",
"░░░░░░░░░░░░░░",
];
let filled = BLOCKS[filled_blocks.min(14)];
let empty = EMPTY_BLOCKS[empty_blocks.min(14)];
format!("[{}{}]", filled, empty)
}
pub fn get_terminal_color(color_blocks: &str) -> String {
let color_codes: [u8; 8] = [30, 31, 32, 33, 34, 35, 36, 37];
let mut normal = Vec::with_capacity(8);
for &code in &color_codes {
normal.push(format!("\x1b[{}m{}\x1b[0m", code, color_blocks)); }
normal.join("")
}
pub fn get_custom_ascii(custom_path: &str) -> String {
if let Ok(content) = fs::read_to_string(Path::new(custom_path)) {
return content;
}
"".to_string()
}
pub fn is_image_path(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| matches!(ext.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg"))
.unwrap_or(false)
}
pub fn terminal_supports_inline_images() -> bool {
matches!(env::var("TERM"), Ok(term) if term == "xterm-kitty")
|| env::var_os("KITTY_WINDOW_ID").is_some()
}
pub fn render_inline_image(path: &str, columns: usize) -> Result<(), String> {
let reader = ImageReader::open(path)
.map_err(|err| format!("Failed to open image {path}: {err}"))?
.with_guessed_format()
.map_err(|err| format!("Failed to detect image format for {path}: {err}"))?;
let image = reader
.decode()
.map_err(|err| format!("Failed to decode image {path}: {err}"))?;
let mut png_bytes = Cursor::new(Vec::new());
image
.write_to(&mut png_bytes, ImageFormat::Png)
.map_err(|err| format!("Failed to encode image {path} as PNG: {err}"))?;
let encoded = base64_encode(png_bytes.get_ref());
let mut stdout = std::io::stdout();
if columns > 0 {
write!(
&mut stdout,
"\x1b_Ga=T,C=1,f=100,c={columns};{encoded}\x1b\\"
)
} else {
write!(&mut stdout, "\x1b_Ga=T,C=1,f=100;{encoded}\x1b\\")
}
.map_err(|err| format!("Failed to write inline image escape sequence: {err}"))?;
stdout
.flush()
.map_err(|err| format!("Failed to flush inline image: {err}"))?;
Ok(())
}
fn base64_encode(data: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut chunks = data.chunks_exact(3);
for chunk in &mut chunks {
let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push(TABLE[(n & 0x3f) as usize] as char);
}
match chunks.remainder() {
[b0] => {
let n = (*b0 as u32) << 16;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push('=');
out.push('=');
}
[b0, b1] => {
let n = ((*b0 as u32) << 16) | ((*b1 as u32) << 8);
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push('=');
}
_ => {}
}
out
}
pub fn get_ascii_and_colors(ascii_distro: &str) -> String {
if ascii_distro == "off" {
return "".to_string();
}
let ascii_art = resolve_ascii_art(ascii_distro);
ascii_art.to_string()
}
fn resolve_ascii_art(distro: &str) -> &'static str {
if let Some(art) = get_builtin_ascii_art(distro) {
return art;
}
#[cfg(target_os = "linux")]
if let Some(parent) = crate::modules::linux::system::distro::get_id_like() {
if let Some(art) = get_builtin_ascii_art(&parent) {
return art;
}
}
DEFAULT_ASCII
}
const DEFAULT_ASCII: &str = r#"${c2} #####
${c2} #######
${c2} ##${c1}O${c2}#${c1}O${c2}##
${c2} #${c3}#####${c2}#
${c2} ##${c1}##${c3}###${c1}##${c2}##
${c2} #${c1}##########${c2}##
${c2} #${c1}############${c2}##
${c2} #${c1}############${c2}###
${c3} ##${c2}#${c1}###########${c2}##${c3}#
${c3}######${c2}#${c1}#######${c2}#${c3}######
${c3}#######${c2}#${c1}#####${c2}#${c3}#######
${c3} #####${c2}#######${c3}#####"#;
pub fn colorize_text(input: String, colors: &HashMap<&str, &str>) -> String {
let mut result = String::new();
for line in input.lines() {
let mut colored = line.to_owned();
for (key, code) in colors {
let placeholder = format!("${{{}}}", key);
colored = colored.replace(&placeholder, code);
}
result.push_str(&colored);
result.push('\n');
}
result
}
pub fn color_palette(
entries: &[(&'static str, &'static str)],
) -> HashMap<&'static str, &'static str> {
let mut map = HashMap::new();
for (k, v) in entries {
map.insert(*k, *v);
if let Some(code) = v.strip_prefix("\x1b[0;") {
let bold_code = format!("\x1b[1;{}", code);
let bold_key = format!("bold.{}", k);
map.insert(
Box::leak(bold_key.into_boxed_str()),
Box::leak(bold_code.into_boxed_str()),
);
}
}
map.insert("reset", "\x1b[0m");
map
}
pub fn get_colors_in_order(color_order: &[u8]) -> HashMap<&'static str, &'static str> {
let mut entries: Vec<(&'static str, &'static str)> = vec![("c0", "\x1b[1;30m")];
let mut used = vec![false; 16];
for (i, &idx) in color_order.iter().enumerate() {
if idx < 16 {
let key: &'static str = Box::leak(format!("c{}", i + 1).into_boxed_str());
entries.push((key, DEFAULT_ANSI_ALL_COLORS[idx as usize]));
used[idx as usize] = true;
}
}
let mut next_index = color_order.len() + 1;
for (i, &color) in DEFAULT_ANSI_ALL_COLORS.iter().enumerate() {
if !used[i] {
let key: &'static str = Box::leak(format!("c{}", next_index).into_boxed_str());
entries.push((key, color));
next_index += 1;
}
}
let mut map = color_palette(&entries);
map.insert("reset", "\x1b[0m");
map
}
pub fn get_custom_colors_order(colors_str_order: &str) -> HashMap<&'static str, &'static str> {
let custom_color_str_list: Vec<&str> = colors_str_order.split(',').map(str::trim).collect();
let all_parsed: Option<Vec<u8>> = custom_color_str_list
.iter()
.map(|s| s.parse::<u8>().ok())
.collect();
let color_list: Vec<u8> = if let Some(list) = all_parsed {
list
} else {
get_builtin_distro_colors(colors_str_order).to_vec()
};
get_colors_in_order(&color_list)
}
pub fn get_distro_colors(distro: &str) -> HashMap<&'static str, &'static str> {
let dist_color = get_builtin_distro_colors(distro);
get_colors_in_order(dist_color)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EnvLock;
#[test]
fn bar_respects_percentage_bounds() {
assert_eq!(get_bar(0), "[░░░░░░░░░░░░░░]");
assert_eq!(get_bar(100), "[██████████████]");
assert!(get_bar(50).contains('█'));
}
#[test]
fn terminal_color_emits_expected_blocks() {
let visual = get_terminal_color("■");
assert_eq!(visual.matches('■').count(), 8);
assert!(visual.contains("\x1b[31m"), "missing ANSI escape: {visual}");
}
#[test]
fn color_palette_includes_bold_and_reset() {
let map = color_palette(&[("c1", "\x1b[0;31m")]);
assert_eq!(map.get("c1"), Some(&"\x1b[0;31m"));
let bold_key = map
.keys()
.find(|k| k.starts_with("bold.c1"))
.expect("bold variant missing");
assert!(map.get(bold_key).unwrap().starts_with("\x1b[1;"));
assert_eq!(map.get("reset"), Some(&"\x1b[0m"));
}
#[test]
fn colors_in_order_fills_defaults() {
let map = get_colors_in_order(&[1, 2, 3]);
assert_eq!(map.get("c1"), Some(&DEFAULT_ANSI_ALL_COLORS[1]));
assert_eq!(map.get("c2"), Some(&DEFAULT_ANSI_ALL_COLORS[2]));
assert_eq!(map.get("c3"), Some(&DEFAULT_ANSI_ALL_COLORS[3]));
assert!(map.contains_key("c4"));
assert_eq!(map.get("reset"), Some(&"\x1b[0m"));
}
#[test]
fn image_path_detection_is_extension_based() {
assert!(is_image_path("/tmp/logo.png"));
assert!(is_image_path("/tmp/logo.JPG"));
assert!(is_image_path("/tmp/logo.jpeg"));
assert!(!is_image_path("/tmp/logo.txt"));
}
#[test]
fn kitty_detection_uses_terminal_hints() {
let env = EnvLock::acquire(&["TERM", "KITTY_WINDOW_ID"]);
env.set_var("TERM", "xterm-kitty");
env.remove_var("KITTY_WINDOW_ID");
assert!(terminal_supports_inline_images());
env.set_var("TERM", "xterm-256color");
env.set_var("KITTY_WINDOW_ID", "1");
assert!(terminal_supports_inline_images());
env.set_var("TERM", "xterm-256color");
env.remove_var("KITTY_WINDOW_ID");
assert!(!terminal_supports_inline_images());
}
}