retch-cli 0.3.35

A fast, feature-rich system information fetcher written in Rust (similar to fastfetch or neofetch)
Documentation
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
// SPDX-FileCopyrightText: 2026 Ken Tobias
// SPDX-License-Identifier: GPL-3.0-or-later

//! Formatting and display logic for terminal output.
//!
//! Handles text rendering, layout, and image/ASCII logo rendering.

use crate::cli::Cli;
use crate::config::Config;
use crate::fetch::SystemInfo;
use crate::logo;
use crate::theme::Theme;
use owo_colors::OwoColorize;

/// Renders the collected system information to the terminal.
///
/// This function handles theme selection, logo rendering (including fallbacks
/// between graphics, Chafa, and ASCII), and field filtering based on
/// CLI flags and configuration.
pub fn display(info: &SystemInfo, cli: &Cli, config: &Config) -> anyhow::Result<()> {
    let _config = config;
    let theme_name = _config.theme.as_deref().or(cli.theme.as_deref());
    let mut theme = match theme_name {
        Some(name) => Theme::from_name(name),
        None => Theme::detect_system_theme(), // Default to system preference
    };

    // Apply custom theme overrides from config if present
    if let Some(custom) = &_config.custom_theme {
        theme = Theme::with_custom_overrides(theme, custom);
    }

    // Determine terminal width.
    let term_size = terminal_size::terminal_size();
    let term_width = if let Some((terminal_size::Width(w), _)) = term_size {
        w as usize
    } else {
        80
    };
    // Use isatty() directly — terminal_size() can return Some() when a pager
    // (e.g. bat) allocates a PTY, giving a false positive.
    let stdout_is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());

    let show_logo = _config.show_logo.unwrap_or(true) && !cli.no_logo && stdout_is_tty;

    // Determine which fields to show
    let allowed_fields: Option<Vec<String>> = if cli.full {
        Some(vec![
            // Standard fields
            "os".to_string(),
            "kernel".to_string(),
            "host".to_string(),
            "cpu".to_string(),
            "cpu-cache".to_string(),
            "cpu-usage".to_string(),
            "motherboard".to_string(),
            "gpu".to_string(),
            "display".to_string(),
            "audio".to_string(),
            "camera".to_string(),
            "memory".to_string(),
            "phys-mem".to_string(),
            "swap".to_string(),
            "load".to_string(),
            "disk".to_string(),
            "phys-disk".to_string(),
            "net".to_string(),
            "uptime".to_string(),
            // Long fields
            "bios".to_string(),
            "font".to_string(),
            "shell".to_string(),
            "editor".to_string(),
            "terminal".to_string(),
            "terminal-font".to_string(),
            "terminal-size".to_string(),
            "desktop".to_string(),
            "wm".to_string(),
            "dns".to_string(),
            "domain".to_string(),
            "wifi".to_string(),
            "bluetooth".to_string(),
            "battery".to_string(),
            "public-ip".to_string(),
            "locale".to_string(),
            "init".to_string(),
            "chassis".to_string(),
            "bootmgr".to_string(),
            "temp".to_string(),
            "cpu-freq".to_string(),
            "procs".to_string(),
            "arch".to_string(),
            "users".to_string(),
            "packages".to_string(),
            // Full-only fields
            "theme".to_string(),
            "icons".to_string(),
            "cursor".to_string(),
            "gamepad".to_string(),
            "weather".to_string(),
            "domain-search".to_string(),
        ])
    } else if cli.long {
        Some(vec![
            // Standard fields
            "os".to_string(),
            "kernel".to_string(),
            "host".to_string(),
            "cpu".to_string(),
            "cpu-cache".to_string(),
            "cpu-usage".to_string(),
            "motherboard".to_string(),
            "gpu".to_string(),
            "display".to_string(),
            "audio".to_string(),
            "camera".to_string(),
            "memory".to_string(),
            "phys-mem".to_string(),
            "swap".to_string(),
            "load".to_string(),
            "disk".to_string(),
            "phys-disk".to_string(),
            "net".to_string(),
            "uptime".to_string(),
            // Long-only fields
            "bios".to_string(),
            "font".to_string(),
            "shell".to_string(),
            "editor".to_string(),
            "terminal".to_string(),
            "terminal-font".to_string(),
            "terminal-size".to_string(),
            "desktop".to_string(),
            "wm".to_string(),
            "dns".to_string(),
            "domain".to_string(),
            "wifi".to_string(),
            "bluetooth".to_string(),
            "battery".to_string(),
            "public-ip".to_string(),
            "locale".to_string(),
            "init".to_string(),
            "chassis".to_string(),
            "bootmgr".to_string(),
            "temp".to_string(),
            "cpu-freq".to_string(),
            "procs".to_string(),
            "arch".to_string(),
            "users".to_string(),
            "packages".to_string(),
        ])
    } else if cli.short {
        Some(vec![
            "os".to_string(),
            "kernel".to_string(),
            "host".to_string(),
            "cpu".to_string(),
            "gpu".to_string(),
            "memory".to_string(),
            "disk".to_string(),
            "net".to_string(),
        ])
    } else if let Some(fields) = &_config.fields {
        Some(fields.iter().map(|s| s.to_lowercase()).collect())
    } else {
        // Default (standard) set
        Some(vec![
            "os".to_string(),
            "kernel".to_string(),
            "host".to_string(),
            "cpu".to_string(),
            "cpu-cache".to_string(),
            "cpu-usage".to_string(),
            "motherboard".to_string(),
            "gpu".to_string(),
            "display".to_string(),
            "audio".to_string(),
            "camera".to_string(),
            "memory".to_string(),
            "phys-mem".to_string(),
            "swap".to_string(),
            "load".to_string(),
            "disk".to_string(),
            "phys-disk".to_string(),
            "net".to_string(),
            "uptime".to_string(),
        ])
    };

    let should_show = |label: &str| -> bool {
        match &allowed_fields {
            Some(fields) => {
                let norm_label = label.to_lowercase().replace(['-', '_'], " ");
                let norm_label_no_spaces = norm_label.replace(' ', "");
                fields.iter().any(|f| {
                    let norm_f = f.to_lowercase().replace(['-', '_'], " ");
                    norm_f == norm_label
                        || norm_f.replace(' ', "") == norm_label_no_spaces
                        // "dns" field key matches "DNS Server" display label
                        || (norm_label == "dns server" && norm_f == "dns")
                })
            }
            None => true,
        }
    };

    // Helper for right-aligned labels
    let label_width = 10;
    let mut info_lines = Vec::new();
    let mut print_line = |label: &str, value: &str| {
        if should_show(label) {
            info_lines.push(format!(
                "{:>width$}{} {}",
                theme.color_label(label),
                theme.color_separator(":"),
                theme.color_value(value),
                width = label_width
            ));
        }
    };

    // OS / system identity
    print_line("OS", &info.os);
    if let Some(kernel) = &info.kernel {
        print_line("Kernel", kernel);
    }
    if let Some(host) = &info.hostname {
        print_line("Host", host);
    }
    if let Some(domain) = &info.domain {
        print_line("Domain", domain);
    }
    if should_show("domain-search") {
        for entry in &info.domain_search {
            print_line("Domain Search", entry);
        }
    }
    if let Some(chassis) = &info.chassis {
        print_line("Chassis", chassis);
    }
    if let Some(init) = &info.init_system {
        print_line("Init", init);
    }
    if let Some(locale) = &info.locale {
        print_line("Locale", locale);
    }
    print_line("Arch", &info.arch);
    print_line("Users", &info.users.to_string());
    if let Some(pkgs) = info.packages {
        if pkgs > 0 {
            print_line("Packages", &pkgs.to_string());
        }
    }
    if let Some(user) = &info.current_user {
        print_line("User", user);
    }
    // Uptime belongs with system identity, not hardware
    let uptime_str = format_uptime(&info.uptime);
    let boot_display = format!("{} since {}", uptime_str, info.boot_time);
    print_line("Uptime", &boot_display);

    // Hardware
    print_line("CPU", &format!("{} ({})", info.cpu, info.cpu_core_info));
    if let Some(freq) = &info.cpu_freq {
        print_line("CPU Freq", freq);
    }
    if let Some(cache) = &info.cpu_cache {
        print_line("CPU Cache", cache);
    }
    if let Some(usage) = &info.cpu_usage {
        print_line("CPU Usage", usage);
    }
    if let Some(motherboard) = &info.motherboard {
        print_line("Motherboard", motherboard);
    }
    if let Some(bios) = &info.bios {
        print_line("BIOS", bios);
    }
    if let Some(bootmgr) = &info.bootmgr {
        print_line("Bootmgr", bootmgr);
    }
    if should_show("GPU") {
        for gpu in &info.gpu {
            print_line("GPU", gpu);
        }
    }
    if should_show("Display") {
        for display in &info.displays {
            print_line("Display", display);
        }
    }
    if let Some(audio) = &info.audio {
        print_line("Audio", audio);
    }
    if should_show("Camera") {
        for cam in &info.camera {
            print_line("Camera", cam);
        }
    }
    if should_show("Gamepad") {
        for gp in &info.gamepad {
            print_line("Gamepad", gp);
        }
    }
    if let Some(wifi) = &info.wifi {
        print_line("Wi-Fi", wifi);
    }
    if let Some(bt) = &info.bluetooth {
        print_line("Bluetooth", bt);
    }
    if let Some(bat) = &info.battery {
        print_line("Battery", bat);
    }
    print_line("Memory", &info.memory);
    if let Some(phys_mem) = &info.physical_memory {
        print_line("Phys Mem", phys_mem);
    }
    print_line("Swap", &info.swap);
    print_line("Procs", &info.processes.to_string());
    if let Some(load) = &info.load_avg {
        print_line("Load", load);
    }
    if should_show("Disk") {
        for disk in &info.disks {
            print_line("Disk", disk);
        }
    }
    if should_show("Phys Disk") {
        for disk in &info.physical_disks {
            print_line("Phys Disk", disk);
        }
    }
    if should_show("Temp") {
        if cli.full {
            for temp in &info.temps {
                print_line("Temp", temp);
            }
        } else {
            for temp in consolidate_temps(&info.temps) {
                print_line("Temp", &temp);
            }
        }
    }

    // Network
    if should_show("Net") {
        if cli.long || cli.full {
            for net in &info.networks {
                if let Some(ref active) = info.active_interface {
                    if net.contains(active) {
                        print_line("Net", &net.bright_blue().to_string());
                    }
                }
            }
            for net in &info.networks {
                if let Some(ref active) = info.active_interface {
                    if net.contains(active) {
                        continue;
                    }
                }
                print_line("Net", net);
            }
        } else {
            let mut printed = false;
            if let Some(ref active) = info.active_interface {
                for net in &info.networks {
                    if net.contains(active) {
                        print_line("Net", net);
                        printed = true;
                        break;
                    }
                }
            }
            if !printed {
                for net in &info.networks {
                    if net.contains("[Up]") {
                        print_line("Net", net);
                        break;
                    }
                }
            }
        }
    }
    if let Some(ip) = &info.public_ip {
        print_line("Public IP", ip);
    }
    if !info.dns.is_empty() {
        print_line("DNS Server", &info.dns.join(", "));
    }

    // Environment
    if let Some(shell) = &info.shell {
        print_line("Shell", shell);
    }
    if let Some(editor) = &info.editor {
        print_line("Editor", editor);
    }
    if let Some(term) = &info.terminal {
        print_line("Terminal", term);
    }
    if let Some(ts) = &info.terminal_size {
        print_line("Terminal Size", ts);
    }
    if let Some(de) = &info.desktop {
        print_line("Desktop", de);
    }
    if let Some(wm) = &info.wm {
        let duplicate = info
            .desktop
            .as_deref()
            .map(|de| de.to_lowercase() == wm.to_lowercase())
            .unwrap_or(false);
        if !duplicate {
            print_line("WM", wm);
        }
    }
    if let Some(ui_theme) = &info.ui_theme {
        print_line("Theme", ui_theme);
    }
    if let Some(icons) = &info.icons {
        print_line("Icons", icons);
    }
    if let Some(cursor) = &info.cursor {
        print_line("Cursor", cursor);
    }
    if let Some(font) = &info.font {
        print_line("Font", font);
    }
    if let Some(term_font) = &info.terminal_font {
        print_line("Terminal Font", term_font);
    }
    if let Some(weather) = &info.weather {
        print_line("Weather", weather);
    }

    // Setup logo representation
    enum ActiveLogo {
        Lines(Vec<String>),
        Kitty(Vec<u8>, usize), // bytes, height_lines
        Iterm2(Vec<u8>, usize),
        Sixel(Vec<u8>, usize),
        None,
    }

    let mut active_logo = ActiveLogo::None;

    if show_logo {
        let distro_hint = _config.logo.clone().or_else(logo::detect_distro);
        let user_logo = if let Some(config_dir) = dirs::config_dir() {
            let p = config_dir.join("retch").join("logo.png");
            if p.exists() {
                Some(p)
            } else {
                None
            }
        } else {
            None
        };

        if cli.ascii_logo {
            active_logo = ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
        } else if _config.chafa.unwrap_or(false) || cli.chafa_logo {
            let mut resolved = false;
            if logo::chafa_available() {
                if let Some(path) = &user_logo {
                    if let Some(lines) = logo::get_chafa_logo_lines(path) {
                        active_logo = ActiveLogo::Lines(lines);
                        resolved = true;
                    }
                } else if let Some(distro) = &distro_hint {
                    if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
                        let temp_path = std::env::temp_dir()
                            .join(format!("retch_logo_{}.png", std::process::id()));
                        if std::fs::write(&temp_path, bytes).is_ok() {
                            if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
                                active_logo = ActiveLogo::Lines(lines);
                                resolved = true;
                            }
                            let _ = std::fs::remove_file(&temp_path);
                        }
                    }
                }
            }
            if !resolved {
                active_logo =
                    ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
            }
        } else {
            let mut resolved = false;

            // Kitty
            #[cfg(feature = "graphics")]
            if !resolved && logo::supports_kitty() {
                if let Some(path) = &user_logo {
                    if let Ok(bytes) = std::fs::read(path) {
                        let h = graphical_logo_height_lines(&bytes);
                        active_logo = ActiveLogo::Kitty(bytes, h);
                        resolved = true;
                    }
                } else if let Some(distro) = &distro_hint {
                    if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
                        let h = graphical_logo_height_lines(bytes);
                        active_logo = ActiveLogo::Kitty(bytes.to_vec(), h);
                        resolved = true;
                    }
                }
            }

            // iTerm2
            #[cfg(feature = "graphics")]
            if !resolved && logo::supports_iterm2() {
                if let Some(path) = &user_logo {
                    if let Ok(bytes) = std::fs::read(path) {
                        let h = graphical_logo_height_lines(&bytes);
                        active_logo = ActiveLogo::Iterm2(bytes, h);
                        resolved = true;
                    }
                } else if let Some(distro) = &distro_hint {
                    if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
                        let h = graphical_logo_height_lines(bytes);
                        active_logo = ActiveLogo::Iterm2(bytes.to_vec(), h);
                        resolved = true;
                    }
                }
            }

            // Sixel
            #[cfg(feature = "graphics")]
            if !resolved && logo::supports_sixel() {
                if let Some(path) = &user_logo {
                    if let Ok(bytes) = std::fs::read(path) {
                        let h = graphical_logo_height_lines(&bytes);
                        active_logo = ActiveLogo::Sixel(bytes, h);
                        resolved = true;
                    }
                } else if let Some(distro) = &distro_hint {
                    if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
                        let h = graphical_logo_height_lines(bytes);
                        active_logo = ActiveLogo::Sixel(bytes.to_vec(), h);
                        resolved = true;
                    }
                }
            }

            // Chafa
            if !resolved && logo::chafa_available() {
                if let Some(path) = &user_logo {
                    if let Some(lines) = logo::get_chafa_logo_lines(path) {
                        active_logo = ActiveLogo::Lines(lines);
                        resolved = true;
                    }
                } else if let Some(distro) = &distro_hint {
                    if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
                        // Write temp logo and read lines via chafa
                        let temp_path = std::env::temp_dir()
                            .join(format!("retch_logo_{}.png", std::process::id()));
                        if std::fs::write(&temp_path, bytes).is_ok() {
                            if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
                                active_logo = ActiveLogo::Lines(lines);
                                resolved = true;
                            }
                            let _ = std::fs::remove_file(&temp_path);
                        }
                    }
                }
            }

            // Fallback to ASCII lines
            if !resolved {
                active_logo =
                    ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
            }
        }
    }

    // Helper to strip ANSI codes and calculate visible length
    let visible_len = |s: &str| -> usize {
        let mut count = 0;
        let mut in_esc = false;
        for c in s.chars() {
            if c == '\x1b' {
                in_esc = true;
            } else if in_esc {
                if c.is_ascii_alphabetic() {
                    in_esc = false;
                }
            } else {
                count += 1;
            }
        }
        count
    };

    let max_text_width = info_lines
        .iter()
        .map(|line| visible_len(line))
        .max()
        .unwrap_or(0);
    let text_column_width = std::cmp::max(max_text_width + 4, 45);

    let max_logo_width = match &active_logo {
        ActiveLogo::Lines(logo_lines) => logo_lines
            .iter()
            .map(|line| visible_len(line))
            .max()
            .unwrap_or(0),
        ActiveLogo::Kitty(_, _) | ActiveLogo::Iterm2(_, _) | ActiveLogo::Sixel(_, _) => 40,
        ActiveLogo::None => 0,
    };

    let side_by_side =
        show_logo && term_width >= 95 && term_width >= (text_column_width + max_logo_width);

    println!(); // leading newline

    if side_by_side {
        match active_logo {
            ActiveLogo::Lines(logo_lines) => {
                let max_lines = std::cmp::max(info_lines.len(), logo_lines.len());
                for i in 0..max_lines {
                    let info_line = info_lines.get(i).cloned().unwrap_or_default();
                    let logo_line = logo_lines.get(i).cloned().unwrap_or_default();
                    let vis_len = visible_len(&info_line);
                    let padding = if vis_len < text_column_width {
                        " ".repeat(text_column_width - vis_len)
                    } else {
                        String::new()
                    };
                    println!("{}{}{}", info_line, padding, logo_line);
                }
            }
            ActiveLogo::Kitty(bytes, height_lines) => {
                for line in &info_lines {
                    println!("{}", line);
                }
                let num_lines = info_lines.len();
                print!("\x1b7"); // DEC save cursor
                if num_lines > 0 {
                    print!("\x1b[{}A", num_lines); // Move up
                }
                print!("\x1b[{}C", text_column_width); // Move right
                logo::print_graphical_logo(&bytes);
                print!("\x1b8"); // DEC restore cursor
                                 // Advance past the logo's bottom edge if it extends below the text.
                let overflow = height_lines.saturating_sub(num_lines);
                if overflow > 0 {
                    print!("\x1b[{}B", overflow);
                }
            }
            ActiveLogo::Iterm2(bytes, height_lines) => {
                for line in &info_lines {
                    println!("{}", line);
                }
                let num_lines = info_lines.len();
                print!("\x1b7"); // DEC save cursor
                if num_lines > 0 {
                    print!("\x1b[{}A", num_lines); // Move up
                }
                print!("\x1b[{}C", text_column_width); // Move right
                logo::print_iterm2_logo(&bytes);
                print!("\x1b8"); // DEC restore cursor
                let overflow = height_lines.saturating_sub(num_lines);
                if overflow > 0 {
                    print!("\x1b[{}B", overflow);
                }
            }
            ActiveLogo::Sixel(bytes, height_lines) => {
                for line in &info_lines {
                    println!("{}", line);
                }
                let num_lines = info_lines.len();
                print!("\x1b7"); // DEC save cursor
                if num_lines > 0 {
                    print!("\x1b[{}A", num_lines); // Move up
                }
                print!("\x1b[{}C", text_column_width); // Move right
                logo::print_sixel_logo(&bytes);
                print!("\x1b8"); // DEC restore cursor
                let overflow = height_lines.saturating_sub(num_lines);
                if overflow > 0 {
                    print!("\x1b[{}B", overflow);
                }
            }
            ActiveLogo::None => {
                for line in &info_lines {
                    println!("{}", line);
                }
            }
        }
    } else {
        // Narrow or no-logo fallback: print logo, then print data
        match active_logo {
            ActiveLogo::Lines(logo_lines) => {
                for line in logo_lines {
                    println!("{}", line);
                }
                println!();
            }
            ActiveLogo::Kitty(bytes, _) => {
                logo::print_graphical_logo(&bytes);
                println!();
            }
            ActiveLogo::Iterm2(bytes, _) => {
                logo::print_iterm2_logo(&bytes);
                println!();
            }
            ActiveLogo::Sixel(bytes, _) => {
                logo::print_sixel_logo(&bytes);
                println!();
            }
            ActiveLogo::None => {}
        }
        for line in &info_lines {
            println!("{}", line);
        }
    }

    Ok(())
}

/// Returns the highest temperature per physical category from a raw sensor list.
///
/// Input strings are formatted as `"label: 83°C"`. Output is one entry per
/// detected category (CPU / GPU / NVMe / WiFi / Battery / System), ordered
/// from most to least specific. Used by `--long` mode; `--full` shows the raw list.
fn consolidate_temps(temps: &[String]) -> Vec<String> {
    fn categorize(label: &str) -> &'static str {
        let l = label.to_lowercase();
        if l.contains("cpu")
            || l.contains("core")
            || l.contains("k10temp")
            || l.contains("k8temp")
            || l.contains("coretemp")
            || l.contains("tctl")
            || l.contains("tdie")
            || l.contains("tccd")
            || l.contains("package")
        {
            "CPU"
        } else if l.contains("gpu")
            || l.contains("nouveau")
            || l.contains("radeon")
            || l.contains("amdgpu")
        {
            "GPU"
        } else if l.contains("nvme") || l.contains("nand") {
            "NVMe"
        } else if l.contains("ath")
            || l.contains("wifi")
            || l.contains("wireless")
            || l.contains("wlan")
            || l.contains("iwl")
        {
            "WiFi"
        } else if l.contains("bat") {
            "Battery"
        } else {
            "System"
        }
    }

    let mut max: std::collections::HashMap<&str, f32> = std::collections::HashMap::new();
    for s in temps {
        // Parse "some label: 83°C"
        if let Some((label_part, val_part)) = s.rsplit_once(':') {
            let val_str = val_part.trim().trim_end_matches("°C");
            if let Ok(val) = val_str.parse::<f32>() {
                let cat = categorize(label_part.trim());
                let entry = max.entry(cat).or_insert(f32::NEG_INFINITY);
                if val > *entry {
                    *entry = val;
                }
            }
        }
    }

    const ORDER: &[&str] = &["CPU", "GPU", "NVMe", "WiFi", "Battery", "System"];
    ORDER
        .iter()
        .filter_map(|cat| max.get(cat).map(|v| format!("{}: {:.0}°C", cat, v)))
        .collect()
}

/// Formats a raw uptime string (in seconds) into a human-readable duration.
///
/// Example: "45224s" -> "12h 33m 44s"
fn format_uptime(uptime: &str) -> String {
    // Parse the uptime string (e.g. "45224s")
    let seconds: u64 = uptime.trim_end_matches('s').parse().unwrap_or(0);

    let years = seconds / (365 * 24 * 3600);
    let days = (seconds % (365 * 24 * 3600)) / (24 * 3600);
    let hours = (seconds % (24 * 3600)) / 3600;
    let minutes = (seconds % 3600) / 60;
    let secs = seconds % 60;

    let mut parts = Vec::new();
    if years > 0 {
        parts.push(format!("{}y", years));
    }
    if days > 0 {
        parts.push(format!("{}d", days));
    }
    if hours > 0 {
        parts.push(format!("{}h", hours));
    }
    if minutes > 0 {
        parts.push(format!("{}m", minutes));
    }
    if secs > 0 || parts.is_empty() {
        parts.push(format!("{}s", secs));
    }

    parts.join(" ")
}

/// Returns the height in terminal rows a graphical logo image will occupy.
///
/// Uses TIOCGWINSZ pixel dimensions on Unix to get the real cell height.
/// Falls back to 20px per cell when the terminal doesn't report pixel dims.
#[cfg(feature = "graphics")]
fn graphical_logo_height_lines(bytes: &[u8]) -> usize {
    let img_h = image::load_from_memory(bytes)
        .map(|img| img.height() as usize)
        .unwrap_or(384);
    let cell_h = terminal_cell_height_px();
    img_h.div_ceil(cell_h)
}

/// Returns the terminal cell height in pixels via TIOCGWINSZ, or 20 as fallback.
fn terminal_cell_height_px() -> usize {
    #[cfg(unix)]
    {
        use std::mem::MaybeUninit;
        let mut ws: libc::winsize = unsafe { MaybeUninit::zeroed().assume_init() };
        let ret = unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) };
        if ret == 0 && ws.ws_row > 0 && ws.ws_ypixel > 0 {
            return ws.ws_ypixel as usize / ws.ws_row as usize;
        }
    }
    20
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_consolidate_temps_basic() {
        let raw = vec![
            "k10temp Tctl: 83°C".to_string(),
            "amdgpu edge: 65°C".to_string(),
            "nvme Composite: 62°C".to_string(),
            "ath11k_hwmon temp1: 58°C".to_string(),
            "acpitz temp1: 77°C".to_string(),
        ];
        let result = consolidate_temps(&raw);
        assert_eq!(
            result,
            vec![
                "CPU: 83°C",
                "GPU: 65°C",
                "NVMe: 62°C",
                "WiFi: 58°C",
                "System: 77°C"
            ]
        );
    }

    #[test]
    fn test_consolidate_temps_highest_wins() {
        let raw = vec![
            "thinkpad CPU: 83°C".to_string(),
            "k10temp Tctl: 79°C".to_string(),
            "nvme Composite: 62°C".to_string(),
            "nvme Sensor 1: 59°C".to_string(),
            "nvme Sensor 2: 56°C".to_string(),
        ];
        let result = consolidate_temps(&raw);
        assert!(result.contains(&"CPU: 83°C".to_string()));
        assert!(result.contains(&"NVMe: 62°C".to_string()));
        assert!(!result
            .iter()
            .any(|s| s.contains("79") || s.contains("59") || s.contains("56")));
    }

    #[test]
    fn test_consolidate_temps_order() {
        let raw = vec![
            "acpitz: 60°C".to_string(),
            "nvme: 55°C".to_string(),
            "amdgpu edge: 65°C".to_string(),
            "k10temp Tctl: 80°C".to_string(),
        ];
        let result = consolidate_temps(&raw);
        let cpu_pos = result.iter().position(|s| s.starts_with("CPU"));
        let gpu_pos = result.iter().position(|s| s.starts_with("GPU"));
        let nvme_pos = result.iter().position(|s| s.starts_with("NVMe"));
        let sys_pos = result.iter().position(|s| s.starts_with("System"));
        assert!(cpu_pos < gpu_pos);
        assert!(gpu_pos < nvme_pos);
        assert!(nvme_pos < sys_pos);
    }

    #[test]
    fn test_consolidate_temps_empty() {
        assert!(consolidate_temps(&[]).is_empty());
    }

    #[test]
    fn test_format_uptime() {
        assert_eq!(format_uptime("60s"), "1m");
        assert_eq!(format_uptime("3600s"), "1h");
        assert_eq!(format_uptime("3661s"), "1h 1m 1s");
        assert_eq!(format_uptime("86400s"), "1d");
        assert_eq!(format_uptime("90061s"), "1d 1h 1m 1s");
        assert_eq!(format_uptime("31536000s"), "1y");
        assert_eq!(format_uptime("31626061s"), "1y 1d 1h 1m 1s");
        assert_eq!(format_uptime("0s"), "0s");
    }
}