diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index 3a479a36e..f3a41a229 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -912,7 +912,7 @@ fn on_reverse_request(mgr: &Arc, s: &Arc, seq: i64, comma /// A `runInTerminal` program and the pseudo-terminal it runs in. pub(crate) struct ProgramTerminal { - writer: ide_core::input::InputWriter, + writer: Arc, killer: Box, #[cfg_attr(not(unix), allow(dead_code))] pid: Option, @@ -1025,10 +1025,12 @@ pub(crate) fn run_in_terminal(s: &Arc, args: &Value) -> Result, args: &Value) -> Result (Vec, usize) { + let mut out = Vec::with_capacity(chunk.len()); + let mut queries = 0; + let mut rest = chunk; + while let Some(at) = rest.windows(CURSOR_QUERY.len()).position(|w| w == CURSOR_QUERY) { + out.extend_from_slice(&rest[..at]); + rest = &rest[at + CURSOR_QUERY.len()..]; + queries += 1; + } + out.extend_from_slice(rest); + (out, queries) +} + +/// Length of the end of `pending` that may begin a cursor position query the next read completes. +pub(crate) fn partial_cursor_query(pending: &[u8]) -> usize { + (1..CURSOR_QUERY.len()).rev().find(|&n| pending.ends_with(&CURSOR_QUERY[..n])).unwrap_or(0) +} + +/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept). The debug +/// console is no terminal, so cursor position queries are answered here (top-left corner). fn forward_terminal_output( s: &Session, mut reader: Box, + answer: Arc, #[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static, ) { let session = s.id; @@ -1078,11 +1105,20 @@ fn forward_terminal_output( break; } } - // Keep incomplete UTF-8 sequences, and a `\r` that may start a `\r\n`, for the next chunk. - let mut valid = match std::str::from_utf8(&pending) { - Ok(_) => pending.len(), + let (rest, queries) = take_cursor_queries(&pending); + pending = rest; + for _ in 0..queries { + if let Err(e) = answer.write(b"\x1b[1;1R") { + tracing::warn!(%session, "debug terminal cursor position: {e}"); + } + } + // Keep incomplete UTF-8 sequences, a `\r` that may start a `\r\n`, and the start of + // a cursor position query for the next chunk. + let keep = partial_cursor_query(&pending); + let mut valid = match std::str::from_utf8(&pending[..pending.len() - keep]) { + Ok(_) => pending.len() - keep, Err(e) if e.error_len().is_none() => e.valid_up_to(), - Err(_) => pending.len(), + Err(_) => pending.len() - keep, }; if valid > 0 && pending[valid - 1] == b'\r' { valid -= 1; diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index 646420a52..0de96e082 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -1010,6 +1010,44 @@ async fn run_in_terminal_spawns_debuggee() { assert!(response["body"]["processId"].as_u64().unwrap() > 0); } +/// The debug console answers a terminal's cursor position query: ConPTY asks one before it runs +/// the program at all (Windows debuggees never started), and programs that lay out a prompt ask too. +#[tokio::test] +async fn run_in_terminal_answers_cursor_position_queries() { + #[cfg(unix)] + let program = vec![ + "sh".into(), + "-c".into(), + r"stty -echo -icanon min 6; printf '\033[6n'; reply=$(dd bs=6 count=1 2>/dev/null); stty sane; case $reply in *'[1;1R') echo answered;; esac".into(), + ]; + #[cfg(windows)] + let program = vec!["cmd".into(), "/c".into(), "echo answered".into()]; + let h = harness(Script { run_in_terminal: Some(program), ..Script::default() }); + h.start(config()).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output.contains("answered"))).await; + let output: String = h + .events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } => Some(output.clone()), + _ => None, + }) + .collect(); + assert!(!output.contains("\x1b[6n"), "{output:?}"); +} + +#[test] +fn cursor_position_queries_are_taken_out_of_the_output() { + use crate::session::{partial_cursor_query, take_cursor_queries}; + assert_eq!(take_cursor_queries(b"a\x1b[6nb\x1b[6n"), (b"ab".to_vec(), 2)); + assert_eq!(take_cursor_queries(b"\x1b[0mtext"), (b"\x1b[0mtext".to_vec(), 0)); + assert_eq!(partial_cursor_query(b"text\x1b["), 2); + assert_eq!(partial_cursor_query(b"text\x1b[6"), 3); + assert_eq!(partial_cursor_query(b"text\x1b[0m"), 0); + assert_eq!(partial_cursor_query(b"text"), 0); +} + #[cfg(unix)] #[tokio::test] async fn run_in_terminal_program_reads_typed_input() {