chore: clippy & fmt

This commit is contained in:
neoarz
2026-01-07 22:35:41 -05:00
parent ef666c53e5
commit fd7da43393
16 changed files with 322 additions and 284 deletions

View File

@@ -45,8 +45,9 @@ pub fn get_battery_info() -> (String, String) {
let value = value_part.trim_matches(';').trim(); let value = value_part.trim_matches(';').trim();
is_charging = value == "Yes"; is_charging = value == "Yes";
} }
} else if line.contains("\"AvgTimeToEmpty\"") { } else if line.contains("\"AvgTimeToEmpty\"")
if let Some(equals_pos) = line.find('=') { && let Some(equals_pos) = line.find('=')
{
let value_part = &line[equals_pos + 1..].trim(); let value_part = &line[equals_pos + 1..].trim();
let value = value_part.trim_matches(';').trim(); let value = value_part.trim_matches(';').trim();
if let Ok(time) = value.parse::<i32>() { if let Ok(time) = value.parse::<i32>() {
@@ -54,10 +55,9 @@ pub fn get_battery_info() -> (String, String) {
} }
} }
} }
}
let percentage = if let Some(capacity) = current_capacity { let percentage = if let Some(capacity) = current_capacity {
if capacity >= 0 && capacity <= 100 { if (0..=100).contains(&capacity) {
capacity as u32 capacity as u32
} else { } else {
return (format!("({})", device_name), "<unknown>".to_string()); return (format!("({})", device_name), "<unknown>".to_string());
@@ -76,9 +76,12 @@ pub fn get_battery_info() -> (String, String) {
let mut result = crate::output::colors::battery_percent(percentage); let mut result = crate::output::colors::battery_percent(percentage);
if !external_connected && !is_charging { if !external_connected
if let Some(time_mins) = avg_time_to_empty { && !is_charging
if time_mins > 0 && time_mins < 0xFFFF { && let Some(time_mins) = avg_time_to_empty
&& time_mins > 0
&& time_mins < 0xFFFF
{
let hours = time_mins / 60; let hours = time_mins / 60;
let mins = time_mins % 60; let mins = time_mins % 60;
@@ -90,11 +93,8 @@ pub fn get_battery_info() -> (String, String) {
result.push_str(&format!(" ({} mins remaining)", mins)); result.push_str(&format!(" ({} mins remaining)", mins));
} }
} }
}
}
result.push_str(&format!(" [{}]", status)); result.push_str(&format!(" [{}]", status));
(format!("({})", device_name), result) (format!("({})", device_name), result)
} }

View File

@@ -12,13 +12,18 @@ pub fn get_cursor_info() -> String {
let mut outline = "White".to_string(); let mut outline = "White".to_string();
let mut size = "32".to_string(); let mut size = "32".to_string();
if let Ok(value) = Value::from_file(path) { if let Ok(value) = Value::from_file(path)
if let Some(dict) = value.as_dictionary() { && let Some(dict) = value.as_dictionary()
{
if let Some(f_dict) = dict.get("cursorFill").and_then(|v| v.as_dictionary()) { if let Some(f_dict) = dict.get("cursorFill").and_then(|v| v.as_dictionary()) {
let r = (f_dict.get("red").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; let r =
let g = (f_dict.get("green").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; (f_dict.get("red").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let b = (f_dict.get("blue").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; let g =
let a = (f_dict.get("alpha").and_then(|v| v.as_real()).unwrap_or(1.0) * 255.0 + 0.5) as u32; (f_dict.get("green").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let b =
(f_dict.get("blue").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let a =
(f_dict.get("alpha").and_then(|v| v.as_real()).unwrap_or(1.0) * 255.0 + 0.5) as u32;
let color_hex = (r << 24) | (g << 16) | (b << 8) | a; let color_hex = (r << 24) | (g << 16) | (b << 8) | a;
fill = match color_hex { fill = match color_hex {
0x000000FF => "Black".to_string(), 0x000000FF => "Black".to_string(),
@@ -32,10 +37,14 @@ pub fn get_cursor_info() -> String {
} }
if let Some(o_dict) = dict.get("cursorOutline").and_then(|v| v.as_dictionary()) { if let Some(o_dict) = dict.get("cursorOutline").and_then(|v| v.as_dictionary()) {
let r = (o_dict.get("red").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; let r =
let g = (o_dict.get("green").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; (o_dict.get("red").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let b = (o_dict.get("blue").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32; let g =
let a = (o_dict.get("alpha").and_then(|v| v.as_real()).unwrap_or(1.0) * 255.0 + 0.5) as u32; (o_dict.get("green").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let b =
(o_dict.get("blue").and_then(|v| v.as_real()).unwrap_or(0.0) * 255.0 + 0.5) as u32;
let a =
(o_dict.get("alpha").and_then(|v| v.as_real()).unwrap_or(1.0) * 255.0 + 0.5) as u32;
let color_hex = (r << 24) | (g << 16) | (b << 8) | a; let color_hex = (r << 24) | (g << 16) | (b << 8) | a;
outline = match color_hex { outline = match color_hex {
0x000000FF => "Black".to_string(), 0x000000FF => "Black".to_string(),
@@ -52,7 +61,6 @@ pub fn get_cursor_info() -> String {
size = format!("{:.0}", s_val * 32.0); size = format!("{:.0}", s_val * 32.0);
} }
} }
}
format!("Fill - {}, Outline - {} ({}px)", fill, outline, size) format!("Fill - {}, Outline - {} ({}px)", fill, outline, size)
} }

View File

@@ -18,10 +18,20 @@ pub fn get_display_info() -> String {
}; };
if display_count > 1 { if display_count > 1 {
let name = if main.name.is_empty() { "Color LCD" } else { &main.name }; let name = if main.name.is_empty() {
"Color LCD"
} else {
&main.name
};
format!( format!(
"({}) {}x{} @ {}x in {}\", {} Hz {}", "({}) {}x{} @ {}x in {}\", {} Hz {}",
name, p_width, p_height, main.scale_factor as u32, inches, main.frequency as u32, tag name,
p_width,
p_height,
main.scale_factor as u32,
inches,
main.frequency as u32,
tag
) )
} else { } else {
format!( format!(

View File

@@ -20,9 +20,7 @@ pub fn get_gpu_info() -> String {
.nth(1) .nth(1)
.unwrap_or("") .unwrap_or("")
.trim() .trim()
.replace('"', "") .replace(['"', '<', '>'], "");
.replace('<', "")
.replace('>', "");
} }
if line.contains("\"gpu-core-count\"") { if line.contains("\"gpu-core-count\"") {
cores = line.split('=').nth(1).unwrap_or("").trim().to_string(); cores = line.split('=').nth(1).unwrap_or("").trim().to_string();

View File

@@ -11,13 +11,16 @@ pub fn get_host_info() -> String {
} }
fn model_to_name(model: &str) -> Option<String> { fn model_to_name(model: &str) -> Option<String> {
let version = if model.starts_with("Mac") && !model.starts_with("MacBook") && !model.starts_with("Macmini") && !model.starts_with("MacPro") { let version = if model.starts_with("Mac")
&& !model.starts_with("MacBook")
&& !model.starts_with("Macmini")
&& !model.starts_with("MacPro")
{
Some(model.strip_prefix("Mac")?) Some(model.strip_prefix("Mac")?)
} else { } else {
None None
}; };
// Database stolen from https://github.com/fastfetch-cli/fastfetch/blob/dev/src/detection/host/host_mac.c // Database stolen from https://github.com/fastfetch-cli/fastfetch/blob/dev/src/detection/host/host_mac.c
// Macbook Pro: https://support.apple.com/en-us/HT201300 // Macbook Pro: https://support.apple.com/en-us/HT201300
// Macbook Air: https://support.apple.com/en-us/HT201862 // Macbook Air: https://support.apple.com/en-us/HT201862
@@ -26,7 +29,8 @@ fn model_to_name(model: &str) -> Option<String> {
// Mac Pro: https://support.apple.com/en-us/HT202888 // Mac Pro: https://support.apple.com/en-us/HT202888
// Mac Studio: https://support.apple.com/en-us/HT213073 // Mac Studio: https://support.apple.com/en-us/HT213073
if let Some(v) = version { if let Some(v) = version {
return Some(match v { return Some(
match v {
// MacBook Air // MacBook Air
"16,13" => "MacBook Air (15-inch, M4, 2025)", "16,13" => "MacBook Air (15-inch, M4, 2025)",
"16,12" => "MacBook Air (13-inch, M4, 2025)", "16,12" => "MacBook Air (13-inch, M4, 2025)",
@@ -65,11 +69,14 @@ fn model_to_name(model: &str) -> Option<String> {
"16,2" => "iMac (24-inch, M4, 2024)", "16,2" => "iMac (24-inch, M4, 2024)",
"15,4" | "15,5" => "iMac (24-inch, M3, 2023)", "15,4" | "15,5" => "iMac (24-inch, M3, 2023)",
_ => return None, _ => return None,
}.to_string()); }
.to_string(),
);
} }
// Older Macs with specific prefixes // Older Macs with specific prefixes
Some(match model { Some(
match model {
// MacBook Air (Intel/M1) // MacBook Air (Intel/M1)
"MacBookAir10,1" => "MacBook Air (M1, 2020)", "MacBookAir10,1" => "MacBook Air (M1, 2020)",
"MacBookAir9,1" => "MacBook Air (Retina, 13-inch, 2020)", "MacBookAir9,1" => "MacBook Air (Retina, 13-inch, 2020)",
@@ -101,5 +108,7 @@ fn model_to_name(model: &str) -> Option<String> {
"MacPro7,1" => "Mac Pro (2019)", "MacPro7,1" => "Mac Pro (2019)",
"MacPro6,1" => "Mac Pro (Late 2013)", "MacPro6,1" => "Mac Pro (Late 2013)",
_ => return None, _ => return None,
}.to_string()) }
.to_string(),
)
} }

View File

@@ -3,25 +3,21 @@ use std::process::Command;
pub fn get_ip_info() -> String { pub fn get_ip_info() -> String {
let mut interface = "en0".to_string(); let mut interface = "en0".to_string();
let route_output = Command::new("route") let route_output = Command::new("route").args(["get", "default"]).output();
.args(["get", "default"])
.output();
if let Ok(output) = route_output { if let Ok(output) = route_output {
let stdout = String::from_utf8_lossy(&output.stdout); let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() { for line in stdout.lines() {
if line.trim().starts_with("interface:") { if line.trim().starts_with("interface:")
if let Some(iface) = line.split_whitespace().nth(1) { && let Some(iface) = line.split_whitespace().nth(1)
{
interface = iface.to_string(); interface = iface.to_string();
break; break;
} }
} }
} }
}
let ifconfig_output = Command::new("ifconfig") let ifconfig_output = Command::new("ifconfig").arg(&interface).output();
.arg(&interface)
.output();
if let Ok(output) = ifconfig_output { if let Ok(output) = ifconfig_output {
let stdout = String::from_utf8_lossy(&output.stdout); let stdout = String::from_utf8_lossy(&output.stdout);
@@ -32,17 +28,17 @@ pub fn get_ip_info() -> String {
let ip = parts[1]; let ip = parts[1];
let mut ip_with_cidr = ip.to_string(); let mut ip_with_cidr = ip.to_string();
if let Some(netmask_idx) = parts.iter().position(|&x| x == "netmask") { if let Some(netmask_idx) = parts.iter().position(|&x| x == "netmask")
if netmask_idx + 1 < parts.len() { && netmask_idx + 1 < parts.len()
{
let netmask_hex = parts[netmask_idx + 1]; let netmask_hex = parts[netmask_idx + 1];
if netmask_hex.starts_with("0x") { if netmask_hex.starts_with("0x")
if let Ok(num) = u32::from_str_radix(&netmask_hex[2..], 16) { && let Ok(num) = u32::from_str_radix(&netmask_hex[2..], 16)
{
let cidr = num.count_ones(); let cidr = num.count_ones();
ip_with_cidr = format!("{}/{}", ip, cidr); ip_with_cidr = format!("{}/{}", ip, cidr);
} }
} }
}
}
return format!("({}) {}", interface, ip_with_cidr); return format!("({}) {}", interface, ip_with_cidr);
} }
@@ -52,4 +48,3 @@ pub fn get_ip_info() -> String {
"<unknown>".to_string() "<unknown>".to_string()
} }

View File

@@ -1,18 +1,17 @@
use std::env; use std::env;
pub fn get_locale_info() -> String { pub fn get_locale_info() -> String {
if let Ok(locale) = env::var("LC_ALL") { if let Ok(locale) = env::var("LC_ALL")
if !locale.is_empty() { && !locale.is_empty()
{
return locale; return locale;
} }
}
if let Ok(locale) = env::var("LANG") { if let Ok(locale) = env::var("LANG")
if !locale.is_empty() { && !locale.is_empty()
{
return locale; return locale;
} }
}
"<unknown>".to_string() "<unknown>".to_string()
} }

View File

@@ -74,6 +74,8 @@ pub fn get_memory_info() -> String {
format!( format!(
"{:.2} GiB / {:.2} GiB ({})", "{:.2} GiB / {:.2} GiB ({})",
used_gib, total_gib, crate::output::colors::percent(percentage) used_gib,
total_gib,
crate::output::colors::percent(percentage)
) )
} }

View File

@@ -3,8 +3,9 @@ use std::process::Command;
pub fn get_shell_info() -> String { pub fn get_shell_info() -> String {
let shell_path = env::var("SHELL").unwrap_or_else(|_| "unknown".to_string()); let shell_path = env::var("SHELL").unwrap_or_else(|_| "unknown".to_string());
let shell_name = shell_path.split('/').last().unwrap_or("unknown"); let shell_name = shell_path.split('/').next_back().unwrap_or("unknown");
let version = Command::new(&shell_path)
Command::new(&shell_path)
.arg("--version") .arg("--version")
.output() .output()
.map(|output| { .map(|output| {
@@ -16,7 +17,5 @@ pub fn get_shell_info() -> String {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(" ") .join(" ")
}) })
.unwrap_or_else(|_| shell_name.to_string()); .unwrap_or_else(|_| shell_name.to_string())
version
} }

View File

@@ -1,6 +1,6 @@
// https://github.com/fastfetch-cli/fastfetch/blob/dev/src/detection/disk/disk.c // https://github.com/fastfetch-cli/fastfetch/blob/dev/src/detection/disk/disk.c
use libc::{c_int, c_char}; use libc::{c_char, c_int};
use std::ffi::CStr; use std::ffi::CStr;
#[repr(C)] #[repr(C)]
@@ -79,7 +79,9 @@ pub fn get_storage_info() -> String {
let mut result = format!( let mut result = format!(
"{:.2} GiB / {:.2} GiB ({})", "{:.2} GiB / {:.2} GiB ({})",
used_gib, total_gib, crate::output::colors::percent(percentage) used_gib,
total_gib,
crate::output::colors::percent(percentage)
); );
if !filesystem.is_empty() { if !filesystem.is_empty() {
@@ -97,4 +99,3 @@ pub fn get_storage_info() -> String {
"<unknown>".to_string() "<unknown>".to_string()
} }

View File

@@ -12,8 +12,9 @@ pub fn get_swap_info() -> String {
let mut used_mb = 0.0; let mut used_mb = 0.0;
for part in stdout.split_whitespace() { for part in stdout.split_whitespace() {
if let Some(val) = part.strip_suffix('M') { if let Some(val) = part.strip_suffix('M')
if let Ok(num) = val.parse::<f64>() { && let Ok(num) = val.parse::<f64>()
{
if stdout.contains(&format!("total = {}", part)) { if stdout.contains(&format!("total = {}", part)) {
total_mb = num; total_mb = num;
} else if stdout.contains(&format!("used = {}", part)) { } else if stdout.contains(&format!("used = {}", part)) {
@@ -21,7 +22,6 @@ pub fn get_swap_info() -> String {
} }
} }
} }
}
let total_gib = total_mb / 1024.0; let total_gib = total_mb / 1024.0;
let used_gib = used_mb / 1024.0; let used_gib = used_mb / 1024.0;
@@ -33,7 +33,9 @@ pub fn get_swap_info() -> String {
return format!( return format!(
"{:.2} GiB / {:.2} GiB ({})", "{:.2} GiB / {:.2} GiB ({})",
used_gib, total_gib, crate::output::colors::percent(percentage) used_gib,
total_gib,
crate::output::colors::percent(percentage)
); );
} }

View File

@@ -26,13 +26,12 @@ pub fn get_terminal_info() -> String {
let my_pid = sysinfo::get_current_pid().unwrap_or(sysinfo::Pid::from(0)); let my_pid = sysinfo::get_current_pid().unwrap_or(sysinfo::Pid::from(0));
if let Some(process) = sys.process(my_pid) { if let Some(process) = sys.process(my_pid)
if let Some(parent_pid) = process.parent() { && let Some(parent_pid) = process.parent()
if let Some(parent_proc) = sys.process(parent_pid) { && let Some(parent_proc) = sys.process(parent_pid)
{
return parent_proc.name().to_string_lossy().replace(".app", ""); return parent_proc.name().to_string_lossy().replace(".app", "");
} }
}
}
"unknown".to_string() "unknown".to_string()
} }

View File

@@ -15,15 +15,14 @@ pub fn get_window_manager_info() -> DisplayServerResult {
if cfg!(target_os = "macos") { if cfg!(target_os = "macos") {
let plist_path = "/System/Library/CoreServices/WindowManager.app/Contents/version.plist"; let plist_path = "/System/Library/CoreServices/WindowManager.app/Contents/version.plist";
if Path::new(plist_path).exists() { if Path::new(plist_path).exists()
if let Ok(value) = Value::from_file(plist_path) { && let Ok(value) = Value::from_file(plist_path)
if let Some(dict) = value.as_dictionary() { && let Some(dict) = value.as_dictionary()
if let Some(raw_version) = dict.get("SourceVersion").and_then(|v| v.as_string()) && let Some(raw_version) = dict.get("SourceVersion").and_then(|v| v.as_string())
{ {
// Apple format: AAAABBBCCDDDDDD (Major, Minor, Patch, Build) // Apple format: AAAABBBCCDDDDDD (Major, Minor, Patch, Build)
if raw_version.len() >= 8 && raw_version.chars().all(|c| c.is_numeric()) { if raw_version.len() >= 8 && raw_version.chars().all(|c| c.is_numeric()) {
let major = let major = raw_version[..raw_version.len() - 12].trim_start_matches('0');
raw_version[..raw_version.len() - 12].trim_start_matches('0');
let minor = raw_version[raw_version.len() - 12..raw_version.len() - 9] let minor = raw_version[raw_version.len() - 12..raw_version.len() - 9]
.trim_start_matches('0'); .trim_start_matches('0');
let patch = raw_version[raw_version.len() - 9..raw_version.len() - 7] let patch = raw_version[raw_version.len() - 9..raw_version.len() - 7]
@@ -32,16 +31,12 @@ pub fn get_window_manager_info() -> DisplayServerResult {
let m = if minor.is_empty() { "0" } else { minor }; let m = if minor.is_empty() { "0" } else { minor };
let p = if patch.is_empty() { "0" } else { patch }; let p = if patch.is_empty() { "0" } else { patch };
result.wm_pretty_name = result.wm_pretty_name = format!("Quartz Compositor {}.{}.{}", major, m, p);
format!("Quartz Compositor {}.{}.{}", major, m, p);
} else { } else {
result.wm_pretty_name = format!("Quartz Compositor {}", raw_version); result.wm_pretty_name = format!("Quartz Compositor {}", raw_version);
} }
} }
} }
}
}
}
result result
} }

View File

@@ -11,8 +11,9 @@ pub fn get_wm_theme_info() -> String {
let mut accent_name = "Multicolor".to_string(); let mut accent_name = "Multicolor".to_string();
let mut appearance = "Light".to_string(); let mut appearance = "Light".to_string();
if let Ok(value) = Value::from_file(path) { if let Ok(value) = Value::from_file(path)
if let Some(dict) = value.as_dictionary() { && let Some(dict) = value.as_dictionary()
{
if let Some(accent_val) = dict if let Some(accent_val) = dict
.get("AppleAccentColor") .get("AppleAccentColor")
.and_then(|v| v.as_signed_integer()) .and_then(|v| v.as_signed_integer())
@@ -34,7 +35,6 @@ pub fn get_wm_theme_info() -> String {
appearance = style.to_string(); // Usually "Dark" appearance = style.to_string(); // Usually "Dark"
} }
} }
}
format!("{} ({})", accent_name, appearance) format!("{} ({})", accent_name, appearance)
} }

View File

@@ -1,7 +1,6 @@
// neoarz // neoarz
// neo64fetch - "jarvis, rewrite this project in rust" // neo64fetch - "jarvis, rewrite this project in rust"
use std::env;
use sysinfo::System; use sysinfo::System;
mod helpers; mod helpers;
@@ -41,7 +40,6 @@ struct Stats {
architecture: String, // appended to os architecture: String, // appended to os
} }
fn get_system_stats() -> Stats { fn get_system_stats() -> Stats {
let mut sys = System::new_all(); let mut sys = System::new_all();
sys.refresh_all(); sys.refresh_all();
@@ -82,7 +80,6 @@ fn get_system_stats() -> Stats {
} }
} }
fn print_stats(stats: &Stats, offset: usize) { fn print_stats(stats: &Stats, offset: usize) {
let mut lines = Vec::new(); let mut lines = Vec::new();
@@ -90,10 +87,15 @@ fn print_stats(stats: &Stats, offset: usize) {
lines.push(colors::title(&stats.username, &stats.hostname)); lines.push(colors::title(&stats.username, &stats.hostname));
// separator // separator
lines.push(colors::separator(stats.username.len() + stats.hostname.len() + 1)); lines.push(colors::separator(
stats.username.len() + stats.hostname.len() + 1,
));
// info // info
lines.push(colors::info("OS", &format!("{} {}", stats.os, stats.architecture))); lines.push(colors::info(
"OS",
&format!("{} {}", stats.os, stats.architecture),
));
lines.push(colors::info("Host", &stats.host)); lines.push(colors::info("Host", &stats.host));
lines.push(colors::info("Kernel", &stats.kernel)); lines.push(colors::info("Kernel", &stats.kernel));
lines.push(colors::info("Uptime", &stats.uptime)); lines.push(colors::info("Uptime", &stats.uptime));
@@ -113,7 +115,10 @@ fn print_stats(stats: &Stats, offset: usize) {
lines.push(colors::info("Swap", &stats.swap)); lines.push(colors::info("Swap", &stats.swap));
lines.push(colors::info("Disk (/)", &stats.storage)); lines.push(colors::info("Disk (/)", &stats.storage));
// lines.push(colors::info("Local IP", &stats.ip)); // lines.push(colors::info("Local IP", &stats.ip));
lines.push(colors::info(&format!("Battery {}", stats.battery.0), &stats.battery.1)); lines.push(colors::info(
&format!("Battery {}", stats.battery.0),
&stats.battery.1,
));
// lines.push(colors::info("Locale", &stats.locale)); // lines.push(colors::info("Locale", &stats.locale));
// color blocks // color blocks
@@ -127,8 +132,6 @@ fn print_stats(stats: &Stats, offset: usize) {
} }
} }
fn main() { fn main() {
let stats = get_system_stats(); let stats = get_system_stats();
let (offset, img_rows) = image::print_image_and_setup("assets/logo.png", 700); let (offset, img_rows) = image::print_image_and_setup("assets/logo.png", 700);

View File

@@ -6,9 +6,9 @@
// Images are base64-encoded and chunked copying what swiftfetch does // Images are base64-encoded and chunked copying what swiftfetch does
// Compatible terminals: Any terminals which use Kitty protocol, like Ghostty, Kitty, Wezterm // Compatible terminals: Any terminals which use Kitty protocol, like Ghostty, Kitty, Wezterm
use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use image::{GenericImageView, ImageFormat}; use image::{GenericImageView, ImageFormat};
use libc::{ioctl, winsize, STDOUT_FILENO, TIOCGWINSZ}; use libc::{STDOUT_FILENO, TIOCGWINSZ, ioctl, winsize};
use std::env; use std::env;
use std::io::{Cursor, Write}; use std::io::{Cursor, Write};
use std::mem; use std::mem;
@@ -41,8 +41,12 @@ pub fn terminal_supports_kitty() -> bool {
return true; return true;
} }
if env::var("KITTY_WINDOW_ID").is_ok() { return true; } if env::var("KITTY_WINDOW_ID").is_ok() {
if env::var("WEZTERM_PANE").is_ok() { return true; } return true;
}
if env::var("WEZTERM_PANE").is_ok() {
return true;
}
if let Ok(term_program) = env::var("TERM_PROGRAM") { if let Ok(term_program) = env::var("TERM_PROGRAM") {
let t = term_program.to_lowercase(); let t = term_program.to_lowercase();
@@ -51,8 +55,10 @@ pub fn terminal_supports_kitty() -> bool {
} }
} }
if let Ok(term) = env::var("TERM") { if let Ok(term) = env::var("TERM")
if term.to_lowercase().contains("kitty") { return true; } && term.to_lowercase().contains("kitty")
{
return true;
} }
false false
@@ -65,8 +71,10 @@ fn terminal_cell_metrics() -> (f32, f32) {
unsafe { unsafe {
let mut ws: winsize = mem::zeroed(); let mut ws: winsize = mem::zeroed();
if ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut ws) == 0 if ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut ws) == 0
&& ws.ws_col > 0 && ws.ws_row > 0 && ws.ws_col > 0
&& ws.ws_xpixel > 0 && ws.ws_ypixel > 0 && ws.ws_row > 0
&& ws.ws_xpixel > 0
&& ws.ws_ypixel > 0
{ {
return ( return (
ws.ws_xpixel as f32 / ws.ws_col as f32, ws.ws_xpixel as f32 / ws.ws_col as f32,
@@ -109,7 +117,10 @@ pub fn print_image_and_setup(path: &str, target_height: u32) -> (usize, usize) {
// Kitty protocol requires PNG format, even for JPEG/WebP sources // Kitty protocol requires PNG format, even for JPEG/WebP sources
// See: https://github.com/Ly-sec/swiftfetch/blob/main/src/display.rs#L495-L501 // See: https://github.com/Ly-sec/swiftfetch/blob/main/src/display.rs#L495-L501
let mut png_bytes = Vec::new(); let mut png_bytes = Vec::new();
if image.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png).is_err() { if image
.write_to(&mut Cursor::new(&mut png_bytes), ImageFormat::Png)
.is_err()
{
return (0, 0); return (0, 0);
} }
@@ -124,7 +135,10 @@ pub fn print_image_and_setup(path: &str, target_height: u32) -> (usize, usize) {
let more = if end < encoded.len() { 1 } else { 0 }; let more = if end < encoded.len() { 1 } else { 0 };
if first { if first {
output.push_str(&format!("\x1b_Ga=T,f=100,s={},v={},m={};", width, height, more)); output.push_str(&format!(
"\x1b_Ga=T,f=100,s={},v={},m={};",
width, height, more
));
first = false; first = false;
} else { } else {
output.push_str(&format!("\x1b_Gm={};", more)); output.push_str(&format!("\x1b_Gm={};", more));
@@ -165,7 +179,11 @@ pub fn print_image_and_setup(path: &str, target_height: u32) -> (usize, usize) {
let text = "a creeper made this"; let text = "a creeper made this";
let text_len = 16; let text_len = 16;
let pad = if image_width_cols > text_len { (image_width_cols - text_len) / 2 } else { 0 }; let pad = if image_width_cols > text_len {
(image_width_cols - text_len) / 2
} else {
0
};
print!("\x1b[{}B", rows); print!("\x1b[{}B", rows);
print!("\r\x1b[{}C{}", pad, text); print!("\r\x1b[{}C{}", pad, text);