Commit b7501e0197

b7501e0197511f30d7664f5b820777fa516d7664

parent: dd3ae0e8cf

Unregistered key

Matthew Kabat <45803702+Nightchicken@users.noreply.github.com> · 2026-09-12 19:44 UTC
committer: <noreply@github.com>

Disable terminal alt screen before opening the external editor (#688)

Layout: unified · split

src/config.rs +26
@@ -13,6 +13,7 @@ use matrix_sdk::authentication::matrix::MatrixSession;
1313use matrix_sdk::media::MediaRetentionPolicy;
1414use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
1515use matrix_sdk::ruma::OwnedDeviceId;
16use modalkit::crossterm;
1617use modalkit::env::vim::VimMode;
1718use modalkit::keybindings::InputKey;
1819use ratatui_image::FilterType;
@@ -1237,6 +1238,11 @@ pub struct ApplicationSettings {
12371238 pub dirs: DirectoryValues,
12381239 pub layout: Layout,
12391240 pub macros: Macros,
1241
1242 /// Whether to use the Kitty keyboard protocol. Resolved by
1243 /// [`ApplicationSettings::probe_enhanced_keys`] once the TUI starts, since
1244 /// it may require querying the terminal.
1245 pub enable_enhanced_keys: bool,
12401246}
12411247
12421248impl ApplicationSettings {
@@ -1380,11 +1386,31 @@ impl ApplicationSettings {
13801386 dirs,
13811387 layout,
13821388 macros,
1389 enable_enhanced_keys: false,
13831390 };
13841391
13851392 Ok(settings)
13861393 }
13871394
1395 /// Work out whether to use the Kitty keyboard protocol, asking the terminal
1396 /// when the user has not configured it explicitly.
1397 ///
1398 /// This queries the terminal, so it must only be called once, before the
1399 /// TUI starts reading input.
1400 pub fn probe_enhanced_keys(&mut self) {
1401 self.enable_enhanced_keys =
1402 self.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1403 crossterm::terminal::supports_keyboard_enhancement()
1404 .inspect_err(|e| {
1405 tracing::warn!(
1406 err = %e,
1407 "Failed to determine whether the terminal supports keyboard enhancements"
1408 )
1409 })
1410 .unwrap_or_default()
1411 });
1412 }
1413
13881414 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
13891415 let file = File::open(path)?;
13901416 let reader = BufReader::new(file);
src/main.rs +10 −81
@@ -28,24 +28,8 @@ use matrix_sdk::ruma::api::error::ErrorKind;
2828use matrix_sdk_crypto::encrypt_room_key_export;
2929use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
3030use modalkit::crossterm;
31use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow};
32use modalkit::crossterm::event::{
33 DisableBracketedPaste,
34 DisableFocusChange,
35 DisableMouseCapture,
36 EnableBracketedPaste,
37 EnableFocusChange,
38 EnableMouseCapture,
39 Event,
40 KeyEventKind,
41 KeyboardEnhancementFlags,
42 MouseEventKind,
43 PopKeyboardEnhancementFlags,
44 PushKeyboardEnhancementFlags,
45 poll,
46 read,
47};
48use modalkit::crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle};
31use modalkit::crossterm::cursor::SetCursorStyle;
32use modalkit::crossterm::event::{Event, KeyEventKind, MouseEventKind, poll, read};
4933use modalkit::editing::key::KeyManager;
5034use modalkit::editing::store::Store;
5135use modalkit::keybindings::dialog::Pager;
@@ -68,6 +52,7 @@ use crate::base::{HomeserverAction, KeysAction};
6852use crate::completions::IambCompleter;
6953use crate::config::{CursorShape, Iamb};
7054use crate::prelude::*;
55use crate::util::{restore_tty, setup_tty};
7156use crate::windows::IambWindow;
7257use crate::worker::{ClientWorker, LoginStyle, create_room};
7358
@@ -992,60 +977,12 @@ async fn login_normal(
992977 Ok(())
993978}
994979
995/// Set up the terminal for drawing the TUI, and getting additional info.
996fn setup_tty(settings: &ApplicationSettings, enable_enhanced_keys: bool) -> std::io::Result<()> {
997 // Enable raw mode and enter the alternate screen.
998 crossterm::terminal::enable_raw_mode()?;
999 crossterm::execute!(stdout(), EnterAlternateScreen)?;
1000
1001 if enable_enhanced_keys {
1002 // Enable the Kitty keyboard enhancement protocol for improved keypresses.
1003 crossterm::queue!(
1004 stdout(),
1005 PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
1006 )?;
1007 }
1008
1009 if settings.tunables.mouse.enabled {
1010 crossterm::execute!(stdout(), EnableMouseCapture)?;
1011 }
1012
1013 if settings.tunables.terminal.enable_title {
1014 let title = format!("iamb ({})", settings.profile.user_id.as_str());
1015 crossterm::execute!(stdout(), SetTitle(title))?;
1016 }
1017
1018 let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape);
1019
1020 crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape)
1021}
1022
1023// Do our best to reverse what we did in setup_tty() when we exit or crash.
1024fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
1025 // The keyboard enhancement flags were pushed onto the alternate screen's
1026 // stack, which the terminal keeps separate from the main screen's, so they
1027 // have to be popped before LeaveAlternateScreen below.
1028 if enable_enhanced_keys {
1029 let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
1030 }
1031
1032 if enable_mouse {
1033 let _ = crossterm::queue!(stdout(), DisableMouseCapture);
1034 }
1035
1036 let _ = crossterm::execute!(
1037 stdout(),
1038 DisableBracketedPaste,
1039 DisableFocusChange,
1040 SetCursorStyle::DefaultUserShape,
1041 LeaveAlternateScreen,
1042 CursorShow,
1043 );
1044
1045 let _ = crossterm::terminal::disable_raw_mode();
1046}
980async fn run(mut settings: ApplicationSettings) -> IambResult<()> {
981 // Work out whether to use the Kitty keyboard protocol before anything
982 // clones the settings, so that every copy agrees with the flags we push in
983 // setup_tty() and pop in restore_tty().
984 settings.probe_enhanced_keys();
1047985
1048async fn run(settings: ApplicationSettings) -> IambResult<()> {
1049986 // Get old keys the first time we run w/ the upgraded SDK.
1050987 let import_keys = check_import_keys(&settings).await?;
1051988
@@ -1089,18 +1026,10 @@ async fn run(settings: ApplicationSettings) -> IambResult<()> {
10891026 }
10901027
10911028 // Set up the terminal for drawing, and cleanup properly on panics.
1092 let enable_enhanced_keys =
1093 settings.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1094 crossterm::terminal::supports_keyboard_enhancement()
1095 .inspect_err(|e| tracing::warn!(
1096 err = %e,
1097 "Failed to determine whether the terminal supports keyboard enhancements"
1098 ))
1099 .unwrap_or_default()
1100 });
1101 setup_tty(&settings, enable_enhanced_keys)?;
1029 setup_tty(&settings)?;
11021030
11031031 let orig_hook = std::panic::take_hook();
1032 let enable_enhanced_keys = settings.enable_enhanced_keys;
11041033 let enable_mouse = settings.tunables.mouse.enabled;
11051034 std::panic::set_hook(Box::new(move |panic_info| {
11061035 restore_tty(enable_enhanced_keys, enable_mouse);
src/tests.rs +1
@@ -220,6 +220,7 @@ pub fn mock_settings() -> ApplicationSettings {
220220 dirs: mock_dirs(),
221221 layout: Default::default(),
222222 macros: HashMap::default(),
223 enable_enhanced_keys: false,
223224 }
224225}
225226
src/util.rs +96
@@ -1,5 +1,21 @@
11//! # Utility functions
22
3use std::io::stdout;
4
5use modalkit::crossterm;
6use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow};
7use modalkit::crossterm::event::{
8 DisableBracketedPaste,
9 DisableFocusChange,
10 DisableMouseCapture,
11 EnableBracketedPaste,
12 EnableFocusChange,
13 EnableMouseCapture,
14 KeyboardEnhancementFlags,
15 PopKeyboardEnhancementFlags,
16 PushKeyboardEnhancementFlags,
17};
18use modalkit::crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle};
319use regex::{Regex, RegexBuilder};
420
521use crate::prelude::*;
@@ -191,6 +207,86 @@ pub fn compile_search(pattern: &str, case_insensitive: bool) -> Result<Regex, re
191207 RegexBuilder::new(pattern).case_insensitive(case_insensitive).build()
192208}
193209
210/// Set up the terminal for drawing the TUI, and getting additional info.
211pub fn setup_tty(settings: &ApplicationSettings) -> std::io::Result<()> {
212 // Enable raw mode and enter the alternate screen.
213 crossterm::terminal::enable_raw_mode()?;
214 crossterm::execute!(stdout(), EnterAlternateScreen)?;
215
216 if settings.enable_enhanced_keys {
217 // Enable the Kitty keyboard enhancement protocol for improved keypresses.
218 crossterm::queue!(
219 stdout(),
220 PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
221 )?;
222 }
223
224 if settings.tunables.mouse.enabled {
225 crossterm::execute!(stdout(), EnableMouseCapture)?;
226 }
227
228 if settings.tunables.terminal.enable_title {
229 let title = format!("iamb ({})", settings.profile.user_id.as_str());
230 crossterm::execute!(stdout(), SetTitle(title))?;
231 }
232
233 let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape);
234
235 crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape)
236}
237
238// Do our best to reverse what we did in setup_tty() when we exit or crash.
239pub fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
240 // The keyboard enhancement flags were pushed onto the alternate screen's
241 // stack, which the terminal keeps separate from the main screen's, so they
242 // have to be popped before LeaveAlternateScreen below.
243 if enable_enhanced_keys {
244 let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
245 }
246
247 if enable_mouse {
248 let _ = crossterm::queue!(stdout(), DisableMouseCapture);
249 }
250
251 let _ = crossterm::execute!(
252 stdout(),
253 DisableBracketedPaste,
254 DisableFocusChange,
255 SetCursorStyle::DefaultUserShape,
256 LeaveAlternateScreen,
257 CursorShow,
258 );
259
260 let _ = crossterm::terminal::disable_raw_mode();
261}
262
263/// Hands the terminal back to an external program, and sets it up for the TUI
264/// again when dropped.
265///
266/// Programs that use the alternate screen themselves (editors, pagers) leave it
267/// on exit, which drops us back to the main screen without iamb knowing, and the
268/// TUI then draws over the user's scrollback. Suspending around the child keeps
269/// the alternate screen entries and exits balanced.
270pub struct SuspendedTty<'a> {
271 settings: &'a ApplicationSettings,
272}
273
274impl<'a> SuspendedTty<'a> {
275 pub fn new(settings: &'a ApplicationSettings) -> Self {
276 restore_tty(settings.enable_enhanced_keys, settings.tunables.mouse.enabled);
277
278 SuspendedTty { settings }
279 }
280}
281
282impl Drop for SuspendedTty<'_> {
283 fn drop(&mut self) {
284 if let Err(e) = setup_tty(self.settings) {
285 tracing::error!(err = %e, "Failed to set the terminal back up after an external program");
286 }
287 }
288}
289
194290#[cfg(test)]
195291pub mod tests {
196292 use super::*;
src/windows/room/chat.rs +4
@@ -31,6 +31,7 @@ use crate::message::{
3131 text_to_text_message_event_content,
3232};
3333use crate::prelude::*;
34use crate::util::SuspendedTty;
3435use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
3536
3637/// State needed for rendering [Chat].
@@ -566,6 +567,9 @@ impl ChatState {
566567 let msg = if let SendAction::SubmitFromEditor = act {
567568 let suffix =
568569 store.application.settings.tunables.external_edit_file_suffix.as_str();
570 // Give the terminal back to the editor, and take it again
571 // however we leave this block.
572 let _tty = SuspendedTty::new(&store.application.settings);
569573 let edited_msg =
570574 external_edit(msg.trim_end().to_string(), Builder::new().suffix(suffix))?
571575 .trim_end()