Skip to main content

retch_cli/
display.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2// Copyright (C) 2026 l1a
3
4//! Formatting and display logic for terminal output.
5//!
6//! Handles text rendering, layout, and image/ASCII logo rendering.
7
8use crate::cli::Cli;
9use crate::config::Config;
10use crate::fetch::SystemInfo;
11use crate::logo;
12use crate::theme::Theme;
13use owo_colors::OwoColorize;
14
15impl SystemInfo {
16    /// Renders the collected system information to the terminal.
17    ///
18    /// This method handles theme selection, logo rendering (including fallbacks
19    /// between graphics, Chafa, and ASCII), and field filtering based on
20    /// CLI flags and configuration.
21    pub fn display(&self, cli: &Cli, _config: &Config) -> anyhow::Result<()> {
22        println!();
23        let theme_name = _config.theme.as_deref().or(cli.theme.as_deref());
24        let mut theme = match theme_name {
25            Some(name) => Theme::from_name(name),
26            None => Theme::detect_system_theme(), // Default to system preference
27        };
28
29        // Apply custom theme overrides from config if present
30        if let Some(custom) = &_config.custom_theme {
31            theme = Theme::with_custom_overrides(theme, custom);
32        }
33
34        let show_logo = _config.show_logo.unwrap_or(true) && !cli.no_logo;
35        if show_logo {
36            let distro_hint = _config.logo.clone().or_else(logo::detect_distro);
37            #[cfg(feature = "graphics")]
38            let mut printed_logo = false;
39            #[cfg(not(feature = "graphics"))]
40            let printed_logo = false;
41
42            if !cli.ascii_only {
43                // 1. Try user-provided custom logo first (config override)
44                let user_logo = if let Some(config_dir) = dirs::config_dir() {
45                    let p = config_dir.join("retch").join("logo.png");
46                    if p.exists() {
47                        Some(p)
48                    } else {
49                        None
50                    }
51                } else {
52                    None
53                };
54
55                // 2. Kitty mode
56                #[cfg(feature = "graphics")]
57                if !printed_logo && logo::supports_kitty() {
58                    if let Some(path) = &user_logo {
59                        logo::print_graphical_logo_from_path(path);
60                        printed_logo = true;
61                    } else if let Some(distro) = &distro_hint {
62                        if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
63                            logo::print_graphical_logo(bytes);
64                            printed_logo = true;
65                        }
66                    }
67                }
68
69                // 2.3 iTerm2 mode
70                #[cfg(feature = "graphics")]
71                if !printed_logo && logo::supports_iterm2() {
72                    if let Some(path) = &user_logo {
73                        logo::print_iterm2_logo_from_path(path);
74                        printed_logo = true;
75                    } else if let Some(distro) = &distro_hint {
76                        if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
77                            logo::print_iterm2_logo(bytes);
78                            printed_logo = true;
79                        }
80                    }
81                }
82
83                // 2.5 Sixel mode
84                #[cfg(feature = "graphics")]
85                if !printed_logo && logo::supports_sixel() {
86                    if let Some(path) = &user_logo {
87                        logo::print_sixel_logo_from_path(path);
88                        printed_logo = true;
89                    } else if let Some(distro) = &distro_hint {
90                        if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
91                            logo::print_sixel_logo(bytes);
92                            printed_logo = true;
93                        }
94                    }
95                }
96
97                // 3. Chafa fallback (high-quality symbols)
98                if !printed_logo && logo::chafa_available() {
99                    if let Some(path) = &user_logo {
100                        if logo::print_with_chafa(path) {
101                            printed_logo = true;
102                        }
103                    } else if distro_hint.is_some() {
104                        // For chafa we need a file, so we skip embedded for now
105                        // (user can provide logo.png for chafa path)
106                    }
107                }
108            }
109
110            // 3. Final fallback: Real Fastfetch ASCII logo
111            if !printed_logo {
112                // Use the unified priority logic (graphic -> chafa -> ASCII)
113                logo::print_distro_logo_with_ascii(distro_hint.as_deref(), cli.ascii_only);
114            }
115            println!(); // spacing after logo
116        }
117
118        // Determine which fields to show
119        let allowed_fields: Option<Vec<String>> = if cli.long {
120            None // show everything
121        } else if cli.short {
122            Some(vec![
123                "os".to_string(),
124                "kernel".to_string(),
125                "host".to_string(),
126                "cpu".to_string(),
127                "gpu".to_string(),
128                "memory".to_string(),
129                "disk".to_string(),
130            ])
131        } else if let Some(fields) = &_config.fields {
132            Some(fields.iter().map(|s| s.to_lowercase()).collect())
133        } else {
134            // Default set
135            Some(vec![
136                "os".to_string(),
137                "kernel".to_string(),
138                "host".to_string(),
139                "cpu".to_string(),
140                "gpu".to_string(),
141                "memory".to_string(),
142                "swap".to_string(),
143                "load".to_string(),
144                "disk".to_string(),
145                "net".to_string(),
146                "uptime".to_string(),
147            ])
148        };
149
150        let should_show = |label: &str| -> bool {
151            match &allowed_fields {
152                Some(fields) => fields.contains(&label.to_lowercase()),
153                None => true,
154            }
155        };
156
157        // Helper for right-aligned labels
158        let label_width = 10;
159        let print_line = |label: &str, value: &str| {
160            if should_show(label) {
161                println!(
162                    "{:>width$}{} {}",
163                    theme.color_label(label),
164                    theme.color_separator(":"),
165                    theme.color_value(value),
166                    width = label_width
167                );
168            }
169        };
170
171        print_line("OS", &self.os);
172        if let Some(kernel) = &self.kernel {
173            print_line("Kernel", kernel);
174        }
175        if let Some(host) = &self.hostname {
176            print_line("Host", host);
177        }
178        if let Some(user) = &self.current_user {
179            print_line("User", user);
180        }
181        print_line("Arch", &self.arch);
182        print_line("CPU", &format!("{} ({} cores)", self.cpu, self.cpu_cores));
183        if let Some(freq) = &self.cpu_freq {
184            print_line("CPU Freq", freq);
185        }
186        if should_show("GPU") {
187            for gpu in &self.gpu {
188                print_line("GPU", gpu);
189            }
190        }
191        print_line("Memory", &self.memory);
192        print_line("Swap", &self.swap);
193        print_line("Procs", &self.processes.to_string());
194        if let Some(load) = &self.load_avg {
195            print_line("Load", load);
196        }
197
198        if should_show("Disk") {
199            for disk in &self.disks {
200                print_line("Disk", disk);
201            }
202        }
203
204        if should_show("Temp") {
205            for temp in &self.temps {
206                print_line("Temp", temp);
207            }
208        }
209
210        if should_show("Net") {
211            for net in &self.networks {
212                if let Some(ref active) = self.active_interface {
213                    if net.contains(active) {
214                        // Highlight active interface by coloring the value
215                        print_line("Net", &net.bright_blue().to_string());
216                        continue;
217                    }
218                }
219                print_line("Net", net);
220            }
221        }
222
223        if let Some(ip) = &self.public_ip {
224            print_line("Public IP", ip);
225        }
226
227        // Uptime: human duration first, then ISO boot time with timezone
228        let uptime_str = format_uptime(&self.uptime);
229        let boot_display = format!("{} since {}", uptime_str, self.boot_time);
230        print_line("Uptime", &boot_display);
231
232        if let Some(bat) = &self.battery {
233            print_line("Battery", bat);
234        }
235
236        if let Some(shell) = &self.shell {
237            print_line("Shell", shell);
238        }
239        if let Some(term) = &self.terminal {
240            print_line("Terminal", term);
241        }
242        if let Some(de) = &self.desktop {
243            print_line("Desktop", de);
244        }
245        print_line("Users", &self.users.to_string());
246        if let Some(pkgs) = self.packages {
247            if pkgs > 0 {
248                print_line("Packages", &pkgs.to_string());
249            }
250        }
251
252        Ok(())
253    }
254}
255
256/// Formats a raw uptime string (in seconds) into a human-readable duration.
257///
258/// Example: "45224s" -> "12h 33m 44s"
259fn format_uptime(uptime: &str) -> String {
260    // Parse the uptime string (e.g. "45224s")
261    let seconds: u64 = uptime.trim_end_matches('s').parse().unwrap_or(0);
262
263    let years = seconds / (365 * 24 * 3600);
264    let days = (seconds % (365 * 24 * 3600)) / (24 * 3600);
265    let hours = (seconds % (24 * 3600)) / 3600;
266    let minutes = (seconds % 3600) / 60;
267    let secs = seconds % 60;
268
269    let mut parts = Vec::new();
270    if years > 0 {
271        parts.push(format!("{}y", years));
272    }
273    if days > 0 {
274        parts.push(format!("{}d", days));
275    }
276    if hours > 0 {
277        parts.push(format!("{}h", hours));
278    }
279    if minutes > 0 {
280        parts.push(format!("{}m", minutes));
281    }
282    if secs > 0 || parts.is_empty() {
283        parts.push(format!("{}s", secs));
284    }
285
286    parts.join(" ")
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn test_format_uptime() {
295        assert_eq!(format_uptime("60s"), "1m");
296        assert_eq!(format_uptime("3600s"), "1h");
297        assert_eq!(format_uptime("3661s"), "1h 1m 1s");
298        assert_eq!(format_uptime("86400s"), "1d");
299        assert_eq!(format_uptime("90061s"), "1d 1h 1m 1s");
300        assert_eq!(format_uptime("31536000s"), "1y");
301        assert_eq!(format_uptime("31626061s"), "1y 1d 1h 1m 1s");
302        assert_eq!(format_uptime("0s"), "0s");
303    }
304}