pub struct Program<I, O>{ /* private fields */ }Expand description
An interactive terminal session composing a Terminal, an
EventSource, and a Screen to render with. See
the module documentation for the lifecycle.
Program is Send and Sync whenever its input and output handles
are, so it can be moved onto another thread or held across an .await
point in a multi-threaded async runtime.
Implementations§
Source§impl<I: Input, O: Write> Program<I, O>
impl<I: Input, O: Write> Program<I, O>
Sourcepub fn set_program_status(&mut self, report: &ProgramStatus<'_>) -> Result<()>
pub fn set_program_status(&mut self, report: &ProgramStatus<'_>) -> Result<()>
Send a complete OSC 7501 program status report and flush.
Reports replace the addressed record. Include its app, title, and
message on every update when they should remain present. Use
ProgramStatusState::CLEAR to
remove the record and its descendants; a root clear removes all records.
The terminal owns record lifetime. Pause, resume, screen switches, and finish leave these reports unchanged, so done and error records can survive exit. Explicit discovery is optional; unsupported terminals ignore reports.
Invalid fields return io::ErrorKind::InvalidInput before output.
See write_program_status
for validation and protocol limits.
Sourcepub fn request_program_status(&mut self) -> Result<()>
pub fn request_program_status(&mut self) -> Result<()>
Query OSC 7501 support and flush, without waiting for a reply.
The reply is Event::ProgramStatus,
with the accepted state and kind names.
Capabilities::record records support
and both lists. To include this query in a capability batch, set
Probe::program_status.
Initialization sends no queries.
Sourcepub fn supports_program_resume(&self) -> bool
pub fn supports_program_resume(&self) -> bool
Return whether the terminal accepts OSC 7577 program resume reports.
Support is present when the environment of the
Terminal has a nonempty
OSC7577_TOKEN. The protocol has
no query. A supporting terminal can still choose not to resume.
Sourcepub fn set_program_resume(&mut self, report: &ProgramResume<'_>) -> Result<()>
pub fn set_program_resume(&mut self, report: &ProgramResume<'_>) -> Result<()>
Report how the terminal can resume this process (OSC 7577) and flush.
The report names std::process::id and the current time, and
carries a hash of the terminal’s token. The token itself is not
written. Without a token, this writes nothing and returns Ok.
Report again when the command changes, when the working directory
in report.cwd changes, and after resume. Pause,
resume, and finish leave the record unchanged.
A command that the protocol cannot carry, such as one with a control
character or one that exceeds the
limits, returns
io::ErrorKind::InvalidInput. Before it returns, this method sends
a clear report, so the terminal does not resume an earlier command.
An invalid token returns the same error and writes nothing.
Sourcepub fn clear_program_resume(&mut self) -> Result<()>
pub fn clear_program_resume(&mut self) -> Result<()>
Remove this process’s resume record (OSC 7577) and flush.
Call it when the user ends the program. When the program exits because
of SIGHUP, SIGTERM, or the loss of its terminal, keep the record:
the terminal needs it to resume the program. Without a
token, this writes nothing and returns Ok. An invalid token returns
io::ErrorKind::InvalidInput and writes nothing.
Sourcepub fn set_cursor_style(
&mut self,
shape: CursorShape,
blinking: bool,
) -> Result<()>
pub fn set_cursor_style( &mut self, shape: CursorShape, blinking: bool, ) -> Result<()>
Sourcepub fn reset_cursor_style(&mut self) -> Result<()>
pub fn reset_cursor_style(&mut self) -> Result<()>
Hand the cursor style back to the terminal (DECSCUSR parameter 0)
and flush.
Every terminal surveyed for this reads its own configuration here: kitty, foot, rio, Alacritty, wezterm, VTE, Konsole and Windows Terminal all restore the shape their user chose. xterm documents the parameter as a blinking block instead, so what appears is the terminal’s to decide either way.
That makes this the portable way to undo
set_cursor_style without knowing what
came before. To put back the cursor this session found rather than
the one the user configured, read it with
request_cursor_style before changing
it and set that style again.
Sourcepub fn set_pointer_shape(&mut self, shape: &str) -> Result<()>
pub fn set_pointer_shape(&mut self, shape: &str) -> Result<()>
Set the pointer (mouse cursor) shape (OSC 22) and flush.
shape is a pointer shape name such as "default", "text", or
"pointer". The shape is recorded for save/restore.
Sourcepub fn reset_pointer_shape(&mut self) -> Result<()>
pub fn reset_pointer_shape(&mut self) -> Result<()>
Reset the pointer (mouse cursor) shape to the terminal default
(OSC 22 ; default) and flush.
Uses the explicit "default" shape name rather than an empty one: some
terminals don’t treat an empty OSC 22 as a reset.
Sourcepub fn set_progress_state(&mut self, progress: ProgressState) -> Result<()>
pub fn set_progress_state(&mut self, progress: ProgressState) -> Result<()>
Report progress to the terminal (OSC 9;4) and flush.
Terminals that support it show the progress in the taskbar, tab, or
window chrome; the rest ignore the sequence. Percentages are clamped
to 0..=100.
The state is recorded for save/restore: it is removed on a shell
handoff (pause, Unix suspend,
finish) and re-reported by
resume. Take it down with
reset_progress_state.
Sourcepub fn reset_progress_state(&mut self) -> Result<()>
pub fn reset_progress_state(&mut self) -> Result<()>
Remove the progress report (OSC 9;4;0) and flush.
Sourcepub fn enable_mouse(&mut self, tracking: MouseTracking) -> Result<()>
pub fn enable_mouse(&mut self, tracking: MouseTracking) -> Result<()>
Enable mouse tracking and flush.
This emits exactly what is asked for and does not consult terminal
Capabilities. Unsupported modes are ignored by
the terminal, and because the mode requests are mutually exclusive, each
terminal settles on the most capable variant it understands:
- Tracking: button (
1000) and button-event (1002) are always requested, so a terminal reports drag where it can and plain clicks otherwise. WithMouseTracking::MOTION, any-event tracking (1003) is added on top, so motion without a button held is reported where supported. - Encoding: SGR (
1006) is always requested, since the legacy byte encoding caps coordinates at 223 and SGR is universally supported. WithMouseTracking::PIXELS, SGR-pixel (1016) is added; terminals that support it report pixel coordinates, and the rest fall back to SGR cell coordinates.
Pass MouseTracking::empty() for basic button tracking with no
extras. To turn mouse tracking off, call disable_mouse.
To learn which variant a terminal actually chose, read the
Capabilities record (for example
supports(Mode::MOUSE_SGR_PIXEL) to
tell whether pixels or cells will arrive). When pixel reporting is active, a
Mouse event’s pixel coordinates can be converted
to cells with mouse_pixel_to_cell.
Mouse coordinates are physical screen coordinates. Inline, call
request_origin and pass the matching reply to
set_origin, so
mouse_to_origin can map them into it.
The request is recorded for save/restore.
Sourcepub fn disable_mouse(&mut self) -> Result<()>
pub fn disable_mouse(&mut self) -> Result<()>
Disable all mouse tracking modes and encodings, and flush.
Sourcepub fn enable_bracketed_paste(&mut self) -> Result<()>
pub fn enable_bracketed_paste(&mut self) -> Result<()>
Enable bracketed paste mode (DEC private mode 2004) and flush.
Sourcepub fn disable_bracketed_paste(&mut self) -> Result<()>
pub fn disable_bracketed_paste(&mut self) -> Result<()>
Disable bracketed paste mode (DEC private mode 2004) and flush.
Sourcepub fn enable_focus_events(&mut self) -> Result<()>
pub fn enable_focus_events(&mut self) -> Result<()>
Enable focus in/out reporting (DEC private mode 1004) and flush.
Sourcepub fn disable_focus_events(&mut self) -> Result<()>
pub fn disable_focus_events(&mut self) -> Result<()>
Disable focus in/out reporting (DEC private mode 1004) and flush.
Sourcepub fn enable_color_scheme_updates(&mut self) -> Result<()>
pub fn enable_color_scheme_updates(&mut self) -> Result<()>
Enable color-scheme update notifications (DEC private mode 2031) and
flush. The terminal then sends a CSI ? 997 ; {1|2} n report
whenever the user or operating system switches between dark and
light schemes; these surface as Event::ColorScheme. The report
indicates only the dark/light preference, not the actual colors.
Sourcepub fn disable_color_scheme_updates(&mut self) -> Result<()>
pub fn disable_color_scheme_updates(&mut self) -> Result<()>
Disable color-scheme update notifications (DEC private mode 2031) and flush.
Sourcepub fn enable_visibility_reports(&mut self) -> Result<()>
pub fn enable_visibility_reports(&mut self) -> Result<()>
Enable terminal visibility reports (DEC private mode 2033) and flush.
The terminal then sends a CSI ? 999 ; {1|2} n report whenever the
view stops being observable or becomes observable again, which the
decoder surfaces as Event::Visibility. Being covered by another
window, scrolled out of a tab, or on a minimized window all count.
The report is advisory and asymmetric: Visibility::Hidden means
the terminal knows nothing can be seen, so a render can be skipped,
while Visibility::Visible only means it may be observable. A
terminal that never reports is therefore treated as visible, which is
what makes ignoring this mode safe.
Visibility is independent of focus: an unfocused window is usually still visible.
Sourcepub fn disable_visibility_reports(&mut self) -> Result<()>
pub fn disable_visibility_reports(&mut self) -> Result<()>
Disable terminal visibility reports (DEC private mode 2033) and flush.
Sourcepub fn request_visibility(&mut self) -> Result<()>
pub fn request_visibility(&mut self) -> Result<()>
Ask the terminal to report its visibility once and flush.
The reply arrives as Event::Visibility, the same event the
unsolicited reports use. This does not enable or disable
enable_visibility_reports, so it
is the way to read visibility without subscribing to changes. A
terminal that does not implement DEC private mode 2033 answers
nothing at all, so never block waiting for this reply.
Sourcepub fn enable_in_band_resize(&mut self) -> Result<()>
pub fn enable_in_band_resize(&mut self) -> Result<()>
Enable in-band resize notifications (DEC private mode 2048) and
flush. The terminal then reports every surface size change in-band
as a CSI 48 ; height ; width ; ypixel ; xpixel t sequence, which
the decoder surfaces as Event::Resize — no SIGWINCH handler
required. The event source stops synthesizing resizes from SIGWINCH
while this is on, so a size change is reported once, not twice.
Only call this after the Capabilities record
reports supports(Mode::IN_BAND_RESIZE); a
terminal that ignores the mode would otherwise leave you with no
resize events at all.
Sourcepub fn disable_in_band_resize(&mut self) -> Result<()>
pub fn disable_in_band_resize(&mut self) -> Result<()>
Disable in-band resize notifications (DEC private mode 2048) and
flush, handing resize reporting back to the SIGWINCH path.
Sourcepub fn set_title(&mut self, title: &str) -> Result<()>
pub fn set_title(&mut self, title: &str) -> Result<()>
Set both the window title and icon name (OSC 0) and flush.
An empty title clears both overrides, restoring the terminal’s
defaults; the state is recorded as unset so teardown and resume skip
them. To set just one, use
set_window_title (OSC 2) or
set_icon_title (OSC 1).
Sourcepub fn set_window_title(&mut self, title: &str) -> Result<()>
pub fn set_window_title(&mut self, title: &str) -> Result<()>
Set the window title only (OSC 2) and flush.
An empty title clears the override, restoring the terminal’s default
window title. Unlike set_title (OSC 0), this
leaves the icon name untouched.
Sourcepub fn set_icon_title(&mut self, title: &str) -> Result<()>
pub fn set_icon_title(&mut self, title: &str) -> Result<()>
Set the icon name only (OSC 1) and flush.
An empty title clears the override, restoring the terminal’s default
icon name. Unlike set_title (OSC 0), this leaves
the window title untouched.
Sourcepub fn enter_alt_screen(&mut self) -> Result<()>
pub fn enter_alt_screen(&mut self) -> Result<()>
Enter the alternate screen buffer (DECSET 1049) and flush.
The managed area becomes the whole viewport: the screen switches to
absolute addressing and repaints in full on the next
render. The normal buffer, its scrollback, and the
shell prompt are left untouched underneath and come back on
exit_alt_screen.
Cursor visibility and the Kitty keyboard stack are per-screen-buffer on some terminals, so both are re-asserted on the newly active buffer.
Sourcepub fn exit_alt_screen(&mut self) -> Result<()>
pub fn exit_alt_screen(&mut self) -> Result<()>
Leave the alternate screen buffer (DECRST 1049) and flush, restoring the normal buffer and its scrollback. The managed area becomes an inline band again, addressed with relative moves.
Sourcepub fn show_cursor(&mut self) -> Result<()>
pub fn show_cursor(&mut self) -> Result<()>
Show the terminal cursor (DECSET 25) and flush.
Also tells the screen, which hides a visible cursor around each frame’s cell diff so it does not dance across cells as the renderer repositions it.
Sourcepub fn hide_cursor(&mut self) -> Result<()>
pub fn hide_cursor(&mut self) -> Result<()>
Hide the terminal cursor (DECRST 25) and flush.
Sourcepub fn enable_grapheme_clusters(&mut self) -> Result<()>
pub fn enable_grapheme_clusters(&mut self) -> Result<()>
Enable Unicode core / grapheme-cluster mode (DECSET 2027) and flush, switching the screen to measure text per extended grapheme cluster so it agrees with the terminal.
Only call this after the Capabilities record
reports supports(Mode::UNICODE_CORE); a
terminal that ignores the mode still measures per code point, and the
two disagreeing misplaces every cell after the first cluster on a line.
Sourcepub fn disable_grapheme_clusters(&mut self) -> Result<()>
pub fn disable_grapheme_clusters(&mut self) -> Result<()>
Disable grapheme-cluster mode (DECRST 2027) and flush, returning the screen to per-code-point (wcwidth-style) measurement.
Sourcepub fn backspace_mode(&self) -> bool
pub fn backspace_mode(&self) -> bool
Return the decoder’s current Backarrow mode (DECBKM).
Reset (false) is the default assumption.
apply_defaults applies a recorded
report to future decoding. Already queued events
keep their decoded values.
Sourcepub fn set_backspace_mode(&mut self, enabled: bool) -> Result<()>
pub fn set_backspace_mode(&mut self, enabled: bool) -> Result<()>
Set Backarrow mode (DECBKM), flush, and update legacy key decoding.
Set (true) selects BS (0x08) for ordinary Backspace; reset (false)
selects DEL (0x7f). DecoderFlags
choose the ambiguous interpretations. Terminals can ignore the request.
Teardown resets an application-selected mode. Resume reapplies this
selection. After this call,
apply_defaults leaves decoding as
selected. The caller’s options remain unchanged.
Sourcepub fn set_kitty_keyboard(
&mut self,
flags: Option<KittyKeyboardFlags>,
) -> Result<()>
pub fn set_kitty_keyboard( &mut self, flags: Option<KittyKeyboardFlags>, ) -> Result<()>
Set the per-screen-buffer Kitty keyboard enhancements and flush.
Some(flags) enables the selected progressive-enhancement bits;
None disables every enhancement.
The Kitty stack is per-screen-buffer, so the flags are re-applied on
the newly active buffer by enter_alt_screen
/ exit_alt_screen, as part of the switch.
Sourcepub fn set_modify_other_keys(&mut self, mode: ModifyOtherKeysMode) -> Result<()>
pub fn set_modify_other_keys(&mut self, mode: ModifyOtherKeysMode) -> Result<()>
Set the xterm modifyOtherKeys mode (CSI > 4 ; n m) and flush.
Passing ModifyOtherKeysMode::Disabled resets it (CSI > 4 m).
The mode is recorded so Program::finish
can reset it and Program::resume re-apply
it.
Sourcepub fn set_foreground_color(&mut self, color: Color) -> Result<()>
pub fn set_foreground_color(&mut self, color: Color) -> Result<()>
Set the default foreground color (OSC 10) and flush. The color is
converted to 24-bit RGB and emitted as rgb:RRRR/GGGG/BBBB, and is
recorded so Program::finish can restore
the terminal default and Program::resume
can re-apply it.
Sourcepub fn reset_foreground_color(&mut self) -> Result<()>
pub fn reset_foreground_color(&mut self) -> Result<()>
Restore the terminal’s default foreground color (OSC 110) and
flush.
Sourcepub fn set_background_color(&mut self, color: Color) -> Result<()>
pub fn set_background_color(&mut self, color: Color) -> Result<()>
Set the default background color (OSC 11) and flush. See
set_foreground_color for
state-tracking semantics.
Sourcepub fn reset_background_color(&mut self) -> Result<()>
pub fn reset_background_color(&mut self) -> Result<()>
Restore the terminal’s default background color (OSC 111) and
flush.
Sourcepub fn set_cursor_color(&mut self, color: Color) -> Result<()>
pub fn set_cursor_color(&mut self, color: Color) -> Result<()>
Set the cursor color (OSC 12) and flush. See
set_foreground_color for
state-tracking semantics.
Sourcepub fn reset_cursor_color(&mut self) -> Result<()>
pub fn reset_cursor_color(&mut self) -> Result<()>
Restore the terminal’s default cursor color (OSC 112) and flush.
Sourcepub fn set_palette_color(&mut self, index: u8, color: Color) -> Result<()>
pub fn set_palette_color(&mut self, index: u8, color: Color) -> Result<()>
Set a terminal palette color by index (OSC 4) and flush. The
override is tracked so Program::finish can
restore it and Program::resume re-apply it.
Sourcepub fn reset_palette_color(&mut self, index: u8) -> Result<()>
pub fn reset_palette_color(&mut self, index: u8) -> Result<()>
Reset a single terminal palette color to its default
(OSC 104 ; index) and flush.
Sourcepub fn reset_palette_colors(&mut self) -> Result<()>
pub fn reset_palette_colors(&mut self) -> Result<()>
Reset the entire terminal palette to its defaults (OSC 104) and
flush, clearing every tracked palette override.
Sourcepub fn request_window_pixel_size(&mut self) -> Result<()>
pub fn request_window_pixel_size(&mut self) -> Result<()>
Request the text-area pixel dimensions (XTWINOPS CSI 14 t).
Reply: a Size in pixels through
Event::WindowPixelSize.
Sourcepub fn request_cell_pixel_size(&mut self) -> Result<()>
pub fn request_cell_pixel_size(&mut self) -> Result<()>
Request one cell’s pixel width and height (XTWINOPS CSI 16 t).
Reply: a Size in pixels through
Event::CellPixelSize.
Sourcepub fn request_origin(&mut self) -> Result<()>
pub fn request_origin(&mut self) -> Result<()>
Move the cursor to the managed area’s top-left cell, request its physical position, and flush.
The reply arrives through the event flow as
Event::CursorPosition.
Match it to this request in your read loop, then pass its position to
set_origin.
Cursor reports carry no request ID. Keep origin requests separate
from other cursor requests, including the width measurement from
Probe::query_capabilities.
See request_cursor_position for
the modified F3 ambiguity.
Request the origin again after a resize or
resume, because either can move the managed area.
In fullscreen, the origin is (0, 0) and this call performs no I/O.
Sourcepub fn request_kitty_keyboard(&mut self) -> Result<()>
pub fn request_kitty_keyboard(&mut self) -> Result<()>
Request the terminal’s active Kitty keyboard flags (CSI ? u).
Capabilities::record records the reply.
Sourcepub fn request_modify_other_keys(&mut self) -> Result<()>
pub fn request_modify_other_keys(&mut self) -> Result<()>
Request the terminal’s modifyOtherKeys state (CSI ? 4 m).
Capabilities::record records the reply.
Sourcepub fn request_foreground_color(&mut self) -> Result<()>
pub fn request_foreground_color(&mut self) -> Result<()>
Request the default foreground color (OSC 10 ; ? ST). Reply:
Event::ForegroundColor.
Sourcepub fn request_background_color(&mut self) -> Result<()>
pub fn request_background_color(&mut self) -> Result<()>
Request the default background color (OSC 11 ; ? ST). Reply:
Event::BackgroundColor.
Sourcepub fn request_cursor_color(&mut self) -> Result<()>
pub fn request_cursor_color(&mut self) -> Result<()>
Request the cursor color (OSC 12 ; ? ST). Reply:
Event::CursorColor.
Sourcepub fn request_palette_color(&mut self, index: u8) -> Result<()>
pub fn request_palette_color(&mut self, index: u8) -> Result<()>
Request a terminal palette color by index (OSC 4 ; index ; ? ST).
Reply: OSC 4 ; index ; rgb:... ST.
Sourcepub fn request_mode(&mut self, mode: Mode) -> Result<()>
pub fn request_mode(&mut self, mode: Mode) -> Result<()>
Request a terminal mode’s current setting (DECRQM). Reply:
Event::ModeReport.
The reply’s ModeSetting reports whether
the mode is set, reset, or permanently fixed. A permanently reset mode
is recognized but can never be enabled, so check
ModeSetting::is_available
before relying on it.
Sourcepub fn request_cursor_position(&mut self) -> Result<()>
pub fn request_cursor_position(&mut self) -> Result<()>
Request the cursor position (CSI 6 n). Reply:
Event::CursorPosition.
A report on row 1, column 1 to 16, has the same bytes as legacy
modified F3. For that report, the decoder emits a
KeyPress for F3 just before the
cursor event. The code that waits for the report drops that key.
A real modified F3 can have the same bytes. If it arrives while a
standard request waits, the code that drops the ambiguous key can lose
that input.
For a reply distinct from modified F3, use
request_extended_cursor_position
on terminals that support DECXCPR.
Sourcepub fn request_extended_cursor_position(&mut self) -> Result<()>
pub fn request_extended_cursor_position(&mut self) -> Result<()>
Request the extended cursor position (CSI ? 6 n) and flush.
DECXCPR replies produce Event::CursorPosition
with zero-based cell coordinates and a one-based page number when
reported. An absent page is zero. The private reply distinguishes cursor
reports from modified F3.
A Primary DA request follows DECXCPR. Its reply arrives after the
cursor report, or alone when the terminal ignores DECXCPR. Read that
reply before you call
Probe::query_capabilities, which uses Primary DA
to end its batch.
Sourcepub fn request_cursor_style(&mut self) -> Result<()>
pub fn request_cursor_style(&mut self) -> Result<()>
Request the current cursor style (DECRQSS for DECSCUSR). Reply:
Event::SettingReport carrying
SettingReport::CursorStyle.
The reply says what the cursor is now, so ask before changing it if
you mean to put it back. Teardown writes CursorStyle::Default,
which returns the cursor the terminal’s user configured; keeping the
one this session found is yours to do, because only you know when you
asked.
A terminal that does not implement DECRQSS may answer
SettingReport::Unrecognized
or stay silent, so treat the reply as optional.
Read the answer with CursorStyle::shape and
CursorStyle::blinking, the same terms
set_cursor_style takes.
Sourcepub fn request_color_scheme(&mut self) -> Result<()>
pub fn request_color_scheme(&mut self) -> Result<()>
Request the current color scheme (CSI ? 996 n): whether the
terminal’s scheme is dark or light. This reports only the dark/light
preference, not the actual colors. Reply:
Event::ColorScheme.
Sourcepub fn set_system_clipboard(&mut self, data: &[u8]) -> Result<()>
pub fn set_system_clipboard(&mut self, data: &[u8]) -> Result<()>
Set the system clipboard contents (OSC 52 ; c). data is
base64-encoded for transport.
Sourcepub fn set_primary_clipboard(&mut self, data: &[u8]) -> Result<()>
pub fn set_primary_clipboard(&mut self, data: &[u8]) -> Result<()>
Set the primary selection contents (OSC 52 ; p). data is
base64-encoded for transport.
Sourcepub fn request_system_clipboard(&mut self) -> Result<()>
pub fn request_system_clipboard(&mut self) -> Result<()>
Request the system clipboard contents (OSC 52 ; c ; ?). Reply:
Event::ClipboardStart, raw
Event::ClipboardChunk bytes,
then Event::ClipboardEnd.
Sourcepub fn request_primary_clipboard(&mut self) -> Result<()>
pub fn request_primary_clipboard(&mut self) -> Result<()>
Request the primary selection contents (OSC 52 ; p ; ?). Reply:
Event::ClipboardStart, raw
Event::ClipboardChunk bytes,
then Event::ClipboardEnd.
Source§impl<I, O> Program<I, O>
impl<I, O> Program<I, O>
Sourcepub fn terminal(&self) -> &Terminal<I, O> ⓘ
pub fn terminal(&self) -> &Terminal<I, O> ⓘ
Borrow the Terminal this program drives.
Shared on purpose: the program keeps ownership, so its record of the
modes and raw-mode state it emitted stays the authority for
finish. Everything the program itself changes has a
method here. The borrow is not a seal, though. Terminal::set_state
takes &self, so a caller holding this can still change raw mode
behind the program’s back, and the restore record will not know.
Sourcepub fn env(&self) -> &dyn Env
pub fn env(&self) -> &dyn Env
The environment the Terminal reads variables from.
This is where the answers the terminal never sends live: TERM,
COLORTERM, TERM_PROGRAM, and the rest. Shorthand for
terminal().env(), and the
counterpart to Capabilities, which holds only what the terminal
answered.
Sourcepub fn screen_mut(&mut self) -> &mut Screen<O> ⓘ
pub fn screen_mut(&mut self) -> &mut Screen<O> ⓘ
Borrow the Screen mutably — this is how you draw.
let screen = program.screen_mut();
screen.set_str((0, 0), "hello", Style::default());
screen.render()?;Drawing is the expected use. The screen’s render properties are also
reachable here, and setting one directly moves only how frames are
drawn — it emits no mode, so the terminal never hears about it. Prefer
the program’s own enter_alt_screen,
hide_cursor, and
enable_grapheme_clusters, which
emit the mode and move the property together. Teardown follows what
this program emitted, so a property changed behind its back is not
undone by finish and does not survive a
pause / resume round trip.
Sourcepub fn decoder_flags(&self) -> DecoderFlags
pub fn decoder_flags(&self) -> DecoderFlags
Return the event source’s current legacy decoder flags.
See DecoderFlags for the available key mappings.
Sourcepub fn set_decoder_flags(&mut self, flags: DecoderFlags)
pub fn set_decoder_flags(&mut self, flags: DecoderFlags)
Set the legacy decoder flags for subsequent input decoding.
Already-decoded events keep their values, including events returned
through unread_event. This updates the shared
EventSource and leaves ProgramOptions::legacy_keys unchanged.
Terminal modes remain unchanged.
Sourcepub fn poll_event(&self, timeout: Option<Duration>) -> Result<bool>
pub fn poll_event(&self, timeout: Option<Duration>) -> Result<bool>
Drive the input source for up to timeout, returning whether any
event became available. See EventSource::poll.
Sourcepub fn try_read_event(&mut self) -> Result<Option<Event>>
pub fn try_read_event(&mut self) -> Result<Option<Event>>
Take the next queued event without reading more input.
Returns Ok(None) when the queue is empty. See EventSource::try_read.
Events returned through unread_event come
first. Reads never write to the terminal and never change program
state.
Sourcepub fn read_event(&mut self) -> Result<Event>
pub fn read_event(&mut self) -> Result<Event>
Block until the next event. See EventSource::read.
Sourcepub fn unread_event(&mut self, event: Event)
pub fn unread_event(&mut self, event: Event)
Return an event to the front of the input queue, so the next
read_event / try_read_event
yields it before anything already queued. Restore a batch in original
order by unreading in reverse.
The shared event_source holds these events,
so synchronous readers and async streams can receive them.
A synchronous reader blocked on the shared source is interrupted, so this call does not wait for input.
Sourcepub fn event_source(&self) -> Arc<Mutex<EventSource<I>>> ⓘ
pub fn event_source(&self) -> Arc<Mutex<EventSource<I>>> ⓘ
A shared handle to the input source behind
read_event and friends, for driving input from a
separate reader over the same decoder rather than a second one racing
the same file descriptor.
The main use is async input: build an
EventStream with
EventStream::from_shared from
this handle and poll it on your executor.
Sharing one source between a live reader and the program’s own
read_event is best-effort: an event goes to
whichever consumer drains it first, so pick one reader in steady state.
Sourcepub fn event_stream(&self) -> EventStream<I>where
I: 'static,
pub fn event_stream(&self) -> EventStream<I>where
I: 'static,
Build an async EventStream over this
program’s input, for reading events with events.next().await inside a
select! on any executor. The stream shares the program’s decoder, so
it does not race a second reader on the same file descriptor.
The stream yields the same events as read_event.
Pass each event to Capabilities::record while a capability batch
is pending. Read through the stream or through read_event in steady
state, not both at once: a shared source hands each event to whichever
consumer drains it first.
Sourcepub fn state(&self) -> &State
pub fn state(&self) -> &State
Read-only record of the modes and settings selected through this program.
Sourcepub fn origin(&self) -> Position
pub fn origin(&self) -> Position
The physical screen coordinate of the managed area’s top-left cell.
Always (0, 0) in fullscreen. Inline it holds the last value given to
set_origin, and (0, 0) before that.
Sourcepub fn mouse_to_origin(&self, mouse: Mouse) -> Mouse
pub fn mouse_to_origin(&self, mouse: Mouse) -> Mouse
Translate a mouse event’s screen coordinates into coordinates relative
to the managed area, by subtracting the origin.
In fullscreen, the coordinates do not change.
Sourcepub fn apply_defaults(&mut self, caps: &Capabilities) -> Result<()>
pub fn apply_defaults(&mut self, caps: &Capabilities) -> Result<()>
Apply supported defaults from a record using the retained program options.
Call after the application’s capability batch, or when later replies update the record.
- Synchronized output, grapheme clusters, and in-band resize are
adopted when the terminal reports them and the matching
prefer_*field inProgramOptionsis set. Grapheme clusters and in-band resize are terminal modes, so adoption writes them. - A Backarrow mode report sets how the decoder reads Backspace, until
set_backspace_modeselects a mode. - A measured East Asian Ambiguous width updates
Screen::set_ambiguous_wide. Rewrite existing text after a change. - An
RGBorTctermcap reply upgrades the color profile to true color.
Each call sets ambiguous width and upgrades the color profile when the
record reports RGB or Tc. Call Screen::set_ambiguous_wide or
Screen::set_color_profile after it to choose your own values.
Adoption happens only while the application has taken no position of
its own. Calling a mode’s enable_* or disable_* method, in either
direction and at any point, settles it, and adoption settles it too. So
each mode is adopted at most once, and never against an explicit
choice. A synchronized-output opt-out also settles that preference.
The retained options and the record stay unchanged.
Source§impl<I, O> Program<I, O>
impl<I, O> Program<I, O>
Sourcepub fn new(terminal: Terminal<I, O>) -> Result<Self>
pub fn new(terminal: Terminal<I, O>) -> Result<Self>
Construct a program over terminal without touching the terminal:
size the screen to it and create an EventSource on its input
half. The terminal is left as-is; call Self::init to enter raw
mode and begin a session.
Sourcepub fn with_options(
terminal: Terminal<I, O>,
options: ProgramOptions,
) -> Result<Self>
pub fn with_options( terminal: Terminal<I, O>, options: ProgramOptions, ) -> Result<Self>
Construct a program with explicit session options.
Construction stores options and leaves terminal modes unchanged.
Call Self::init to enter raw mode and apply startup settings.
Self::apply_defaults uses the stored adoption preferences.
Sourcepub fn with_event_source(
terminal: Terminal<I, O>,
source: Arc<Mutex<EventSource<I>>>,
options: ProgramOptions,
) -> Result<Self>
pub fn with_event_source( terminal: Terminal<I, O>, source: Arc<Mutex<EventSource<I>>>, options: ProgramOptions, ) -> Result<Self>
Build a program with an existing shared input source.
Use the previous program’s event_source to
preserve queued events and incomplete input sequences across a handoff.
Pause the previous program first, then resume it after this program
finishes. Read from the shared source through one program at a time.
Like Self::new, this leaves terminal modes unchanged.
§Errors
Returns an error if the terminal size cannot be read.
use uncurses::{program::{Program, ProgramOptions}, terminal::Terminal};
let mut main = Program::open()?;
main.init()?;
main.pause()?;
let mut dialog = Program::with_event_source(
Terminal::open()?,
main.event_source(),
ProgramOptions::default(),
)?;
dialog.init()?;
dialog.finish()?;
main.resume()?;
main.finish()Sourcepub fn init(&mut self) -> Result<()>
pub fn init(&mut self) -> Result<()>
Begin a session: enter raw mode and apply the stored startup settings.
Call once after construction, before rendering.
Adoption preferences take effect through Self::apply_defaults.
Sourcepub fn get_window_size(&self) -> Result<Winsize>
pub fn get_window_size(&self) -> Result<Winsize>
Query the current terminal window size through
Terminal::get_window_size. The operating system answers, so
nothing is written to the terminal. Some platforms (the Windows
console) report no pixel dimensions. Use
request_window_pixel_size there.
Sourcepub fn set_origin(&mut self, position: Position)
pub fn set_origin(&mut self, position: Position)
Set the inline origin.
To measure the origin, call request_origin.
It moves the cursor to the managed area’s top-left cell and requests
the cursor position:
program.request_origin()?;Pass the position of the matching
CursorPosition reply here.
Cursor reports carry no request ID and arrive in request order, so
count the origin requests that wait for a reply. Measure again after a
resize and after resume, because both can move the
managed area.
The row is clipped so that the managed area stays on screen: its top
row is at most terminal_height - area_height. This covers a reply to
a request sent before the first render, which can report a row that
the render then scrolls. The terminal height comes from
get_window_size. When that query fails, the
row becomes 0.
Sourcepub fn autoresize(&mut self) -> Result<()>
pub fn autoresize(&mut self) -> Result<()>
Re-query the terminal size and resize the managed area to fit: the full terminal size when fullscreen, or the terminal width with the current managed height preserved when inline. Nothing is asked of the terminal: this reads the size the operating system already knows.
When the managed area already fits the queried size, this returns
without resizing and without repainting, so it is safe to call on every
resize report. Terminals send a report per pixel of a window drag while
the cell grid only changes at cell boundaries, so most reports ask for a
size the area already has. To re-establish the area whatever the size,
call Screen::resize instead.
Sourcepub fn finish(self) -> Result<()>
pub fn finish(self) -> Result<()>
Consume the program and hand the terminal back to the shell: tear down every staged mode, reset the managed area, flush, and restore the terminal’s prior state.
The terminal state is restored even when the teardown writes fail, so a broken pipe cannot leave the terminal in raw mode. The teardown error is still returned.
Sourcepub fn pause(&mut self) -> Result<()>
pub fn pause(&mut self) -> Result<()>
Hand the terminal back to the shell without consuming the program,
e.g. to run a child process. Re-enter with Self::resume. Like
Self::finish but keeps the program so the session can continue, and
likewise restores the terminal even when the teardown writes fail.
Sourcepub fn resume(&mut self) -> Result<()>
pub fn resume(&mut self) -> Result<()>
Re-acquire the terminal after a Self::pause or Unix suspend:
re-enter raw mode, refit the managed area to the current viewport, re-apply
the saved render state and modes, and force a full repaint.
Re-enables TABS and
BS and resets the hardware tab stops, since
whatever ran while paused may have disturbed both.