uncurses/program/mod.rs
1//! [`Program`] — the interactive terminal session.
2//!
3//! `Program<I, O>` is what you build a terminal application on. It owns the
4//! things a session needs and a [`Screen`] to render with:
5//!
6//! - a [`Terminal`] for the raw-mode lifecycle,
7//! - an [`EventSource`] for decoded input,
8//! - the terminal and input modes (mouse, bracketed paste, focus reporting,
9//! in-band resize, titles, colors, cursor style, keyboard enhancements),
10//! tracked so they can be torn down on a shell handoff and re-applied after,
11//! - the inline origin that maps mouse coordinates into the managed area.
12//!
13//! Reads hand each event to you without changes. Replies to terminal
14//! queries are ordinary events: your read loop matches them to its requests.
15//! Capability discovery belongs to the application:
16//! [`Probe::query_capabilities`] returns a [`Capabilities`] record that your read loop
17//! fills, and [`Program::apply_defaults`] acts on it using [`ProgramOptions`].
18//!
19//! Drawing is not on `Program`. Reach the renderer with
20//! [`screen_mut`](Program::screen_mut) and call
21//! [`render`](Screen::render) on it — that is the only `render` in the crate,
22//! and the only `flush`.
23//!
24//! Construction is inert: [`Program::new`] (and the [`stdio`](Program::stdio)
25//! / [`open`](Program::open) shortcuts) only build the program. Begin a
26//! session with [`Program::init`], which enters raw mode. Nothing is probed
27//! unless you ask: call [`Probe::query_capabilities`] for that. Teardown is
28//! explicit: there is **no** `Drop`.
29//! Hand the terminal back to the shell with [`Program::finish`] (consume),
30//! [`Program::pause`] (keep, e.g. to shell out), or Unix `Program::suspend`
31//! (pause, then stop the process with `SIGTSTP`); resume a
32//! paused/suspended program with [`Program::resume`].
33//!
34//! ```no_run
35//! use uncurses::program::Program;
36//! use uncurses::style::Style;
37//! use uncurses::text::TextSurface;
38//!
39//! # fn main() -> std::io::Result<()> {
40//! let mut program = Program::open()?; // build over /dev/tty
41//! program.init()?; // raw mode; probes nothing on its own
42//! program.enter_alt_screen()?;
43//!
44//! let screen = program.screen_mut();
45//! screen.set_str((0, 0), "hello", Style::default());
46//! screen.render()?;
47//!
48//! let event = program.read_event()?; // handle input and replies in your loop
49//! program.finish()?; // restore the terminal
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! # Options and defaults
55//!
56//! [`new`](Program::new), [`stdio`](Program::stdio), and [`open`](Program::open)
57//! store [`ProgramOptions::default`]. Use [`with_options`](Program::with_options)
58//! to select bracketed paste, mouse tracking, and the initial color profile.
59//! [`init`](Program::init) applies those startup settings.
60//!
61//! A [`Probe`] selects explicit capability queries. Create it from
62//! [`Program::env`], write through [`Program::screen_mut`], then flush.
63//! Record replies with [`Capabilities::record`] and detect the final
64//! [`Event::PrimaryDeviceAttributes`] in your input loop.
65//! [`ProgramOptions`] selects which supported defaults to adopt.
66//! Pass the record to [`apply_defaults`](Program::apply_defaults).
67//!
68//! [`Terminal`]: crate::terminal::Terminal
69//! [`EventSource`]: crate::event::EventSource
70
71mod modes;
72mod probe;
73mod state;
74#[cfg(test)]
75mod tests;
76
77pub use crate::ansi::program_resume::ProgramResume;
78pub use crate::ansi::program_status::{ProgramStatus, ProgramStatusKind, ProgramStatusState};
79pub use probe::Probe;
80pub use state::{Capabilities, State};
81
82use std::io::{self, Write};
83use std::sync::{Arc, Mutex};
84use std::time::Duration;
85
86use bitflags::bitflags;
87
88use crate::ansi::{mode, progress};
89use crate::color::Profile;
90use crate::event::Input;
91use crate::event::{DecoderFlags, Event, EventSource};
92use crate::layout::Position;
93use crate::renderer::Optimizations;
94use crate::screen::Screen;
95use crate::terminal::{AsTerminalHandle, Terminal};
96
97/// An interactive terminal session composing a [`Terminal`], an
98/// [`EventSource`], and a [`Screen`] to render with. See
99/// the [module documentation](self) for the lifecycle.
100///
101/// `Program` is [`Send`] and [`Sync`] whenever its input and output handles
102/// are, so it can be moved onto another thread or held across an `.await`
103/// point in a multi-threaded async runtime.
104///
105/// [`Terminal`]: crate::terminal::Terminal
106/// [`EventSource`]: crate::event::EventSource
107pub struct Program<I, O>
108where
109 I: Input,
110 O: Write,
111{
112 /// Owns the raw-mode state and answers the fd-bound queries (window size,
113 /// is-a-tty). Never written through: output goes through `screen`, which
114 /// holds a copy of the same handle, so one staging buffer keeps
115 /// everything in order.
116 terminal: Terminal<I, O>,
117 /// The renderer. Reach it with [`screen`](Self::screen) /
118 /// [`screen_mut`](Self::screen_mut).
119 screen: Screen<O>,
120 /// Input source behind the read path ([`Self::read_event`] and friends).
121 /// Held in an `Arc<Mutex<_>>`; the lock is uncontended in the common
122 /// single-reader case.
123 source: Arc<Mutex<EventSource<I>>>,
124 /// Interrupts a shared reader without acquiring its source lock.
125 source_waker: crate::event::Waker,
126 state: state::State,
127 options: ProgramOptions,
128 /// Physical screen coordinate (0-based, from the terminal's top-left) of
129 /// the managed area's top-left cell, set by
130 /// [`set_origin`](Self::set_origin). Only meaningful inline; fullscreen
131 /// [`origin`](Self::origin) is always `(0, 0)`.
132 origin: Position,
133}
134
135/// Options for session setup.
136///
137/// Constructors store these options. [`Program::init`] applies startup
138/// settings, and [`Program::apply_defaults`] uses the adoption preferences.
139/// [`Probe`] selects queries.
140#[derive(Debug, Clone)]
141pub struct ProgramOptions {
142 /// Enable bracketed paste at init. Defaults to `true`.
143 pub bracketed_paste: bool,
144 /// Enable mouse tracking at init with the given [`MouseTracking`] extras
145 /// (see [`Program::enable_mouse`]). The request is emitted unconditionally;
146 /// terminals ignore modes they do not support and degrade gracefully.
147 /// Defaults to `None` (mouse tracking off).
148 pub mouse: Option<MouseTracking>,
149 /// Select the initial renderer color profile.
150 ///
151 /// `None` detects the profile from the environment and output terminal.
152 /// `Some(profile)` uses the supplied profile, including for redirected output.
153 /// [`apply_defaults`](Program::apply_defaults) can later upgrade it
154 /// to truecolor when the terminal reports direct-color support.
155 pub color_profile: Option<Profile>,
156 /// How to read the ambiguous legacy keys.
157 ///
158 /// Defaults to [`empty`](DecoderFlags::empty). LF reads as Ctrl+J;
159 /// [`DecoderFlags::LF_IS_ENTER`] selects Enter instead. See [`DecoderFlags`]
160 /// for all mappings. Use [`Program::set_decoder_flags`] to change the
161 /// active flags after initialization.
162 pub legacy_keys: DecoderFlags,
163 /// Adopt grapheme-cluster mode when the capability record confirms support.
164 ///
165 /// Defaults to `true`. Takes effect through [`Program::apply_defaults`],
166 /// after a support reply. An explicit mode choice takes precedence.
167 pub prefer_grapheme_clusters: bool,
168 /// Adopt in-band resize when the capability record confirms support.
169 ///
170 /// Defaults to `true`. Takes effect through [`Program::apply_defaults`],
171 /// after a support reply. An explicit mode choice takes precedence.
172 pub prefer_in_band_resize: bool,
173 /// Adopt synchronized output when the capability record confirms support.
174 ///
175 /// Defaults to `true`. Takes effect through [`Program::apply_defaults`].
176 /// The first supporting record settles this preference, including an
177 /// opt-out. Use this preference for a session-wide choice.
178 pub prefer_synchronized_output: bool,
179}
180
181bitflags! {
182 /// Optional mouse tracking features layered on top of basic button
183 /// tracking.
184 ///
185 /// When mouse tracking is enabled, button-event tracking (presses,
186 /// releases, and drags) and SGR encoding are always requested; these flags
187 /// add optional extras on top. An empty set ([`MouseTracking::empty()`])
188 /// means basic tracking with no extras.
189 ///
190 /// Mouse tracking is turned *off* through [`Program::disable_mouse`] or by
191 /// leaving [`ProgramOptions::mouse`] as `None`, not by an empty flag set.
192 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
193 pub struct MouseTracking: u8 {
194 /// Report pointer motion with no button held (any-event tracking).
195 /// Adds hover motion on terminals that support it.
196 const MOTION = 1 << 0;
197 /// Request pixel coordinates (SGR-pixel). Terminals that support it
198 /// report pixels; the rest fall back to SGR cell coordinates.
199 const PIXELS = 1 << 1;
200 }
201}
202
203/// A progress indication reported to the terminal with `OSC 9;4`, shown in
204/// the taskbar, tab, or window chrome by terminals that support it.
205///
206/// Set it with [`Program::set_progress_state`] and take it down with
207/// [`Program::reset_progress_state`]. Percentages are clamped to `0..=100`
208/// when emitted.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210pub enum ProgressState {
211 /// Determinate progress at the given percentage.
212 Normal(u8),
213 /// A failed operation, at the given percentage. Usually red.
214 Error(u8),
215 /// An operation needing attention, at the given percentage. Usually
216 /// yellow. Named "paused" in ConEmu, which originated the sequence.
217 Warning(u8),
218 /// Work in progress of unknown duration. Usually a pulsing bar.
219 Indeterminate,
220}
221
222impl ProgressState {
223 /// Emit the `OSC 9;4` sequence for this state.
224 fn write<W: Write>(self, w: &mut W) -> io::Result<()> {
225 match self {
226 ProgressState::Normal(p) => progress::write_set_progress_bar(w, p.into()),
227 ProgressState::Error(p) => progress::write_set_error_progress_bar(w, p.into()),
228 ProgressState::Warning(p) => progress::write_set_warning_progress_bar(w, p.into()),
229 ProgressState::Indeterminate => w.write_all(progress::SET_INDETERMINATE_PROGRESS_BAR),
230 }
231 }
232}
233
234impl Default for ProgramOptions {
235 fn default() -> Self {
236 Self {
237 bracketed_paste: true,
238 prefer_grapheme_clusters: true,
239 prefer_in_band_resize: true,
240 prefer_synchronized_output: true,
241 ..Self::new()
242 }
243 }
244}
245
246impl ProgramOptions {
247 /// Create options with optional modes and decoder flags disabled.
248 ///
249 /// The color profile is detected from the environment and output.
250 /// [`Program::init`] still enters raw mode and sets up the session.
251 /// [`Default`] also enables bracketed paste.
252 pub const fn new() -> Self {
253 Self {
254 bracketed_paste: false,
255 mouse: None,
256 color_profile: None,
257 legacy_keys: DecoderFlags::empty(),
258 prefer_grapheme_clusters: false,
259 prefer_in_band_resize: false,
260 prefer_synchronized_output: false,
261 }
262 }
263}
264
265impl<I, O> Program<I, O>
266where
267 I: Input,
268 O: Write,
269{
270 // --- The terminal ----------------------------------------------------
271
272 /// Borrow the [`Terminal`] this program drives.
273 ///
274 /// Shared on purpose: the program keeps ownership, so its record of the
275 /// modes and raw-mode state it emitted stays the authority for
276 /// [`finish`](Self::finish). Everything the program itself changes has a
277 /// method here. The borrow is not a seal, though. `Terminal::set_state`
278 /// takes `&self`, so a caller holding this can still change raw mode
279 /// behind the program's back, and the restore record will not know.
280 pub fn terminal(&self) -> &Terminal<I, O> {
281 &self.terminal
282 }
283
284 /// The environment the [`Terminal`] reads variables from.
285 ///
286 /// This is where the answers the terminal never sends live: `TERM`,
287 /// `COLORTERM`, `TERM_PROGRAM`, and the rest. Shorthand for
288 /// [`terminal().env()`](crate::terminal::Terminal::env), and the
289 /// counterpart to [`Capabilities`], which holds only what the terminal
290 /// answered.
291 pub fn env(&self) -> &dyn crate::terminal::Env {
292 self.terminal.env()
293 }
294
295 // --- The screen ------------------------------------------------------
296
297 /// Borrow the [`Screen`] this program renders with.
298 pub fn screen(&self) -> &Screen<O> {
299 &self.screen
300 }
301
302 /// Borrow the [`Screen`] mutably — this is how you draw.
303 ///
304 /// ```no_run
305 /// # use uncurses::program::Program;
306 /// # use uncurses::style::Style;
307 /// # use uncurses::text::TextSurface;
308 /// # fn main() -> std::io::Result<()> {
309 /// # let mut program = Program::open()?;
310 /// let screen = program.screen_mut();
311 /// screen.set_str((0, 0), "hello", Style::default());
312 /// screen.render()?;
313 /// # Ok(())
314 /// # }
315 /// ```
316 ///
317 /// Drawing is the expected use. The screen's *render properties* are also
318 /// reachable here, and setting one directly moves only how frames are
319 /// drawn — it emits no mode, so the terminal never hears about it. Prefer
320 /// the program's own [`enter_alt_screen`](Self::enter_alt_screen),
321 /// [`hide_cursor`](Self::hide_cursor), and
322 /// [`enable_grapheme_clusters`](Self::enable_grapheme_clusters), which
323 /// emit the mode *and* move the property together. Teardown follows what
324 /// this program emitted, so a property changed behind its back is not
325 /// undone by [`finish`](Self::finish) and does not survive a
326 /// [`pause`](Self::pause) / [`resume`](Self::resume) round trip.
327 pub fn screen_mut(&mut self) -> &mut Screen<O> {
328 &mut self.screen
329 }
330
331 // --- Event delegates -------------------------------------------------
332
333 /// Return the event source's current legacy decoder flags.
334 ///
335 /// See [`DecoderFlags`] for the available key mappings.
336 pub fn decoder_flags(&self) -> DecoderFlags {
337 self.source.lock().unwrap().decoder_flags()
338 }
339
340 /// Set the legacy decoder flags for subsequent input decoding.
341 ///
342 /// Already-decoded events keep their values, including events returned
343 /// through [`unread_event`](Self::unread_event). This updates the shared
344 /// [`EventSource`] and leaves [`ProgramOptions::legacy_keys`] unchanged.
345 /// Terminal modes remain unchanged.
346 pub fn set_decoder_flags(&mut self, flags: DecoderFlags) {
347 self.source.lock().unwrap().set_decoder_flags(flags);
348 }
349
350 /// Drive the input source for up to `timeout`, returning whether any
351 /// event became available. See [`EventSource::poll`].
352 pub fn poll_event(&self, timeout: Option<Duration>) -> io::Result<bool> {
353 let ready = self.source.lock().unwrap().poll(timeout)?;
354 Ok(ready)
355 }
356
357 /// Take the next queued event without reading more input.
358 /// Returns `Ok(None)` when the queue is empty. See [`EventSource::try_read`].
359 ///
360 /// Events returned through [`unread_event`](Self::unread_event) come
361 /// first. Reads never write to the terminal and never change program
362 /// state.
363 pub fn try_read_event(&mut self) -> io::Result<Option<Event>> {
364 Ok(self.source.lock().unwrap().try_read())
365 }
366
367 /// Block until the next event. See [`EventSource::read`].
368 pub fn read_event(&mut self) -> io::Result<Event> {
369 self.source.lock().unwrap().read()
370 }
371
372 /// Return an event to the front of the input queue, so the next
373 /// [`read_event`](Self::read_event) / [`try_read_event`](Self::try_read_event)
374 /// yields it before anything already queued. Restore a batch in original
375 /// order by unreading in reverse.
376 ///
377 /// The shared [`event_source`](Self::event_source) holds these events,
378 /// so synchronous readers and async streams can receive them.
379 ///
380 /// A synchronous reader blocked on the shared source is interrupted, so
381 /// this call does not wait for input.
382 pub fn unread_event(&mut self, event: Event) {
383 lock_source_interrupting_readers(&self.source, &self.source_waker)
384 .unwrap_or_else(|_| self.source.lock().unwrap())
385 .unread(event);
386 }
387
388 /// A shared handle to the input source behind
389 /// [`read_event`](Self::read_event) and friends, for driving input from a
390 /// separate reader over the same decoder rather than a second one racing
391 /// the same file descriptor.
392 ///
393 /// The main use is async input: build an
394 /// [`EventStream`](crate::event::EventStream) with
395 /// [`EventStream::from_shared`](crate::event::EventStream::from_shared) from
396 /// this handle and poll it on your executor.
397 ///
398 /// Sharing one source between a live reader and the program's own
399 /// [`read_event`](Self::read_event) is best-effort: an event goes to
400 /// whichever consumer drains it first, so pick one reader in steady state.
401 pub fn event_source(&self) -> Arc<Mutex<EventSource<I>>> {
402 Arc::clone(&self.source)
403 }
404
405 /// Build an async [`EventStream`](crate::event::EventStream) over this
406 /// program's input, for reading events with `events.next().await` inside a
407 /// `select!` on any executor. The stream shares the program's decoder, so
408 /// it does not race a second reader on the same file descriptor.
409 ///
410 /// The stream yields the same events as [`read_event`](Self::read_event).
411 /// Pass each event to [`Capabilities::record`] while a capability batch
412 /// is pending. Read through the stream *or* through `read_event` in steady
413 /// state, not both at once: a shared source hands each event to whichever
414 /// consumer drains it first.
415 #[cfg(feature = "async")]
416 pub fn event_stream(&self) -> crate::event::EventStream<I>
417 where
418 I: 'static,
419 {
420 crate::event::EventStream::from_shared(Arc::clone(&self.source))
421 }
422
423 // --- Inline origin ----------------------------------------------------
424
425 /// Read-only record of the modes and settings selected through this
426 /// program.
427 pub fn state(&self) -> &State {
428 &self.state
429 }
430
431 /// The physical screen coordinate of the managed area's top-left cell.
432 /// Always `(0, 0)` in fullscreen. Inline it holds the last value given to
433 /// [`set_origin`](Self::set_origin), and `(0, 0)` before that.
434 pub fn origin(&self) -> Position {
435 if self.screen.fullscreen() {
436 Position::ORIGIN
437 } else {
438 self.origin
439 }
440 }
441
442 /// Store `position` as the origin, with its row clipped so that the
443 /// managed area stays on a terminal `terminal_height` rows tall.
444 fn clip_origin(&mut self, position: Position, terminal_height: Option<u16>) {
445 let height = self.screen.size().height;
446 let max_y = terminal_height.unwrap_or(height).saturating_sub(height);
447 self.origin = Position::new(position.x, position.y.min(max_y));
448 }
449
450 /// Translate a mouse event's screen coordinates into coordinates relative
451 /// to the managed area, by subtracting the [`origin`](Self::origin).
452 /// In fullscreen, the coordinates do not change.
453 pub fn mouse_to_origin(&self, mouse: crate::event::Mouse) -> crate::event::Mouse {
454 let origin = self.origin();
455 crate::event::Mouse::new(
456 mouse.x.saturating_sub(origin.x),
457 mouse.y.saturating_sub(origin.y),
458 mouse.button,
459 mouse.modifiers,
460 )
461 }
462
463 // --- Capabilities -----------------------------------------------------
464
465 /// Apply supported defaults from a record using the retained program options.
466 ///
467 /// Call after the application's capability batch, or when later replies
468 /// update the record.
469 ///
470 /// - Synchronized output, grapheme clusters, and in-band resize are
471 /// adopted when the terminal reports them and the matching
472 /// `prefer_*` field in [`ProgramOptions`] is set. Grapheme clusters and
473 /// in-band resize are terminal modes, so adoption writes them.
474 /// - A Backarrow mode report sets how the decoder reads Backspace, until
475 /// [`set_backspace_mode`](Self::set_backspace_mode) selects a mode.
476 /// - A measured East Asian Ambiguous width updates
477 /// [`Screen::set_ambiguous_wide`]. Rewrite existing text after a change.
478 /// - An `RGB` or `Tc` termcap reply upgrades the color profile to true
479 /// color.
480 ///
481 /// Each call sets ambiguous width and upgrades the color profile when the
482 /// record reports `RGB` or `Tc`. Call [`Screen::set_ambiguous_wide`] or
483 /// [`Screen::set_color_profile`] after it to choose your own values.
484 ///
485 /// Adoption happens only while the application has taken no position of
486 /// its own. Calling a mode's `enable_*` or `disable_*` method, in either
487 /// direction and at any point, settles it, and adoption settles it too. So
488 /// each mode is adopted at most once, and never against an explicit
489 /// choice. A synchronized-output opt-out also settles that preference.
490 /// The retained options and the record stay unchanged.
491 pub fn apply_defaults(&mut self, caps: &Capabilities) -> io::Result<()> {
492 use crate::ansi::mode::Mode;
493 for (&mode, &setting) in &caps.modes {
494 if mode == Mode::BACKARROW_KEY
495 && setting.is_recognized()
496 && !self.state.chosen.contains(&mode)
497 {
498 self.source
499 .lock()
500 .unwrap()
501 .set_backspace_mode(setting.is_set());
502 }
503 if !setting.is_available() || self.state.chosen.contains(&mode) {
504 continue;
505 }
506 match mode {
507 // Render-affecting and free to adopt: the screen emits the
508 // 2026 markers per frame, so knowing the terminal understands
509 // them is all it takes. Turn it off for the session with
510 // `prefer_synchronized_output`, or per frame with
511 // [`Screen::set_synchronized_output`].
512 Mode::SYNCHRONIZED_OUTPUT => {
513 if self.options.prefer_synchronized_output {
514 self.screen.set_synchronized_output(true);
515 }
516 self.state.chosen.insert(mode);
517 }
518 Mode::UNICODE_CORE if self.options.prefer_grapheme_clusters => {
519 self.enable_grapheme_clusters()?;
520 }
521 Mode::IN_BAND_RESIZE if self.options.prefer_in_band_resize => {
522 self.enable_in_band_resize()?;
523 }
524 _ => {}
525 }
526 }
527 if let Some(width) = caps.eaw_width {
528 self.screen.set_ambiguous_wide(width == 2);
529 }
530 // The profile, not the record, answers "can I send 24-bit color":
531 // the environment can establish it just as well.
532 if caps.supports_termcap("RGB") || caps.supports_termcap("Tc") {
533 self.screen
534 .set_color_profile(crate::color::Profile::TrueColor);
535 }
536 Ok(())
537 }
538
539 /// Enable [`TABS`](Optimizations::TABS) and [`BS`](Optimizations::BS),
540 /// the two optimizations raw mode makes safe: `\t` and `\x08` now
541 /// reach the terminal intact instead of being rewritten on the way.
542 ///
543 /// On Unix raw mode clears `OPOST`, disabling output processing
544 /// wholesale, so the kernel can no longer expand `\t` into spaces. On
545 /// Windows it enables virtual-terminal processing, which is the same
546 /// bargain. So this reads no terminal state: `make_raw` returning
547 /// `Ok` *is* the answer, and no `$TERM` baseline carries either flag,
548 /// so a program that never enters raw mode emits escape sequences
549 /// instead.
550 ///
551 /// [`ONLCR`](Optimizations::ONLCR) is deliberately untouched. Raw
552 /// mode makes it false, but it is opt-in: a caller who set it knows
553 /// something about their output path that we do not, and clobbering
554 /// that is worse than the bytes it would save.
555 ///
556 /// Runs after every successful `make_raw`, including
557 /// [`resume`](Self::resume), since whatever ran while paused may have
558 /// put the terminal back into cooked mode.
559 #[cfg(any(unix, windows))]
560 fn enable_tabs_and_bs(&mut self) {
561 let opts = self.screen.optimizations().with_tabs(true).with_bs(true);
562 self.screen.set_optimizations(opts);
563 }
564
565 /// Apply the explicit profile or detect one from the environment.
566 fn apply_color_profile(&mut self, profile: Option<Profile>, is_tty: bool) {
567 let profile = profile.unwrap_or_else(|| Profile::detect_from(self.terminal.env(), is_tty));
568 self.screen.set_color_profile(profile);
569 }
570
571 /// Reconcile the terminal's hardware tab stops with the every-eight
572 /// columns layout the renderer assumes. A prior program may have left
573 /// arbitrary stops behind, which would make the `HT` (`\t`) moves the
574 /// cursor planner emits land on the wrong columns. Modern terminals
575 /// reset in one cursor-safe write via DECST8C; the rest get the
576 /// portable TBC-then-HTS fallback. Staged and flushed so it reaches
577 /// the terminal even when capability queries are disabled.
578 ///
579 /// Runs whether or not `TABS` is set: the stops belong to the
580 /// terminal, not to our willingness to use them, so turning `TABS` on
581 /// later must not find them unknown.
582 fn reset_tab_stops(&mut self) -> io::Result<()> {
583 if Optimizations::supports_decst8c(self.terminal.env()) {
584 self.screen
585 .write_all(crate::ansi::screen::SET_TAB_EVERY_8_COLUMNS)?;
586 } else {
587 let width = self.screen.size().width;
588 crate::ansi::screen::write_reset_tab_stops_every_8(&mut self.screen, width)?;
589 }
590 self.screen.flush()
591 }
592
593 /// Reset LNM (ANSI mode 20) so a `\n` moves the cursor down without
594 /// touching the column.
595 ///
596 /// The cursor planner emits a bare `\n` for downward moves and, unless
597 /// [`Optimizations::ONLCR`] says the host's line discipline expands it,
598 /// carries the column across unchanged. A terminal left in LNM by a prior
599 /// program breaks that assumption on the terminal's side of the wire:
600 /// LNM makes a *received* LF return to column 1, so every horizontal leg
601 /// planned after a `\n` starts from a column the cursor is not in.
602 ///
603 /// No query first. LNM reset is the documented default — the VT510
604 /// manual asks that it be kept reset — so there is nothing to learn from
605 /// asking, and this follows [`reset_tab_stops`](Self::reset_tab_stops) in
606 /// imposing the state the planner assumes rather than trusting what it
607 /// inherited. Reset on every raw-mode entry, since a program run during a
608 /// [`pause`](Self::pause) can set it while we are not looking.
609 ///
610 /// Staged and flushed so it reaches the terminal even when capability
611 /// queries are disabled.
612 fn reset_lnm(&mut self) -> io::Result<()> {
613 mode::Mode::LINE_FEED_NEW_LINE.reset(&mut self.screen)?;
614 self.screen.flush()
615 }
616
617 /// Hand the terminal back: reset every staged mode and the managed area to defaults, and flush. The
618 /// caller restores the saved raw-mode state afterward.
619 fn teardown(&mut self) -> io::Result<()> {
620 self.reset()?;
621 self.screen.flush()
622 }
623}
624
625impl<I, O> Program<I, O>
626where
627 I: Input + Copy,
628 O: Write + Copy,
629{
630 /// Build the screen and event source over `terminal`, sizing the managed
631 /// area to `size`. The color profile and renderer optimizations are
632 /// detected from the terminal's environment. The terminal is
633 /// left as-is.
634 fn with_render(
635 terminal: Terminal<I, O>,
636 size: (u16, u16),
637 options: ProgramOptions,
638 ) -> io::Result<Self> {
639 let source = Arc::new(Mutex::new(EventSource::new(terminal.input())?));
640 Ok(Self::render_with_source(terminal, size, source, options))
641 }
642
643 fn render_with_source(
644 terminal: Terminal<I, O>,
645 size: (u16, u16),
646 source: Arc<Mutex<EventSource<I>>>,
647 options: ProgramOptions,
648 ) -> Self {
649 let env = terminal.env();
650 // Provisional profile; init reapplies it with the real
651 // output-is-tty signal via apply_color_profile.
652 let color_profile = Profile::detect_from(env, true);
653 let optimizations = Optimizations::from_env(env);
654 let mut screen = Screen::new(terminal.output(), size);
655 screen.set_color_profile(color_profile);
656 screen.set_optimizations(optimizations);
657 let source_waker = source.lock().unwrap().waker();
658 Self {
659 terminal,
660 screen,
661 source,
662 source_waker,
663 state: state::State::default(),
664 options,
665 origin: Position::ORIGIN,
666 }
667 }
668}
669
670impl<I, O> Program<I, O>
671where
672 I: Input + Copy,
673 O: Write + Copy + AsTerminalHandle,
674{
675 /// Construct a program over `terminal` without touching the terminal:
676 /// size the screen to it and create an [`EventSource`] on its input
677 /// half. The terminal is left as-is; call [`Self::init`] to enter raw
678 /// mode and begin a session.
679 pub fn new(terminal: Terminal<I, O>) -> io::Result<Self> {
680 Self::with_options(terminal, ProgramOptions::default())
681 }
682
683 /// Construct a program with explicit session options.
684 ///
685 /// Construction stores `options` and leaves terminal modes unchanged.
686 /// Call [`Self::init`] to enter raw mode and apply startup settings.
687 /// [`Self::apply_defaults`] uses the stored adoption preferences.
688 pub fn with_options(terminal: Terminal<I, O>, options: ProgramOptions) -> io::Result<Self> {
689 let ws = terminal.get_window_size()?;
690 Self::with_render(terminal, (ws.col, ws.row), options)
691 }
692
693 /// Build a program with an existing shared input source.
694 ///
695 /// Use the previous program's [`event_source`](Self::event_source) to
696 /// preserve queued events and incomplete input sequences across a handoff.
697 /// Pause the previous program first, then resume it after this program
698 /// finishes. Read from the shared source through one program at a time.
699 ///
700 /// Like [`Self::new`], this leaves terminal modes unchanged.
701 ///
702 /// # Errors
703 ///
704 /// Returns an error if the terminal size cannot be read.
705 ///
706 /// ```no_run
707 /// # fn main() -> std::io::Result<()> {
708 /// use uncurses::{program::{Program, ProgramOptions}, terminal::Terminal};
709 ///
710 /// let mut main = Program::open()?;
711 /// main.init()?;
712 /// main.pause()?;
713 /// let mut dialog = Program::with_event_source(
714 /// Terminal::open()?,
715 /// main.event_source(),
716 /// ProgramOptions::default(),
717 /// )?;
718 /// dialog.init()?;
719 /// dialog.finish()?;
720 /// main.resume()?;
721 /// main.finish()
722 /// # }
723 /// ```
724 pub fn with_event_source(
725 terminal: Terminal<I, O>,
726 source: Arc<Mutex<EventSource<I>>>,
727 options: ProgramOptions,
728 ) -> io::Result<Self> {
729 let ws = terminal.get_window_size()?;
730 Ok(Self::render_with_source(
731 terminal,
732 (ws.col, ws.row),
733 source,
734 options,
735 ))
736 }
737
738 /// Begin a session: enter raw mode and apply the stored startup settings.
739 ///
740 /// Call once after construction, before rendering.
741 /// Adoption preferences take effect through [`Self::apply_defaults`].
742 pub fn init(&mut self) -> io::Result<()> {
743 // The decoder is the only thing that can act on this, and it is
744 // behind the source, so the option is carried there as it is taken.
745 #[cfg(windows)]
746 lock_source_interrupting_readers(&self.source, &self.source_waker)?
747 .set_decoder_flags(self.options.legacy_keys);
748 #[cfg(not(windows))]
749 self.set_decoder_flags(self.options.legacy_keys);
750 self.enter_raw_mode()?;
751 self.enable_tabs_and_bs();
752 self.reset_lnm()?;
753 self.autoresize()?;
754 // Apply the env color profile on every path so output downsamples
755 // correctly even when capability queries are skipped. Disable color
756 // when the output is not a terminal unless an explicit profile is set.
757 let is_tty = self.terminal.is_terminal().1;
758 self.apply_color_profile(self.options.color_profile, is_tty);
759 self.reset_tab_stops()?;
760 if self.options.bracketed_paste {
761 self.enable_bracketed_paste()?;
762 }
763 if let Some(tracking) = self.options.mouse {
764 self.enable_mouse(tracking)?;
765 }
766 Ok(())
767 }
768
769 /// Query the current terminal window size through
770 /// [`Terminal::get_window_size`]. The operating system answers, so
771 /// nothing is written to the terminal. Some platforms (the Windows
772 /// console) report no pixel dimensions. Use
773 /// [`request_window_pixel_size`](Self::request_window_pixel_size) there.
774 pub fn get_window_size(&self) -> io::Result<crate::terminal::Winsize> {
775 self.terminal.get_window_size()
776 }
777
778 /// Set the inline [`origin`](Self::origin).
779 ///
780 /// To measure the origin, call [`request_origin`](Self::request_origin).
781 /// It moves the cursor to the managed area's top-left cell and requests
782 /// the cursor position:
783 ///
784 /// ```no_run
785 /// # fn main() -> std::io::Result<()> {
786 /// # let mut program = uncurses::program::Program::stdio()?;
787 /// program.request_origin()?;
788 /// # Ok(())
789 /// # }
790 /// ```
791 ///
792 /// Pass the position of the matching
793 /// [`CursorPosition`](crate::event::Event::CursorPosition) reply here.
794 /// Cursor reports carry no request ID and arrive in request order, so
795 /// count the origin requests that wait for a reply. Measure again after a
796 /// resize and after [`resume`](Self::resume), because both can move the
797 /// managed area.
798 ///
799 /// The row is clipped so that the managed area stays on screen: its top
800 /// row is at most `terminal_height - area_height`. This covers a reply to
801 /// a request sent before the first render, which can report a row that
802 /// the render then scrolls. The terminal height comes from
803 /// [`get_window_size`](Self::get_window_size). When that query fails, the
804 /// row becomes 0.
805 pub fn set_origin(&mut self, position: Position) {
806 let terminal_height = self.terminal.get_window_size().ok().map(|ws| ws.row);
807 self.clip_origin(position, terminal_height);
808 }
809
810 /// Re-query the terminal size and resize the managed area to fit: the full
811 /// terminal size when fullscreen, or the terminal width with the current
812 /// managed height preserved when inline. Nothing is asked of the
813 /// terminal: this reads the size the operating system already knows.
814 ///
815 /// When the managed area already fits the queried size, this returns
816 /// without resizing and without repainting, so it is safe to call on every
817 /// resize report. Terminals send a report per pixel of a window drag while
818 /// the cell grid only changes at cell boundaries, so most reports ask for a
819 /// size the area already has. To re-establish the area whatever the size,
820 /// call [`Screen::resize`](crate::screen::Screen::resize) instead.
821 pub fn autoresize(&mut self) -> io::Result<()> {
822 let Ok(ws) = self.terminal.get_window_size() else {
823 // Keep the current size when the query fails rather than
824 // collapsing the managed area to zero.
825 return Ok(());
826 };
827 let height = match self.screen.fullscreen() {
828 true => ws.row,
829 false => self.screen.size().height,
830 };
831 // Terminals report resizes for changes that leave the cell grid alone
832 // (a font change that keeps rows and columns, a window move on some
833 // terminals). This runs on every one of them, and `Screen::resize`
834 // repaints unconditionally, so skip the ones that change nothing
835 // rather than flickering on each. A caller that wants the repaint
836 // anyway calls `Screen::resize` directly.
837 if self.screen.size() == crate::layout::Size::new(ws.col, height) {
838 return Ok(());
839 }
840 self.screen.resize((ws.col, height));
841 Ok(())
842 }
843
844 /// Consume the program and hand the terminal back to the shell: tear down
845 /// every staged mode, reset the managed area, flush, and restore the
846 /// terminal's prior state.
847 ///
848 /// The terminal state is restored even when the teardown writes fail, so a
849 /// broken pipe cannot leave the terminal in raw mode. The teardown error is
850 /// still returned.
851 pub fn finish(mut self) -> io::Result<()> {
852 self.pause()
853 }
854
855 /// Hand the terminal back to the shell without consuming the program,
856 /// e.g. to run a child process. Re-enter with [`Self::resume`]. Like
857 /// [`Self::finish`] but keeps the program so the session can continue, and
858 /// likewise restores the terminal even when the teardown writes fail.
859 pub fn pause(&mut self) -> io::Result<()> {
860 // Restore even when teardown fails: the caller asked for the terminal
861 // back, and a failed write to it is not a reason to keep it raw.
862 let teardown = self.teardown();
863 #[cfg(not(windows))]
864 let restore = self.terminal.restore();
865 #[cfg(windows)]
866 let restore = {
867 use windows_sys::Win32::System::Console::ENABLE_VIRTUAL_TERMINAL_INPUT;
868 let source = Arc::clone(&self.source);
869 let mut source = lock_source_interrupting_readers(&source, &self.source_waker);
870 let restore = self.terminal.restore_with_input(|mode| {
871 if let Ok(source) = source.as_mut() {
872 source.set_vt_input(mode & ENABLE_VIRTUAL_TERMINAL_INPUT != 0);
873 }
874 });
875 source.map(|_| ()).and(restore)
876 };
877 teardown.and(restore)
878 }
879
880 /// Re-acquire the terminal after a [`Self::pause`] or Unix `suspend`:
881 /// re-enter raw mode, refit the managed area to the current viewport, re-apply
882 /// the saved render state and modes, and force a full repaint.
883 ///
884 /// Re-enables [`TABS`](Optimizations::TABS) and
885 /// [`BS`](Optimizations::BS) and resets the hardware tab stops, since
886 /// whatever ran while paused may have disturbed both.
887 pub fn resume(&mut self) -> io::Result<()> {
888 self.enter_raw_mode()?;
889 self.enable_tabs_and_bs();
890 self.reset_lnm()?;
891 self.autoresize()?;
892 self.reset_tab_stops()?;
893 self.restore()?;
894 self.screen.invalidate();
895 self.screen.flush()
896 }
897
898 fn enter_raw_mode(&mut self) -> io::Result<()> {
899 #[cfg(windows)]
900 let source = Arc::clone(&self.source);
901 #[cfg(windows)]
902 let mut source = lock_source_interrupting_readers(&source, &self.source_waker)?;
903 self.terminal.make_raw()?;
904 #[cfg(windows)]
905 source.set_vt_input(true);
906 #[cfg(unix)]
907 self.source
908 .lock()
909 .unwrap()
910 .set_handle_resize(!self.state.in_band_resize);
911 Ok(())
912 }
913
914 /// Suspend the process: [`pause`](Self::pause) the program, then stop
915 /// the process with `SIGTSTP`. Returns once the process is
916 /// foregrounded again; the caller should then call [`Self::resume`].
917 #[cfg(unix)]
918 pub fn suspend(&mut self) -> io::Result<()> {
919 self.pause()?;
920 // SAFETY: raise is async-signal-safe.
921 unsafe { libc::raise(libc::SIGTSTP) };
922 Ok(())
923 }
924}
925
926fn lock_source_interrupting_readers<'a, I: Input>(
927 source: &'a Mutex<EventSource<I>>,
928 waker: &crate::event::Waker,
929) -> io::Result<std::sync::MutexGuard<'a, EventSource<I>>> {
930 // A retrying reader can consume a wake and keep or reacquire the lock.
931 loop {
932 match source.try_lock() {
933 Err(std::sync::TryLockError::WouldBlock) => {
934 waker.wake()?;
935 std::thread::yield_now();
936 }
937 result => return Ok(result.unwrap()),
938 }
939 }
940}
941
942impl Program<crate::terminal::Stdin, crate::terminal::Stdout> {
943 /// Build a program over the process stdio (`stdin` + `stdout`).
944 pub fn stdio() -> io::Result<Self> {
945 Self::new(Terminal::stdio())
946 }
947}
948
949impl Program<crate::terminal::TtyInput, crate::terminal::TtyOutput> {
950 /// Build a program over the controlling terminal (`/dev/tty`, or
951 /// `CONIN$`/`CONOUT$` on Windows), useful when stdio is redirected.
952 pub fn open() -> io::Result<Self> {
953 Self::new(Terminal::open()?)
954 }
955}