Skip to main content

retch_cli/
display.rs

1// SPDX-FileCopyrightText: 2026 Ken Tobias
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4//! Formatting and display logic for terminal output.
5//!
6//! Handles text rendering, layout, and image/ASCII logo rendering.
7
8use 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
16/// Decide whether to render a logo at all.
17///
18/// In *auto* mode the logo is shown only when stdout is a TTY: the graphical and
19/// Chafa heuristics (and the side-by-side layout) are meaningless when output is
20/// piped or redirected, so we suppress the logo there. Two explicit overrides break
21/// that rule:
22/// - `no_logo` (from `--no-logo` or config) always wins → no logo.
23/// - `ascii_logo` (from `--ascii-logo`) forces the logo on **even without a TTY**:
24///   ASCII art is plain, pipe-safe text, so a caller (e.g. `retch --ascii-logo | cat`,
25///   or CI's `full-test` dry run) that explicitly asks for it should get it — mirroring
26///   how `--no-logo` is honored regardless of TTY. `--chafa-logo`/graphical modes are
27///   deliberately NOT forced here, since they emit terminal-specific control sequences
28///   that are only meaningful on a real terminal.
29fn 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; // explicit suppression always wins
37    }
38    if ascii_logo {
39        return true; // explicit ASCII request forces the logo on, TTY or not, config or not
40    }
41    config_show_logo.unwrap_or(true) && stdout_is_tty // auto mode: default-on, but TTY-gated
42}
43
44/// Result of [`plan_layout`]: whether the logo sits beside the text, the width the info
45/// lines beside the logo wrap to, and the column the logo itself is drawn at.
46///
47/// `text_column_width` and `logo_column` are deliberately **separate**. The first bounds how
48/// wide a beside-logo info line may grow; the second is where the logo block starts. Folding
49/// them into one value is what let the logo drift inward: the text column is clamped to 65
50/// columns, so on a wide terminal the logo was drawn at column 65 with the rest of the
51/// terminal left empty.
52struct LayoutPlan {
53    side_by_side: bool,
54    text_column_width: usize,
55    logo_column: usize,
56}
57
58/// Decide side-by-side vs. stacked layout, and the text-column width, from the geometry of
59/// the info block and the currently-selected logo.
60///
61/// Only the info lines that actually sit **beside** the logo — the first `logo_height` rows —
62/// constrain the layout. In `--long`/`--full` the widest lines (Wi-Fi, Network, Battery) fall
63/// *below* the logo, where nothing overlaps them, so they must neither widen the text column
64/// nor force a stacked layout. Basing the decision on every line (the previous behaviour) let
65/// a single 150+ char Wi-Fi line push the logo above the text on any normal-width terminal.
66///
67/// This is logo-type-agnostic: `logo_height`/`logo_width` are supplied by the caller from the
68/// active logo, so it works identically for ASCII art, Chafa (both rendered as text lines),
69/// and the graphical image protocols (Kitty/iTerm2/Sixel, whose cell footprint comes from
70/// [`logo::fit_logo_cells`] — the *same* call the emitters use to size the image, so the
71/// reserved area and the drawn area cannot disagree).
72///
73/// In side-by-side mode the logo is **flush against the right margin** (`logo_column =
74/// term_width - logo_width`), not butted up against the end of the text column. The two used
75/// to be the same number, which was only ever right by accident: before the text column was
76/// narrowed to the beside-logo lines (v0.6.8) and then clamped to 65 (v0.6.16), a long
77/// `Wi-Fi`/`Net` line inflated it far enough that the logo happened to land near the edge.
78/// Afterwards it sat at column 65 on every wide terminal, stranding the remainder.
79///
80/// Right-anchoring can never push the logo *left* of the text: `side_by_side` already
81/// requires `term_width >= text_column_width + logo_width`, so `term_width - logo_width` is
82/// at least `text_column_width`.
83///
84/// `info_widths` are the ANSI-stripped visible widths of the info lines, in render order.
85fn 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    // Flush right. The `max(text_column_width)` floor is belt-and-braces: the `side_by_side`
108    // condition above already guarantees it, and the value is unused when stacked.
109    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
117/// Strip ANSI escape sequences and return the string's width in **terminal columns**.
118///
119/// Not a character count. A CJK ideograph or a Hangul syllable occupies two columns, a
120/// combining mark occupies none, and an emoji followed by the variation selector U+FE0F
121/// (`☀️`) is two columns even though its base character alone would be one — none of which a
122/// `chars().count()` can express.
123///
124/// This matters because every layout decision in this module is denominated in columns: the
125/// padding that positions the logo, the wrap width for beside-logo lines, and the logo's own
126/// measured width. Counting characters undercounted `Media: 宇多田ヒカル - 花束を君に` by 11
127/// columns, so the line overran its column and pushed the logo out of alignment on that row.
128/// `media`/`player` (v0.8.0) read arbitrary track metadata, so non-Latin text is an ordinary
129/// input here, not an exotic one.
130///
131/// Escape handling is unchanged: `\x1b` opens a sequence that ends at the first ASCII letter,
132/// which covers the CSI (`\x1b[…m`), charset (`\x1b(B`) and private (`\x1b[?25l`) forms that
133/// `owo_colors` and `chafa` emit.
134///
135/// The visible characters are measured as one run rather than summed per character, because
136/// width is not a per-character property: variation-selector and zero-width-joiner sequences
137/// are only correct when the whole grapheme is measured together.
138pub 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
157/// Wrap a formatted info line (key: value) at logical boundaries to fit within `max_width`.
158///
159/// Continuation lines are indented to align with the start of the value portion.
160/// Prefers splitting on logical delimiters (e.g. `, `, ` - `) over arbitrary space boundaries,
161/// keeping atomic pairs (like `RX: ... TX: ...`) on the same line.
162pub 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    // Try logical splitting by comma (", ") if present
183    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(&current) + item_vis <= max_width {
197                current.push_str(&item);
198            } else {
199                // Keep the separator we split on. Dropping it changed the *data*, not just
200                // its appearance: `American Megatrends International, LLC.` wrapped to
201                // `…International` / `LLC.`, which reads as two values rather than one
202                // company name. The comma stays on the preceding line, as in prose.
203                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    // Whitespace splitting fallback: group RX/TX headers with their values
216    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(&current) + 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        // No separator to retain here — this branch breaks on whitespace, and a space at a
264        // line break needs no visible marker the way a comma does.
265        carry_sgr_across_lines(lines)
266    }
267}
268
269/// The foreground-colour SGR sequence still in effect at the end of `s`, given the sequence
270/// `entry` that was in effect when it started.
271///
272/// Only foreground colour is tracked, because that is all `Theme`/`owo_colors` emit here.
273/// A reset — `\x1b[0m` or `\x1b[39m` — clears it; any other `…m` sequence becomes the new
274/// state. Non-`m` sequences (cursor moves, chafa's `\x1b[?25l`) are ignored.
275fn 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
304/// Re-open the active colour on every continuation line, and close it at each line end.
305///
306/// Info lines are colourised **before** they are wrapped, so a value split across lines has
307/// its opening SGR on the first line and its closing `\x1b[39m` on the last: every line in
308/// between renders in the terminal's default colour. Reported against a wrapped `BIOS:` value,
309/// whose second line came out uncoloured while the first was cyan.
310///
311/// Fixing it at the wrap step rather than by colourising after wrapping is deliberate — the
312/// wrap points are chosen from *visible* width, so wrapping has to see the escapes anyway.
313///
314/// Only zero-width escape sequences are added, so [`visible_len`] of every line is unchanged
315/// and the widths the layout already computed still hold.
316fn 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            // Close the colour at the line end so it cannot bleed into the logo column.
328            Some(_) => format!("{reopened}\x1b[39m"),
329            None => reopened,
330        });
331    }
332    out
333}
334
335/// Split the Wi-Fi detail string into `(hardware, connection)` for two-line display.
336///
337/// The Linux `iw` path builds `"{adapter model} [{iface}] - {SSID} ({band/rate})"` — hardware
338/// and connection joined by `" - "`. Splitting on the first `" - "` puts the adapter on one
339/// line ("Wi-Fi") and the live connection on a second ("Wi-Fi Link"), so neither is the
340/// 150+ char line that used to wrap and collide with the logo. The fallback detectors
341/// (nmcli/iwgetid/macOS/Windows) return only the connection with no `" - "`, so those render
342/// as a single line (`connection` is `None`).
343fn 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
350/// Compose one row of the side-by-side layout: the info line, padded out to `logo_column`,
351/// followed by the logo line.
352///
353/// Padding goes to the **logo column** (the right margin), not merely to the end of the text
354/// column. Rows with no logo content get none at all — otherwise every line below the logo
355/// would carry ~90 trailing spaces.
356///
357/// Extracted from `display()`'s render loop deliberately. This arithmetic used to be inline
358/// there, alongside a local `visible_len` closure that shadowed the module function for the
359/// whole of `display()`; the shadow was a byte-for-byte copy of an older, character-counting
360/// implementation, so the layout silently measured characters while the module function —
361/// and its unit tests — measured columns. A free function cannot be shadowed by a local
362/// binding in another function's body, so the two can no longer diverge, and this is now
363/// directly testable without a pseudo-terminal.
364fn 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
375/// Escape prelude for [`render_graphical_side_by_side`]: reserve `logo_rows` rows with
376/// newlines, move back up to the image-top row, shift right to `logo_column`, and save the
377/// cursor (`\x1b7`).
378///
379/// The reservation is the scroll-safety mechanism: printing the newlines *first* forces any
380/// scrolling to happen before the cursor is saved, so nothing between the save and the
381/// restore can scroll. Without it, drawing the image with the cursor near the bottom margin
382/// scrolled the screen mid-draw, and `\x1b8` — which restores a *viewport-relative*
383/// position — landed on the row below the image instead of beside its top (text rendered
384/// under the logo; reproduced on Rio and kitty alike whenever the prompt sat near the
385/// bottom of a used terminal).
386///
387/// `logo_rows == 0` emits no reservation and no cursor-up (`CSI 0 A` would still move one
388/// row on real terminals).
389fn 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
399/// Render an image-protocol logo (Kitty/iTerm2/Sixel) beside the info text, scroll-safely.
400///
401/// The logo's rows are **reserved first** (newlines, then cursor-up — see
402/// [`graphical_side_by_side_prelude`]) so any scrolling happens up front; the image is then
403/// drawn at the top of the logo column bracketed by save/restore (`\x1b7`/`\x1b8`), which is
404/// only valid because no scroll can occur between the two. The info lines are then printed
405/// top-to-bottom at column 0, so the terminal scrolls naturally and carries the cell-anchored
406/// image with it.
407///
408/// This replaces two broken predecessors: "print all text, then `\x1b[{n}A` back up and draw"
409/// (clamped at the viewport top for tall `--long`/`--full` output, drawing the image
410/// mid-text) and the v0.6.8 unreserved save/draw/restore (correct on a fresh screen, but with
411/// the prompt near the bottom the draw scrolled the screen and the restore landed *below* the
412/// image). Residual risk: the draw can still scroll only if the image's real row count
413/// exceeds `logo_rows` — the same cell-height estimate the layout already trusts.
414fn 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    // Reserve the logo rows (scroll now, if at all), return to the image-top row at the
422    // logo column, save, draw the image, restore, return to column 0.
423    print!("{}", graphical_side_by_side_prelude(logo_column, logo_rows));
424    draw(); // emits the image escape (and may move the cursor / print a newline)
425    print!("\x1b8\r");
426    for line in info_lines {
427        println!("{}", line);
428    }
429    // If the image is taller than the text block, advance past its bottom edge so a following
430    // shell prompt doesn't overlap it.
431    for _ in info_lines.len()..logo_rows {
432        println!();
433    }
434    let _ = std::io::stdout().flush();
435}
436
437/// Renders the collected system information to the terminal.
438///
439/// This function handles theme selection, logo rendering (including fallbacks
440/// between graphics, Chafa, and ASCII), and field filtering based on
441/// CLI flags and configuration.
442/// Splits interfaces into (active, everything else), preserving order within each group.
443///
444/// **The active interface is identified by an exact NAME match**, which is the whole point
445/// of this function existing. It replaces `line.contains(active)` over the rendered line,
446/// which matched any interface whose *presentation* happened to contain the active name:
447/// on Windows `Wi-Fi` matched the `Wi-Fi-Native WiFi Filter Driver-0000` pseudo-interface,
448/// so both were printed as the active interface; on Linux `eth0` matches an `eth0.100`
449/// VLAN or a `veth0…` pair. Substring-matching a formatted string cannot answer a question
450/// about identity, and it also read the addresses and byte counts, not just the name.
451fn 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
458/// Chooses the single interface standard mode shows: the active one, else the first that
459/// is up.
460///
461/// The fallback is the part that was broken. It used to test `line.contains("[Up]")`, but
462/// the status is colourised before the line is built, so the bytes are
463/// `[` + `ESC[32m` + `Up` + `ESC[39m` + `]` and the literal `[Up]` **never appears** —
464/// the branch could not fire, and standard mode printed no `Net` line at all whenever the
465/// active interface could not be resolved. Keyed on the interface's own `is_up` now.
466fn 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(), // Default to system preference
481    };
482
483    // Apply custom theme overrides from config if present
484    if let Some(custom) = &_config.custom_theme {
485        theme = Theme::with_custom_overrides(theme, custom);
486    }
487
488    // Determine terminal width.
489    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    // Use isatty() directly — terminal_size() can return Some() when a pager
496    // (e.g. bat) allocates a PTY, giving a false positive.
497    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    // Determine which fields to show. Strata allow-lists are derived from the
507    // single field registry (src/fields.rs) — the same source `main.rs` uses for
508    // collection, so display and collection can no longer drift apart. An explicit
509    // `config.fields` list bypasses the strata.
510    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                        // "dns" field key matches "DNS Server" display label
532                        || (norm_label == "dns server" && norm_f == "dns")
533                        // "memory" field key matches "Memory Usage" display label
534                        || (norm_label == "memory usage" && norm_f == "memory")
535                        // "Wi-Fi Link" (the connection line) maps to the "wifi" field key
536                        || (norm_label == "wi fi link" && norm_f == "wifi")
537                })
538            }
539            None => true,
540        }
541    };
542
543    // Helper for right-aligned labels
544    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    // OS / system identity
559    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    // Suppress "Users: 0" — a 0 means the count couldn't be determined (e.g. the Unix
585    // uid>=1000 heuristic on a platform that keys users differently), not that nobody is
586    // logged in. Mirrors the `packages` guard below.
587    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    // Uptime belongs with system identity, not hardware
599    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    // Hardware
604    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        // Split the (often 150+ char) Wi-Fi string into a hardware line and a connection line
664        // so neither wraps and collides with the logo. See `split_wifi_line`.
665        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    // Network
727    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                // Re-assert bright blue after the nested green "Up" /
733                // red "Down" reset so the whole active line stays blue
734                // (brackets and RX/TX included), not just up to "[".
735                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    // Environment
757    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    // Setup logo representation
820    enum ActiveLogo {
821        Lines(Vec<String>),
822        Kitty(Vec<u8>, usize, usize), // bytes, cols, rows
823        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            // Kitty
875            #[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            // iTerm2
893            #[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            // Sixel
911            #[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            // Chafa
929            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                        // Write temp logo and read lines via chafa
938                        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            // Fallback to ASCII lines
952            if !resolved {
953                active_logo =
954                    ActiveLogo::Lines(logo::get_distro_logo_lines(distro_hint.as_deref()));
955            }
956        }
957    }
958
959    // NOTE: `display()` previously defined a local `visible_len` closure here that was a
960    // byte-for-byte copy of the module-level [`visible_len`] and shadowed it for this entire
961    // function — which is where every layout decision is made. It has been removed so there
962    // is one implementation. Do not reintroduce a local helper by this name: the shadow was
963    // invisible at every call site (the calls below read identically either way), and it
964    // silently reverted this module's width handling for the layout while the module
965    // function's own unit tests kept passing.
966    let info_widths: Vec<usize> = info_lines.iter().map(|line| visible_len(line)).collect();
967
968    // Height (row count) and width of the active logo, whatever its kind. ASCII and Chafa are
969    // both `Lines`; the graphical protocols carry their pixel-derived row count and use the
970    // fixed image column width.
971    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    // Only the lines beside the logo constrain placement — a long Wi-Fi/Network line below it
987    // must not force a stacked layout. See `plan_layout`.
988    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!(); // leading newline
1001
1002    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            // Beside-logo rows may use every column up to the logo, not just the text
1006            // column. Those were the same number until the logo was anchored to the right
1007            // margin; afterwards, wrapping at the text column left a wrapped line with the
1008            // whole gap to the logo unused — a 283-column terminal wrapped `BIOS:` at 55
1009            // columns with ~177 free to its right. Below-logo rows already use the full
1010            // terminal width, so this makes the two consistent.
1011            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        // Narrow or no-logo fallback: print logo, then print data
1068        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
1097/// Returns the highest temperature per physical category from a raw sensor list.
1098///
1099/// Input strings are formatted as `"label: 83°C"`. Output is one entry per
1100/// detected category (CPU / GPU / NVMe / WiFi / Battery / System), ordered
1101/// from most to least specific. Used by `--long` mode; `--full` shows the raw list.
1102fn 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        // Parse "some label: 83°C"
1141        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
1160/// Formats a raw uptime string (in seconds) into a human-readable duration.
1161///
1162/// Example: "45224s" -> "12h 33m 44s"
1163fn format_uptime(uptime: &str) -> String {
1164    // Parse the uptime string (e.g. "45224s")
1165    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/// Returns the `(columns, rows)` a graphical logo image will occupy on this terminal.
1194///
1195/// Delegates to [`logo::logo_cells_for`], which is also what the Kitty/iTerm2/Sixel emitters
1196/// use to size the image itself — so the footprint reserved by [`plan_layout`] and the
1197/// footprint actually drawn are the same numbers by construction. They used to be computed
1198/// independently (rows here from the pixel height, width hardcoded to 40, and the Kitty
1199/// escape hardcoding a third answer), which is how the logo ended up stretched *and*
1200/// mis-positioned.
1201#[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    // ── net line selection ────────────────────────────────────────────────────
1215
1216    fn net(name: &str, is_up: bool) -> NetworkInterface {
1217        // The status is COLOURISED, exactly as `detect_networks` builds it, so the literal
1218        // "[Up]" does not appear in the line. That is not incidental detail: the bug being
1219        // guarded is a `line.contains("[Up]")` test that could never match, and a fixture
1220        // with a plain "[Up]" would let that broken predicate pass and prove nothing.
1221        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        // The Windows case that shipped: an NDIS filter pseudo-interface whose name has
1236        // the real adapter's name as a prefix. Both were previously printed as active.
1237        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        // The same defect on Linux, where it is not hidden by any filtering: a VLAN and a
1251        // veth pair both carry the parent's name as a prefix.
1252        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        // This is the branch that could never fire: it tested the rendered line for the
1281        // literal "[Up]", which is never present because the status is colourised. With
1282        // no active interface, standard mode printed NO Net line at all.
1283        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        // Same fallback when the active interface is known but absent from the list.
1288        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        // Under-reporting beats asserting something false: no up interface means no line,
1295        // rather than presenting a down one as the connection.
1296        let nets = vec![net("eth0", false), net("eth1", false)];
1297        assert!(choose_net_line(&nets, None).is_none());
1298    }
1299
1300    // ── should_show_logo ──────────────────────────────────────────────────────
1301
1302    #[test]
1303    fn test_show_logo_auto_requires_tty() {
1304        // Auto mode (no explicit flags): logo only on a TTY.
1305        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        // --ascii-logo forces the logo even when stdout is not a TTY (pipe / CI).
1312        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        // --no-logo suppresses even when --ascii-logo is set or on a TTY.
1319        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        // config show_logo=false suppresses in auto mode...
1326        assert!(!should_show_logo(Some(false), false, false, true));
1327        // ...but an explicit --ascii-logo still forces it on (CLI overrides config default).
1328        assert!(should_show_logo(Some(false), false, true, false));
1329    }
1330
1331    // ── visible_len ───────────────────────────────────────────────────────────
1332
1333    #[test]
1334    fn test_visible_len_strips_every_escape_form_retch_emits() {
1335        // owo_colors' SGR, its default-reset, chafa's private-mode cursor hide, and the
1336        // charset designator. `\x1b[?25l` is the one that bit a measurement harness during
1337        // this work: it is 6 characters and an SGR-only stripper leaves all of them.
1338        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        // Regression: this returned a char count, so every wide glyph was undercounted by
1348        // one column. `media`/`player` (v0.8.0) surface arbitrary track metadata, so CJK and
1349        // Hangul are ordinary inputs.
1350        assert_eq!(visible_len("宇多田ヒカル"), 12); // 6 ideographs, 2 columns each
1351        assert_eq!(visible_len("아이유"), 6); // 3 Hangul syllables
1352        assert_eq!(visible_len("Media: 宇多田ヒカル - 花束を君に"), 32);
1353        assert_eq!(visible_len("Media: 아이유 - 밤편지"), 22);
1354
1355        // Combining marks add no width: "cafe" + U+0301 renders as four columns.
1356        assert_eq!(visible_len("cafe\u{301}"), 4);
1357        // Precomposed form measures the same, so the two spellings cannot disagree.
1358        assert_eq!(visible_len("café"), 4);
1359
1360        // A colour-wrapped wide value must measure the same as the bare one — the layout
1361        // sees the wrapped form.
1362        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        // Every shipped logo is ASCII or narrow block-drawing, which is why the char-count
1371        // bug never showed on a logo. Pin that, so a future wide-glyph asset fails here
1372        // rather than silently overflowing the right margin.
1373        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        // Chafa's half-block/quadrant symbols are all narrow.
1382        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    /// Test-only escape stripper, deliberately independent of [`visible_len`] so the test
1390    /// above compares two different implementations rather than one against itself.
1391    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    // ── wrap_info_line: separator retention and colour carry ──────────────────
1409
1410    /// The shape `Theme::color_value` produces: `<SGR>value<reset>`.
1411    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        // Regression: the comma was dropped at the break, so a wrapped
1417        // `American Megatrends International, LLC.` read as two separate values. That is a
1418        // change to the data, not to its presentation.
1419        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        // And nothing is invented or dropped: rejoining recovers the original text.
1430        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        // Reported symptom: a wrapped BIOS value rendered its second line in the terminal
1444        // default because the opening SGR stayed on line 1 and the closing reset landed on
1445        // the last line.
1446        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        // Every line that opens a colour also closes it, so none can bleed into the logo.
1457        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        // The escapes added must be zero-width, or every layout number computed from these
1467        // lines would be wrong.
1468        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        // Carried in from the previous line and never reset here.
1496        assert_eq!(
1497            active_sgr_after("more text", Some(CYAN.into())),
1498            Some(CYAN.to_string())
1499        );
1500        // A non-`m` sequence (chafa's cursor hide) must not disturb the colour state.
1501        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        // The `Net` line embeds a green Up inside the value colour (v0.5.1). Whatever the
1510        // nesting, the state at end-of-line is simply the last sequence seen.
1511        let green = "\x1b[32m";
1512        let s = format!("{CYAN}[{green}Up{RESET}] RX: 1 MB");
1513        assert_eq!(active_sgr_after(&s, None), None); // last was the reset
1514        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    // ── compose_side_by_side_row ──────────────────────────────────────────────
1519
1520    #[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        // The regression that hid behind a shadowed `visible_len`: the layout measured
1530        // characters while the module function measured columns, so a CJK value pushed the
1531        // logo right by one column per wide glyph. Both rows below must put the logo at
1532        // exactly the same column.
1533        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        // And the logo really is at column 40 in both, not merely the same total width.
1542        assert!(latin.ends_with("   ###") && cjk.ends_with("  ###"));
1543    }
1544
1545    #[test]
1546    fn test_row_without_a_logo_gets_no_trailing_padding() {
1547        // Lines below the logo would otherwise carry ~90 trailing spaces each.
1548        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        // An info line wider than the logo column must not panic on the subtraction.
1554        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    // ── plan_layout ───────────────────────────────────────────────────────────
1566
1567    // A ~20-row logo with the widest beside-logo line = 54 (e.g. the CPU line), then a very
1568    // long Wi-Fi line (158) far below it — the real --full shape on this hardware.
1569    fn realistic_full_widths() -> Vec<usize> {
1570        let mut w = vec![40; 20]; // rows 0..20 sit beside the logo
1571        w[13] = 54; // CPU line, still beside the logo
1572        w.extend([158, 91, 79, 60, 45, 62]); // Wi-Fi/Net/Battery/etc., all BELOW the logo
1573        w
1574    }
1575
1576    #[test]
1577    fn test_layout_long_line_below_logo_stays_side_by_side() {
1578        // The 158-wide Wi-Fi line is below the 20-row logo, so it must NOT force a stack.
1579        let p = plan_layout(&realistic_full_widths(), 20, 40, 120, true);
1580        assert!(p.side_by_side);
1581        // Text column is driven by the widest BESIDE-logo line (54), not the 158 below it.
1582        assert_eq!(p.text_column_width, 58); // 54 + 4
1583    }
1584
1585    #[test]
1586    fn test_layout_old_behavior_would_have_stacked() {
1587        // Sanity: the pre-fix rule (widest of ALL lines) would need 158+4+40 = 202 cols and
1588        // stack at 120. Confirm the *new* rule does not, on the same inputs.
1589        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); // old rule: stacked
1592        assert!(plan_layout(&widths, 20, 40, 120, true).side_by_side); // new rule: side-by-side
1593    }
1594
1595    #[test]
1596    fn test_layout_long_line_within_logo_wraps_and_stays_side_by_side() {
1597        // A 158-wide line among the first `logo_height` rows no longer breaks side-by-side layout
1598        // because text_column_width is clamped and the line is wrapped.
1599        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); // < 95 hard floor
1609        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        // Tiny lines → text column floored at 45; graphical logo width (40) still applies.
1620        let p = plan_layout(&[10; 25], 20, 40, 100, true);
1621        assert!(p.side_by_side);
1622        assert_eq!(p.text_column_width, 45); // max(10+4, 45)
1623    }
1624
1625    #[test]
1626    fn test_layout_widened_logo_box_still_fits_at_the_side_by_side_threshold() {
1627        // The logo cell box grew from 28 to `logo::LOGO_MAX_COLS` (45) so wide-aspect logos get
1628        // enough rows to stay legible. That must not cost the side-by-side layout at the 95-col
1629        // threshold: the text column floors at 45, and 45 + 45 = 90 <= 95.
1630        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        // And a wide terminal is unaffected — the text column still reaches its 65 cap.
1638        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        // Fewer info lines than logo rows: all lines are beside the logo (no panic on slice).
1646        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); // widest of the 3 (54) + 4
1649    }
1650
1651    #[test]
1652    fn test_layout_logo_is_flush_with_the_right_margin() {
1653        // The drift this fixes: on a wide terminal the logo used to be drawn at
1654        // `text_column_width` (capped at 65), stranding everything to its right. Measured on
1655        // arrakis at 138 columns with the 49-wide Windows ASCII logo: output stopped at
1656        // column 103, leaving 35 dead columns.
1657        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); // unchanged: still driven by the beside lines
1660        assert_eq!(p.logo_column, 138 - 49); // logo now ends exactly at the right margin
1661        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        // At the 95-column threshold with a full-width logo the two columns meet exactly;
1670        // the logo must never be pulled left of where beside-logo text can reach.
1671        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        // A logo wider than the terminal stacks, and the (unused) column must not underflow.
1689        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    // ── graphical_side_by_side_prelude ────────────────────────────────────────
1695
1696    #[test]
1697    fn test_prelude_reserves_rows_before_saving_cursor() {
1698        // Regression for the below-the-logo bug (Rio/kitty, prompt at the bottom row): the
1699        // scroll-forcing reservation (newlines) and the cursor-up must both come BEFORE the
1700        // cursor save, so nothing between save and restore can scroll.
1701        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        // With the reservation stripped, the prelude is exactly the v0.6.8 bytes — the fresh
1708        // top-of-screen rendering (where no scroll happens) is unchanged.
1709        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        // CSI 0 A still moves one row on real terminals, so logo_rows == 0 must emit
1719        // neither the reservation nor the cursor-up.
1720        let p = graphical_side_by_side_prelude(45, 0);
1721        assert_eq!(p, "\x1b[45C\x1b7");
1722    }
1723
1724    // ── split_wifi_line ───────────────────────────────────────────────────────
1725
1726    #[test]
1727    fn test_split_wifi_hardware_and_connection() {
1728        // The real `iw`-path shape: "{adapter} [{iface}] - {ssid} ({details})".
1729        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        // Only the first " - " (the hardware|connection boundary) splits; a " - " inside the
1741        // SSID/details stays with the connection.
1742        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        // Fallback detectors (nmcli/iwgetid/macOS/Windows) have no " - " → single line.
1750        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}