ctb_io_environment/
detection.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Platform identity, capability, and display/terminal detection.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::collections::HashSet;
30use std::env;
31use std::io::IsTerminal;
32use std::path::Path;
33
34use ctb_formats_utilities::format_id::{FormatCategory, FormatId};
35use serde::{Deserialize, Serialize};
36
37/// Operating system, kernel, libc, userspace, and architecture identity.
38///
39/// The format identifiers comprising this identity are stored losslessly
40/// within the `supported_formats` field of [`crate::environment::EnvDescription`]
41/// (along with its `kernel_version`), and this structured representation can be
42/// retrieved via the [`crate::environment::EnvDescription::identity`] accessor.
43#[derive(
44    Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
45)]
46pub struct EnvironmentIdentity {
47    /// Authoritative kernel format if detected (e.g. `FormatId::Linux`,
48    /// `FormatId::Xnu`, `FormatId::WinNtKernel`, `FormatId::Wsl2`).
49    pub kernel: Option<FormatId>,
50    /// Kernel release / version string if available (e.g. "6.12.11-amd64").
51    pub kernel_version: Option<String>,
52    /// Authoritative C standard library if detected (e.g. `FormatId::Gnu`,
53    /// `FormatId::MuslLibc`, `FormatId::Darwin`, `FormatId::BsdLibc`).
54    pub libc: Option<FormatId>,
55    /// Active userspace environments, utilities, and subsystems.
56    pub userspace: Vec<FormatId>,
57    /// Primary operating system format if detected (e.g. `FormatId::GnuLinux`,
58    /// `FormatId::MacOsDarwin`, `FormatId::Windows`).
59    pub os: Option<FormatId>,
60    /// Operating system family ancestor formats (e.g. `[FormatId::Unix]`).
61    pub os_families: Vec<FormatId>,
62    /// Machine architecture format if detected (e.g. `FormatId::amd64`,
63    /// `FormatId::arm64`).
64    pub architecture: Option<FormatId>,
65}
66
67/// Display, terminal, and interactive rendering capabilities.
68///
69/// The format identifiers comprising these capabilities are stored losslessly
70/// within the `supported_formats` field of [`crate::environment::EnvDescription`],
71/// and this structured representation can be retrieved via the
72/// [`crate::environment::EnvDescription::capabilities`] accessor.
73#[derive(
74    Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
75)]
76pub struct EnvironmentCapabilities {
77    /// Active device capabilities (e.g. `[FormatId::RasterDisplay,
78    /// FormatId::Videoterminal, FormatId::WebUi]`).
79    pub device_caps: Vec<FormatId>,
80    /// Supported render modes (e.g. `[FormatId::RenderModeInteractive,
81    /// FormatId::RenderModeImmediate]`).
82    pub render_modes: Vec<FormatId>,
83    /// Videoterminal protocol capabilities (e.g. `[FormatId::Vt100,
84    /// FormatId::TerminalCanEdit, FormatId::TerminalColors24bit]`).
85    pub terminal_caps: Vec<FormatId>,
86    /// Active display server protocol if any (e.g. `FormatId::WaylandDisplay`,
87    /// `FormatId::X11Display`, `FormatId::QuartzDisplay`,
88    /// `FormatId::Win32Display`, or `FormatId::HeadlessDisplay`).
89    pub display_server: Option<FormatId>,
90    /// Standard input is connected to an interactive terminal.
91    pub is_stdin_terminal: bool,
92    /// Standard output is connected to an interactive terminal.
93    pub is_stdout_terminal: bool,
94    /// Standard error is connected to an interactive terminal.
95    pub is_stderr_terminal: bool,
96}
97
98/// Detect the target machine architecture as an authoritative [`FormatId`].
99#[must_use]
100pub fn detect_architecture() -> Option<FormatId> {
101    if cfg!(target_arch = "x86_64") {
102        Some(FormatId::amd64)
103    } else if cfg!(target_arch = "aarch64") {
104        Some(FormatId::arm64)
105    } else if cfg!(target_arch = "x86") {
106        Some(FormatId::x86)
107    } else if cfg!(target_arch = "arm") {
108        Some(FormatId::arm)
109    } else {
110        None
111    }
112}
113
114fn probe_linux_procfs(detected: &mut Vec<FormatId>) -> Option<String> {
115    let mut kernel_version = None;
116    if let Ok(release) = std::fs::read_to_string("/proc/sys/kernel/osrelease") {
117        let trimmed = release.trim().to_string();
118        if !trimmed.is_empty() {
119            kernel_version = Some(trimmed);
120        }
121    }
122
123    if let Ok(version_str) = std::fs::read_to_string("/proc/version") {
124        let v = version_str.to_ascii_lowercase();
125        if v.contains("wsl2") {
126            detected.push(FormatId::Wsl2);
127            detected.push(FormatId::Wsl);
128            detected.push(FormatId::Linux);
129        } else if v.contains("microsoft") || v.contains("wsl") {
130            detected.push(FormatId::Wsl);
131            detected.push(FormatId::Linux);
132        } else if v.contains("linux") {
133            detected.push(FormatId::Linux);
134        }
135    }
136
137    kernel_version
138}
139
140/// Detect the host execution identity.
141#[expect(
142    clippy::too_many_lines,
143    reason = "Comprehensive platform-specific target identity branching"
144)]
145#[must_use]
146pub fn detect_identity() -> EnvironmentIdentity {
147    let mut detected = Vec::new();
148
149    // 1. Architecture detection
150    let architecture = detect_architecture();
151    if let Some(arch) = architecture {
152        detected.push(arch);
153    }
154
155    // 2. Kernel & OS probing
156    let kernel_version = if ctb_utilities::environment::is_wine() {
157        None
158    } else {
159        probe_linux_procfs(&mut detected)
160    };
161
162    if cfg!(target_os = "android") {
163        detected.push(FormatId::Android);
164    } else if cfg!(target_os = "linux") {
165        detected.push(FormatId::GnuLinux);
166    } else if cfg!(target_os = "macos") {
167        detected.push(FormatId::MacOsDarwin);
168    } else if cfg!(target_os = "ios") {
169        detected.push(FormatId::AppleIos);
170    } else if cfg!(target_os = "watchos") {
171        detected.push(FormatId::WatchOs);
172    } else if cfg!(target_os = "tvos") {
173        detected.push(FormatId::TvOs);
174    } else if cfg!(target_os = "visionos") {
175        detected.push(FormatId::VisionOs);
176    } else if cfg!(target_os = "windows") {
177        detected.push(FormatId::WinNt);
178    } else if cfg!(target_os = "freebsd") {
179        detected.push(FormatId::FreeBsd);
180    } else if cfg!(target_os = "openbsd") {
181        detected.push(FormatId::OpenBsd);
182    } else if cfg!(target_os = "netbsd") {
183        detected.push(FormatId::NetBsd);
184    } else if cfg!(target_os = "dragonfly") {
185        detected.push(FormatId::DragonFlyBsd);
186    } else if cfg!(target_os = "hurd") || Path::new("/servers/socket").exists()
187    {
188        detected.push(FormatId::Hurd);
189    } else if super::looks_like_nextstep_or_openstep() {
190        detected.push(FormatId::NextStep);
191    } else if cfg!(unix) {
192        detected.push(FormatId::Unix);
193    }
194
195    // 3. Libc overrides (when distinct from OS default implied libc)
196    if cfg!(target_env = "musl") {
197        detected.push(FormatId::MuslLibc);
198    }
199
200    // 4. Userspace environments, subsystems, and package managers
201    // (Checked across platforms without assumptions)
202    if super::looks_like_gnustep() {
203        detected.push(FormatId::GnuStep);
204    }
205    if super::looks_like_nextstep_or_openstep() {
206        detected.push(FormatId::NextStep);
207    }
208    if Path::new("/bin/busybox").exists()
209        || Path::new("/usr/bin/busybox").exists()
210    {
211        detected.push(FormatId::BusyBoxUtilities);
212    }
213    if env::var_os("WINDIR").is_some() || env::var_os("SYSTEMROOT").is_some() {
214        detected.push(FormatId::Win32Subsystem);
215    }
216    if ctb_utilities::environment::is_wine() {
217        detected.push(FormatId::Wine);
218    }
219    // Note: Detecting a package manager on the host system indicates its presence in
220    // the environment, but does not guarantee that ctoolbox itself was installed
221    // using that package manager.
222    if env::var_os("HOMEBREW_PREFIX").is_some()
223        || Path::new("/opt/homebrew").exists()
224        || Path::new("/usr/local/Homebrew").exists()
225        || Path::new("/home/linuxbrew/.linuxbrew").exists()
226    {
227        detected.push(FormatId::Homebrew);
228    }
229    if env::var_os("MACPORTS_PREFIX").is_some()
230        || Path::new("/opt/local/bin/port").exists()
231    {
232        detected.push(FormatId::MacPorts);
233    }
234    if env::var_os("NIX_PROFILES").is_some() || Path::new("/nix/store").exists()
235    {
236        detected.push(FormatId::Nix);
237    }
238    if env::var_os("GUIX_ENVIRONMENT").is_some()
239        || Path::new("/gnu/store").exists()
240    {
241        detected.push(FormatId::Guix);
242    }
243
244    // Expand implied formats from declarative @implies(...) directives
245    let initial = detected.clone();
246    for id in initial {
247        for &implied in id.implies() {
248            detected.push(implied);
249        }
250    }
251
252    // Deduplicate detected formats
253    let mut seen = HashSet::new();
254    detected.retain(|id| seen.insert(*id));
255
256    // Derive EnvironmentIdentity from detected formats
257    let kernel = if detected.contains(&FormatId::Wsl2) {
258        Some(FormatId::Wsl2)
259    } else if detected.contains(&FormatId::Wsl) {
260        Some(FormatId::Wsl)
261    } else if detected.contains(&FormatId::Linux) {
262        Some(FormatId::Linux)
263    } else if detected.contains(&FormatId::Xnu) {
264        Some(FormatId::Xnu)
265    } else if detected.contains(&FormatId::WinNtKernel) {
266        Some(FormatId::WinNtKernel)
267    } else if detected.contains(&FormatId::BsdKernel) {
268        Some(FormatId::BsdKernel)
269    } else if detected.contains(&FormatId::Hurd) {
270        Some(FormatId::Hurd)
271    } else if detected.contains(&FormatId::GnuMach) {
272        Some(FormatId::GnuMach)
273    } else if detected.contains(&FormatId::Mach) {
274        Some(FormatId::Mach)
275    } else {
276        detected
277            .iter()
278            .copied()
279            .find(|f| f.category() == FormatCategory::Kernel)
280    };
281
282    let libc = detected
283        .iter()
284        .copied()
285        .find(|f| f.category() == FormatCategory::Libc);
286
287    let os = if detected.contains(&FormatId::MacOsDarwin) {
288        Some(FormatId::MacOsDarwin)
289    } else if detected.contains(&FormatId::AppleIos) {
290        Some(FormatId::AppleIos)
291    } else if detected.contains(&FormatId::WatchOs) {
292        Some(FormatId::WatchOs)
293    } else if detected.contains(&FormatId::TvOs) {
294        Some(FormatId::TvOs)
295    } else if detected.contains(&FormatId::VisionOs) {
296        Some(FormatId::VisionOs)
297    } else if detected.contains(&FormatId::WinNt) {
298        Some(FormatId::WinNt)
299    } else if detected.contains(&FormatId::Windows) {
300        Some(FormatId::Windows)
301    } else if detected.contains(&FormatId::FreeBsd) {
302        Some(FormatId::FreeBsd)
303    } else if detected.contains(&FormatId::OpenBsd) {
304        Some(FormatId::OpenBsd)
305    } else if detected.contains(&FormatId::NetBsd) {
306        Some(FormatId::NetBsd)
307    } else if detected.contains(&FormatId::DragonFlyBsd) {
308        Some(FormatId::DragonFlyBsd)
309    } else if detected.contains(&FormatId::Android) {
310        Some(FormatId::Android)
311    } else if detected.contains(&FormatId::GnuLinux)
312        || detected.contains(&FormatId::Linux)
313    {
314        Some(FormatId::GnuLinux)
315    } else if detected.contains(&FormatId::NextStep) {
316        Some(FormatId::NextStep)
317    } else {
318        detected.iter().copied().find(|f| {
319            f.category() == FormatCategory::Os
320                && !matches!(
321                    f,
322                    FormatId::Unix
323                        | FormatId::Windows
324                        | FormatId::MacOs
325                        | FormatId::WinClassic
326                )
327        })
328    };
329
330    let os_families: Vec<FormatId> = detected
331        .iter()
332        .copied()
333        .filter(|f| {
334            matches!(
335                f,
336                FormatId::Unix
337                    | FormatId::Windows
338                    | FormatId::MacOs
339                    | FormatId::WinClassic
340                    | FormatId::Linux
341                    | FormatId::Darwin
342                    | FormatId::FreeBsd
343                    | FormatId::OpenBsd
344                    | FormatId::NetBsd
345                    | FormatId::DragonFlyBsd
346            )
347        })
348        .collect();
349
350    let userspace: Vec<FormatId> = detected
351        .iter()
352        .copied()
353        .filter(|f| {
354            matches!(
355                f.category(),
356                FormatCategory::Userspace
357                    | FormatCategory::UserspaceUtilities
358                    | FormatCategory::UserspaceLibraries
359                    | FormatCategory::Packagemgr
360            )
361        })
362        .collect();
363
364    EnvironmentIdentity {
365        kernel,
366        kernel_version,
367        libc,
368        userspace,
369        os,
370        os_families,
371        architecture,
372    }
373}
374
375/// Detect the active display protocol and windowing context.
376#[must_use]
377pub fn detect_display_server() -> Option<FormatId> {
378    if env::var_os("WAYLAND_DISPLAY").is_some() {
379        Some(FormatId::WaylandDisplay)
380    } else if env::var_os("DISPLAY").is_some() {
381        Some(FormatId::X11Display)
382    } else if cfg!(target_os = "macos")
383        && env::var_os("SSH_CONNECTION").is_none()
384    {
385        Some(FormatId::QuartzDisplay)
386    } else if cfg!(target_os = "windows") {
387        Some(FormatId::Win32Display)
388    } else {
389        Some(FormatId::HeadlessDisplay)
390    }
391}
392
393/// Detect active device capabilities, display server, and terminal features.
394#[must_use]
395pub fn detect_capabilities() -> EnvironmentCapabilities {
396    let is_stdin_terminal = std::io::stdin().is_terminal();
397    let is_stdout_terminal = std::io::stdout().is_terminal();
398    let is_stderr_terminal = std::io::stderr().is_terminal();
399
400    let display_server = detect_display_server();
401
402    let mut device_caps = Vec::new();
403    if !matches!(display_server, None | Some(FormatId::HeadlessDisplay)) {
404        device_caps.push(FormatId::RasterDisplay);
405        device_caps.push(FormatId::RasterColors24bit);
406    }
407    if super::is_webui() {
408        device_caps.push(FormatId::WebUi);
409    }
410
411    // Reason for fallback: unset TERM defaults to empty string baseline
412    let term = env::var("TERM").unwrap_or_default();
413    let (mut terminal_caps, term_device_caps) =
414        detect_terminal_capabilities_for(
415            &term,
416            is_stdout_terminal,
417            is_stdin_terminal,
418            is_stderr_terminal,
419        );
420    device_caps.extend(term_device_caps);
421
422    // Reason for fallback: unset COLORTERM defaults to empty string baseline
423    let colorterm = env::var("COLORTERM")
424        .unwrap_or_default()
425        .to_ascii_lowercase();
426    if is_stdout_terminal
427        && terminal_caps.contains(&FormatId::Videoterminal)
428        && (colorterm == "truecolor" || colorterm == "24bit")
429        && !terminal_caps.contains(&FormatId::TerminalColors24bit)
430    {
431        terminal_caps.push(FormatId::TerminalColors24bit);
432    }
433
434    let mut render_modes = Vec::new();
435    if is_stdout_terminal && is_stdin_terminal {
436        render_modes.push(FormatId::RenderModeInteractive);
437        render_modes.push(FormatId::RenderModeImmediate);
438    } else {
439        render_modes.push(FormatId::RenderModeImmediate);
440    }
441
442    EnvironmentCapabilities {
443        device_caps,
444        render_modes,
445        terminal_caps,
446        display_server,
447        is_stdin_terminal,
448        is_stdout_terminal,
449        is_stderr_terminal,
450    }
451}
452
453/// Detect terminal capabilities and associated device capabilities for a
454/// specific terminal name and stdio terminal stream flags.
455#[must_use]
456pub fn detect_terminal_capabilities_for(
457    term: &str,
458    is_stdout_terminal: bool,
459    is_stdin_terminal: bool,
460    is_stderr_terminal: bool,
461) -> (Vec<FormatId>, Vec<FormatId>) {
462    let mut terminal_caps = Vec::new();
463    let mut device_caps = Vec::new();
464
465    if is_stdin_terminal {
466        terminal_caps.push(FormatId::IsStdinTerminal);
467    }
468    if is_stdout_terminal {
469        terminal_caps.push(FormatId::IsStdoutTerminal);
470    }
471    if is_stderr_terminal {
472        terminal_caps.push(FormatId::IsStderrTerminal);
473    }
474
475    if is_stdout_terminal {
476        let term_info = if term.is_empty() {
477            None
478        } else {
479            Terminfo::from_name(term)
480        };
481
482        // Reason for fallback: unconfirmed terminals lacking cursor addressing capability default to teleprinter mode
483        let is_teleprinter = term == "dumb"
484            || term_info
485                .as_ref()
486                .is_none_or(|info| !info.can_cursor_address());
487
488        if is_teleprinter {
489            device_caps.push(FormatId::Teleprinter);
490            terminal_caps.push(FormatId::Teleprinter);
491            terminal_caps.push(FormatId::LineModeTerminal);
492            terminal_caps.push(FormatId::TerminalColors1bit);
493        } else {
494            device_caps.push(FormatId::Videoterminal);
495            terminal_caps.push(FormatId::Videoterminal);
496
497            // Reason for fallback: unconfirmed cursor addressing capability defaults to false to avoid sending unsupported escape sequences
498            let can_edit_past_lines =
499                term_info.as_ref().is_some_and(Terminfo::can_cursor_address);
500            if can_edit_past_lines {
501                terminal_caps.push(FormatId::TerminalCanEditPastLines);
502            }
503
504            // Reason for fallback: unconfirmed line editing capability defaults to false to avoid sending unsupported escape sequences
505            let can_edit =
506                term_info.as_ref().is_some_and(Terminfo::can_edit_line);
507            if can_edit {
508                terminal_caps.push(FormatId::TerminalCanEdit);
509            }
510
511            // Reason for fallback: unconfirmed VT100 compatibility defaults to false to avoid sending unsupported control sequences
512            let is_vt100 = term_info
513                .as_ref()
514                .is_some_and(Terminfo::is_vt100_compatible);
515            if is_vt100 {
516                terminal_caps.push(FormatId::Vt100);
517            }
518
519            // Note: User-facing CLI or pc_settings configuration may be added later.
520            // Reason for fallback: unconfirmed mouse reporting capability defaults to false to avoid sending unsupported escape sequences
521            let has_mouse = term_info.as_ref().is_some_and(Terminfo::has_mouse);
522            if has_mouse {
523                terminal_caps.push(FormatId::TerminalMouse);
524            }
525
526            // Reason for fallback: unconfirmed 24-bit color capability defaults to false to avoid emitting unhandled escape sequences
527            let is_truecolor =
528                term_info.as_ref().is_some_and(Terminfo::has_truecolor);
529
530            if is_truecolor {
531                terminal_caps.push(FormatId::TerminalColors24bit);
532            } else {
533                // Reason for fallback: unconfirmed color count defaults to 0 monochrome baseline to avoid printing unsupported color sequences
534                let max_colors =
535                    term_info.as_ref().map_or(0, Terminfo::max_colors);
536                if max_colors >= 256 {
537                    terminal_caps.push(FormatId::TerminalColors8bit);
538                } else if max_colors >= 8 {
539                    terminal_caps.push(FormatId::TerminalColors4bit);
540                } else {
541                    terminal_caps.push(FormatId::TerminalColors1bit);
542                }
543            }
544
545            let is_interactive = is_stdout_terminal && is_stdin_terminal;
546
547            if detect_sixel_support(term_info.as_ref(), is_interactive)
548                == Some(true)
549            {
550                terminal_caps.push(FormatId::TerminalSixelGraphics);
551                device_caps.push(FormatId::TerminalSixelGraphics);
552            }
553            if detect_kitty_support(term_info.as_ref(), is_interactive, term)
554                == Some(true)
555            {
556                terminal_caps.push(FormatId::TerminalKittyGraphics);
557                device_caps.push(FormatId::TerminalKittyGraphics);
558            }
559            if detect_iterm_support(term_info.as_ref(), is_interactive)
560                == Some(true)
561            {
562                terminal_caps.push(FormatId::TerminalIterm2Graphics);
563                device_caps.push(FormatId::TerminalIterm2Graphics);
564            }
565        }
566    }
567
568    (terminal_caps, device_caps)
569}
570
571fn parse_konsole_version(val: &str) -> Option<u64> {
572    let trimmed = val.trim();
573    if trimmed.is_empty() {
574        return None;
575    }
576    if trimmed.contains('.') {
577        let mut parts = trimmed.split('.');
578        let major: u64 = parts.next()?.parse().ok()?;
579        let minor: u64 = parts.next()?.parse().ok()?;
580        // Reason for fallback: omitted patch version in dotted string defaults to 0
581        let patch: u64 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
582        major
583            .checked_mul(10_000)?
584            .checked_add(minor.checked_mul(100)?)?
585            .checked_add(patch)
586    } else {
587        trimmed.parse::<u64>().ok()
588    }
589}
590
591/// Detect whether the terminal supports Sixel graphics.
592///
593/// First checks the terminfo database. If terminfo does not confirm or refute
594/// support (`None`), verifies that the session is interactive and supports
595/// Primary Device Attributes (DA1) queries according to terminfo before
596/// performing an in-band DA1 probe. Returns `None` if support is unknown.
597#[must_use]
598pub fn detect_sixel_support(
599    term_info: Option<&Terminfo>,
600    is_interactive: bool,
601) -> Option<bool> {
602    if let Some(info) = term_info {
603        if let Some(supported) = info.supports_sixel() {
604            return Some(supported);
605        }
606    }
607
608    let can_query_da1 = is_interactive
609        && !cfg!(test)
610        && std::io::stdin().is_terminal()
611        && std::io::stdout().is_terminal()
612        // Reason for fallback: absent terminfo cannot confirm DA1 query support
613        && term_info.is_some_and(Terminfo::supports_da1);
614
615    if can_query_da1 {
616        Some(viuer::is_sixel_supported())
617    } else {
618        None
619    }
620}
621
622/// Detect whether the terminal supports the Kitty graphics protocol.
623///
624/// Checks terminal capabilities, environment hints, and in-band APC
625/// querying via `viuer`. Returns `None` if support is unknown.
626#[must_use]
627pub fn detect_kitty_support(
628    term_info: Option<&Terminfo>,
629    is_interactive: bool,
630    term: &str,
631) -> Option<bool> {
632    // Reason for fallback: absent terminfo cannot refute video terminal capabilities
633    if term_info
634        .is_some_and(|info| !info.can_cursor_address() || info.name == "dumb")
635    {
636        return Some(false);
637    }
638
639    if env::var_os("KITTY_WINDOW_ID").is_some() || term == "xterm-kitty" {
640        return Some(true);
641    }
642
643    if let Ok(konsole_ver) = env::var("KONSOLE_VERSION") {
644        if let Some(ver) = parse_konsole_version(&konsole_ver) {
645            if ver >= 220400 {
646                return Some(true);
647            }
648        }
649    }
650
651    let can_query = is_interactive
652        && !cfg!(test)
653        && std::io::stdin().is_terminal()
654        && std::io::stdout().is_terminal()
655        // Reason for fallback: absent terminfo cannot confirm escape query support
656        && term_info.is_some_and(Terminfo::supports_da1);
657
658    if can_query {
659        match viuer::get_kitty_support() {
660            viuer::KittySupport::Local | viuer::KittySupport::Remote => {
661                Some(true)
662            }
663            viuer::KittySupport::None => Some(false),
664        }
665    } else {
666        None
667    }
668}
669
670/// Detect whether the terminal supports the iTerm2 graphics protocol.
671///
672/// Checks environment and terminal capabilities via `viuer`, ensuring
673/// older Konsole versions (prior to 22.04) return `false`.
674#[must_use]
675pub fn detect_iterm_support(
676    term_info: Option<&Terminfo>,
677    is_interactive: bool,
678) -> Option<bool> {
679    // Reason for fallback: absent terminfo cannot refute video terminal capabilities
680    if term_info
681        .is_some_and(|info| !info.can_cursor_address() || info.name == "dumb")
682    {
683        return Some(false);
684    }
685
686    if let Ok(konsole_ver) = env::var("KONSOLE_VERSION") {
687        if let Some(ver) = parse_konsole_version(&konsole_ver) {
688            if ver < 220400 {
689                return Some(false);
690            }
691        }
692    }
693
694    if viuer::is_iterm_supported() {
695        return Some(true);
696    }
697
698    let can_query = is_interactive
699        && !cfg!(test)
700        && std::io::stdin().is_terminal()
701        && std::io::stdout().is_terminal()
702        // Reason for fallback: absent terminfo cannot confirm escape query support
703        && term_info.is_some_and(Terminfo::supports_da1);
704
705    if can_query { Some(false) } else { None }
706}
707
708/// Collect and deduplicate all [`FormatId`] elements representing an
709/// environment.
710#[must_use]
711pub fn collect_all_format_ids(
712    ident: &EnvironmentIdentity,
713    caps: &EnvironmentCapabilities,
714) -> Vec<FormatId> {
715    let mut ids = Vec::new();
716    if let Some(kernel) = ident.kernel {
717        ids.push(kernel);
718    }
719    if let Some(libc) = ident.libc {
720        ids.push(libc);
721    }
722    for u in &ident.userspace {
723        ids.push(*u);
724    }
725    if let Some(os) = ident.os {
726        ids.push(os);
727    }
728    for fam in &ident.os_families {
729        ids.push(*fam);
730    }
731    if let Some(arch) = ident.architecture {
732        ids.push(arch);
733    }
734
735    if let Some(ds) = caps.display_server {
736        ids.push(ds);
737    }
738    for cap in &caps.device_caps {
739        ids.push(*cap);
740    }
741    for mode in &caps.render_modes {
742        ids.push(*mode);
743    }
744    for term in &caps.terminal_caps {
745        ids.push(*term);
746    }
747
748    if caps.is_stdin_terminal {
749        ids.push(FormatId::IsStdinTerminal);
750    }
751    if caps.is_stdout_terminal {
752        ids.push(FormatId::IsStdoutTerminal);
753    }
754    if caps.is_stderr_terminal {
755        ids.push(FormatId::IsStderrTerminal);
756    }
757
758    let mut seen = HashSet::new();
759    ids.retain(|id| seen.insert(*id));
760    ids
761}
762
763/// Check if an environment identity and capabilities set contains a format.
764#[must_use]
765pub fn check_has_format(
766    ident: &EnvironmentIdentity,
767    caps: &EnvironmentCapabilities,
768    format: FormatId,
769) -> bool {
770    if ident.kernel == Some(format)
771        || ident.libc == Some(format)
772        || ident.userspace.contains(&format)
773        || ident.os == Some(format)
774        || ident.os_families.contains(&format)
775        || ident.architecture == Some(format)
776    {
777        return true;
778    }
779    if caps.display_server == Some(format)
780        || caps.device_caps.contains(&format)
781        || caps.render_modes.contains(&format)
782        || caps.terminal_caps.contains(&format)
783    {
784        return true;
785    }
786    match format {
787        FormatId::IsStdinTerminal => caps.is_stdin_terminal,
788        FormatId::IsStdoutTerminal => caps.is_stdout_terminal,
789        FormatId::IsStderrTerminal => caps.is_stderr_terminal,
790        _ => false,
791    }
792}
793
794/// Decode [`EnvironmentIdentity`] and [`EnvironmentCapabilities`] from
795/// a slice of [`FormatId`] formats and an optional kernel version string,
796/// classifying each format by its declarative [`FormatCategory`].
797#[expect(
798    clippy::too_many_lines,
799    reason = "Comprehensive environment decoding across multiple format categories"
800)]
801#[must_use]
802pub fn decode_environment_from_formats(
803    formats: &[FormatId],
804    kernel_version: Option<String>,
805) -> (EnvironmentIdentity, EnvironmentCapabilities) {
806    let mut kernel: Option<FormatId> = None;
807    let mut libc: Option<FormatId> = None;
808    let mut architecture: Option<FormatId> = None;
809    let mut primary_os: Option<FormatId> = None;
810    let mut userspace = Vec::new();
811    let mut display_server: Option<FormatId> = None;
812    let mut device_caps = Vec::new();
813    let mut other_terminal_caps = Vec::new();
814    let mut render_modes = Vec::new();
815    let mut is_stdin_terminal = false;
816    let mut is_stdout_terminal = false;
817    let mut is_stderr_terminal = false;
818
819    // Expand implied formats from declarative @implies(...) directives
820    let mut expanded = formats.to_vec();
821    for &f in formats {
822        for &imp in f.implies() {
823            if !expanded.contains(&imp) {
824                expanded.push(imp);
825            }
826        }
827    }
828
829    for &f in &expanded {
830        match f.category() {
831            FormatCategory::Kernel => {
832                if let Some(prev) = kernel {
833                    warn_fmt!(
834                        "Duplicate kernel format {} in environment snapshot, keeping previous {}",
835                        f.ident(),
836                        prev.ident()
837                    );
838                } else {
839                    kernel = Some(f);
840                }
841            }
842            FormatCategory::Libc => {
843                if let Some(prev) = libc {
844                    warn_fmt!(
845                        "Duplicate libc format {} in environment snapshot, keeping previous {}",
846                        f.ident(),
847                        prev.ident()
848                    );
849                } else {
850                    libc = Some(f);
851                }
852            }
853            FormatCategory::Arch => {
854                if let Some(prev) = architecture {
855                    warn_fmt!(
856                        "Duplicate architecture format {} in environment snapshot, keeping previous {}",
857                        f.ident(),
858                        prev.ident()
859                    );
860                } else {
861                    architecture = Some(f);
862                }
863            }
864            FormatCategory::DisplaySystem => {
865                if let Some(prev) = display_server {
866                    warn_fmt!(
867                        "Duplicate display system format {} in environment snapshot, keeping previous {}",
868                        f.ident(),
869                        prev.ident()
870                    );
871                } else {
872                    display_server = Some(f);
873                }
874            }
875            FormatCategory::Os => {
876                if !matches!(
877                    f,
878                    FormatId::Unix
879                        | FormatId::Windows
880                        | FormatId::MacOs
881                        | FormatId::WinClassic
882                        | FormatId::FreeBsd
883                        | FormatId::OpenBsd
884                        | FormatId::NetBsd
885                        | FormatId::DragonFlyBsd
886                ) && primary_os.is_none()
887                {
888                    primary_os = Some(f);
889                }
890            }
891            FormatCategory::Userspace
892            | FormatCategory::UserspaceUtilities
893            | FormatCategory::UserspaceLibraries
894            | FormatCategory::Packagemgr => {
895                if !userspace.contains(&f) {
896                    userspace.push(f);
897                }
898            }
899            FormatCategory::Videoterminal => {
900                if !other_terminal_caps.contains(&f) {
901                    other_terminal_caps.push(f);
902                }
903                if f == FormatId::Videoterminal && !device_caps.contains(&f) {
904                    device_caps.push(f);
905                }
906            }
907            FormatCategory::DeviceCaps => match f {
908                FormatId::IsStdinTerminal => {
909                    is_stdin_terminal = true;
910                }
911                FormatId::IsStdoutTerminal => {
912                    is_stdout_terminal = true;
913                }
914                FormatId::IsStderrTerminal => {
915                    is_stderr_terminal = true;
916                }
917                FormatId::Teleprinter => {
918                    if !device_caps.contains(&f) {
919                        device_caps.push(f);
920                    }
921                    if !other_terminal_caps.contains(&f) {
922                        other_terminal_caps.push(f);
923                    }
924                }
925                FormatId::LineModeTerminal | FormatId::TerminalColors1bit => {
926                    if !other_terminal_caps.contains(&f) {
927                        other_terminal_caps.push(f);
928                    }
929                }
930                FormatId::RenderModeInteractive
931                | FormatId::RenderModeImmediate => {
932                    if !render_modes.contains(&f) {
933                        render_modes.push(f);
934                    }
935                }
936                _ => {
937                    if !device_caps.contains(&f) {
938                        device_caps.push(f);
939                    }
940                }
941            },
942            _ => {}
943        }
944    }
945
946    let os_families: Vec<FormatId> = expanded
947        .iter()
948        .copied()
949        .filter(|f| {
950            matches!(
951                f,
952                FormatId::Unix
953                    | FormatId::Windows
954                    | FormatId::MacOs
955                    | FormatId::WinClassic
956                    | FormatId::Linux
957                    | FormatId::Darwin
958                    | FormatId::FreeBsd
959                    | FormatId::OpenBsd
960                    | FormatId::NetBsd
961                    | FormatId::DragonFlyBsd
962            )
963        })
964        .fold(Vec::new(), |mut acc, f| {
965            if !acc.contains(&f) {
966                acc.push(f);
967            }
968            acc
969        });
970
971    let ident = EnvironmentIdentity {
972        kernel,
973        kernel_version,
974        libc,
975        userspace,
976        os: primary_os,
977        os_families,
978        architecture,
979    };
980
981    let mut terminal_caps = Vec::new();
982    if is_stdin_terminal {
983        terminal_caps.push(FormatId::IsStdinTerminal);
984    }
985    if is_stdout_terminal {
986        terminal_caps.push(FormatId::IsStdoutTerminal);
987    }
988    if is_stderr_terminal {
989        terminal_caps.push(FormatId::IsStderrTerminal);
990    }
991    for cap in other_terminal_caps {
992        if !terminal_caps.contains(&cap) {
993            terminal_caps.push(cap);
994        }
995    }
996
997    let caps = EnvironmentCapabilities {
998        device_caps,
999        render_modes,
1000        terminal_caps,
1001        display_server,
1002        is_stdin_terminal,
1003        is_stdout_terminal,
1004        is_stderr_terminal,
1005    };
1006
1007    (ident, caps)
1008}
1009
1010/// Produce a human-readable one-line summary string for an environment.
1011#[must_use]
1012pub fn format_environment_summary(
1013    ident: &EnvironmentIdentity,
1014    caps: &EnvironmentCapabilities,
1015) -> String {
1016    let os_name = if let Some(os) = ident.os {
1017        // Reason for fallback: formats without custom display title fall back to canonical ident
1018        os.title().unwrap_or_else(|| os.ident())
1019    } else {
1020        "Unknown OS"
1021    };
1022
1023    let mut parts = Vec::new();
1024    if let Some(kernel) = ident.kernel {
1025        if let Some(ver) = &ident.kernel_version {
1026            parts.push(format!("{} {}", kernel.ident(), ver));
1027        } else {
1028            parts.push(kernel.ident().to_string());
1029        }
1030    } else if let Some(ver) = &ident.kernel_version {
1031        parts.push(ver.clone());
1032    }
1033
1034    if let Some(libc) = ident.libc {
1035        parts.push(format!("/ {}", libc.ident()));
1036    }
1037
1038    if let Some(arch) = ident.architecture {
1039        parts.push(arch.ident().to_string());
1040    }
1041
1042    let identity_details = if parts.is_empty() {
1043        String::new()
1044    } else {
1045        format!(" ({})", parts.join(" "))
1046    };
1047
1048    let mut cap_tags = Vec::new();
1049    if let Some(ds) = caps.display_server {
1050        if ds != FormatId::HeadlessDisplay {
1051            cap_tags.push(ds.ident());
1052        }
1053    }
1054    if caps.device_caps.contains(&FormatId::RasterDisplay) {
1055        cap_tags.push("RasterDisplay");
1056    }
1057    if caps.terminal_caps.contains(&FormatId::Videoterminal) {
1058        cap_tags.push("Videoterminal");
1059    } else if caps.terminal_caps.contains(&FormatId::Teleprinter) {
1060        cap_tags.push("Teleprinter");
1061    }
1062    if caps.render_modes.contains(&FormatId::RenderModeInteractive) {
1063        cap_tags.push("Interactive");
1064    }
1065
1066    let caps_summary = if cap_tags.is_empty() {
1067        "Headless".to_string()
1068    } else {
1069        cap_tags.join(" + ")
1070    };
1071
1072    format!("{os_name}{identity_details} [{caps_summary}]")
1073}
1074
1075#[cfg(test)]
1076#[allow(
1077    clippy::panic,
1078    clippy::expect_used,
1079    clippy::unwrap_used,
1080    clippy::unwrap_in_result,
1081    clippy::panic_in_result_fn,
1082    clippy::indexing_slicing,
1083    clippy::arithmetic_side_effects,
1084    reason = "Standard repository test boilerplate"
1085)]
1086mod tests {
1087    use super::*;
1088
1089    #[crate::ctb_test]
1090    fn test_xterm_256color_capabilities() {
1091        let (term_caps, dev_caps) = detect_terminal_capabilities_for(
1092            "xterm-256color",
1093            true,
1094            true,
1095            true,
1096        );
1097        assert!(term_caps.contains(&FormatId::Videoterminal));
1098        assert!(term_caps.contains(&FormatId::TerminalCanEditPastLines));
1099        assert!(term_caps.contains(&FormatId::TerminalCanEdit));
1100        assert!(term_caps.contains(&FormatId::Vt100));
1101        assert!(term_caps.contains(&FormatId::TerminalMouse));
1102        assert!(term_caps.contains(&FormatId::TerminalColors8bit));
1103        assert!(dev_caps.contains(&FormatId::Videoterminal));
1104    }
1105
1106    #[crate::ctb_test]
1107    fn test_dumb_terminal_capabilities() {
1108        let (term_caps, dev_caps) =
1109            detect_terminal_capabilities_for("dumb", true, true, true);
1110        assert!(term_caps.contains(&FormatId::Teleprinter));
1111        assert!(term_caps.contains(&FormatId::LineModeTerminal));
1112        assert!(term_caps.contains(&FormatId::TerminalColors1bit));
1113        assert!(!term_caps.contains(&FormatId::TerminalMouse));
1114        assert!(!term_caps.contains(&FormatId::Vt100));
1115        assert!(!term_caps.contains(&FormatId::Videoterminal));
1116        assert!(dev_caps.contains(&FormatId::Teleprinter));
1117    }
1118
1119    #[crate::ctb_test]
1120    fn test_vt100_capabilities() {
1121        let (term_caps, dev_caps) =
1122            detect_terminal_capabilities_for("vt100", true, true, true);
1123        assert!(term_caps.contains(&FormatId::Videoterminal));
1124        assert!(term_caps.contains(&FormatId::Vt100));
1125        assert!(term_caps.contains(&FormatId::TerminalCanEditPastLines));
1126        assert!(!term_caps.contains(&FormatId::TerminalMouse));
1127        assert!(dev_caps.contains(&FormatId::Videoterminal));
1128    }
1129
1130    #[crate::ctb_test]
1131    fn test_xterm_direct_capabilities() {
1132        let (term_caps, _) =
1133            detect_terminal_capabilities_for("xterm-direct", true, true, true);
1134        assert!(term_caps.contains(&FormatId::TerminalColors24bit));
1135    }
1136
1137    #[crate::ctb_test]
1138    fn test_ms_terminal_capabilities() {
1139        let (term_caps, dev_caps) =
1140            detect_terminal_capabilities_for("ms-terminal", true, true, true);
1141        assert!(term_caps.contains(&FormatId::Videoterminal));
1142        assert!(term_caps.contains(&FormatId::TerminalMouse));
1143        assert!(term_caps.contains(&FormatId::TerminalColors8bit));
1144        assert!(dev_caps.contains(&FormatId::Videoterminal));
1145    }
1146
1147    #[crate::ctb_test]
1148    fn test_sixel_detection() {
1149        let vt340 = Terminfo::from_name("vt340");
1150        assert_eq!(detect_sixel_support(vt340.as_ref(), false), Some(true));
1151        assert_eq!(detect_sixel_support(vt340.as_ref(), true), Some(true));
1152
1153        let dumb = Terminfo::from_name("dumb");
1154        assert_eq!(detect_sixel_support(dumb.as_ref(), false), Some(false));
1155        assert_eq!(detect_sixel_support(dumb.as_ref(), true), Some(false));
1156
1157        let xterm = Terminfo::from_name("xterm-256color");
1158        // Non-interactive cannot query DA1, returning None (unknown)
1159        assert_eq!(detect_sixel_support(xterm.as_ref(), false), None);
1160
1161        let (term_caps, dev_caps) =
1162            detect_terminal_capabilities_for("vt340", true, true, true);
1163        assert!(term_caps.contains(&FormatId::TerminalSixelGraphics));
1164        assert!(dev_caps.contains(&FormatId::TerminalSixelGraphics));
1165    }
1166
1167    #[crate::ctb_test]
1168    fn test_konsole_version_parsing() {
1169        assert_eq!(parse_konsole_version("220400"), Some(220400));
1170        assert_eq!(parse_konsole_version("22.04.0"), Some(220400));
1171        assert_eq!(parse_konsole_version("20.12.0"), Some(201200));
1172        assert_eq!(parse_konsole_version("190800"), Some(190800));
1173        assert_eq!(parse_konsole_version(""), None);
1174    }
1175
1176    #[crate::ctb_test]
1177    fn test_kitty_and_iterm_detection() {
1178        let dumb = Terminfo::from_name("dumb");
1179        assert_eq!(
1180            detect_kitty_support(dumb.as_ref(), false, "dumb"),
1181            Some(false)
1182        );
1183        assert_eq!(detect_iterm_support(dumb.as_ref(), false), Some(false));
1184
1185        let xterm_kitty = Terminfo::from_name("xterm-kitty");
1186        assert_eq!(
1187            detect_kitty_support(xterm_kitty.as_ref(), false, "xterm-kitty"),
1188            Some(true)
1189        );
1190    }
1191}