Swadhin Biswas feat: add temperature detection and Homebrew formula · 3/7/2026
320ac67
606 lines · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Display module for FetchX — proper neofetch-style side-by-side rendering.
//!
//! ASCII art on the left, info lines on the right, properly aligned.
//! Uses {c1}-{c6} placeholder substitution, correct visible-width calculation,
//! and respects all config flags.

use crate::ascii;
use crate::colors::{self, ColorScheme, BOLD, RESET};
use crate::config::{ColorConfig, Config};
use crate::image_backend::{self, Backend};
use crate::system::SystemInfo;
use crate::utils::{pad_right, truncate_to_width, visible_width};

pub struct Display {
    config: Config,
}

impl Display {
    pub fn new(config: &Config) -> Self {
        Display {
            config: config.clone(),
        }
    }

    pub fn render(&self, sys_info: &SystemInfo) {
        let backend = Backend::from_str(&self.config.image_backend);

        // Resolve image path if using an image backend
        let image_path = if backend != Backend::Ascii && backend != Backend::Off {
            self.resolve_image_path()
        } else {
            None
        };

        // If we have an image backend + valid image, use image mode
        if let Some(ref img_path) = image_path {
            if backend != Backend::Ascii && backend != Backend::Off {
                self.render_with_image(sys_info, &backend, img_path);
                return;
            }
        }

        // Fall through to ASCII art mode
        self.render_ascii(sys_info);
    }

    /// Resolve which image to display based on config.
    fn resolve_image_path(&self) -> Option<String> {
        // Priority: custom_image > image_source path > None
        if let Some(ref path) = self.config.custom_image {
            if std::path::Path::new(path).exists() {
                return Some(path.clone());
            } else {
                eprintln!("Warning: custom_image '{}' not found", path);
            }
        }
        let src = &self.config.image_source;
        if src != "auto" && src != "ascii" && src != "wallpaper" {
            // Treat as a file path
            if std::path::Path::new(src).exists() {
                return Some(src.clone());
            }
        }
        None
    }

    /// Render with an image on the left side.
    fn render_with_image(&self, sys_info: &SystemInfo, backend: &Backend, image_path: &str) {
        // Build color scheme for info text
        let distro_id = if self.config.ascii_distro == "auto" {
            &sys_info.distro_id
        } else {
            &self.config.ascii_distro
        };
        let scheme = self.build_color_scheme(distro_id);
        let info_lines = self.build_info_lines(sys_info, &scheme);

        // Determine size for the image
        let max_cols = self.parse_image_size_cols().unwrap_or(35);
        let max_rows = info_lines.len().max(20);

        match backend {
            Backend::Kitty => {
                // Kitty: render image directly via escape codes, then print info beside it
                match image_backend::display_kitty(image_path, max_cols, max_rows) {
                    Ok((img_cols, img_rows)) => {
                        let gap = self.config.gap;
                        let reset = if self.config.no_color { "" } else { RESET };
                        let total = img_rows.max(info_lines.len());
                        let term_w = terminal_width();
                        let right_avail = term_w.saturating_sub(img_cols + gap);

                        // Move cursor up by img_rows to start printing info beside image
                        print!("\x1b[{}A", img_rows);

                        for i in 0..total {
                            // Move to the right of the image
                            print!("\x1b[{}C", img_cols + gap);
                            if i < info_lines.len() {
                                let truncated = if right_avail > 0 {
                                    truncate_to_width(&info_lines[i], right_avail)
                                } else {
                                    info_lines[i].clone()
                                };
                                println!("{}{}", truncated, reset);
                            } else {
                                println!();
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Warning: kitty image failed: {}", e);
                        self.render_ascii(sys_info);
                    }
                }
            }
            Backend::Chafa => {
                // Chafa: get text lines and use them like ASCII art
                match image_backend::display_chafa(image_path, max_cols, max_rows) {
                    Ok(img_lines) => {
                        self.render_side_by_side(&img_lines, &info_lines);
                    }
                    Err(e) => {
                        eprintln!("Warning: chafa failed: {}", e);
                        self.render_ascii(sys_info);
                    }
                }
            }
            Backend::Sixel => {
                match image_backend::display_sixel(image_path, max_cols, max_rows) {
                    Ok(()) => {
                        // Sixel prints inline; just print info lines below
                        let reset = if self.config.no_color { "" } else { RESET };
                        for line in &info_lines {
                            println!("{}{}", line, reset);
                        }
                    }
                    Err(e) => {
                        eprintln!("Warning: sixel failed: {}", e);
                        self.render_ascii(sys_info);
                    }
                }
            }
            Backend::W3m => {
                match image_backend::display_w3m(image_path, max_cols, max_rows) {
                    Ok(()) => {
                        // w3m renders image at position; print info offset to the right
                        let gap = self.config.gap;
                        let offset = max_cols + gap;
                        let reset = if self.config.no_color { "" } else { RESET };
                        let term_w = terminal_width();
                        let right_avail = term_w.saturating_sub(offset);
                        // Move up to start of image area
                        print!("\x1b[{}A", max_rows);
                        for i in 0..max_rows.max(info_lines.len()) {
                            print!("\x1b[{}C", offset);
                            if i < info_lines.len() {
                                let truncated = if right_avail > 0 {
                                    truncate_to_width(&info_lines[i], right_avail)
                                } else {
                                    info_lines[i].clone()
                                };
                                println!("{}{}", truncated, reset);
                            } else {
                                println!();
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Warning: w3m image failed: {}", e);
                        self.render_ascii(sys_info);
                    }
                }
            }
            Backend::Iterm2 => {
                match image_backend::display_iterm2(image_path, max_cols, max_rows) {
                    Ok(()) => {
                        // iTerm2 inline image works like kitty; print info beside it
                        let gap = self.config.gap;
                        let reset = if self.config.no_color { "" } else { RESET };
                        let total = max_rows.max(info_lines.len());
                        let term_w = terminal_width();
                        let right_avail = term_w.saturating_sub(max_cols + gap);

                        print!("\x1b[{}A", max_rows);
                        for i in 0..total {
                            print!("\x1b[{}C", max_cols + gap);
                            if i < info_lines.len() {
                                let truncated = if right_avail > 0 {
                                    truncate_to_width(&info_lines[i], right_avail)
                                } else {
                                    info_lines[i].clone()
                                };
                                println!("{}{}", truncated, reset);
                            } else {
                                println!();
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Warning: iTerm2 image failed: {}", e);
                        self.render_ascii(sys_info);
                    }
                }
            }
            _ => self.render_ascii(sys_info),
        }
    }

    /// Parse image_size config into column count.
    fn parse_image_size_cols(&self) -> Option<usize> {
        let s = &self.config.image_size;
        if s == "auto" || s == "none" {
            return None;
        }
        if let Some(stripped) = s.strip_suffix("px") {
            // Convert pixels to approximate columns (8px per col)
            stripped.parse::<usize>().ok().map(|px| px / 8)
        } else if let Some(stripped) = s.strip_suffix('%') {
            // Percentage of terminal width
            let term_cols = terminal_width();
            stripped
                .parse::<usize>()
                .ok()
                .map(|pct| term_cols * pct / 100)
        } else {
            s.parse::<usize>().ok()
        }
    }

    /// Standard ASCII art rendering path.
    fn render_ascii(&self, sys_info: &SystemInfo) {
        // Resolve which distro art to use
        let distro_id = if self.config.ascii_distro == "auto" {
            &sys_info.distro_id
        } else {
            &self.config.ascii_distro
        };

        let scheme = self.build_color_scheme(distro_id);

        // Get ASCII art lines with color placeholders resolved
        let ascii_lines = self.build_ascii_lines(distro_id, &scheme);

        if self.config.logo_only {
            let reset = if self.config.no_color { "" } else { RESET };
            for line in &ascii_lines {
                println!("{}{}", line, reset);
            }
            return;
        }

        // Build info lines
        let info_lines = self.build_info_lines(sys_info, &scheme);

        self.render_side_by_side(&ascii_lines, &info_lines);
    }

    /// Build the color scheme based on config and distro.
    fn build_color_scheme(&self, distro_id: &str) -> ColorScheme {
        // Determine ASCII art colors to use
        let art_color_nums: Vec<u8> = match &self.config.ascii_colors {
            ColorConfig::Numbers(nums) if !nums.is_empty() => nums.clone(),
            _ => {
                let art = ascii::get_ascii(distro_id);
                art.colors.clone()
            }
        };

        let art_bold = self.config.ascii_bold && self.config.bold;
        if self.config.no_color {
            ColorScheme::plain()
        } else {
            let mut cs = ColorScheme::from_colors(&art_color_nums, art_bold);

            // Override text colors if user specified custom colors
            match &self.config.colors {
                ColorConfig::Numbers(nums) if !nums.is_empty() => {
                    if let Some(&n) = nums.first() {
                        cs.title = colors::color(n);
                    }
                    if let Some(&n) = nums.get(1) {
                        cs.at = colors::color(n);
                    }
                    if let Some(&n) = nums.get(2) {
                        cs.underline = colors::color(n);
                    }
                    if let Some(&n) = nums.get(3) {
                        cs.subtitle = colors::color(n);
                    }
                    if let Some(&n) = nums.get(4) {
                        cs.colon = colors::color(n);
                    }
                    if let Some(&n) = nums.get(5) {
                        cs.info = colors::color(n);
                    }
                }
                _ => {}
            }

            cs
        }
    }

    /// Render left-side lines and right-side info lines side-by-side.
    fn render_side_by_side(&self, left_lines: &[String], right_lines: &[String]) {
        // Calculate max visible width of ASCII art (for padding calculations)
        let max_left_width = left_lines
            .iter()
            .map(|l| visible_width(l))
            .max()
            .unwrap_or(0);

        let gap = self.config.gap;
        let term_w = terminal_width();
        let right_avail = term_w.saturating_sub(max_left_width + gap);
        let reset = if self.config.no_color { "" } else { RESET };

        // Simple approach: just pad ASCII lines and print with info alongside
        // No cursor repositioning - just proper column alignment

        let total_rows = left_lines.len().max(right_lines.len());

        for i in 0..total_rows {
            // Left column: ASCII art (padded to width)
            let left_part = if i < left_lines.len() {
                pad_right(&left_lines[i], max_left_width)
            } else {
                " ".repeat(max_left_width)
            };

            // Gap between columns
            let gap_str = " ".repeat(gap);

            // Right column: info lines (truncated to fit)
            if i < right_lines.len() {
                let truncated = if right_avail > 0 {
                    truncate_to_width(&right_lines[i], right_avail)
                } else {
                    right_lines[i].clone()
                };
                println!("{}{}{}{}{}", left_part, reset, gap_str, truncated, reset);
            } else {
                println!("{}{}", left_part, reset);
            }
        }
    }

    /// Build ASCII art lines with {c1}-{c6} placeholders replaced by actual ANSI codes.
    fn build_ascii_lines(&self, distro_id: &str, scheme: &ColorScheme) -> Vec<String> {
        if self.config.emoji_mode {
            return ascii::get_emoji_art(distro_id)
                .into_iter()
                .map(|s| s.to_string())
                .collect();
        }

        // If user specified a custom ASCII file, load it from disk
        let raw_lines: Vec<String> = if let Some(ref path) = self.config.ascii_file {
            match std::fs::read_to_string(path) {
                Ok(contents) => contents.lines().map(|l| l.to_string()).collect(),
                Err(e) => {
                    eprintln!("Warning: could not read ascii_file '{}': {}", path, e);
                    let art = ascii::get_ascii(distro_id);
                    art.lines.iter().map(|s| s.to_string()).collect()
                }
            }
        } else {
            let art = ascii::get_ascii(distro_id);
            art.lines.iter().map(|s| s.to_string()).collect()
        };

        raw_lines
            .iter()
            .map(|line| {
                let mut s = line.to_string();
                for (i, color_seq) in scheme.c.iter().enumerate() {
                    let placeholder = format!("{{c{}}}", i + 1);
                    s = s.replace(&placeholder, color_seq);
                }
                s
            })
            .collect()
    }

    /// Build all info lines (title, underline, fields, color blocks).
    fn build_info_lines(&self, sys: &SystemInfo, scheme: &ColorScheme) -> Vec<String> {
        let mut lines: Vec<String> = Vec::new();
        let sep = &self.config.separator;

        // Title: user@host
        if self.config.show_title {
            if self.config.no_color {
                lines.push(format!("{}@{}", sys.username, sys.hostname));
            } else {
                let title_line = format!(
                    "{}{}{}{}{}@{}{}{}{}",
                    scheme.title,
                    BOLD,
                    sys.username,
                    RESET,
                    scheme.at,
                    scheme.title,
                    BOLD,
                    sys.hostname,
                    RESET,
                );
                lines.push(title_line);
            }
        }

        // Underline (uses configurable underline_char, defaults to '-' like neofetch)
        if self.config.show_underline && self.config.show_title {
            let title_visible_len = sys.username.len() + 1 + sys.hostname.len(); // user@host
            let dashes = self.config.underline_char.repeat(title_visible_len);
            if self.config.no_color {
                lines.push(dashes);
            } else {
                lines.push(format!("{}{}{}", scheme.underline, dashes, RESET));
            }
        }

        // Info fields — each one: colored label + separator + value
        let nf = self.config.nerd_font;

        let field = |label: &str, icon: &str, value: &str| -> String {
            if self.config.no_color {
                let prefix = if nf {
                    format!("{} {}", icon, label)
                } else {
                    label.to_string()
                };
                format!("{}{}{}", prefix, sep, value)
            } else {
                let prefix = if nf {
                    format!("{} {}{}{}", icon, scheme.subtitle, BOLD, label)
                } else {
                    format!("{}{}{}", scheme.subtitle, BOLD, label)
                };
                format!(
                    "{}{}{}{}{}{}",
                    prefix, RESET, scheme.colon, sep, scheme.info, value
                )
            }
        };

        // Helper to skip "Unknown" fields
        macro_rules! add_field {
            ($show:expr, $label:expr, $icon:expr, $val:expr) => {
                if $show && $val != "Unknown" && !$val.is_empty() {
                    lines.push(field($label, $icon, $val));
                }
            };
        }

        add_field!(self.config.show_os, "OS", "\u{f303}", &sys.os); //
        add_field!(self.config.show_host, "Host", "\u{f7c9}", &sys.host); //  󰟩
        add_field!(self.config.show_kernel, "Kernel", "\u{f303}", &sys.kernel); //
        add_field!(self.config.show_uptime, "Uptime", "\u{f64f}", &sys.uptime); //
        add_field!(
            self.config.show_packages,
            "Packages",
            "\u{f487}",
            &sys.packages
        ); //
        add_field!(self.config.show_shell, "Shell", "\u{f489}", &sys.shell); //
        add_field!(
            self.config.show_resolution,
            "Resolution",
            "\u{f878}",
            &sys.resolution
        ); //
        add_field!(self.config.show_de, "DE", "\u{f108}", &sys.de); //
        add_field!(self.config.show_wm, "WM", "\u{f2d0}", &sys.wm); //
        add_field!(
            self.config.show_wm_theme,
            "WM Theme",
            "\u{f53e}",
            &sys.wm_theme
        ); //
        add_field!(self.config.show_theme, "Theme", "\u{f53e}", &sys.theme); //
        add_field!(self.config.show_icons, "Icons", "\u{f53e}", &sys.icons); //
        add_field!(
            self.config.show_terminal,
            "Terminal",
            "\u{f120}",
            &sys.terminal
        ); //
        add_field!(
            self.config.show_term_font,
            "Terminal Font",
            "\u{f031}",
            &sys.term_font
        ); //
        add_field!(self.config.show_cpu, "CPU", "\u{f4bc}", &sys.cpu); //

        // GPU: each GPU on its own line (like neofetch)
        if self.config.show_gpu {
            for (i, gpu_entry) in sys.gpu.iter().enumerate() {
                if gpu_entry != "Unknown" && !gpu_entry.is_empty() {
                    let label = if sys.gpu.len() > 1 {
                        format!("GPU{}", i)
                    } else {
                        "GPU".to_string()
                    };
                    lines.push(field(&label, "\u{f4bd}", gpu_entry));
                }
            }
        }

        // Temperature
        add_field!(
            self.config.show_temperature,
            "Temperature",
            "\u{f76c}",
            &sys.temperature
        );

        // Memory — optionally with progress bar
        if self.config.show_memory && sys.memory != "Unknown" && !sys.memory.is_empty() {
            if self.config.memory_bar {
                let bar =
                    colors::progress_bar(sys.memory_percent, self.config.bar_width, &scheme.c[0]);
                lines.push(field(
                    "Memory",
                    "\u{f85a}",
                    &format!("{} {}", sys.memory, bar),
                ));
            } else {
                lines.push(field("Memory", "\u{f85a}", &sys.memory));
            }
        }

        // Disk — optionally with progress bar
        if self.config.show_disk && sys.disk != "Unknown" && !sys.disk.is_empty() {
            if self.config.disk_bar {
                let bar =
                    colors::progress_bar(sys.disk_percent, self.config.bar_width, &scheme.c[0]);
                lines.push(field("Disk", "\u{f0a0}", &format!("{} {}", sys.disk, bar)));
            } else {
                lines.push(field("Disk", "\u{f0a0}", &sys.disk));
            }
        }

        add_field!(
            self.config.show_battery,
            "Battery",
            "\u{f240}",
            &sys.battery
        ); //
        add_field!(
            self.config.show_local_ip,
            "Local IP",
            "\u{f6ff}",
            &sys.local_ip
        ); //  󰛿
        add_field!(
            self.config.show_public_ip,
            "Public IP",
            "\u{f0ac}",
            &sys.public_ip
        ); //
        add_field!(self.config.show_locale, "Locale", "\u{f0ac}", &sys.locale); //
        add_field!(self.config.show_song, "Song", "\u{f001}", &sys.song); //
        add_field!(self.config.show_users, "Users", "\u{f007}", &sys.users); //

        // Blank line before color blocks
        if self.config.show_colors && !self.config.no_color {
            lines.push(String::new());
            let blocks = colors::color_blocks(
                self.config.block_range.0,
                self.config.block_range.1,
                self.config.block_width,
            );
            for block_line in blocks {
                lines.push(block_line);
            }
        }

        lines
    }
}

/// Get terminal width in columns.
fn terminal_width() -> usize {
    // Try COLUMNS env first
    if let Ok(cols) = std::env::var("COLUMNS") {
        if let Ok(n) = cols.parse::<usize>() {
            return n;
        }
    }

    // Try `tput cols`
    if let Ok(output) = std::process::Command::new("tput").arg("cols").output() {
        if output.status.success() {
            if let Ok(s) = String::from_utf8(output.stdout) {
                if let Ok(n) = s.trim().parse::<usize>() {
                    return n;
                }
            }
        }
    }

    80
}