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 {
52 side_by_side: bool,
53 text_column_width: usize,
54 logo_column: usize,
55}
56
57fn plan_layout(
85 info_widths: &[usize],
86 logo_height: usize,
87 logo_width: usize,
88 term_width: usize,
89 show_logo: bool,
90) -> LayoutPlan {
91 let beside_count = info_widths.len().min(logo_height);
92 let max_beside_width = info_widths[..beside_count]
93 .iter()
94 .copied()
95 .max()
96 .unwrap_or(0);
97 let text_column_width = if term_width >= 95 {
98 (term_width.saturating_sub(logo_width + 4))
99 .min(std::cmp::max(max_beside_width + 4, 45))
100 .clamp(45, 65)
101 } else {
102 std::cmp::max(max_beside_width + 4, 45)
103 };
104 let side_by_side =
105 show_logo && term_width >= 95 && term_width >= text_column_width + logo_width;
106 let logo_column = term_width.saturating_sub(logo_width).max(text_column_width);
109 LayoutPlan {
110 side_by_side,
111 text_column_width,
112 logo_column,
113 }
114}
115
116pub fn visible_len(s: &str) -> usize {
138 use unicode_width::UnicodeWidthStr;
139
140 let mut visible = String::with_capacity(s.len());
141 let mut in_esc = false;
142 for c in s.chars() {
143 if c == '\x1b' {
144 in_esc = true;
145 } else if in_esc {
146 if c.is_ascii_alphabetic() {
147 in_esc = false;
148 }
149 } else {
150 visible.push(c);
151 }
152 }
153 visible.width()
154}
155
156pub fn wrap_info_line(line: &str, max_width: usize) -> Vec<String> {
162 let vis_len = visible_len(line);
163 if vis_len <= max_width || max_width < 20 {
164 return vec![line.to_string()];
165 }
166
167 let prefix_len = if let Some(idx) = line.find(':') {
168 let prefix_sub = &line[..=idx];
169 let extra_space = if line[idx + 1..].starts_with(' ') {
170 1
171 } else {
172 0
173 };
174 visible_len(prefix_sub) + extra_space
175 } else {
176 4
177 };
178
179 let indent = " ".repeat(prefix_len.min(max_width / 2));
180
181 if line.contains(", ") {
183 let parts: Vec<&str> = line.split(", ").collect();
184 let mut lines = Vec::new();
185 let mut current = String::new();
186
187 for (i, part) in parts.iter().enumerate() {
188 let item = if i == 0 {
189 part.to_string()
190 } else {
191 format!(", {}", part)
192 };
193 let item_vis = visible_len(&item);
194
195 if current.is_empty() || visible_len(¤t) + item_vis <= max_width {
196 current.push_str(&item);
197 } else {
198 lines.push(format!("{current},"));
203 current = format!("{}{}", indent, part);
204 }
205 }
206 if !current.is_empty() {
207 lines.push(current);
208 }
209 if lines.iter().all(|l| visible_len(l) <= max_width + 10) {
210 return carry_sgr_across_lines(lines);
211 }
212 }
213
214 let raw_words: Vec<&str> = line.split_whitespace().collect();
216 let mut words: Vec<String> = Vec::new();
217 let mut idx = 0;
218 while idx < raw_words.len() {
219 if raw_words[idx] == "RX:"
220 && idx + 3 < raw_words.len()
221 && raw_words.iter().skip(idx).any(|&w| w == "TX:")
222 {
223 let rx_tx = format!(
224 "{} {} {} {} {} {}",
225 raw_words[idx],
226 raw_words[idx + 1],
227 raw_words[idx + 2],
228 raw_words[idx + 3],
229 raw_words.get(idx + 4).copied().unwrap_or(""),
230 raw_words.get(idx + 5).copied().unwrap_or("")
231 );
232 words.push(rx_tx.trim().to_string());
233 idx += if idx + 5 < raw_words.len() { 6 } else { 4 };
234 continue;
235 }
236 words.push(raw_words[idx].to_string());
237 idx += 1;
238 }
239
240 let mut lines = Vec::new();
241 let mut current = String::new();
242
243 for word in words {
244 let word_vis = visible_len(&word);
245 if current.is_empty() {
246 current.push_str(&word);
247 } else if visible_len(¤t) + 1 + word_vis <= max_width {
248 current.push(' ');
249 current.push_str(&word);
250 } else {
251 lines.push(current);
252 current = format!("{}{}", indent, word);
253 }
254 }
255 if !current.is_empty() {
256 lines.push(current);
257 }
258
259 if lines.is_empty() {
260 vec![line.to_string()]
261 } else {
262 carry_sgr_across_lines(lines)
265 }
266}
267
268fn active_sgr_after(s: &str, entry: Option<String>) -> Option<String> {
275 let mut active = entry;
276 let bytes = s.as_bytes();
277 let mut i = 0;
278 while i < bytes.len() {
279 if bytes[i] != 0x1b {
280 i += 1;
281 continue;
282 }
283 let start = i;
284 i += 1;
285 while i < bytes.len() && !bytes[i].is_ascii_alphabetic() {
286 i += 1;
287 }
288 if i < bytes.len() {
289 let seq = &s[start..=i];
290 if seq.ends_with('m') {
291 active = if seq == "\x1b[0m" || seq == "\x1b[39m" {
292 None
293 } else {
294 Some(seq.to_string())
295 };
296 }
297 i += 1;
298 }
299 }
300 active
301}
302
303fn carry_sgr_across_lines(lines: Vec<String>) -> Vec<String> {
316 let mut active: Option<String> = None;
317 let mut out = Vec::with_capacity(lines.len());
318 for line in lines {
319 let reopened = match &active {
320 Some(sgr) => format!("{sgr}{line}"),
321 None => line.clone(),
322 };
323 let end_state = active_sgr_after(&line, active.clone());
324 active = end_state.clone();
325 out.push(match end_state {
326 Some(_) => format!("{reopened}\x1b[39m"),
328 None => reopened,
329 });
330 }
331 out
332}
333
334fn split_wifi_line(wifi: &str) -> (&str, Option<&str>) {
343 match wifi.split_once(" - ") {
344 Some((hardware, connection)) => (hardware, Some(connection)),
345 None => (wifi, None),
346 }
347}
348
349fn compose_side_by_side_row(info_line: &str, logo_line: &str, logo_column: usize) -> String {
364 let vis_len = visible_len(info_line);
365 if logo_line.is_empty() || vis_len >= logo_column {
366 return format!("{info_line}{logo_line}");
367 }
368 format!(
369 "{info_line}{}{logo_line}",
370 " ".repeat(logo_column - vis_len)
371 )
372}
373
374fn graphical_side_by_side_prelude(logo_column: usize, logo_rows: usize) -> String {
389 let mut prelude = String::new();
390 if logo_rows > 0 {
391 prelude.push_str(&"\n".repeat(logo_rows));
392 prelude.push_str(&format!("\x1b[{}A", logo_rows));
393 }
394 prelude.push_str(&format!("\x1b[{}C\x1b7", logo_column));
395 prelude
396}
397
398fn render_graphical_side_by_side(
414 logo_column: usize,
415 info_lines: &[String],
416 logo_rows: usize,
417 draw: impl FnOnce(),
418) {
419 use std::io::Write;
420 print!("{}", graphical_side_by_side_prelude(logo_column, logo_rows));
423 draw(); print!("\x1b8\r");
425 for line in info_lines {
426 println!("{}", line);
427 }
428 for _ in info_lines.len()..logo_rows {
431 println!();
432 }
433 let _ = std::io::stdout().flush();
434}
435
436pub fn display(info: &SystemInfo, cli: &Cli, config: &Config) -> anyhow::Result<()> {
442 let _config = config;
443 let theme_name = _config.theme.as_deref().or(cli.theme.as_deref());
444 let mut theme = match theme_name {
445 Some(name) => Theme::from_name(name),
446 None => Theme::detect_system_theme(), };
448
449 if let Some(custom) = &_config.custom_theme {
451 theme = Theme::with_custom_overrides(theme, custom);
452 }
453
454 let term_size = terminal_size::terminal_size();
456 let term_width = if let Some((terminal_size::Width(w), _)) = term_size {
457 w as usize
458 } else {
459 80
460 };
461 let stdout_is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
464
465 let show_logo = should_show_logo(
466 _config.show_logo,
467 cli.no_logo,
468 cli.ascii_logo,
469 stdout_is_tty,
470 );
471
472 let allowed_fields: Option<Vec<String>> = if cli.full {
477 Some(fields::fields_for(Mode::Full))
478 } else if cli.long {
479 Some(fields::fields_for(Mode::Long))
480 } else if cli.short {
481 Some(fields::fields_for(Mode::Short))
482 } else if let Some(fields) = &_config.fields {
483 Some(fields.iter().map(|s| s.to_lowercase()).collect())
484 } else {
485 Some(fields::fields_for(Mode::Standard))
486 };
487
488 let should_show = |label: &str| -> bool {
489 match &allowed_fields {
490 Some(fields) => {
491 let norm_label = label.to_lowercase().replace(['-', '_'], " ");
492 let norm_label_no_spaces = norm_label.replace(' ', "");
493 fields.iter().any(|f| {
494 let norm_f = f.to_lowercase().replace(['-', '_'], " ");
495 norm_f == norm_label
496 || norm_f.replace(' ', "") == norm_label_no_spaces
497 || (norm_label == "dns server" && norm_f == "dns")
499 || (norm_label == "memory usage" && norm_f == "memory")
501 || (norm_label == "wi fi link" && norm_f == "wifi")
503 })
504 }
505 None => true,
506 }
507 };
508
509 let label_width = 10;
511 let mut info_lines = Vec::new();
512 let mut print_line = |label: &str, value: &str| {
513 if should_show(label) {
514 info_lines.push(format!(
515 "{:>width$}{} {}",
516 theme.color_label(label),
517 theme.color_separator(":"),
518 theme.color_value(value),
519 width = label_width
520 ));
521 }
522 };
523
524 print_line("OS", &info.os);
526 if let Some(kernel) = &info.kernel {
527 print_line("Kernel", kernel);
528 }
529 if let Some(host) = &info.hostname {
530 print_line("Host", host);
531 }
532 if let Some(domain) = &info.domain {
533 print_line("Domain", domain);
534 }
535 if should_show("domain-search") {
536 for entry in &info.domain_search {
537 print_line("Domain Search", entry);
538 }
539 }
540 if let Some(chassis) = &info.chassis {
541 print_line("Chassis", chassis);
542 }
543 if let Some(init) = &info.init_system {
544 print_line("Init", init);
545 }
546 if let Some(locale) = &info.locale {
547 print_line("Locale", locale);
548 }
549 print_line("Arch", &info.arch);
550 if info.users > 0 {
554 print_line("Users", &info.users.to_string());
555 }
556 if let Some(pkgs) = info.packages {
557 if pkgs > 0 {
558 print_line("Packages", &pkgs.to_string());
559 }
560 }
561 if let Some(user) = &info.current_user {
562 print_line("User", user);
563 }
564 let uptime_str = format_uptime(&info.uptime);
566 let boot_display = format!("{} since {}", uptime_str, info.boot_time);
567 print_line("Uptime", &boot_display);
568
569 print_line("CPU", &format!("{} ({})", info.cpu, info.cpu_core_info));
571 if let Some(freq) = &info.cpu_freq {
572 print_line("CPU Freq", freq);
573 }
574 if let Some(cache) = &info.cpu_cache {
575 print_line("CPU Cache", cache);
576 }
577 if let Some(usage) = &info.cpu_usage {
578 print_line("CPU Usage", usage);
579 }
580 if let Some(motherboard) = &info.motherboard {
581 print_line("Motherboard", motherboard);
582 }
583 if let Some(bios) = &info.bios {
584 print_line("BIOS", bios);
585 }
586 if let Some(bootmgr) = &info.bootmgr {
587 print_line("Bootmgr", bootmgr);
588 }
589 if let Some(tpm) = &info.tpm {
590 print_line("TPM", tpm);
591 }
592 if should_show("GPU") {
593 for gpu in &info.gpu {
594 print_line("GPU", gpu);
595 }
596 }
597 if should_show("Display") {
598 for display in &info.displays {
599 print_line("Display", display);
600 }
601 }
602 if let Some(brightness) = &info.brightness {
603 print_line("Brightness", brightness);
604 }
605 if let Some(audio) = &info.audio {
606 print_line("Audio", audio);
607 }
608 if should_show("Camera") {
609 for cam in &info.camera {
610 print_line("Camera", cam);
611 }
612 }
613 if should_show("Gamepad") {
614 for gp in &info.gamepad {
615 print_line("Gamepad", gp);
616 }
617 }
618 if should_show("Keyboard") {
619 for kb in &info.keyboard {
620 print_line("Keyboard", kb);
621 }
622 }
623 if should_show("Mouse") {
624 for m in &info.mouse {
625 print_line("Mouse", m);
626 }
627 }
628 if let Some(wifi) = &info.wifi {
629 let (hardware, connection) = split_wifi_line(wifi);
632 print_line("Wi-Fi", hardware);
633 if let Some(conn) = connection {
634 print_line("Wi-Fi Link", conn);
635 }
636 }
637 if let Some(bt) = &info.bluetooth {
638 print_line("Bluetooth", bt);
639 }
640 if let Some(bat) = &info.battery {
641 print_line("Battery", bat);
642 }
643 if let Some(power) = &info.power_adapter {
644 print_line("Power Adapter", power);
645 }
646 print_line("Memory Usage", &info.memory);
647 if let Some(phys_mem) = &info.physical_memory {
648 print_line("Phys Mem", phys_mem);
649 }
650 print_line("Swap", &info.swap);
651 print_line("Procs", &info.processes.to_string());
652 if let Some(load) = &info.load_avg {
653 print_line("Load", load);
654 }
655 if should_show("Disk") {
656 for disk in &info.disks {
657 print_line("Disk", disk);
658 }
659 }
660 if should_show("Phys Disk") {
661 for disk in &info.physical_disks {
662 print_line("Phys Disk", disk);
663 }
664 }
665 if should_show("Btrfs") {
666 for vol in &info.btrfs {
667 print_line("Btrfs", vol);
668 }
669 }
670 if should_show("Zpool") {
671 for pool in &info.zpool {
672 print_line("Zpool", pool);
673 }
674 }
675 if should_show("Temp") {
676 if cli.full {
677 for temp in &info.temps {
678 print_line("Temp", temp);
679 }
680 } else {
681 for temp in consolidate_temps(&info.temps) {
682 print_line("Temp", &temp);
683 }
684 }
685 }
686
687 if should_show("Net") {
689 if cli.long || cli.full {
690 for net in &info.networks {
691 if let Some(ref active) = info.active_interface {
692 if net.contains(active) {
693 print_line("Net", &colorize_nested(net, ACTIVE_IFACE_PREFIX));
697 }
698 }
699 }
700 for net in &info.networks {
701 if let Some(ref active) = info.active_interface {
702 if net.contains(active) {
703 continue;
704 }
705 }
706 print_line("Net", net);
707 }
708 } else {
709 let mut printed = false;
710 if let Some(ref active) = info.active_interface {
711 for net in &info.networks {
712 if net.contains(active) {
713 print_line("Net", net);
714 printed = true;
715 break;
716 }
717 }
718 }
719 if !printed {
720 for net in &info.networks {
721 if net.contains("[Up]") {
722 print_line("Net", net);
723 break;
724 }
725 }
726 }
727 }
728 }
729 if let Some(ip) = &info.public_ip {
730 print_line("Public IP", ip);
731 }
732 if !info.dns.is_empty() {
733 print_line("DNS Server", &info.dns.join(", "));
734 }
735
736 if let Some(shell) = &info.shell {
738 print_line("Shell", shell);
739 }
740 if let Some(editor) = &info.editor {
741 print_line("Editor", editor);
742 }
743 if let Some(term) = &info.terminal {
744 print_line("Terminal", term);
745 }
746 if let Some(ts) = &info.terminal_size {
747 print_line("Terminal Size", ts);
748 }
749 if let Some(de) = &info.desktop {
750 print_line("Desktop", de);
751 }
752 if let Some(wm) = &info.wm {
753 let duplicate = info
754 .desktop
755 .as_deref()
756 .map(|de| de.to_lowercase() == wm.to_lowercase())
757 .unwrap_or(false);
758 if !duplicate {
759 print_line("WM", wm);
760 }
761 }
762 if let Some(wm_theme) = &info.wm_theme {
763 print_line("WM Theme", wm_theme);
764 }
765 if let Some(wallpaper) = &info.wallpaper {
766 print_line("Wallpaper", wallpaper);
767 }
768 if let Some(lm) = &info.login_manager {
769 print_line("Login Manager", lm);
770 }
771 if let Some(player) = &info.player {
772 print_line("Player", player);
773 }
774 if let Some(media) = &info.media {
775 print_line("Media", media);
776 }
777 if let Some(ui_theme) = &info.ui_theme {
778 print_line("Theme", ui_theme);
779 }
780 if let Some(icons) = &info.icons {
781 print_line("Icons", icons);
782 }
783 if let Some(cursor) = &info.cursor {
784 print_line("Cursor", cursor);
785 }
786 if let Some(font) = &info.font {
787 print_line("Font", font);
788 }
789 if let Some(term_font) = &info.terminal_font {
790 print_line("Terminal Font", term_font);
791 }
792 if let Some(term_theme) = &info.terminal_theme {
793 print_line("Terminal Theme", term_theme);
794 }
795 if let Some(weather) = &info.weather {
796 print_line("Weather", weather);
797 }
798
799 enum ActiveLogo {
801 Lines(Vec<String>),
802 Kitty(Vec<u8>, usize, usize), Iterm2(Vec<u8>, usize, usize),
804 Sixel(Vec<u8>, usize, usize),
805 None,
806 }
807
808 let mut active_logo = ActiveLogo::None;
809
810 if show_logo {
811 let distro_hint = _config.logo.clone().or_else(logo::detect_distro);
812 let user_logo = if let Some(config_dir) = dirs::config_dir() {
813 let p = config_dir.join("retch").join("logo.png");
814 if p.exists() {
815 Some(p)
816 } else {
817 None
818 }
819 } else {
820 None
821 };
822
823 if cli.ascii_logo {
824 active_logo = ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
825 } else if _config.chafa.unwrap_or(false) || cli.chafa_logo {
826 let mut resolved = false;
827 if logo::chafa_available() {
828 if let Some(path) = &user_logo {
829 if let Some(lines) = logo::get_chafa_logo_lines(path) {
830 active_logo = ActiveLogo::Lines(lines);
831 resolved = true;
832 }
833 } else if let Some(distro) = &distro_hint {
834 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
835 let temp_path = std::env::temp_dir()
836 .join(format!("retch_logo_{}.png", std::process::id()));
837 if std::fs::write(&temp_path, bytes).is_ok() {
838 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
839 active_logo = ActiveLogo::Lines(lines);
840 resolved = true;
841 }
842 let _ = std::fs::remove_file(&temp_path);
843 }
844 }
845 }
846 }
847 if !resolved {
848 active_logo =
849 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
850 }
851 } else {
852 let mut resolved = false;
853
854 #[cfg(feature = "graphics")]
856 if !resolved && logo::supports_kitty() {
857 if let Some(path) = &user_logo {
858 if let Ok(bytes) = std::fs::read(path) {
859 let (cols, rows) = graphical_logo_cells(&bytes);
860 active_logo = ActiveLogo::Kitty(bytes, cols, rows);
861 resolved = true;
862 }
863 } else if let Some(distro) = &distro_hint {
864 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
865 let (cols, rows) = graphical_logo_cells(bytes);
866 active_logo = ActiveLogo::Kitty(bytes.to_vec(), cols, rows);
867 resolved = true;
868 }
869 }
870 }
871
872 #[cfg(feature = "graphics")]
874 if !resolved && logo::supports_iterm2() {
875 if let Some(path) = &user_logo {
876 if let Ok(bytes) = std::fs::read(path) {
877 let (cols, rows) = graphical_logo_cells(&bytes);
878 active_logo = ActiveLogo::Iterm2(bytes, cols, rows);
879 resolved = true;
880 }
881 } else if let Some(distro) = &distro_hint {
882 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
883 let (cols, rows) = graphical_logo_cells(bytes);
884 active_logo = ActiveLogo::Iterm2(bytes.to_vec(), cols, rows);
885 resolved = true;
886 }
887 }
888 }
889
890 #[cfg(feature = "graphics")]
892 if !resolved && logo::supports_sixel() {
893 if let Some(path) = &user_logo {
894 if let Ok(bytes) = std::fs::read(path) {
895 let (cols, rows) = graphical_logo_cells(&bytes);
896 active_logo = ActiveLogo::Sixel(bytes, cols, rows);
897 resolved = true;
898 }
899 } else if let Some(distro) = &distro_hint {
900 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
901 let (cols, rows) = graphical_logo_cells(bytes);
902 active_logo = ActiveLogo::Sixel(bytes.to_vec(), cols, rows);
903 resolved = true;
904 }
905 }
906 }
907
908 if !resolved && logo::chafa_available() {
910 if let Some(path) = &user_logo {
911 if let Some(lines) = logo::get_chafa_logo_lines(path) {
912 active_logo = ActiveLogo::Lines(lines);
913 resolved = true;
914 }
915 } else if let Some(distro) = &distro_hint {
916 if let Some(bytes) = logo::get_embedded_logo(Some(distro)) {
917 let temp_path = std::env::temp_dir()
919 .join(format!("retch_logo_{}.png", std::process::id()));
920 if std::fs::write(&temp_path, bytes).is_ok() {
921 if let Some(lines) = logo::get_chafa_logo_lines(&temp_path) {
922 active_logo = ActiveLogo::Lines(lines);
923 resolved = true;
924 }
925 let _ = std::fs::remove_file(&temp_path);
926 }
927 }
928 }
929 }
930
931 if !resolved {
933 active_logo =
934 ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
935 }
936 }
937 }
938
939 let info_widths: Vec<usize> = info_lines.iter().map(|line| visible_len(line)).collect();
947
948 let (logo_height, max_logo_width) = match &active_logo {
952 ActiveLogo::Lines(logo_lines) => (
953 logo_lines.len(),
954 logo_lines
955 .iter()
956 .map(|line| visible_len(line))
957 .max()
958 .unwrap_or(0),
959 ),
960 ActiveLogo::Kitty(_, cols, rows)
961 | ActiveLogo::Iterm2(_, cols, rows)
962 | ActiveLogo::Sixel(_, cols, rows) => (*rows, *cols),
963 ActiveLogo::None => (0, 0),
964 };
965
966 let LayoutPlan {
969 side_by_side,
970 text_column_width,
971 logo_column,
972 } = plan_layout(
973 &info_widths,
974 logo_height,
975 max_logo_width,
976 term_width,
977 show_logo,
978 );
979
980 println!(); let formatted_info_lines: Vec<String> = if side_by_side && text_column_width > 15 {
983 let mut result = Vec::new();
984 for (i, line) in info_lines.iter().enumerate() {
985 let max_w = if i < logo_height {
992 logo_column.saturating_sub(2)
993 } else {
994 term_width.saturating_sub(2)
995 };
996 result.extend(wrap_info_line(line, max_w));
997 }
998 result
999 } else {
1000 info_lines.clone()
1001 };
1002
1003 if side_by_side {
1004 match active_logo {
1005 ActiveLogo::Lines(logo_lines) => {
1006 let max_lines = std::cmp::max(formatted_info_lines.len(), logo_lines.len());
1007 for i in 0..max_lines {
1008 let info_line = formatted_info_lines.get(i).cloned().unwrap_or_default();
1009 let logo_line = logo_lines.get(i).cloned().unwrap_or_default();
1010 println!(
1011 "{}",
1012 compose_side_by_side_row(&info_line, &logo_line, logo_column)
1013 );
1014 }
1015 }
1016 ActiveLogo::Kitty(bytes, _, logo_rows) => {
1017 render_graphical_side_by_side(
1018 logo_column,
1019 &formatted_info_lines,
1020 logo_rows,
1021 || logo::print_graphical_logo(&bytes),
1022 );
1023 }
1024 ActiveLogo::Iterm2(bytes, _, logo_rows) => {
1025 render_graphical_side_by_side(
1026 logo_column,
1027 &formatted_info_lines,
1028 logo_rows,
1029 || logo::print_iterm2_logo(&bytes),
1030 );
1031 }
1032 ActiveLogo::Sixel(bytes, _, logo_rows) => {
1033 render_graphical_side_by_side(
1034 logo_column,
1035 &formatted_info_lines,
1036 logo_rows,
1037 || logo::print_sixel_logo(&bytes),
1038 );
1039 }
1040 ActiveLogo::None => {
1041 for line in &formatted_info_lines {
1042 println!("{}", line);
1043 }
1044 }
1045 }
1046 } else {
1047 match active_logo {
1049 ActiveLogo::Lines(logo_lines) => {
1050 for line in logo_lines {
1051 println!("{}", line);
1052 }
1053 println!();
1054 }
1055 ActiveLogo::Kitty(bytes, _, _) => {
1056 logo::print_graphical_logo(&bytes);
1057 println!();
1058 }
1059 ActiveLogo::Iterm2(bytes, _, _) => {
1060 logo::print_iterm2_logo(&bytes);
1061 println!();
1062 }
1063 ActiveLogo::Sixel(bytes, _, _) => {
1064 logo::print_sixel_logo(&bytes);
1065 println!();
1066 }
1067 ActiveLogo::None => {}
1068 }
1069 for line in &info_lines {
1070 println!("{}", line);
1071 }
1072 }
1073
1074 Ok(())
1075}
1076
1077fn consolidate_temps(temps: &[String]) -> Vec<String> {
1083 fn categorize(label: &str) -> &'static str {
1084 let l = label.to_lowercase();
1085 if l.contains("cpu")
1086 || l.contains("core")
1087 || l.contains("k10temp")
1088 || l.contains("k8temp")
1089 || l.contains("coretemp")
1090 || l.contains("tctl")
1091 || l.contains("tdie")
1092 || l.contains("tccd")
1093 || l.contains("package")
1094 {
1095 "CPU"
1096 } else if l.contains("gpu")
1097 || l.contains("nouveau")
1098 || l.contains("radeon")
1099 || l.contains("amdgpu")
1100 {
1101 "GPU"
1102 } else if l.contains("nvme") || l.contains("nand") {
1103 "NVMe"
1104 } else if l.contains("ath")
1105 || l.contains("wifi")
1106 || l.contains("wireless")
1107 || l.contains("wlan")
1108 || l.contains("iwl")
1109 {
1110 "WiFi"
1111 } else if l.contains("bat") {
1112 "Battery"
1113 } else {
1114 "System"
1115 }
1116 }
1117
1118 let mut max: std::collections::HashMap<&str, f32> = std::collections::HashMap::new();
1119 for s in temps {
1120 if let Some((label_part, val_part)) = s.rsplit_once(':') {
1122 let val_str = val_part.trim().trim_end_matches("°C");
1123 if let Ok(val) = val_str.parse::<f32>() {
1124 let cat = categorize(label_part.trim());
1125 let entry = max.entry(cat).or_insert(f32::NEG_INFINITY);
1126 if val > *entry {
1127 *entry = val;
1128 }
1129 }
1130 }
1131 }
1132
1133 const ORDER: &[&str] = &["CPU", "GPU", "NVMe", "WiFi", "Battery", "System"];
1134 ORDER
1135 .iter()
1136 .filter_map(|cat| max.get(cat).map(|v| format!("{}: {:.0}°C", cat, v)))
1137 .collect()
1138}
1139
1140fn format_uptime(uptime: &str) -> String {
1144 let seconds: u64 = uptime.trim_end_matches('s').parse().unwrap_or(0);
1146
1147 let years = seconds / (365 * 24 * 3600);
1148 let days = (seconds % (365 * 24 * 3600)) / (24 * 3600);
1149 let hours = (seconds % (24 * 3600)) / 3600;
1150 let minutes = (seconds % 3600) / 60;
1151 let secs = seconds % 60;
1152
1153 let mut parts = Vec::new();
1154 if years > 0 {
1155 parts.push(format!("{}y", years));
1156 }
1157 if days > 0 {
1158 parts.push(format!("{}d", days));
1159 }
1160 if hours > 0 {
1161 parts.push(format!("{}h", hours));
1162 }
1163 if minutes > 0 {
1164 parts.push(format!("{}m", minutes));
1165 }
1166 if secs > 0 || parts.is_empty() {
1167 parts.push(format!("{}s", secs));
1168 }
1169
1170 parts.join(" ")
1171}
1172
1173#[cfg(feature = "graphics")]
1182fn graphical_logo_cells(bytes: &[u8]) -> (usize, usize) {
1183 let (img_w, img_h) = image::load_from_memory(bytes)
1184 .map(|img| (img.width(), img.height()))
1185 .unwrap_or((0, 0));
1186 let fit = logo::logo_cells_for(img_w, img_h);
1187 (fit.cols, fit.rows)
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192 use super::*;
1193
1194 #[test]
1197 fn test_show_logo_auto_requires_tty() {
1198 assert!(should_show_logo(None, false, false, true));
1200 assert!(!should_show_logo(None, false, false, false));
1201 }
1202
1203 #[test]
1204 fn test_show_logo_ascii_forces_without_tty() {
1205 assert!(should_show_logo(None, false, true, false));
1207 assert!(should_show_logo(None, false, true, true));
1208 }
1209
1210 #[test]
1211 fn test_show_logo_no_logo_always_wins() {
1212 assert!(!should_show_logo(None, true, true, true));
1214 assert!(!should_show_logo(None, true, false, true));
1215 }
1216
1217 #[test]
1218 fn test_show_logo_config_disable() {
1219 assert!(!should_show_logo(Some(false), false, false, true));
1221 assert!(should_show_logo(Some(false), false, true, false));
1223 }
1224
1225 #[test]
1228 fn test_visible_len_strips_every_escape_form_retch_emits() {
1229 assert_eq!(visible_len("plain"), 5);
1233 assert_eq!(visible_len("\x1b[38;2;1;2;3mabc\x1b[39m"), 3);
1234 assert_eq!(visible_len("\x1b[?25labc"), 3);
1235 assert_eq!(visible_len("\x1b(Babc"), 3);
1236 assert_eq!(visible_len("\x1b[0m \x1b[38;2;0;0;0m\u{2582}"), 2);
1237 }
1238
1239 #[test]
1240 fn test_visible_len_counts_columns_not_characters() {
1241 assert_eq!(visible_len("宇多田ヒカル"), 12); assert_eq!(visible_len("아이유"), 6); assert_eq!(visible_len("Media: 宇多田ヒカル - 花束を君に"), 32);
1247 assert_eq!(visible_len("Media: 아이유 - 밤편지"), 22);
1248
1249 assert_eq!(visible_len("cafe\u{301}"), 4);
1251 assert_eq!(visible_len("café"), 4);
1253
1254 assert_eq!(
1257 visible_len("\x1b[38;2;1;2;3m宇多田\x1b[39m"),
1258 visible_len("宇多田")
1259 );
1260 }
1261
1262 #[test]
1263 fn test_visible_len_ascii_art_and_chafa_symbols_are_one_column_each() {
1264 for line in logo::get_ascii_logo(Some("fedora")) {
1268 let stripped: String = strip_for_test(&line);
1269 assert_eq!(
1270 visible_len(&line),
1271 stripped.chars().count(),
1272 "fedora ASCII logo line is not one column per character: {stripped:?}"
1273 );
1274 }
1275 for sym in [
1277 '\u{2580}', '\u{2584}', '\u{2588}', '\u{258c}', '\u{2596}', '\u{2582}',
1278 ] {
1279 assert_eq!(visible_len(&sym.to_string()), 1, "{sym:?} is not 1 column");
1280 }
1281 }
1282
1283 fn strip_for_test(s: &str) -> String {
1286 let mut out = String::new();
1287 let mut in_esc = false;
1288 for c in s.chars() {
1289 if c == '\x1b' {
1290 in_esc = true;
1291 } else if in_esc {
1292 if c.is_ascii_alphabetic() {
1293 in_esc = false;
1294 }
1295 } else {
1296 out.push(c);
1297 }
1298 }
1299 out
1300 }
1301
1302 const CYAN: &str = "\x1b[38;2;0;255;255m";
1306 const RESET: &str = "\x1b[39m";
1307
1308 #[test]
1309 fn test_wrap_keeps_the_comma_it_split_on() {
1310 let out = wrap_info_line(
1314 "BIOS: American Megatrends International, LLC. HN7306EAC.310 (8//20/07/0)",
1315 40,
1316 );
1317 assert!(out.len() > 1, "expected a wrap, got {out:?}");
1318 assert!(
1319 out[0].ends_with(','),
1320 "separator lost at the break: {:?}",
1321 out[0]
1322 );
1323 let rejoined: String = out
1325 .iter()
1326 .map(|l| l.trim_start().to_string())
1327 .collect::<Vec<_>>()
1328 .join(" ");
1329 assert_eq!(
1330 rejoined,
1331 "BIOS: American Megatrends International, LLC. HN7306EAC.310 (8//20/07/0)"
1332 );
1333 }
1334
1335 #[test]
1336 fn test_wrap_reopens_the_colour_on_every_continuation_line() {
1337 let line =
1341 format!("BIOS: {CYAN}American Megatrends International, LLC. HN7306EAC.310{RESET}");
1342 let out = wrap_info_line(&line, 40);
1343 assert!(out.len() > 1, "expected a wrap, got {out:?}");
1344 for (i, l) in out.iter().enumerate().skip(1) {
1345 assert!(
1346 l.contains(CYAN),
1347 "continuation line {i} has no colour: {l:?}"
1348 );
1349 }
1350 for l in &out {
1352 if l.contains(CYAN) {
1353 assert!(l.ends_with(RESET), "colour left open on {l:?}");
1354 }
1355 }
1356 }
1357
1358 #[test]
1359 fn test_wrap_colour_carry_does_not_change_visible_width() {
1360 let plain = "BIOS: American Megatrends International, LLC. HN7306EAC.310";
1363 let coloured =
1364 format!("BIOS: {CYAN}American Megatrends International, LLC. HN7306EAC.310{RESET}");
1365 let a = wrap_info_line(plain, 40);
1366 let b = wrap_info_line(&coloured, 40);
1367 assert_eq!(a.len(), b.len());
1368 for (x, y) in a.iter().zip(b.iter()) {
1369 assert_eq!(visible_len(x), visible_len(y), "{x:?} vs {y:?}");
1370 }
1371 }
1372
1373 #[test]
1374 fn test_wrap_uncoloured_line_is_untouched_by_the_carry() {
1375 let out = wrap_info_line("Disk: aaaa, bbbb, cccc, dddd, eeee, ffff, gggg, hhhh", 24);
1376 assert!(out.len() > 1);
1377 assert!(
1378 out.iter().all(|l| !l.contains('\x1b')),
1379 "carry injected escapes into an uncoloured line: {out:?}"
1380 );
1381 }
1382
1383 #[test]
1384 fn test_active_sgr_after_tracks_open_and_reset() {
1385 assert_eq!(active_sgr_after("plain", None), None);
1386 assert_eq!(active_sgr_after(CYAN, None), Some(CYAN.to_string()));
1387 assert_eq!(active_sgr_after(&format!("{CYAN}x{RESET}"), None), None);
1388 assert_eq!(active_sgr_after("\x1b[0m", Some(CYAN.into())), None);
1389 assert_eq!(
1391 active_sgr_after("more text", Some(CYAN.into())),
1392 Some(CYAN.to_string())
1393 );
1394 assert_eq!(
1396 active_sgr_after("\x1b[?25l", Some(CYAN.into())),
1397 Some(CYAN.to_string())
1398 );
1399 }
1400
1401 #[test]
1402 fn test_active_sgr_after_takes_the_last_colour_when_nested() {
1403 let green = "\x1b[32m";
1406 let s = format!("{CYAN}[{green}Up{RESET}] RX: 1 MB");
1407 assert_eq!(active_sgr_after(&s, None), None); let s2 = format!("{CYAN}[{green}Up{RESET}]{CYAN} RX: 1 MB");
1409 assert_eq!(active_sgr_after(&s2, None), Some(CYAN.to_string()));
1410 }
1411
1412 #[test]
1415 fn test_row_places_the_logo_at_the_logo_column() {
1416 let row = compose_side_by_side_row("OS: Fedora", "###", 20);
1417 assert_eq!(row, format!("OS: Fedora{}###", " ".repeat(10)));
1418 assert_eq!(visible_len(&row), 23);
1419 }
1420
1421 #[test]
1422 fn test_row_aligns_wide_characters_by_column_not_character_count() {
1423 let latin = compose_side_by_side_row("Locale: en_US.UTF-8", "###", 40);
1428 let cjk = compose_side_by_side_row("Locale: ja_JP.宇多田ヒカル", "###", 40);
1429 assert_eq!(visible_len(&latin), 43);
1430 assert_eq!(
1431 visible_len(&cjk),
1432 43,
1433 "a wide-character info line must not shift the logo column"
1434 );
1435 assert!(latin.ends_with(" ###") && cjk.ends_with(" ###"));
1437 }
1438
1439 #[test]
1440 fn test_row_without_a_logo_gets_no_trailing_padding() {
1441 assert_eq!(compose_side_by_side_row("Net: eth0", "", 40), "Net: eth0");
1443 }
1444
1445 #[test]
1446 fn test_row_with_overlong_info_does_not_underflow() {
1447 let row = compose_side_by_side_row("x".repeat(50).as_str(), "###", 40);
1449 assert_eq!(row, format!("{}###", "x".repeat(50)));
1450 }
1451
1452 #[test]
1453 fn test_row_ignores_ansi_colour_when_measuring() {
1454 let plain = compose_side_by_side_row("abc", "###", 10);
1455 let coloured = compose_side_by_side_row("\x1b[31mabc\x1b[39m", "###", 10);
1456 assert_eq!(visible_len(&plain), visible_len(&coloured));
1457 }
1458
1459 fn realistic_full_widths() -> Vec<usize> {
1464 let mut w = vec![40; 20]; w[13] = 54; w.extend([158, 91, 79, 60, 45, 62]); w
1468 }
1469
1470 #[test]
1471 fn test_layout_long_line_below_logo_stays_side_by_side() {
1472 let p = plan_layout(&realistic_full_widths(), 20, 40, 120, true);
1474 assert!(p.side_by_side);
1475 assert_eq!(p.text_column_width, 58); }
1478
1479 #[test]
1480 fn test_layout_old_behavior_would_have_stacked() {
1481 let widths = realistic_full_widths();
1484 let old_text_col = std::cmp::max(widths.iter().copied().max().unwrap() + 4, 45);
1485 assert!(120 < old_text_col + 40); assert!(plan_layout(&widths, 20, 40, 120, true).side_by_side); }
1488
1489 #[test]
1490 fn test_layout_long_line_within_logo_wraps_and_stays_side_by_side() {
1491 let mut w = vec![40; 20];
1494 w[5] = 158;
1495 let p = plan_layout(&w, 20, 40, 120, true);
1496 assert!(p.side_by_side);
1497 assert_eq!(p.text_column_width, 65);
1498 }
1499
1500 #[test]
1501 fn test_layout_narrow_terminal_stacks() {
1502 assert!(!plan_layout(&[40; 30], 20, 40, 94, true).side_by_side); assert!(!plan_layout(&[40; 30], 20, 40, 80, true).side_by_side);
1504 }
1505
1506 #[test]
1507 fn test_layout_show_logo_false_stacks() {
1508 assert!(!plan_layout(&[40; 30], 20, 40, 200, false).side_by_side);
1509 }
1510
1511 #[test]
1512 fn test_layout_column_floor_and_graphical_width() {
1513 let p = plan_layout(&[10; 25], 20, 40, 100, true);
1515 assert!(p.side_by_side);
1516 assert_eq!(p.text_column_width, 45); }
1518
1519 #[test]
1520 fn test_layout_widened_logo_box_still_fits_at_the_side_by_side_threshold() {
1521 let p = plan_layout(&[10; 25], 10, logo::LOGO_MAX_COLS, 95, true);
1525 assert!(
1526 p.side_by_side,
1527 "a full-width logo must still sit beside the text at 95 columns"
1528 );
1529 assert!(p.text_column_width + logo::LOGO_MAX_COLS <= 95);
1530
1531 let wide = plan_layout(&[120; 25], 10, logo::LOGO_MAX_COLS, 169, true);
1533 assert!(wide.side_by_side);
1534 assert_eq!(wide.text_column_width, 65);
1535 }
1536
1537 #[test]
1538 fn test_layout_logo_taller_than_text() {
1539 let p = plan_layout(&[50, 30, 54], 20, 40, 120, true);
1541 assert!(p.side_by_side);
1542 assert_eq!(p.text_column_width, 58); }
1544
1545 #[test]
1546 fn test_layout_logo_is_flush_with_the_right_margin() {
1547 let p = plan_layout(&realistic_full_widths(), 20, 49, 138, true);
1552 assert!(p.side_by_side);
1553 assert_eq!(p.text_column_width, 58); assert_eq!(p.logo_column, 138 - 49); assert!(
1556 p.logo_column > p.text_column_width,
1557 "the pre-fix behaviour was logo_column == text_column_width"
1558 );
1559 }
1560
1561 #[test]
1562 fn test_layout_right_anchor_never_overlaps_the_text_column() {
1563 for term_width in 95..200 {
1566 let p = plan_layout(&[120; 25], 10, logo::LOGO_MAX_COLS, term_width, true);
1567 if p.side_by_side {
1568 assert!(
1569 p.logo_column >= p.text_column_width,
1570 "logo_column {} < text_column_width {} at {} cols",
1571 p.logo_column,
1572 p.text_column_width,
1573 term_width
1574 );
1575 assert_eq!(p.logo_column + logo::LOGO_MAX_COLS, term_width);
1576 }
1577 }
1578 }
1579
1580 #[test]
1581 fn test_layout_logo_column_does_not_underflow_on_an_oversized_logo() {
1582 let p = plan_layout(&[40; 10], 10, 200, 100, true);
1584 assert!(!p.side_by_side);
1585 assert_eq!(p.logo_column, p.text_column_width);
1586 }
1587
1588 #[test]
1591 fn test_prelude_reserves_rows_before_saving_cursor() {
1592 let p = graphical_side_by_side_prelude(52, 3);
1596 assert_eq!(p, "\n\n\n\x1b[3A\x1b[52C\x1b7");
1597 }
1598
1599 #[test]
1600 fn test_prelude_v068_shape_only_differs_by_reservation() {
1601 let p = graphical_side_by_side_prelude(45, 20);
1604 assert_eq!(
1605 p.replace(&format!("{}\x1b[20A", "\n".repeat(20)), ""),
1606 "\x1b[45C\x1b7"
1607 );
1608 }
1609
1610 #[test]
1611 fn test_prelude_zero_rows_skips_reservation_and_cursor_up() {
1612 let p = graphical_side_by_side_prelude(45, 0);
1615 assert_eq!(p, "\x1b[45C\x1b7");
1616 }
1617
1618 #[test]
1621 fn test_split_wifi_hardware_and_connection() {
1622 let s = "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0] - myssid (5.0 GHz ch36 [↓866 ↑866])";
1624 let (hw, conn) = split_wifi_line(s);
1625 assert_eq!(
1626 hw,
1627 "MEDIATEK Corp. MT7925 802.11be [Filogic 360] [wlp194s0]"
1628 );
1629 assert_eq!(conn, Some("myssid (5.0 GHz ch36 [↓866 ↑866])"));
1630 }
1631
1632 #[test]
1633 fn test_split_wifi_splits_on_first_separator() {
1634 let (hw, conn) = split_wifi_line("Card X [wlan0] - Guest - 5G (5 GHz)");
1637 assert_eq!(hw, "Card X [wlan0]");
1638 assert_eq!(conn, Some("Guest - 5G (5 GHz)"));
1639 }
1640
1641 #[test]
1642 fn test_split_wifi_connection_only_fallback() {
1643 let (hw, conn) = split_wifi_line("myssid (300 Mbps)");
1645 assert_eq!(hw, "myssid (300 Mbps)");
1646 assert_eq!(conn, None);
1647 }
1648
1649 #[test]
1650 fn test_consolidate_temps_basic() {
1651 let raw = vec![
1652 "k10temp Tctl: 83°C".to_string(),
1653 "amdgpu edge: 65°C".to_string(),
1654 "nvme Composite: 62°C".to_string(),
1655 "ath11k_hwmon temp1: 58°C".to_string(),
1656 "acpitz temp1: 77°C".to_string(),
1657 ];
1658 let result = consolidate_temps(&raw);
1659 assert_eq!(
1660 result,
1661 vec![
1662 "CPU: 83°C",
1663 "GPU: 65°C",
1664 "NVMe: 62°C",
1665 "WiFi: 58°C",
1666 "System: 77°C"
1667 ]
1668 );
1669 }
1670
1671 #[test]
1672 fn test_consolidate_temps_highest_wins() {
1673 let raw = vec![
1674 "thinkpad CPU: 83°C".to_string(),
1675 "k10temp Tctl: 79°C".to_string(),
1676 "nvme Composite: 62°C".to_string(),
1677 "nvme Sensor 1: 59°C".to_string(),
1678 "nvme Sensor 2: 56°C".to_string(),
1679 ];
1680 let result = consolidate_temps(&raw);
1681 assert!(result.contains(&"CPU: 83°C".to_string()));
1682 assert!(result.contains(&"NVMe: 62°C".to_string()));
1683 assert!(!result
1684 .iter()
1685 .any(|s| s.contains("79") || s.contains("59") || s.contains("56")));
1686 }
1687
1688 #[test]
1689 fn test_consolidate_temps_order() {
1690 let raw = vec![
1691 "acpitz: 60°C".to_string(),
1692 "nvme: 55°C".to_string(),
1693 "amdgpu edge: 65°C".to_string(),
1694 "k10temp Tctl: 80°C".to_string(),
1695 ];
1696 let result = consolidate_temps(&raw);
1697 let cpu_pos = result.iter().position(|s| s.starts_with("CPU"));
1698 let gpu_pos = result.iter().position(|s| s.starts_with("GPU"));
1699 let nvme_pos = result.iter().position(|s| s.starts_with("NVMe"));
1700 let sys_pos = result.iter().position(|s| s.starts_with("System"));
1701 assert!(cpu_pos < gpu_pos);
1702 assert!(gpu_pos < nvme_pos);
1703 assert!(nvme_pos < sys_pos);
1704 }
1705
1706 #[test]
1707 fn test_consolidate_temps_empty() {
1708 assert!(consolidate_temps(&[]).is_empty());
1709 }
1710
1711 #[test]
1712 fn test_format_uptime() {
1713 assert_eq!(format_uptime("60s"), "1m");
1714 assert_eq!(format_uptime("3600s"), "1h");
1715 assert_eq!(format_uptime("3661s"), "1h 1m 1s");
1716 assert_eq!(format_uptime("86400s"), "1d");
1717 assert_eq!(format_uptime("90061s"), "1d 1h 1m 1s");
1718 assert_eq!(format_uptime("31536000s"), "1y");
1719 assert_eq!(format_uptime("31626061s"), "1y 1d 1h 1m 1s");
1720 assert_eq!(format_uptime("0s"), "0s");
1721 }
1722
1723 #[test]
1724 fn test_wrap_info_line_short_line_unchanged() {
1725 let line = "Audio: Windows Audio (USB Audio Device)";
1726 let wrapped = wrap_info_line(line, 50);
1727 assert_eq!(wrapped, vec![line.to_string()]);
1728 }
1729
1730 #[test]
1731 fn test_wrap_info_line_wraps_and_indents() {
1732 let line = "Audio: Windows Audio (USB Audio Device, AMD High Definition Audio Device, AMD SoundWire Device)";
1733 let wrapped = wrap_info_line(line, 45);
1734 assert!(wrapped.len() > 1);
1735 assert!(wrapped[0].starts_with("Audio: Windows Audio"));
1736 assert!(wrapped[1].starts_with(" "));
1737 }
1738}