Skip to main content

i3status_rs/
doctor.rs

1//! `--doctor`: diagnose configuration problems.
2//!
3//! The report is assessment-first: short status lines for what works, a
4//! per-block live test, a per-glyph icon table, and a final Problems list
5//! where every finding gets a one-line diagnosis and a matter-of-fact fix.
6//!
7//! Sections:
8//! - Header: which config file, icon set file and bar font are in use (the
9//!   bar font is auto-detected from a running i3/sway over IPC; `--font`
10//!   overrides it).
11//! - Blocks: every configured block is instantiated and run for one cycle
12//!   (unless `--doctor-skip-live`), showing its rendered output or a
13//!   diagnosed failure — including render errors, which are explained with
14//!   the placeholders the block actually provided. Note that this performs
15//!   real work: network requests, command execution, D-Bus calls.
16//! - Icons: one row per glyph with its codepoint and the font that will
17//!   actually draw it (via fontconfig). Rows drawn by fonts outside the
18//!   bar's font list are highlighted. "Used by" lists the blocks that can
19//!   request the icon.
20//!
21//! - Problems: numbered findings with concrete fixes.
22//!
23//! A block can only request icons its prepared contract declares — the
24//! block plan each block builds from its configuration, checked when the
25//! block publishes a widget — so doctor validates the whole declared
26//! contract and takes every declared icon as in use by that block. It does not try to prove
27//! which declarations a particular configuration or runtime state would
28//! reach: a declaration a format never renders is reported as undefined
29//! just the same, because the contract is what the block is allowed to ask
30//! for. Blocks that choose names at runtime (`custom`, `custom_dbus`)
31//! declare that openly and are reported as such.
32//!
33//! Doctor continues after recoverable failures: a missing tool, an
34//! unreadable section, a block that fails its live test are reported (with
35//! install or fix instructions where known) and the rest of the report
36//! still runs. It stops early only when there is nothing left to inspect —
37//! a configuration file that is missing, unreadable, or not valid TOML.
38
39use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
40use std::io::IsTerminal as _;
41use std::os::unix::fs::DirBuilderExt as _;
42use std::path::{Path, PathBuf};
43use std::sync::Arc;
44use std::time::Duration;
45
46use futures::StreamExt as _;
47use icu_properties::CodePointSetData;
48use icu_properties::props::DefaultIgnorableCodePoint;
49use tokio::sync::mpsc;
50use unicode_width::UnicodeWidthStr;
51
52use crate::block_plan::CONTRACT_BUG;
53use crate::blocks::CommonApi;
54use crate::config::{BlockConfigEntry, Config, SharedConfig};
55use crate::errors::*;
56use crate::formatting::template as format_template;
57use crate::formatting::value::ValueInner;
58use crate::geolocator::Geolocator;
59use crate::icons::{Icon, Icons};
60use crate::term_graphics::{self, CellSize};
61use crate::util;
62use crate::widget::Widget;
63use crate::{Request, RequestCmd};
64
65/// i3bar switches a block to short mode only when the other text field is
66/// a non-empty string, so the bar sends this placeholder, which renders as
67/// nothing. It is protocol plumbing, never user-visible output.
68const SHORT_MODE_SENTINEL: &str = "<span/>";
69
70/// How long a block gets to produce its first output.
71const LIVE_TIMEOUT: Duration = Duration::from_secs(10);
72/// How long the live test keeps watching after a block's first output.
73const LIVE_SETTLE: Duration = Duration::from_millis(1500);
74
75struct Problem {
76    diagnosis: String,
77    fix: Option<String>,
78}
79
80struct Style {
81    red: &'static str,
82    reset: &'static str,
83}
84
85impl Style {
86    fn detect() -> Self {
87        if std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none() {
88            Self {
89                red: "\x1b[31m",
90                reset: "\x1b[0m",
91            }
92        } else {
93            Self { red: "", reset: "" }
94        }
95    }
96}
97
98/// Returns the number of problems found. The caller turns that into a
99/// conventional exit status: zero when clean, nonzero when doctor found
100/// something.
101/// How doctor shows icons in the terminal.
102#[derive(Clone, Copy, PartialEq, Eq)]
103pub enum IconDisplay {
104    /// The glyphs themselves, drawn with the terminal's fonts.
105    Glyphs,
106    /// `{name}` placeholders, for terminals whose fonts differ from the bar's.
107    Names,
108}
109
110pub fn run(
111    config_arg: &str,
112    font_arg: Option<&str>,
113    skip_live: bool,
114    display: IconDisplay,
115) -> usize {
116    let style = Style::detect();
117    let mut problems: Vec<Problem> = Vec::new();
118
119    println!("i3status-rs doctor");
120    println!();
121
122    // === Config file ===
123    let (resolved, trace) = resolve_file(config_arg, None);
124    let config_path = match resolved {
125        Resolved::Found(path) => path,
126        Resolved::Missing => {
127            problems.push(Problem {
128                diagnosis: escape_control_multiline(&format!(
129                    "Configuration file {config_arg:?} not found. Searched:\n{trace}"
130                )),
131                fix: Some(
132                    "Create ~/.config/i3status-rust/config.toml, or pass a path: i3status-rs --doctor <path>"
133                        .into(),
134                ),
135            });
136            print_problems(&problems, false, &style);
137            return problems.len();
138        }
139        Resolved::Failed(err) => {
140            problems.push(Problem {
141                diagnosis: escape_control_multiline(&format!(
142                    "Configuration file {config_arg:?} cannot be resolved: {err}. The bar's own \
143                     lookup stops at this candidate, so it would not start either — and the \
144                     locations after it are never consulted. Searched:\n{trace}"
145                )),
146                fix: Some(
147                    "Repair or remove that path; a broken symlink or an unreadable directory is \
148                     the usual cause."
149                        .into(),
150                ),
151            });
152            print_problems(&problems, false, &style);
153            return problems.len();
154        }
155    };
156    println!(
157        "Config:   {}",
158        escape_control(&config_path.display().to_string())
159    );
160
161    let raw: Option<toml::Value> = match std::fs::read_to_string(&config_path) {
162        Err(err) => {
163            problems.push(Problem {
164                diagnosis: escape_control_multiline(&format!(
165                    "Cannot read {}: {err}",
166                    config_path.display()
167                )),
168                fix: None,
169            });
170            None
171        }
172        Ok(text) => match toml::from_str(&text) {
173            Ok(value) => Some(value),
174            Err(err) => {
175                problems.push(Problem {
176                    diagnosis: format!(
177                    "Configuration is not valid TOML:\n{}",
178                    escape_control_multiline(&err.to_string())
179                ),
180                    fix: Some(
181                        "Fix the syntax error above; nothing else can be checked until the file parses."
182                            .into(),
183                    ),
184                });
185                None
186            }
187        },
188    };
189    let Some(raw) = raw else {
190        print_problems(&problems, false, &style);
191        return problems.len();
192    };
193
194    // === Icon set ===
195    // Parser complaints already explained in specific terms, so the typed
196    // parse below does not report the same defect a second time.
197    let mut explained_parse_errors: Vec<String> = Vec::new();
198    let builtin = Icons::default().0;
199    let (set_name, overrides_value) = icons_config(&raw, &mut problems);
200    let (base_map, set_desc) = if set_name == "none" {
201        (builtin.clone(), "built-in text icons".to_string())
202    } else {
203        let (file, trace) = resolve_file(set_name, Some("icons"));
204        match file {
205            Resolved::Failed(err) => {
206                problems.push(Problem {
207                    diagnosis: escape_control_multiline(&format!(
208                        "Icon set {set_name:?} cannot be resolved: {err}. The bar's own lookup \
209                         stops at this candidate, so the locations after it are never \
210                         consulted. Searched:\n{trace}"
211                    )),
212                    fix: Some(
213                        "Repair or remove that path; a broken symlink or an unreadable \
214                         directory is the usual cause."
215                            .into(),
216                    ),
217                });
218                (
219                    builtin.clone(),
220                    "built-in text icons (fallback)".to_string(),
221                )
222            }
223            Resolved::Missing => {
224                // The typed parse fails on the same lookup; let this
225                // specific diagnosis stand in for it.
226                explained_parse_errors.push(format!("Icon set '{set_name}' not found"));
227                problems.push(Problem {
228                    diagnosis: escape_control_multiline(&format!(
229                        "Icon set {set_name:?} not found. Icon sets are plain TOML files looked \
230                         up on disk, not built into the binary. Searched:\n{trace}"
231                    )),
232                    fix: Some(escape_control(&format!(
233                        "Copy the set (e.g. files/icons/{}.toml from the source tree) into \
234                         ~/.config/i3status-rust/icons/, or use an absolute path in `icons = `.",
235                        escape_control(set_name)
236                    ))),
237                });
238                (
239                    builtin.clone(),
240                    "built-in text icons (fallback)".to_string(),
241                )
242            }
243            Resolved::Found(file) => {
244                match util::deserialize_toml_file::<HashMap<String, Icon>, _>(&file) {
245                    Err(err) => {
246                        explained_parse_errors.push(err.to_string().trim().to_string());
247                        problems.push(Problem {
248                        diagnosis: escape_control_multiline(&format!(
249                            "Icon set file {} cannot be parsed: {err}",
250                            file.display()
251                        )),
252                        fix: Some(
253                            "Fix the file, or remove `icons = ` to use the built-in text icons."
254                                .into(),
255                        ),
256                    });
257                        (
258                            builtin.clone(),
259                            "built-in text icons (fallback)".to_string(),
260                        )
261                    }
262                    Ok(map) => {
263                        let file = file.display().to_string();
264                        let desc = if set_name == file {
265                            format!("{file} ({} names)", map.len())
266                        } else {
267                            format!("{set_name} ({file}, {} names)", map.len())
268                        };
269                        (map, desc)
270                    }
271                }
272            }
273        }
274    };
275    println!("Icon set: {}", escape_control(&set_desc));
276
277    let global_overrides: HashMap<String, Icon> = match overrides_value {
278        None => HashMap::new(),
279        Some(value) => match value.clone().try_into() {
280            Ok(overrides) => overrides,
281            Err(err) => {
282                explained_parse_errors.push(err.to_string().trim().to_string());
283                problems.push(Problem {
284                    diagnosis: escape_control_multiline(&format!(
285                        "[icons.overrides] is not a valid icon table: {err}"
286                    )),
287                    fix: None,
288                });
289                HashMap::new()
290            }
291        },
292    };
293
294    // Per-instance icons_overrides tables, inspected here so a malformed
295    // one is explained before the typed parse reports the same complaint.
296    let raw_overrides = raw_block_overrides(&raw, &mut problems, &mut explained_parse_errors);
297
298    // === Bar font ===
299    let detected = if font_arg.is_none() {
300        detect_bar_font()
301    } else {
302        None
303    };
304    let font_pattern = font_arg.or(detected.as_ref().map(|d| d.font.as_str()));
305    // X core fonts (XLFD, "-misc-fixed-...") bypass fontconfig entirely, so
306    // the glyph analysis would be meaningless.
307    let is_xlfd = font_pattern.is_some_and(|f| f.starts_with('-'));
308    let mut font_check = if is_xlfd {
309        None
310    } else {
311        FontCheck::new(font_pattern)
312    };
313    // Findings that depend on the bar font are only authoritative when the
314    // font is known unambiguously: given via --font, or auto-detected without
315    // ambiguity. Otherwise they are reported as notes, not problems.
316    let font_authoritative =
317        font_arg.is_some() || (detected.as_ref().is_some_and(|d| d.note.is_none()));
318    // Environment limitations are notes, not problems: they say what doctor
319    // could not check, not that the user's configuration is wrong, and must
320    // not affect the exit code.
321    match (&font_check, font_arg, &detected) {
322        (None, ..) if is_xlfd => {
323            println!(
324                "Bar font: {} (X core font)",
325                escape_control(font_pattern.unwrap_or(""))
326            );
327            println!(
328                "   note: XLFD fonts bypass fontconfig, so doctor cannot analyze which font\n   \
329                 draws each glyph; the font check is skipped."
330            );
331        }
332        (None, ..) => {
333            println!("Bar font: (unchecked)");
334            println!(
335                "   note: `fc-match` or `fc-list` is not available, so doctor cannot tell\n   \
336                 which font will draw each icon glyph — the most common cause of wrong\n   \
337                 icons. Install the fontconfig utilities (package `fontconfig` on most\n   \
338                 distros) and re-run."
339            );
340        }
341        (Some(_), Some(font), _) => {
342            println!("Bar font: {} (from --font)", escape_control(font));
343        }
344        (Some(_), None, Some(d)) => {
345            println!(
346                "Bar font: {} (auto-detected via IPC, {})",
347                escape_control(&d.font),
348                escape_control(&d.bar_id)
349            );
350            if let Some(note) = &d.note {
351                println!("   note: {}", escape_control(note));
352            }
353        }
354        (Some(check), None, None) => {
355            println!(
356                "Bar font: fontconfig default ({})",
357                escape_control(&check.base_family)
358            );
359            println!(
360                "   note: no --font given and no running i3/sway answered over IPC; glyph\n   \
361                 providers below may not match your actual bar and are reported as notes,\n   \
362                 not problems. Re-run with the `font` directive from the bar {{ }} section\n   \
363                 of your i3/sway config: i3status-rs --doctor --font \"pango:...\""
364            );
365            if let Some(note) = stale_socket_note() {
366                println!("   note: {note}");
367            }
368        }
369    }
370    // XLFD fonts are not pango's, so pango cannot draw them either.
371    let renderer = match display {
372        IconDisplay::Glyphs if !is_xlfd => {
373            BarRenderer::new(font_pattern, detected.as_ref().map(|d| &d.colors))
374        }
375        _ => None,
376    };
377    match (display, &renderer) {
378        (IconDisplay::Glyphs, Some(_)) => println!(
379            "   note: icons below are images drawn by pango with the bar's font, as the bar\n   \
380             draws them."
381        ),
382        (IconDisplay::Glyphs, None) => println!(
383            "   note: icons below are drawn with this terminal's fonts, which may not be your\n   \
384             bar's; the Code and \"Effectively provided by\" columns describe the bar.\n   \
385             --noicons shows icon names instead. A terminal with kitty graphics (kitty,\n   \
386             Ghostty, WezTerm) shows them as the bar draws them, if pango-view is installed\n   \
387             (pango1.0-tools on Debian/Ubuntu)."
388        ),
389        (IconDisplay::Names, _) => (),
390    }
391    // === Per-instance pango markup ===
392    // The bar's final output is pango markup, and markup can come from an
393    // icons_format, from literal text in any of the block's formats, or
394    // from the resolved icon value itself. Doctor does not emulate pango:
395    // it conservatively marks the affected icons' providers inconclusive.
396    let block_names = raw_block_names(&raw);
397    let labels = instance_labels(&block_names);
398    let global_markup = raw
399        .get("icons_format")
400        .and_then(|v| v.as_str())
401        .is_some_and(contains_markup);
402    let mut markup_labels: HashSet<String> = HashSet::new();
403    // The wrapper applied to every icon a block renders: its own
404    // icons_format if it sets one, the global one otherwise.
405    let global_icons_format = raw
406        .get("icons_format")
407        .and_then(|v| v.as_str())
408        .unwrap_or("{icon}");
409    let mut icons_formats: HashMap<String, String> = HashMap::new();
410    for (index, label) in labels.iter().enumerate() {
411        let table = raw
412            .get("block")
413            .and_then(|b| b.as_array())
414            .and_then(|b| b.get(index))
415            .and_then(|b| b.as_table());
416        let local_icons_format = table
417            .and_then(|t| t.get("icons_format"))
418            .and_then(|v| v.as_str())
419            .map(contains_markup);
420        // Every format the block can show, whichever naming it uses: a
421        // `format` list, `full_format`, `disconnected_format`, ...
422        let format_markup = table.is_some_and(|t| {
423            t.iter().any(|(key, value)| {
424                (key == "format" || key.starts_with("format_") || key.ends_with("_format"))
425                    && format_value_is_markup(value)
426            })
427        });
428        // Error output is rendered by the bar too, with the block's
429        // effective error formats: its own if it sets them, the global
430        // ones otherwise.
431        let error_markup = ["error_format", "error_fullscreen_format"]
432            .into_iter()
433            .any(|key| match table.and_then(|t| t.get(key)) {
434                Some(value) => format_value_is_markup(value),
435                None => raw.get(key).is_some_and(format_value_is_markup),
436            });
437        icons_formats.insert(
438            label.clone(),
439            table
440                .and_then(|t| t.get("icons_format"))
441                .and_then(|v| v.as_str())
442                .unwrap_or(global_icons_format)
443                .to_string(),
444        );
445        if local_icons_format.unwrap_or(global_markup) || format_markup || error_markup {
446            markup_labels.insert(label.clone());
447        }
448    }
449    if let Some(check) = &font_check {
450        for (family, resolved) in &check.families {
451            // Generic fontconfig aliases (monospace, sans-serif, ...) always
452            // resolve to some concrete family; that is normal, not a missing
453            // font.
454            if is_generic_family(family) {
455                continue;
456            }
457            if !family_present(family) {
458                let diagnosis = escape_control(&format!(
459                    "Font {family:?} is in the bar's font list but not installed{}.",
460                    resolved
461                        .as_ref()
462                        .map(|r| format!(" (fontconfig silently uses {r:?} in its place)"))
463                        .unwrap_or_default()
464                ));
465                if font_authoritative {
466                    problems.push(Problem {
467                        diagnosis,
468                        fix: Some(format!(
469                            "Install {family:?}, or remove it from the bar's font directive."
470                        )),
471                    });
472                } else {
473                    println!("   note: {diagnosis} (guessed font; not counted as a problem)");
474                }
475            }
476        }
477    }
478    println!();
479
480    // === Blocks (live test) ===
481    // Everything is attributed per block INSTANCE: two blocks of the same
482    // type get distinct labels ("time#1", "time#2") so per-instance
483    // icons_overrides are analyzed separately.
484    let mut used_now: BTreeMap<String, HashSet<String>> = BTreeMap::new();
485
486    let parsed: Option<Config> = match util::deserialize_toml_file::<Config, _>(&config_path) {
487        Ok(config) => Some(config),
488        Err(err) => {
489            // The same defect the icon-set/overrides inspection above
490            // already described in specific terms would fail this parse
491            // too; do not report one root cause twice.
492            // Skip only what a specific problem above already explained:
493            // the typed parse repeats the same parser complaint verbatim.
494            let text = err.to_string();
495            if !explained_parse_errors
496                .iter()
497                .any(|explained| text.contains(explained))
498            {
499                problems.push(Problem {
500                    diagnosis: escape_control_multiline(&format!(
501                        "Configuration does not validate: {text}"
502                    )),
503                    fix: None,
504                });
505            }
506            None
507        }
508    };
509
510    // Icon name -> the block instances whose contract declares it. Every
511    // declared icon counts as in use by that block.
512    let mut declared_by: BTreeMap<String, Vec<String>> = BTreeMap::new();
513
514    // Labels whose block configuration failed to deserialize: the static
515    // problem below already covers them, so the live report must not
516    // diagnose the same root cause again.
517    let mut prepared_errors: HashSet<String> = HashSet::new();
518
519    // Blocks that can request icon names doctor cannot enumerate.
520    let mut open_labels: BTreeSet<String> = BTreeSet::new();
521
522    for (index, label) in labels.iter().enumerate() {
523        let label = label.clone();
524
525        // The prepared contract of this block instance.
526        let plan = parsed
527            .as_ref()
528            .and_then(|config| config.blocks.get(index))
529            .and_then(|entry| match entry.config.plan() {
530                Ok(plan) => Some(plan),
531                Err(err) => {
532                    // The block's own configuration did not deserialize (the
533                    // bar would show a configuration error in its place).
534                    problems.push(Problem {
535                        diagnosis: format!(
536                            "Block `{label}` cannot be prepared from its configuration: {err}"
537                        ),
538                        fix: None,
539                    });
540                    prepared_errors.insert(label.clone());
541                    None
542                }
543            });
544
545        if let Some(plan) = &plan {
546            let analysis = analyze_plan(plan);
547            if analysis.open {
548                open_labels.insert(label.clone());
549            }
550            // Direct ^icon_* tokens in effective formats (including
551            // defaults) count the same as declared icons: in use.
552            for icon in &analysis.direct {
553                used_now
554                    .entry(icon.clone())
555                    .or_default()
556                    .insert(label.clone());
557            }
558            for icon in &analysis.required {
559                declared_by
560                    .entry(icon.clone())
561                    .or_default()
562                    .push(label.clone());
563            }
564        }
565        // Errors render through the shared error-widget plan with the
566        // block's effective error formats; whatever those formats reach
567        // (typically the conditional `refresh` restart icon) is a latent
568        // requirement of every block.
569        let error_rel = parsed
570            .as_ref()
571            .and_then(|config| config.blocks.get(index).map(|entry| (config, entry)))
572            .map(|(config, entry)| {
573                let plan = crate::block_plan::error_plan(
574                    entry
575                        .common
576                        .error_format
577                        .with_default_config(&config.error_format),
578                    entry
579                        .common
580                        .error_fullscreen_format
581                        .with_default_config(&config.error_fullscreen_format),
582                    // The restart button (and its refresh icon) can only
583                    // appear when retries are limited; configuration-error
584                    // blocks are never restartable.
585                    entry.common.max_retries.is_some()
586                        && !matches!(entry.config, crate::blocks::BlockConfig::Err(..)),
587                )
588                .expect("the error plan has statically unique ids");
589                analyze_plan(&plan)
590            });
591        if let Some(error_rel) = &error_rel {
592            for icon in &error_rel.required {
593                let users = declared_by.entry(icon.clone()).or_default();
594                if !users.contains(&label) {
595                    users.push(label.clone());
596                }
597            }
598        }
599    }
600
601    let mut live_ran = false;
602    // What each block that produced output actually rendered, with the
603    // strings its own icons expanded to, for the text-glyph check below.
604    let mut rendered_texts: Vec<(String, String, Vec<String>)> = Vec::new();
605    // (label, icon) pairs already diagnosed by a live render error, so the
606    // icon table does not report the same root cause twice
607    let mut live_reported: HashSet<(String, String)> = HashSet::new();
608    let icons_skip_reason = parsed
609        .is_none()
610        .then_some("configuration does not validate");
611    match (parsed, skip_live) {
612        (None, _) => println!("Blocks: skipped (configuration does not validate)\n"),
613        (Some(_), true) => println!("Blocks: skipped (--doctor-skip-live)\n"),
614        (Some(config), false) => {
615            live_ran = true;
616            println!(
617                "Blocks (each run for one cycle; performs real requests/commands, {}s timeout)",
618                LIVE_TIMEOUT.as_secs()
619            );
620            let mut reports = run_live(config_arg, config.blocks.len(), &mut problems);
621            if display == IconDisplay::Names {
622                reports.iter_mut().for_each(name_icons);
623            }
624            let num_w = format!("{}", reports.len()).len().max("#".len());
625            let name_w = column_width("Name", reports.iter().map(|r| r.name.as_str()));
626            let out_w = reports
627                .iter()
628                .map(|r| UnicodeWidthStr::width(output_cell(&r.verdict).0.as_str()))
629                .chain(["Output".len()])
630                .max()
631                .unwrap_or(0);
632            println!(
633                "{:>num_w$}  {}  {}  Icons/text glyphs used during this run",
634                "#",
635                pad_right("Name", name_w),
636                pad_right("Output", out_w)
637            );
638            for report in &reports {
639                let label = labels
640                    .get(report.index)
641                    .cloned()
642                    .unwrap_or_else(|| report.name.clone());
643                match &report.verdict {
644                    LiveVerdict::Rendered {
645                        check_text,
646                        icon_glyphs,
647                        ..
648                    } => {
649                        // The block's actual output contains pango markup
650                        // (from a format, a pango-str value, or an icon):
651                        // which font draws its icons is not verifiable.
652                        if contains_markup(check_text) {
653                            markup_labels.insert(label.clone());
654                        }
655                        rendered_texts.push((
656                            label.clone(),
657                            check_text.clone(),
658                            icon_glyphs.clone(),
659                        ));
660                    }
661                    // A block skipped by if_command keeps its declared icon
662                    // obligations: the command's result is a property of
663                    // this moment, not of the configuration, and the bar
664                    // will render the block whenever it succeeds.
665                    LiveVerdict::RenderError { error, .. } => {
666                        // The name is delimited by the message's own
667                        // wording, not by the first quote: icon names may
668                        // contain apostrophes.
669                        if let Some(icon) = error
670                            .split_once("Icon '")
671                            .and_then(|(_, rest)| rest.rsplit_once("' not found"))
672                            .map(|(icon, _)| icon)
673                        {
674                            live_reported.insert((label.clone(), icon.to_string()));
675                        }
676                        // Rendering failed, possibly on an icon. The
677                        // prepared contract already names exactly what can
678                        // render — including whatever the render failed on —
679                        // so the static analysis stays authoritative.
680                    }
681                    _ => (),
682                }
683                print_block_report(
684                    report,
685                    num_w,
686                    name_w,
687                    out_w,
688                    &style,
689                    &mut problems,
690                    &mut used_now,
691                    &prepared_errors,
692                    &label,
693                );
694            }
695            if reports.iter().any(|report| {
696                rendered_flags(&report.verdict, &report.flags)
697                    .next()
698                    .is_some()
699            }) {
700                println!("{FLAG_FOOTNOTE}");
701            }
702            println!();
703        }
704    }
705
706    // === Icons table ===
707    let block_overrides: Vec<(String, HashMap<String, Icon>)> = raw_overrides
708        .into_iter()
709        .map(|(index, overrides)| (labels[index].clone(), overrides))
710        .collect();
711    // === Text glyphs in live output ===
712    // Blocks emit text glyphs too (country flags, unit symbols, ...) whose
713    // rendering depends on installed fonts just like icons. Doctor asks
714    // fontconfig the same decidable questions about them: substituted
715    // glyphs are worth a note (the common, working case), and glyphs no
716    // installed font provides are a problem (they render as empty boxes).
717    // Characters are classified one by one and only then grouped into
718    // consecutive same-verdict runs, so a sequence that renders (a country
719    // flag) stays intact while an unavailable neighbour is reported alone.
720    //
721    // (label, provider) -> sequences that provider draws for that block.
722    let mut text_fallbacks: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
723    let mut text_missing: BTreeMap<String, Vec<String>> = BTreeMap::new();
724    if let Some(check) = font_check.as_mut() {
725        for (label, text, icon_glyphs) in &rendered_texts {
726            if markup_labels.contains(label) {
727                continue;
728            }
729            // Characters this block's own icons contributed already have
730            // rows in the icon table. Another icon in the set that happens
731            // to use the same character says nothing about this text.
732            let icon_chars: HashSet<char> = icon_glyphs.iter().flat_map(|g| g.chars()).collect();
733            let mut runs: Vec<(Option<String>, String)> = Vec::new();
734            // Only characters that are adjacent in the output belong to the
735            // same sequence; anything skipped in between ends it.
736            let mut adjacent = false;
737            for c in text.chars() {
738                if !is_drawn(c) || icon_chars.contains(&c) {
739                    adjacent = false;
740                    continue;
741                }
742                // None = no installed font provides it
743                let verdict = match check.check(c) {
744                    GlyphFont::Base | GlyphFont::Configured(_) => {
745                        adjacent = false;
746                        continue;
747                    }
748                    GlyphFont::Fallback(family) => Some(first_family(&family)),
749                    GlyphFont::Missing => None,
750                };
751                match runs.last_mut() {
752                    Some((last, run)) if adjacent && *last == verdict => run.push(c),
753                    _ => runs.push((verdict, c.to_string())),
754                }
755                adjacent = true;
756            }
757            for (verdict, run) in runs {
758                let entry = match verdict {
759                    Some(family) => text_fallbacks.entry((label.clone(), family)).or_default(),
760                    None => text_missing.entry(label.clone()).or_default(),
761                };
762                if !entry.contains(&run) {
763                    entry.push(run);
764                }
765            }
766        }
767    }
768
769    print_icon_table(IconTableInput {
770        base_map: &base_map,
771        global_overrides: &global_overrides,
772        block_overrides: &block_overrides,
773        used_now: &used_now,
774        declared_by: &declared_by,
775        live_reported: &live_reported,
776        icons_formats: &icons_formats,
777        markup_labels: &markup_labels,
778        font_check: &mut font_check,
779        font_authoritative,
780        style: &style,
781        problems: &mut problems,
782        skip_reason: icons_skip_reason,
783        display,
784        renderer: renderer.as_ref(),
785    });
786
787    if !text_fallbacks.is_empty() {
788        println!("Text glyphs in live output drawn by fonts outside the bar's font list:");
789        for ((label, family), runs) in &text_fallbacks {
790            let shown: Vec<String> = runs
791                .iter()
792                .map(|run| format!("{} ({})", escape_control(run), codepoints(run)))
793                .collect();
794            println!(
795                "   {} — {} ({label})",
796                shown.join(", "),
797                escape_control(family)
798            );
799        }
800        println!(
801            "   Like * rows above, these depend on which fonts happen to be installed; \
802             not counted as problems."
803        );
804        println!();
805    }
806    for (label, runs) in &text_missing {
807        let listed: Vec<String> = runs
808            .iter()
809            .map(|run| format!("{} ({})", escape_control(run), codepoints(run)))
810            .collect();
811        problems.push(Problem {
812            diagnosis: format!(
813                "`{label}` output contains glyph(s) no installed font provides \
814                 ({}): they render as empty boxes.",
815                listed.join(", ")
816            ),
817            fix: Some("Install a font that contains these codepoints.".into()),
818        });
819    }
820
821    if !open_labels.is_empty() {
822        let listed = open_labels
823            .iter()
824            .map(String::as_str)
825            .collect::<Vec<_>>()
826            .join(", ");
827        println!(
828            "note: dynamic icon source in: {listed}. These blocks choose icon names at runtime,\n\
829             so doctor cannot enumerate them in advance — {}",
830            if live_ran {
831                "the names above are what this run observed, not the complete set."
832            } else {
833                "and the live block test did not run, so none were observed."
834            }
835        );
836        println!();
837    }
838
839    print_problems(&problems, live_ran, &style);
840    problems.len()
841}
842
843/// What the bar's own escaping (`crate::escape`) turns plain text into. It
844/// changes no font, so it is not markup.
845const PLAIN_TEXT_ESCAPES: [&str; 4] = ["&amp;", "&lt;", "&gt;", "&#39;"];
846
847/// Whether a string is pango markup: a tag, or a character reference like
848/// `&#x1F600;` (which pango resolves without any tag being present).
849/// `"a &amp; b"` is plain text the bar escaped; `"<b>a</b>"` is markup.
850fn contains_markup(s: &str) -> bool {
851    if s.contains('<') {
852        return true;
853    }
854    let unescaped = PLAIN_TEXT_ESCAPES
855        .iter()
856        .fold(s.to_string(), |acc, escape| acc.replace(escape, ""));
857    unescaped.contains('&')
858}
859
860/// Whether a format value (string or {full, short} table) is markup.
861fn format_value_is_markup(value: &toml::Value) -> bool {
862    match value {
863        toml::Value::String(s) => contains_markup(s),
864        toml::Value::Table(t) => t.values().any(|v| v.as_str().is_some_and(contains_markup)),
865        // A block can rotate through several formats, so a format value may
866        // be a list of any of the above.
867        toml::Value::Array(items) => items.iter().any(format_value_is_markup),
868        _ => false,
869    }
870}
871
872fn icons_config<'a>(
873    raw: &'a toml::Value,
874    problems: &mut Vec<Problem>,
875) -> (&'a str, Option<&'a toml::Value>) {
876    match raw.get("icons") {
877        Some(toml::Value::String(name)) => {
878            problems.push(Problem {
879                diagnosis: format!("`icons = {name:?}` at the top level is not valid."),
880                fix: Some(format!(
881                    "Use a section:\n        [icons]\n        icons = {name:?}"
882                )),
883            });
884            (name.as_str(), None)
885        }
886        Some(toml::Value::Table(table)) => (
887            table
888                .get("icons")
889                .and_then(|v| v.as_str())
890                .unwrap_or("none"),
891            table.get("overrides"),
892        ),
893        _ => ("none", None),
894    }
895}
896
897/// Per-block-instance `icons_overrides` tables from the raw config, keyed by
898/// the block's position in the config.
899fn raw_block_overrides(
900    raw: &toml::Value,
901    problems: &mut Vec<Problem>,
902    explained_parse_errors: &mut Vec<String>,
903) -> Vec<(usize, HashMap<String, Icon>)> {
904    let Some(blocks) = raw.get("block").and_then(|v| v.as_array()) else {
905        return Vec::new();
906    };
907    let mut out = Vec::new();
908    for (index, block) in blocks.iter().enumerate() {
909        let name = block
910            .get("block")
911            .and_then(|v| v.as_str())
912            .unwrap_or("<unknown>");
913        let Some(value) = block.get("icons_overrides") else {
914            continue;
915        };
916        match value.clone().try_into() {
917            Ok(overrides) => out.push((index, overrides)),
918            Err(err) => {
919                explained_parse_errors.push(err.to_string().trim().to_string());
920                problems.push(Problem {
921                    diagnosis: escape_control_multiline(&format!(
922                        "{name}: icons_overrides is not a valid icon table: {err}"
923                    )),
924                    fix: None,
925                });
926            }
927        }
928    }
929    out
930}
931
932/// A unique label per block instance: the type name alone when the type
933/// appears once, "name#N" (1-based config position) otherwise.
934fn instance_labels(block_names: &[String]) -> Vec<String> {
935    let mut counts: HashMap<&str, usize> = HashMap::new();
936    for name in block_names {
937        *counts.entry(name.as_str()).or_default() += 1;
938    }
939    block_names
940        .iter()
941        .enumerate()
942        .map(|(index, name)| {
943            if counts.get(name.as_str()).copied().unwrap_or(0) > 1 {
944                format!("{name}#{}", index + 1)
945            } else {
946                name.clone()
947            }
948        })
949        .collect()
950}
951
952fn raw_block_names(raw: &toml::Value) -> Vec<String> {
953    raw.get("block")
954        .and_then(|v| v.as_array())
955        .map(|blocks| {
956            blocks
957                .iter()
958                .map(|b| {
959                    b.get("block")
960                        .and_then(|v| v.as_str())
961                        .unwrap_or("<unknown>")
962                        .to_string()
963                })
964                .collect()
965        })
966        .unwrap_or_default()
967}
968
969// ---------------------------------------------------------------------------
970// Live block test
971// ---------------------------------------------------------------------------
972
973#[derive(serde::Serialize, serde::Deserialize)]
974enum LiveVerdict {
975    Rendered {
976        /// What the bar shows (full text only; the i3bar short-text
977        /// sentinel is protocol plumbing, not user output).
978        text: String,
979        /// Everything the block actually rendered, full and short, for font
980        /// and markup analysis.
981        #[serde(default)]
982        check_text: String,
983        /// The strings the block's icons expanded to, so live-output
984        /// analysis can tell icon characters from text characters.
985        #[serde(default)]
986        icon_glyphs: Vec<String>,
987        /// Icon names actually rendered (recorded during rendering, so only
988        /// the format branch that succeeded counts).
989        icons: Vec<String>,
990        /// (icon name, the string it drew), to show names instead of glyphs.
991        #[serde(default)]
992        icon_strings: Vec<(String, String)>,
993        /// All icon values the block provided: placeholder key -> icon name.
994        provided_icons: Vec<(String, String)>,
995    },
996    RenderError {
997        error: String,
998        provided: Vec<String>,
999        icons: Vec<String>,
1000    },
1001    BlockError(String),
1002    Panicked(String),
1003    Hidden,
1004    Finished,
1005    NoOutput,
1006    Skipped(String),
1007    /// The if_command could not run: the real bar fails at startup in this
1008    /// case, so this is a problem.
1009    IfCommandFailed(String),
1010    /// The if_command exceeded doctor's deadline. The real bar waits without
1011    /// a timeout, so this is inconclusive, not a config problem.
1012    IfCommandTimeout(String),
1013}
1014
1015#[derive(serde::Serialize, serde::Deserialize)]
1016struct BlockReport {
1017    index: usize,
1018    name: String,
1019    verdict: LiveVerdict,
1020    /// (country code, flag) pairs the block generated during the run
1021    /// (recorded at the source, `util::country_flag_from_iso_code`).
1022    #[serde(default)]
1023    flags: Vec<(String, String)>,
1024}
1025
1026enum LiveOutput {
1027    Widget(Box<Widget>),
1028    Error(Error),
1029    Hidden,
1030}
1031
1032/// Extra time the parent grants a worker beyond the block's own deadline
1033/// before SIGKILLing its process group.
1034const WORKER_GRACE: Duration = Duration::from_secs(3);
1035
1036/// Run every block in its own worker process (`--doctor-worker <index>`, this
1037/// same binary). Future cancellation cannot reap OS processes a block has
1038/// spawned (e.g. the custom block's command), so each worker gets its own
1039/// process group, which the parent SIGKILLs after collecting the result —
1040/// nothing can hang doctor or outlive it.
1041fn run_live(config_arg: &str, count: usize, problems: &mut Vec<Problem>) -> Vec<BlockReport> {
1042    let exe = match std::env::current_exe() {
1043        Ok(exe) => exe,
1044        Err(err) => {
1045            return vec![BlockReport {
1046                index: 0,
1047                name: "<worker>".into(),
1048                verdict: LiveVerdict::BlockError(format!("cannot find own executable: {err}")),
1049                flags: Vec::new(),
1050            }];
1051        }
1052    };
1053    let runtime = match tokio::runtime::Builder::new_current_thread()
1054        .enable_all()
1055        .build()
1056    {
1057        Ok(runtime) => runtime,
1058        Err(err) => {
1059            return vec![BlockReport {
1060                index: 0,
1061                name: "<runtime>".into(),
1062                verdict: LiveVerdict::BlockError(format!("failed to start async runtime: {err}")),
1063                flags: Vec::new(),
1064            }];
1065        }
1066    };
1067
1068    // A block's subprocess can leave its worker's process group (setsid), so
1069    // the group SIGKILL alone cannot guarantee cleanup. Registering as a
1070    // child subreaper makes every orphaned descendant reparent to us instead
1071    // of init; after the workers are done we sweep and kill whatever is left.
1072    // SAFETY: plain prctl syscall
1073    let subreaper_ok = unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1) } == 0;
1074    if !subreaper_ok {
1075        problems.push(Problem {
1076            diagnosis: "Cannot register as a child subreaper; processes spawned by blocks \
1077                        that detach from their process group may outlive doctor."
1078                .into(),
1079            fix: None,
1080        });
1081    }
1082
1083    let reports = runtime.block_on(async {
1084        let done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1085        let workers = (0..count).map(|index| {
1086            let exe = exe.clone();
1087            let done = done.clone();
1088            async move {
1089                let report = run_worker_process(&exe, config_arg, index).await;
1090                done.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1091                report
1092            }
1093        });
1094        let work = futures::future::join_all(workers);
1095        // Blocks with slow commands or network requests can take their full
1096        // deadline; show progress while the user waits (tty only, so piped
1097        // output stays clean).
1098        if std::io::stdout().is_terminal() {
1099            use std::io::Write as _;
1100            const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1101            let mut ticker = tokio::time::interval(Duration::from_millis(120));
1102            let mut frame = 0usize;
1103            tokio::pin!(work);
1104            loop {
1105                tokio::select! {
1106                    reports = &mut work => {
1107                        print!("\r\x1b[K");
1108                        let _ = std::io::stdout().flush();
1109                        break reports;
1110                    }
1111                    _ = ticker.tick() => {
1112                        print!(
1113                            "\r{} testing blocks… {}/{count} done",
1114                            FRAMES[frame % FRAMES.len()],
1115                            done.load(std::sync::atomic::Ordering::Relaxed),
1116                        );
1117                        let _ = std::io::stdout().flush();
1118                        frame += 1;
1119                    }
1120                }
1121            }
1122        } else {
1123            work.await
1124        }
1125    });
1126
1127    if subreaper_ok && let Err(leftover) = sweep_orphaned_children() {
1128        problems.push(Problem {
1129            diagnosis: format!(
1130                "Could not clean up all processes spawned by the block test: {leftover}"
1131            ),
1132            fix: Some("Check for leftover processes and kill them manually.".into()),
1133        });
1134    }
1135    reports
1136}
1137
1138/// Kill every remaining child of this process. All legitimate children (the
1139/// workers) have already been reaped by this point, so anything left is an
1140/// escaped descendant of some block's subprocess tree, reparented to us by
1141/// the subreaper registration.
1142///
1143/// Each pass can uncover one more level of a nested chain (killing a parent
1144/// orphans its children, which then reparent to us), so this sweeps until a
1145/// pass finds nothing, bounded by a deadline rather than a pass count.
1146/// Returns Err with a description if processes remain at the deadline.
1147fn sweep_orphaned_children() -> Result<(), String> {
1148    let self_pid = std::process::id();
1149    let deadline = std::time::Instant::now() + Duration::from_secs(5);
1150    loop {
1151        // Reap any zombies first so they neither linger nor hide behind the
1152        // early return below.
1153        // SAFETY: plain syscall
1154        while unsafe { libc::waitpid(-1, std::ptr::null_mut(), libc::WNOHANG) } > 0 {}
1155        let mut found = 0usize;
1156        let dir = match std::fs::read_dir("/proc") {
1157            Ok(dir) => dir,
1158            Err(err) => return Err(format!("cannot scan /proc: {err}")),
1159        };
1160        for entry in dir.flatten() {
1161            let Some(pid) = entry
1162                .file_name()
1163                .to_str()
1164                .and_then(|s| s.parse::<u32>().ok())
1165            else {
1166                continue;
1167            };
1168            // The process may exit between the scan and the read; that is
1169            // fine, it is gone either way.
1170            let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
1171                continue;
1172            };
1173            // ppid is the second field after the parenthesized comm
1174            let Some((_, rest)) = stat.rsplit_once(')') else {
1175                continue;
1176            };
1177            let mut fields = rest.split_whitespace();
1178            let state = fields.next();
1179            let Some(ppid) = fields.next().and_then(|p| p.parse::<u32>().ok()) else {
1180                continue;
1181            };
1182            if ppid == self_pid && state != Some("Z") {
1183                // SAFETY: plain syscall. "No such process" (already gone) is
1184                // fine; any other failure leaves the process for the next
1185                // pass or the deadline report.
1186                unsafe { libc::kill(pid as i32, libc::SIGKILL) };
1187                found += 1;
1188            }
1189        }
1190        if found == 0 {
1191            return Ok(());
1192        }
1193        if std::time::Instant::now() > deadline {
1194            return Err(format!(
1195                "{found} process(es) still alive after 5s of sweeping"
1196            ));
1197        }
1198        // Give the kills a moment: children of the killed processes reparent
1199        // to us and are caught by the next iteration.
1200        std::thread::sleep(Duration::from_millis(10));
1201        // Reap the zombies so they vanish from the next scan.
1202        // SAFETY: plain syscall
1203        while unsafe { libc::waitpid(-1, std::ptr::null_mut(), libc::WNOHANG) } > 0 {}
1204    }
1205}
1206
1207async fn run_worker_process(exe: &Path, config_arg: &str, index: usize) -> BlockReport {
1208    let fail = |msg: String| BlockReport {
1209        index,
1210        name: format!("block #{}", index + 1),
1211        verdict: LiveVerdict::BlockError(msg),
1212        flags: Vec::new(),
1213    };
1214
1215    let mut command = tokio::process::Command::new(exe);
1216    command
1217        .arg("--doctor-worker")
1218        .arg(index.to_string())
1219        // The parent may have been given the name after its own `--`;
1220        // without one here the worker reads a leading dash as an option.
1221        .arg("--")
1222        .arg(config_arg)
1223        .stdin(std::process::Stdio::null())
1224        .stdout(std::process::Stdio::piped())
1225        .stderr(std::process::Stdio::null())
1226        .process_group(0);
1227    let child = match command.spawn() {
1228        Ok(child) => child,
1229        Err(err) => return fail(format!("cannot start doctor worker: {err}")),
1230    };
1231    let pid = child.id();
1232
1233    let result = tokio::time::timeout(LIVE_TIMEOUT + WORKER_GRACE, child.wait_with_output()).await;
1234
1235    // Sweep the worker's whole process group unconditionally: this reaps any
1236    // subprocess a block spawned and left behind (the worker itself is
1237    // already gone in the normal case).
1238    if let Some(pid) = pid {
1239        // SAFETY: plain syscall; negative pid targets the process group
1240        unsafe { libc::kill(-(pid as i32), libc::SIGKILL) };
1241    }
1242
1243    match result {
1244        Err(_) => {
1245            // reap the killed worker so it does not linger as a zombie
1246            if let Some(pid) = pid {
1247                // SAFETY: plain syscall; the group was just SIGKILLed
1248                unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
1249            }
1250            fail(format!(
1251                "doctor worker did not finish within {}s and was killed",
1252                (LIVE_TIMEOUT + WORKER_GRACE).as_secs()
1253            ))
1254        }
1255        Ok(Err(err)) => fail(format!("doctor worker failed: {err}")),
1256        Ok(Ok(output)) => match serde_json::from_slice::<BlockReport>(&output.stdout) {
1257            Ok(report) => report,
1258            Err(err) => fail(format!(
1259                "doctor worker produced no readable result ({err}); it may have crashed"
1260            )),
1261        },
1262    }
1263}
1264
1265/// Entry point for `--doctor-worker <index>`: run one block's live test in
1266/// this process and print the result as JSON on stdout.
1267pub fn run_worker(config_arg: &str, index: usize) {
1268    // Workers are separate concurrent processes; give custom_dbus a unique
1269    // well-known name via an in-process channel — the environment every
1270    // block command and if_command sees stays exactly the user's own.
1271    // Unique per worker AND per doctor process: two doctor runs (or a
1272    // doctor run beside another) must not fight over the same name.
1273    crate::blocks::custom_dbus::set_doctor_dbus_suffix(format!(
1274        "doctor{}_{index}",
1275        std::process::id()
1276    ));
1277    util::enable_flag_recorder();
1278    let mut report = worker_report(config_arg, index);
1279    report.flags = util::recorded_flags();
1280    let report = report;
1281    match serde_json::to_string(&report) {
1282        Ok(json) => println!("{json}"),
1283        Err(err) => eprintln!("doctor worker: cannot serialize report: {err}"),
1284    }
1285}
1286
1287fn worker_report(config_arg: &str, index: usize) -> BlockReport {
1288    let fail = |msg: String| BlockReport {
1289        index,
1290        name: format!("block #{}", index + 1),
1291        verdict: LiveVerdict::BlockError(msg),
1292        flags: Vec::new(),
1293    };
1294    let Ok(Some(config_path)) = util::find_file(config_arg, None, Some("toml")) else {
1295        return fail("worker cannot find the configuration file".into());
1296    };
1297    let mut config: Config = match util::deserialize_toml_file(&config_path) {
1298        Ok(config) => config,
1299        Err(err) => return fail(format!("worker cannot parse the configuration: {err}")),
1300    };
1301    if index >= config.blocks.len() {
1302        return fail("worker got an out-of-range block index".into());
1303    }
1304    let entry = config.blocks.swap_remove(index);
1305    let shared = config.shared.clone();
1306    let geolocator = config.geolocator.clone();
1307
1308    let runtime = match tokio::runtime::Builder::new_current_thread()
1309        .enable_all()
1310        .build()
1311    {
1312        Ok(runtime) => runtime,
1313        Err(err) => return fail(format!("worker failed to start async runtime: {err}")),
1314    };
1315    let local = tokio::task::LocalSet::new();
1316    local.block_on(&runtime, test_block(index, entry, shared, geolocator))
1317}
1318
1319async fn test_block(
1320    index: usize,
1321    entry: BlockConfigEntry,
1322    mut shared: SharedConfig,
1323    geolocator: Arc<Geolocator>,
1324) -> BlockReport {
1325    let name = entry.config.name().to_string();
1326    // One deadline shared by everything the block test does: if_command and
1327    // the block's first output together get LIVE_TIMEOUT, not each.
1328    let deadline = tokio::time::Instant::now() + LIVE_TIMEOUT;
1329
1330    if let Some(cmd) = &entry.common.if_command {
1331        // Subprocess cleanup is guaranteed by the worker's process group,
1332        // which the parent sweeps.
1333        let output = tokio::time::timeout_at(
1334            deadline,
1335            tokio::process::Command::new("sh")
1336                .args(["-c", cmd])
1337                .stdin(std::process::Stdio::null())
1338                .kill_on_drop(true)
1339                .output(),
1340        )
1341        .await;
1342        match output {
1343            Err(_) => {
1344                return BlockReport {
1345                    index,
1346                    name,
1347                    verdict: LiveVerdict::IfCommandTimeout(format!(
1348                        "if_command did not finish within {}s ({cmd})",
1349                        LIVE_TIMEOUT.as_secs()
1350                    )),
1351                    flags: Vec::new(),
1352                };
1353            }
1354            Ok(Err(err)) => {
1355                return BlockReport {
1356                    index,
1357                    name,
1358                    verdict: LiveVerdict::IfCommandFailed(format!(
1359                        "if_command could not run: {err}"
1360                    )),
1361                    flags: Vec::new(),
1362                };
1363            }
1364            Ok(Ok(output)) if !output.status.success() => {
1365                return BlockReport {
1366                    index,
1367                    name,
1368                    verdict: LiveVerdict::Skipped(format!(
1369                        "if_command exited non-zero ({cmd}) — the bar would not show this block"
1370                    )),
1371                    flags: Vec::new(),
1372                };
1373            }
1374            Ok(Ok(_)) => (),
1375        }
1376    }
1377
1378    // Apply per-block overrides the same way BarState::spawn_block does
1379    if let Some(icons_format) = entry.common.icons_format {
1380        shared.icons_format = Arc::new(icons_format);
1381    }
1382    if let Some(theme_overrides) = entry.common.theme_overrides
1383        && let Err(err) = Arc::make_mut(&mut shared.theme).apply_overrides(theme_overrides)
1384    {
1385        return BlockReport {
1386            index,
1387            name,
1388            verdict: LiveVerdict::BlockError(format!("invalid theme_overrides: {err}")),
1389            flags: Vec::new(),
1390        };
1391    }
1392    if let Some(icons_overrides) = entry.common.icons_overrides {
1393        Arc::make_mut(&mut shared.icons).apply_overrides(icons_overrides);
1394    }
1395
1396    let (sender, mut receiver) = mpsc::unbounded_channel();
1397    let api = CommonApi {
1398        id: index,
1399        update_request: Arc::new(tokio::sync::Notify::new()),
1400        request_sender: sender,
1401        // effectively "never": doctor only watches the first seconds of output
1402        error_interval: Duration::from_secs(3600),
1403        geolocator,
1404        max_retries: Some(0),
1405    };
1406
1407    let mut futures = futures::stream::FuturesUnordered::new();
1408    entry.config.spawn(api, &mut futures);
1409    let handle = tokio::task::spawn_local(async move {
1410        futures.next().await;
1411    });
1412
1413    let first = capture_output(&mut receiver, deadline).await;
1414
1415    handle.abort();
1416    if let Err(err) = handle.await
1417        && err.is_panic()
1418    {
1419        return BlockReport {
1420            index,
1421            name,
1422            verdict: LiveVerdict::Panicked(join_error_message(err)),
1423            flags: Vec::new(),
1424        };
1425    }
1426
1427    let verdict = match first {
1428        Err(_) => LiveVerdict::NoOutput,
1429        Ok(None) => LiveVerdict::Finished,
1430        Ok(Some(LiveOutput::Hidden)) => LiveVerdict::Hidden,
1431        Ok(Some(LiveOutput::Error(error))) => LiveVerdict::BlockError(unwrap_terminated(&error)),
1432        Ok(Some(LiveOutput::Widget(widget))) => render_widget(&widget, &shared, index),
1433    };
1434
1435    BlockReport {
1436        index,
1437        name,
1438        verdict,
1439        flags: Vec::new(),
1440    }
1441}
1442
1443/// The block's output as the live test reports it: the latest thing it
1444/// publishes within `LIVE_SETTLE` of its first output. Blocks such as sound
1445/// publish before their backend reports the real state, so the first output
1446/// is not what the bar settles on. `Err` when nothing arrives by `deadline`.
1447async fn capture_output(
1448    receiver: &mut mpsc::UnboundedReceiver<Request>,
1449    deadline: tokio::time::Instant,
1450) -> std::result::Result<Option<LiveOutput>, tokio::time::error::Elapsed> {
1451    let Some(mut latest) = tokio::time::timeout_at(deadline, next_output(receiver)).await? else {
1452        return Ok(None);
1453    };
1454
1455    let settled = (tokio::time::Instant::now() + LIVE_SETTLE).min(deadline);
1456    while let Ok(Some(output)) = tokio::time::timeout_at(settled, next_output(receiver)).await {
1457        latest = output;
1458    }
1459    Ok(Some(latest))
1460}
1461
1462/// The next request that changes what the block shows; `None` once the
1463/// block's channel closes.
1464async fn next_output(receiver: &mut mpsc::UnboundedReceiver<Request>) -> Option<LiveOutput> {
1465    loop {
1466        let Request { cmd, .. } = receiver.recv().await?;
1467        match cmd {
1468            RequestCmd::SetWidget(widget) => return Some(LiveOutput::Widget(Box::new(widget))),
1469            RequestCmd::SetError { error, .. } => return Some(LiveOutput::Error(error)),
1470            RequestCmd::UnsetWidget => return Some(LiveOutput::Hidden),
1471            _ => continue,
1472        }
1473    }
1474}
1475
1476fn render_widget(widget: &Widget, shared: &SharedConfig, index: usize) -> LiveVerdict {
1477    // Record which icons rendering actually consumes: syntactic inspection
1478    // of the format is not enough, because a fallback branch containing
1479    // $icon may never be evaluated.
1480    crate::config::enable_icon_recorder();
1481    let _ = crate::config::take_recorded_icons();
1482    match widget.get_data(shared, index) {
1483        Ok(segments) => {
1484            let recorded = crate::config::take_recorded_icons();
1485            let icon_strings = recorded.clone();
1486            let mut icons: Vec<String> = recorded.iter().map(|(name, _)| name.clone()).collect();
1487            icons.sort_unstable();
1488            icons.dedup();
1489            let mut icon_glyphs: Vec<String> =
1490                recorded.into_iter().map(|(_, glyph)| glyph).collect();
1491            icon_glyphs.sort_unstable();
1492            icon_glyphs.dedup();
1493            // i3bar needs a non-empty placeholder in the other field to
1494            // switch a block between full and short mode; it draws nothing
1495            // and is not part of what the block rendered.
1496            let real = |s: &str| (s != SHORT_MODE_SENTINEL).then(|| s.to_string());
1497            let full: String = segments
1498                .iter()
1499                .filter_map(|s| real(&s.full_text))
1500                .collect::<Vec<_>>()
1501                .join("");
1502            let short: String = segments
1503                .iter()
1504                .filter_map(|s| real(&s.short_text))
1505                .collect::<Vec<_>>()
1506                .join("");
1507            LiveVerdict::Rendered {
1508                check_text: format!("{full}{short}"),
1509                text: full,
1510                icon_glyphs,
1511                icons,
1512                icon_strings,
1513                provided_icons: provided_icon_values(widget),
1514            }
1515        }
1516        Err(error) => {
1517            let mut provided: Vec<String> = widget.values().keys().map(|k| k.to_string()).collect();
1518            provided.sort_unstable();
1519            LiveVerdict::RenderError {
1520                error: error.to_string(),
1521                provided,
1522                // rendering failed, possibly on an icon: count all of them
1523                icons: provided_icon_values(widget)
1524                    .into_iter()
1525                    .map(|(_, name)| name)
1526                    .collect(),
1527            }
1528        }
1529    }
1530}
1531
1532/// All icon values a widget carries, as (placeholder key, icon name).
1533fn provided_icon_values(widget: &Widget) -> Vec<(String, String)> {
1534    let mut icons: Vec<(String, String)> = widget
1535        .values()
1536        .iter()
1537        .filter_map(|(key, value)| match &value.inner {
1538            ValueInner::Icon(name, _) => Some((key.to_string(), name.to_string())),
1539            _ => None,
1540        })
1541        .collect();
1542    icons.sort_unstable();
1543    icons.dedup();
1544    icons
1545}
1546
1547/// The block restart machinery wraps the real error in "Block terminated".
1548fn unwrap_terminated(error: &Error) -> String {
1549    match (&error.message, &error.cause) {
1550        (Some(msg), Some(cause)) if msg == "Block terminated" => cause.to_string(),
1551        _ => error.to_string(),
1552    }
1553}
1554
1555fn join_error_message(err: tokio::task::JoinError) -> String {
1556    match err.try_into_panic() {
1557        Ok(payload) => payload
1558            .downcast_ref::<String>()
1559            .cloned()
1560            .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
1561            .unwrap_or_else(|| "panic with non-string payload".into()),
1562        Err(err) => err.to_string(),
1563    }
1564}
1565
1566#[allow(clippy::too_many_arguments)]
1567/// Replace the strings a block's icons drew with `{name}`: `" 🔊 50% "`
1568/// becomes `" {volume} 50% "`. Longest first, so an icon string containing
1569/// another is replaced whole.
1570fn name_icons(report: &mut BlockReport) {
1571    let LiveVerdict::Rendered {
1572        text, icon_strings, ..
1573    } = &mut report.verdict
1574    else {
1575        return;
1576    };
1577    let mut strings: Vec<&(String, String)> = icon_strings
1578        .iter()
1579        .filter(|(_, drawn)| !drawn.is_empty())
1580        .collect();
1581    strings.sort_by_key(|(_, drawn)| std::cmp::Reverse(drawn.len()));
1582    for (name, drawn) in strings {
1583        // Keep the padding an icons_format adds around the glyph.
1584        let glyph = drawn.trim();
1585        let start = drawn.len() - drawn.trim_start().len();
1586        let named = format!(
1587            "{}{{{name}}}{}",
1588            &drawn[..start],
1589            &drawn[start + glyph.len()..]
1590        );
1591        *text = text.replace(drawn.as_str(), &named);
1592    }
1593}
1594
1595/// The Output cell for one live verdict: (text, is_red).
1596fn output_cell(verdict: &LiveVerdict) -> (String, bool) {
1597    let (cell, red) = output_cell_raw(verdict);
1598    // Everything here is derived from block output, command errors, or
1599    // configuration: never let it emit terminal control sequences.
1600    (escape_control(&cell), red)
1601}
1602
1603fn output_cell_raw(verdict: &LiveVerdict) -> (String, bool) {
1604    match verdict {
1605        LiveVerdict::Rendered { text, .. } => (format!("\"{text}\""), false),
1606        LiveVerdict::RenderError { error, .. } => (format!("RENDER ERROR: {error}"), true),
1607        LiveVerdict::BlockError(error) => (format!("ERROR: {error}"), true),
1608        LiveVerdict::Panicked(msg) => (format!("PANICKED: {msg}"), true),
1609        LiveVerdict::Hidden => (
1610            "(block hides itself — no data to show right now)".into(),
1611            false,
1612        ),
1613        LiveVerdict::Finished => ("(finished without producing output)".into(), false),
1614        LiveVerdict::NoOutput => (
1615            format!(
1616                "(no output within {}s — event-driven blocks may be waiting for an event; \
1617                 probably fine)",
1618                LIVE_TIMEOUT.as_secs()
1619            ),
1620            false,
1621        ),
1622        LiveVerdict::Skipped(reason) => (format!("(skipped: {reason})"), false),
1623        LiveVerdict::IfCommandFailed(reason) => (format!("IF_COMMAND FAILED: {reason}"), true),
1624        LiveVerdict::IfCommandTimeout(reason) => (
1625            format!("(inconclusive: {reason}; the bar itself would wait for it)"),
1626            false,
1627        ),
1628    }
1629}
1630
1631/// Like [`escape_control`], but keeping newlines: for diagnostics whose
1632/// own layout is multi-line (TOML parse errors, search traces).
1633fn escape_control_multiline(text: &str) -> String {
1634    text.split('\n')
1635        .map(escape_control)
1636        .collect::<Vec<_>>()
1637        .join("\n")
1638}
1639
1640/// The flags a block generated AND rendered: a block can compute a value
1641/// its configured format never shows (vpn's `$country_flag` when the
1642/// format asks only for `$country`), and what the bar never draws is not
1643/// something doctor should report as used.
1644fn rendered_flags<'a>(
1645    verdict: &'a LiveVerdict,
1646    flags: &'a [(String, String)],
1647) -> impl Iterator<Item = (&'a str, &'a str)> {
1648    let rendered = match verdict {
1649        LiveVerdict::Rendered { check_text, .. } => check_text.as_str(),
1650        _ => "",
1651    };
1652    flags
1653        .iter()
1654        .filter(move |(_, flag)| rendered.contains(flag.as_str()))
1655        .map(|(code, flag)| (code.as_str(), flag.as_str()))
1656}
1657
1658/// Marks a country flag a block generated. The `*` points at
1659/// [`FLAG_FOOTNOTE`]: the same codepoints ligate into a flag on the bar
1660/// but usually not in a terminal, so what doctor prints and what the bar
1661/// draws can differ.
1662fn flag_cell(country_code: &str, flag: &str) -> String {
1663    format!("{flag} ({country_code} country flag) *")
1664}
1665
1666const FLAG_FOOTNOTE: &str = "* Country flags are drawn differently in your terminal than on your bar, so a flag above \
1667     may not look like the one the bar shows.";
1668
1669/// Render control characters visibly, leaving printable text (including
1670/// icon glyphs and flags) untouched.
1671fn escape_control(text: &str) -> String {
1672    text.chars()
1673        .flat_map(|c| {
1674            // Invisible characters are shown, not obeyed: a bidi override
1675            // can reorder a whole line of doctor's own report. Visible text
1676            // is left alone, combining marks included.
1677            if c.is_control() {
1678                // \n, \t and friends read better than their codepoints.
1679                c.escape_debug().collect::<Vec<_>>()
1680            } else if is_invisible(c) {
1681                // Rust considers several of these printable, so the escape
1682                // has to be spelled out rather than delegated.
1683                format!("\\u{{{:x}}}", c as u32).chars().collect::<Vec<_>>()
1684            } else {
1685                vec![c]
1686            }
1687        })
1688        .collect()
1689}
1690
1691/// Print one row of the live-test table and record its consequences
1692/// (problems, live icon usage).
1693#[allow(clippy::too_many_arguments)]
1694fn print_block_report(
1695    report: &BlockReport,
1696    num_w: usize,
1697    name_w: usize,
1698    out_w: usize,
1699    style: &Style,
1700    problems: &mut Vec<Problem>,
1701    used_now: &mut BTreeMap<String, HashSet<String>>,
1702    prepared_errors: &HashSet<String>,
1703    label: &str,
1704) {
1705    let (cell, red) = output_cell(&report.verdict);
1706    let icons: &[String] = match &report.verdict {
1707        LiveVerdict::Rendered { icons, .. } | LiveVerdict::RenderError { icons, .. } => icons,
1708        _ => &[],
1709    };
1710    // Icons by name, plus text glyphs the block generated at the source
1711    // (country flags): both are font-dependent output. Icon names can come
1712    // straight from a command's JSON, so escape them too.
1713    let mut cells: Vec<String> = icons.iter().map(|name| escape_control(name)).collect();
1714    cells.extend(
1715        rendered_flags(&report.verdict, &report.flags).map(|(code, flag)| flag_cell(code, flag)),
1716    );
1717    let icons_cell = if cells.is_empty() {
1718        "-".to_string()
1719    } else {
1720        cells.join(", ")
1721    };
1722    let line = format!(
1723        "{:>num_w$}  {}  {}  {icons_cell}",
1724        report.index + 1,
1725        pad_right(&report.name, name_w),
1726        pad_right(&cell, out_w)
1727    );
1728    if red {
1729        println!("{}{line}{}", style.red, style.reset);
1730    } else {
1731        println!("{line}");
1732    }
1733
1734    for icon in icons {
1735        used_now
1736            .entry(icon.clone())
1737            .or_default()
1738            .insert(label.to_string());
1739    }
1740
1741    match &report.verdict {
1742        LiveVerdict::RenderError {
1743            error, provided, ..
1744        } => {
1745            println!(
1746                "    values the block provided: {}",
1747                escape_control(&provided.join(", "))
1748            );
1749            let fix = if error.contains("Placeholder") {
1750                Some(
1751                    "The format references a placeholder the block did not provide (it may be \
1752                     state-dependent). Make it optional with a fallback: \"{ $placeholder |}\"."
1753                        .to_string(),
1754                )
1755            } else if error.contains("Icon") {
1756                Some(
1757                    "Add the icon name to [icons.overrides] or use an icon set that defines it \
1758                     (see the icon table below)."
1759                        .to_string(),
1760                )
1761            } else {
1762                None
1763            };
1764            problems.push(Problem {
1765                diagnosis: format!("{}: render error: {}", report.name, escape_control(error)),
1766                fix,
1767            });
1768        }
1769        LiveVerdict::BlockError(error) if error.contains(CONTRACT_BUG) => {
1770            // set_widget rejects a widget whose icons its plan does not
1771            // declare, so the violation arrives here as a block error.
1772            // That is a fault in i3status-rs, not in the configuration.
1773            problems.push(Problem {
1774                diagnosis: format!(
1775                    "`{}` violated its own output contract: {}. This is a bug in i3status-rs, \
1776                     not in your configuration.",
1777                    report.name,
1778                    escape_control(error)
1779                ),
1780                fix: Some("Report it at https://github.com/greshake/i3status-rust/issues.".into()),
1781            });
1782        }
1783        LiveVerdict::BlockError(error) => {
1784            // A block that failed to prepare already has a static problem
1785            // with the same root cause; do not diagnose it twice.
1786            if !prepared_errors.contains(label) {
1787                problems.push(Problem {
1788                    diagnosis: format!("{}: {}", report.name, escape_control(error)),
1789                    fix: suggest_fix(&report.name, error),
1790                });
1791            }
1792        }
1793        LiveVerdict::Panicked(msg) => {
1794            problems.push(Problem {
1795                diagnosis: format!(
1796                    "{}: panicked ({}). In the bar this would show a permanent error.",
1797                    report.name,
1798                    escape_control(msg)
1799                ),
1800                fix: Some(
1801                    "This is a bug in i3status-rs; please report it upstream with your block \
1802                     config."
1803                        .into(),
1804                ),
1805            });
1806        }
1807        LiveVerdict::IfCommandFailed(reason) => {
1808            problems.push(Problem {
1809                diagnosis: format!(
1810                    "{}: {} — the bar fails to start when if_command cannot run.",
1811                    report.name,
1812                    escape_control(reason)
1813                ),
1814                fix: Some("Fix or remove the if_command.".into()),
1815            });
1816        }
1817        _ => (),
1818    }
1819}
1820
1821fn suggest_fix(block: &str, error: &str) -> Option<String> {
1822    let lower = error.to_lowercase();
1823    // D-Bus first: a missing bus socket also reads "no such file".
1824    if lower.contains("dbus") || lower.contains("d-bus") || lower.contains("org.freedesktop") {
1825        Some(format!(
1826            "A D-Bus service the `{block}` block needs is not available. Start the corresponding \
1827             daemon, or remove the block."
1828        ))
1829    } else if lower.contains("no such file") || lower.contains("program not found") {
1830        Some(format!(
1831            "A program the `{block}` block runs is not installed. Install it, or remove the block."
1832        ))
1833    } else if lower.contains("api key") || lower.contains("unauthorized") || lower.contains("401") {
1834        Some(format!(
1835            "Configure a valid API key for the `{block}` block."
1836        ))
1837    } else if lower.contains("rate limit") {
1838        Some("The service is rate limiting; wait, or reduce the update frequency.".into())
1839    } else {
1840        None
1841    }
1842}
1843
1844// ---------------------------------------------------------------------------
1845// Icon table
1846// ---------------------------------------------------------------------------
1847
1848/// Where a block's icon actually comes from, in precedence order.
1849#[derive(PartialEq, Eq, PartialOrd, Ord, Clone)]
1850enum Provenance {
1851    Base,
1852    Global,
1853    Local(String),
1854}
1855
1856/// Authoritative static analysis derived from a block's prepared contract
1857/// (see [`crate::block_plan`]). Runtime and doctor consume the same effective
1858/// formats and declared icon choices, so this cannot drift from what the
1859/// block actually does.
1860#[derive(Default)]
1861struct PlanAnalysis {
1862    /// Every icon name the block's contract declares, plus every direct
1863    /// `^icon_*` token in its effective formats. Blocks can only request
1864    /// declared icons (capability tokens), so all of these count as "in use
1865    /// by the block" — no reachability claims are made, and a declared icon
1866    /// the configuration never renders is harmless.
1867    required: HashSet<String>,
1868    /// Direct `^icon_*` names (subset of `required`).
1869    direct: HashSet<String>,
1870    /// The block declares an open dynamic icon source (custom/custom_dbus):
1871    /// any name may be requested at runtime, so static coverage is
1872    /// inherently partial for this block.
1873    open: bool,
1874}
1875
1876fn analyze_plan(plan: &crate::block_plan::BlockPlan) -> PlanAnalysis {
1877    use crate::block_plan::IconChoices;
1878    let mut analysis = PlanAnalysis::default();
1879    for output in plan.outputs() {
1880        for (_, choices) in output.icon_placeholders() {
1881            match choices {
1882                IconChoices::Fixed(names) => analysis.required.extend(
1883                    names
1884                        .iter()
1885                        .filter(|n| !n.is_empty())
1886                        .map(|n| n.to_string()),
1887                ),
1888                IconChoices::OpenResolvable => analysis.open = true,
1889            }
1890        }
1891        for template in [&output.format().full, &output.format().short] {
1892            let mut icons = Vec::new();
1893            collect_icon_tokens(template, &mut icons);
1894            for name in icons.into_iter().filter(|name| !name.is_empty()) {
1895                analysis.required.insert(name.clone());
1896                analysis.direct.insert(name);
1897            }
1898        }
1899    }
1900    analysis
1901}
1902
1903/// Every direct `^icon_*` token in a compiled template, without branch
1904/// analysis: doctor makes no reachability claims.
1905fn collect_icon_tokens(template: &format_template::FormatTemplate, icon_refs: &mut Vec<String>) {
1906    for token_list in template.0.iter() {
1907        for token in &token_list.0 {
1908            match token {
1909                format_template::Token::Icon { name } => icon_refs.push(name.clone()),
1910                format_template::Token::Recursive(rec) => collect_icon_tokens(rec, icon_refs),
1911                format_template::Token::Placeholder { .. } | format_template::Token::Text(_) => (),
1912            }
1913        }
1914    }
1915}
1916
1917struct IconTableInput<'a> {
1918    base_map: &'a HashMap<String, Icon>,
1919    global_overrides: &'a HashMap<String, Icon>,
1920    block_overrides: &'a [(String, HashMap<String, Icon>)],
1921    used_now: &'a BTreeMap<String, HashSet<String>>,
1922    /// Icon name -> labels of block instances whose contract declares it.
1923    declared_by: &'a BTreeMap<String, Vec<String>>,
1924    /// (label, icon) pairs already diagnosed by a live render error.
1925    live_reported: &'a HashSet<(String, String)>,
1926    /// Per block label: its effective icons_format (the wrapper applied to
1927    /// every icon it renders).
1928    icons_formats: &'a HashMap<String, String>,
1929    /// Block labels whose effective icons_format contains pango markup:
1930    /// the font drawing their icons is not verified (inconclusive).
1931    markup_labels: &'a HashSet<String>,
1932    font_check: &'a mut Option<FontCheck>,
1933    font_authoritative: bool,
1934    style: &'a Style,
1935    problems: &'a mut Vec<Problem>,
1936    /// Set when there is nothing to list, e.g. the config does not validate.
1937    skip_reason: Option<&'static str>,
1938    display: IconDisplay,
1939    /// Draws glyphs as the bar does, when the terminal can show images.
1940    renderer: Option<&'a BarRenderer>,
1941}
1942
1943fn print_icon_table(input: IconTableInput) {
1944    let IconTableInput {
1945        base_map,
1946        global_overrides,
1947        block_overrides,
1948        used_now,
1949        declared_by,
1950        live_reported,
1951        icons_formats,
1952        markup_labels,
1953        font_check,
1954        font_authoritative,
1955        style,
1956        problems,
1957        skip_reason,
1958        display,
1959        renderer,
1960    } = input;
1961    // Per-instance local overrides, keyed by instance label ("time#2"), so
1962    // two blocks of the same type are analyzed separately.
1963    let mut local: HashMap<&str, HashMap<&str, &Icon>> = HashMap::new();
1964    for (block, overrides) in block_overrides {
1965        let entry = local.entry(block.as_str()).or_default();
1966        for (name, icon) in overrides {
1967            entry.insert(name.as_str(), icon);
1968        }
1969    }
1970
1971    // What a given block instance actually resolves an icon name to.
1972    let resolve = |icon: &str, block: &str| -> Option<(&Icon, Provenance)> {
1973        if let Some(found) = local.get(block).and_then(|o| o.get(icon)) {
1974            return Some((found, Provenance::Local(block.to_string())));
1975        }
1976        if let Some(found) = global_overrides.get(icon) {
1977            return Some((found, Provenance::Global));
1978        }
1979        base_map.get(icon).map(|found| (found, Provenance::Base))
1980    };
1981
1982    // usage: icon name -> block labels. Declared = in use, period: every
1983    // icon a block's contract declares counts, whether or not this
1984    // particular run (or configuration) rendered it. Live-observed names
1985    // are merged in for the dynamic blocks.
1986    let mut usage: BTreeMap<String, Vec<String>> = BTreeMap::new();
1987    for (icon, blocks) in used_now {
1988        for block in blocks {
1989            usage.entry(icon.clone()).or_default().push(block.clone());
1990        }
1991    }
1992    for (icon, blocks) in declared_by {
1993        for block in blocks {
1994            let users = usage.entry((*icon).to_string()).or_default();
1995            if !users.contains(block) {
1996                users.push((*block).to_string());
1997            }
1998        }
1999    }
2000
2001    let mut used_rows: Vec<IconRow> = Vec::new();
2002    // Declared icon names that do not resolve for a block (not in the icon
2003    // set or any applicable override): listed as information.
2004    let mut undefined: Vec<(String, String)> = Vec::new();
2005    let mut fallback_rows = 0usize;
2006    let mut missing_rows = 0usize;
2007
2008    for (icon_name, users) in &usage {
2009        // Group the using blocks by what the icon actually resolves to for
2010        // them (an override REPLACES the base glyph for its block) and by
2011        // whether their icons_format markup makes the font inconclusive.
2012        let mut groups: BTreeMap<(Provenance, bool, String), Vec<String>> = BTreeMap::new();
2013        for block in users {
2014            match resolve(icon_name, block) {
2015                Some((icon, provenance)) => {
2016                    if matches!(icon, Icon::Progression(steps) if steps.is_empty()) {
2017                        // An empty progression cannot satisfy a request:
2018                        // Icons::get returns None for it, exactly like an
2019                        // undefined name.
2020                        if !live_reported.contains(&(block.clone(), icon_name.clone()))
2021                            && !undefined
2022                                .iter()
2023                                .any(|(name, b)| name == icon_name && b == block)
2024                        {
2025                            undefined.push((icon_name.clone(), block.clone()));
2026                        }
2027                        continue;
2028                    }
2029                    let markup = markup_labels.contains(block);
2030                    let icons_format = icons_formats
2031                        .get(block)
2032                        .cloned()
2033                        .unwrap_or_else(|| "{icon}".to_string());
2034                    groups
2035                        .entry((provenance, markup, icons_format))
2036                        .or_default()
2037                        .push(block.clone());
2038                }
2039                // already diagnosed by the live render error for this block
2040                None if live_reported.contains(&(block.clone(), icon_name.clone())) => (),
2041                None => {
2042                    // Availability information, not a problem: doctor makes
2043                    // no claim about whether the block's states and formats
2044                    // will actually request it — the live test reports
2045                    // failures that really happen.
2046                    if !undefined
2047                        .iter()
2048                        .any(|(name, b)| name == icon_name && b == block)
2049                    {
2050                        undefined.push((icon_name.clone(), block.clone()));
2051                    }
2052                }
2053            }
2054        }
2055        if groups.is_empty() {
2056            continue;
2057        }
2058        for ((provenance, markup, icons_format), mut blocks) in groups {
2059            blocks.sort_unstable();
2060            let (icon, tag) = match &provenance {
2061                Provenance::Base => (base_map.get(icon_name), String::new()),
2062                Provenance::Global => (global_overrides.get(icon_name), " [override]".into()),
2063                Provenance::Local(block) => (
2064                    local
2065                        .get(block.as_str())
2066                        .and_then(|o| o.get(icon_name.as_str()))
2067                        .copied(),
2068                    format!(" [{block} override]"),
2069                ),
2070            };
2071            let Some(icon) = icon else { continue };
2072            push_icon_rows(
2073                &mut used_rows,
2074                icon_name,
2075                icon,
2076                &tag,
2077                &blocks.join(", "),
2078                &icons_format,
2079                markup,
2080                font_check,
2081                &mut fallback_rows,
2082                &mut missing_rows,
2083            );
2084        }
2085    }
2086
2087    // Without a validated config there are no plans, so the table would be
2088    // its headers alone.
2089    if let Some(reason) = skip_reason {
2090        println!("Icons referenced by your blocks: skipped ({reason})");
2091    } else if used_rows.is_empty() {
2092        println!("Icons referenced by your blocks: none");
2093    } else {
2094        println!("Icons referenced by your blocks");
2095        let name_w = column_width("Name", used_rows.iter().map(|r| r.name.as_str()));
2096        let codes_w = column_width("Code", used_rows.iter().map(|r| r.codes.as_str()));
2097        let provider_w = column_width(
2098            "Effectively provided by",
2099            used_rows.iter().map(|r| r.provider.as_str()),
2100        );
2101        // As the bar draws them, where the terminal can show it. Markup is
2102        // left as text: doctor does not know all the markup around it.
2103        let images: Vec<Option<(String, usize)>> = used_rows
2104            .iter()
2105            .map(|r| {
2106                let renderer = renderer.filter(|_| !r.markup)?;
2107                renderer.render(&r.bar_text)
2108            })
2109            .collect();
2110        // The glyph cell renders as "X" including the quotes; size it by
2111        // display width so multi-character text icons ("LO") stay aligned.
2112        let glyph_w = used_rows
2113            .iter()
2114            .zip(&images)
2115            .map(|(r, image)| match image {
2116                Some((_, cells)) => *cells,
2117                None => UnicodeWidthStr::width(r.glyph.as_str()) + 2,
2118            })
2119            .chain([UnicodeWidthStr::width("Glyph")])
2120            .max()
2121            .unwrap_or(5);
2122        // With names the glyph column would only repeat the Name column.
2123        let glyph_col = |glyph: &str| match display {
2124            IconDisplay::Glyphs => format!("{}  ", pad_right(glyph, glyph_w)),
2125            IconDisplay::Names => String::new(),
2126        };
2127        // The image stays where it is drawn; spaces move the cursor past it.
2128        let image_col = |(escape, cells): &(String, usize)| {
2129            format!("{escape}{}  ", " ".repeat(glyph_w.max(*cells)))
2130        };
2131        println!(
2132            "{}  {}{}  {}  Used by",
2133            pad_right("Name", name_w),
2134            glyph_col("Glyph"),
2135            pad_right("Code", codes_w),
2136            pad_right("Effectively provided by", provider_w)
2137        );
2138        for (row, image) in used_rows.iter().zip(&images) {
2139            let glyph = match image {
2140                Some(image) => image_col(image),
2141                None => glyph_col(&format!("\"{}\"", row.glyph)),
2142            };
2143            let line = format!(
2144                "{}  {}{}  {}  {}",
2145                pad_right(&row.name, name_w),
2146                glyph,
2147                pad_right(&row.codes, codes_w),
2148                pad_right(&row.provider, provider_w),
2149                row.used_by
2150            );
2151            if row.red {
2152                println!("{}{line}{}", style.red, style.reset);
2153            } else {
2154                println!("{line}");
2155            }
2156        }
2157    }
2158    if fallback_rows > 0 || missing_rows > 0 || !undefined.is_empty() || !markup_labels.is_empty() {
2159        println!();
2160    }
2161    if fallback_rows > 0 {
2162        println!("* Glyph provider selected by the system because no font in your list has it.");
2163    }
2164    if missing_rows > 0 {
2165        println!("† No installed font has this glyph; it renders as an empty box.");
2166    }
2167    if !undefined.is_empty() {
2168        let listed: Vec<String> = undefined
2169            .iter()
2170            .map(|(name, block)| format!("{} ({block})", escape_control(name)))
2171            .collect();
2172        // A block can only ever request icons its contract declares, so a
2173        // declared name with no definition is a real gap: whenever the
2174        // block reaches that state, the bar shows an error instead of the
2175        // block.
2176        problems.push(Problem {
2177            diagnosis: format!(
2178                "Icon(s) declared by a block but not defined in your icon set or overrides: {}.",
2179                listed.join(", ")
2180            ),
2181            fix: Some(
2182                "Add the name(s) to [icons.overrides] (or the block's icons_overrides), or use \
2183                 an icon set that defines them."
2184                    .into(),
2185            ),
2186        });
2187    }
2188    if !markup_labels.is_empty() {
2189        let mut listed: Vec<&str> = markup_labels.iter().map(String::as_str).collect();
2190        listed.sort_unstable();
2191        println!(
2192            "note: pango markup (from a format, icons_format, or an icon value) affects: {}.\n\
2193             The font drawing those blocks' icons depends on that markup and is not verified\n\
2194             by doctor.",
2195            listed.join(", ")
2196        );
2197    }
2198    println!();
2199
2200    if fallback_rows > 0 {
2201        let diagnosis = format!(
2202            "{fallback_rows} icon glyph(s) will be drawn by fonts outside the bar's font \
2203             list (red rows above). Their appearance depends on which fonts happen to be \
2204             installed and can change with any font install or system update."
2205        );
2206        if font_authoritative {
2207            problems.push(Problem {
2208                diagnosis,
2209                fix: Some(
2210                    "Add a font that provides these glyphs to the bar's font directive \
2211                     (matching the icon set in use), and make sure it is installed."
2212                        .into(),
2213                ),
2214            });
2215        } else {
2216            println!("note: {diagnosis}");
2217            println!("note: the bar font was guessed, so this is not counted as a problem.");
2218            println!();
2219        }
2220    }
2221    if missing_rows > 0 {
2222        problems.push(Problem {
2223            diagnosis: format!(
2224                "{missing_rows} icon glyph(s) have no provider at all († rows above)."
2225            ),
2226            fix: Some(
2227                "Install a font that contains these codepoints, or override the icons with \
2228                 glyphs your fonts have."
2229                    .into(),
2230            ),
2231        });
2232    }
2233}
2234
2235/// Expand an icon into one table row per glyph (progressions as "name k/n")
2236/// and classify each glyph's font provider.
2237#[allow(clippy::too_many_arguments)]
2238fn push_icon_rows(
2239    used_rows: &mut Vec<IconRow>,
2240    name: &str,
2241    icon: &Icon,
2242    tag: &str,
2243    used_by: &str,
2244    icons_format: &str,
2245    markup: bool,
2246    font_check: &mut Option<FontCheck>,
2247    fallback_rows: &mut usize,
2248    missing_rows: &mut usize,
2249) {
2250    let name = escape_control(name);
2251    let rows: Vec<(String, &str)> = match icon {
2252        Icon::Single(s) => vec![(name.clone(), s.as_str())],
2253        Icon::Progression(steps) => steps
2254            .iter()
2255            .enumerate()
2256            .map(|(k, s)| (format!("{name} {}/{}", k + 1, steps.len()), s.as_str()))
2257            .collect(),
2258    };
2259    for (row_name, glyph) in rows {
2260        // What the bar actually draws: icons_format wraps every icon, and
2261        // whatever it adds is rendered with the same font questions.
2262        let effective = icons_format.replace("{icon}", glyph);
2263        let codes = codepoints(&effective);
2264        // An icon value containing markup is not a plain glyph: fontconfig
2265        // cannot be asked which font draws it.
2266        let markup = markup || contains_markup(&effective);
2267        let (provider, mark) = if markup {
2268            // Pango markup applies to this icon; doctor does not emulate
2269            // pango, so which font draws the glyph is unknown.
2270            ("(depends on pango markup)".to_string(), "")
2271        } else {
2272            match font_check.as_mut() {
2273                None => ("?".to_string(), ""),
2274                Some(check) => match glyph_provider(check, &effective) {
2275                    GlyphProvider::Known(family) => (escape_control(&first_family(&family)), ""),
2276                    GlyphProvider::Fallback(family) => {
2277                        *fallback_rows += 1;
2278                        (escape_control(&first_family(&family)), " *")
2279                    }
2280                    GlyphProvider::Missing => {
2281                        *missing_rows += 1;
2282                        ("(none)".to_string(), " †")
2283                    }
2284                },
2285            }
2286        };
2287        used_rows.push(IconRow {
2288            name: row_name,
2289            // Icon values are user-supplied: never let one emit terminal
2290            // control sequences into the table.
2291            glyph: escape_control(&effective),
2292            bar_text: effective.clone(),
2293            markup,
2294            codes,
2295            provider: format!("{provider}{mark}{tag}"),
2296            used_by: used_by.to_string(),
2297            red: !mark.is_empty(),
2298        });
2299    }
2300}
2301
2302struct IconRow {
2303    name: String,
2304    glyph: String,
2305    /// What the bar draws, unescaped: only ever rendered into an image.
2306    bar_text: String,
2307    markup: bool,
2308    codes: String,
2309    provider: String,
2310    used_by: String,
2311    red: bool,
2312}
2313
2314/// Pad `text` with spaces until it occupies `width` terminal cells. The
2315/// standard formatter pads by character count, which misaligns any table
2316/// containing wide (CJK, emoji) or zero-width characters.
2317fn pad_right(text: &str, width: usize) -> String {
2318    let padding = width.saturating_sub(UnicodeWidthStr::width(text));
2319    format!("{text}{}", " ".repeat(padding))
2320}
2321
2322fn column_width<'a>(header: &str, values: impl Iterator<Item = &'a str>) -> usize {
2323    values
2324        .map(UnicodeWidthStr::width)
2325        .chain([UnicodeWidthStr::width(header)])
2326        .max()
2327        .unwrap_or(0)
2328}
2329
2330fn codepoints(s: &str) -> String {
2331    let codes: Vec<String> = s
2332        .chars()
2333        .filter(|c| !c.is_ascii())
2334        .map(|c| format!("U+{:04X}", c as u32))
2335        .collect();
2336    if codes.is_empty() {
2337        "-".to_string()
2338    } else {
2339        codes.join(" ")
2340    }
2341}
2342
2343enum GlyphProvider {
2344    /// Primary or configured fallback family: expected, not flagged.
2345    Known(String),
2346    Fallback(String),
2347    Missing,
2348}
2349
2350/// fc-match reports family lists like "Font Awesome 5 Free,Font Awesome 5
2351/// Free Solid"; the first member is enough for display.
2352fn first_family(family: &str) -> String {
2353    family.split(',').next().unwrap_or(family).to_string()
2354}
2355
2356/// Unicode's `Default_Ignorable_Code_Point` property: characters a
2357/// renderer is expected to draw nothing for — joiners, variation
2358/// selectors, bidi controls, fillers, tags. Answered by ICU's Unicode
2359/// data rather than by a table maintained here.
2360///
2361/// This is not the same question as the general category: U+115F HANGUL
2362/// CHOSEONG FILLER is a letter that draws nothing, while a combining
2363/// acute accent has no advance width but a very visible glyph.
2364fn is_default_ignorable(c: char) -> bool {
2365    CodePointSetData::new::<DefaultIgnorableCodePoint>().contains(c)
2366}
2367
2368/// Interlinear annotation controls: `Cf` characters that are not
2369/// default-ignorable but are still an editing protocol rather than text.
2370fn is_annotation_char(c: char) -> bool {
2371    matches!(c, '\u{fff9}'..='\u{fffb}')
2372}
2373
2374/// Characters with no glyph of their own, which fontconfig cannot
2375/// meaningfully be asked about.
2376fn is_invisible(c: char) -> bool {
2377    is_default_ignorable(c) || is_annotation_char(c)
2378}
2379
2380/// Whether a character has a glyph a font must supply. Zero *advance
2381/// width* is not the test — combining marks draw perfectly visible
2382/// accents — so this asks Unicode which characters are ignorable.
2383fn is_drawn(c: char) -> bool {
2384    !c.is_control() && !c.is_whitespace() && !is_invisible(c)
2385}
2386
2387fn glyph_provider(check: &mut FontCheck, glyph: &str) -> GlyphProvider {
2388    let mut result = GlyphProvider::Known(check.base_family.clone());
2389    for c in glyph.chars() {
2390        if !is_drawn(c) {
2391            continue;
2392        }
2393        match check.check(c) {
2394            GlyphFont::Base => (),
2395            GlyphFont::Configured(family) => {
2396                if matches!(result, GlyphProvider::Known(_)) {
2397                    result = GlyphProvider::Known(family.clone());
2398                }
2399            }
2400            GlyphFont::Fallback(family) => {
2401                if !matches!(result, GlyphProvider::Missing) {
2402                    result = GlyphProvider::Fallback(family.clone());
2403                }
2404            }
2405            GlyphFont::Missing => result = GlyphProvider::Missing,
2406        }
2407    }
2408    result
2409}
2410
2411fn print_problems(problems: &[Problem], live_ran: bool, style: &Style) {
2412    if problems.is_empty() {
2413        if live_ran {
2414            println!("Problems: none found");
2415        } else {
2416            println!(
2417                "Problems: none statically provable (the live block test did not run; \
2418                 runtime behavior — commands, services, dynamic icon names — was not \
2419                 checked)"
2420            );
2421        }
2422        return;
2423    }
2424    println!("{}Problems ({}){}", style.red, problems.len(), style.reset);
2425    for (i, problem) in problems.iter().enumerate() {
2426        println!("{}. {}", i + 1, problem.diagnosis);
2427        match &problem.fix {
2428            Some(fix) => println!("   Fix: {fix}"),
2429            None => println!("   (no fix suggestion)"),
2430        }
2431    }
2432}
2433
2434// ---------------------------------------------------------------------------
2435// File resolution
2436// ---------------------------------------------------------------------------
2437
2438/// Returns the winning path and a human-readable trace of every candidate.
2439/// What the bar's own lookup would do with this name.
2440enum Resolved {
2441    /// The file the bar would use.
2442    Found(PathBuf),
2443    /// No candidate exists.
2444    Missing,
2445    /// A candidate could not be examined. [`util::find_file`] returns the
2446    /// error rather than moving on, so the bar never reaches the
2447    /// lower-priority candidates and neither may doctor.
2448    Failed(String),
2449}
2450
2451fn resolve_file(file: &str, subdir: Option<&str>) -> (Resolved, String) {
2452    let mut found: Option<PathBuf> = None;
2453    let mut failure: Option<String> = None;
2454    let mut trace = String::new();
2455    if !Path::new(file).is_absolute() {
2456        trace.push_str("   (not an absolute path; standard locations searched in order)\n");
2457    }
2458    for candidate in util::file_candidates(file, subdir, Some("toml")) {
2459        let line = match (candidate.try_exists(), &found) {
2460            (Ok(true), None) => {
2461                let line = format!(
2462                    "   ✓ {} ← using this\n",
2463                    escape_control(&candidate.display().to_string())
2464                );
2465                found = Some(candidate);
2466                line
2467            }
2468            // Candidates embed the configured name: a newline in it must
2469            // not forge a line in doctor's own report.
2470            (Ok(true), Some(_)) => format!(
2471                "   ✓ {} (shadowed)\n",
2472                escape_control(&candidate.display().to_string())
2473            ),
2474            (Ok(false), _) => format!(
2475                "   ✗ {}\n",
2476                escape_control(&candidate.display().to_string())
2477            ),
2478            (Err(err), _) => {
2479                let line = format!(
2480                    "   ✗ {} (cannot be examined: {err} — the bar stops here)\n",
2481                    escape_control(&candidate.display().to_string())
2482                );
2483                failure = Some(format!("{}: {err}", candidate.display()));
2484                line
2485            }
2486        };
2487        trace.push_str(&line);
2488        if failure.is_some() {
2489            break;
2490        }
2491    }
2492    let resolved = match (failure, found) {
2493        (Some(err), _) => Resolved::Failed(err),
2494        (None, Some(path)) => Resolved::Found(path),
2495        (None, None) => Resolved::Missing,
2496    };
2497    (resolved, trace.trim_end().to_string())
2498}
2499
2500// ---------------------------------------------------------------------------
2501// Fonts (fc-match / fc-list / bar IPC)
2502// ---------------------------------------------------------------------------
2503
2504/// How a single character gets rendered, according to fontconfig.
2505#[derive(Clone)]
2506enum GlyphFont {
2507    /// Rendered by the primary (first) configured family.
2508    Base,
2509    /// Rendered by one of the other configured fallback families.
2510    Configured(String),
2511    /// No configured family has it; fontconfig substitutes this family.
2512    Fallback(String),
2513    /// No installed font provides it: renders as an empty box.
2514    Missing,
2515}
2516
2517/// Asks fontconfig (via `fc-match`/`fc-list`) which font actually renders
2518/// each glyph. This happens in the bar, outside of i3status-rs, and is the
2519/// usual source of "my icon was silently replaced by a different symbol":
2520/// when no configured font has a codepoint, fontconfig substitutes another
2521/// installed font without telling anyone.
2522struct FontCheck {
2523    /// The family that draws plain text: the first configured family that is
2524    /// actually present.
2525    base_family: String,
2526    /// Index of that family in `families`.
2527    base_index: Option<usize>,
2528    /// Each bar family with what fc-match resolves it to; a family that
2529    /// resolves to something else entirely is not installed.
2530    families: Vec<(String, Option<String>)>,
2531    cache: HashMap<char, GlyphFont>,
2532}
2533
2534impl FontCheck {
2535    fn new(font_arg: Option<&str>) -> Option<Self> {
2536        let families = parse_font_directive(font_arg.unwrap_or(""));
2537        let pattern = families.join(",");
2538        // Also proves fc-match exists; used as the base family only when the
2539        // bar configured no families of its own.
2540        let fontconfig_default = fc_match(&pattern, None)?;
2541        // fontconfig ships fc-list with fc-match; without both, no check.
2542        let has_fc_list = std::process::Command::new("fc-list")
2543            .arg("--version")
2544            .output()
2545            .is_ok_and(|out| out.status.success());
2546        if !has_fc_list {
2547            return None;
2548        }
2549        let mut families: Vec<(String, Option<String>)> = families
2550            .into_iter()
2551            .map(|family| {
2552                let resolved = fc_match(&family, None);
2553                (family, resolved)
2554            })
2555            .collect();
2556        if families.is_empty() {
2557            // No font directive: the bar renders with fontconfig's default,
2558            // so that is the one family it "configured".
2559            families.push((fontconfig_default.clone(), Some(fontconfig_default.clone())));
2560        }
2561        let base_index = families
2562            .iter()
2563            .position(|(family, _)| family_present(family));
2564        let base_family = match base_index {
2565            Some(index) => {
2566                let (family, resolved) = &families[index];
2567                // A generic alias is not a family any font carries; report
2568                // the concrete family it stands for.
2569                if is_generic_family(family) {
2570                    resolved
2571                        .as_deref()
2572                        .map_or_else(|| family.clone(), first_family)
2573                } else {
2574                    family.clone()
2575                }
2576            }
2577            None => fontconfig_default,
2578        };
2579        Some(Self {
2580            base_family,
2581            base_index,
2582            families,
2583            cache: HashMap::new(),
2584        })
2585    }
2586
2587    fn check(&mut self, c: char) -> GlyphFont {
2588        if let Some(hit) = self.cache.get(&c) {
2589            return hit.clone();
2590        }
2591        let result = self.classify(c);
2592        self.cache.insert(c, result.clone());
2593        result
2594    }
2595
2596    fn classify(&self, c: char) -> GlyphFont {
2597        let charset = format!("{:x}", c as u32);
2598        if !fc_list_provides(&charset) {
2599            return GlyphFont::Missing;
2600        }
2601        // The bar falls back per character down its font list, so the first
2602        // configured family that has the codepoint is the one that draws it.
2603        // Asking fontconfig to match the whole list at once answers a
2604        // different question — it ranks by its own rules, and a color emoji
2605        // font in the list outranks family order for every codepoint, which
2606        // made every glyph look like it came from that one font.
2607        for (index, (family, resolved)) in self.families.iter().enumerate() {
2608            if !family_covers(family, resolved, &charset) {
2609                continue;
2610            }
2611            return if Some(index) == self.base_index {
2612                GlyphFont::Base
2613            } else {
2614                GlyphFont::Configured(family.clone())
2615            };
2616        }
2617        // No configured family has it: whatever fontconfig substitutes is
2618        // what the user will actually see, and is not what they asked for.
2619        match fc_match("", Some(&charset)) {
2620            Some(family) => GlyphFont::Fallback(family),
2621            None => GlyphFont::Missing,
2622        }
2623    }
2624}
2625
2626/// Whether one configured family has this codepoint, asked of fontconfig:
2627/// `fc-list` with a family and a charset lists only fonts that satisfy both.
2628///
2629/// A generic alias (`monospace`, ...) is not a family any font carries, so it
2630/// is tested through the concrete family it resolves to. A family that is not
2631/// installed also resolves to something, but that substitute is not what the
2632/// user configured, so it is not consulted.
2633fn family_covers(family: &str, resolved: &Option<String>, charset: &str) -> bool {
2634    if fc_list_family_provides(family, charset) {
2635        return true;
2636    }
2637    is_generic_family(family)
2638        && resolved.as_ref().is_some_and(|resolved| {
2639            resolved
2640                .split(',')
2641                .any(|concrete| fc_list_family_provides(concrete, charset))
2642        })
2643}
2644
2645/// Whether a configured family is present at all. Generic aliases always
2646/// resolve to something.
2647fn family_present(family: &str) -> bool {
2648    is_generic_family(family) || family_installed(family)
2649}
2650
2651/// Whether a family is installed, asked of fontconfig itself: `fc-list` with
2652/// a family pattern lists only fonts whose family matches under fontconfig's
2653/// own normalization (so "DejaVuSansMono" finds "DejaVu Sans Mono").
2654fn family_installed(family: &str) -> bool {
2655    std::process::Command::new("fc-list")
2656        .arg(family)
2657        .arg("family")
2658        .output()
2659        .is_ok_and(|out| {
2660            out.status.success() && !String::from_utf8_lossy(&out.stdout).trim().is_empty()
2661        })
2662}
2663
2664/// Fontconfig's generic aliases: asking for these by design resolves to some
2665/// installed concrete family.
2666fn is_generic_family(family: &str) -> bool {
2667    matches!(
2668        family.to_lowercase().as_str(),
2669        "monospace"
2670            | "mono"
2671            | "sans-serif"
2672            | "sans"
2673            | "serif"
2674            | "cursive"
2675            | "fantasy"
2676            | "system-ui"
2677            | "emoji"
2678            | "math"
2679    )
2680}
2681
2682fn fc_match(pattern: &str, charset: Option<&str>) -> Option<String> {
2683    let mut pattern = pattern.to_string();
2684    if let Some(charset) = charset {
2685        pattern.push_str(&format!(":charset={charset}"));
2686    }
2687    let out = std::process::Command::new("fc-match")
2688        .arg("--format=%{family}")
2689        .arg(&pattern)
2690        .output()
2691        .ok()?;
2692    if !out.status.success() {
2693        return None;
2694    }
2695    let family = String::from_utf8_lossy(&out.stdout).trim().to_string();
2696    (!family.is_empty()).then_some(family)
2697}
2698
2699fn fc_list_provides(charset: &str) -> bool {
2700    std::process::Command::new("fc-list")
2701        .arg(format!(":charset={charset}"))
2702        .arg("family")
2703        .output()
2704        .is_ok_and(|out| out.status.success() && !out.stdout.is_empty())
2705}
2706
2707/// Whether any installed font of `family` provides `charset`.
2708fn fc_list_family_provides(family: &str, charset: &str) -> bool {
2709    std::process::Command::new("fc-list")
2710        .arg(format!("{family}:charset={charset}"))
2711        .arg("family")
2712        .output()
2713        .is_ok_and(|out| {
2714            out.status.success() && !String::from_utf8_lossy(&out.stdout).trim().is_empty()
2715        })
2716}
2717
2718struct DetectedFont {
2719    bar_id: String,
2720    font: String,
2721    colors: BarColors,
2722    /// Ambiguity warning when several bars with different fonts exist.
2723    note: Option<String>,
2724}
2725
2726/// The bar's text and background colors, as `#rrggbbaa`.
2727struct BarColors {
2728    text: String,
2729    background: String,
2730}
2731
2732/// What swaybar draws with when its config sets no font or colors.
2733const DEFAULT_BAR_FONT: &str = "monospace 10";
2734const DEFAULT_BAR_TEXT: &str = "#ffffffff";
2735const DEFAULT_BAR_BACKGROUND: &str = "#000000ff";
2736
2737/// Draws text into images the way the bar draws it, for terminals that can
2738/// show images: pango-view is pango itself, the renderer behind the bar, so
2739/// its font selection and fallback are the bar's, not an emulation.
2740struct BarRenderer {
2741    args: Vec<String>,
2742    cell: CellSize,
2743    /// A private directory for pango-view's output, removed on drop.
2744    dir: PathBuf,
2745}
2746
2747impl BarRenderer {
2748    /// `None` when the terminal cannot show images or pango-view is missing.
2749    fn new(font: Option<&str>, colors: Option<&BarColors>) -> Option<Self> {
2750        let has_pango_view = std::process::Command::new("pango-view")
2751            .arg("--version")
2752            .output()
2753            .is_ok_and(|out| out.status.success());
2754        if !has_pango_view {
2755            return None;
2756        }
2757        let cell = term_graphics::kitty_cell_size()?;
2758
2759        // create_dir fails if the path exists, so nobody else's file or
2760        // symlink is ever written through.
2761        let dir = std::env::temp_dir().join(format!("i3status-rs-doctor-{}", std::process::id()));
2762        std::fs::DirBuilder::new().mode(0o700).create(&dir).ok()?;
2763        Some(Self {
2764            args: pango_view_args(font, colors, &dir.join("glyph.png")),
2765            cell,
2766            dir,
2767        })
2768    }
2769
2770    /// The image escape for `text` and its width in cells.
2771    fn render(&self, text: &str) -> Option<(String, usize)> {
2772        let out = std::process::Command::new("pango-view")
2773            .args(&self.args)
2774            .arg(format!("--text={text}"))
2775            .output()
2776            .ok()?;
2777        if !out.status.success() {
2778            return None;
2779        }
2780        let png = std::fs::read(self.dir.join("glyph.png")).ok()?;
2781        term_graphics::png_image(&png, self.cell)
2782    }
2783}
2784
2785impl Drop for BarRenderer {
2786    fn drop(&mut self) {
2787        let _ = std::fs::remove_dir_all(&self.dir);
2788    }
2789}
2790
2791/// pango-view's arguments for drawing like the bar: its font directive
2792/// (without the `pango:` prefix pango does not know) and colors, no margin.
2793fn pango_view_args(font: Option<&str>, colors: Option<&BarColors>, png: &Path) -> Vec<String> {
2794    let font = font.map_or(DEFAULT_BAR_FONT, |f| f.strip_prefix("pango:").unwrap_or(f));
2795    let (text, background) = colors.map_or((DEFAULT_BAR_TEXT, DEFAULT_BAR_BACKGROUND), |c| {
2796        (c.text.as_str(), c.background.as_str())
2797    });
2798    vec![
2799        "--no-display".into(),
2800        "--margin=0".into(),
2801        format!("--font={font}"),
2802        format!("--foreground={text}"),
2803        format!("--background={background}"),
2804        format!("--output={}", png.display()),
2805    ]
2806}
2807
2808/// Ask the running i3/sway over IPC which font the bar is configured with,
2809/// so `--font` is only needed when there is no live bar to ask.
2810///
2811/// With several bars, prefer the one whose status_command runs i3status-rs;
2812/// if the remaining candidates disagree on the font, report the ambiguity.
2813fn detect_bar_font() -> Option<DetectedFont> {
2814    // The same connection the sway bar colour integration uses; it finds
2815    // i3 or sway through I3SOCK, SWAYSOCK or `--get-socketpath`.
2816    crate::util::run_sync(async {
2817        let mut ipc = swayipc_async::Connection::new().await.ok()?;
2818
2819        // (bar_id, font, status_command), and colors kept apart for pick_bar.
2820        let bar_ids = ipc.get_bar_ids().await.ok()?;
2821        let mut configs = Vec::with_capacity(bar_ids.len());
2822        for id in bar_ids {
2823            if let Ok(bar) = ipc.get_bar_config(&id).await {
2824                configs.push(bar);
2825            }
2826        }
2827        let bars: Vec<(String, String, String)> = configs
2828            .iter()
2829            .map(|bar| {
2830                let command = bar.status_command.clone().unwrap_or_default();
2831                (bar.id.clone(), bar.font.clone(), command)
2832            })
2833            .collect();
2834        if bars.is_empty() {
2835            return None;
2836        }
2837
2838        let (chosen, note) = pick_bar(&bars);
2839        let bar = configs.into_iter().nth(chosen)?;
2840        let colors = BarColors {
2841            text: bar.colors.statusline,
2842            background: bar.colors.background,
2843        };
2844        Some(DetectedFont {
2845            bar_id: bar.id,
2846            font: bar.font,
2847            colors,
2848            note,
2849        })
2850    })
2851}
2852
2853/// Why IPC found no bar, when the environment explains it: a shell or tmux
2854/// server started under an earlier i3/sway keeps a socket path that no
2855/// longer exists.
2856fn stale_socket_note() -> Option<String> {
2857    ["I3SOCK", "SWAYSOCK"].into_iter().find_map(|var| {
2858        let path = std::env::var_os(var)?;
2859        if std::path::Path::new(&path).exists() {
2860            return None;
2861        }
2862        Some(format!(
2863            "{var} points to {:?},\n   which no longer exists: this shell or tmux session \
2864             was started under an earlier\n   i3/sway. Open a new one (or update {var}) and \
2865             re-run.",
2866            path
2867        ))
2868    })
2869}
2870
2871/// The bar whose font to check, as `(index, note)` into `bars`, which holds
2872/// `(bar_id, font, status_command)`. Only bars running i3status-rs are
2873/// candidates; with none, every bar is. The note warns when the candidates
2874/// disagree on the font.
2875fn pick_bar(bars: &[(String, String, String)]) -> (usize, Option<String>) {
2876    let ours: Vec<usize> = (0..bars.len())
2877        .filter(|&i| bars[i].2.contains("i3status-rs"))
2878        .collect();
2879    let candidates = if ours.is_empty() {
2880        (0..bars.len()).collect()
2881    } else {
2882        ours
2883    };
2884
2885    let chosen = candidates[0];
2886    let font = &bars[chosen].1;
2887    if candidates.iter().all(|&i| bars[i].1 == *font) {
2888        return (chosen, None);
2889    }
2890
2891    let list = candidates
2892        .iter()
2893        .map(|&i| format!("{}: {:?}", bars[i].0, bars[i].1))
2894        .collect::<Vec<_>>()
2895        .join(", ");
2896    let note = format!(
2897        "several bars with different fonts ({list}); picked {:?} — pass --font if that \
2898         is the wrong one",
2899        bars[chosen].0
2900    );
2901    (chosen, Some(note))
2902}
2903
2904/// The font families an i3/sway font directive names, in order.
2905///
2906/// `"pango:DejaVu Sans Mono, Font Awesome 6 Free Bold 12"` →
2907/// `["DejaVu Sans Mono", "Font Awesome 6 Free"]`
2908///
2909/// (the style and size qualify the whole description, so they follow the
2910/// fallback list rather than the first family)
2911///
2912/// This reads the description the way `pango_font_description_from_string`
2913/// does, from the end: optional `@variations`, then a size (`12`, `16px`),
2914/// then style words; what is left is the comma-separated family list. A test
2915/// checks it against pango itself.
2916fn parse_font_directive(raw: &str) -> Vec<String> {
2917    let mut rest = raw.strip_prefix("pango:").unwrap_or(raw);
2918
2919    // Variations start a word and may hold commas (`@wght=600,wdth=80`), so
2920    // only whitespace ends them.
2921    let trimmed = rest.trim_end();
2922    let word_start = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1);
2923    if trimmed[word_start..].starts_with('@') {
2924        rest = &trimmed[..word_start];
2925    }
2926    if let Some((head, word)) = last_word(rest)
2927        && is_font_size(word)
2928    {
2929        rest = head;
2930    }
2931    while let Some((head, word)) = last_word(rest)
2932        && is_style_word(word)
2933    {
2934        rest = head;
2935    }
2936
2937    rest.split(',')
2938        .map(str::trim)
2939        .filter(|family| !family.is_empty())
2940        .map(String::from)
2941        .collect()
2942}
2943
2944/// The last word of a font description and what precedes it. Words end at
2945/// whitespace or a comma, as in pango: `"Sans, Bold"` → `("Sans, ", "Bold")`.
2946fn last_word(description: &str) -> Option<(&str, &str)> {
2947    let trimmed = description.trim_end();
2948    let start = trimmed
2949        .rfind(|c: char| c.is_whitespace() || c == ',')
2950        .map_or(0, |i| i + 1);
2951    let word = &trimmed[start..];
2952    (!word.is_empty()).then(|| (&trimmed[..start], word))
2953}
2954
2955/// A size as pango reads one: a number, optionally in pixels (`16px`).
2956fn is_font_size(word: &str) -> bool {
2957    let number = word.strip_suffix("px").unwrap_or(word);
2958    number
2959        .parse::<f64>()
2960        .is_ok_and(|size| size.is_finite() && size >= 0.0)
2961}
2962
2963/// pango's style, variant, weight, stretch and gravity names.
2964const PANGO_STYLE_WORDS: &[&str] = &[
2965    "Normal",
2966    "Roman",
2967    "Oblique",
2968    "Italic",
2969    "Small-Caps",
2970    "All-Small-Caps",
2971    "Petite-Caps",
2972    "All-Petite-Caps",
2973    "Unicase",
2974    "Title-Caps",
2975    "Thin",
2976    "Ultra-Light",
2977    "Extra-Light",
2978    "Light",
2979    "Semi-Light",
2980    "Demi-Light",
2981    "Book",
2982    "Regular",
2983    "Medium",
2984    "Semi-Bold",
2985    "Demi-Bold",
2986    "Bold",
2987    "Ultra-Bold",
2988    "Extra-Bold",
2989    "Heavy",
2990    "Black",
2991    "Ultra-Heavy",
2992    "Extra-Heavy",
2993    "Ultra-Condensed",
2994    "Extra-Condensed",
2995    "Condensed",
2996    "Semi-Condensed",
2997    "Semi-Expanded",
2998    "Expanded",
2999    "Extra-Expanded",
3000    "Ultra-Expanded",
3001    "Not-Rotated",
3002    "South",
3003    "Upside-Down",
3004    "North",
3005    "Rotated-Left",
3006    "East",
3007    "Rotated-Right",
3008    "West",
3009];
3010
3011/// Whether pango takes `word` as a style word. Like pango, case is ignored
3012/// and the hyphen is optional: `semibold` is `Semi-Bold`.
3013fn is_style_word(word: &str) -> bool {
3014    let word = word.to_ascii_lowercase();
3015    PANGO_STYLE_WORDS.iter().any(|name| {
3016        let name = name.to_ascii_lowercase();
3017        word == name || word == name.replace('-', "")
3018    })
3019}
3020
3021// ---------------------------------------------------------------------------
3022// Raw-config format string analysis
3023// ---------------------------------------------------------------------------
3024
3025#[cfg(test)]
3026mod tests {
3027    use super::*;
3028
3029    fn bar(id: &str, font: &str, cmd: &str) -> (String, String, String) {
3030        (id.into(), font.into(), cmd.into())
3031    }
3032
3033    #[test]
3034    fn name_icons_keeps_icons_format_padding() {
3035        let mut report = BlockReport {
3036            index: 0,
3037            name: "sound".into(),
3038            verdict: LiveVerdict::Rendered {
3039                text: "[ V ]50%".into(),
3040                check_text: String::new(),
3041                icon_glyphs: Vec::new(),
3042                icons: vec!["volume".into()],
3043                icon_strings: vec![("volume".into(), " V ".into())],
3044                provided_icons: Vec::new(),
3045            },
3046            flags: Vec::new(),
3047        };
3048        name_icons(&mut report);
3049        let LiveVerdict::Rendered { text, .. } = report.verdict else {
3050            unreachable!()
3051        };
3052        assert_eq!(text, "[ {volume} ]50%");
3053    }
3054
3055    #[tokio::test]
3056    async fn live_capture_reports_the_settled_output_not_the_first() {
3057        // Blocks like sound publish before their backend reports the real
3058        // state; the live test must show where the block settles.
3059        let (sender, mut receiver) = mpsc::unbounded_channel();
3060        sender
3061            .send(Request {
3062                block_id: 0,
3063                cmd: RequestCmd::SetWidget(Widget::new()),
3064            })
3065            .unwrap();
3066        sender
3067            .send(Request {
3068                block_id: 0,
3069                cmd: RequestCmd::UnsetWidget,
3070            })
3071            .unwrap();
3072        drop(sender);
3073        let deadline = tokio::time::Instant::now() + LIVE_TIMEOUT;
3074        let output = capture_output(&mut receiver, deadline).await.unwrap();
3075        assert!(matches!(output, Some(LiveOutput::Hidden)));
3076    }
3077
3078    #[test]
3079    fn suggest_fix_prefers_dbus_over_a_missing_file() {
3080        // A missing D-Bus socket surfaces as an I/O "no such file" error.
3081        let fix = suggest_fix(
3082            "battery",
3083            "Failed to open DBus system connection. Cause: I/O error: \
3084             No such file or directory (os error 2)",
3085        )
3086        .unwrap();
3087        assert!(fix.contains("D-Bus"), "{fix}");
3088    }
3089
3090    #[test]
3091    fn contains_markup_ignores_the_bars_own_escapes() {
3092        assert!(!contains_markup("a &amp; b &#39;q&#39; &lt;tag&gt;"));
3093        assert!(contains_markup("<b>bold</b>"));
3094        assert!(contains_markup("&#x1F600;"));
3095        assert!(contains_markup("&nbsp;"));
3096    }
3097
3098    #[test]
3099    fn pango_view_draws_with_the_bars_font_and_colors() {
3100        let colors = BarColors {
3101            text: "#e6e1cfff".into(),
3102            background: "#1f2430ff".into(),
3103        };
3104        let args = pango_view_args(
3105            Some("pango:DejaVu Sans Mono 12"),
3106            Some(&colors),
3107            Path::new("/d/glyph.png"),
3108        );
3109        assert_eq!(
3110            args,
3111            [
3112                "--no-display",
3113                "--margin=0",
3114                "--font=DejaVu Sans Mono 12",
3115                "--foreground=#e6e1cfff",
3116                "--background=#1f2430ff",
3117                "--output=/d/glyph.png",
3118            ]
3119        );
3120    }
3121
3122    #[test]
3123    fn pango_view_falls_back_to_swaybar_defaults() {
3124        let args = pango_view_args(None, None, Path::new("/d/glyph.png"));
3125        assert!(args.contains(&format!("--font={DEFAULT_BAR_FONT}")));
3126        assert!(args.contains(&format!("--foreground={DEFAULT_BAR_TEXT}")));
3127        assert!(args.contains(&format!("--background={DEFAULT_BAR_BACKGROUND}")));
3128    }
3129
3130    #[test]
3131    fn renderer_turns_a_glyph_into_a_kitty_image() {
3132        let has_pango_view = std::process::Command::new("pango-view")
3133            .arg("--version")
3134            .output()
3135            .is_ok_and(|out| out.status.success());
3136        if !has_pango_view {
3137            eprintln!("skipped: pango-view not installed");
3138            return;
3139        }
3140
3141        let dir = std::env::temp_dir().join(format!("i3rs-render-test-{}", std::process::id()));
3142        std::fs::create_dir_all(&dir).unwrap();
3143        let renderer = BarRenderer {
3144            args: pango_view_args(Some("monospace 10"), None, &dir.join("glyph.png")),
3145            cell: CellSize {
3146                width: 10,
3147                height: 20,
3148            },
3149            dir,
3150        };
3151
3152        let (escape, cells) = renderer.render("W").unwrap();
3153        assert!(escape.starts_with("\x1b_Ga=T,f=100,"));
3154        // One monospace letter, scaled to a row, is about a cell wide.
3155        assert!((1..=2).contains(&cells), "{cells} cells");
3156    }
3157
3158    #[test]
3159    fn parse_font_directive_agrees_with_pango() {
3160        let directives = [
3161            "DejaVu Sans Mono, Font Awesome 6 Free 12",
3162            "DejaVu Sans Mono 13.5",
3163            "DejaVu Sans Mono Bold 10",
3164            "Liberation Mono Bold Italic 11",
3165            "Terminus (TTF) 16px",
3166            "Terminus (TTF) 16px, FontAwesome 10",
3167            "monospace,Font Awesome 5 Free",
3168            "Roboto Mono for Powerline, Symbols Nerd Font Mono 9",
3169            "Font Awesome 6 Free Solid 10",
3170            "Sans Semi-Bold Condensed 12",
3171            "Sans semibold 12",
3172            "Sans SEMI-BOLD 12",
3173            "Sans Small-Caps Not-Rotated 12",
3174            "Sans Ultra-Heavy Ultra-Expanded Oblique 12",
3175            "Sans 12 @wght=400",
3176            "Sans Bold @wght=600,wdth=80",
3177            "Sans, Bold 12",
3178            "Sans ,Mono, 12",
3179            "Sans 300 12",
3180            "Bold 12",
3181            "Italic",
3182            "12",
3183            "Noto Sans CJK JP Regular 10",
3184            "Sans  Bold   12  ",
3185            "Sans Italic 12px",
3186            "DejaVu Sans Mono Book",
3187            "Sans 0",
3188            "Sans 12.",
3189            "Sans .5",
3190            "Sans 1e3",
3191            "Sans -12",
3192            "Sans 12pt",
3193            "Sans inf",
3194            "Sans nan",
3195            "Sans +12",
3196            "Sans 1.5e1px",
3197            "Normal",
3198            "Sans Normal 12",
3199            "Sans@wght=400",
3200            "Sans 12 @wght=400 extra",
3201            "",
3202        ];
3203        for raw in directives {
3204            let pango: Vec<String> = pango::FontDescription::from_string(raw)
3205                .family()
3206                .map(|families| {
3207                    families
3208                        .split(',')
3209                        .map(|f| f.trim().to_string())
3210                        .filter(|f| !f.is_empty())
3211                        .collect()
3212                })
3213                .unwrap_or_default();
3214            assert_eq!(parse_font_directive(raw), pango, "{raw:?}");
3215        }
3216    }
3217
3218    #[test]
3219    fn pick_bar_ignores_bars_not_running_i3status_rs() {
3220        // A second bar running something else is not ours: its font must
3221        // neither be picked nor trigger the "different fonts" note.
3222        let bars = [
3223            bar("bar-0", "pango:Other 10", "i3blocks"),
3224            bar("bar-1", "pango:Ours 12", "i3status-rs ~/config.toml"),
3225        ];
3226        assert_eq!(pick_bar(&bars), (1, None));
3227    }
3228
3229    #[test]
3230    fn pick_bar_does_not_match_plain_i3status() {
3231        // The binary is always `i3status-rs`; a bar running i3status is
3232        // not a candidate, so with no i3status-rs bar the first one is used.
3233        let bars = [
3234            bar("bar-0", "pango:A 10", "i3blocks"),
3235            bar("bar-1", "pango:B 10", "i3status"),
3236        ];
3237        assert_eq!(pick_bar(&bars).0, 0);
3238    }
3239
3240    #[test]
3241    fn pick_bar_notes_disagreeing_i3status_rs_bars() {
3242        let bars = [
3243            bar("bar-0", "pango:A 10", "i3status-rs top.toml"),
3244            bar("bar-1", "pango:B 10", "i3status-rs bottom.toml"),
3245        ];
3246        let (chosen, note) = pick_bar(&bars);
3247        assert_eq!(chosen, 0);
3248        assert!(note.unwrap().contains("bar-1"));
3249    }
3250
3251    /// The contract-based analysis of block `index` in `config`.
3252    fn contract(config: &str, index: usize) -> PlanAnalysis {
3253        let config: Config = toml::from_str(config).unwrap();
3254        let plan = config.blocks[index].config.plan().expect("prepare failed");
3255        analyze_plan(&plan)
3256    }
3257
3258    #[test]
3259    fn contract_declared_icons_all_count_as_in_use() {
3260        // No reachability claims: every declared icon counts as in use by
3261        // the block, whichever formats the user configured. Unused
3262        // declarations are harmless (never problems).
3263        let analysis = contract(
3264            r#"
3265            [[block]]
3266            block = "kdeconnect"
3267            format = " $icon "
3268            disconnected_format = " disconnected "
3269            missing_format = " missing "
3270            "#,
3271            0,
3272        );
3273        assert!(analysis.required.contains("phone"));
3274        assert!(analysis.required.contains("phone_disconnected"));
3275    }
3276
3277    #[test]
3278    fn contract_icons_are_driver_scoped() {
3279        // The default nordvpn driver has no connecting state, so
3280        // net_wireless is not declared at all.
3281        let analysis = contract("[[block]]\nblock = \"vpn\"", 0);
3282        for icon in ["net_vpn", "net_wired", "net_down"] {
3283            assert!(analysis.required.contains(icon), "{icon}");
3284        }
3285        assert!(!analysis.required.contains("net_wireless"));
3286
3287        let analysis = contract("[[block]]\nblock = \"vpn\"\ndriver = \"mullvad\"", 0);
3288        assert!(analysis.required.contains("net_wireless"));
3289    }
3290
3291    #[test]
3292    fn contract_configuration_derived_names() {
3293        let analysis = contract(
3294            r#"
3295            [[block]]
3296            block = "toggle"
3297            format = " $icon "
3298            command_on = ""
3299            command_off = ""
3300            command_state = ""
3301            icon_on = "my_enabled_icon"
3302            "#,
3303            0,
3304        );
3305        assert!(analysis.required.contains("my_enabled_icon"));
3306        assert!(analysis.required.contains("toggle_off"));
3307        assert!(!analysis.required.contains("toggle_on"));
3308    }
3309
3310    #[test]
3311    fn contract_open_capability_follows_the_declaration() {
3312        // A plain-text custom command cannot set icons at all; with JSON
3313        // the source is open regardless of the configured formats (doctor
3314        // makes no reachability claims).
3315        let analysis = contract("[[block]]\nblock = \"custom\"\ncommand = \"true\"", 0);
3316        assert!(!analysis.open);
3317
3318        let analysis = contract(
3319            "[[block]]\nblock = \"custom\"\ncommand = \"true\"\njson = true",
3320            0,
3321        );
3322        assert!(analysis.open);
3323    }
3324
3325    #[test]
3326    fn contract_direct_icon_tokens_are_collected() {
3327        let analysis = contract(
3328            "[[block]]\nblock = \"vpn\"\nformat_connected = \" ^icon_net_down $country \"",
3329            0,
3330        );
3331        assert!(analysis.direct.contains("net_down"));
3332        assert!(analysis.required.contains("net_down"));
3333    }
3334
3335    /// The error-widget analysis of block `index` in `config`.
3336    fn error_analysis(config: &str, index: usize) -> PlanAnalysis {
3337        let config: Config = toml::from_str(config).unwrap();
3338        let entry = &config.blocks[index];
3339        analyze_plan(
3340            &crate::block_plan::error_plan(
3341                entry
3342                    .common
3343                    .error_format
3344                    .with_default_config(&config.error_format),
3345                entry
3346                    .common
3347                    .error_fullscreen_format
3348                    .with_default_config(&config.error_fullscreen_format),
3349                entry.common.max_retries.is_some(),
3350            )
3351            .unwrap(),
3352        )
3353    }
3354
3355    #[test]
3356    fn empty_icon_names_are_runtime_noops() {
3357        // The runtime renders an empty icon name as empty output, so it is
3358        // never a requirement.
3359        let analysis = contract(
3360            r#"
3361            [[block]]
3362            block = "toggle"
3363            format = " $icon "
3364            command_on = ""
3365            command_off = ""
3366            command_state = ""
3367            icon_on = ""
3368            icon_off = ""
3369            "#,
3370            0,
3371        );
3372        assert!(analysis.required.is_empty());
3373    }
3374
3375    #[test]
3376    fn refresh_requires_a_retry_limit() {
3377        // Without max_retries the block retries forever and the restart
3378        // button (and its refresh icon) can never appear.
3379        let analysis = error_analysis("[[block]]\nblock = \"cpu\"", 0);
3380        assert!(!analysis.required.contains("refresh"));
3381
3382        let analysis = error_analysis("[[block]]\nblock = \"cpu\"\nmax_retries = 5", 0);
3383        assert!(analysis.required.contains("refresh"));
3384    }
3385
3386    #[test]
3387    fn error_formats_without_restart_icon_do_not_require_refresh() {
3388        let analysis = error_analysis(
3389            r#"
3390            [[block]]
3391            block = "cpu"
3392            error_format = " $short_error_message "
3393            error_fullscreen_format = " $full_error_message "
3394            "#,
3395            0,
3396        );
3397        assert!(!analysis.required.contains("refresh"));
3398    }
3399
3400    #[test]
3401    fn global_error_format_applies_to_blocks_without_overrides() {
3402        let analysis = error_analysis(
3403            "error_format = \" $short_error_message \"\nerror_fullscreen_format = \" e \"\n[[block]]\nblock = \"cpu\"",
3404            0,
3405        );
3406        assert!(!analysis.required.contains("refresh"));
3407    }
3408
3409    #[test]
3410    fn font_directive_parsing() {
3411        assert_eq!(
3412            parse_font_directive("pango:DejaVu Sans Mono, Font Awesome 6 Free 12"),
3413            ["DejaVu Sans Mono", "Font Awesome 6 Free"]
3414        );
3415        assert_eq!(
3416            parse_font_directive("DejaVu Sans Mono 13.5"),
3417            ["DejaVu Sans Mono"]
3418        );
3419        // Pango style options are not part of the family name
3420        assert_eq!(
3421            parse_font_directive("pango:DejaVu Sans Mono Bold 10"),
3422            ["DejaVu Sans Mono"]
3423        );
3424        assert_eq!(
3425            parse_font_directive("Liberation Mono Bold Italic 11"),
3426            ["Liberation Mono"]
3427        );
3428        assert_eq!(
3429            parse_font_directive("Terminus (TTF) 16px"),
3430            ["Terminus (TTF)"]
3431        );
3432        assert_eq!(
3433            parse_font_directive("monospace,Font Awesome 5 Free"),
3434            ["monospace", "Font Awesome 5 Free"]
3435        );
3436        assert_eq!(parse_font_directive(""), Vec::<String>::new());
3437        assert_eq!(parse_font_directive("pango:"), Vec::<String>::new());
3438    }
3439
3440    #[test]
3441    fn font_directive_parsing_matches_pango_family_boundaries() {
3442        // These are the families returned by
3443        // pango_font_description_get_family after parsing each description;
3444        // Doctor must model the renderer, not font-file naming conventions.
3445        assert_eq!(
3446            parse_font_directive("pango:DejaVu Sans Condensed 11"),
3447            ["DejaVu Sans"]
3448        );
3449        assert_eq!(parse_font_directive("pango:Arial Black 12"), ["Arial"]);
3450        assert_eq!(
3451            parse_font_directive("pango:DejaVu Sans Mono Light 11"),
3452            ["DejaVu Sans Mono"]
3453        );
3454        assert_eq!(
3455            parse_font_directive("pango:Source Serif 4 12"),
3456            ["Source Serif 4"]
3457        );
3458        assert_eq!(parse_font_directive("pango:3270 12"), ["3270"]);
3459        assert_eq!(
3460            parse_font_directive("pango:Noto Sans SmallCaps 12"),
3461            ["Noto Sans"]
3462        );
3463        assert_eq!(
3464            parse_font_directive("pango:Cantarell Bold 11 @wght=200"),
3465            ["Cantarell"]
3466        );
3467        assert_eq!(
3468            parse_font_directive("pango:Cantarell 11 @wght=200,wdth=90"),
3469            ["Cantarell"]
3470        );
3471    }
3472
3473    #[test]
3474    fn font_directive_modifiers_apply_after_the_whole_fallback_list() {
3475        // Pango parses only the final `12` as the description's size.  The
3476        // `4` belongs to the first family name, not to a per-family size.
3477        assert_eq!(
3478            parse_font_directive("pango:Source Serif 4, Noto Sans 12"),
3479            ["Source Serif 4", "Noto Sans"]
3480        );
3481    }
3482
3483    #[test]
3484    fn font_directive_at_sign_is_not_always_a_variations_suffix() {
3485        // Pango recognizes variations at a trailing, whitespace-delimited
3486        // `@`; an at-sign embedded in a family name remains literal.
3487        assert_eq!(
3488            parse_font_directive("pango:Foo@Bar, Noto Sans 12"),
3489            ["Foo@Bar", "Noto Sans"]
3490        );
3491    }
3492
3493    #[test]
3494    fn font_directive_does_not_accept_non_pango_sizes() {
3495        assert_eq!(parse_font_directive("pango:Noto Sans -1"), ["Noto Sans -1"]);
3496    }
3497
3498    #[test]
3499    fn flag_cells_point_at_the_terminal_footnote() {
3500        let cell = flag_cell("US", "\u{1f1fa}\u{1f1f8}");
3501        assert_eq!(cell, "\u{1f1fa}\u{1f1f8} (US country flag) *");
3502        // The marker is only useful if the footnote explaining it exists.
3503        assert!(FLAG_FOOTNOTE.starts_with('*'));
3504        assert!(FLAG_FOOTNOTE.contains("terminal") && FLAG_FOOTNOTE.contains("bar"));
3505    }
3506
3507    #[test]
3508    fn codepoint_formatting() {
3509        assert_eq!(codepoints("BAT"), "-");
3510        assert_eq!(codepoints("\u{f244}"), "U+F244");
3511        assert_eq!(codepoints("🍅"), "U+1F345");
3512    }
3513
3514    #[test]
3515    fn table_column_width_uses_terminal_display_width() {
3516        assert_eq!(column_width("", ["é"].into_iter()), 1);
3517        assert_eq!(column_width("", ["界"].into_iter()), 2);
3518    }
3519
3520    #[test]
3521    fn display_padding_handles_wide_characters() {
3522        for text in ["界", "ab", "a"] {
3523            let padded = pad_right(text, 2);
3524            assert_eq!(UnicodeWidthStr::width(padded.as_str()), 2);
3525        }
3526
3527        assert_eq!(pad_right("界", 2), "界");
3528        assert_eq!(pad_right("a", 2), "a ");
3529    }
3530
3531    #[test]
3532    fn glyph_checks_skip_non_rendering_format_characters() {
3533        assert!(!is_drawn('\u{200d}'), "a zero-width joiner is not a glyph");
3534        assert!(
3535            !is_drawn('\u{fe0f}'),
3536            "an emoji variation selector is not a glyph"
3537        );
3538        assert!(
3539            !is_drawn('\u{fff9}'),
3540            "an interlinear annotation anchor is not a glyph"
3541        );
3542        assert!(
3543            !is_drawn('\u{206a}'),
3544            "an inhibit-symmetric-swapping control is not a glyph"
3545        );
3546    }
3547
3548    #[test]
3549    fn glyph_checks_include_zero_advance_combining_marks() {
3550        assert!(
3551            is_drawn('\u{0301}'),
3552            "a combining acute accent has a visible glyph despite having zero advance width"
3553        );
3554    }
3555
3556    #[test]
3557    fn glyph_checks_skip_spacing_default_ignorables() {
3558        assert!(
3559            !is_drawn('\u{115f}'),
3560            "a Hangul choseong filler is invisible despite occupying terminal columns"
3561        );
3562    }
3563
3564    #[test]
3565    fn terminal_escaping_preserves_visible_combining_marks() {
3566        assert_eq!(escape_control("e\u{0301}"), "e\u{0301}");
3567    }
3568
3569    #[test]
3570    fn terminal_escaping_makes_all_invisible_characters_visible() {
3571        let escaped = escape_control("safe\u{1160}text");
3572        assert!(!escaped.contains('\u{1160}'));
3573        assert_eq!(escaped, "safe\\u{1160}text");
3574    }
3575
3576    #[test]
3577    fn terminal_escaping_makes_bidi_controls_visible() {
3578        let escaped = escape_control("safe\u{202e}spoofed");
3579        assert!(!escaped.contains('\u{202e}'));
3580        assert_eq!(escaped, "safe\\u{202e}spoofed");
3581    }
3582
3583    #[test]
3584    fn generic_families_are_not_missing_fonts() {
3585        assert!(is_generic_family("monospace"));
3586        assert!(is_generic_family("Sans-Serif"));
3587        assert!(!is_generic_family("DejaVu Sans Mono"));
3588        assert!(!is_generic_family("Font Awesome 6 Free"));
3589    }
3590
3591    #[test]
3592    fn per_block_overrides_are_extracted() {
3593        let raw: toml::Value = toml::from_str(
3594            r#"
3595            [[block]]
3596            block = "time"
3597            icons_overrides = { time = "CUSTOM" }
3598
3599            [[block]]
3600            block = "cpu"
3601            "#,
3602        )
3603        .unwrap();
3604        let mut problems = Vec::new();
3605        let overrides = raw_block_overrides(&raw, &mut problems, &mut Vec::new());
3606        assert!(problems.is_empty());
3607        assert_eq!(overrides.len(), 1);
3608        assert_eq!(overrides[0].0, 0);
3609        assert!(matches!(&overrides[0].1["time"], Icon::Single(s) if s == "CUSTOM"));
3610    }
3611
3612    #[test]
3613    fn instance_labels_disambiguate_duplicates() {
3614        let names = ["time".to_string(), "cpu".to_string(), "time".to_string()];
3615        assert_eq!(instance_labels(&names), ["time#1", "cpu", "time#3"]);
3616        let unique = ["time".to_string(), "cpu".to_string()];
3617        assert_eq!(instance_labels(&unique), ["time", "cpu"]);
3618    }
3619
3620    #[test]
3621    fn fix_suggestions() {
3622        assert!(
3623            suggest_fix(
3624                "taskwarrior",
3625                "failed to run taskwarrior. Cause: No such file or directory"
3626            )
3627            .unwrap()
3628            .contains("Install")
3629        );
3630        assert!(
3631            suggest_fix("kdeconnect", "Failed to open DBus session connection")
3632                .unwrap()
3633                .contains("D-Bus")
3634        );
3635        assert!(suggest_fix("time", "something exotic").is_none());
3636    }
3637
3638    #[test]
3639    fn publication_time_contract_failures_are_reported_as_internal_bugs() {
3640        // CommonApi::set_widget checks the contract before sending the
3641        // widget, so a violation reaches the worker as BlockError rather
3642        // than render_widget's contract_violations field.
3643        let report = BlockReport {
3644            index: 0,
3645            name: "test".into(),
3646            verdict: LiveVerdict::BlockError(
3647                "block contract bug: icon 'bad' is not declared".into(),
3648            ),
3649            flags: Vec::new(),
3650        };
3651        let mut problems = Vec::new();
3652        print_block_report(
3653            &report,
3654            1,
3655            4,
3656            1,
3657            &Style { red: "", reset: "" },
3658            &mut problems,
3659            &mut BTreeMap::new(),
3660            &HashSet::new(),
3661            "test",
3662        );
3663
3664        assert_eq!(problems.len(), 1);
3665        assert!(
3666            problems[0].diagnosis.contains("bug in i3status-rs"),
3667            "contract failures must not be presented as user configuration problems: {}",
3668            problems[0].diagnosis
3669        );
3670        assert!(
3671            problems[0]
3672                .fix
3673                .as_deref()
3674                .is_some_and(|fix| fix.contains("Report it")),
3675            "contract failures should tell the user to report the internal bug"
3676        );
3677    }
3678}