1#[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#[derive(
44 Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
45)]
46pub struct EnvironmentIdentity {
47 pub kernel: Option<FormatId>,
50 pub kernel_version: Option<String>,
52 pub libc: Option<FormatId>,
55 pub userspace: Vec<FormatId>,
57 pub os: Option<FormatId>,
60 pub os_families: Vec<FormatId>,
62 pub architecture: Option<FormatId>,
65}
66
67#[derive(
74 Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize,
75)]
76pub struct EnvironmentCapabilities {
77 pub device_caps: Vec<FormatId>,
80 pub render_modes: Vec<FormatId>,
83 pub terminal_caps: Vec<FormatId>,
86 pub display_server: Option<FormatId>,
90 pub is_stdin_terminal: bool,
92 pub is_stdout_terminal: bool,
94 pub is_stderr_terminal: bool,
96}
97
98#[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#[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 let architecture = detect_architecture();
151 if let Some(arch) = architecture {
152 detected.push(arch);
153 }
154
155 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 if cfg!(target_env = "musl") {
197 detected.push(FormatId::MuslLibc);
198 }
199
200 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 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 let initial = detected.clone();
246 for id in initial {
247 for &implied in id.implies() {
248 detected.push(implied);
249 }
250 }
251
252 let mut seen = HashSet::new();
254 detected.retain(|id| seen.insert(*id));
255
256 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#[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#[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 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 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#[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 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 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 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 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 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 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 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 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#[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 && 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#[must_use]
627pub fn detect_kitty_support(
628 term_info: Option<&Terminfo>,
629 is_interactive: bool,
630 term: &str,
631) -> Option<bool> {
632 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 && 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#[must_use]
675pub fn detect_iterm_support(
676 term_info: Option<&Terminfo>,
677 is_interactive: bool,
678) -> Option<bool> {
679 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 && term_info.is_some_and(Terminfo::supports_da1);
704
705 if can_query { Some(false) } else { None }
706}
707
708#[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#[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#[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 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#[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 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 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}