uncurses/program/modes.rs
1//! Non-render terminal/input mode toggles for the [`Program`] facade —
2//! cursor style, mouse tracking, bracketed paste, focus reporting,
3//! color-scheme update reports, in-band resize reports, window title,
4//! progress reports, and the default foreground/background/cursor colors.
5//!
6//! Each setter emits its escape bytes through the owned renderer and
7//! flushes immediately, so the mode change takes effect on the terminal
8//! right away and the call returns [`io::Result<()>`](std::io::Result). A
9//! setter whose tracked value is unchanged is a no-op and performs no I/O.
10//!
11//! [`Program`]: super::Program
12
13use std::io::{self, Write};
14
15use crate::ansi::{self, color, cursor, kitty, mode, progress, status, xterm};
16use crate::color::Color;
17use crate::event::Input;
18
19use super::MouseTracking;
20use super::Program;
21use super::ProgressState;
22use crate::ansi::cursor::{CursorShape, CursorStyle};
23
24/// DEC private modes for the mouse tracking modes and encodings this
25/// library supports. Reset together to unconditionally turn mouse
26/// reporting off.
27const MOUSE_MODES: &[mode::Mode] = &[
28 mode::Mode::MOUSE_X10,
29 mode::Mode::MOUSE_NORMAL,
30 mode::Mode::MOUSE_BUTTON,
31 mode::Mode::MOUSE_ANY,
32 mode::Mode::MOUSE_SGR,
33 mode::Mode::MOUSE_SGR_PIXEL,
34];
35
36impl<I: Input, O: Write> Program<I, O> {
37 /// Send a complete OSC 7501 program status report and flush.
38 ///
39 /// Reports replace the addressed record. Include its app, title, and
40 /// message on every update when they should remain present. Use
41 /// [`ProgramStatusState::CLEAR`](super::ProgramStatusState::CLEAR) to
42 /// remove the record and its descendants; a root clear removes all records.
43 ///
44 /// The terminal owns record lifetime. Pause, resume, screen switches,
45 /// and finish leave these reports unchanged, so done and error records
46 /// can survive exit. Explicit discovery is optional; unsupported
47 /// terminals ignore reports.
48 ///
49 /// Invalid fields return [`io::ErrorKind::InvalidInput`] before output.
50 /// See [`write_program_status`](ansi::program_status::write_program_status)
51 /// for validation and protocol limits.
52 pub fn set_program_status(&mut self, report: &super::ProgramStatus<'_>) -> io::Result<()> {
53 ansi::program_status::write_program_status(&mut self.screen, report)?;
54 self.screen.flush()
55 }
56
57 /// Query OSC 7501 support and flush, without waiting for a reply.
58 ///
59 /// The reply is [`Event::ProgramStatus`](crate::event::Event::ProgramStatus),
60 /// with the accepted state and kind names.
61 /// [`Capabilities::record`](super::Capabilities::record) records support
62 /// and both lists. To include this query in a capability batch, set
63 /// [`Probe::program_status`](super::Probe::program_status).
64 /// Initialization sends no queries.
65 pub fn request_program_status(&mut self) -> io::Result<()> {
66 self.screen
67 .write_all(ansi::program_status::REQUEST_PROGRAM_STATUS)?;
68 self.screen.flush()
69 }
70
71 /// Return whether the terminal accepts OSC 7577 program resume reports.
72 ///
73 /// Support is present when the environment of the
74 /// [`Terminal`](crate::terminal::Terminal) has a nonempty
75 /// [`OSC7577_TOKEN`](ansi::program_resume::TOKEN_ENV). The protocol has
76 /// no query. A supporting terminal can still choose not to resume.
77 pub fn supports_program_resume(&self) -> bool {
78 self.terminal.has_env(ansi::program_resume::TOKEN_ENV)
79 }
80
81 /// Report how the terminal can resume this process (OSC 7577) and flush.
82 ///
83 /// The report names [`std::process::id`] and the current time, and
84 /// carries a hash of the terminal's token. The token itself is not
85 /// written. Without a token, this writes nothing and returns `Ok`.
86 ///
87 /// Report again when the command changes, when the working directory
88 /// in `report.cwd` changes, and after [`resume`](Self::resume). Pause,
89 /// resume, and [`finish`](Self::finish) leave the record unchanged.
90 ///
91 /// A command that the protocol cannot carry, such as one with a control
92 /// character or one that exceeds the
93 /// [limits](ansi::program_resume::write_program_resume), returns
94 /// [`io::ErrorKind::InvalidInput`]. Before it returns, this method sends
95 /// a clear report, so the terminal does not resume an earlier command.
96 /// An invalid token returns the same error and writes nothing.
97 pub fn set_program_resume(&mut self, report: &super::ProgramResume<'_>) -> io::Result<()> {
98 let Some(token) = self.program_resume_token() else {
99 return Ok(());
100 };
101 let (pid, time) = (std::process::id(), unix_time()?);
102 match ansi::program_resume::write_program_resume(
103 &mut self.screen,
104 report,
105 pid,
106 time,
107 &token,
108 ) {
109 Ok(()) => self.screen.flush(),
110 Err(err) if err.kind() == io::ErrorKind::InvalidInput => {
111 match ansi::program_resume::write_program_resume_clear(
112 &mut self.screen,
113 pid,
114 time,
115 &token,
116 ) {
117 Ok(()) => self.screen.flush()?,
118 Err(clear) if clear.kind() == io::ErrorKind::InvalidInput => {}
119 Err(clear) => return Err(clear),
120 }
121 Err(err)
122 }
123 Err(err) => Err(err),
124 }
125 }
126
127 /// Remove this process's resume record (OSC 7577) and flush.
128 ///
129 /// Call it when the user ends the program. When the program exits because
130 /// of `SIGHUP`, `SIGTERM`, or the loss of its terminal, keep the record:
131 /// the terminal needs it to resume the program. Without a
132 /// token, this writes nothing and returns `Ok`. An invalid token returns
133 /// [`io::ErrorKind::InvalidInput`] and writes nothing.
134 pub fn clear_program_resume(&mut self) -> io::Result<()> {
135 let Some(token) = self.program_resume_token() else {
136 return Ok(());
137 };
138 ansi::program_resume::write_program_resume_clear(
139 &mut self.screen,
140 std::process::id(),
141 unix_time()?,
142 &token,
143 )?;
144 self.screen.flush()
145 }
146
147 fn program_resume_token(&self) -> Option<String> {
148 self.terminal
149 .get_env(ansi::program_resume::TOKEN_ENV)
150 .filter(|token| !token.is_empty())
151 }
152
153 /// Set the cursor shape and blinking state (`DECSCUSR`) and flush.
154 ///
155 /// * `shape` — the visual cursor shape ([`Block`](CursorShape::Block),
156 /// [`Underline`](CursorShape::Underline), or [`Bar`](CursorShape::Bar)).
157 /// * `blinking` — whether the cursor blinks.
158 pub fn set_cursor_style(&mut self, shape: CursorShape, blinking: bool) -> io::Result<()> {
159 let style = CursorStyle::new(shape, blinking);
160 cursor::write_cursor_style(&mut self.screen, style)?;
161 self.state.cursor_style = style;
162 self.screen.flush()
163 }
164
165 /// Hand the cursor style back to the terminal (`DECSCUSR` parameter 0)
166 /// and flush.
167 ///
168 /// Every terminal surveyed for this reads its own configuration here:
169 /// kitty, foot, rio, Alacritty, wezterm, VTE, Konsole and Windows
170 /// Terminal all restore the shape their user chose. xterm documents the
171 /// parameter as a blinking block instead, so what appears is the
172 /// terminal's to decide either way.
173 ///
174 /// That makes this the portable way to undo
175 /// [`set_cursor_style`](Self::set_cursor_style) without knowing what
176 /// came before. To put back the cursor *this session* found rather than
177 /// the one the user configured, read it with
178 /// [`request_cursor_style`](Self::request_cursor_style) before changing
179 /// it and set that style again.
180 pub fn reset_cursor_style(&mut self) -> io::Result<()> {
181 cursor::write_cursor_style(&mut self.screen, CursorStyle::Default)?;
182 self.state.cursor_style = CursorStyle::Default;
183 self.screen.flush()
184 }
185
186 /// Ring the terminal bell (`BEL`) and flush.
187 pub fn beep(&mut self) -> io::Result<()> {
188 self.screen.write_all(b"\x07")?;
189 self.screen.flush()
190 }
191
192 /// Set the pointer (mouse cursor) shape (`OSC 22`) and flush.
193 ///
194 /// `shape` is a pointer shape name such as `"default"`, `"text"`, or
195 /// `"pointer"`. The shape is recorded for save/restore.
196 pub fn set_pointer_shape(&mut self, shape: &str) -> io::Result<()> {
197 cursor::write_set_pointer_shape(&mut self.screen, shape)?;
198 self.state.pointer_shape = Some(shape.to_string());
199 self.screen.flush()
200 }
201
202 /// Reset the pointer (mouse cursor) shape to the terminal default
203 /// (`OSC 22 ; default`) and flush.
204 ///
205 /// Uses the explicit `"default"` shape name rather than an empty one: some
206 /// terminals don't treat an empty `OSC 22` as a reset.
207 pub fn reset_pointer_shape(&mut self) -> io::Result<()> {
208 cursor::write_set_pointer_shape(&mut self.screen, "default")?;
209 self.state.pointer_shape = None;
210 self.screen.flush()
211 }
212
213 /// Report progress to the terminal (`OSC 9;4`) and flush.
214 ///
215 /// Terminals that support it show the progress in the taskbar, tab, or
216 /// window chrome; the rest ignore the sequence. Percentages are clamped
217 /// to `0..=100`.
218 ///
219 /// The state is recorded for save/restore: it is removed on a shell
220 /// handoff ([`pause`](Self::pause), Unix `suspend`,
221 /// [`finish`](Self::finish)) and re-reported by
222 /// [`resume`](Self::resume). Take it down with
223 /// [`reset_progress_state`](Self::reset_progress_state).
224 pub fn set_progress_state(&mut self, progress: ProgressState) -> io::Result<()> {
225 progress.write(&mut self.screen)?;
226 self.state.progress = Some(progress);
227 self.screen.flush()
228 }
229
230 /// Remove the progress report (`OSC 9;4;0`) and flush.
231 pub fn reset_progress_state(&mut self) -> io::Result<()> {
232 self.screen.write_all(progress::RESET_PROGRESS_BAR)?;
233 self.state.progress = None;
234 self.screen.flush()
235 }
236
237 /// Enable mouse tracking and flush.
238 ///
239 /// This emits exactly what is asked for and does not consult terminal
240 /// [`Capabilities`](super::Capabilities). Unsupported modes are ignored by
241 /// the terminal, and because the mode requests are mutually exclusive, each
242 /// terminal settles on the most capable variant it understands:
243 ///
244 /// * Tracking: button (`1000`) and button-event (`1002`) are always
245 /// requested, so a terminal reports drag where it can and plain clicks
246 /// otherwise. With [`MouseTracking::MOTION`], any-event tracking (`1003`)
247 /// is added on top, so motion without a button held is reported where
248 /// supported.
249 /// * Encoding: SGR (`1006`) is always requested, since the legacy byte
250 /// encoding caps coordinates at 223 and SGR is universally supported.
251 /// With [`MouseTracking::PIXELS`], SGR-pixel (`1016`) is added; terminals
252 /// that support it report pixel coordinates, and the rest fall back to
253 /// SGR cell coordinates.
254 ///
255 /// Pass [`MouseTracking::empty()`] for basic button tracking with no
256 /// extras. To turn mouse tracking off, call [`disable_mouse`](Self::disable_mouse).
257 ///
258 /// To learn which variant a terminal actually chose, read the
259 /// [`Capabilities`](super::Capabilities) record (for example
260 /// [`supports(Mode::MOUSE_SGR_PIXEL)`](super::Capabilities::supports) to
261 /// tell whether pixels or cells will arrive). When pixel reporting is active, a
262 /// [`Mouse`](crate::event::Mouse) event's pixel coordinates can be converted
263 /// to cells with [`mouse_pixel_to_cell`](crate::event::mouse_pixel_to_cell).
264 ///
265 /// Mouse coordinates are physical screen coordinates. Inline, call
266 /// [`request_origin`](Self::request_origin) and pass the matching reply to
267 /// [`set_origin`](Self::set_origin), so
268 /// [`mouse_to_origin`](Self::mouse_to_origin) can map them into it.
269 ///
270 /// The request is recorded for save/restore.
271 pub fn enable_mouse(&mut self, tracking: MouseTracking) -> io::Result<()> {
272 // Drop any prior tracking first so modes don't stack ambiguously.
273 mode::write_reset_mode(&mut self.screen, MOUSE_MODES)?;
274 self.write_mouse_modes(tracking, true)?;
275 self.state.mouse = Some(tracking);
276 self.state.chosen.insert(mode::Mode::MOUSE_NORMAL);
277 self.screen.flush()
278 }
279
280 /// Disable all mouse tracking modes and encodings, and flush.
281 pub fn disable_mouse(&mut self) -> io::Result<()> {
282 mode::write_reset_mode(&mut self.screen, MOUSE_MODES)?;
283 self.state.mouse = None;
284 self.state.chosen.insert(mode::Mode::MOUSE_NORMAL);
285 self.screen.flush()
286 }
287
288 /// Set or reset the mouse tracking modes and encoding for the given
289 /// tracking flags. `enable` selects set vs reset. The modes are emitted in
290 /// ascending order so that, where the requests are mutually exclusive, the
291 /// most capable supported variant wins (`1003` over `1002`/`1000`, `1016`
292 /// over `1006`).
293 fn write_mouse_modes(&mut self, tracking: MouseTracking, enable: bool) -> io::Result<()> {
294 // Always request plain and button-event tracking as a fallback pair,
295 // adding any-event tracking on top when motion is requested.
296 let mut modes = vec![mode::Mode::MOUSE_NORMAL, mode::Mode::MOUSE_BUTTON];
297 if tracking.contains(MouseTracking::MOTION) {
298 modes.push(mode::Mode::MOUSE_ANY);
299 }
300 // Always request SGR encoding; add SGR-pixel on top when pixels are
301 // requested. Terminals without pixel support fall back to SGR cells.
302 modes.push(mode::Mode::MOUSE_SGR);
303 if tracking.contains(MouseTracking::PIXELS) {
304 modes.push(mode::Mode::MOUSE_SGR_PIXEL);
305 }
306 if enable {
307 mode::write_set_mode(&mut self.screen, &modes)
308 } else {
309 mode::write_reset_mode(&mut self.screen, &modes)
310 }
311 }
312
313 /// Enable bracketed paste mode (DEC private mode 2004) and flush.
314 pub fn enable_bracketed_paste(&mut self) -> io::Result<()> {
315 mode::Mode::BRACKETED_PASTE.set(&mut self.screen)?;
316 self.state.bracketed_paste = true;
317 self.state.chosen.insert(mode::Mode::BRACKETED_PASTE);
318 self.screen.flush()
319 }
320
321 /// Disable bracketed paste mode (DEC private mode 2004) and flush.
322 pub fn disable_bracketed_paste(&mut self) -> io::Result<()> {
323 mode::Mode::BRACKETED_PASTE.reset(&mut self.screen)?;
324 self.state.bracketed_paste = false;
325 self.state.chosen.insert(mode::Mode::BRACKETED_PASTE);
326 self.screen.flush()
327 }
328
329 /// Enable focus in/out reporting (DEC private mode 1004) and flush.
330 pub fn enable_focus_events(&mut self) -> io::Result<()> {
331 mode::Mode::FOCUS.set(&mut self.screen)?;
332 self.state.focus_events = true;
333 self.state.chosen.insert(mode::Mode::FOCUS);
334 self.screen.flush()
335 }
336
337 /// Disable focus in/out reporting (DEC private mode 1004) and flush.
338 pub fn disable_focus_events(&mut self) -> io::Result<()> {
339 mode::Mode::FOCUS.reset(&mut self.screen)?;
340 self.state.focus_events = false;
341 self.state.chosen.insert(mode::Mode::FOCUS);
342 self.screen.flush()
343 }
344
345 /// Enable color-scheme update notifications (DEC private mode 2031) and
346 /// flush. The terminal then sends a `CSI ? 997 ; {1|2} n` report
347 /// whenever the user or operating system switches between dark and
348 /// light schemes; these surface as [`Event::ColorScheme`]. The report
349 /// indicates only the dark/light preference, not the actual colors.
350 ///
351 /// [`Event::ColorScheme`]: crate::event::Event::ColorScheme
352 pub fn enable_color_scheme_updates(&mut self) -> io::Result<()> {
353 mode::Mode::LIGHT_DARK.set(&mut self.screen)?;
354 self.state.color_scheme_updates = true;
355 self.state.chosen.insert(mode::Mode::LIGHT_DARK);
356 self.screen.flush()
357 }
358
359 /// Disable color-scheme update notifications (DEC private mode 2031) and
360 /// flush.
361 pub fn disable_color_scheme_updates(&mut self) -> io::Result<()> {
362 mode::Mode::LIGHT_DARK.reset(&mut self.screen)?;
363 self.state.color_scheme_updates = false;
364 self.state.chosen.insert(mode::Mode::LIGHT_DARK);
365 self.screen.flush()
366 }
367
368 /// Enable terminal visibility reports (DEC private mode 2033) and flush.
369 /// The terminal then sends a `CSI ? 999 ; {1|2} n` report whenever the
370 /// view stops being observable or becomes observable again, which the
371 /// decoder surfaces as [`Event::Visibility`]. Being covered by another
372 /// window, scrolled out of a tab, or on a minimized window all count.
373 ///
374 /// The report is advisory and asymmetric: [`Visibility::Hidden`] means
375 /// the terminal knows nothing can be seen, so a render can be skipped,
376 /// while [`Visibility::Visible`] only means it may be observable. A
377 /// terminal that never reports is therefore treated as visible, which is
378 /// what makes ignoring this mode safe.
379 ///
380 /// Visibility is independent of focus: an unfocused window is usually
381 /// still visible.
382 ///
383 /// [`Event::Visibility`]: crate::event::Event::Visibility
384 /// [`Visibility::Hidden`]: crate::event::Visibility::Hidden
385 /// [`Visibility::Visible`]: crate::event::Visibility::Visible
386 pub fn enable_visibility_reports(&mut self) -> io::Result<()> {
387 mode::Mode::VISIBILITY_REPORTS.set(&mut self.screen)?;
388 self.state.visibility_reports = true;
389 self.state.chosen.insert(mode::Mode::VISIBILITY_REPORTS);
390 self.screen.flush()
391 }
392
393 /// Disable terminal visibility reports (DEC private mode 2033) and flush.
394 pub fn disable_visibility_reports(&mut self) -> io::Result<()> {
395 mode::Mode::VISIBILITY_REPORTS.reset(&mut self.screen)?;
396 self.state.visibility_reports = false;
397 self.state.chosen.insert(mode::Mode::VISIBILITY_REPORTS);
398 self.screen.flush()
399 }
400
401 /// Ask the terminal to report its visibility once and flush.
402 ///
403 /// The reply arrives as [`Event::Visibility`], the same event the
404 /// unsolicited reports use. This does not enable or disable
405 /// [`enable_visibility_reports`](Self::enable_visibility_reports), so it
406 /// is the way to read visibility without subscribing to changes. A
407 /// terminal that does not implement DEC private mode 2033 answers
408 /// nothing at all, so never block waiting for this reply.
409 ///
410 /// [`Event::Visibility`]: crate::event::Event::Visibility
411 pub fn request_visibility(&mut self) -> io::Result<()> {
412 self.screen
413 .write_all(status::REQUEST_VISIBILITY_REPORT)
414 .and_then(|()| self.screen.flush())
415 }
416
417 /// Enable in-band resize notifications (DEC private mode 2048) and
418 /// flush. The terminal then reports every surface size change in-band
419 /// as a `CSI 48 ; height ; width ; ypixel ; xpixel t` sequence, which
420 /// the decoder surfaces as [`Event::Resize`] — no `SIGWINCH` handler
421 /// required. The event source stops synthesizing resizes from `SIGWINCH`
422 /// while this is on, so a size change is reported once, not twice.
423 ///
424 /// Only call this after the [`Capabilities`](super::Capabilities) record
425 /// reports [`supports(Mode::IN_BAND_RESIZE)`](super::Capabilities::supports); a
426 /// terminal that ignores the mode would otherwise leave you with no
427 /// resize events at all.
428 ///
429 /// [`Event::Resize`]: crate::event::Event::Resize
430 pub fn enable_in_band_resize(&mut self) -> io::Result<()> {
431 mode::Mode::IN_BAND_RESIZE.set(&mut self.screen)?;
432 self.state.in_band_resize = true;
433 self.state.chosen.insert(mode::Mode::IN_BAND_RESIZE);
434 self.source.lock().unwrap().set_handle_resize(false);
435 self.screen.flush()
436 }
437
438 /// Disable in-band resize notifications (DEC private mode 2048) and
439 /// flush, handing resize reporting back to the `SIGWINCH` path.
440 pub fn disable_in_band_resize(&mut self) -> io::Result<()> {
441 mode::Mode::IN_BAND_RESIZE.reset(&mut self.screen)?;
442 self.state.in_band_resize = false;
443 self.state.chosen.insert(mode::Mode::IN_BAND_RESIZE);
444 self.source.lock().unwrap().set_handle_resize(true);
445 self.screen.flush()
446 }
447
448 /// Set both the window title and icon name (`OSC 0`) and flush.
449 ///
450 /// An empty `title` clears both overrides, restoring the terminal's
451 /// defaults; the state is recorded as unset so teardown and resume skip
452 /// them. To set just one, use
453 /// [`set_window_title`](Self::set_window_title) (`OSC 2`) or
454 /// [`set_icon_title`](Self::set_icon_title) (`OSC 1`).
455 pub fn set_title(&mut self, title: &str) -> io::Result<()> {
456 ansi::title::write_window_title_and_icon(&mut self.screen, title)?;
457 let stored = (!title.is_empty()).then(|| title.to_string());
458 self.state.window_title = stored.clone();
459 self.state.icon_name = stored;
460 self.screen.flush()
461 }
462
463 /// Set the window title only (`OSC 2`) and flush.
464 ///
465 /// An empty `title` clears the override, restoring the terminal's default
466 /// window title. Unlike [`set_title`](Self::set_title) (`OSC 0`), this
467 /// leaves the icon name untouched.
468 pub fn set_window_title(&mut self, title: &str) -> io::Result<()> {
469 ansi::title::write_window_title(&mut self.screen, title)?;
470 self.state.window_title = (!title.is_empty()).then(|| title.to_string());
471 self.screen.flush()
472 }
473
474 /// Set the icon name only (`OSC 1`) and flush.
475 ///
476 /// An empty `title` clears the override, restoring the terminal's default
477 /// icon name. Unlike [`set_title`](Self::set_title) (`OSC 0`), this leaves
478 /// the window title untouched.
479 pub fn set_icon_title(&mut self, title: &str) -> io::Result<()> {
480 ansi::title::write_icon_name(&mut self.screen, title)?;
481 self.state.icon_name = (!title.is_empty()).then(|| title.to_string());
482 self.screen.flush()
483 }
484
485 /// Enter the alternate screen buffer (DECSET 1049) and flush.
486 ///
487 /// The managed area becomes the whole viewport: the screen switches to
488 /// absolute addressing and repaints in full on the next
489 /// [`render`](crate::screen::Screen::render). The normal buffer, its scrollback, and the
490 /// shell prompt are left untouched underneath and come back on
491 /// [`exit_alt_screen`](Self::exit_alt_screen).
492 ///
493 /// Cursor visibility and the Kitty keyboard stack are per-screen-buffer
494 /// on some terminals, so both are re-asserted on the newly active buffer.
495 pub fn enter_alt_screen(&mut self) -> io::Result<()> {
496 self.set_alt_screen(true)
497 }
498
499 /// Leave the alternate screen buffer (DECRST 1049) and flush, restoring
500 /// the normal buffer and its scrollback. The managed area becomes an
501 /// inline band again, addressed with relative moves.
502 pub fn exit_alt_screen(&mut self) -> io::Result<()> {
503 self.set_alt_screen(false)
504 }
505
506 /// Emit the alternate-screen switch and bring the screen and the
507 /// per-buffer modes with it. Always emits the mode; the bookkeeping runs
508 /// only on an actual transition.
509 pub(super) fn set_alt_screen(&mut self, enter: bool) -> io::Result<()> {
510 let changed = self.state.alt_screen != enter;
511 if changed && enter {
512 // Capture the inline anchor before the buffer switch hides it.
513 self.screen.save_cursor();
514 }
515 if enter {
516 mode::Mode::ALT_SCREEN_SAVE_CURSOR.set(&mut self.screen)?;
517 } else {
518 // This buffer can remain inactive through finish. Clear its frame
519 // before leaving, while preserving the choice for the main buffer.
520 if changed && self.state.kitty_keyboard_chosen {
521 kitty::write_set_kitty_keyboard(
522 &mut self.screen,
523 kitty::KittyKeyboardFlags::empty(),
524 kitty::KittyKeyboardMode::Set,
525 )?;
526 }
527 mode::Mode::ALT_SCREEN_SAVE_CURSOR.reset(&mut self.screen)?;
528 }
529 self.state.alt_screen = enter;
530 self.state.chosen.insert(mode::Mode::ALT_SCREEN_SAVE_CURSOR);
531 if changed {
532 self.screen.set_fullscreen(enter);
533 // Some terminals track DECTCEM and the Kitty keyboard stack per
534 // screen buffer, so the newly active one can disagree with what
535 // this program asked for. Re-assert both.
536 if !self.state.cursor_visible {
537 mode::Mode::CURSOR_VISIBLE.reset(&mut self.screen)?;
538 } else {
539 mode::Mode::CURSOR_VISIBLE.set(&mut self.screen)?;
540 }
541 if self.state.kitty_keyboard_chosen {
542 kitty::write_set_kitty_keyboard(
543 &mut self.screen,
544 self.state.kitty_keyboard,
545 kitty::KittyKeyboardMode::Set,
546 )?;
547 }
548 }
549 self.screen.flush()
550 }
551
552 /// Show the terminal cursor (DECSET 25) and flush.
553 ///
554 /// Also tells the screen, which hides a visible cursor around each frame's
555 /// cell diff so it does not dance across cells as the renderer
556 /// repositions it.
557 pub fn show_cursor(&mut self) -> io::Result<()> {
558 mode::Mode::CURSOR_VISIBLE.set(&mut self.screen)?;
559 self.state.cursor_visible = true;
560 self.state.chosen.insert(mode::Mode::CURSOR_VISIBLE);
561 self.screen.set_cursor_visible(true);
562 self.screen.flush()
563 }
564
565 /// Hide the terminal cursor (DECRST 25) and flush.
566 pub fn hide_cursor(&mut self) -> io::Result<()> {
567 mode::Mode::CURSOR_VISIBLE.reset(&mut self.screen)?;
568 self.state.cursor_visible = false;
569 self.state.chosen.insert(mode::Mode::CURSOR_VISIBLE);
570 self.screen.set_cursor_visible(false);
571 self.screen.flush()
572 }
573
574 /// Enable Unicode core / grapheme-cluster mode (DECSET 2027) and flush,
575 /// switching the screen to measure text per extended grapheme cluster so
576 /// it agrees with the terminal.
577 ///
578 /// Only call this after the [`Capabilities`](super::Capabilities) record
579 /// reports [`supports(Mode::UNICODE_CORE)`](super::Capabilities::supports); a
580 /// terminal that ignores the mode still measures per code point, and the
581 /// two disagreeing misplaces every cell after the first cluster on a line.
582 pub fn enable_grapheme_clusters(&mut self) -> io::Result<()> {
583 mode::Mode::UNICODE_CORE.set(&mut self.screen)?;
584 self.state.grapheme_clusters = true;
585 self.state.chosen.insert(mode::Mode::UNICODE_CORE);
586 self.screen.set_grapheme_clusters(true);
587 self.screen.flush()
588 }
589
590 /// Disable grapheme-cluster mode (DECRST 2027) and flush, returning the
591 /// screen to per-code-point (wcwidth-style) measurement.
592 pub fn disable_grapheme_clusters(&mut self) -> io::Result<()> {
593 mode::Mode::UNICODE_CORE.reset(&mut self.screen)?;
594 self.state.grapheme_clusters = false;
595 self.state.chosen.insert(mode::Mode::UNICODE_CORE);
596 self.screen.set_grapheme_clusters(false);
597 self.screen.flush()
598 }
599
600 /// Return the decoder's current Backarrow mode (DECBKM).
601 ///
602 /// Reset (`false`) is the default assumption.
603 /// [`apply_defaults`](Self::apply_defaults) applies a recorded
604 /// report to future decoding. Already queued events
605 /// keep their decoded values.
606 pub fn backspace_mode(&self) -> bool {
607 self.source.lock().unwrap().backspace_mode()
608 }
609
610 /// Set Backarrow mode (DECBKM), flush, and update legacy key decoding.
611 ///
612 /// Set (`true`) selects BS (`0x08`) for ordinary Backspace; reset (`false`)
613 /// selects DEL (`0x7f`). [`DecoderFlags`](crate::event::DecoderFlags)
614 /// choose the ambiguous interpretations. Terminals can ignore the request.
615 ///
616 /// Teardown resets an application-selected mode. Resume reapplies this
617 /// selection. After this call,
618 /// [`apply_defaults`](Self::apply_defaults) leaves decoding as
619 /// selected. The caller's options remain unchanged.
620 pub fn set_backspace_mode(&mut self, enabled: bool) -> io::Result<()> {
621 self.write_backspace_mode(enabled)?;
622 self.state.backspace_mode = enabled;
623 self.state.chosen.insert(mode::Mode::BACKARROW_KEY);
624 Ok(())
625 }
626
627 fn write_backspace_mode(&mut self, enabled: bool) -> io::Result<()> {
628 // Keep async decoding in step with the terminal mode change.
629 #[cfg(windows)]
630 let mut source = super::lock_source_interrupting_readers(&self.source, &self.source_waker)?;
631 #[cfg(not(windows))]
632 let mut source = self.source.lock().unwrap();
633 if enabled {
634 mode::Mode::BACKARROW_KEY.set(&mut self.screen)?;
635 } else {
636 mode::Mode::BACKARROW_KEY.reset(&mut self.screen)?;
637 }
638 self.screen.flush()?;
639 source.set_backspace_mode(enabled);
640 Ok(())
641 }
642
643 /// Set the per-screen-buffer Kitty keyboard enhancements and flush.
644 /// `Some(flags)` enables the selected progressive-enhancement bits;
645 /// `None` disables every enhancement.
646 ///
647 /// The Kitty stack is per-screen-buffer, so the flags are re-applied on
648 /// the newly active buffer by [`enter_alt_screen`](Self::enter_alt_screen)
649 /// / [`exit_alt_screen`](Self::exit_alt_screen), as part of the switch.
650 pub fn set_kitty_keyboard(
651 &mut self,
652 flags: Option<kitty::KittyKeyboardFlags>,
653 ) -> io::Result<()> {
654 let flags = flags.unwrap_or_else(kitty::KittyKeyboardFlags::empty);
655 kitty::write_set_kitty_keyboard(&mut self.screen, flags, kitty::KittyKeyboardMode::Set)?;
656 self.state.kitty_keyboard = flags;
657 self.state.kitty_keyboard_chosen = true;
658 self.screen.flush()
659 }
660
661 /// Set the xterm modifyOtherKeys mode (`CSI > 4 ; n m`) and flush.
662 /// Passing [`ModifyOtherKeysMode::Disabled`] resets it (`CSI > 4 m`).
663 /// The mode is recorded so [`Program::finish`](super::Program::finish)
664 /// can reset it and [`Program::resume`](super::Program::resume) re-apply
665 /// it.
666 ///
667 /// [`ModifyOtherKeysMode::Disabled`]: crate::event::ModifyOtherKeysMode::Disabled
668 pub fn set_modify_other_keys(
669 &mut self,
670 mode: crate::event::ModifyOtherKeysMode,
671 ) -> io::Result<()> {
672 use crate::event::ModifyOtherKeysMode;
673 match mode {
674 ModifyOtherKeysMode::Disabled => {
675 self.screen.write_all(xterm::RESET_MODIFY_OTHER_KEYS)?
676 }
677 ModifyOtherKeysMode::Mode1 => self.screen.write_all(xterm::SET_MODIFY_OTHER_KEYS_1)?,
678 ModifyOtherKeysMode::Mode2 => self.screen.write_all(xterm::SET_MODIFY_OTHER_KEYS_2)?,
679 }
680 self.state.modify_other_keys = mode;
681 self.state.modify_other_keys_chosen = true;
682 self.screen.flush()
683 }
684
685 /// Set the default foreground color (`OSC 10`) and flush. The color is
686 /// converted to 24-bit RGB and emitted as `rgb:RRRR/GGGG/BBBB`, and is
687 /// recorded so [`Program::finish`](super::Program::finish) can restore
688 /// the terminal default and [`Program::resume`](super::Program::resume)
689 /// can re-apply it.
690 pub fn set_foreground_color(&mut self, color: Color) -> io::Result<()> {
691 let (r, g, b) = color.to_rgb();
692 color::write_set_foreground_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
693 self.state.foreground_color = Some(color);
694 self.screen.flush()
695 }
696
697 /// Restore the terminal's default foreground color (`OSC 110`) and
698 /// flush.
699 pub fn reset_foreground_color(&mut self) -> io::Result<()> {
700 self.screen.write_all(color::RESET_FOREGROUND_COLOR)?;
701 self.state.foreground_color = None;
702 self.screen.flush()
703 }
704
705 /// Set the default background color (`OSC 11`) and flush. See
706 /// [`set_foreground_color`](Self::set_foreground_color) for
707 /// state-tracking semantics.
708 pub fn set_background_color(&mut self, color: Color) -> io::Result<()> {
709 let (r, g, b) = color.to_rgb();
710 color::write_set_background_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
711 self.state.background_color = Some(color);
712 self.screen.flush()
713 }
714
715 /// Restore the terminal's default background color (`OSC 111`) and
716 /// flush.
717 pub fn reset_background_color(&mut self) -> io::Result<()> {
718 self.screen.write_all(color::RESET_BACKGROUND_COLOR)?;
719 self.state.background_color = None;
720 self.screen.flush()
721 }
722
723 /// Set the cursor color (`OSC 12`) and flush. See
724 /// [`set_foreground_color`](Self::set_foreground_color) for
725 /// state-tracking semantics.
726 pub fn set_cursor_color(&mut self, color: Color) -> io::Result<()> {
727 let (r, g, b) = color.to_rgb();
728 color::write_set_cursor_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
729 self.state.cursor_color = Some(color);
730 self.screen.flush()
731 }
732
733 /// Restore the terminal's default cursor color (`OSC 112`) and flush.
734 pub fn reset_cursor_color(&mut self) -> io::Result<()> {
735 self.screen.write_all(color::RESET_CURSOR_COLOR)?;
736 self.state.cursor_color = None;
737 self.screen.flush()
738 }
739
740 /// Set a terminal palette color by index (`OSC 4`) and flush. The
741 /// override is tracked so [`Program::finish`](super::Program::finish) can
742 /// restore it and [`Program::resume`](super::Program::resume) re-apply it.
743 pub fn set_palette_color(&mut self, index: u8, color: Color) -> io::Result<()> {
744 let (r, g, b) = color.to_rgb();
745 color::write_set_palette_color(&mut self.screen, index, &color::xparse_rgb(r, g, b))?;
746 self.state.palette.insert(index, color);
747 self.screen.flush()
748 }
749
750 /// Reset a single terminal palette color to its default
751 /// (`OSC 104 ; index`) and flush.
752 pub fn reset_palette_color(&mut self, index: u8) -> io::Result<()> {
753 color::write_reset_palette_color(&mut self.screen, index)?;
754 self.state.palette.remove(&index);
755 self.screen.flush()
756 }
757
758 /// Reset the entire terminal palette to its defaults (`OSC 104`) and
759 /// flush, clearing every tracked palette override.
760 pub fn reset_palette_colors(&mut self) -> io::Result<()> {
761 self.screen.write_all(color::RESET_PALETTE_COLORS)?;
762 self.state.palette.clear();
763 self.screen.flush()
764 }
765
766 /// Stage the teardown of every mode currently held — non-render modes
767 /// (cursor style, mouse, paste, focus, colors, title, …) followed by the
768 /// render-coupled modes (cursor visibility, alternate screen, Kitty
769 /// keyboard, Unicode core) — returning the terminal to a clean baseline
770 /// before handing control back to the shell. Preserves the selected
771 /// state, so [`restore`](Self::restore) re-applies the same modes.
772 /// Backarrow changes also update the decoder. The caller flushes.
773 pub(super) fn reset(&mut self) -> io::Result<()> {
774 // --- Non-render modes ---
775 if self.state.cursor_style != cursor::CursorStyle::Default {
776 cursor::write_cursor_style(&mut self.screen, cursor::CursorStyle::Default)?;
777 }
778 if self.state.bracketed_paste {
779 mode::Mode::BRACKETED_PASTE.reset(&mut self.screen)?;
780 }
781 if self.state.focus_events {
782 mode::Mode::FOCUS.reset(&mut self.screen)?;
783 }
784 if let Some(tracking) = self.state.mouse {
785 self.write_mouse_modes(tracking, false)?;
786 }
787 if self.state.color_scheme_updates {
788 mode::Mode::LIGHT_DARK.reset(&mut self.screen)?;
789 }
790 if self.state.visibility_reports {
791 mode::Mode::VISIBILITY_REPORTS.reset(&mut self.screen)?;
792 }
793 if self.state.in_band_resize {
794 mode::Mode::IN_BAND_RESIZE.reset(&mut self.screen)?;
795 }
796 if self.state.chosen.contains(&mode::Mode::BACKARROW_KEY) {
797 self.write_backspace_mode(false)?;
798 }
799 if self.state.modify_other_keys != crate::event::ModifyOtherKeysMode::Disabled {
800 self.screen.write_all(xterm::RESET_MODIFY_OTHER_KEYS)?;
801 }
802 if self.state.foreground_color.is_some() {
803 self.screen.write_all(color::RESET_FOREGROUND_COLOR)?;
804 }
805 if self.state.background_color.is_some() {
806 self.screen.write_all(color::RESET_BACKGROUND_COLOR)?;
807 }
808 if self.state.cursor_color.is_some() {
809 self.screen.write_all(color::RESET_CURSOR_COLOR)?;
810 }
811 for &index in self.state.palette.keys() {
812 color::write_reset_palette_color(&mut self.screen, index)?;
813 }
814 match (&self.state.window_title, &self.state.icon_name) {
815 // Both set to the same string (e.g. via `set_title`): clear both
816 // with a single `OSC 0`.
817 (Some(w), Some(i)) if w == i => {
818 ansi::title::write_window_title_and_icon(&mut self.screen, "")?;
819 }
820 (window_title, icon_name) => {
821 if window_title.is_some() {
822 ansi::title::write_window_title(&mut self.screen, "")?;
823 }
824 if icon_name.is_some() {
825 ansi::title::write_icon_name(&mut self.screen, "")?;
826 }
827 }
828 }
829 if self.state.pointer_shape.is_some() {
830 cursor::write_set_pointer_shape(&mut self.screen, "default")?;
831 }
832 if self.state.progress.is_some() {
833 self.screen.write_all(progress::RESET_PROGRESS_BAR)?;
834 }
835
836 // --- Render-coupled modes ---
837 // Park the cursor below the managed area before any teardown, so the
838 // shell prompt lands where the user expects.
839 self.screen.park_cursor()?;
840 if !self.state.cursor_visible {
841 mode::Mode::CURSOR_VISIBLE.set(&mut self.screen)?;
842 }
843 let fullscreen = self.state.alt_screen;
844 // Clear the alt screen's kitty keyboard frame *before* leaving the alt
845 // screen — the stack is per-screen-buffer.
846 if fullscreen && self.state.kitty_keyboard_chosen {
847 kitty::write_set_kitty_keyboard(
848 &mut self.screen,
849 kitty::KittyKeyboardFlags::empty(),
850 kitty::KittyKeyboardMode::Set,
851 )?;
852 }
853 if fullscreen {
854 mode::Mode::ALT_SCREEN_SAVE_CURSOR.reset(&mut self.screen)?;
855 self.screen.restore_cursor();
856 }
857 // Now on the main screen — clear its frame too.
858 if self.state.kitty_keyboard_chosen {
859 kitty::write_set_kitty_keyboard(
860 &mut self.screen,
861 kitty::KittyKeyboardFlags::empty(),
862 kitty::KittyKeyboardMode::Set,
863 )?;
864 }
865 if self.state.grapheme_clusters {
866 mode::Mode::UNICODE_CORE.reset(&mut self.screen)?;
867 }
868 self.screen.invalidate_cursor();
869 Ok(())
870 }
871
872 /// Re-emit every mode held in the tracked state — the render-coupled
873 /// modes (Kitty keyboard, alternate screen, Unicode core, cursor
874 /// visibility) first, then the non-render modes — for any scenario where
875 /// the terminal was temporarily handed back to the shell. Pairs with
876 /// [`reset`](Self::reset). Preserves the selected state and updates the
877 /// decoder's Backarrow mode. The caller flushes.
878 pub(super) fn restore(&mut self) -> io::Result<()> {
879 // --- Render-coupled modes ---
880 let fullscreen = self.state.alt_screen;
881 if !fullscreen
882 && self
883 .state
884 .chosen
885 .contains(&mode::Mode::ALT_SCREEN_SAVE_CURSOR)
886 {
887 mode::Mode::ALT_SCREEN_SAVE_CURSOR.reset(&mut self.screen)?;
888 }
889 // Re-apply the desired kitty keyboard flags on the main screen
890 // *before* entering the alt screen — the stack is per-buffer.
891 if self.state.kitty_keyboard_chosen {
892 kitty::write_set_kitty_keyboard(
893 &mut self.screen,
894 self.state.kitty_keyboard,
895 kitty::KittyKeyboardMode::Set,
896 )?;
897 }
898 if fullscreen {
899 self.screen.save_cursor();
900 mode::Mode::ALT_SCREEN_SAVE_CURSOR.set(&mut self.screen)?;
901 }
902 // Now on the alt screen (if alt was active) — re-apply on the alt
903 // buffer too, since its stack is independent.
904 if fullscreen && self.state.kitty_keyboard_chosen {
905 kitty::write_set_kitty_keyboard(
906 &mut self.screen,
907 self.state.kitty_keyboard,
908 kitty::KittyKeyboardMode::Set,
909 )?;
910 }
911 self.restore_boolean_mode(mode::Mode::UNICODE_CORE, self.state.grapheme_clusters)?;
912 if !self.state.cursor_visible {
913 mode::Mode::CURSOR_VISIBLE.reset(&mut self.screen)?;
914 } else if self.state.chosen.contains(&mode::Mode::CURSOR_VISIBLE) {
915 mode::Mode::CURSOR_VISIBLE.set(&mut self.screen)?;
916 }
917
918 // --- Non-render modes ---
919 if self.state.cursor_style != cursor::CursorStyle::Default {
920 cursor::write_cursor_style(&mut self.screen, self.state.cursor_style)?;
921 }
922 self.restore_boolean_mode(mode::Mode::LIGHT_DARK, self.state.color_scheme_updates)?;
923 self.restore_boolean_mode(
924 mode::Mode::VISIBILITY_REPORTS,
925 self.state.visibility_reports,
926 )?;
927 self.restore_boolean_mode(mode::Mode::IN_BAND_RESIZE, self.state.in_band_resize)?;
928 if self.state.chosen.contains(&mode::Mode::BACKARROW_KEY) {
929 self.write_backspace_mode(self.state.backspace_mode)?;
930 }
931 match self.state.modify_other_keys {
932 crate::event::ModifyOtherKeysMode::Mode1 => {
933 self.screen.write_all(xterm::SET_MODIFY_OTHER_KEYS_1)?;
934 }
935 crate::event::ModifyOtherKeysMode::Mode2 => {
936 self.screen.write_all(xterm::SET_MODIFY_OTHER_KEYS_2)?;
937 }
938 crate::event::ModifyOtherKeysMode::Disabled => {
939 if self.state.modify_other_keys_chosen {
940 self.screen.write_all(xterm::RESET_MODIFY_OTHER_KEYS)?;
941 }
942 }
943 }
944 self.restore_boolean_mode(mode::Mode::BRACKETED_PASTE, self.state.bracketed_paste)?;
945 self.restore_boolean_mode(mode::Mode::FOCUS, self.state.focus_events)?;
946 if let Some(pref) = self.state.mouse {
947 self.write_mouse_modes(pref, true)?;
948 } else if self.state.chosen.contains(&mode::Mode::MOUSE_NORMAL) {
949 mode::write_reset_mode(&mut self.screen, MOUSE_MODES)?;
950 }
951 if let Some(c) = self.state.foreground_color {
952 let (r, g, b) = c.to_rgb();
953 color::write_set_foreground_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
954 }
955 if let Some(c) = self.state.background_color {
956 let (r, g, b) = c.to_rgb();
957 color::write_set_background_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
958 }
959 if let Some(c) = self.state.cursor_color {
960 let (r, g, b) = c.to_rgb();
961 color::write_set_cursor_color(&mut self.screen, &color::xparse_rgb(r, g, b))?;
962 }
963 for (&index, &c) in &self.state.palette {
964 let (r, g, b) = c.to_rgb();
965 color::write_set_palette_color(&mut self.screen, index, &color::xparse_rgb(r, g, b))?;
966 }
967 match (
968 self.state.window_title.clone(),
969 self.state.icon_name.clone(),
970 ) {
971 // Both set to the same string (e.g. via `set_title`): restore both
972 // with a single `OSC 0`.
973 (Some(w), Some(i)) if w == i => {
974 ansi::title::write_window_title_and_icon(&mut self.screen, &w)?;
975 }
976 (window_title, icon_name) => {
977 if let Some(title) = window_title {
978 ansi::title::write_window_title(&mut self.screen, &title)?;
979 }
980 if let Some(name) = icon_name {
981 ansi::title::write_icon_name(&mut self.screen, &name)?;
982 }
983 }
984 }
985 if let Some(shape) = self.state.pointer_shape.clone() {
986 cursor::write_set_pointer_shape(&mut self.screen, &shape)?;
987 }
988 if let Some(progress) = self.state.progress {
989 progress.write(&mut self.screen)?;
990 }
991 Ok(())
992 }
993
994 /// Explicit resets must survive a handoff too: a child can enable a mode
995 /// that this application selected off.
996 fn restore_boolean_mode(&mut self, mode: mode::Mode, enabled: bool) -> io::Result<()> {
997 if enabled {
998 mode.set(&mut self.screen)?;
999 } else if self.state.chosen.contains(&mode) {
1000 mode.reset(&mut self.screen)?;
1001 }
1002 Ok(())
1003 }
1004
1005 // --- Request delegates -----------------------------------------------
1006 //
1007 // Each writes a terminal query and flushes; the reply arrives later
1008 // through the event flow. Pass replies that describe the terminal
1009 // (mode, kitty keyboard, colors) to a `Capabilities` record; the
1010 // application keeps the geometry replies it needs.
1011
1012 /// Request the text-area pixel dimensions (XTWINOPS `CSI 14 t`).
1013 /// Reply: a [`Size`](crate::layout::Size) in pixels through
1014 /// [`Event::WindowPixelSize`](crate::event::Event::WindowPixelSize).
1015 pub fn request_window_pixel_size(&mut self) -> io::Result<()> {
1016 self.screen
1017 .write_all(crate::ansi::winop::REQUEST_WINDOW_PIXEL_SIZE)?;
1018 self.screen.flush()
1019 }
1020
1021 /// Request one cell's pixel width and height (XTWINOPS `CSI 16 t`).
1022 /// Reply: a [`Size`](crate::layout::Size) in pixels through
1023 /// [`Event::CellPixelSize`](crate::event::Event::CellPixelSize).
1024 pub fn request_cell_pixel_size(&mut self) -> io::Result<()> {
1025 self.screen
1026 .write_all(crate::ansi::winop::REQUEST_CELL_PIXEL_SIZE)?;
1027 self.screen.flush()
1028 }
1029
1030 /// Move the cursor to the managed area's top-left cell, request its
1031 /// physical position, and flush.
1032 ///
1033 /// The reply arrives through the event flow as
1034 /// [`Event::CursorPosition`](crate::event::Event::CursorPosition).
1035 /// Match it to this request in your read loop, then pass its position to
1036 /// [`set_origin`](Self::set_origin).
1037 ///
1038 /// Cursor reports carry no request ID. Keep origin requests separate
1039 /// from other cursor requests, including the width measurement from
1040 /// [`Probe::query_capabilities`](super::Probe::query_capabilities).
1041 /// See [`request_cursor_position`](Self::request_cursor_position) for
1042 /// the modified F3 ambiguity.
1043 ///
1044 /// Request the origin again after a resize or
1045 /// [`resume`](Self::resume), because either can move the managed area.
1046 /// In fullscreen, the origin is `(0, 0)` and this call performs no I/O.
1047 pub fn request_origin(&mut self) -> io::Result<()> {
1048 if self.screen.fullscreen() {
1049 return Ok(());
1050 }
1051 self.screen
1052 .stage_move_cursor_to(crate::layout::Position::ORIGIN);
1053 self.request_cursor_position()
1054 }
1055
1056 /// Request the terminal's active Kitty keyboard flags (`CSI ? u`).
1057 /// [`Capabilities::record`](super::Capabilities::record) records the reply.
1058 pub fn request_kitty_keyboard(&mut self) -> io::Result<()> {
1059 self.screen
1060 .write_all(crate::ansi::kitty::REQUEST_KITTY_KEYBOARD)?;
1061 self.screen.flush()
1062 }
1063
1064 /// Request the terminal's modifyOtherKeys state (`CSI ? 4 m`).
1065 /// [`Capabilities::record`](super::Capabilities::record) records the reply.
1066 pub fn request_modify_other_keys(&mut self) -> io::Result<()> {
1067 self.screen
1068 .write_all(crate::ansi::xterm::QUERY_MODIFY_OTHER_KEYS)?;
1069 self.screen.flush()
1070 }
1071
1072 /// Request the default foreground color (`OSC 10 ; ? ST`). Reply:
1073 /// [`Event::ForegroundColor`](crate::event::Event::ForegroundColor).
1074 pub fn request_foreground_color(&mut self) -> io::Result<()> {
1075 self.screen
1076 .write_all(crate::ansi::color::REQUEST_FOREGROUND_COLOR)?;
1077 self.screen.flush()
1078 }
1079
1080 /// Request the default background color (`OSC 11 ; ? ST`). Reply:
1081 /// [`Event::BackgroundColor`](crate::event::Event::BackgroundColor).
1082 pub fn request_background_color(&mut self) -> io::Result<()> {
1083 self.screen
1084 .write_all(crate::ansi::color::REQUEST_BACKGROUND_COLOR)?;
1085 self.screen.flush()
1086 }
1087
1088 /// Request the cursor color (`OSC 12 ; ? ST`). Reply:
1089 /// [`Event::CursorColor`](crate::event::Event::CursorColor).
1090 pub fn request_cursor_color(&mut self) -> io::Result<()> {
1091 self.screen
1092 .write_all(crate::ansi::color::REQUEST_CURSOR_COLOR)?;
1093 self.screen.flush()
1094 }
1095
1096 /// Request a terminal palette color by index (`OSC 4 ; index ; ? ST`).
1097 /// Reply: `OSC 4 ; index ; rgb:... ST`.
1098 pub fn request_palette_color(&mut self, index: u8) -> io::Result<()> {
1099 crate::ansi::color::write_request_palette_color(&mut self.screen, index)?;
1100 self.screen.flush()
1101 }
1102
1103 /// Request a terminal mode's current setting (DECRQM). Reply:
1104 /// [`Event::ModeReport`](crate::event::Event::ModeReport).
1105 ///
1106 /// The reply's [`ModeSetting`](crate::ansi::mode::ModeSetting) reports whether
1107 /// the mode is set, reset, or permanently fixed. A permanently reset mode
1108 /// is recognized but can never be enabled, so check
1109 /// [`ModeSetting::is_available`](crate::ansi::mode::ModeSetting::is_available)
1110 /// before relying on it.
1111 pub fn request_mode(&mut self, mode: crate::ansi::mode::Mode) -> io::Result<()> {
1112 mode.request(&mut self.screen)?;
1113 self.screen.flush()
1114 }
1115
1116 /// Request the cursor position (`CSI 6 n`). Reply:
1117 /// [`Event::CursorPosition`](crate::event::Event::CursorPosition).
1118 ///
1119 /// A report on row 1, column 1 to 16, has the same bytes as legacy
1120 /// modified F3. For that report, the decoder emits a
1121 /// [`KeyPress`](crate::event::Event::KeyPress) for F3 just before the
1122 /// cursor event. The code that waits for the report drops that key.
1123 /// A real modified F3 can have the same bytes. If it arrives while a
1124 /// standard request waits, the code that drops the ambiguous key can lose
1125 /// that input.
1126 ///
1127 /// For a reply distinct from modified F3, use
1128 /// [`request_extended_cursor_position`](Self::request_extended_cursor_position)
1129 /// on terminals that support DECXCPR.
1130 pub fn request_cursor_position(&mut self) -> io::Result<()> {
1131 self.screen
1132 .write_all(crate::ansi::status::REQUEST_CURSOR_POSITION)?;
1133 self.screen.flush()
1134 }
1135
1136 /// Request the extended cursor position (`CSI ? 6 n`) and flush.
1137 ///
1138 /// DECXCPR replies produce [`Event::CursorPosition`](crate::event::Event::CursorPosition)
1139 /// with zero-based cell coordinates and a one-based page number when
1140 /// reported. An absent page is zero. The private reply distinguishes cursor
1141 /// reports from modified F3.
1142 ///
1143 /// A Primary DA request follows DECXCPR. Its reply arrives after the
1144 /// cursor report, or alone when the terminal ignores DECXCPR. Read that
1145 /// reply before you call
1146 /// [`Probe::query_capabilities`](super::Probe::query_capabilities), which uses Primary DA
1147 /// to end its batch.
1148 pub fn request_extended_cursor_position(&mut self) -> io::Result<()> {
1149 self.screen
1150 .write_all(crate::ansi::status::REQUEST_EXTENDED_CURSOR_POSITION)?;
1151 self.screen
1152 .write_all(crate::ansi::ctrl::REQUEST_PRIMARY_DA)?;
1153 self.screen.flush()
1154 }
1155
1156 /// Request the current cursor style (DECRQSS for `DECSCUSR`). Reply:
1157 /// [`Event::SettingReport`](crate::event::Event::SettingReport) carrying
1158 /// [`SettingReport::CursorStyle`](crate::event::SettingReport::CursorStyle).
1159 ///
1160 /// The reply says what the cursor is *now*, so ask before changing it if
1161 /// you mean to put it back. Teardown writes [`CursorStyle::Default`],
1162 /// which returns the cursor the terminal's user configured; keeping the
1163 /// one this session found is yours to do, because only you know when you
1164 /// asked.
1165 ///
1166 /// A terminal that does not implement DECRQSS may answer
1167 /// [`SettingReport::Unrecognized`](crate::event::SettingReport::Unrecognized)
1168 /// or stay silent, so treat the reply as optional.
1169 ///
1170 /// Read the answer with [`CursorStyle::shape`] and
1171 /// [`CursorStyle::blinking`], the same terms
1172 /// [`set_cursor_style`](Self::set_cursor_style) takes.
1173 pub fn request_cursor_style(&mut self) -> io::Result<()> {
1174 crate::ansi::status::write_decrqss(&mut self.screen, " q")?;
1175 self.screen.flush()
1176 }
1177
1178 /// Request the current color scheme (`CSI ? 996 n`): whether the
1179 /// terminal's scheme is dark or light. This reports only the dark/light
1180 /// preference, not the actual colors. Reply:
1181 /// [`Event::ColorScheme`](crate::event::Event::ColorScheme).
1182 pub fn request_color_scheme(&mut self) -> io::Result<()> {
1183 self.screen
1184 .write_all(crate::ansi::status::REQUEST_LIGHT_DARK_REPORT)?;
1185 self.screen.flush()
1186 }
1187
1188 /// Set the system clipboard contents (`OSC 52 ; c`). `data` is
1189 /// base64-encoded for transport.
1190 pub fn set_system_clipboard(&mut self, data: &[u8]) -> io::Result<()> {
1191 crate::ansi::clipboard::write_set_clipboard(
1192 &mut self.screen,
1193 crate::ansi::clipboard::SYSTEM_CLIPBOARD,
1194 data,
1195 )?;
1196 self.screen.flush()
1197 }
1198
1199 /// Set the primary selection contents (`OSC 52 ; p`). `data` is
1200 /// base64-encoded for transport.
1201 pub fn set_primary_clipboard(&mut self, data: &[u8]) -> io::Result<()> {
1202 crate::ansi::clipboard::write_set_clipboard(
1203 &mut self.screen,
1204 crate::ansi::clipboard::PRIMARY_CLIPBOARD,
1205 data,
1206 )?;
1207 self.screen.flush()
1208 }
1209
1210 /// Request the system clipboard contents (`OSC 52 ; c ; ?`). Reply:
1211 /// [`Event::ClipboardStart`](crate::event::Event::ClipboardStart), raw
1212 /// [`Event::ClipboardChunk`](crate::event::Event::ClipboardChunk) bytes,
1213 /// then [`Event::ClipboardEnd`](crate::event::Event::ClipboardEnd).
1214 pub fn request_system_clipboard(&mut self) -> io::Result<()> {
1215 crate::ansi::clipboard::write_request_clipboard(
1216 &mut self.screen,
1217 crate::ansi::clipboard::SYSTEM_CLIPBOARD,
1218 )?;
1219 self.screen.flush()
1220 }
1221
1222 /// Request the primary selection contents (`OSC 52 ; p ; ?`). Reply:
1223 /// [`Event::ClipboardStart`](crate::event::Event::ClipboardStart), raw
1224 /// [`Event::ClipboardChunk`](crate::event::Event::ClipboardChunk) bytes,
1225 /// then [`Event::ClipboardEnd`](crate::event::Event::ClipboardEnd).
1226 pub fn request_primary_clipboard(&mut self) -> io::Result<()> {
1227 crate::ansi::clipboard::write_request_clipboard(
1228 &mut self.screen,
1229 crate::ansi::clipboard::PRIMARY_CLIPBOARD,
1230 )?;
1231 self.screen.flush()
1232 }
1233}
1234
1235fn unix_time() -> io::Result<u64> {
1236 std::time::SystemTime::now()
1237 .duration_since(std::time::UNIX_EPOCH)
1238 .map(|elapsed| elapsed.as_secs())
1239 .map_err(io::Error::other)
1240}