mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Centralize terminal compatibility policy in the TUI (#63793)
## What changed Have startup and screen code consume capability decisions for inline mode, Kitty graphics, mouse capture, session polling, and pointer reset. Keep terminal and multiplexer detection behind the capability helpers for these decisions. Share stdout color detection between the CLI and standalone TUI exit messages, and use the TUI's terminal warning helper for the CLI startup confirmation. ## Testing Exercise mouse-capture cleanup in separate Kitty and Ghostty test processes and verify that each emits its expected OSC 22 reset sequence. GitOrigin-RevId: 15cb972034397e521a97c2813628533b71539530
This commit is contained in:
@@ -42,7 +42,6 @@ use std::io::IsTerminal;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use supports_color::Stream;
|
||||
|
||||
#[cfg(all(
|
||||
target_os = "linux",
|
||||
@@ -110,7 +109,6 @@ use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_terminal_detection::TerminalName;
|
||||
|
||||
/// Codex CLI
|
||||
///
|
||||
@@ -784,7 +782,7 @@ fn handle_app_exit(
|
||||
eprintln!("{warning}");
|
||||
}
|
||||
} else {
|
||||
let color_enabled = supports_color::on(Stream::Stdout).is_some();
|
||||
let color_enabled = codex_tui::stdout_supports_color();
|
||||
for line in exit_info.format_exit_messages(color_enabled) {
|
||||
println!("{line}");
|
||||
}
|
||||
@@ -2554,21 +2552,18 @@ async fn run_interactive_tui(
|
||||
interactive.prompt = Some(prompt.replace("\r\n", "\n").replace('\r', "\n"));
|
||||
}
|
||||
|
||||
let terminal_info = codex_terminal_detection::terminal_info();
|
||||
if terminal_info.name == TerminalName::Dumb {
|
||||
if let Some(reason) = codex_tui::interactive_terminal_warning() {
|
||||
if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()) {
|
||||
return Ok(AppExitInfo::fatal(
|
||||
"TERM is set to \"dumb\". Refusing to start the interactive TUI because no terminal is available for a confirmation prompt (stdin/stderr is not a TTY). Run in a supported terminal or unset TERM.",
|
||||
));
|
||||
return Ok(AppExitInfo::fatal(format!(
|
||||
"{reason}. Refusing to start the interactive TUI because no terminal is available for a confirmation prompt (stdin/stderr is not a TTY). Run in a supported terminal or unset TERM."
|
||||
)));
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"WARNING: TERM is set to \"dumb\". Codex's interactive TUI may not work in this terminal."
|
||||
);
|
||||
eprintln!("WARNING: {reason}. Codex's interactive TUI may not work in this terminal.");
|
||||
if !confirm("Continue anyway? [y/N]: ")? {
|
||||
return Ok(AppExitInfo::fatal(
|
||||
"Refusing to start the interactive TUI because TERM is set to \"dumb\". Run in a supported terminal or unset TERM.",
|
||||
));
|
||||
return Ok(AppExitInfo::fatal(format!(
|
||||
"Refusing to start the interactive TUI because {reason}. Run in a supported terminal or unset TERM."
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -896,7 +896,7 @@ impl App {
|
||||
app_server: &mut AppServerSession,
|
||||
event: TuiEvent,
|
||||
) -> Result<AppRunControl> {
|
||||
if matches!(event, TuiEvent::Draw) && tui::tmux_mouse_disabled() {
|
||||
if matches!(event, TuiEvent::Draw) && tui::mouse_capture_disabled() {
|
||||
self.sidebar_press = None;
|
||||
self.divider_drag = None;
|
||||
self.agents_overview.workspace.divider_drag_viewport = None;
|
||||
@@ -1581,7 +1581,7 @@ impl App {
|
||||
}
|
||||
|
||||
fn preview_image_protocol(&self, tui: &tui::Tui) -> Option<crate::pets::ImageProtocol> {
|
||||
match tui.herdr_kitty_graphics {
|
||||
match tui.probed_kitty_graphics {
|
||||
Some(true) => Some(crate::pets::ImageProtocol::Kitty),
|
||||
Some(false) => None,
|
||||
None => self.chat_widget.pet_image_support().protocol(),
|
||||
|
||||
@@ -187,7 +187,7 @@ impl App {
|
||||
let Some((id, area)) = self.passive_link_drag else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.conversation_focus_available(tui) && !crate::tui::tmux_mouse_disabled() {
|
||||
if self.conversation_focus_available(tui) && !crate::tui::mouse_capture_disabled() {
|
||||
match event {
|
||||
TuiEvent::Draw => {
|
||||
if let Some(companion) = self.side_companions.get_mut(&id)
|
||||
|
||||
@@ -243,6 +243,8 @@ mod system_motion;
|
||||
mod task_mentions;
|
||||
mod temporary_structured_request;
|
||||
mod terminal_capabilities;
|
||||
pub use terminal_capabilities::interactive_terminal_warning;
|
||||
pub use terminal_capabilities::stdout_supports_color;
|
||||
mod terminal_hyperlinks;
|
||||
mod terminal_palette;
|
||||
use terminal_capabilities::terminal_probe;
|
||||
@@ -2131,7 +2133,7 @@ async fn run_ratatui_app(
|
||||
let use_alt_screen = determine_alt_screen_mode(
|
||||
cli.no_alt_screen,
|
||||
config.tui_alternate_screen,
|
||||
tui.terminal_app_over_ssh,
|
||||
tui.prefer_inline_screen,
|
||||
);
|
||||
let mode = crate::transcript_mode::TranscriptMode::resolve(
|
||||
config.tui_fullscreen_transcript,
|
||||
@@ -2473,7 +2475,7 @@ impl Drop for TerminalRestoreGuard {
|
||||
fn determine_alt_screen_mode(
|
||||
no_alt_screen: bool,
|
||||
tui_alternate_screen: AltScreenMode,
|
||||
terminal_app_over_ssh: bool,
|
||||
prefer_inline_screen: bool,
|
||||
) -> bool {
|
||||
if no_alt_screen {
|
||||
return false;
|
||||
@@ -2482,7 +2484,7 @@ fn determine_alt_screen_mode(
|
||||
match tui_alternate_screen {
|
||||
AltScreenMode::Always => true,
|
||||
AltScreenMode::Never => false,
|
||||
AltScreenMode::Auto => !terminal_app_over_ssh,
|
||||
AltScreenMode::Auto => !prefer_inline_screen,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -710,24 +710,20 @@ async fn startup_session_cwd_without_metadata_is_rejected() -> color_eyre::Resul
|
||||
|
||||
#[test]
|
||||
fn alternate_screen_respects_terminal_compatibility_and_overrides() {
|
||||
for terminal_app_over_ssh in [false, true] {
|
||||
for prefer_inline_screen in [false, true] {
|
||||
for (mode, expected) in [
|
||||
(AltScreenMode::Auto, !terminal_app_over_ssh),
|
||||
(AltScreenMode::Auto, !prefer_inline_screen),
|
||||
(AltScreenMode::Always, true),
|
||||
(AltScreenMode::Never, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
determine_alt_screen_mode(
|
||||
/*no_alt_screen*/ false,
|
||||
mode,
|
||||
terminal_app_over_ssh
|
||||
),
|
||||
determine_alt_screen_mode(/*no_alt_screen*/ false, mode, prefer_inline_screen),
|
||||
expected,
|
||||
);
|
||||
assert!(!determine_alt_screen_mode(
|
||||
/*no_alt_screen*/ true,
|
||||
mode,
|
||||
terminal_app_over_ssh
|
||||
prefer_inline_screen
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ use clap::Parser;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_terminal_detection::StdoutColorLevel;
|
||||
use codex_terminal_detection::stdout_color_level;
|
||||
use codex_tui::Cli;
|
||||
use codex_tui::ExitReason;
|
||||
use codex_tui::run_main;
|
||||
@@ -47,7 +45,7 @@ fn main() -> anyhow::Result<()> {
|
||||
ExitReason::UserRequested | ExitReason::TurnInterrupted => false,
|
||||
};
|
||||
|
||||
let color_enabled = stdout_color_level() != StdoutColorLevel::Unknown;
|
||||
let color_enabled = codex_tui::stdout_supports_color();
|
||||
for line in exit_info.format_exit_messages(color_enabled) {
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
@@ -137,8 +137,8 @@ impl StartupDraft {
|
||||
initialized_terminal.stderr_guard,
|
||||
);
|
||||
terminal_restore_guard.events = Some(tui.event_broker.clone());
|
||||
tui.terminal_app_over_ssh = initialized_terminal.terminal_app_over_ssh;
|
||||
tui.herdr_kitty_graphics = initialized_terminal.herdr_kitty_graphics;
|
||||
tui.prefer_inline_screen = initialized_terminal.prefer_inline_screen;
|
||||
tui.probed_kitty_graphics = initialized_terminal.probed_kitty_graphics;
|
||||
tui.set_alt_screen_enabled(screen.use_alt_screen);
|
||||
let mut pump = StartupDraftPump::new(&tui, initial_screen, session_action);
|
||||
pump.motion = screen.welcome_motion;
|
||||
|
||||
@@ -266,11 +266,11 @@ fn terminal_app_ssh_fallback_renders_inline_startup() {
|
||||
let pump = startup_test_pump(std::iter::empty());
|
||||
let owned_layout = super::layout::OwnedStartupLayout::new(&pump);
|
||||
let mut frames = Vec::new();
|
||||
for terminal_app_over_ssh in [false, true] {
|
||||
for prefer_inline_screen in [false, true] {
|
||||
let owned = crate::determine_alt_screen_mode(
|
||||
/*no_alt_screen*/ false,
|
||||
codex_config::types::AltScreenMode::Auto,
|
||||
terminal_app_over_ssh,
|
||||
prefer_inline_screen,
|
||||
);
|
||||
let renderable = if owned {
|
||||
crate::render::renderable::RenderableItem::Borrowed(&owned_layout)
|
||||
@@ -307,7 +307,7 @@ fn terminal_app_ssh_fallback_renders_inline_startup() {
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
frames.push(format!(
|
||||
"terminal_app_over_ssh={terminal_app_over_ssh}, owned={owned}\n{frame}"
|
||||
"terminal_app_over_ssh={prefer_inline_screen}, owned={owned}\n{frame}"
|
||||
));
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
|
||||
@@ -349,7 +349,7 @@ pub(super) async fn run_main_inner(
|
||||
screen.use_alt_screen = determine_alt_screen_mode(
|
||||
cli.no_alt_screen,
|
||||
local_settings.tui.alternate_screen,
|
||||
initialized_terminal.terminal_app_over_ssh,
|
||||
initialized_terminal.prefer_inline_screen,
|
||||
);
|
||||
screen.transcript_mode = crate::transcript_mode::TranscriptMode::resolve(
|
||||
screen.transcript_mode.is_owned(),
|
||||
|
||||
@@ -61,7 +61,7 @@ pub(super) async fn load(
|
||||
let use_alt_screen = crate::determine_alt_screen_mode(
|
||||
cli.no_alt_screen,
|
||||
settings.alternate_screen,
|
||||
/*terminal_app_over_ssh*/ false,
|
||||
/*prefer_inline_screen*/ false,
|
||||
);
|
||||
let transcript_mode = crate::transcript_mode::TranscriptMode::resolve(
|
||||
settings.fullscreen_transcript,
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
pub(crate) mod images;
|
||||
pub(crate) mod keyboard_modes;
|
||||
mod resize_reflow_cap;
|
||||
#[cfg(unix)]
|
||||
mod terminal_identity;
|
||||
pub(crate) mod terminal_probe;
|
||||
pub(crate) mod tmux;
|
||||
mod tmux;
|
||||
pub(crate) mod tmux_clipboard;
|
||||
|
||||
use codex_terminal_detection::Multiplexer;
|
||||
use codex_terminal_detection::TerminalInfo;
|
||||
use codex_terminal_detection::TerminalName;
|
||||
use codex_terminal_detection::terminal_info;
|
||||
@@ -18,6 +21,10 @@ pub use codex_terminal_detection::StdoutColorLevel;
|
||||
pub use codex_terminal_detection::stdout_color_level;
|
||||
pub(crate) use codex_terminal_detection::terminal_color_level;
|
||||
pub(crate) use resize_reflow_cap::resize_reflow_max_rows;
|
||||
#[cfg(unix)]
|
||||
pub(crate) use terminal_identity::requires_inline_screen;
|
||||
pub(crate) use tmux::MouseCapture;
|
||||
pub(crate) use tmux::sample_mouse;
|
||||
|
||||
pub(crate) fn is_ssh_session() -> bool {
|
||||
std::env::var_os("SSH_TTY").is_some() || std::env::var_os("SSH_CONNECTION").is_some()
|
||||
@@ -35,6 +42,50 @@ fn screen_active() -> bool {
|
||||
std::env::var_os("STY").is_some()
|
||||
}
|
||||
|
||||
pub(crate) struct SessionCapabilities {
|
||||
pub(crate) mouse_capture: MouseCapture,
|
||||
virtual_image_base: Option<u32>,
|
||||
}
|
||||
|
||||
impl SessionCapabilities {
|
||||
pub(crate) fn virtual_image_base(&self) -> Option<u32> {
|
||||
if tmux_transport()
|
||||
&& !zellij_session()
|
||||
&& !crossterm::style::Colored::ansi_color_disabled_memoized()
|
||||
{
|
||||
self.virtual_image_base
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn zellij_session() -> bool {
|
||||
["ZELLIJ", "ZELLIJ_SESSION_NAME", "ZELLIJ_VERSION"]
|
||||
.iter()
|
||||
.any(|key| std::env::var_os(key).is_some())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn should_probe_inline_screen() -> bool {
|
||||
terminal_info().multiplexer.is_none() && is_ssh_session()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn should_probe_kitty_graphics() -> bool {
|
||||
let info = terminal_info();
|
||||
info.multiplexer.is_none() && info.term_program.as_deref() == Some("herdr")
|
||||
}
|
||||
|
||||
pub(crate) fn needs_session_polling(info: &TerminalInfo) -> bool {
|
||||
cfg!(unix) && matches!(info.multiplexer, Some(Multiplexer::Tmux { .. }))
|
||||
}
|
||||
|
||||
pub(crate) fn screen_capabilities() -> (ScrollbackStrategy, bool) {
|
||||
let info = terminal_info();
|
||||
(scrollback_strategy(&info), needs_session_polling(&info))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ScrollbackStrategy {
|
||||
Standard,
|
||||
@@ -158,3 +209,34 @@ pub(crate) fn detect_web_link_display() -> WebLinkDisplay {
|
||||
}
|
||||
web_link_display(&terminal_info(), std::env::var("TERM").ok().as_deref())
|
||||
}
|
||||
|
||||
/// Why interactive screen control may be unavailable at launch.
|
||||
pub fn interactive_terminal_warning() -> Option<&'static str> {
|
||||
(terminal_info().name == TerminalName::Dumb).then_some("TERM is set to \"dumb\"")
|
||||
}
|
||||
|
||||
/// Whether stdout supports colored exit messages.
|
||||
pub fn stdout_supports_color() -> bool {
|
||||
stdout_color_level() != StdoutColorLevel::Unknown
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) enum PointerReset {
|
||||
Text,
|
||||
Release,
|
||||
}
|
||||
|
||||
impl PointerReset {
|
||||
/// Only request CSS pointer shapes when their OSC 22 reset is known.
|
||||
pub(crate) fn detect() -> Option<Self> {
|
||||
let info = terminal_info();
|
||||
if info.multiplexer.is_some() {
|
||||
return None;
|
||||
}
|
||||
match info.name {
|
||||
TerminalName::Kitty => Some(Self::Release),
|
||||
TerminalName::Ghostty => Some(Self::Text),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(crate) enum VscodeDetection {
|
||||
|
||||
pub(crate) fn keyboard_enhancement_disabled() -> bool {
|
||||
let disable_env = std::env::var(DISABLE_KEYBOARD_ENHANCEMENT_ENV_VAR).ok();
|
||||
let is_wsl = running_in_wsl();
|
||||
let is_wsl = crate::clipboard_copy::is_wsl_session();
|
||||
let vscode_detection = if is_wsl {
|
||||
detect_vscode_terminal()
|
||||
} else {
|
||||
@@ -40,6 +40,14 @@ pub(crate) fn keyboard_enhancement_disabled() -> bool {
|
||||
keyboard_enhancement_disabled_for(disable_env.as_deref(), is_wsl, vscode_detection)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn detect_keyboard_enhancement_supported() -> bool {
|
||||
// Non-Unix startup keeps the existing crossterm keyboard probe path because it already knows
|
||||
// how to interpret platform-specific event sources.
|
||||
!keyboard_enhancement_disabled()
|
||||
&& crossterm::terminal::supports_keyboard_enhancement().unwrap_or(/*default*/ false)
|
||||
}
|
||||
|
||||
fn keyboard_enhancement_disabled_for(
|
||||
disable_env: Option<&str>,
|
||||
is_wsl: bool,
|
||||
@@ -71,19 +79,7 @@ fn parse_bool_env(value: Option<&str>) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn running_in_wsl() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
crate::clipboard_paste::is_probably_wsl()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn running_in_vscode_terminal() -> bool {
|
||||
pub(super) fn running_in_vscode_terminal() -> bool {
|
||||
detect_vscode_terminal() == VscodeDetection::VsCode
|
||||
}
|
||||
|
||||
@@ -111,7 +107,7 @@ fn windows_vscode_detection() -> VscodeDetection {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_windows_vscode_detection() -> VscodeDetection {
|
||||
if !running_in_wsl() {
|
||||
if !crate::clipboard_copy::is_wsl_session() {
|
||||
return VscodeDetection::Other;
|
||||
}
|
||||
read_windows_vscode_detection_with_timeout(
|
||||
@@ -193,11 +189,15 @@ fn read_windows_vscode_detection_with_timeout(
|
||||
mod windows_term_program_tests;
|
||||
|
||||
/// Restore keyboard reporting and return the settings from the same tmux probe.
|
||||
pub(crate) fn enable_keyboard_enhancement(writer: &mut impl Write) -> super::tmux::Options {
|
||||
pub(crate) fn enable_keyboard_enhancement(writer: &mut impl Write) -> super::SessionCapabilities {
|
||||
let tmux_options = super::tmux::options();
|
||||
let capabilities = super::SessionCapabilities {
|
||||
mouse_capture: tmux_options.mouse_capture,
|
||||
virtual_image_base: tmux_options.kitty_image_base,
|
||||
};
|
||||
if keyboard_enhancement_disabled() {
|
||||
set_reports_key_releases(/*reports*/ false);
|
||||
return tmux_options;
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
let running_in_tmux_session = running_in_tmux_session();
|
||||
@@ -225,7 +225,7 @@ pub(crate) fn enable_keyboard_enhancement(writer: &mut impl Write) -> super::tmu
|
||||
{
|
||||
let _ = execute!(writer, EnableModifyOtherKeys);
|
||||
}
|
||||
tmux_options
|
||||
capabilities
|
||||
}
|
||||
|
||||
fn keyboard_enhancement_flags(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Recognize Terminal.app's device attributes without interpreting pasted text as a reply.
|
||||
|
||||
/// A complete pair is required; missing or incomplete replies remain unknown.
|
||||
pub(super) fn is_apple_terminal(input: &[u8]) -> Option<bool> {
|
||||
pub(crate) fn requires_inline_screen(input: &[u8]) -> Option<bool> {
|
||||
let primary = device_attributes(input, b"[?")?;
|
||||
let secondary = device_attributes(input, b"[>")?;
|
||||
Some(primary == b"1;2" && secondary == b"1;95;0")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Cover observed terminal signatures, fragmented replies, and pasted lookalikes.
|
||||
|
||||
use super::is_apple_terminal;
|
||||
use super::requires_inline_screen;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
@@ -24,7 +24,7 @@ fn distinguishes_the_native_terminal_replies() {
|
||||
format!("{secondary}{primary}"),
|
||||
] {
|
||||
assert_eq!(
|
||||
is_apple_terminal(input.as_bytes()),
|
||||
requires_inline_screen(input.as_bytes()),
|
||||
Some(expected),
|
||||
"{input:?}"
|
||||
);
|
||||
@@ -37,9 +37,9 @@ fn unrelated_csi_replies_cannot_consume_typed_text_as_device_attributes() {
|
||||
for reply in [b"\x1b[?7u".as_slice(), b"\x1b[>4;2m".as_slice()] {
|
||||
let mut input = reply.to_vec();
|
||||
input.extend_from_slice(b"c\x1b[>1;95;0c");
|
||||
assert_eq!(is_apple_terminal(&input), None);
|
||||
assert_eq!(requires_inline_screen(&input), None);
|
||||
input.extend_from_slice(b"\x1b[?1;2c");
|
||||
assert_eq!(is_apple_terminal(&input), Some(true));
|
||||
assert_eq!(requires_inline_screen(&input), Some(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,13 +47,13 @@ fn unrelated_csi_replies_cannot_consume_typed_text_as_device_attributes() {
|
||||
fn identity_waits_for_complete_replies_and_ignores_pasted_signatures() {
|
||||
let signature = b"\x1b[?1;2c\x1b[>1;95;0c";
|
||||
for end in 0..signature.len() {
|
||||
assert_eq!(is_apple_terminal(&signature[..end]), None);
|
||||
assert_eq!(requires_inline_screen(&signature[..end]), None);
|
||||
}
|
||||
let mut input = b"typed\x1b[200~".to_vec();
|
||||
input.extend_from_slice(signature);
|
||||
assert_eq!(is_apple_terminal(&input), None);
|
||||
assert_eq!(requires_inline_screen(&input), None);
|
||||
input.extend_from_slice(b"\x1b[201~more typed");
|
||||
assert_eq!(is_apple_terminal(&input), None);
|
||||
assert_eq!(requires_inline_screen(&input), None);
|
||||
input.extend_from_slice(signature);
|
||||
assert_eq!(is_apple_terminal(&input), Some(true));
|
||||
assert_eq!(requires_inline_screen(&input), Some(true));
|
||||
}
|
||||
|
||||
@@ -16,10 +16,6 @@ use std::time::Duration;
|
||||
#[cfg(unix)]
|
||||
mod startup_replay;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "terminal_identity.rs"]
|
||||
mod terminal_identity;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
#[path = "terminal_probe/windows_replay.rs"]
|
||||
mod windows_replay;
|
||||
@@ -51,7 +47,7 @@ fn alternate_scroll_report(input: &[u8]) -> Option<bool> {
|
||||
mod imp {
|
||||
use super::parse_default_colors;
|
||||
use super::startup_replay::parse_startup_input;
|
||||
use super::terminal_identity;
|
||||
|
||||
use crate::terminal_palette::DefaultColors;
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
@@ -81,7 +77,7 @@ mod imp {
|
||||
pub(crate) cursor_position: Option<Position>,
|
||||
pub(crate) default_colors: Option<DefaultColors>,
|
||||
pub(crate) keyboard_enhancement_supported: Option<bool>,
|
||||
pub(crate) terminal_app_over_ssh: Option<bool>,
|
||||
pub(crate) prefer_inline_screen: Option<bool>,
|
||||
pub(crate) kitty_graphics: bool,
|
||||
}
|
||||
|
||||
@@ -314,22 +310,18 @@ mod imp {
|
||||
pub(crate) fn startup(
|
||||
timeout: Duration,
|
||||
keyboard_probe: StartupKeyboardEnhancementProbe,
|
||||
probe_herdr: bool,
|
||||
probe_kitty_graphics: bool,
|
||||
) -> io::Result<StartupProbe> {
|
||||
DA1_SUPPORTED.store(false, Ordering::Relaxed);
|
||||
let mut tty = Tty::open()?;
|
||||
let query_identity = codex_terminal_detection::terminal_info()
|
||||
.multiplexer
|
||||
.is_none()
|
||||
&& (std::env::var_os("SSH_TTY").is_some()
|
||||
|| std::env::var_os("SSH_CONNECTION").is_some());
|
||||
let query_identity = crate::terminal_capabilities::should_probe_inline_screen();
|
||||
let mut query = Vec::new();
|
||||
if keyboard_probe == StartupKeyboardEnhancementProbe::Query {
|
||||
query.extend_from_slice(b"\x1B[?u");
|
||||
}
|
||||
// Query before DA1 so its reply acts as a barrier even if mode 1007 is unsupported.
|
||||
query.extend_from_slice(b"\x1B[?1007$p");
|
||||
if probe_herdr {
|
||||
if probe_kitty_graphics {
|
||||
// Query a single inline RGB pixel without storing or displaying an image.
|
||||
query.extend_from_slice(b"\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\");
|
||||
}
|
||||
@@ -346,10 +338,10 @@ mod imp {
|
||||
timeout,
|
||||
keyboard_probe,
|
||||
query_identity,
|
||||
probe_herdr,
|
||||
probe_kitty_graphics,
|
||||
&mut buffer,
|
||||
);
|
||||
let (replay, kitty_graphics) = parse_startup_input(&buffer, probe_herdr);
|
||||
let (replay, kitty_graphics) = parse_startup_input(&buffer, probe_kitty_graphics);
|
||||
crossterm::event::buffer_input(&replay)?;
|
||||
let saw_da1 = find_primary_device_attributes(&buffer).is_some();
|
||||
DA1_SUPPORTED.store(saw_da1, Ordering::Relaxed);
|
||||
@@ -392,12 +384,12 @@ mod imp {
|
||||
timeout: Duration,
|
||||
keyboard_probe: StartupKeyboardEnhancementProbe,
|
||||
query_identity: bool,
|
||||
probe_herdr: bool,
|
||||
probe_kitty_graphics: bool,
|
||||
buffer: &mut Vec<u8>,
|
||||
) -> io::Result<StartupProbe> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut probe = StartupProbe {
|
||||
terminal_app_over_ssh: (!query_identity).then_some(/*t*/ false),
|
||||
prefer_inline_screen: (!query_identity).then_some(/*t*/ false),
|
||||
..Default::default()
|
||||
};
|
||||
let mut saw_supported_keyboard = false;
|
||||
@@ -410,7 +402,7 @@ mod imp {
|
||||
keyboard_probe,
|
||||
);
|
||||
if startup_probe_complete(&probe, keyboard_probe)
|
||||
&& (!probe_herdr || find_primary_device_attributes(buffer).is_some())
|
||||
&& (!probe_kitty_graphics || find_primary_device_attributes(buffer).is_some())
|
||||
{
|
||||
return Ok(probe);
|
||||
}
|
||||
@@ -445,8 +437,9 @@ mod imp {
|
||||
{
|
||||
probe.default_colors = parse_default_colors(buffer);
|
||||
}
|
||||
if probe.terminal_app_over_ssh.is_none() {
|
||||
probe.terminal_app_over_ssh = terminal_identity::is_apple_terminal(buffer);
|
||||
if probe.prefer_inline_screen.is_none() {
|
||||
probe.prefer_inline_screen =
|
||||
crate::terminal_capabilities::requires_inline_screen(buffer);
|
||||
}
|
||||
if keyboard_probe == StartupKeyboardEnhancementProbe::Skip
|
||||
|| probe.keyboard_enhancement_supported.is_some()
|
||||
@@ -475,7 +468,7 @@ mod imp {
|
||||
&& probe
|
||||
.default_colors
|
||||
.is_some_and(|colors| colors.fg.is_some())
|
||||
&& probe.terminal_app_over_ssh.is_some()
|
||||
&& probe.prefer_inline_screen.is_some()
|
||||
&& (keyboard_probe == StartupKeyboardEnhancementProbe::Skip
|
||||
|| probe.keyboard_enhancement_supported.is_some())
|
||||
}
|
||||
@@ -721,7 +714,7 @@ mod imp {
|
||||
cursor_position: None,
|
||||
default_colors: None,
|
||||
keyboard_enhancement_supported: None,
|
||||
terminal_app_over_ssh: Some(false),
|
||||
prefer_inline_screen: Some(false),
|
||||
kitty_graphics: false,
|
||||
};
|
||||
let mut saw_supported_keyboard = false;
|
||||
@@ -756,7 +749,7 @@ mod imp {
|
||||
bg: (17, 17, 17),
|
||||
}),
|
||||
keyboard_enhancement_supported: Some(true),
|
||||
terminal_app_over_ssh: Some(false),
|
||||
prefer_inline_screen: Some(false),
|
||||
kitty_graphics: false,
|
||||
}
|
||||
);
|
||||
@@ -773,7 +766,7 @@ mod imp {
|
||||
cursor_position: None,
|
||||
default_colors: None,
|
||||
keyboard_enhancement_supported: None,
|
||||
terminal_app_over_ssh: None,
|
||||
prefer_inline_screen: None,
|
||||
kitty_graphics: false,
|
||||
};
|
||||
let mut supported_keyboard = false;
|
||||
@@ -797,7 +790,7 @@ mod imp {
|
||||
&input,
|
||||
StartupKeyboardEnhancementProbe::Skip,
|
||||
);
|
||||
assert_eq!(probe.terminal_app_over_ssh, Some(true));
|
||||
assert_eq!(probe.prefer_inline_screen, Some(true));
|
||||
assert!(startup_probe_complete(
|
||||
&probe,
|
||||
StartupKeyboardEnhancementProbe::Skip
|
||||
@@ -813,11 +806,11 @@ mod imp {
|
||||
Duration::ZERO,
|
||||
StartupKeyboardEnhancementProbe::Skip,
|
||||
/*query_identity*/ true,
|
||||
/*probe_herdr*/ false,
|
||||
/*probe_kitty_graphics*/ false,
|
||||
&mut buffer,
|
||||
)
|
||||
.expect("finish within probe deadline");
|
||||
assert_eq!(probe.terminal_app_over_ssh, None);
|
||||
assert_eq!(probe.prefer_inline_screen, None);
|
||||
let colors = probe.default_colors.expect("OSC 11 background");
|
||||
assert_eq!(colors.fg, None);
|
||||
let fill = crate::style::user_message_bg_rgb(colors.bg);
|
||||
@@ -838,7 +831,7 @@ mod imp {
|
||||
Duration::from_secs(/*secs*/ 1),
|
||||
StartupKeyboardEnhancementProbe::Query,
|
||||
/*query_identity*/ false,
|
||||
/*probe_herdr*/ false,
|
||||
/*probe_kitty_graphics*/ false,
|
||||
&mut buffer,
|
||||
)
|
||||
.expect("read terminal responses after buffered typeahead");
|
||||
@@ -853,14 +846,14 @@ mod imp {
|
||||
bg: (17, 17, 17),
|
||||
}),
|
||||
keyboard_enhancement_supported: Some(true),
|
||||
terminal_app_over_ssh: Some(false),
|
||||
prefer_inline_screen: Some(false),
|
||||
kitty_graphics: false,
|
||||
}
|
||||
);
|
||||
let mut expected_replay = vec![b'x'; 2_048];
|
||||
expected_replay.extend_from_slice(b"\x1B[20;10R\x1B[?64;1;2c\x1B[?7u");
|
||||
assert_eq!(
|
||||
parse_startup_input(&buffer, /*probe_herdr*/ false),
|
||||
parse_startup_input(&buffer, /*probe_kitty_graphics*/ false),
|
||||
(expected_replay, false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
const MAX_REPLAYED_OSC_BYTES: usize = 1024;
|
||||
|
||||
/// Return the input to replay and whether Herdr acknowledged the Kitty graphics query.
|
||||
/// Return the input to replay and whether the terminal acknowledged the Kitty graphics query.
|
||||
///
|
||||
/// Keep bounded incomplete OSC prefixes so unread continuations stay parser-framed.
|
||||
pub(super) fn parse_startup_input(input: &[u8], probe_herdr: bool) -> (Vec<u8>, bool) {
|
||||
pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> (Vec<u8>, bool) {
|
||||
const PASTE_START: &[u8] = b"\x1b[200~";
|
||||
const PASTE_END: &[u8] = b"\x1b[201~";
|
||||
const KITTY_REPLY: &[u8] = b"\x1b_Gi=31;";
|
||||
@@ -55,7 +55,7 @@ pub(super) fn parse_startup_input(input: &[u8], probe_herdr: bool) -> (Vec<u8>,
|
||||
}
|
||||
|
||||
// Only consume replies to our query. Bracketed paste above remains user input.
|
||||
if probe_herdr
|
||||
if probe_kitty_graphics
|
||||
&& let Some(message) = input[cursor..].strip_prefix(KITTY_REPLY)
|
||||
&& let Some(end) = message.iter().position(|b| !(0x20..=0x7e).contains(b))
|
||||
&& message[end..].starts_with(b"\x1b\\")
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::parse_startup_input;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn startup_replay_input(input: &[u8]) -> Vec<u8> {
|
||||
parse_startup_input(input, /*probe_herdr*/ false).0
|
||||
parse_startup_input(input, /*probe_kitty_graphics*/ false).0
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -73,7 +73,7 @@ fn herdr_graphics_reply_selects_previews_without_replaying_the_response_as_keys(
|
||||
] {
|
||||
let input = [paste.as_slice(), reply, b"typed"].concat();
|
||||
assert_eq!(
|
||||
parse_startup_input(&input, /*probe_herdr*/ true),
|
||||
parse_startup_input(&input, /*probe_kitty_graphics*/ true),
|
||||
([paste.as_slice(), b"typed"].concat(), expected)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,13 +23,13 @@ static PROBE_IN_FLIGHT: AtomicBool = AtomicBool::new(false);
|
||||
pub(crate) enum MouseCapture {
|
||||
#[default]
|
||||
Enabled,
|
||||
DisabledByTmux,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl MouseCapture {
|
||||
fn parse(mouse: &str) -> Option<Self> {
|
||||
match mouse.trim() {
|
||||
"0" | "off" => Some(Self::DisabledByTmux),
|
||||
"0" | "off" => Some(Self::Disabled),
|
||||
"1" | "on" => Some(Self::Enabled),
|
||||
_ => None,
|
||||
}
|
||||
@@ -80,7 +80,7 @@ pub(crate) fn sample_mouse(previous: MouseCapture) -> Option<MouseCapture> {
|
||||
// display-message (and the user's after-display-message hook) on a change.
|
||||
let (condition, report) = match previous {
|
||||
MouseCapture::Enabled => ("#{==:#{mouse},0}", "display-message -p 0"),
|
||||
MouseCapture::DisabledByTmux => ("#{==:#{mouse},1}", "display-message -p 1"),
|
||||
MouseCapture::Disabled => ("#{==:#{mouse},1}", "display-message -p 1"),
|
||||
};
|
||||
command.args(["if-shell", "-F", "-t", &target, condition, report]);
|
||||
// Keep the periodic check short so a busy server cannot starve resize recovery.
|
||||
@@ -90,13 +90,13 @@ pub(crate) fn sample_mouse(previous: MouseCapture) -> Option<MouseCapture> {
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Options {
|
||||
pub(crate) extended_keys_format: Option<String>,
|
||||
pub(crate) mouse_capture: MouseCapture,
|
||||
pub(crate) kitty_image_base: Option<u32>,
|
||||
pub(super) struct Options {
|
||||
pub(super) extended_keys_format: Option<String>,
|
||||
pub(super) mouse_capture: MouseCapture,
|
||||
pub(super) kitty_image_base: Option<u32>,
|
||||
}
|
||||
|
||||
pub(crate) fn options() -> Options {
|
||||
pub(super) fn options() -> Options {
|
||||
let pane = target();
|
||||
if std::env::var_os("TMUX").is_none() && pane.is_none() {
|
||||
return Options::default();
|
||||
|
||||
@@ -81,8 +81,8 @@ fn completed_probe_does_not_wait_for_descendant_holding_stdout() {
|
||||
#[test]
|
||||
fn input_probe_targets_the_containing_pane_and_only_disables_confirmed_mouse_off() {
|
||||
for (mouse, mouse_capture) in [
|
||||
("0", MouseCapture::DisabledByTmux),
|
||||
("off", MouseCapture::DisabledByTmux),
|
||||
("0", MouseCapture::Disabled),
|
||||
("off", MouseCapture::Disabled),
|
||||
("1", MouseCapture::Enabled),
|
||||
("on", MouseCapture::Enabled),
|
||||
("", MouseCapture::Enabled),
|
||||
@@ -122,7 +122,7 @@ fn visible_only_passthrough_disables_kitty_previews() {
|
||||
#[test]
|
||||
fn keyboard_fallback_preserves_confirmed_mouse_policy_without_guessing_on_failure() {
|
||||
for (output, mouse_capture) in [
|
||||
(Some(b"\t0\n".to_vec()), MouseCapture::DisabledByTmux),
|
||||
(Some(b"\t0\n".to_vec()), MouseCapture::Disabled),
|
||||
(Some(b"\t\n".to_vec()), MouseCapture::Enabled),
|
||||
(Some(vec![0xff]), MouseCapture::Enabled),
|
||||
(None, MouseCapture::Enabled),
|
||||
|
||||
@@ -858,7 +858,7 @@ impl TranscriptView {
|
||||
|
||||
pub(crate) fn tick_selection(&mut self, cells: &[Arc<dyn HistoryCell>]) -> bool {
|
||||
// A lost release can strand a Back to bottom press even without a text selection.
|
||||
if crate::tui::tmux_mouse_disabled() {
|
||||
if crate::tui::mouse_capture_disabled() {
|
||||
self.end_drag();
|
||||
return false;
|
||||
}
|
||||
|
||||
+30
-51
@@ -25,8 +25,6 @@ use crossterm::event::EnableBracketedPaste;
|
||||
use crossterm::event::EnableFocusChange;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::MouseEvent;
|
||||
#[cfg(not(unix))]
|
||||
use crossterm::terminal::supports_keyboard_enhancement;
|
||||
use ratatui::backend::Backend;
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::crossterm::execute;
|
||||
@@ -51,10 +49,9 @@ use crate::insert_history::HistoryLineWrapPolicy;
|
||||
use crate::insert_history::InsertHistoryMode;
|
||||
use crate::notifications::DesktopNotificationBackend;
|
||||
use crate::notifications::detect_backend;
|
||||
use crate::terminal_capabilities;
|
||||
use crate::terminal_capabilities::ScrollbackStrategy;
|
||||
use crate::terminal_capabilities::keyboard_modes;
|
||||
use crate::terminal_capabilities::scrollback_strategy;
|
||||
use crate::terminal_capabilities::tmux;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use crate::tui::alternate_screen::ALTERNATE_SCREEN;
|
||||
@@ -112,8 +109,8 @@ pub type Terminal = CustomTerminal<CrosstermBackend<Stdout>>;
|
||||
pub(crate) struct InitializedTerminal {
|
||||
pub(crate) terminal: Terminal,
|
||||
pub(crate) enhanced_keys_supported: bool,
|
||||
pub(crate) terminal_app_over_ssh: bool,
|
||||
pub(crate) herdr_kitty_graphics: Option<bool>,
|
||||
pub(crate) prefer_inline_screen: bool,
|
||||
pub(crate) probed_kitty_graphics: Option<bool>,
|
||||
pub(crate) stderr_guard: terminal_stderr::TerminalStderrGuard,
|
||||
}
|
||||
|
||||
@@ -124,9 +121,9 @@ pub(crate) fn reports_key_releases() -> bool {
|
||||
keyboard_modes::reports_key_releases()
|
||||
}
|
||||
|
||||
pub(crate) fn tmux_mouse_disabled() -> bool {
|
||||
pub(crate) fn mouse_capture_disabled() -> bool {
|
||||
ALTERNATE_SCREEN.is_active()
|
||||
&& ALTERNATE_SCREEN.tmux_mouse() == tmux::MouseCapture::DisabledByTmux
|
||||
&& ALTERNATE_SCREEN.mouse_policy() == terminal_capabilities::MouseCapture::Disabled
|
||||
}
|
||||
|
||||
fn should_emit_notification(condition: NotificationCondition, terminal_focused: bool) -> bool {
|
||||
@@ -257,7 +254,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_modes() -> Result<tmux::Options> {
|
||||
fn set_modes() -> Result<terminal_capabilities::SessionCapabilities> {
|
||||
ensure_virtual_terminal_processing()?;
|
||||
|
||||
execute!(stdout(), EnableBracketedPaste)?;
|
||||
@@ -515,7 +512,7 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
}
|
||||
custom_terminal::STDOUT_CURSOR_STYLED.store(false, Ordering::Relaxed);
|
||||
let mut restore_guard = TerminalInitializationGuard { active: true };
|
||||
let tmux_options = set_modes()?;
|
||||
let session = set_modes()?;
|
||||
|
||||
set_panic_hook();
|
||||
|
||||
@@ -523,10 +520,7 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
let backend = CrosstermBackend::new(stdout());
|
||||
|
||||
#[cfg(unix)]
|
||||
let probe_herdr = {
|
||||
let info = codex_terminal_detection::terminal_info();
|
||||
info.multiplexer.is_none() && info.term_program.as_deref() == Some("herdr")
|
||||
};
|
||||
let probe_kitty_graphics = terminal_capabilities::should_probe_kitty_graphics();
|
||||
|
||||
#[cfg(unix)]
|
||||
let startup_probe = {
|
||||
@@ -541,7 +535,7 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
match crate::terminal_probe::startup(
|
||||
crate::terminal_probe::DEFAULT_TIMEOUT,
|
||||
keyboard_probe,
|
||||
probe_herdr,
|
||||
probe_kitty_graphics,
|
||||
) {
|
||||
Ok(probe) => {
|
||||
tracing::info!(
|
||||
@@ -595,8 +589,7 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
let cursor_pos = cursor_position_with_crossterm(&mut backend);
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let enhanced_keys_supported =
|
||||
!keyboard_modes::keyboard_enhancement_disabled() && detect_keyboard_enhancement_supported();
|
||||
let enhanced_keys_supported = keyboard_modes::detect_keyboard_enhancement_supported();
|
||||
|
||||
#[cfg(windows)]
|
||||
// OSC replies can arrive after their deadline. Do not issue terminal queries before directory
|
||||
@@ -604,28 +597,21 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None);
|
||||
|
||||
let mut tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?;
|
||||
if std::env::var_os("TMUX").is_some()
|
||||
&& !["ZELLIJ", "ZELLIJ_SESSION_NAME", "ZELLIJ_VERSION"]
|
||||
.iter()
|
||||
.any(|key| std::env::var_os(key).is_some())
|
||||
&& !crossterm::style::Colored::ansi_color_disabled_memoized()
|
||||
{
|
||||
tui.tmux_kitty_image_base = tmux_options.kitty_image_base;
|
||||
}
|
||||
tui.tmux_kitty_image_base = session.virtual_image_base();
|
||||
let stderr_guard = terminal_stderr::TerminalStderrGuard::install()?;
|
||||
let initialized_terminal = InitializedTerminal {
|
||||
terminal: tui,
|
||||
enhanced_keys_supported,
|
||||
#[cfg(unix)]
|
||||
terminal_app_over_ssh: startup_probe
|
||||
.terminal_app_over_ssh
|
||||
prefer_inline_screen: startup_probe
|
||||
.prefer_inline_screen
|
||||
.unwrap_or(/*default*/ false),
|
||||
#[cfg(not(unix))]
|
||||
terminal_app_over_ssh: false,
|
||||
prefer_inline_screen: false,
|
||||
#[cfg(unix)]
|
||||
herdr_kitty_graphics: probe_herdr.then_some(startup_probe.kitty_graphics),
|
||||
probed_kitty_graphics: probe_kitty_graphics.then_some(startup_probe.kitty_graphics),
|
||||
#[cfg(not(unix))]
|
||||
herdr_kitty_graphics: None,
|
||||
probed_kitty_graphics: None,
|
||||
stderr_guard,
|
||||
};
|
||||
restore_guard.active = false;
|
||||
@@ -640,13 +626,6 @@ fn cursor_position_with_crossterm(backend: &mut CrosstermBackend<Stdout>) -> Pos
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn detect_keyboard_enhancement_supported() -> bool {
|
||||
// Non-Unix startup keeps the existing crossterm keyboard probe path because it already knows
|
||||
// how to interpret platform-specific event sources.
|
||||
supports_keyboard_enhancement().unwrap_or(/*default*/ false)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn probe_windows_default_colors() {
|
||||
let started_at = std::time::Instant::now();
|
||||
@@ -762,8 +741,8 @@ pub struct Tui {
|
||||
terminal_focused: Arc<AtomicBool>,
|
||||
enhanced_keys_supported: bool,
|
||||
// Cache the startup result so later configuration loads use the same terminal policy.
|
||||
pub(crate) terminal_app_over_ssh: bool,
|
||||
pub(crate) herdr_kitty_graphics: Option<bool>,
|
||||
pub(crate) prefer_inline_screen: bool,
|
||||
pub(crate) probed_kitty_graphics: Option<bool>,
|
||||
notification_backend: Option<DesktopNotificationBackend>,
|
||||
notification_condition: NotificationCondition,
|
||||
scrollback: ScrollbackStrategy,
|
||||
@@ -810,13 +789,12 @@ impl Tui {
|
||||
let frame_requester = FrameRequester::new(draw_tx.clone());
|
||||
|
||||
// Cache this to avoid contention with the event reader.
|
||||
crate::terminal_capabilities::stdout_color_level();
|
||||
terminal_capabilities::stdout_color_level();
|
||||
let _ = crate::terminal_palette::default_colors();
|
||||
let terminal_info = codex_terminal_detection::terminal_info();
|
||||
let scrollback = scrollback_strategy(&terminal_info);
|
||||
let (scrollback, poll_session) = terminal_capabilities::screen_capabilities();
|
||||
let mut event_broker = EventBroker::new();
|
||||
event_broker.size_monitor = size_monitor::SizeMonitor::start(
|
||||
&terminal_info,
|
||||
poll_session,
|
||||
terminal.last_known_screen_size,
|
||||
draw_tx.clone(),
|
||||
);
|
||||
@@ -842,8 +820,8 @@ impl Tui {
|
||||
alt_screen_active: Arc::new(AtomicBool::new(false)),
|
||||
terminal_focused: Arc::new(AtomicBool::new(true)),
|
||||
enhanced_keys_supported,
|
||||
terminal_app_over_ssh: false,
|
||||
herdr_kitty_graphics: None,
|
||||
prefer_inline_screen: false,
|
||||
probed_kitty_graphics: None,
|
||||
notification_backend: Some(detect_backend(NotificationMethod::default())),
|
||||
notification_condition: NotificationCondition::default(),
|
||||
scrollback,
|
||||
@@ -942,8 +920,8 @@ impl Tui {
|
||||
}
|
||||
|
||||
// Nested screens such as /resume retain the capture request across draws.
|
||||
// Apply a new tmux policy even if the screen never changes its request.
|
||||
fn refresh_tmux_mouse(&mut self) -> Result<()> {
|
||||
// Apply a new mouse policy even if the screen never changes its request.
|
||||
fn refresh_mouse_policy(&mut self) -> Result<()> {
|
||||
if ALTERNATE_SCREEN.is_active()
|
||||
&& let Some(mouse) = self
|
||||
.event_broker
|
||||
@@ -953,11 +931,12 @@ impl Tui {
|
||||
{
|
||||
// Selection ticks can run before this draw applies the policy. Give
|
||||
// even a stationary drag a chance to end without a button release.
|
||||
if mouse == tmux::MouseCapture::DisabledByTmux && mouse != ALTERNATE_SCREEN.tmux_mouse()
|
||||
if mouse == terminal_capabilities::MouseCapture::Disabled
|
||||
&& mouse != ALTERNATE_SCREEN.mouse_policy()
|
||||
{
|
||||
self.frame_requester.schedule_frame();
|
||||
}
|
||||
ALTERNATE_SCREEN.set_tmux_mouse(mouse);
|
||||
ALTERNATE_SCREEN.set_mouse_policy(mouse);
|
||||
self.set_mouse_capture(self.mouse_capture)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1558,7 +1537,7 @@ impl Tui {
|
||||
height: u16,
|
||||
draw_fn: impl FnOnce(&mut custom_terminal::Frame),
|
||||
) -> Result<()> {
|
||||
self.refresh_tmux_mouse()?;
|
||||
self.refresh_mouse_policy()?;
|
||||
let screen_size = self.take_event_screen_size()?;
|
||||
// If we are resuming from ^Z, we need to prepare the resume action now so we can apply it
|
||||
// in the synchronized update.
|
||||
@@ -1714,7 +1693,7 @@ impl Tui {
|
||||
hud: Option<crate::bottom_pane::ShortcutHud>,
|
||||
draw_fn: impl FnOnce(&mut custom_terminal::Frame),
|
||||
) -> Result<()> {
|
||||
self.refresh_tmux_mouse()?;
|
||||
self.refresh_mouse_policy()?;
|
||||
// This draw uses the caller's resolved geometry directly, so its reservation is consumed.
|
||||
self.screen_size.pending_draw_size = None;
|
||||
// If we are resuming from ^Z, we need to prepare the resume action now so we can apply it
|
||||
|
||||
@@ -24,7 +24,7 @@ use super::DisableAlternateScroll;
|
||||
use super::EnableAlternateScroll;
|
||||
use super::KeyboardRestore;
|
||||
use super::keyboard_modes;
|
||||
use super::tmux;
|
||||
use crate::terminal_capabilities;
|
||||
|
||||
// Panic and exit cleanup cannot borrow Tui. Track the actual screen independently of its owner.
|
||||
pub(super) static ALTERNATE_SCREEN: AlternateScreen = AlternateScreen {
|
||||
@@ -84,8 +84,11 @@ impl AlternateScreen {
|
||||
if self.mouse_active.load(Ordering::Relaxed) {
|
||||
self.link_pointer.update(writer, shape)
|
||||
} else {
|
||||
self.link_pointer
|
||||
.restore(writer, codex_terminal_detection::terminal_info().name)
|
||||
self.link_pointer.restore(
|
||||
writer,
|
||||
terminal_capabilities::PointerReset::detect()
|
||||
.unwrap_or(terminal_capabilities::PointerReset::Text),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,22 +108,22 @@ impl AlternateScreen {
|
||||
!cfg!(windows) && !keyboard_modes::keyboard_enhancement_disabled(),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
self.set_tmux_mouse(mouse_capture);
|
||||
self.set_mouse_policy(mouse_capture);
|
||||
self.configure_input(writer, capture_mouse)
|
||||
}
|
||||
|
||||
pub(super) fn tmux_mouse(&self) -> tmux::MouseCapture {
|
||||
pub(super) fn mouse_policy(&self) -> terminal_capabilities::MouseCapture {
|
||||
if self.mouse_capture_disabled.load(Ordering::Relaxed) {
|
||||
tmux::MouseCapture::DisabledByTmux
|
||||
terminal_capabilities::MouseCapture::Disabled
|
||||
} else {
|
||||
tmux::MouseCapture::Enabled
|
||||
terminal_capabilities::MouseCapture::Enabled
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_tmux_mouse(&self, mouse: tmux::MouseCapture) {
|
||||
if self.tmux_mouse() != mouse {
|
||||
pub(super) fn set_mouse_policy(&self, mouse: terminal_capabilities::MouseCapture) {
|
||||
if self.mouse_policy() != mouse {
|
||||
self.mouse_capture_disabled.store(
|
||||
mouse == tmux::MouseCapture::DisabledByTmux,
|
||||
mouse == terminal_capabilities::MouseCapture::Disabled,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
self.input_configured
|
||||
@@ -157,9 +160,11 @@ impl AlternateScreen {
|
||||
}
|
||||
|
||||
fn disable_mouse(&self, writer: &mut impl Write) -> Result<()> {
|
||||
let pointer_result = self
|
||||
.link_pointer
|
||||
.restore(writer, codex_terminal_detection::terminal_info().name);
|
||||
let pointer_result = self.link_pointer.restore(
|
||||
writer,
|
||||
terminal_capabilities::PointerReset::detect()
|
||||
.unwrap_or(terminal_capabilities::PointerReset::Text),
|
||||
);
|
||||
if self.mouse_active.load(Ordering::Relaxed) {
|
||||
let result = execute!(writer, DisableMouseCapture);
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -34,11 +34,11 @@ fn refreshed_mouse_policy_applies_to_fullscreen_and_overlays() {
|
||||
MouseCapture::Disabled,
|
||||
] {
|
||||
for mouse in [
|
||||
tmux::MouseCapture::Enabled,
|
||||
tmux::MouseCapture::DisabledByTmux,
|
||||
tmux::MouseCapture::Enabled,
|
||||
terminal_capabilities::MouseCapture::Enabled,
|
||||
terminal_capabilities::MouseCapture::Disabled,
|
||||
terminal_capabilities::MouseCapture::Enabled,
|
||||
] {
|
||||
screen.set_tmux_mouse(mouse);
|
||||
screen.set_mouse_policy(mouse);
|
||||
input.apply(&screen, &mut output, next, owned).unwrap();
|
||||
terminal.process(&std::mem::take(&mut output));
|
||||
let capture = match next {
|
||||
@@ -46,7 +46,7 @@ fn refreshed_mouse_policy_applies_to_fullscreen_and_overlays() {
|
||||
MouseCapture::Enabled => true,
|
||||
MouseCapture::Disabled => false,
|
||||
};
|
||||
let expected = if mouse == tmux::MouseCapture::Enabled && capture {
|
||||
let expected = if mouse == terminal_capabilities::MouseCapture::Enabled && capture {
|
||||
vt100::MouseProtocolMode::AnyMotion
|
||||
} else {
|
||||
vt100::MouseProtocolMode::None
|
||||
|
||||
@@ -347,7 +347,7 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
|
||||
Some(TuiEvent::FocusLost)
|
||||
}
|
||||
// A report queued before capture stopped can precede the cleanup draw.
|
||||
Event::Mouse(_) if super::tmux_mouse_disabled() => None,
|
||||
Event::Mouse(_) if super::mouse_capture_disabled() => None,
|
||||
Event::Mouse(mouse) => Some(TuiEvent::Mouse(mouse)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::io::Write;
|
||||
use std::sync::atomic::AtomicU8;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_terminal_detection::TerminalName;
|
||||
use crate::terminal_capabilities::PointerReset;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind;
|
||||
use ratatui::layout::Position;
|
||||
@@ -93,12 +93,12 @@ impl LinkPointer {
|
||||
pub(super) fn restore(
|
||||
&self,
|
||||
writer: &mut impl Write,
|
||||
terminal: TerminalName,
|
||||
reset: PointerReset,
|
||||
) -> std::io::Result<()> {
|
||||
if self.0.load(Ordering::Relaxed) != 0 {
|
||||
// In Kitty, a named shape persists across mouse capture and screen changes.
|
||||
// An empty OSC 22 releases that override back to the terminal's default policy.
|
||||
writer.write_all(if terminal == TerminalName::Kitty {
|
||||
writer.write_all(if reset == PointerReset::Release {
|
||||
b"\x1b]22;\x1b\\"
|
||||
} else {
|
||||
b"\x1b]22;text\x1b\\"
|
||||
@@ -112,12 +112,7 @@ impl LinkPointer {
|
||||
|
||||
impl Tui {
|
||||
pub(crate) fn set_pointer_shape(&mut self, shape: PointerShape) -> std::io::Result<()> {
|
||||
// OSC 22 names differ between terminals. Restrict CSS names to known implementations;
|
||||
// multiplexers may consume OSC 22 and do not promise pointer-shape passthrough.
|
||||
let info = codex_terminal_detection::terminal_info();
|
||||
if info.multiplexer.is_none()
|
||||
&& matches!(info.name, TerminalName::Ghostty | TerminalName::Kitty)
|
||||
{
|
||||
if PointerReset::detect().is_some() {
|
||||
super::alternate_screen::ALTERNATE_SCREEN
|
||||
.set_pointer_shape(self.terminal.backend_mut(), shape)?;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use pretty_assertions::assert_eq;
|
||||
#[test]
|
||||
fn hover_transitions_are_deduplicated_and_restore_after_leaving_a_link() {
|
||||
let mut frames = Vec::new();
|
||||
for terminal in [TerminalName::Ghostty, TerminalName::Kitty] {
|
||||
for terminal in [PointerReset::Text, PointerReset::Release] {
|
||||
let pointer = LinkPointer::default();
|
||||
let mut output = Vec::new();
|
||||
for shape in [Arrow, Link, Link, Resize, Resize, Arrow, Arrow, Link] {
|
||||
@@ -54,6 +54,29 @@ fn hover_transitions_are_deduplicated_and_restore_after_leaving_a_link() {
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn capture_release_restores_pointer_even_after_moving_off_link() {
|
||||
// Terminal identity is cached per process.
|
||||
const CHILD: &str = "CODEX_TUI_POINTER_RESET_CHILD";
|
||||
let Ok(expected) = std::env::var(CHILD) else {
|
||||
for (terminal, reset) in [
|
||||
("kitty", "\x1b]22;\x1b\\"),
|
||||
("ghostty", "\x1b]22;text\x1b\\"),
|
||||
] {
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tui::link_pointer::tests::capture_release_restores_pointer_even_after_moving_off_link"])
|
||||
.env(CHILD, reset)
|
||||
.env("TERM_PROGRAM", terminal)
|
||||
.env_remove("TMUX")
|
||||
.env_remove("TMUX_PANE")
|
||||
.env_remove("ZELLIJ")
|
||||
.env_remove("ZELLIJ_SESSION_NAME")
|
||||
.env_remove("ZELLIJ_VERSION")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{terminal} pointer cleanup failed");
|
||||
}
|
||||
return;
|
||||
};
|
||||
assert!(PointerReset::detect().is_some());
|
||||
for shape in [Link, Resize, Arrow] {
|
||||
let screen = super::super::alternate_screen::AlternateScreen::default();
|
||||
let mut output = Vec::new();
|
||||
@@ -64,12 +87,7 @@ fn capture_release_restores_pointer_even_after_moving_off_link() {
|
||||
screen.set_pointer_shape(&mut output, shape).unwrap();
|
||||
output.clear();
|
||||
screen.release_input(&mut output).unwrap();
|
||||
let expected = if codex_terminal_detection::terminal_info().name == TerminalName::Kitty {
|
||||
b"\x1b]22;\x1b\\".as_slice()
|
||||
} else {
|
||||
b"\x1b]22;text\x1b\\".as_slice()
|
||||
};
|
||||
assert!(output.starts_with(expected));
|
||||
assert!(output.starts_with(expected.as_bytes()));
|
||||
output.clear();
|
||||
screen.set_pointer_shape(&mut output, Link).unwrap();
|
||||
assert_eq!(output, Vec::<u8>::new());
|
||||
@@ -88,8 +106,8 @@ fn failed_write_is_retried_and_cleanup_remains_armed() {
|
||||
}
|
||||
}
|
||||
for (terminal, expected) in [
|
||||
(TerminalName::Ghostty, b"\x1b]22;text\x1b\\".as_slice()),
|
||||
(TerminalName::Kitty, b"\x1b]22;\x1b\\".as_slice()),
|
||||
(PointerReset::Text, b"\x1b]22;text\x1b\\".as_slice()),
|
||||
(PointerReset::Release, b"\x1b]22;\x1b\\".as_slice()),
|
||||
] {
|
||||
let pointer = LinkPointer::default();
|
||||
assert!(pointer.update(&mut Fails, Link).is_err());
|
||||
|
||||
@@ -13,10 +13,8 @@ use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use super::alternate_screen::ALTERNATE_SCREEN;
|
||||
use super::tmux;
|
||||
use crate::terminal_capabilities;
|
||||
|
||||
use codex_terminal_detection::Multiplexer;
|
||||
use codex_terminal_detection::TerminalInfo;
|
||||
use ratatui::layout::Size;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
@@ -29,7 +27,7 @@ struct State {
|
||||
size: Size,
|
||||
generation: u64,
|
||||
pending: Option<Size>,
|
||||
mouse: Option<tmux::MouseCapture>,
|
||||
mouse: Option<terminal_capabilities::MouseCapture>,
|
||||
active: bool,
|
||||
stopped: bool,
|
||||
}
|
||||
@@ -41,11 +39,11 @@ pub(super) struct SizeMonitor {
|
||||
|
||||
impl SizeMonitor {
|
||||
pub(super) fn start(
|
||||
terminal_info: &TerminalInfo,
|
||||
poll_session: bool,
|
||||
size: Size,
|
||||
draw_tx: broadcast::Sender<()>,
|
||||
) -> Option<Self> {
|
||||
if !cfg!(unix) || !matches!(terminal_info.multiplexer, Some(Multiplexer::Tmux { .. })) {
|
||||
if !poll_session {
|
||||
return None;
|
||||
}
|
||||
let mut last_mouse_check = Instant::now();
|
||||
@@ -54,7 +52,9 @@ impl SizeMonitor {
|
||||
&& last_mouse_check.elapsed() >= MOUSE_CHECK_INTERVAL
|
||||
{
|
||||
last_mouse_check = Instant::now();
|
||||
tmux::sample_mouse(previous_mouse.unwrap_or_else(|| ALTERNATE_SCREEN.tmux_mouse()))
|
||||
terminal_capabilities::sample_mouse(
|
||||
previous_mouse.unwrap_or_else(|| ALTERNATE_SCREEN.mouse_policy()),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -71,9 +71,11 @@ impl SizeMonitor {
|
||||
size: Size,
|
||||
draw_tx: broadcast::Sender<()>,
|
||||
mut query: impl FnMut(
|
||||
Option<tmux::MouseCapture>,
|
||||
) -> (io::Result<Size>, Option<tmux::MouseCapture>)
|
||||
+ Send
|
||||
Option<terminal_capabilities::MouseCapture>,
|
||||
) -> (
|
||||
io::Result<Size>,
|
||||
Option<terminal_capabilities::MouseCapture>,
|
||||
) + Send
|
||||
+ 'static,
|
||||
) -> io::Result<Self> {
|
||||
let state = Arc::new(Mutex::new(State {
|
||||
@@ -160,7 +162,7 @@ impl SizeMonitor {
|
||||
state.mouse = None;
|
||||
}
|
||||
|
||||
pub(super) fn mouse(&self) -> Option<tmux::MouseCapture> {
|
||||
pub(super) fn mouse(&self) -> Option<terminal_capabilities::MouseCapture> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::*;
|
||||
use codex_terminal_detection::Multiplexer;
|
||||
use codex_terminal_detection::TerminalInfo;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::task::Context;
|
||||
@@ -47,7 +49,10 @@ impl EventSource for KeySource {
|
||||
struct Harness {
|
||||
broker: Arc<EventBroker<KeySource>>,
|
||||
queries: tokio::sync::mpsc::UnboundedReceiver<()>,
|
||||
replies: std::sync::mpsc::Sender<(io::Result<Size>, Option<tmux::MouseCapture>)>,
|
||||
replies: std::sync::mpsc::Sender<(
|
||||
io::Result<Size>,
|
||||
Option<terminal_capabilities::MouseCapture>,
|
||||
)>,
|
||||
draws: broadcast::Receiver<()>,
|
||||
}
|
||||
|
||||
@@ -199,8 +204,8 @@ async fn unchanged_invalid_and_failed_samples_do_not_redraw() {
|
||||
async fn mouse_change_wakes_idle_screen_and_ignores_stale_or_failed_probes() {
|
||||
let size = Size::new(/*width*/ 80, /*height*/ 24);
|
||||
let mut harness = Harness::new(size);
|
||||
let off = Some(tmux::MouseCapture::DisabledByTmux);
|
||||
let on = Some(tmux::MouseCapture::Enabled);
|
||||
let off = Some(terminal_capabilities::MouseCapture::Disabled);
|
||||
let on = Some(terminal_capabilities::MouseCapture::Enabled);
|
||||
harness.next_query().await;
|
||||
for (sample, expected, redraw) in [
|
||||
(off, off, true),
|
||||
@@ -281,12 +286,31 @@ fn monitor_requires_tmux_detection() {
|
||||
multiplexer: None,
|
||||
};
|
||||
let size = Size::new(/*width*/ 80, /*height*/ 24);
|
||||
assert!(SizeMonitor::start(&info, size, draw_tx.clone()).is_none());
|
||||
assert!(
|
||||
SizeMonitor::start(
|
||||
terminal_capabilities::needs_session_polling(&info),
|
||||
size,
|
||||
draw_tx.clone()
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
info.multiplexer = Some(Multiplexer::Zellij { version: None });
|
||||
assert!(SizeMonitor::start(&info, size, draw_tx.clone()).is_none());
|
||||
assert!(
|
||||
SizeMonitor::start(
|
||||
terminal_capabilities::needs_session_polling(&info),
|
||||
size,
|
||||
draw_tx.clone()
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
info.multiplexer = Some(Multiplexer::Tmux { version: None });
|
||||
assert_eq!(
|
||||
SizeMonitor::start(&info, size, draw_tx).is_some(),
|
||||
SizeMonitor::start(
|
||||
terminal_capabilities::needs_session_polling(&info),
|
||||
size,
|
||||
draw_tx
|
||||
)
|
||||
.is_some(),
|
||||
cfg!(unix)
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user