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};
14
15fn should_show_logo(
29 config_show_logo: Option<bool>,
30 no_logo: bool,
31 ascii_logo: bool,
32 stdout_is_tty: bool,
33) -> bool {
34 if no_logo {
35 return false; }
37 if ascii_logo {
38 return true; }
40 config_show_logo.unwrap_or(true) && stdout_is_tty }
42
43struct LayoutPlan {
46 side_by_side: bool,
47 text_column_width: usize,
48}
49
50fn plan_layout(
67 info_widths: &[usize],
68 logo_height: usize,
69 logo_width: usize,
70 term_width: usize,
71 show_logo: bool,
72) -> LayoutPlan {
73 let beside_count = info_widths.len().min(logo_height);
74 let max_beside_width = info_widths[..beside_count]
75 .iter()
76 .copied()
77 .max()
78 .unwrap_or(0);
79 let text_column_width = if term_width >= 95 {
80 (term_width.saturating_sub(logo_width + 4))
81 .min(std::cmp::max(max_beside_width + 4, 45))
82 .clamp(45, 65)
83 } else {
84 std::cmp::max(max_beside_width + 4, 45)
85 };
86 let side_by_side =
87 show_logo && term_width >= 95 && term_width >= text_column_width + logo_width;
88 LayoutPlan {
89 side_by_side,
90 text_column_width,
91 }
92}
93
94pub fn visible_len(s: &str) -> usize {
96 let mut count = 0;
97 let mut in_esc = false;
98 for c in s.chars() {
99 if c == '\x1b' {
100 in_esc = true;
101 } else if in_esc {
102 if c.is_ascii_alphabetic() {
103 in_esc = false;
104 }
105 } else {
106 count += 1;
107 }
108 }
109 count
110}
111
112pub fn wrap_info_line(line: &str, max_width: usize) -> Vec<String> {
118 let vis_len = visible_len(line);
119 if vis_len <= max_width || max_width < 20 {
120 return vec![line.to_string()];
121 }
122
123 let prefix_len = if let Some(idx) = line.find(':') {
124 let prefix_sub = &line[..=idx];
125 let extra_space = if line[idx + 1..].starts_with(' ') {
126 1
127 } else {
128 0
129 };
130 visible_len(prefix_sub) + extra_space
131 } else {
132 4
133 };
134
135 let indent = " ".repeat(prefix_len.min(max_width / 2));
136
137 if line.contains(", ") {
139 let parts: Vec<&str> = line.split(", ").collect();
140 let mut lines = Vec::new();
141 let mut current = String::new();
142
143 for (i, part) in parts.iter().enumerate() {
144 let item = if i == 0 {
145 part.to_string()
146 } else {
147 format!(", {}", part)
148 };
149 let item_vis = visible_len(&item);
150
151 if current.is_empty() || visible_len(¤t) + item_vis <= max_width {
152 current.push_str(&item);
153 } else {
154 lines.push(current);
155 current = format!("{}{}", indent, part);
156 }
157 }
158 if !current.is_empty() {
159 lines.push(current);
160 }
161 if lines.iter().all(|l| visible_len(l) <= max_width + 10) {
162 return lines;
163 }
164 }
165
166 let raw_words: Vec<&str> = line.split_whitespace().collect();
168 let mut words: Vec<String> = Vec::new();
169 let mut idx = 0;
170 while idx < raw_words.len() {
171 if raw_words[idx] == "RX:"
172 && idx + 3 < raw_words.len()
173 && raw_words.iter().skip(idx).any(|&w| w == "TX:")
174 {
175 let rx_tx = format!(
176 "{} {} {} {} {} {}",
177 raw_words[idx],
178 raw_words[idx + 1],
179 raw_words[idx + 2],
180 raw_words[idx + 3],
181 raw_words.get(idx + 4).copied().unwrap_or(""),
182 raw_words.get(idx + 5).copied().unwrap_or("")
183 );
184 words.push(rx_tx.trim().to_string());
185 idx += if idx + 5 < raw_words.len() { 6 } else { 4 };
186 continue;
187 }
188 words.push(raw_words[idx].to_string());
189 idx += 1;
190 }
191
192 let mut lines = Vec::new();
193 let mut current = String::new();
194
195 for word in words {
196 let word_vis = visible_len(&word);
197 if current.is_empty() {
198 current.push_str(&word);
199 } else if visible_len(¤t) + 1 + word_vis <= max_width {
200 current.push(' ');
201 current.push_str(&word);
202 } else {
203 lines.push(current);
204 current = format!("{}{}", indent, word);
205 }
206 }
207 if !current.is_empty() {
208 lines.push(current);
209 }
210
211 if lines.is_empty() {
212 vec![line.to_string()]
213 } else {
214 lines
215 }
216}
217
218fn split_wifi_line(wifi: &str) -> (&str, Option<&str>) {
227 match wifi.split_once(" - ") {
228 Some((hardware, connection)) => (hardware, Some(connection)),
229 None => (wifi, None),
230 }
231}
232
233fn graphical_side_by_side_prelude(text_column_width: usize, logo_rows: usize) -> String {
248 let mut prelude = String::new();
249 if logo_rows > 0 {
250 prelude.push_str(&"\n".repeat(logo_rows));
251 prelude.push_str(&format!("\x1b[{}A", logo_rows));
252 }
253 prelude.push_str(&format!("\x1b[{}C\x1b7", text_column_width));
254 prelude
255}
256
257fn render_graphical_side_by_side(
273 text_column_width: usize,
274 info_lines: &[String],
275 logo_rows: usize,
276 draw: impl FnOnce(),
277) {
278 use std::io::Write;
279 print!(
282 "{}",
283 graphical_side_by_side_prelude(text_column_width, logo_rows)
284 );
285 draw(); print!("\x1b8\r");
287 for line in info_lines {
288 println!("{}", line);
289 }
290 for _ in info_lines.len()..logo_rows {
293 println!();
294 }
295 let _ = std::io::stdout().flush();
296}
297
298pub fn display(info: &SystemInfo, cli: &Cli, config: &Config) -> anyhow::Result<()> {
304 let _config = config;
305 let theme_name = _config.theme.as_deref().or(cli.theme.as_deref());
306 let mut theme = match theme_name {
307 Some(name) => Theme::from_name(name),
308 None => Theme::detect_system_theme(), };
310
311 if let Some(custom) = &_config.custom_theme {
313 theme = Theme::with_custom_overrides(theme, custom);
314 }
315
316 let term_size = terminal_size::terminal_size();
318 let term_width = if let Some((terminal_size::Width(w), _)) = term_size {
319 w as usize
320 } else {
321 80
322 };
323 let stdout_is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
326
327 let show_logo = should_show_logo(
328 _config.show_logo,
329 cli.no_logo,
330 cli.ascii_logo,
331 stdout_is_tty,
332 );
333
334 let allowed_fields: Option<Vec<String>> = if cli.full {
339 Some(fields::fields_for(Mode::Full))
340 } else if cli.long {
341 Some(fields::fields_for(Mode::Long))
342 } else if cli.short {
343 Some(fields::fields_for(Mode::Short))
344 } else if let Some(fields) = &_config.fields {
345 Some(fields.iter().map(|s| s.to_lowercase()).collect())
346 } else {
347 Some(fields::fields_for(Mode::Standard))
348 };
349
350 let should_show = |label: &str| -> bool {
351 match &allowed_fields {
352 Some(fields) => {
353 let norm_label = label.to_lowercase().replace(['-', '_'], " ");
354 let norm_label_no_spaces = norm_label.replace(' ', "");
355 fields.iter().any(|f| {
356 let norm_f = f.to_lowercase().replace(['-', '_'], " ");
357 norm_f == norm_label
358 || norm_f.replace(' ', "") == norm_label_no_spaces
359 || (norm_label == "dns server" && norm_f == "dns")
361 || (norm_label == "memory usage" && norm_f == "memory")
363 || (norm_label == "wi fi link" && norm_f == "wifi")
365 })
366 }
367 None => true,
368 }
369 };
370
371 let label_width = 10;
373 let mut info_lines = Vec::new();
374 let mut print_line = |label: &str, value: &str| {
375 if should_show(label) {
376 info_lines.push(format!(
377 "{:>width$}{} {}",
378 theme.color_label(label),
379 theme.color_separator(":"),
380 theme.color_value(value),
381 width = label_width
382 ));
383 }
384 };
385
386 print_line("OS", &info.os);
388 if let Some(kernel) = &info.kernel {
389 print_line("Kernel", kernel);
390 }
391 if let Some(host) = &info.hostname {
392 print_line("Host", host);
393 }
394 if let Some(domain) = &info.domain {
395 print_line("Domain", domain);
396 }
397 if should_show("domain-search") {
398 for entry in &info.domain_search {
399 print_line("Domain Search", entry);
400 }
401 }
402 if let Some(chassis) = &info.chassis {
403 print_line("Chassis", chassis);
404 }
405 if let Some(init) = &info.init_system {
406 print_line("Init", init);
407 }
408 if let Some(locale) = &info.locale {
409 print_line("Locale", locale);
410 }
411 print_line("Arch", &info.arch);
412 if info.users > 0 {
416 print_line("Users", &info.users.to_string());
417 }
418 if let Some(pkgs) = info.packages {
419 if pkgs > 0 {
420 print_line("Packages", &pkgs.to_string());
421 }
422 }
423 if let Some(user) = &info.current_user {
424 print_line("User", user);
425 }
426 let uptime_str = format_uptime(&info.uptime);
428 let boot_display = format!("{} since {}", uptime_str, info.boot_time);
429 print_line("Uptime", &boot_display);
430
431 print_line("CPU", &format!("{} ({})", info.cpu, info.cpu_core_info));
433 if let Some(freq) = &info.cpu_freq {
434 print_line("CPU Freq", freq);
435 }
436 if let Some(cache) = &info.cpu_cache {
437 print_line("CPU Cache", cache);
438 }
439 if let Some(usage) = &info.cpu_usage {
440 print_line("CPU Usage", usage);
441 }
442 if let Some(motherboard) = &info.motherboard {
443 print_line("Motherboard", motherboard);
444 }
445 if let Some(bios) = &info.bios {
446 print_line("BIOS", bios);
447 }
448 if let Some(bootmgr) = &info.bootmgr {
449 print_line("Bootmgr", bootmgr);
450 }
451 if let Some(tpm) = &info.tpm {
452 print_line("TPM", tpm);
453 }
454 if should_show("GPU") {
455 for gpu in &info.gpu {
456 print_line("GPU", gpu);
457 }
458 }
459 if should_show("Display") {
460 for display in &info.displays {
461 print_line("Display", display);
462 }
463 }
464 if let Some(brightness) = &info.brightness {
465 print_line("Brightness", brightness);
466 }
467 if let Some(audio) = &info.audio {
468 print_line("Audio", audio);
469 }
470 if should_show("Camera") {
471 for cam in &info.camera {
472 print_line("Camera", cam);
473 }
474 }
475 if should_show("Gamepad") {
476 for gp in &info.gamepad {
477 print_line("Gamepad", gp);
478 }
479 }
480 if should_show("Keyboard") {
481 for kb in &info.keyboard {
482 print_line("Keyboard", kb);
483 }
484 }
485 if should_show("Mouse") {
486 for m in &info.mouse {
487 print_line("Mouse", m);
488 }
489 }
490 if let Some(wifi) = &info.wifi {
491 let (hardware, connection) = split_wifi_line(wifi);
494 print_line("Wi-Fi", hardware);
495 if let Some(conn) = connection {
496 print_line("Wi-Fi Link", conn);
497 }
498 }
499 if let Some(bt) = &info.bluetooth {
500 print_line("Bluetooth", bt);
501 }
502 if let Some(bat) = &info.battery {
503 print_line("Battery", bat);
504 }
505 if let Some(power) = &info.power_adapter {
506 print_line("Power Adapter", power);
507 }
508 print_line("Memory Usage", &info.memory);
509 if let Some(phys_mem) = &info.physical_memory {
510 print_line("Phys Mem", phys_mem);
511 }
512 print_line("Swap", &info.swap);
513 print_line("Procs", &info.processes.to_string());
514 if let Some(load) = &info.load_avg {
515 print_line("Load", load);
516 }
517 if should_show("Disk") {
518 for disk in &info.disks {
519 print_line("Disk", disk);
520 }
521 }
522 if should_show("Phys Disk") {
523 for disk in &info.physical_disks {
524 print_line("Phys Disk", disk);
525 }
526 }
527 if should_show("Btrfs") {
528 for vol in &info.btrfs {
529 print_line("Btrfs", vol);
530 }
531 }
532 if should_show("Zpool") {
533 for pool in &info.zpool {
534 print_line("Zpool", pool);
535 }
536 }
537 if should_show("Temp") {
538 if cli.full {
539 for temp in &info.temps {
540 print_line("Temp", temp);
541 }
542 } else {
543 for temp in consolidate_temps(&info.temps) {
544 print_line("Temp", &temp);
545 }
546 }
547 }
548
549 if should_show("Net") {
551 if cli.long || cli.full {
552 for net in &info.networks {
553 if let Some(ref active) = info.active_interface {
554 if net.contains(active) {
555 print_line("Net", &colorize_nested(net, ACTIVE_IFACE_PREFIX));
559 }
560 }
561 }
562 for net in &info.networks {
563 if let Some(ref active) = info.active_interface {
564 if net.contains(active) {
565 continue;
566 }
567 }
568 print_line("Net", net);
569 }
570 } else {
571 let mut printed = false;
572 if let Some(ref active) = info.active_interface {
573 for net in &info.networks {
574 if net.contains(active) {
575 print_line("Net", net);
576 printed = true;
577 break;
578 }
579 }
580 }
581 if !printed {
582 for net in &info.networks {
583 if net.contains("[Up]") {
584 print_line("Net", net);
585 break;
586 }
587 }
588 }
589 }
590 }
591 if let Some(ip) = &info.public_ip {
592 print_line("Public IP", ip);
593 }
594 if !info.dns.is_empty() {
595 print_line("DNS Server", &info.dns.join(", "));
596 }
597
598 if let Some(shell) = &info.shell {
600 print_line("Shell", shell);
601 }
602 if let Some(editor) = &info.editor {
603 print_line("Editor", editor);
604 }
605 if let Some(term) = &info.terminal {
606 print_line("Terminal", term);
607 }
608 if let Some(ts) = &info.terminal_size {
609 print_line("Terminal Size", ts);
610 }
611 if let Some(de) = &info.desktop {
612 print_line("Desktop", de);
613 }
614 if let Some(wm) = &info.wm {
615 let duplicate = info
616 .desktop
617 .as_deref()
618 .map(|de| de.to_lowercase() == wm.to_lowercase())
619 .unwrap_or(false);
620 if !duplicate {
621 print_line("WM", wm);
622 }
623 }
624 if let Some(lm) = &info.login_manager {
625 print_line("Login Manager", lm);
626 }
627 if let Some(ui_theme) = &info.ui_theme {
628 print_line("Theme", ui_theme);
629 }
630 if let Some(icons) = &info.icons {
631 print_line("Icons", icons);
632 }
633 if let Some(cursor) = &info.cursor {
634 print_line("Cursor", cursor);
635 }
636 if let Some(font) = &info.font {
637 print_line("Font", font);
638 }
639 if let Some(term_font) = &info.terminal_font {
640 print_line("Terminal Font", term_font);
641 }
642 if let Some(weather) = &info.weather {
643 print_line("Weather", weather);
644 }
645
646 enum ActiveLogo {
648 Lines(Vec<String>),
649 Kitty(Vec<u8>, usize, usize), Iterm2(Vec<u8>, usize, usize),
651 Sixel(Vec<u8>, usize, usize),
652 None,
653 }
654
655 let mut active_logo = ActiveLogo::None;
656
657 if show_logo {
658 let distro_hint = _config.logo.clone().or_else(logo::detect_distro);
659 let user_logo = if let Some(config_dir) = dirs::config_dir() {
660 let p = config_dir.join("retch").join("logo.png");
661 if p.exists() {
662 Some(p)
663 } else {
664 None
665 }
666 } else {
667 None
668 };
669
670 if cli.ascii_logo {
671 active_logo = ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
672 } else if _config.chafa.unwrap_or(false) || cli.chafa_logo {
673 let mut resolved = false;
674 if logo::chafa_available() {
675 if let Some(path) = &user_logo {
676 if let Some(lines) = logo::get_chafa_logo_lines(path) {
677 active_logo = ActiveLogo::Lines(lines);
678 resolved = true;
679 }
680 } else if let Some(distro) = &distro_hint {
681 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
682 let temp_path = std::env::temp_dir()
683 .join(format!("retch_logo_{}.png", std::process::id()));
684 if std::fs::write(&temp_path, bytes).is_ok() {
685 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
686 active_logo = ActiveLogo::Lines(lines);
687 resolved = true;
688 }
689 let _ = std::fs::remove_file(&temp_path);
690 }
691 }
692 }
693 }
694 if !resolved {
695 active_logo =
696 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
697 }
698 } else {
699 let mut resolved = false;
700
701 #[cfg(feature = "graphics")]
703 if !resolved && logo::supports_kitty() {
704 if let Some(path) = &user_logo {
705 if let Ok(bytes) = std::fs::read(path) {
706 let (cols, rows) = graphical_logo_cells(&bytes);
707 active_logo = ActiveLogo::Kitty(bytes, cols, rows);
708 resolved = true;
709 }
710 } else if let Some(distro) = &distro_hint {
711 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
712 let (cols, rows) = graphical_logo_cells(bytes);
713 active_logo = ActiveLogo::Kitty(bytes.to_vec(), cols, rows);
714 resolved = true;
715 }
716 }
717 }
718
719 #[cfg(feature = "graphics")]
721 if !resolved && logo::supports_iterm2() {
722 if let Some(path) = &user_logo {
723 if let Ok(bytes) = std::fs::read(path) {
724 let (cols, rows) = graphical_logo_cells(&bytes);
725 active_logo = ActiveLogo::Iterm2(bytes, cols, rows);
726 resolved = true;
727 }
728 } else if let Some(distro) = &distro_hint {
729 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
730 let (cols, rows) = graphical_logo_cells(bytes);
731 active_logo = ActiveLogo::Iterm2(bytes.to_vec(), cols, rows);
732 resolved = true;
733 }
734 }
735 }
736
737 #[cfg(feature = "graphics")]
739 if !resolved && logo::supports_sixel() {
740 if let Some(path) = &user_logo {
741 if let Ok(bytes) = std::fs::read(path) {
742 let (cols, rows) = graphical_logo_cells(&bytes);
743 active_logo = ActiveLogo::Sixel(bytes, cols, rows);
744 resolved = true;
745 }
746 } else if let Some(distro) = &distro_hint {
747 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
748 let (cols, rows) = graphical_logo_cells(bytes);
749 active_logo = ActiveLogo::Sixel(bytes.to_vec(), cols, rows);
750 resolved = true;
751 }
752 }
753 }
754
755 if !resolved && logo::chafa_available() {
757 if let Some(path) = &user_logo {
758 if let Some(lines) = logo::get_chafa_logo_lines(path) {
759 active_logo = ActiveLogo::Lines(lines);
760 resolved = true;
761 }
762 } else if let Some(distro) = &distro_hint {
763 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
764 let temp_path = std::env::temp_dir()
766 .join(format!("retch_logo_{}.png", std::process::id()));
767 if std::fs::write(&temp_path, bytes).is_ok() {
768 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
769 active_logo = ActiveLogo::Lines(lines);
770 resolved = true;
771 }
772 let _ = std::fs::remove_file(&temp_path);
773 }
774 }
775 }
776 }
777
778 if !resolved {
780 active_logo =
781 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
782 }
783 }
784 }
785
786 let visible_len = |s: &str| -> usize {
788 let mut count = 0;
789 let mut in_esc = false;
790 for c in s.chars() {
791 if c == '\x1b' {
792 in_esc = true;
793 } else if in_esc {
794 if c.is_ascii_alphabetic() {
795 in_esc = false;
796 }
797 } else {
798 count += 1;
799 }
800 }
801 count
802 };
803
804 let info_widths: Vec<usize> = info_lines.iter().map(|line| visible_len(line)).collect();
805
806 let (logo_height, max_logo_width) = match &active_logo {
810 ActiveLogo::Lines(logo_lines) => (
811 logo_lines.len(),
812 logo_lines
813 .iter()
814 .map(|line| visible_len(line))
815 .max()
816 .unwrap_or(0),
817 ),
818 ActiveLogo::Kitty(_, cols, rows)
819 | ActiveLogo::Iterm2(_, cols, rows)
820 | ActiveLogo::Sixel(_, cols, rows) => (*rows, *cols),
821 ActiveLogo::None => (0, 0),
822 };
823
824 let LayoutPlan {
827 side_by_side,
828 text_column_width,
829 } = plan_layout(
830 &info_widths,
831 logo_height,
832 max_logo_width,
833 term_width,
834 show_logo,
835 );
836
837 println!(); let formatted_info_lines: Vec<String> = if side_by_side && text_column_width > 15 {
840 let mut result = Vec::new();
841 for (i, line) in info_lines.iter().enumerate() {
842 let max_w = if i < logo_height {
843 text_column_width.saturating_sub(2)
844 } else {
845 term_width.saturating_sub(2)
846 };
847 result.extend(wrap_info_line(line, max_w));
848 }
849 result
850 } else {
851 info_lines.clone()
852 };
853
854 if side_by_side {
855 match active_logo {
856 ActiveLogo::Lines(logo_lines) => {
857 let max_lines = std::cmp::max(formatted_info_lines.len(), logo_lines.len());
858 for i in 0..max_lines {
859 let info_line = formatted_info_lines.get(i).cloned().unwrap_or_default();
860 let logo_line = logo_lines.get(i).cloned().unwrap_or_default();
861 let vis_len = visible_len(&info_line);
862 let padding = if vis_len < text_column_width {
863 " ".repeat(text_column_width - vis_len)
864 } else {
865 String::new()
866 };
867 println!("{}{}{}", info_line, padding, logo_line);
868 }
869 }
870 ActiveLogo::Kitty(bytes, _, logo_rows) => {
871 render_graphical_side_by_side(
872 text_column_width,
873 &formatted_info_lines,
874 logo_rows,
875 || logo::print_graphical_logo(&bytes),
876 );
877 }
878 ActiveLogo::Iterm2(bytes, _, logo_rows) => {
879 render_graphical_side_by_side(
880 text_column_width,
881 &formatted_info_lines,
882 logo_rows,
883 || logo::print_iterm2_logo(&bytes),
884 );
885 }
886 ActiveLogo::Sixel(bytes, _, logo_rows) => {
887 render_graphical_side_by_side(
888 text_column_width,
889 &formatted_info_lines,
890 logo_rows,
891 || logo::print_sixel_logo(&bytes),
892 );
893 }
894 ActiveLogo::None => {
895 for line in &formatted_info_lines {
896 println!("{}", line);
897 }
898 }
899 }
900 } else {
901 match active_logo {
903 ActiveLogo::Lines(logo_lines) => {
904 for line in logo_lines {
905 println!("{}", line);
906 }
907 println!();
908 }
909 ActiveLogo::Kitty(bytes, _, _) => {
910 logo::print_graphical_logo(&bytes);
911 println!();
912 }
913 ActiveLogo::Iterm2(bytes, _, _) => {
914 logo::print_iterm2_logo(&bytes);
915 println!();
916 }
917 ActiveLogo::Sixel(bytes, _, _) => {
918 logo::print_sixel_logo(&bytes);
919 println!();
920 }
921 ActiveLogo::None => {}
922 }
923 for line in &info_lines {
924 println!("{}", line);
925 }
926 }
927
928 Ok(())
929}
930
931fn consolidate_temps(temps: &[String]) -> Vec<String> {
937 fn categorize(label: &str) -> &'static str {
938 let l = label.to_lowercase();
939 if l.contains("cpu")
940 || l.contains("core")
941 || l.contains("k10temp")
942 || l.contains("k8temp")
943 || l.contains("coretemp")
944 || l.contains("tctl")
945 || l.contains("tdie")
946 || l.contains("tccd")
947 || l.contains("package")
948 {
949 "CPU"
950 } else if l.contains("gpu")
951 || l.contains("nouveau")
952 || l.contains("radeon")
953 || l.contains("amdgpu")
954 {
955 "GPU"
956 } else if l.contains("nvme") || l.contains("nand") {
957 "NVMe"
958 } else if l.contains("ath")
959 || l.contains("wifi")
960 || l.contains("wireless")
961 || l.contains("wlan")
962 || l.contains("iwl")
963 {
964 "WiFi"
965 } else if l.contains("bat") {
966 "Battery"
967 } else {
968 "System"
969 }
970 }
971
972 let mut max: std::collections::HashMap<&str, f32> = std::collections::HashMap::new();
973 for s in temps {
974 if let Some((label_part, val_part)) = s.rsplit_once(':') {
976 let val_str = val_part.trim().trim_end_matches("°C");
977 if let Ok(val) = val_str.parse::<f32>() {
978 let cat = categorize(label_part.trim());
979 let entry = max.entry(cat).or_insert(f32::NEG_INFINITY);
980 if val > *entry {
981 *entry = val;
982 }
983 }
984 }
985 }
986
987 const ORDER: &[&str] = &["CPU", "GPU", "NVMe", "WiFi", "Battery", "System"];
988 ORDER
989 .iter()
990 .filter_map(|cat| max.get(cat).map(|v| format!("{}: {:.0}°C", cat, v)))
991 .collect()
992}
993
994fn format_uptime(uptime: &str) -> String {
998 let seconds: u64 = uptime.trim_end_matches('s').parse().unwrap_or(0);
1000
1001 let years = seconds / (365 * 24 * 3600);
1002 let days = (seconds % (365 * 24 * 3600)) / (24 * 3600);
1003 let hours = (seconds % (24 * 3600)) / 3600;
1004 let minutes = (seconds % 3600) / 60;
1005 let secs = seconds % 60;
1006
1007 let mut parts = Vec::new();
1008 if years > 0 {
1009 parts.push(format!("{}y", years));
1010 }
1011 if days > 0 {
1012 parts.push(format!("{}d", days));
1013 }
1014 if hours > 0 {
1015 parts.push(format!("{}h", hours));
1016 }
1017 if minutes > 0 {
1018 parts.push(format!("{}m", minutes));
1019 }
1020 if secs > 0 || parts.is_empty() {
1021 parts.push(format!("{}s", secs));
1022 }
1023
1024 parts.join(" ")
1025}
1026
1027#[cfg(feature = "graphics")]
1036fn graphical_logo_cells(bytes: &[u8]) -> (usize, usize) {
1037 let (img_w, img_h) = image::load_from_memory(bytes)
1038 .map(|img| (img.width(), img.height()))
1039 .unwrap_or((0, 0));
1040 let fit = logo::logo_cells_for(img_w, img_h);
1041 (fit.cols, fit.rows)
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046 use super::*;
1047
1048 #[test]
1051 fn test_show_logo_auto_requires_tty() {
1052 assert!(should_show_logo(None, false, false, true));
1054 assert!(!should_show_logo(None, false, false, false));
1055 }
1056
1057 #[test]
1058 fn test_show_logo_ascii_forces_without_tty() {
1059 assert!(should_show_logo(None, false, true, false));
1061 assert!(should_show_logo(None, false, true, true));
1062 }
1063
1064 #[test]
1065 fn test_show_logo_no_logo_always_wins() {
1066 assert!(!should_show_logo(None, true, true, true));
1068 assert!(!should_show_logo(None, true, false, true));
1069 }
1070
1071 #[test]
1072 fn test_show_logo_config_disable() {
1073 assert!(!should_show_logo(Some(false), false, false, true));
1075 assert!(should_show_logo(Some(false), false, true, false));
1077 }
1078
1079 fn realistic_full_widths() -> Vec<usize> {
1084 let mut w = vec![40; 20]; w[13] = 54; w.extend([158, 91, 79, 60, 45, 62]); w
1088 }
1089
1090 #[test]
1091 fn test_layout_long_line_below_logo_stays_side_by_side() {
1092 let p = plan_layout(&realistic_full_widths(), 20, 40, 120, true);
1094 assert!(p.side_by_side);
1095 assert_eq!(p.text_column_width, 58); }
1098
1099 #[test]
1100 fn test_layout_old_behavior_would_have_stacked() {
1101 let widths = realistic_full_widths();
1104 let old_text_col = std::cmp::max(widths.iter().copied().max().unwrap() + 4, 45);
1105 assert!(120 < old_text_col + 40); assert!(plan_layout(&widths, 20, 40, 120, true).side_by_side); }
1108
1109 #[test]
1110 fn test_layout_long_line_within_logo_wraps_and_stays_side_by_side() {
1111 let mut w = vec![40; 20];
1114 w[5] = 158;
1115 let p = plan_layout(&w, 20, 40, 120, true);
1116 assert!(p.side_by_side);
1117 assert_eq!(p.text_column_width, 65);
1118 }
1119
1120 #[test]
1121 fn test_layout_narrow_terminal_stacks() {
1122 assert!(!plan_layout(&[40; 30], 20, 40, 94, true).side_by_side); assert!(!plan_layout(&[40; 30], 20, 40, 80, true).side_by_side);
1124 }
1125
1126 #[test]
1127 fn test_layout_show_logo_false_stacks() {
1128 assert!(!plan_layout(&[40; 30], 20, 40, 200, false).side_by_side);
1129 }
1130
1131 #[test]
1132 fn test_layout_column_floor_and_graphical_width() {
1133 let p = plan_layout(&[10; 25], 20, 40, 100, true);
1135 assert!(p.side_by_side);
1136 assert_eq!(p.text_column_width, 45); }
1138
1139 #[test]
1140 fn test_layout_widened_logo_box_still_fits_at_the_side_by_side_threshold() {
1141 let p = plan_layout(&[10; 25], 10, logo::LOGO_MAX_COLS, 95, true);
1145 assert!(
1146 p.side_by_side,
1147 "a full-width logo must still sit beside the text at 95 columns"
1148 );
1149 assert!(p.text_column_width + logo::LOGO_MAX_COLS <= 95);
1150
1151 let wide = plan_layout(&[120; 25], 10, logo::LOGO_MAX_COLS, 169, true);
1153 assert!(wide.side_by_side);
1154 assert_eq!(wide.text_column_width, 65);
1155 }
1156
1157 #[test]
1158 fn test_layout_logo_taller_than_text() {
1159 let p = plan_layout(&[50, 30, 54], 20, 40, 120, true);
1161 assert!(p.side_by_side);
1162 assert_eq!(p.text_column_width, 58); }
1164
1165 #[test]
1168 fn test_prelude_reserves_rows_before_saving_cursor() {
1169 let p = graphical_side_by_side_prelude(52, 3);
1173 assert_eq!(p, "\n\n\n\x1b[3A\x1b[52C\x1b7");
1174 }
1175
1176 #[test]
1177 fn test_prelude_v068_shape_only_differs_by_reservation() {
1178 let p = graphical_side_by_side_prelude(45, 20);
1181 assert_eq!(
1182 p.replace(&format!("{}\x1b[20A", "\n".repeat(20)), ""),
1183 "\x1b[45C\x1b7"
1184 );
1185 }
1186
1187 #[test]
1188 fn test_prelude_zero_rows_skips_reservation_and_cursor_up() {
1189 let p = graphical_side_by_side_prelude(45, 0);
1192 assert_eq!(p, "\x1b[45C\x1b7");
1193 }
1194
1195 #[test]
1198 fn test_split_wifi_hardware_and_connection() {
1199 let s = "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0] - myssid (5.0 GHz ch36 [↓866 ↑866])";
1201 let (hw, conn) = split_wifi_line(s);
1202 assert_eq!(
1203 hw,
1204 "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0]"
1205 );
1206 assert_eq!(conn, Some("myssid (5.0 GHz ch36 [↓866 ↑866])"));
1207 }
1208
1209 #[test]
1210 fn test_split_wifi_splits_on_first_separator() {
1211 let (hw, conn) = split_wifi_line("Card X [wlan0] - Guest - 5G (5 GHz)");
1214 assert_eq!(hw, "Card X [wlan0]");
1215 assert_eq!(conn, Some("Guest - 5G (5 GHz)"));
1216 }
1217
1218 #[test]
1219 fn test_split_wifi_connection_only_fallback() {
1220 let (hw, conn) = split_wifi_line("myssid (300 Mbps)");
1222 assert_eq!(hw, "myssid (300 Mbps)");
1223 assert_eq!(conn, None);
1224 }
1225
1226 #[test]
1227 fn test_consolidate_temps_basic() {
1228 let raw = vec![
1229 "k10temp Tctl: 83°C".to_string(),
1230 "amdgpu edge: 65°C".to_string(),
1231 "nvme Composite: 62°C".to_string(),
1232 "ath11k_hwmon temp1: 58°C".to_string(),
1233 "acpitz temp1: 77°C".to_string(),
1234 ];
1235 let result = consolidate_temps(&raw);
1236 assert_eq!(
1237 result,
1238 vec![
1239 "CPU: 83°C",
1240 "GPU: 65°C",
1241 "NVMe: 62°C",
1242 "WiFi: 58°C",
1243 "System: 77°C"
1244 ]
1245 );
1246 }
1247
1248 #[test]
1249 fn test_consolidate_temps_highest_wins() {
1250 let raw = vec![
1251 "thinkpad CPU: 83°C".to_string(),
1252 "k10temp Tctl: 79°C".to_string(),
1253 "nvme Composite: 62°C".to_string(),
1254 "nvme Sensor 1: 59°C".to_string(),
1255 "nvme Sensor 2: 56°C".to_string(),
1256 ];
1257 let result = consolidate_temps(&raw);
1258 assert!(result.contains(&"CPU: 83°C".to_string()));
1259 assert!(result.contains(&"NVMe: 62°C".to_string()));
1260 assert!(!result
1261 .iter()
1262 .any(|s| s.contains("79") || s.contains("59") || s.contains("56")));
1263 }
1264
1265 #[test]
1266 fn test_consolidate_temps_order() {
1267 let raw = vec![
1268 "acpitz: 60°C".to_string(),
1269 "nvme: 55°C".to_string(),
1270 "amdgpu edge: 65°C".to_string(),
1271 "k10temp Tctl: 80°C".to_string(),
1272 ];
1273 let result = consolidate_temps(&raw);
1274 let cpu_pos = result.iter().position(|s| s.starts_with("CPU"));
1275 let gpu_pos = result.iter().position(|s| s.starts_with("GPU"));
1276 let nvme_pos = result.iter().position(|s| s.starts_with("NVMe"));
1277 let sys_pos = result.iter().position(|s| s.starts_with("System"));
1278 assert!(cpu_pos < gpu_pos);
1279 assert!(gpu_pos < nvme_pos);
1280 assert!(nvme_pos < sys_pos);
1281 }
1282
1283 #[test]
1284 fn test_consolidate_temps_empty() {
1285 assert!(consolidate_temps(&[]).is_empty());
1286 }
1287
1288 #[test]
1289 fn test_format_uptime() {
1290 assert_eq!(format_uptime("60s"), "1m");
1291 assert_eq!(format_uptime("3600s"), "1h");
1292 assert_eq!(format_uptime("3661s"), "1h 1m 1s");
1293 assert_eq!(format_uptime("86400s"), "1d");
1294 assert_eq!(format_uptime("90061s"), "1d 1h 1m 1s");
1295 assert_eq!(format_uptime("31536000s"), "1y");
1296 assert_eq!(format_uptime("31626061s"), "1y 1d 1h 1m 1s");
1297 assert_eq!(format_uptime("0s"), "0s");
1298 }
1299
1300 #[test]
1301 fn test_wrap_info_line_short_line_unchanged() {
1302 let line = "Audio: Windows Audio (USB Audio Device)";
1303 let wrapped = wrap_info_line(line, 50);
1304 assert_eq!(wrapped, vec![line.to_string()]);
1305 }
1306
1307 #[test]
1308 fn test_wrap_info_line_wraps_and_indents() {
1309 let line = "Audio: Windows Audio (USB Audio Device, AMD High Definition Audio Device, AMD SoundWire Device)";
1310 let wrapped = wrap_info_line(line, 45);
1311 assert!(wrapped.len() > 1);
1312 assert!(wrapped[0].starts_with("Audio: Windows Audio"));
1313 assert!(wrapped[1].starts_with(" "));
1314 }
1315}