Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 3 additions & 103 deletions crates/jcode-tui/src/tui/app/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3164,113 +3164,13 @@ pub(super) fn handle_swarm_prompt_command(app: &mut App, trimmed: &str) -> bool
fn run_interactive_editor(
command: &mut std::process::Command,
) -> std::io::Result<std::process::ExitStatus> {
run_interactive_editor_with(
crate::tui::run_interactive_editor_with(
command,
suspend_terminal_for_editor,
resume_terminal_after_editor,
crate::tui::suspend_terminal_for_editor,
crate::tui::resume_terminal_after_editor,
)
}

fn run_interactive_editor_with(
command: &mut std::process::Command,
suspend: impl FnOnce(),
resume: impl FnOnce(),
) -> std::io::Result<std::process::ExitStatus> {
suspend();
let result = command.status();
resume();
result
}

fn suspend_terminal_for_editor() {
use crossterm::event::{DisableBracketedPaste, DisableFocusChange, DisableMouseCapture};

// These commands are safe even when a mode was not enabled. Disable them
// before leaving the alternate screen so the child receives normal input.
let _ = crossterm::execute!(
std::io::stdout(),
DisableBracketedPaste,
DisableFocusChange,
DisableMouseCapture
);
crate::tui::disable_keyboard_enhancement();
jcode_tui_style::restore_terminal_quietly();
}

fn resume_terminal_after_editor() {
use crossterm::event::{EnableBracketedPaste, EnableFocusChange, EnableMouseCapture};

// Re-enter the TUI before returning to the event loop. The existing
// ratatui Terminal remains usable and the next loop iteration redraws it.
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(ratatui::init));
let policy = crate::perf::tui_policy();
let _ = crossterm::execute!(std::io::stdout(), EnableBracketedPaste);
if policy.enable_focus_change {
let _ = crossterm::execute!(std::io::stdout(), EnableFocusChange);
}
if policy.enable_mouse_capture {
let _ = crossterm::execute!(std::io::stdout(), EnableMouseCapture);
}
if policy.enable_keyboard_enhancement {
crate::tui::enable_keyboard_enhancement();
}
}

#[cfg(all(test, unix))]
mod interactive_editor_tests {
use super::run_interactive_editor_with;
use std::cell::RefCell;
use std::rc::Rc;

#[test]
fn handoff_waits_for_editor_before_resuming_terminal() {
let events = Rc::new(RefCell::new(Vec::new()));
let child_events = Rc::clone(&events);
let mut command = std::process::Command::new("sh");
command.args(["-c", "sleep 0.05"]);

let started = std::time::Instant::now();
let status = run_interactive_editor_with(
&mut command,
{
let events = Rc::clone(&events);
move || events.borrow_mut().push("suspend")
},
move || {
assert!(
started.elapsed() >= std::time::Duration::from_millis(40),
"terminal resumed before the editor process exited"
);
child_events.borrow_mut().push("resume");
},
)
.expect("editor command should run");

assert!(status.success());
assert_eq!(&*events.borrow(), &["suspend", "resume"]);
}

#[test]
fn handoff_resumes_terminal_after_editor_failure_status() {
let resumed = Rc::new(RefCell::new(false));
let resumed_after = Rc::clone(&resumed);
let mut command = std::process::Command::new("sh");
command.args(["-c", "exit 7"]);

let status = run_interactive_editor_with(
&mut command,
|| {},
move || {
*resumed_after.borrow_mut() = true;
},
)
.expect("shell should launch");

assert_eq!(status.code(), Some(7));
assert!(*resumed.borrow());
}
}

pub(super) fn handle_agents_command(app: &mut App, trimmed: &str) -> bool {
if !trimmed.starts_with("/agents") {
return false;
Expand Down
248 changes: 2 additions & 246 deletions crates/jcode-tui/src/tui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,252 +119,8 @@ pub use jcode_tui_core::{
};
pub use jcode_tui_messages::DisplayMessage;

fn keyboard_enhancement_flags() -> crossterm::event::KeyboardEnhancementFlags {
use crossterm::event::KeyboardEnhancementFlags;

if std::env::var_os("KCODE_DISABLE_KITTY_KEYBOARD").is_some() {
return KeyboardEnhancementFlags::empty();
}
// Only disambiguate escape codes. REPORT_EVENT_TYPES makes terminals emit
// press AND release events; hosts that half-support the kitty protocol
// (herdr/conpty panes) leak releases into the prompt as "[<code>;1:3u".
KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
}

/// Request Kitty keyboard reporting and tmux's extended-key mode.
///
/// Avoids REPORT_ALL_KEYS_AS_ESCAPE_CODES: with it, kitty/Alacritty/Warp report
/// printable keys as base key plus modifiers instead of the text the active
/// layout produces, and crossterm cannot reconstruct shifted symbols for every
/// layout. Prefer the terminal-delivered character and only synthesize ASCII
/// letter casing in the input fallback.
///
/// On Windows, keep native console key records: Crossterm has no CSI-u decoder
/// there. Focus/resume must follow the same policy even if the config enables it.
///
/// Returns whether the requests were written, not whether the terminal supports them.
pub fn enable_keyboard_enhancement() -> bool {
let result = enable_keyboard_enhancement_to(&mut std::io::stdout(), inside_tmux()).is_ok();
crate::logging::info(&format!(
"Keyboard enhancement request: {}",
if result { "sent" } else { "FAILED" }
));
result
}

fn inside_tmux() -> bool {
std::env::var_os("TMUX").is_some_and(|value| !value.is_empty())
}

fn enable_keyboard_enhancement_to(
writer: &mut impl std::io::Write,
inside_tmux: bool,
) -> std::io::Result<()> {
keyboard_protocol::write_mode(
writer,
keyboard_protocol::Action::Push,
inside_tmux,
keyboard_enhancement_flags().bits(),
)
}

/// Reset extended keyboard reporting only for a decoder that enabled it.
pub fn disable_keyboard_enhancement() {
let _ = disable_keyboard_enhancement_to(&mut std::io::stdout(), inside_tmux());
}

fn disable_keyboard_enhancement_to(
writer: &mut impl std::io::Write,
inside_tmux: bool,
) -> std::io::Result<()> {
keyboard_protocol::write_mode(
writer,
keyboard_protocol::Action::Pop,
inside_tmux,
keyboard_enhancement_flags().bits(),
)
}

fn reapply_keyboard_enhancement_to(
writer: &mut impl std::io::Write,
inside_tmux: bool,
) -> std::io::Result<()> {
keyboard_protocol::write_mode(
writer,
keyboard_protocol::Action::Set,
inside_tmux,
keyboard_enhancement_flags().bits(),
)
}

/// Reassert terminal modes that terminals may clear while the TUI remains alive.
///
/// Kitty keyboard enhancement uses its `set` form rather than the stack-based
/// `push`, keeping the shutdown pop balanced. Enabling focus reporting may itself
/// produce a focus event, so focus-event handlers must pass `focus_change = false`.
pub(crate) fn reapply_terminal_modes_to(
writer: &mut impl std::io::Write,
mouse_capture: bool,
keyboard_enhanced: bool,
focus_change: bool,
) -> std::io::Result<()> {
use crossterm::QueueableCommand;
use crossterm::event::{EnableBracketedPaste, EnableFocusChange, EnableMouseCapture};

writer.queue(EnableBracketedPaste)?;
if focus_change {
writer.queue(EnableFocusChange)?;
}
if mouse_capture {
writer.queue(EnableMouseCapture)?;
// Crossterm toggles Win32 console mouse input on Windows, but ConPTY
// hosts such as VS Code also need the VT tracking modes reasserted.
#[cfg(windows)]
writer.write_all(b"\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1015h\x1b[?1006h")?;
}
if keyboard_enhanced {
reapply_keyboard_enhancement_to(writer, inside_tmux())?;
}
writer.flush()
}

pub(crate) fn reapply_configured_terminal_modes_after_focus() {
let policy = crate::perf::tui_policy();
if let Err(error) = reapply_terminal_modes_after_focus_to(
&mut std::io::stdout(),
policy.enable_mouse_capture,
policy.enable_keyboard_enhancement,
) {
crate::logging::warn(&format!("failed to reapply terminal modes: {error}"));
}
}

fn reapply_terminal_modes_after_focus_to(
writer: &mut impl std::io::Write,
mouse_capture: bool,
keyboard_enhanced: bool,
) -> std::io::Result<()> {
reapply_terminal_modes_to(
writer,
mouse_capture,
keyboard_enhanced,
// Ghostty reports its current focus when mode 1004 is enabled. Re-arming
// it from FocusGained would feed that reply back into this handler forever.
// Startup and resume-after-editor still enable focus reporting normally.
false,
)
}

#[cfg(test)]
mod terminal_mode_tests {
#[cfg(not(windows))]
use super::{
disable_keyboard_enhancement_to, enable_keyboard_enhancement_to,
reapply_keyboard_enhancement_to,
};
use super::{reapply_terminal_modes_after_focus_to, reapply_terminal_modes_to};

#[test]
#[cfg(not(windows))]
fn tmux_keyboard_lifecycle_requests_and_resets_extended_keys() {
let mut output = Vec::new();
enable_keyboard_enhancement_to(&mut output, true).unwrap();
assert_eq!(output, b"\x1b[>4;2m\x1b[>1u");

output.clear();
reapply_keyboard_enhancement_to(&mut output, true).unwrap();
assert_eq!(output, b"\x1b[>4;2m\x1b[=1u");

output.clear();
disable_keyboard_enhancement_to(&mut output, true).unwrap();
assert_eq!(output, b"\x1b[>4;0m\x1b[<1u");
}

#[test]
#[cfg(not(windows))]
fn outside_tmux_keyboard_lifecycle_keeps_kitty_protocol_only() {
let mut output = Vec::new();
enable_keyboard_enhancement_to(&mut output, false).unwrap();
assert_eq!(output, b"\x1b[>1u");

output.clear();
reapply_keyboard_enhancement_to(&mut output, false).unwrap();
assert_eq!(output, b"\x1b[=1u");

output.clear();
disable_keyboard_enhancement_to(&mut output, false).unwrap();
assert_eq!(output, b"\x1b[<1u");
}

#[test]
fn reapply_omits_keyboard_protocols_when_disabled() {
let mut output = Vec::new();
reapply_terminal_modes_to(&mut output, false, false, false).unwrap();
assert_eq!(output, b"\x1b[?2004h");
}

#[test]
fn reapply_omits_mouse_sequences_when_capture_is_disabled() {
let mut output = Vec::new();
reapply_terminal_modes_to(&mut output, false, true, true).unwrap();

let output = String::from_utf8(output).unwrap();
assert!(output.starts_with("\x1b[?2004h\x1b[?1004h"));
assert!(!output.contains("\x1b[?1000h"));
assert_eq!(output.contains("\x1b[="), !cfg!(windows));
}

#[test]
fn reapply_emits_configured_idempotent_modes_without_keyboard_push() {
let mut output = Vec::new();
reapply_terminal_modes_to(&mut output, true, true, true).unwrap();

let output = String::from_utf8(output).unwrap();
assert!(output.contains("\x1b[?2004h"));
assert!(output.contains("\x1b[?1004h"));
assert!(output.contains("\x1b[?1000h"));
assert_eq!(output.contains("\x1b[="), !cfg!(windows));
assert!(
!output.contains("\x1b[>7u"),
"must not push the Kitty keyboard stack"
);
}

#[test]
fn focus_reapply_preserves_other_modes_without_rearming_focus_reporting() {
for mouse_capture in [false, true] {
for keyboard_enhanced in [false, true] {
let mut output = Vec::new();
reapply_terminal_modes_after_focus_to(
&mut output,
mouse_capture,
keyboard_enhanced,
)
.unwrap();

let output = String::from_utf8(output).unwrap();
assert!(output.starts_with("\x1b[?2004h"));
assert!(
!output.contains("\x1b[?1004h"),
"must not trigger a focus reply"
);
assert!(
!output.contains("\x1b[?1004l"),
"must keep focus reporting enabled"
);
assert_eq!(output.contains("\x1b[?1000h"), mouse_capture);
assert_eq!(
output.contains("\x1b[=1u"),
keyboard_enhanced && !cfg!(windows)
);
assert!(
!output.contains("\x1b[>7u"),
"must not push the Kitty keyboard stack (tmux modifyOtherKeys is allowed)"
);
}
}
}
}
mod terminal_modes;
pub use terminal_modes::*;

/// Hash a rendered image's transcript anchor into `hasher`. Shared by the
/// default and `App` implementations of `side_pane_images_signature` so both
Expand Down
Loading
Loading