1use crate::cli::Cli;
9use crate::config::Config;
10use crate::fetch::SystemInfo;
11use crate::fields::{self, Mode};
12use crate::logo;
13use crate::theme::{colorize_nested, Theme, ACTIVE_IFACE_PREFIX};
14use retch_sysinfo::network::NetworkInterface;
15
16fn should_show_logo(
30 config_show_logo: Option<bool>,
31 no_logo: bool,
32 ascii_logo: bool,
33 stdout_is_tty: bool,
34) -> bool {
35 if no_logo {
36 return false; }
38 if ascii_logo {
39 return true; }
41 config_show_logo.unwrap_or(true) && stdout_is_tty }
43
44struct LayoutPlan {
53 side_by_side: bool,
54 text_column_width: usize,
55 logo_column: usize,
56}
57
58fn plan_layout(
86 info_widths: &[usize],
87 logo_height: usize,
88 logo_width: usize,
89 term_width: usize,
90 show_logo: bool,
91) -> LayoutPlan {
92 let beside_count = info_widths.len().min(logo_height);
93 let max_beside_width = info_widths[..beside_count]
94 .iter()
95 .copied()
96 .max()
97 .unwrap_or(0);
98 let text_column_width = if term_width >= 95 {
99 (term_width.saturating_sub(logo_width + 4))
100 .min(std::cmp::max(max_beside_width + 4, 45))
101 .clamp(45, 65)
102 } else {
103 std::cmp::max(max_beside_width + 4, 45)
104 };
105 let side_by_side =
106 show_logo && term_width >= 95 && term_width >= text_column_width + logo_width;
107 let logo_column = term_width.saturating_sub(logo_width).max(text_column_width);
110 LayoutPlan {
111 side_by_side,
112 text_column_width,
113 logo_column,
114 }
115}
116
117pub fn visible_len(s: &str) -> usize {
139 use unicode_width::UnicodeWidthStr;
140
141 let mut visible = String::with_capacity(s.len());
142 let mut in_esc = false;
143 for c in s.chars() {
144 if c == '\x1b' {
145 in_esc = true;
146 } else if in_esc {
147 if c.is_ascii_alphabetic() {
148 in_esc = false;
149 }
150 } else {
151 visible.push(c);
152 }
153 }
154 visible.width()
155}
156
157pub fn wrap_info_line(line: &str, max_width: usize) -> Vec<String> {
163 let vis_len = visible_len(line);
164 if vis_len <= max_width || max_width < 20 {
165 return vec![line.to_string()];
166 }
167
168 let prefix_len = if let Some(idx) = line.find(':') {
169 let prefix_sub = &line[..=idx];
170 let extra_space = if line[idx + 1..].starts_with(' ') {
171 1
172 } else {
173 0
174 };
175 visible_len(prefix_sub) + extra_space
176 } else {
177 4
178 };
179
180 let indent = " ".repeat(prefix_len.min(max_width / 2));
181
182 if line.contains(", ") {
184 let parts: Vec<&str> = line.split(", ").collect();
185 let mut lines = Vec::new();
186 let mut current = String::new();
187
188 for (i, part) in parts.iter().enumerate() {
189 let item = if i == 0 {
190 part.to_string()
191 } else {
192 format!(", {}", part)
193 };
194 let item_vis = visible_len(&item);
195
196 if current.is_empty() || visible_len(¤t) + item_vis <= max_width {
197 current.push_str(&item);
198 } else {
199 lines.push(format!("{current},"));
204 current = format!("{}{}", indent, part);
205 }
206 }
207 if !current.is_empty() {
208 lines.push(current);
209 }
210 if lines.iter().all(|l| visible_len(l) <= max_width + 10) {
211 return carry_sgr_across_lines(lines);
212 }
213 }
214
215 let raw_words: Vec<&str> = line.split_whitespace().collect();
217 let mut words: Vec<String> = Vec::new();
218 let mut idx = 0;
219 while idx < raw_words.len() {
220 if raw_words[idx] == "RX:"
221 && idx + 3 < raw_words.len()
222 && raw_words.iter().skip(idx).any(|&w| w == "TX:")
223 {
224 let rx_tx = format!(
225 "{} {} {} {} {} {}",
226 raw_words[idx],
227 raw_words[idx + 1],
228 raw_words[idx + 2],
229 raw_words[idx + 3],
230 raw_words.get(idx + 4).copied().unwrap_or(""),
231 raw_words.get(idx + 5).copied().unwrap_or("")
232 );
233 words.push(rx_tx.trim().to_string());
234 idx += if idx + 5 < raw_words.len() { 6 } else { 4 };
235 continue;
236 }
237 words.push(raw_words[idx].to_string());
238 idx += 1;
239 }
240
241 let mut lines = Vec::new();
242 let mut current = String::new();
243
244 for word in words {
245 let word_vis = visible_len(&word);
246 if current.is_empty() {
247 current.push_str(&word);
248 } else if visible_len(¤t) + 1 + word_vis <= max_width {
249 current.push(' ');
250 current.push_str(&word);
251 } else {
252 lines.push(current);
253 current = format!("{}{}", indent, word);
254 }
255 }
256 if !current.is_empty() {
257 lines.push(current);
258 }
259
260 if lines.is_empty() {
261 vec![line.to_string()]
262 } else {
263 carry_sgr_across_lines(lines)
266 }
267}
268
269fn active_sgr_after(s: &str, entry: Option<String>) -> Option<String> {
276 let mut active = entry;
277 let bytes = s.as_bytes();
278 let mut i = 0;
279 while i < bytes.len() {
280 if bytes[i] != 0x1b {
281 i += 1;
282 continue;
283 }
284 let start = i;
285 i += 1;
286 while i < bytes.len() && !bytes[i].is_ascii_alphabetic() {
287 i += 1;
288 }
289 if i < bytes.len() {
290 let seq = &s[start..=i];
291 if seq.ends_with('m') {
292 active = if seq == "\x1b[0m" || seq == "\x1b[39m" {
293 None
294 } else {
295 Some(seq.to_string())
296 };
297 }
298 i += 1;
299 }
300 }
301 active
302}
303
304fn carry_sgr_across_lines(lines: Vec<String>) -> Vec<String> {
317 let mut active: Option<String> = None;
318 let mut out = Vec::with_capacity(lines.len());
319 for line in lines {
320 let reopened = match &active {
321 Some(sgr) => format!("{sgr}{line}"),
322 None => line.clone(),
323 };
324 let end_state = active_sgr_after(&line, active.clone());
325 active = end_state.clone();
326 out.push(match end_state {
327 Some(_) => format!("{reopened}\x1b[39m"),
329 None => reopened,
330 });
331 }
332 out
333}
334
335fn split_wifi_line(wifi: &str) -> (&str, Option<&str>) {
344 match wifi.split_once(" - ") {
345 Some((hardware, connection)) => (hardware, Some(connection)),
346 None => (wifi, None),
347 }
348}
349
350fn compose_side_by_side_row(info_line: &str, logo_line: &str, logo_column: usize) -> String {
365 let vis_len = visible_len(info_line);
366 if logo_line.is_empty() || vis_len >= logo_column {
367 return format!("{info_line}{logo_line}");
368 }
369 format!(
370 "{info_line}{}{logo_line}",
371 " ".repeat(logo_column - vis_len)
372 )
373}
374
375fn graphical_side_by_side_prelude(logo_column: usize, logo_rows: usize) -> String {
390 let mut prelude = String::new();
391 if logo_rows > 0 {
392 prelude.push_str(&"\n".repeat(logo_rows));
393 prelude.push_str(&format!("\x1b[{}A", logo_rows));
394 }
395 prelude.push_str(&format!("\x1b[{}C\x1b7", logo_column));
396 prelude
397}
398
399fn render_graphical_side_by_side(
415 logo_column: usize,
416 info_lines: &[String],
417 logo_rows: usize,
418 draw: impl FnOnce(),
419) {
420 use std::io::Write;
421 print!("{}", graphical_side_by_side_prelude(logo_column, logo_rows));
424 draw(); print!("\x1b8\r");
426 for line in info_lines {
427 println!("{}", line);
428 }
429 for _ in info_lines.len()..logo_rows {
432 println!();
433 }
434 let _ = std::io::stdout().flush();
435}
436
437fn partition_net_lines<'a>(
452 nets: &'a [NetworkInterface],
453 active: Option<&str>,
454) -> (Vec<&'a NetworkInterface>, Vec<&'a NetworkInterface>) {
455 nets.iter().partition(|n| active == Some(n.name.as_str()))
456}
457
458fn choose_net_line<'a>(
467 nets: &'a [NetworkInterface],
468 active: Option<&str>,
469) -> Option<&'a NetworkInterface> {
470 nets.iter()
471 .find(|n| active == Some(n.name.as_str()))
472 .or_else(|| nets.iter().find(|n| n.is_up))
473}
474
475pub fn display(info: &SystemInfo, cli: &Cli, config: &Config) -> anyhow::Result<()> {
476 let _config = config;
477 let theme_name = _config.theme.as_deref().or(cli.theme.as_deref());
478 let mut theme = match theme_name {
479 Some(name) => Theme::from_name(name),
480 None => Theme::detect_system_theme(), };
482
483 if let Some(custom) = &_config.custom_theme {
485 theme = Theme::with_custom_overrides(theme, custom);
486 }
487
488 let term_size = terminal_size::terminal_size();
490 let term_width = if let Some((terminal_size::Width(w), _)) = term_size {
491 w as usize
492 } else {
493 80
494 };
495 let stdout_is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
498
499 let show_logo = should_show_logo(
500 _config.show_logo,
501 cli.no_logo,
502 cli.ascii_logo,
503 stdout_is_tty,
504 );
505
506 let allowed_fields: Option<Vec<String>> = if cli.full {
511 Some(fields::fields_for(Mode::Full))
512 } else if cli.long {
513 Some(fields::fields_for(Mode::Long))
514 } else if cli.short {
515 Some(fields::fields_for(Mode::Short))
516 } else if let Some(fields) = &_config.fields {
517 Some(fields.iter().map(|s| s.to_lowercase()).collect())
518 } else {
519 Some(fields::fields_for(Mode::Standard))
520 };
521
522 let should_show = |label: &str| -> bool {
523 match &allowed_fields {
524 Some(fields) => {
525 let norm_label = label.to_lowercase().replace(['-', '_'], " ");
526 let norm_label_no_spaces = norm_label.replace(' ', "");
527 fields.iter().any(|f| {
528 let norm_f = f.to_lowercase().replace(['-', '_'], " ");
529 norm_f == norm_label
530 || norm_f.replace(' ', "") == norm_label_no_spaces
531 || (norm_label == "dns server" && norm_f == "dns")
533 || (norm_label == "memory usage" && norm_f == "memory")
535 || (norm_label == "wi fi link" && norm_f == "wifi")
537 })
538 }
539 None => true,
540 }
541 };
542
543 let label_width = 10;
545 let mut info_lines = Vec::new();
546 let mut print_line = |label: &str, value: &str| {
547 if should_show(label) {
548 info_lines.push(format!(
549 "{:>width$}{} {}",
550 theme.color_label(label),
551 theme.color_separator(":"),
552 theme.color_value(value),
553 width = label_width
554 ));
555 }
556 };
557
558 print_line("OS", &info.os);
560 if let Some(kernel) = &info.kernel {
561 print_line("Kernel", kernel);
562 }
563 if let Some(host) = &info.hostname {
564 print_line("Host", host);
565 }
566 if let Some(domain) = &info.domain {
567 print_line("Domain", domain);
568 }
569 if should_show("domain-search") {
570 for entry in &info.domain_search {
571 print_line("Domain Search", entry);
572 }
573 }
574 if let Some(chassis) = &info.chassis {
575 print_line("Chassis", chassis);
576 }
577 if let Some(init) = &info.init_system {
578 print_line("Init", init);
579 }
580 if let Some(locale) = &info.locale {
581 print_line("Locale", locale);
582 }
583 print_line("Arch", &info.arch);
584 if info.users > 0 {
588 print_line("Users", &info.users.to_string());
589 }
590 if let Some(pkgs) = info.packages {
591 if pkgs > 0 {
592 print_line("Packages", &pkgs.to_string());
593 }
594 }
595 if let Some(user) = &info.current_user {
596 print_line("User", user);
597 }
598 let uptime_str = format_uptime(&info.uptime);
600 let boot_display = format!("{} since {}", uptime_str, info.boot_time);
601 print_line("Uptime", &boot_display);
602
603 print_line("CPU", &format!("{} ({})", info.cpu, info.cpu_core_info));
605 if let Some(freq) = &info.cpu_freq {
606 print_line("CPU Freq", freq);
607 }
608 if let Some(cache) = &info.cpu_cache {
609 print_line("CPU Cache", cache);
610 }
611 if let Some(usage) = &info.cpu_usage {
612 print_line("CPU Usage", usage);
613 }
614 if let Some(motherboard) = &info.motherboard {
615 print_line("Motherboard", motherboard);
616 }
617 if let Some(bios) = &info.bios {
618 print_line("BIOS", bios);
619 }
620 if let Some(bootmgr) = &info.bootmgr {
621 print_line("Bootmgr", bootmgr);
622 }
623 if let Some(tpm) = &info.tpm {
624 print_line("TPM", tpm);
625 }
626 if should_show("GPU") {
627 for gpu in &info.gpu {
628 print_line("GPU", gpu);
629 }
630 }
631 if should_show("Display") {
632 for display in &info.displays {
633 print_line("Display", display);
634 }
635 }
636 if let Some(brightness) = &info.brightness {
637 print_line("Brightness", brightness);
638 }
639 if let Some(audio) = &info.audio {
640 print_line("Audio", audio);
641 }
642 if should_show("Camera") {
643 for cam in &info.camera {
644 print_line("Camera", cam);
645 }
646 }
647 if should_show("Gamepad") {
648 for gp in &info.gamepad {
649 print_line("Gamepad", gp);
650 }
651 }
652 if should_show("Keyboard") {
653 for kb in &info.keyboard {
654 print_line("Keyboard", kb);
655 }
656 }
657 if should_show("Mouse") {
658 for m in &info.mouse {
659 print_line("Mouse", m);
660 }
661 }
662 if let Some(wifi) = &info.wifi {
663 let (hardware, connection) = split_wifi_line(wifi);
666 print_line("Wi-Fi", hardware);
667 if let Some(conn) = connection {
668 print_line("Wi-Fi Link", conn);
669 }
670 }
671 if let Some(bt) = &info.bluetooth {
672 print_line("Bluetooth", bt);
673 }
674 if let Some(bat) = &info.battery {
675 print_line("Battery", bat);
676 }
677 if let Some(power) = &info.power_adapter {
678 print_line("Power Adapter", power);
679 }
680 print_line("Memory Usage", &info.memory);
681 if let Some(phys_mem) = &info.physical_memory {
682 print_line("Phys Mem", phys_mem);
683 }
684 print_line("Swap", &info.swap);
685 print_line("Procs", &info.processes.to_string());
686 if let Some(load) = &info.load_avg {
687 print_line("Load", load);
688 }
689 if should_show("Disk") {
690 for disk in &info.disks {
691 print_line("Disk", disk);
692 }
693 }
694 if should_show("Phys Disk") {
695 for disk in &info.physical_disks {
696 print_line("Phys Disk", disk);
697 }
698 }
699 if should_show("Disk IO") {
700 for io in &info.disk_io {
701 print_line("Disk IO", io);
702 }
703 }
704 if should_show("Btrfs") {
705 for vol in &info.btrfs {
706 print_line("Btrfs", vol);
707 }
708 }
709 if should_show("Zpool") {
710 for pool in &info.zpool {
711 print_line("Zpool", pool);
712 }
713 }
714 if should_show("Temp") {
715 if cli.full {
716 for temp in &info.temps {
717 print_line("Temp", temp);
718 }
719 } else {
720 for temp in consolidate_temps(&info.temps) {
721 print_line("Temp", &temp);
722 }
723 }
724 }
725
726 if should_show("Net") {
728 let active = info.active_interface.as_deref();
729 if cli.long || cli.full {
730 let (active_nets, others) = partition_net_lines(&info.networks, active);
731 for net in active_nets {
732 print_line("Net", &colorize_nested(&net.line, ACTIVE_IFACE_PREFIX));
736 }
737 for net in others {
738 print_line("Net", &net.line);
739 }
740 } else if let Some(net) = choose_net_line(&info.networks, active) {
741 print_line("Net", &net.line);
742 }
743 }
744 if should_show("Net IO") {
745 for io in &info.net_io {
746 print_line("Net IO", io);
747 }
748 }
749 if let Some(ip) = &info.public_ip {
750 print_line("Public IP", ip);
751 }
752 if !info.dns.is_empty() {
753 print_line("DNS Server", &info.dns.join(", "));
754 }
755
756 if let Some(shell) = &info.shell {
758 print_line("Shell", shell);
759 }
760 if let Some(editor) = &info.editor {
761 print_line("Editor", editor);
762 }
763 if let Some(term) = &info.terminal {
764 print_line("Terminal", term);
765 }
766 if let Some(ts) = &info.terminal_size {
767 print_line("Terminal Size", ts);
768 }
769 if let Some(de) = &info.desktop {
770 print_line("Desktop", de);
771 }
772 if let Some(wm) = &info.wm {
773 let duplicate = info
774 .desktop
775 .as_deref()
776 .map(|de| de.to_lowercase() == wm.to_lowercase())
777 .unwrap_or(false);
778 if !duplicate {
779 print_line("WM", wm);
780 }
781 }
782 if let Some(wm_theme) = &info.wm_theme {
783 print_line("WM Theme", wm_theme);
784 }
785 if let Some(wallpaper) = &info.wallpaper {
786 print_line("Wallpaper", wallpaper);
787 }
788 if let Some(lm) = &info.login_manager {
789 print_line("Login Manager", lm);
790 }
791 if let Some(player) = &info.player {
792 print_line("Player", player);
793 }
794 if let Some(media) = &info.media {
795 print_line("Media", media);
796 }
797 if let Some(ui_theme) = &info.ui_theme {
798 print_line("Theme", ui_theme);
799 }
800 if let Some(icons) = &info.icons {
801 print_line("Icons", icons);
802 }
803 if let Some(cursor) = &info.cursor {
804 print_line("Cursor", cursor);
805 }
806 if let Some(font) = &info.font {
807 print_line("Font", font);
808 }
809 if let Some(term_font) = &info.terminal_font {
810 print_line("Terminal Font", term_font);
811 }
812 if let Some(term_theme) = &info.terminal_theme {
813 print_line("Terminal Theme", term_theme);
814 }
815 if let Some(weather) = &info.weather {
816 print_line("Weather", weather);
817 }
818
819 enum ActiveLogo {
821 Lines(Vec<String>),
822 Kitty(Vec<u8>, usize, usize), Iterm2(Vec<u8>, usize, usize),
824 Sixel(Vec<u8>, usize, usize),
825 None,
826 }
827
828 let mut active_logo = ActiveLogo::None;
829
830 if show_logo {
831 let distro_hint = _config.logo.clone().or_else(logo::detect_distro);
832 let user_logo = if let Some(config_dir) = dirs::config_dir() {
833 let p = config_dir.join("retch").join("logo.png");
834 if p.exists() {
835 Some(p)
836 } else {
837 None
838 }
839 } else {
840 None
841 };
842
843 if cli.ascii_logo {
844 active_logo = ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
845 } else if _config.chafa.unwrap_or(false) || cli.chafa_logo {
846 let mut resolved = false;
847 if logo::chafa_available() {
848 if let Some(path) = &user_logo {
849 if let Some(lines) = logo::get_chafa_logo_lines(path) {
850 active_logo = ActiveLogo::Lines(lines);
851 resolved = true;
852 }
853 } else if let Some(distro) = &distro_hint {
854 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
855 let temp_path = std::env::temp_dir()
856 .join(format!("retch_logo_{}.png", std::process::id()));
857 if std::fs::write(&temp_path, bytes).is_ok() {
858 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
859 active_logo = ActiveLogo::Lines(lines);
860 resolved = true;
861 }
862 let _ = std::fs::remove_file(&temp_path);
863 }
864 }
865 }
866 }
867 if !resolved {
868 active_logo =
869 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
870 }
871 } else {
872 let mut resolved = false;
873
874 #[cfg(feature = "graphics")]
876 if !resolved && logo::supports_kitty() {
877 if let Some(path) = &user_logo {
878 if let Ok(bytes) = std::fs::read(path) {
879 let (cols, rows) = graphical_logo_cells(&bytes);
880 active_logo = ActiveLogo::Kitty(bytes, cols, rows);
881 resolved = true;
882 }
883 } else if let Some(distro) = &distro_hint {
884 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
885 let (cols, rows) = graphical_logo_cells(bytes);
886 active_logo = ActiveLogo::Kitty(bytes.to_vec(), cols, rows);
887 resolved = true;
888 }
889 }
890 }
891
892 #[cfg(feature = "graphics")]
894 if !resolved && logo::supports_iterm2() {
895 if let Some(path) = &user_logo {
896 if let Ok(bytes) = std::fs::read(path) {
897 let (cols, rows) = graphical_logo_cells(&bytes);
898 active_logo = ActiveLogo::Iterm2(bytes, cols, rows);
899 resolved = true;
900 }
901 } else if let Some(distro) = &distro_hint {
902 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
903 let (cols, rows) = graphical_logo_cells(bytes);
904 active_logo = ActiveLogo::Iterm2(bytes.to_vec(), cols, rows);
905 resolved = true;
906 }
907 }
908 }
909
910 #[cfg(feature = "graphics")]
912 if !resolved && logo::supports_sixel() {
913 if let Some(path) = &user_logo {
914 if let Ok(bytes) = std::fs::read(path) {
915 let (cols, rows) = graphical_logo_cells(&bytes);
916 active_logo = ActiveLogo::Sixel(bytes, cols, rows);
917 resolved = true;
918 }
919 } else if let Some(distro) = &distro_hint {
920 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
921 let (cols, rows) = graphical_logo_cells(bytes);
922 active_logo = ActiveLogo::Sixel(bytes.to_vec(), cols, rows);
923 resolved = true;
924 }
925 }
926 }
927
928 if !resolved && logo::chafa_available() {
930 if let Some(path) = &user_logo {
931 if let Some(lines) = logo::get_chafa_logo_lines(path) {
932 active_logo = ActiveLogo::Lines(lines);
933 resolved = true;
934 }
935 } else if let Some(distro) = &distro_hint {
936 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
937 let temp_path = std::env::temp_dir()
939 .join(format!("retch_logo_{}.png", std::process::id()));
940 if std::fs::write(&temp_path, bytes).is_ok() {
941 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
942 active_logo = ActiveLogo::Lines(lines);
943 resolved = true;
944 }
945 let _ = std::fs::remove_file(&temp_path);
946 }
947 }
948 }
949 }
950
951 if !resolved {
953 active_logo =
954 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
955 }
956 }
957 }
958
959 let info_widths: Vec<usize> = info_lines.iter().map(|line| visible_len(line)).collect();
967
968 let (logo_height, max_logo_width) = match &active_logo {
972 ActiveLogo::Lines(logo_lines) => (
973 logo_lines.len(),
974 logo_lines
975 .iter()
976 .map(|line| visible_len(line))
977 .max()
978 .unwrap_or(0),
979 ),
980 ActiveLogo::Kitty(_, cols, rows)
981 | ActiveLogo::Iterm2(_, cols, rows)
982 | ActiveLogo::Sixel(_, cols, rows) => (*rows, *cols),
983 ActiveLogo::None => (0, 0),
984 };
985
986 let LayoutPlan {
989 side_by_side,
990 text_column_width,
991 logo_column,
992 } = plan_layout(
993 &info_widths,
994 logo_height,
995 max_logo_width,
996 term_width,
997 show_logo,
998 );
999
1000 println!(); let formatted_info_lines: Vec<String> = if side_by_side && text_column_width > 15 {
1003 let mut result = Vec::new();
1004 for (i, line) in info_lines.iter().enumerate() {
1005 let max_w = if i < logo_height {
1012 logo_column.saturating_sub(2)
1013 } else {
1014 term_width.saturating_sub(2)
1015 };
1016 result.extend(wrap_info_line(line, max_w));
1017 }
1018 result
1019 } else {
1020 info_lines.clone()
1021 };
1022
1023 if side_by_side {
1024 match active_logo {
1025 ActiveLogo::Lines(logo_lines) => {
1026 let max_lines = std::cmp::max(formatted_info_lines.len(), logo_lines.len());
1027 for i in 0..max_lines {
1028 let info_line = formatted_info_lines.get(i).cloned().unwrap_or_default();
1029 let logo_line = logo_lines.get(i).cloned().unwrap_or_default();
1030 println!(
1031 "{}",
1032 compose_side_by_side_row(&info_line, &logo_line, logo_column)
1033 );
1034 }
1035 }
1036 ActiveLogo::Kitty(bytes, _, logo_rows) => {
1037 render_graphical_side_by_side(
1038 logo_column,
1039 &formatted_info_lines,
1040 logo_rows,
1041 || logo::print_graphical_logo(&bytes),
1042 );
1043 }
1044 ActiveLogo::Iterm2(bytes, _, logo_rows) => {
1045 render_graphical_side_by_side(
1046 logo_column,
1047 &formatted_info_lines,
1048 logo_rows,
1049 || logo::print_iterm2_logo(&bytes),
1050 );
1051 }
1052 ActiveLogo::Sixel(bytes, _, logo_rows) => {
1053 render_graphical_side_by_side(
1054 logo_column,
1055 &formatted_info_lines,
1056 logo_rows,
1057 || logo::print_sixel_logo(&bytes),
1058 );
1059 }
1060 ActiveLogo::None => {
1061 for line in &formatted_info_lines {
1062 println!("{}", line);
1063 }
1064 }
1065 }
1066 } else {
1067 match active_logo {
1069 ActiveLogo::Lines(logo_lines) => {
1070 for line in logo_lines {
1071 println!("{}", line);
1072 }
1073 println!();
1074 }
1075 ActiveLogo::Kitty(bytes, _, _) => {
1076 logo::print_graphical_logo(&bytes);
1077 println!();
1078 }
1079 ActiveLogo::Iterm2(bytes, _, _) => {
1080 logo::print_iterm2_logo(&bytes);
1081 println!();
1082 }
1083 ActiveLogo::Sixel(bytes, _, _) => {
1084 logo::print_sixel_logo(&bytes);
1085 println!();
1086 }
1087 ActiveLogo::None => {}
1088 }
1089 for line in &info_lines {
1090 println!("{}", line);
1091 }
1092 }
1093
1094 Ok(())
1095}
1096
1097fn consolidate_temps(temps: &[String]) -> Vec<String> {
1103 fn categorize(label: &str) -> &'static str {
1104 let l = label.to_lowercase();
1105 if l.contains("cpu")
1106 || l.contains("core")
1107 || l.contains("k10temp")
1108 || l.contains("k8temp")
1109 || l.contains("coretemp")
1110 || l.contains("tctl")
1111 || l.contains("tdie")
1112 || l.contains("tccd")
1113 || l.contains("package")
1114 {
1115 "CPU"
1116 } else if l.contains("gpu")
1117 || l.contains("nouveau")
1118 || l.contains("radeon")
1119 || l.contains("amdgpu")
1120 {
1121 "GPU"
1122 } else if l.contains("nvme") || l.contains("nand") {
1123 "NVMe"
1124 } else if l.contains("ath")
1125 || l.contains("wifi")
1126 || l.contains("wireless")
1127 || l.contains("wlan")
1128 || l.contains("iwl")
1129 {
1130 "WiFi"
1131 } else if l.contains("bat") {
1132 "Battery"
1133 } else {
1134 "System"
1135 }
1136 }
1137
1138 let mut max: std::collections::HashMap<&str, f32> = std::collections::HashMap::new();
1139 for s in temps {
1140 if let Some((label_part, val_part)) = s.rsplit_once(':') {
1142 let val_str = val_part.trim().trim_end_matches("°C");
1143 if let Ok(val) = val_str.parse::<f32>() {
1144 let cat = categorize(label_part.trim());
1145 let entry = max.entry(cat).or_insert(f32::NEG_INFINITY);
1146 if val > *entry {
1147 *entry = val;
1148 }
1149 }
1150 }
1151 }
1152
1153 const ORDER: &[&str] = &["CPU", "GPU", "NVMe", "WiFi", "Battery", "System"];
1154 ORDER
1155 .iter()
1156 .filter_map(|cat| max.get(cat).map(|v| format!("{}: {:.0}°C", cat, v)))
1157 .collect()
1158}
1159
1160fn format_uptime(uptime: &str) -> String {
1164 let seconds: u64 = uptime.trim_end_matches('s').parse().unwrap_or(0);
1166
1167 let years = seconds / (365 * 24 * 3600);
1168 let days = (seconds % (365 * 24 * 3600)) / (24 * 3600);
1169 let hours = (seconds % (24 * 3600)) / 3600;
1170 let minutes = (seconds % 3600) / 60;
1171 let secs = seconds % 60;
1172
1173 let mut parts = Vec::new();
1174 if years > 0 {
1175 parts.push(format!("{}y", years));
1176 }
1177 if days > 0 {
1178 parts.push(format!("{}d", days));
1179 }
1180 if hours > 0 {
1181 parts.push(format!("{}h", hours));
1182 }
1183 if minutes > 0 {
1184 parts.push(format!("{}m", minutes));
1185 }
1186 if secs > 0 || parts.is_empty() {
1187 parts.push(format!("{}s", secs));
1188 }
1189
1190 parts.join(" ")
1191}
1192
1193#[cfg(feature = "graphics")]
1202fn graphical_logo_cells(bytes: &[u8]) -> (usize, usize) {
1203 let (img_w, img_h) = image::load_from_memory(bytes)
1204 .map(|img| (img.width(), img.height()))
1205 .unwrap_or((0, 0));
1206 let fit = logo::logo_cells_for(img_w, img_h);
1207 (fit.cols, fit.rows)
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212 use super::*;
1213
1214 fn net(name: &str, is_up: bool) -> NetworkInterface {
1217 let status = if is_up {
1222 "\x1b[32mUp\x1b[39m"
1223 } else {
1224 "\x1b[31mDown\x1b[39m"
1225 };
1226 NetworkInterface {
1227 name: name.to_string(),
1228 is_up,
1229 line: format!("{name} (10.0.0.1) [{status}] RX: 1.0 MB TX: 1.0 MB"),
1230 }
1231 }
1232
1233 #[test]
1234 fn test_active_interface_is_matched_by_exact_name_not_substring() {
1235 let nets = vec![
1238 net("Wi-Fi-Native WiFi Filter Driver-0000", true),
1239 net("Wi-Fi", true),
1240 ];
1241 let (active, others) = partition_net_lines(&nets, Some("Wi-Fi"));
1242 assert_eq!(active.len(), 1);
1243 assert_eq!(active[0].name, "Wi-Fi");
1244 assert_eq!(others.len(), 1);
1245 assert_eq!(others[0].name, "Wi-Fi-Native WiFi Filter Driver-0000");
1246 }
1247
1248 #[test]
1249 fn test_active_interface_does_not_match_a_vlan_or_veth_sibling() {
1250 let nets = vec![
1253 net("eth0", true),
1254 net("eth0.100", true),
1255 net("veth0a1b2c3", true),
1256 ];
1257 let (active, others) = partition_net_lines(&nets, Some("eth0"));
1258 assert_eq!(active.len(), 1);
1259 assert_eq!(active[0].name, "eth0");
1260 assert_eq!(others.len(), 2);
1261 }
1262
1263 #[test]
1264 fn test_no_active_interface_means_no_line_is_highlighted() {
1265 let nets = vec![net("eth0", true), net("wlan0", true)];
1266 let (active, others) = partition_net_lines(&nets, None);
1267 assert!(active.is_empty());
1268 assert_eq!(others.len(), 2);
1269 }
1270
1271 #[test]
1272 fn test_standard_mode_prefers_the_active_interface() {
1273 let nets = vec![net("docker0", true), net("wlan0", true)];
1274 let chosen = choose_net_line(&nets, Some("wlan0")).expect("a line");
1275 assert_eq!(chosen.name, "wlan0");
1276 }
1277
1278 #[test]
1279 fn test_standard_mode_falls_back_to_the_first_up_interface() {
1280 let nets = vec![net("eth0", false), net("wlan0", true), net("eth1", true)];
1284 let chosen = choose_net_line(&nets, None).expect("a line, not None");
1285 assert_eq!(chosen.name, "wlan0");
1286
1287 let chosen = choose_net_line(&nets, Some("ppp0")).expect("a line, not None");
1289 assert_eq!(chosen.name, "wlan0");
1290 }
1291
1292 #[test]
1293 fn test_standard_mode_reports_nothing_when_every_interface_is_down() {
1294 let nets = vec![net("eth0", false), net("eth1", false)];
1297 assert!(choose_net_line(&nets, None).is_none());
1298 }
1299
1300 #[test]
1303 fn test_show_logo_auto_requires_tty() {
1304 assert!(should_show_logo(None, false, false, true));
1306 assert!(!should_show_logo(None, false, false, false));
1307 }
1308
1309 #[test]
1310 fn test_show_logo_ascii_forces_without_tty() {
1311 assert!(should_show_logo(None, false, true, false));
1313 assert!(should_show_logo(None, false, true, true));
1314 }
1315
1316 #[test]
1317 fn test_show_logo_no_logo_always_wins() {
1318 assert!(!should_show_logo(None, true, true, true));
1320 assert!(!should_show_logo(None, true, false, true));
1321 }
1322
1323 #[test]
1324 fn test_show_logo_config_disable() {
1325 assert!(!should_show_logo(Some(false), false, false, true));
1327 assert!(should_show_logo(Some(false), false, true, false));
1329 }
1330
1331 #[test]
1334 fn test_visible_len_strips_every_escape_form_retch_emits() {
1335 assert_eq!(visible_len("plain"), 5);
1339 assert_eq!(visible_len("\x1b[38;2;1;2;3mabc\x1b[39m"), 3);
1340 assert_eq!(visible_len("\x1b[?25labc"), 3);
1341 assert_eq!(visible_len("\x1b(Babc"), 3);
1342 assert_eq!(visible_len("\x1b[0m \x1b[38;2;0;0;0m\u{2582}"), 2);
1343 }
1344
1345 #[test]
1346 fn test_visible_len_counts_columns_not_characters() {
1347 assert_eq!(visible_len("宇多田ヒカル"), 12); assert_eq!(visible_len("아이유"), 6); assert_eq!(visible_len("Media: 宇多田ヒカル - 花束を君に"), 32);
1353 assert_eq!(visible_len("Media: 아이유 - 밤편지"), 22);
1354
1355 assert_eq!(visible_len("cafe\u{301}"), 4);
1357 assert_eq!(visible_len("café"), 4);
1359
1360 assert_eq!(
1363 visible_len("\x1b[38;2;1;2;3m宇多田\x1b[39m"),
1364 visible_len("宇多田")
1365 );
1366 }
1367
1368 #[test]
1369 fn test_visible_len_ascii_art_and_chafa_symbols_are_one_column_each() {
1370 for line in logo::get_ascii_logo(Some("fedora")) {
1374 let stripped: String = strip_for_test(&line);
1375 assert_eq!(
1376 visible_len(&line),
1377 stripped.chars().count(),
1378 "fedora ASCII logo line is not one column per character: {stripped:?}"
1379 );
1380 }
1381 for sym in [
1383 '\u{2580}', '\u{2584}', '\u{2588}', '\u{258c}', '\u{2596}', '\u{2582}',
1384 ] {
1385 assert_eq!(visible_len(&sym.to_string()), 1, "{sym:?} is not 1 column");
1386 }
1387 }
1388
1389 fn strip_for_test(s: &str) -> String {
1392 let mut out = String::new();
1393 let mut in_esc = false;
1394 for c in s.chars() {
1395 if c == '\x1b' {
1396 in_esc = true;
1397 } else if in_esc {
1398 if c.is_ascii_alphabetic() {
1399 in_esc = false;
1400 }
1401 } else {
1402 out.push(c);
1403 }
1404 }
1405 out
1406 }
1407
1408 const CYAN: &str = "\x1b[38;2;0;255;255m";
1412 const RESET: &str = "\x1b[39m";
1413
1414 #[test]
1415 fn test_wrap_keeps_the_comma_it_split_on() {
1416 let out = wrap_info_line(
1420 "BIOS: American Megatrends International, LLC. HN7306EAC.310 (8//20/07/0)",
1421 40,
1422 );
1423 assert!(out.len() > 1, "expected a wrap, got {out:?}");
1424 assert!(
1425 out[0].ends_with(','),
1426 "separator lost at the break: {:?}",
1427 out[0]
1428 );
1429 let rejoined: String = out
1431 .iter()
1432 .map(|l| l.trim_start().to_string())
1433 .collect::<Vec<_>>()
1434 .join(" ");
1435 assert_eq!(
1436 rejoined,
1437 "BIOS: American Megatrends International, LLC. HN7306EAC.310 (8//20/07/0)"
1438 );
1439 }
1440
1441 #[test]
1442 fn test_wrap_reopens_the_colour_on_every_continuation_line() {
1443 let line =
1447 format!("BIOS: {CYAN}American Megatrends International, LLC. HN7306EAC.310{RESET}");
1448 let out = wrap_info_line(&line, 40);
1449 assert!(out.len() > 1, "expected a wrap, got {out:?}");
1450 for (i, l) in out.iter().enumerate().skip(1) {
1451 assert!(
1452 l.contains(CYAN),
1453 "continuation line {i} has no colour: {l:?}"
1454 );
1455 }
1456 for l in &out {
1458 if l.contains(CYAN) {
1459 assert!(l.ends_with(RESET), "colour left open on {l:?}");
1460 }
1461 }
1462 }
1463
1464 #[test]
1465 fn test_wrap_colour_carry_does_not_change_visible_width() {
1466 let plain = "BIOS: American Megatrends International, LLC. HN7306EAC.310";
1469 let coloured =
1470 format!("BIOS: {CYAN}American Megatrends International, LLC. HN7306EAC.310{RESET}");
1471 let a = wrap_info_line(plain, 40);
1472 let b = wrap_info_line(&coloured, 40);
1473 assert_eq!(a.len(), b.len());
1474 for (x, y) in a.iter().zip(b.iter()) {
1475 assert_eq!(visible_len(x), visible_len(y), "{x:?} vs {y:?}");
1476 }
1477 }
1478
1479 #[test]
1480 fn test_wrap_uncoloured_line_is_untouched_by_the_carry() {
1481 let out = wrap_info_line("Disk: aaaa, bbbb, cccc, dddd, eeee, ffff, gggg, hhhh", 24);
1482 assert!(out.len() > 1);
1483 assert!(
1484 out.iter().all(|l| !l.contains('\x1b')),
1485 "carry injected escapes into an uncoloured line: {out:?}"
1486 );
1487 }
1488
1489 #[test]
1490 fn test_active_sgr_after_tracks_open_and_reset() {
1491 assert_eq!(active_sgr_after("plain", None), None);
1492 assert_eq!(active_sgr_after(CYAN, None), Some(CYAN.to_string()));
1493 assert_eq!(active_sgr_after(&format!("{CYAN}x{RESET}"), None), None);
1494 assert_eq!(active_sgr_after("\x1b[0m", Some(CYAN.into())), None);
1495 assert_eq!(
1497 active_sgr_after("more text", Some(CYAN.into())),
1498 Some(CYAN.to_string())
1499 );
1500 assert_eq!(
1502 active_sgr_after("\x1b[?25l", Some(CYAN.into())),
1503 Some(CYAN.to_string())
1504 );
1505 }
1506
1507 #[test]
1508 fn test_active_sgr_after_takes_the_last_colour_when_nested() {
1509 let green = "\x1b[32m";
1512 let s = format!("{CYAN}[{green}Up{RESET}] RX: 1 MB");
1513 assert_eq!(active_sgr_after(&s, None), None); let s2 = format!("{CYAN}[{green}Up{RESET}]{CYAN} RX: 1 MB");
1515 assert_eq!(active_sgr_after(&s2, None), Some(CYAN.to_string()));
1516 }
1517
1518 #[test]
1521 fn test_row_places_the_logo_at_the_logo_column() {
1522 let row = compose_side_by_side_row("OS: Fedora", "###", 20);
1523 assert_eq!(row, format!("OS: Fedora{}###", " ".repeat(10)));
1524 assert_eq!(visible_len(&row), 23);
1525 }
1526
1527 #[test]
1528 fn test_row_aligns_wide_characters_by_column_not_character_count() {
1529 let latin = compose_side_by_side_row("Locale: en_US.UTF-8", "###", 40);
1534 let cjk = compose_side_by_side_row("Locale: ja_JP.宇多田ヒカル", "###", 40);
1535 assert_eq!(visible_len(&latin), 43);
1536 assert_eq!(
1537 visible_len(&cjk),
1538 43,
1539 "a wide-character info line must not shift the logo column"
1540 );
1541 assert!(latin.ends_with(" ###") && cjk.ends_with(" ###"));
1543 }
1544
1545 #[test]
1546 fn test_row_without_a_logo_gets_no_trailing_padding() {
1547 assert_eq!(compose_side_by_side_row("Net: eth0", "", 40), "Net: eth0");
1549 }
1550
1551 #[test]
1552 fn test_row_with_overlong_info_does_not_underflow() {
1553 let row = compose_side_by_side_row("x".repeat(50).as_str(), "###", 40);
1555 assert_eq!(row, format!("{}###", "x".repeat(50)));
1556 }
1557
1558 #[test]
1559 fn test_row_ignores_ansi_colour_when_measuring() {
1560 let plain = compose_side_by_side_row("abc", "###", 10);
1561 let coloured = compose_side_by_side_row("\x1b[31mabc\x1b[39m", "###", 10);
1562 assert_eq!(visible_len(&plain), visible_len(&coloured));
1563 }
1564
1565 fn realistic_full_widths() -> Vec<usize> {
1570 let mut w = vec![40; 20]; w[13] = 54; w.extend([158, 91, 79, 60, 45, 62]); w
1574 }
1575
1576 #[test]
1577 fn test_layout_long_line_below_logo_stays_side_by_side() {
1578 let p = plan_layout(&realistic_full_widths(), 20, 40, 120, true);
1580 assert!(p.side_by_side);
1581 assert_eq!(p.text_column_width, 58); }
1584
1585 #[test]
1586 fn test_layout_old_behavior_would_have_stacked() {
1587 let widths = realistic_full_widths();
1590 let old_text_col = std::cmp::max(widths.iter().copied().max().unwrap() + 4, 45);
1591 assert!(120 < old_text_col + 40); assert!(plan_layout(&widths, 20, 40, 120, true).side_by_side); }
1594
1595 #[test]
1596 fn test_layout_long_line_within_logo_wraps_and_stays_side_by_side() {
1597 let mut w = vec![40; 20];
1600 w[5] = 158;
1601 let p = plan_layout(&w, 20, 40, 120, true);
1602 assert!(p.side_by_side);
1603 assert_eq!(p.text_column_width, 65);
1604 }
1605
1606 #[test]
1607 fn test_layout_narrow_terminal_stacks() {
1608 assert!(!plan_layout(&[40; 30], 20, 40, 94, true).side_by_side); assert!(!plan_layout(&[40; 30], 20, 40, 80, true).side_by_side);
1610 }
1611
1612 #[test]
1613 fn test_layout_show_logo_false_stacks() {
1614 assert!(!plan_layout(&[40; 30], 20, 40, 200, false).side_by_side);
1615 }
1616
1617 #[test]
1618 fn test_layout_column_floor_and_graphical_width() {
1619 let p = plan_layout(&[10; 25], 20, 40, 100, true);
1621 assert!(p.side_by_side);
1622 assert_eq!(p.text_column_width, 45); }
1624
1625 #[test]
1626 fn test_layout_widened_logo_box_still_fits_at_the_side_by_side_threshold() {
1627 let p = plan_layout(&[10; 25], 10, logo::LOGO_MAX_COLS, 95, true);
1631 assert!(
1632 p.side_by_side,
1633 "a full-width logo must still sit beside the text at 95 columns"
1634 );
1635 assert!(p.text_column_width + logo::LOGO_MAX_COLS <= 95);
1636
1637 let wide = plan_layout(&[120; 25], 10, logo::LOGO_MAX_COLS, 169, true);
1639 assert!(wide.side_by_side);
1640 assert_eq!(wide.text_column_width, 65);
1641 }
1642
1643 #[test]
1644 fn test_layout_logo_taller_than_text() {
1645 let p = plan_layout(&[50, 30, 54], 20, 40, 120, true);
1647 assert!(p.side_by_side);
1648 assert_eq!(p.text_column_width, 58); }
1650
1651 #[test]
1652 fn test_layout_logo_is_flush_with_the_right_margin() {
1653 let p = plan_layout(&realistic_full_widths(), 20, 49, 138, true);
1658 assert!(p.side_by_side);
1659 assert_eq!(p.text_column_width, 58); assert_eq!(p.logo_column, 138 - 49); assert!(
1662 p.logo_column > p.text_column_width,
1663 "the pre-fix behaviour was logo_column == text_column_width"
1664 );
1665 }
1666
1667 #[test]
1668 fn test_layout_right_anchor_never_overlaps_the_text_column() {
1669 for term_width in 95..200 {
1672 let p = plan_layout(&[120; 25], 10, logo::LOGO_MAX_COLS, term_width, true);
1673 if p.side_by_side {
1674 assert!(
1675 p.logo_column >= p.text_column_width,
1676 "logo_column {} < text_column_width {} at {} cols",
1677 p.logo_column,
1678 p.text_column_width,
1679 term_width
1680 );
1681 assert_eq!(p.logo_column + logo::LOGO_MAX_COLS, term_width);
1682 }
1683 }
1684 }
1685
1686 #[test]
1687 fn test_layout_logo_column_does_not_underflow_on_an_oversized_logo() {
1688 let p = plan_layout(&[40; 10], 10, 200, 100, true);
1690 assert!(!p.side_by_side);
1691 assert_eq!(p.logo_column, p.text_column_width);
1692 }
1693
1694 #[test]
1697 fn test_prelude_reserves_rows_before_saving_cursor() {
1698 let p = graphical_side_by_side_prelude(52, 3);
1702 assert_eq!(p, "\n\n\n\x1b[3A\x1b[52C\x1b7");
1703 }
1704
1705 #[test]
1706 fn test_prelude_v068_shape_only_differs_by_reservation() {
1707 let p = graphical_side_by_side_prelude(45, 20);
1710 assert_eq!(
1711 p.replace(&format!("{}\x1b[20A", "\n".repeat(20)), ""),
1712 "\x1b[45C\x1b7"
1713 );
1714 }
1715
1716 #[test]
1717 fn test_prelude_zero_rows_skips_reservation_and_cursor_up() {
1718 let p = graphical_side_by_side_prelude(45, 0);
1721 assert_eq!(p, "\x1b[45C\x1b7");
1722 }
1723
1724 #[test]
1727 fn test_split_wifi_hardware_and_connection() {
1728 let s = "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0] - myssid (5.0 GHz ch36 [↓866 ↑866])";
1730 let (hw, conn) = split_wifi_line(s);
1731 assert_eq!(
1732 hw,
1733 "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0]"
1734 );
1735 assert_eq!(conn, Some("myssid (5.0 GHz ch36 [↓866 ↑866])"));
1736 }
1737
1738 #[test]
1739 fn test_split_wifi_splits_on_first_separator() {
1740 let (hw, conn) = split_wifi_line("Card X [wlan0] - Guest - 5G (5 GHz)");
1743 assert_eq!(hw, "Card X [wlan0]");
1744 assert_eq!(conn, Some("Guest - 5G (5 GHz)"));
1745 }
1746
1747 #[test]
1748 fn test_split_wifi_connection_only_fallback() {
1749 let (hw, conn) = split_wifi_line("myssid (300 Mbps)");
1751 assert_eq!(hw, "myssid (300 Mbps)");
1752 assert_eq!(conn, None);
1753 }
1754
1755 #[test]
1756 fn test_consolidate_temps_basic() {
1757 let raw = vec![
1758 "k10temp Tctl: 83°C".to_string(),
1759 "amdgpu edge: 65°C".to_string(),
1760 "nvme Composite: 62°C".to_string(),
1761 "ath11k_hwmon temp1: 58°C".to_string(),
1762 "acpitz temp1: 77°C".to_string(),
1763 ];
1764 let result = consolidate_temps(&raw);
1765 assert_eq!(
1766 result,
1767 vec![
1768 "CPU: 83°C",
1769 "GPU: 65°C",
1770 "NVMe: 62°C",
1771 "WiFi: 58°C",
1772 "System: 77°C"
1773 ]
1774 );
1775 }
1776
1777 #[test]
1778 fn test_consolidate_temps_highest_wins() {
1779 let raw = vec![
1780 "thinkpad CPU: 83°C".to_string(),
1781 "k10temp Tctl: 79°C".to_string(),
1782 "nvme Composite: 62°C".to_string(),
1783 "nvme Sensor 1: 59°C".to_string(),
1784 "nvme Sensor 2: 56°C".to_string(),
1785 ];
1786 let result = consolidate_temps(&raw);
1787 assert!(result.contains(&"CPU: 83°C".to_string()));
1788 assert!(result.contains(&"NVMe: 62°C".to_string()));
1789 assert!(!result
1790 .iter()
1791 .any(|s| s.contains("79") || s.contains("59") || s.contains("56")));
1792 }
1793
1794 #[test]
1795 fn test_consolidate_temps_order() {
1796 let raw = vec![
1797 "acpitz: 60°C".to_string(),
1798 "nvme: 55°C".to_string(),
1799 "amdgpu edge: 65°C".to_string(),
1800 "k10temp Tctl: 80°C".to_string(),
1801 ];
1802 let result = consolidate_temps(&raw);
1803 let cpu_pos = result.iter().position(|s| s.starts_with("CPU"));
1804 let gpu_pos = result.iter().position(|s| s.starts_with("GPU"));
1805 let nvme_pos = result.iter().position(|s| s.starts_with("NVMe"));
1806 let sys_pos = result.iter().position(|s| s.starts_with("System"));
1807 assert!(cpu_pos < gpu_pos);
1808 assert!(gpu_pos < nvme_pos);
1809 assert!(nvme_pos < sys_pos);
1810 }
1811
1812 #[test]
1813 fn test_consolidate_temps_empty() {
1814 assert!(consolidate_temps(&[]).is_empty());
1815 }
1816
1817 #[test]
1818 fn test_format_uptime() {
1819 assert_eq!(format_uptime("60s"), "1m");
1820 assert_eq!(format_uptime("3600s"), "1h");
1821 assert_eq!(format_uptime("3661s"), "1h 1m 1s");
1822 assert_eq!(format_uptime("86400s"), "1d");
1823 assert_eq!(format_uptime("90061s"), "1d 1h 1m 1s");
1824 assert_eq!(format_uptime("31536000s"), "1y");
1825 assert_eq!(format_uptime("31626061s"), "1y 1d 1h 1m 1s");
1826 assert_eq!(format_uptime("0s"), "0s");
1827 }
1828
1829 #[test]
1830 fn test_wrap_info_line_short_line_unchanged() {
1831 let line = "Audio: Windows Audio (USB Audio Device)";
1832 let wrapped = wrap_info_line(line, 50);
1833 assert_eq!(wrapped, vec![line.to_string()]);
1834 }
1835
1836 #[test]
1837 fn test_wrap_info_line_wraps_and_indents() {
1838 let line = "Audio: Windows Audio (USB Audio Device, AMD High Definition Audio Device, AMD SoundWire Device)";
1839 let wrapped = wrap_info_line(line, 45);
1840 assert!(wrapped.len() > 1);
1841 assert!(wrapped[0].starts_with("Audio: Windows Audio"));
1842 assert!(wrapped[1].starts_with(" "));
1843 }
1844}