From 78b738a94c5a59799172e96c2c269f2cb60218b1 Mon Sep 17 00:00:00 2001 From: CharOfString Date: Thu, 15 Oct 2026 22:14:12 -0500 Subject: [PATCH] feat: Terminal wrapper --- Cargo.lock | 116 +++++++++- Cargo.toml | 2 + doc/shortcuts/shortcuts.md | 17 ++ doc/shortcuts/shortcuts.zh.md | 16 ++ src/app.rs | 14 +- src/buffers/completion/keys.rs | 3 +- src/buffers/cpp_checks/tests.rs | 3 + src/buffers/menu/mod.rs | 2 +- src/buffers/mod.rs | 1 + src/buffers/render.rs | 27 ++- src/buffers/terminal.rs | 395 ++++++++++++++++++++++++++++++++ src/buffers/terminal/tests.rs | 225 ++++++++++++++++++ 12 files changed, 808 insertions(+), 13 deletions(-) create mode 100644 src/buffers/terminal.rs create mode 100644 src/buffers/terminal/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 13f6905..83a236c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -49,6 +49,12 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + [[package]] name = "atomic" version = "0.6.1" @@ -168,6 +174,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "cfg_aliases" version = "0.2.2" @@ -400,6 +412,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "either" version = "1.18.0" @@ -783,7 +801,7 @@ version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303" dependencies = [ - "nix", + "nix 0.29.0", "winapi", ] @@ -842,6 +860,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases 0.1.1", + "libc", +] + [[package]] name = "nix" version = "0.29.0" @@ -850,7 +880,7 @@ checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ "bitflags 2.13.2", "cfg-if", - "cfg_aliases", + "cfg_aliases 0.2.2", "libc", "memoffset", ] @@ -1156,6 +1186,27 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix 0.28.0", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -1177,10 +1228,12 @@ version = "0.1.4" dependencies = [ "crossterm", "lsp-types", + "portable-pty", "ratatui", "ratatui-code-editor", "serde_json", "unicode-width", + "vt100", ] [[package]] @@ -1549,6 +1602,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serial2" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730" +dependencies = [ + "cfg-if", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "sha2" version = "0.10.9" @@ -1571,6 +1635,22 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "2.0.1" @@ -1762,7 +1842,7 @@ dependencies = [ "libc", "log", "memmem", - "nix", + "nix 0.29.0", "num-derive", "num-traits", "ordered-float", @@ -2098,6 +2178,27 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vt100" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +dependencies = [ + "itoa", + "unicode-width", + "vte", +] + +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "vtparse" version = "0.6.2" @@ -2369,6 +2470,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index e047e5d..594f526 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,9 @@ edition = "2024" [dependencies] crossterm = "0.29" lsp-types = "0.97" +portable-pty = "0.9.0" ratatui = "0.30.2" ratatui-code-editor = { version = "0.0.6", features = ["crossterm"] } serde_json = "1.0.151" unicode-width = "0.2" +vt100 = "0.16.2" diff --git a/doc/shortcuts/shortcuts.md b/doc/shortcuts/shortcuts.md index b603c0b..877ce0e 100644 --- a/doc/shortcuts/shortcuts.md +++ b/doc/shortcuts/shortcuts.md @@ -13,3 +13,20 @@ * **Search forward / backward**: `Ctrl + S` / `Ctrl + R`. (`Enter` to stop, `Ctrl + G` to go back.) * **Query replace**: `Alt + %`. Then answer at each match: `Y`/`Space` replace, `N` skip, `!` replace all, `.` replace and stop, `Q` stop. * **Go to line**: `Alt + G` `G` (or `Alt + G` `Alt + G`). + +## Terminal + +* `Ctrl + C` `T` `T`: open or hide the terminal. Hiding it keeps the shell running. +* `Ctrl + X` `O`: switch focus between the editor and the visible terminal. +* `Ctrl + C` `T` `C`: run Clang-tidy. +* `Alt + V` / `Ctrl + V`: scroll terminal history up / down one page. + `Shift + PageUp` / `Shift + PageDown` also work. Up to 1000 history rows are kept. + These shortcuts apply while the terminal has focus; typing returns to the latest output. + In alternate-screen programs, these keys go to the program instead. +* Shell keys, including Ctrl-C and Ctrl-D, go to the terminal while it has focus. + Switch back with `Ctrl + X` `O` before using editor commands. + +The terminal opens below the editor when the workspace has at least 28 rows; +otherwise it opens on the right. It starts in the current file's directory, +or the editor's working directory for an unnamed file. After the shell exits, +hide and reopen the terminal to start a new session. diff --git a/doc/shortcuts/shortcuts.zh.md b/doc/shortcuts/shortcuts.zh.md index 1426d19..e397bd0 100644 --- a/doc/shortcuts/shortcuts.zh.md +++ b/doc/shortcuts/shortcuts.zh.md @@ -12,3 +12,19 @@ * **向前 / 向后查找**: `Ctrl + S` / `Ctrl + R`. (`Enter`结束,`Ctrl + G`回到起点) * **逐个替换**: `Alt + %`. (`Y`/`空格`替换,`N`跳过,`!`全部替换,`.`替换后结束,`Q`结束) * **跳转到行**: `Alt + G` `G` (或`Alt + G` `Alt + G`). + +## 终端 + +* `Ctrl + C` `T` `T`:打开或隐藏终端。隐藏后 Shell 继续运行。 +* `Ctrl + X` `O`:在编辑器和已显示的终端之间切换焦点。 +* `Ctrl + C` `T` `C`:运行 Clang-tidy。 +* `Alt + V` / `Ctrl + V`:向上 / 向下翻阅终端历史输出。 + 也支持 `Shift + PageUp` / `Shift + PageDown`,最多保留 1000 行历史。 + 这些快捷键在终端获得焦点时生效;输入时自动回到最新输出。 + 程序使用备用屏幕时,这些按键仍传给程序。 +* 终端获得焦点时,Ctrl-C、Ctrl-D 等按键会传给 Shell。 + 使用编辑器命令前,请按 `Ctrl + X` `O` 切回编辑器。 + +工作区高度不少于 28 行时,终端显示在编辑器下方;否则显示在右侧。 +Shell 在当前文件的目录启动;未命名文件则使用编辑器的工作目录。 +Shell 退出后,隐藏并重新打开终端即可启动新会话。 diff --git a/src/app.rs b/src/app.rs index f612f07..5024fbe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -26,11 +26,14 @@ use std::{ #[derive(Default)] pub(crate) struct App { pub(crate) buffer: Buffer, + pub(crate) terminal: crate::buffers::terminal::Terminal, pub(crate) menu: crate::buffers::menu::Menu, pub(crate) editor_area: Rect, exit_flag: bool, - ctrl_x_wait_flag: bool, + pub(crate) ctrl_x_wait_flag: bool, pub(crate) ctrl_c_wait_flag: bool, + // Set after C-c t, which starts terminal and tool commands. + pub(crate) ctrl_c_t_wait_flag: bool, kill_ring: Option, pub(crate) overwrite_confirm: bool, pub(crate) save_path_input: Option, @@ -62,7 +65,8 @@ impl App { // Talk to the language server, then draw a new frame. self.sync_lsp(); - if !self.ctrl_x_wait_flag && !self.ctrl_c_wait_flag { + self.terminal.poll(); + if !self.ctrl_x_wait_flag && !self.ctrl_c_wait_flag && !self.ctrl_c_t_wait_flag { self.poll_cpp_check(); } @@ -71,7 +75,8 @@ impl App { // Wait for event; ignore key release to avoid handling a keystroke twice. // Wake up sooner while a completion answer is expected. let mut timeout = interval.saturating_sub(last_disk_check.elapsed()); - if self.completion.is_waiting() || self.quick_fix.is_waiting() { + if self.terminal.visible || self.completion.is_waiting() || self.quick_fix.is_waiting() + { timeout = timeout.min(Duration::from_millis(20)); } if event::poll(timeout)? @@ -87,6 +92,9 @@ impl App { } pub(crate) fn handle_key(&mut self, key: KeyEvent) { + if self.handle_terminal_key(key) { + return; + } // Print key in buffer command section in bottom tool bar. let prefix = match (self.ctrl_x_wait_flag, self.ctrl_c_wait_flag) { (true, _) => "C-x ", diff --git a/src/buffers/completion/keys.rs b/src/buffers/completion/keys.rs index 178a9a9..bd0b83c 100644 --- a/src/buffers/completion/keys.rs +++ b/src/buffers/completion/keys.rs @@ -41,7 +41,8 @@ impl App { use crate::buffers::cpp_checks::Tool; match key.code { KeyCode::Char('l') => self.run_cpp_check(Tool::Cpplint), - KeyCode::Char('t') => self.run_cpp_check(Tool::Tidy), + // C-c t is a prefix; handle_terminal_key reads the next key. + KeyCode::Char('t') => self.ctrl_c_t_wait_flag = true, KeyCode::Char('a') => self.request_fix(), _ => {} } diff --git a/src/buffers/cpp_checks/tests.rs b/src/buffers/cpp_checks/tests.rs index 6fd2d1e..fce5519 100644 --- a/src/buffers/cpp_checks/tests.rs +++ b/src/buffers/cpp_checks/tests.rs @@ -82,6 +82,9 @@ fn cpp_only_toggles_and_shortcuts_do_not_edit() { for key in ['t', 'l'] { app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); press(&mut app, KeyCode::Char(key)); + if key == 't' { + press(&mut app, KeyCode::Char('c')); + } assert!(app.status_bar_text.contains("disabled")); } assert_eq!(app.buffer.editor.get_content(), before); diff --git a/src/buffers/menu/mod.rs b/src/buffers/menu/mod.rs index 31f99ea..9f868d8 100644 --- a/src/buffers/menu/mod.rs +++ b/src/buffers/menu/mod.rs @@ -78,7 +78,7 @@ fn cpp_entries(settings: &Settings) -> Vec<(&'static str, &'static str, CppActio ]; if settings.tidy { - entries.push(("Run Clang-tidy", "C-c t", CppAction::Run(Tool::Tidy))); + entries.push(("Run Clang-tidy", "C-c t c", CppAction::Run(Tool::Tidy))); } if settings.cpplint_ready() { diff --git a/src/buffers/mod.rs b/src/buffers/mod.rs index 28cc449..8818f13 100644 --- a/src/buffers/mod.rs +++ b/src/buffers/mod.rs @@ -23,3 +23,4 @@ pub(crate) mod goto_line; pub(crate) mod menu; mod render; pub(crate) mod search; +pub(crate) mod terminal; diff --git a/src/buffers/render.rs b/src/buffers/render.rs index 6fcc3e7..9625b07 100644 --- a/src/buffers/render.rs +++ b/src/buffers/render.rs @@ -30,6 +30,16 @@ impl App { .areas(frame.area()); self.menu.draw_bar(frame, menu_area, self.is_c_or_cpp()); + let editor_area = if self.terminal.visible { + let [editor, terminal] = super::terminal::split(editor_area); + if let Err(err) = self.terminal.draw(frame, terminal) { + self.status_bar_text = format!("Terminal resize failed: {err}"); + } + editor + } else { + editor_area + }; + // Editor buffer. let name = self .buffer @@ -70,7 +80,8 @@ impl App { self.draw_completion(frame); self.draw_fix_chooser(frame); self.draw_diagnostic_popup(frame); - if !self.cpp_check_modal() + if !self.terminal.focused + && !self.cpp_check_modal() && self.save_path_input.is_none() && !self.search.reads_input() && !self.goto_line.is_open() @@ -100,22 +111,28 @@ impl App { .path .as_ref() .map_or_else(|| "[No Name]".to_owned(), |path| path.display().to_string()); + // A focused terminal takes all keys, so show its keys instead. + let hints = if self.terminal.focused { + "C-x o: focus ※ M-v/C-v: scroll" + } else { + "F10: menu ※ C-c t t: terminal" + }; if self.status_bar_text.is_empty() { if self.buffer_command.is_empty() { - format!(" {name} ※ F10: menu") + format!(" {name} ※ {hints}") } else { format!( - " {name} ※ F10: menu ※ Buffer command: {}", + " {name} ※ {hints} ※ Buffer command: {}", self.buffer_command ) } } else { if self.buffer_command.is_empty() { - format!(" {name} ※ F10: menu ※ {}", self.status_bar_text) + format!(" {name} ※ {hints} ※ {}", self.status_bar_text) } else { format!( - " {name} ※ F10: menu ※ Buffer command: {} ※ {}", + " {name} ※ {hints} ※ Buffer command: {} ※ {}", self.buffer_command, self.status_bar_text ) } diff --git a/src/buffers/terminal.rs b/src/buffers/terminal.rs new file mode 100644 index 0000000..131ce69 --- /dev/null +++ b/src/buffers/terminal.rs @@ -0,0 +1,395 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system}; +use ratatui::{ + Frame, + layout::{Constraint, Layout, Rect}, + style::{Color, Modifier, Style}, + widgets::{Block, BorderType}, +}; +use std::{ + io::{self, Read, Write}, + path::Path, + sync::mpsc::{self, Receiver}, +}; + +// Keep the shell alive when its pane is hidden. +#[derive(Default)] +pub(crate) struct Terminal { + session: Option, + pub(crate) visible: bool, + pub(crate) focused: bool, +} + +struct Session { + master: Box, + writer: Box, + child: Box, + output: Receiver>, + parser: vt100::Parser, + exited: bool, +} + +// Keep the window title that the shell sets with OSC 0 or OSC 2. +#[derive(Default)] +struct Title(String); + +impl vt100::Callbacks for Title { + fn set_window_title(&mut self, _: &mut vt100::Screen, title: &[u8]) { + // Drop control characters so they cannot break the border. + let title = String::from_utf8_lossy(title); + self.0 = title.chars().filter(|c| !c.is_control()).collect(); + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +impl Session { + fn start(cwd: Option<&Path>) -> io::Result<Self> { + let pair = native_pty_system() + .openpty(size(24, 80)) + .map_err(io::Error::other)?; + let mut command = + CommandBuilder::new(std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into())); + command.env("TERM", "xterm-256color"); + if let Some(cwd) = cwd { + command.cwd(cwd); + } + let mut reader = pair.master.try_clone_reader().map_err(io::Error::other)?; + let writer = pair.master.take_writer().map_err(io::Error::other)?; + let child = pair + .slave + .spawn_command(command) + .map_err(io::Error::other)?; + drop(pair.slave); + // Bound queued output so a noisy command cannot exhaust memory. + let (sender, output) = mpsc::sync_channel(64); + std::thread::spawn(move || { + let mut bytes = [0; 8192]; + loop { + match reader.read(&mut bytes) { + Ok(0) => break, + Ok(count) => { + if sender.send(bytes[..count].to_vec()).is_err() { + break; + } + } + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + } + }); + Ok(Self { + master: pair.master, + writer, + child, + output, + parser: vt100::Parser::new_with_callbacks(24, 80, 1000, Title::default()), + exited: false, + }) + } +} + +fn size(rows: u16, cols: u16) -> PtySize { + PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + } +} + +// Reserve enough height for both panes; short windows use a side split. +pub(crate) fn split(area: Rect) -> [Rect; 2] { + if area.height >= 28 { + Layout::vertical([Constraint::Percentage(65), Constraint::Percentage(35)]).areas(area) + } else { + Layout::horizontal([Constraint::Percentage(60), Constraint::Percentage(40)]).areas(area) + } +} + +impl Terminal { + pub(crate) fn toggle(&mut self, cwd: Option<&Path>) -> io::Result<()> { + if !self.visible && self.session.as_ref().is_none_or(|session| session.exited) { + self.session = Some(Session::start(cwd)?); + } + self.visible = !self.visible; + self.focused = self.visible; + Ok(()) + } + + pub(crate) fn poll(&mut self) { + if let Some(session) = &mut self.session { + // Limit work per frame so continuous output does not block input. + for bytes in session.output.try_iter().take(64) { + session.parser.process(&bytes); + } + if matches!(session.child.try_wait(), Ok(Some(_))) { + session.exited = true; + } + } + } + + pub(crate) fn input(&mut self, key: KeyEvent) -> io::Result<()> { + if let Some(session) = &mut self.session { + session.parser.screen_mut().set_scrollback(0); + if session.exited { + return Ok(()); + } + let bytes = encode_key(key, session.parser.screen().application_cursor()); + session.writer.write_all(&bytes)?; + session.writer.flush()?; + } + Ok(()) + } + + pub(crate) fn draw(&mut self, frame: &mut Frame, area: Rect) -> io::Result<()> { + let session = self.session.as_ref(); + let exited = session.is_some_and(|session| session.exited); + let offset = session.map_or(0, |s| s.parser.screen().scrollback()); + // Show the shell title like the editor shows its file name. + let name = session + .map(|s| s.parser.callbacks().0.as_str()) + .filter(|name| !name.is_empty()) + .unwrap_or("Terminal"); + let mut title = format!("─ {name}"); + if exited { + title.push_str(" · EXITED"); + } + if offset > 0 { + title.push_str(&format!(" · HISTORY {offset}")); + } + title.push(' '); + let border = Block::bordered() + .border_type(BorderType::Rounded) + .title(title) + .border_style(Style::default().fg(if self.focused { + Color::Green + } else { + Color::White + })); + let inner = border.inner(area); + frame.render_widget(border, area); + let Some(session) = &mut self.session else { + return Ok(()); + }; + if inner.is_empty() { + return Ok(()); + } + if session.parser.screen().size() != (inner.height, inner.width) { + session + .master + .resize(size(inner.height, inner.width)) + .map_err(io::Error::other)?; + session + .parser + .screen_mut() + .set_size(inner.height, inner.width); + } + let screen = session.parser.screen(); + for row in 0..inner.height { + for col in 0..inner.width { + if let Some(cell) = screen.cell(row, col) { + let mut style = Style::default() + .fg(color(cell.fgcolor())) + .bg(color(cell.bgcolor())); + for (enabled, modifier) in [ + (cell.bold(), Modifier::BOLD), + (cell.dim(), Modifier::DIM), + (cell.italic(), Modifier::ITALIC), + (cell.underline(), Modifier::UNDERLINED), + (cell.inverse(), Modifier::REVERSED), + ] { + if enabled { + style = style.add_modifier(modifier); + } + } + let target = &mut frame.buffer_mut()[(inner.x + col, inner.y + row)]; + target.set_symbol(if cell.has_contents() { + cell.contents() + } else { + " " + }); + target.set_style(style); + } + } + } + let (row, col) = screen.cursor_position(); + if self.focused + && !exited + && screen.scrollback() == 0 + && !screen.hide_cursor() + && row < inner.height + && col < inner.width + { + frame.set_cursor_position((inner.x + col, inner.y + row)); + } + Ok(()) + } +} + +// Keep ordinary PageUp and PageDown available to programs running in the PTY. +fn scroll_history(screen: &mut vt100::Screen, key: KeyEvent) -> bool { + if screen.alternate_screen() { + return false; + } + let up = match (key.code, key.modifiers) { + (KeyCode::Char('v'), KeyModifiers::ALT) | (KeyCode::PageUp, KeyModifiers::SHIFT) => true, + (KeyCode::Char('v'), KeyModifiers::CONTROL) | (KeyCode::PageDown, KeyModifiers::SHIFT) => { + false + } + _ => return false, + }; + // Overlap one row to make consecutive pages easier to follow. + let page = usize::from(screen.size().0.saturating_sub(1).max(1)); + let offset = screen.scrollback(); + screen.set_scrollback(if up { + offset.saturating_add(page) + } else { + offset.saturating_sub(page) + }); + true +} + +fn color(value: vt100::Color) -> Color { + match value { + vt100::Color::Default => Color::Reset, + vt100::Color::Idx(index) => Color::Indexed(index), + vt100::Color::Rgb(r, g, b) => Color::Rgb(r, g, b), + } +} + +fn encode_key(key: KeyEvent, application_cursor: bool) -> Vec<u8> { + let mut bytes = match key.code { + KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => match c { + 'a'..='z' | 'A'..='Z' | '@'..='_' => vec![(c as u8) & 0x1f], + ' ' => vec![0], + '?' => vec![127], + _ => return Vec::new(), + }, + KeyCode::Char(c) => c.to_string().into_bytes(), + KeyCode::Enter => vec![b'\r'], + KeyCode::Backspace => vec![127], + KeyCode::Tab => vec![b'\t'], + KeyCode::BackTab => b"\x1b[Z".to_vec(), + KeyCode::Esc => vec![27], + KeyCode::Up + | KeyCode::Down + | KeyCode::Right + | KeyCode::Left + | KeyCode::Home + | KeyCode::End => { + let suffix = match key.code { + KeyCode::Up => 'A', + KeyCode::Down => 'B', + KeyCode::Right => 'C', + KeyCode::Left => 'D', + KeyCode::Home => 'H', + _ => 'F', + }; + format!("\x1b{}{suffix}", if application_cursor { 'O' } else { '[' }).into_bytes() + } + KeyCode::Insert => b"\x1b[2~".to_vec(), + KeyCode::Delete => b"\x1b[3~".to_vec(), + KeyCode::PageUp => b"\x1b[5~".to_vec(), + KeyCode::PageDown => b"\x1b[6~".to_vec(), + KeyCode::F(n @ 1..=4) => vec![27, b'O', b'P' + n - 1], + KeyCode::F(n @ 5..=12) => { + let code = [15, 17, 18, 19, 20, 21, 23, 24][usize::from(n - 5)]; + format!("\x1b[{code}~").into_bytes() + } + _ => return Vec::new(), + }; + if key.modifiers.contains(KeyModifiers::ALT) { + bytes.insert(0, 27); + } + bytes +} + +impl crate::app::App { + pub(crate) fn handle_terminal_key(&mut self, key: KeyEvent) -> bool { + // Modal editor prompts retain their input and focus. + if self.cpp_check_modal() + || self.overwrite_confirm + || self.save_path_input.is_some() + || self.search.reads_input() + || self.goto_line.is_open() + || self.menu.active.is_some() + { + return false; + } + let plain = |c| key.code == KeyCode::Char(c) && key.modifiers.is_empty(); + let ctrl_x = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL); + + // C-c t t opens or hides the terminal; C-c t c runs clang-tidy. + if self.ctrl_c_t_wait_flag { + self.ctrl_c_t_wait_flag = false; + if plain('t') { + let cwd = self + .buffer + .path + .as_deref() + .and_then(Path::parent) + .filter(|path| !path.as_os_str().is_empty()); + if let Err(err) = self.terminal.toggle(cwd) { + self.status_bar_text = format!("Terminal failed: {err}"); + } + } else if plain('c') { + self.run_cpp_check(crate::buffers::cpp_checks::Tool::Tidy); + } + return true; + } + + // C-x o moves focus between the editor and the terminal, like Emacs. + if self.ctrl_x_wait_flag && plain('o') && self.terminal.visible { + self.ctrl_x_wait_flag = false; + self.terminal.focused = !self.terminal.focused; + return true; + } + + if self.terminal.focused { + if !self.ctrl_x_wait_flag + && let Some(session) = &mut self.terminal.session + && scroll_history(session.parser.screen_mut(), key) + { + return true; + } + // Hold C-x back so C-x o can leave the terminal. + if key == ctrl_x && !self.ctrl_x_wait_flag { + self.ctrl_x_wait_flag = true; + return true; + } + // Any other key after C-x goes to the shell together with C-x. + let mut result = Ok(()); + if std::mem::take(&mut self.ctrl_x_wait_flag) { + result = self.terminal.input(ctrl_x); + } + if let Err(err) = result.and_then(|()| self.terminal.input(key)) { + self.status_bar_text = format!("Terminal input failed: {err}"); + } + return true; + } + false + } +} + +#[cfg(test)] +mod tests; diff --git a/src/buffers/terminal/tests.rs b/src/buffers/terminal/tests.rs new file mode 100644 index 0000000..36eda8b --- /dev/null +++ b/src/buffers/terminal/tests.rs @@ -0,0 +1,225 @@ +// Copyright (C) 2026 CharOfString <root@charofstring.cc> +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see <https://www.gnu.org/licenses/>. + +use super::*; + +#[test] +fn layout_switches_to_right_in_short_windows() { + let [editor, terminal] = split(Rect::new(0, 2, 100, 36)); + assert_eq!(terminal.y, editor.bottom()); + assert_eq!(editor.width, terminal.width); + let [editor, terminal] = split(Rect::new(0, 2, 100, 20)); + assert_eq!(terminal.x, editor.right()); + assert_eq!(editor.height, terminal.height); + for width in 0..4 { + for height in 0..4 { + let _ = split(Rect::new(0, 0, width, height)); + } + } +} + +#[test] +#[cfg(unix)] +fn shell_output_and_resize_work() { + use ratatui::backend::TestBackend; + use std::time::{Duration, Instant}; + let mut terminal = Terminal::default(); + terminal.toggle(None).unwrap(); + let session = terminal.session.as_mut().unwrap(); + session + .writer + .write_all(b"printf '\\033[31m'; printf 'pty-%s' ready; printf '\\033[0m\\n'\n") + .unwrap(); + session.writer.flush().unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + terminal.poll(); + if terminal + .session + .as_ref() + .unwrap() + .parser + .screen() + .contents() + .contains("pty-ready") + { + break; + } + assert!(Instant::now() < deadline, "shell output timed out"); + std::thread::sleep(Duration::from_millis(10)); + } + let mut display = ratatui::Terminal::new(TestBackend::new(60, 12)).unwrap(); + // Return the top and bottom border rows. + let borders = |display: &mut ratatui::Terminal<TestBackend>, terminal: &mut Terminal| { + display + .draw(|frame| terminal.draw(frame, frame.area()).unwrap()) + .unwrap(); + let screen = display.backend().buffer(); + [0, 11].map(|y| (0..60).map(|x| screen[(x, y)].symbol()).collect::<String>()) + }; + // The shell title replaces the default name once it is set. + let session = terminal.session.as_mut().unwrap(); + session.parser.callbacks_mut().0.clear(); + let [top, bottom] = borders(&mut display, &mut terminal); + assert!(top.starts_with("╭─ Terminal ─")); + assert!(bottom.starts_with("╰──")); + let session = terminal.session.as_mut().unwrap(); + session.parser.process(b"\x1b]2;make\tbuild\x07"); + assert!(borders(&mut display, &mut terminal)[0].starts_with("╭─ makebuild ─")); + assert_eq!( + terminal + .session + .as_ref() + .unwrap() + .master + .get_size() + .unwrap() + .cols, + 58 + ); + terminal.toggle(None).unwrap(); + assert!(!terminal.visible); + assert!(terminal.session.is_some()); +} + +#[test] +fn status_bar_shows_keys_of_focused_pane() { + let mut app = crate::app::App::default(); + let mut display = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 24)).unwrap(); + let mut status = |app: &mut crate::app::App| { + display.draw(|frame| app.draw(frame)).unwrap(); + let screen = display.backend().buffer(); + (0..100) + .map(|x| screen[(x, 23)].symbol()) + .collect::<String>() + }; + app.terminal.visible = true; + assert!(status(&mut app).contains("F10: menu C-c t t: terminal")); + app.terminal.focused = true; + let text = status(&mut app); + assert!(text.contains("C-x o: focus M-v/C-v: scroll")); + assert!(!text.contains("F10")); +} + +#[test] +fn keys_preserve_shell_controls() { + assert_eq!( + encode_key( + KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL), + false + ), + [3] + ); + assert_eq!( + encode_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE), true), + b"\x1bOA" + ); + assert_eq!( + encode_key( + KeyEvent::new(KeyCode::Char('中'), KeyModifiers::NONE), + false + ), + "中".as_bytes() + ); +} + +#[test] +fn terminal_focus_does_not_edit_buffer() { + let mut app = crate::app::App::default(); + app.terminal.visible = true; + app.terminal.focused = true; + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), ""); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE)); + assert!(!app.terminal.focused); + assert!(!app.ctrl_x_wait_flag); +} + +#[test] +fn history_pages_clamp_and_preserve_output() { + let mut parser = vt100::Parser::new(4, 20, 10); + for n in 0..20 { + parser.process(format!("line {n}\r\n").as_bytes()); + } + let live = parser.screen().contents(); + let up = KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT); + let down = KeyEvent::new(KeyCode::Char('v'), KeyModifiers::CONTROL); + assert!(scroll_history(parser.screen_mut(), up)); + assert_eq!(parser.screen().scrollback(), 3); + assert_ne!(parser.screen().contents(), live); + let history = parser.screen().contents(); + parser.process(b"new line\r\n"); + assert_eq!(parser.screen().contents(), history); + for _ in 0..20 { + scroll_history( + parser.screen_mut(), + KeyEvent::new(KeyCode::PageUp, KeyModifiers::SHIFT), + ); + } + assert_eq!(parser.screen().scrollback(), 10); + assert!(scroll_history(parser.screen_mut(), down)); + assert_eq!(parser.screen().scrollback(), 7); + for _ in 0..20 { + scroll_history( + parser.screen_mut(), + KeyEvent::new(KeyCode::PageDown, KeyModifiers::SHIFT), + ); + } + assert_eq!(parser.screen().scrollback(), 0); + assert!(parser.screen().contents().contains("new line")); + assert!(!scroll_history( + parser.screen_mut(), + KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE) + )); + parser.process(b"\x1b[?1049h"); + assert!(!scroll_history(parser.screen_mut(), up)); + assert!(!scroll_history(parser.screen_mut(), down)); +} + +#[test] +#[cfg(unix)] +fn history_keys_are_local_and_input_returns_to_live_output() { + let mut app = crate::app::App::default(); + app.terminal.toggle(None).unwrap(); + let session = app.terminal.session.as_mut().unwrap(); + for _ in 0..40 { + session.parser.process(b"history\r\n"); + } + // An exited shell still allows browsing its output. + session.exited = true; + app.handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT)); + assert!( + app.terminal + .session + .as_ref() + .unwrap() + .parser + .screen() + .scrollback() + > 0 + ); + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + assert_eq!( + app.terminal + .session + .as_ref() + .unwrap() + .parser + .screen() + .scrollback(), + 0 + ); + assert_eq!(app.buffer.editor.get_content(), ""); +}