Skip to main content

mrk/terminal/
detect.rs

1use crossterm::terminal::WindowSize;
2
3use super::environment::{Environment, background_hint, color_depth, double_height, hyperlinks, known_graphics, wants_pictures};
4use super::query::{self, Questions};
5use super::reply::Replies;
6use super::{Capabilities, ColorChoice, ColorDepth, Graphics, ImagesMode, Protocol};
7use crate::document::{CellSize, Rgb};
8use crate::theme::Appearance;
9
10const DEFAULT_COLUMNS: u16 = 80;
11const DEFAULT_ROWS: u16 = 24;
12
13/// What the user asked for, which detection must respect.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct Preferences {
17    pub color: ColorChoice,
18    pub images: ImagesMode,
19    /// The theme was not named, so the background decides between dark and light.
20    pub needs_background: bool,
21}
22
23pub fn cell_size(window: &WindowSize) -> Option<CellSize> {
24    let has_pixels = window.width > 0 && window.height > 0;
25    let has_cells = window.columns > 0 && window.rows > 0;
26    let cell = CellSize { width_px: window.width / window.columns.max(1), height_px: window.height / window.rows.max(1) };
27    let is_usable = cell.width_px > 0 && cell.height_px > 0;
28    (has_pixels && has_cells && is_usable).then_some(cell)
29}
30
31pub fn appearance(background: Rgb) -> Appearance {
32    let luminance = 2126 * u32::from(background.0) + 7152 * u32::from(background.1) + 722 * u32::from(background.2);
33    let is_dark = luminance < 10_000 * 128;
34    if is_dark { Appearance::Dark } else { Appearance::Light }
35}
36
37fn questions(environment: &Environment, color: ColorDepth, window_cell: Option<CellSize>, preferences: Preferences) -> Questions {
38    let is_background_unknown = preferences.needs_background && background_hint(environment).is_none();
39    let known = known_graphics(environment);
40    let may_draw = wants_pictures(environment, preferences.images) && known != Some(false);
41    Questions {
42        graphics: may_draw && known.is_none(),
43        cell: may_draw && window_cell.is_none(),
44        background: is_background_unknown && environment.stdout_is_tty && color != ColorDepth::None,
45        passthrough: environment.is_tmux(),
46    }
47}
48
49/// Kitty when the environment or the terminal says so, through tmux when inside it; Sixel when only the DA1 reply
50/// lists it, which inside tmux is tmux's own reply, so tmux draws it.
51fn protocol(environment: &Environment, replies: &Replies) -> Option<Protocol> {
52    match known_graphics(environment) {
53        Some(true) => Some(Protocol::Kitty),
54        Some(false) => None,
55        None if replies.graphics && environment.is_tmux() => Some(Protocol::KittyThroughTmux),
56        None if replies.graphics => Some(Protocol::Kitty),
57        None => replies.sixel.then_some(Protocol::Sixel),
58    }
59}
60
61/// How pictures are drawn, when they are wanted, the terminal draws them, and the cell size is known from the window
62/// or the terminal's reply.
63fn graphics(environment: &Environment, images: ImagesMode, window_cell: Option<CellSize>, replies: &Replies) -> Option<Graphics> {
64    let protocol = protocol(environment, replies).filter(|_| wants_pictures(environment, images))?;
65    let cell = window_cell.or(replies.cell)?;
66    Some(Graphics { protocol, cell })
67}
68
69/// What the terminal can do, from the environment, the window size and, only when stdout is a terminal and the
70/// environment leaves a question open, one round of terminal queries.
71pub fn detect(preferences: Preferences) -> Capabilities {
72    let environment = Environment::read();
73    let window = crossterm::terminal::window_size().ok();
74    let color = color_depth(&environment, preferences.color);
75    let window_cell = window.as_ref().and_then(cell_size);
76
77    let questions = questions(&environment, color, window_cell, preferences);
78    let replies = if questions.is_empty() { Replies::default() } else { query::ask(questions) };
79
80    let background = background_hint(&environment).or(replies.background.map(appearance));
81    let columns = window.as_ref().map(|window| window.columns).filter(|&columns| columns > 0).unwrap_or(DEFAULT_COLUMNS);
82    let rows = window.as_ref().map(|window| window.rows).filter(|&rows| rows > 0).unwrap_or(DEFAULT_ROWS);
83    Capabilities {
84        color,
85        hyperlinks: hyperlinks(&environment, color),
86        graphics: graphics(&environment, preferences.images, window_cell, &replies),
87        double_height: double_height(&environment, color),
88        background,
89        columns,
90        rows,
91        is_terminal: environment.stdout_is_tty,
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn window(columns: u16, rows: u16, width: u16, height: u16) -> WindowSize {
100        WindowSize { rows, columns, width, height }
101    }
102
103    #[test]
104    fn the_cell_size_is_pixels_over_cells() {
105        assert_eq!(cell_size(&window(100, 50, 1000, 1000)), Some(CellSize { width_px: 10, height_px: 20 }));
106    }
107
108    #[test]
109    fn an_unknown_pixel_size_means_no_pictures() {
110        assert_eq!(cell_size(&window(100, 50, 0, 0)), None);
111        assert_eq!(cell_size(&window(0, 0, 1000, 1000)), None);
112        assert_eq!(cell_size(&window(100, 50, 50, 1000)), None);
113    }
114
115    #[test]
116    fn luminance_splits_dark_from_light() {
117        assert_eq!(appearance(Rgb(0x1e, 0x1e, 0x2e)), Appearance::Dark);
118        assert_eq!(appearance(Rgb(0xff, 0xff, 0xff)), Appearance::Light);
119        assert_eq!(appearance(Rgb(0xfd, 0xf6, 0xe3)), Appearance::Light);
120        assert_eq!(appearance(Rgb(0x00, 0x2b, 0x36)), Appearance::Dark);
121    }
122
123    fn environment(variables: &[(&str, &str)]) -> Environment {
124        let variables = variables.iter().map(|&(name, value)| (name.to_owned(), value.to_owned())).collect();
125        Environment { variables, stdout_is_tty: true }
126    }
127
128    const CELL: Option<CellSize> = Some(CellSize { width_px: 10, height_px: 20 });
129
130    #[test]
131    fn nothing_is_asked_when_the_environment_knows() {
132        let preferences = Preferences { needs_background: true, ..Preferences::default() };
133        let known = environment(&[("TERM", "xterm-kitty"), ("COLORFGBG", "15;0")]);
134
135        assert!(questions(&known, ColorDepth::TrueColor, CELL, preferences).is_empty());
136    }
137
138    #[test]
139    fn open_questions_are_asked_together() {
140        let preferences = Preferences { needs_background: true, ..Preferences::default() };
141        let asked = questions(&environment(&[("TERM", "xterm-256color")]), ColorDepth::Ansi256, CELL, preferences);
142
143        assert_eq!(asked, Questions { graphics: true, background: true, ..Questions::default() });
144    }
145
146    #[test]
147    fn the_cell_size_is_asked_only_when_the_window_does_not_tell_it() {
148        let kitty = environment(&[("TERM", "xterm-kitty")]);
149
150        assert_eq!(
151            questions(&kitty, ColorDepth::TrueColor, None, Preferences::default()),
152            Questions { cell: true, ..Questions::default() }
153        );
154        assert!(questions(&kitty, ColorDepth::TrueColor, CELL, Preferences::default()).is_empty());
155    }
156
157    #[test]
158    fn graphics_are_not_asked_about_where_pictures_are_off() {
159        let never = Preferences { images: ImagesMode::Never, ..Preferences::default() };
160
161        assert!(questions(&environment(&[]), ColorDepth::TrueColor, None, never).is_empty());
162        assert!(questions(&environment(&[("TERM_PROGRAM", "iTerm.app")]), ColorDepth::TrueColor, None, Preferences::default()).is_empty());
163        assert!(questions(&environment(&[("ZELLIJ", "0")]), ColorDepth::TrueColor, CELL, Preferences::default()).is_empty());
164    }
165
166    fn drawn_with(variables: &[(&str, &str)], replies: Replies) -> Option<Protocol> {
167        graphics(&environment(variables), ImagesMode::Auto, CELL, &replies).map(|graphics| graphics.protocol)
168    }
169
170    #[test]
171    fn kitty_wins_over_sixel() {
172        assert_eq!(drawn_with(&[], Replies { graphics: true, sixel: true, ..Replies::default() }), Some(Protocol::Kitty));
173        assert_eq!(drawn_with(&[("TERM", "xterm-kitty")], Replies { sixel: true, ..Replies::default() }), Some(Protocol::Kitty));
174    }
175
176    #[test]
177    fn inside_tmux_graphics_are_asked_through_it_and_drawn_through_it() {
178        let tmux = [("TMUX", "/tmp/tmux"), ("TERM", "tmux-256color"), ("GHOSTTY_RESOURCES_DIR", "/x")];
179
180        assert_eq!(
181            questions(&environment(&tmux), ColorDepth::TrueColor, CELL, Preferences::default()),
182            Questions { graphics: true, passthrough: true, ..Questions::default() }
183        );
184        assert_eq!(drawn_with(&tmux, Replies { graphics: true, sixel: true, ..Replies::default() }), Some(Protocol::KittyThroughTmux));
185        assert_eq!(drawn_with(&tmux, Replies { sixel: true, ..Replies::default() }), Some(Protocol::Sixel));
186        assert_eq!(drawn_with(&tmux, Replies::default()), None);
187    }
188
189    #[test]
190    fn sixel_is_used_when_only_the_da1_reply_lists_it() {
191        assert_eq!(drawn_with(&[], Replies { sixel: true, ..Replies::default() }), Some(Protocol::Sixel));
192        assert_eq!(drawn_with(&[], Replies::default()), None);
193    }
194
195    #[test]
196    fn terminals_known_without_graphics_stay_without_sixel() {
197        for program in ["iTerm.app", "Apple_Terminal", "vscode"] {
198            assert_eq!(drawn_with(&[("TERM_PROGRAM", program)], Replies { sixel: true, ..Replies::default() }), None, "{program}");
199        }
200    }
201
202    #[test]
203    fn the_replied_cell_size_stands_in_for_the_window() {
204        let replied = CellSize { width_px: 8, height_px: 16 };
205        let replies = Replies { sixel: true, cell: Some(replied), ..Replies::default() };
206
207        assert_eq!(
208            graphics(&environment(&[]), ImagesMode::Auto, None, &replies),
209            Some(Graphics { protocol: Protocol::Sixel, cell: replied })
210        );
211        assert_eq!(graphics(&environment(&[]), ImagesMode::Auto, CELL, &replies).map(|graphics| graphics.cell), CELL);
212        assert_eq!(graphics(&environment(&[]), ImagesMode::Auto, None, &Replies { cell: None, ..replies }), None);
213        assert_eq!(graphics(&environment(&[]), ImagesMode::Never, CELL, &replies), None);
214    }
215
216    #[test]
217    fn a_named_theme_skips_the_background_question() {
218        let asked = questions(&environment(&[("TERM", "xterm-kitty")]), ColorDepth::TrueColor, CELL, Preferences::default());
219
220        assert!(asked.is_empty());
221    }
222
223    #[test]
224    fn nothing_is_asked_when_stdout_is_not_a_terminal() {
225        let preferences = Preferences { needs_background: true, ..Preferences::default() };
226        let piped = Environment { stdout_is_tty: false, ..environment(&[]) };
227
228        assert!(questions(&piped, ColorDepth::TrueColor, None, preferences).is_empty());
229    }
230}