uncurses/program/probe.rs
1//! Explicit capability queries written through any output writer.
2
3use std::io::{self, Write};
4
5use super::Capabilities;
6use crate::ansi::mode::Mode;
7use crate::color::Profile;
8use crate::terminal::{Env, is_apple_terminal};
9
10/// Select the terminal queries to write.
11///
12/// [`new`](Self::new) captures environment restrictions and selects session
13/// modes, keyboard protocols, terminal identity, and truecolor support.
14/// Cursor measurements and color-value queries remain opt-in.
15///
16/// [`query_capabilities`](Self::query_capabilities) returns an application-owned
17/// record. Pass matching events to [`Capabilities::record`], then call
18/// [`Program::apply_defaults`](super::Program::apply_defaults) to apply the
19/// core results according to [`ProgramOptions`](super::ProgramOptions).
20#[derive(Debug, Clone)]
21pub struct Probe {
22 /// Measure East Asian Ambiguous width with one cursor position request.
23 ///
24 /// This writes U+2026 at column zero, requests the cursor position, then
25 /// erases two cells. Select it on a blank row with at least three columns.
26 /// The cursor finishes at column zero. The caller updates its screen's
27 /// tracked cursor and invalidates the erased content before rendering.
28 pub eaw_width: bool,
29 /// Request these ANSI and DEC modes in list order, including duplicates.
30 ///
31 /// Apple Terminal skips these requests. A record keeps every mode reply.
32 /// [`Program::apply_defaults`](super::Program::apply_defaults) applies
33 /// supported defaults according to the program options.
34 pub modes: Vec<Mode>,
35 /// Query the active Kitty keyboard enhancements.
36 pub kitty_keyboard: bool,
37 /// Request the terminal name and version with XTVERSION.
38 ///
39 /// Apple Terminal skips this request.
40 pub terminal_name: bool,
41 /// Query the active xterm modifyOtherKeys mode.
42 ///
43 /// Apple Terminal skips this request.
44 pub modify_other_keys: bool,
45 /// Select XTGETTCAP requests.
46 ///
47 /// `None` automatically requests `RGB` and `Tc` when the captured
48 /// environment does not establish truecolor support.
49 /// `Some(names)` requests exactly those names in list order, including
50 /// duplicates. An empty list skips all termcap requests.
51 /// Explicit names are requested even when detection reports truecolor.
52 /// Apple Terminal skips these requests.
53 pub termcap: Option<Vec<String>>,
54 /// Query the terminal's default foreground color.
55 pub foreground_color: bool,
56 /// Query the terminal's default background color.
57 pub background_color: bool,
58 /// Query the cursor color.
59 pub cursor_color: bool,
60 /// Query these palette entries in list order, including duplicates.
61 pub palette_colors: Vec<u8>,
62 /// Query the accepted OSC 7501 program states and kinds.
63 pub program_status: bool,
64 apple_terminal: bool,
65 env_truecolor: bool,
66}
67
68impl Probe {
69 /// Select common session queries using the supplied environment.
70 ///
71 /// Selects synchronized output, Unicode core, in-band resize, Kitty
72 /// keyboard, terminal name, and modifyOtherKeys. Selects `RGB`/`Tc` termcap
73 /// queries when [`Profile::detect_from`] with `is_tty = true` reports a
74 /// profile below truecolor. Program color overrides do not affect selection.
75 /// Set flags to `false`, clear mode lists, or set `termcap` to `Some(vec![])`
76 /// to omit selected queries.
77 /// Cursor measurements and color-value queries start disabled.
78 ///
79 /// The probe owns the relevant values read from `env`. The caller can
80 /// release the environment borrow before it borrows an output writer.
81 /// Create another probe to use a changed environment.
82 pub fn new(env: &dyn Env) -> Self {
83 Self {
84 eaw_width: false,
85 modes: vec![
86 Mode::SYNCHRONIZED_OUTPUT,
87 Mode::UNICODE_CORE,
88 Mode::IN_BAND_RESIZE,
89 ],
90 kitty_keyboard: true,
91 terminal_name: true,
92 modify_other_keys: true,
93 termcap: None,
94 foreground_color: false,
95 background_color: false,
96 cursor_color: false,
97 palette_colors: Vec::new(),
98 program_status: false,
99 apple_terminal: is_apple_terminal(env),
100 env_truecolor: Profile::detect_from(env, true) == Profile::TrueColor,
101 }
102 }
103
104 /// Write selected queries and return a record initialized for their replies.
105 ///
106 /// The order is ambiguous width, Kitty keyboard, modes, terminal name,
107 /// modifyOtherKeys, XTGETTCAP, foreground, background, cursor color,
108 /// palette entries, and program status. Apple Terminal skips mode,
109 /// terminal-name, modifyOtherKeys, and XTGETTCAP requests.
110 ///
111 /// Set `terminator` on the last probe in a batch to append Primary DA.
112 /// The caller flushes the writer once after all probes have written.
113 /// Errors propagate from the writer; an error can follow a partial write.
114 /// The probe's configuration stays unchanged.
115 ///
116 /// Read replies through the application's input loop with a deadline.
117 /// Route cursor reports to their records in request order. The selected
118 /// width query takes the first cursor report routed to this record.
119 /// On DA1, pass the event to every record before ending initial collection.
120 /// Identified replies can update a record after that point.
121 ///
122 /// Cursor reports and DA1 carry no request ID. Finish earlier requests
123 /// before this batch and keep unrelated cursor requests out of it.
124 /// A timeout leaves outstanding requests active. Multiplexer forwarding
125 /// can also deliver an extension reply after DA1.
126 ///
127 /// On row one, a standard cursor reply can also decode as modified F3.
128 /// See [`Event::CursorPosition`](crate::event::Event::CursorPosition) for
129 /// the input ambiguity and application handling.
130 ///
131 /// ```no_run
132 /// # use std::io::{self, Write};
133 /// # use uncurses::program::{Probe, Program};
134 /// # fn main() -> io::Result<()> {
135 /// let mut program = Program::stdio()?;
136 /// let mut probe = Probe::new(program.env());
137 /// probe.background_color = true;
138 /// let mut caps = probe.query_capabilities(program.screen_mut(), true)?;
139 /// program.screen_mut().flush()?;
140 /// # let _ = &mut caps;
141 /// # Ok(())
142 /// # }
143 /// ```
144 pub fn query_capabilities<W: Write>(
145 &self,
146 writer: &mut W,
147 terminator: bool,
148 ) -> io::Result<Capabilities> {
149 use crate::ansi::color;
150 use crate::ansi::ctrl::{REQUEST_PRIMARY_DA, REQUEST_XTVERSION};
151 use crate::ansi::kitty::REQUEST_KITTY_KEYBOARD;
152 use crate::ansi::termcap::write_xtgettcap;
153
154 if self.eaw_width {
155 writer.write_all(b"\r\xe2\x80\xa6\x1b[6n\r\x1b[2X")?;
156 }
157 if self.kitty_keyboard {
158 writer.write_all(REQUEST_KITTY_KEYBOARD)?;
159 }
160 if !self.apple_terminal {
161 for mode in &self.modes {
162 mode.request(writer)?;
163 }
164 if self.terminal_name {
165 writer.write_all(REQUEST_XTVERSION)?;
166 }
167 if self.modify_other_keys {
168 writer.write_all(crate::ansi::xterm::QUERY_MODIFY_OTHER_KEYS)?;
169 }
170 if let Some(names) = &self.termcap {
171 for name in names {
172 write_xtgettcap(writer, &[name.as_str()])?;
173 }
174 } else if !self.env_truecolor {
175 for name in ["RGB", "Tc"] {
176 write_xtgettcap(writer, &[name])?;
177 }
178 }
179 }
180 if self.foreground_color {
181 writer.write_all(color::REQUEST_FOREGROUND_COLOR)?;
182 }
183 if self.background_color {
184 writer.write_all(color::REQUEST_BACKGROUND_COLOR)?;
185 }
186 if self.cursor_color {
187 writer.write_all(color::REQUEST_CURSOR_COLOR)?;
188 }
189 for &index in &self.palette_colors {
190 color::write_request_palette_color(writer, index)?;
191 }
192 if self.program_status {
193 writer.write_all(crate::ansi::program_status::REQUEST_PROGRAM_STATUS)?;
194 }
195 if terminator {
196 writer.write_all(REQUEST_PRIMARY_DA)?;
197 }
198 Ok(Capabilities {
199 eaw_probe: self.eaw_width,
200 queried_modes: if self.apple_terminal {
201 Vec::new()
202 } else {
203 self.modes.clone()
204 },
205 ..Capabilities::default()
206 })
207 }
208}