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;
13use matrix_sdk::media::MediaRetentionPolicy; 13use matrix_sdk::media::MediaRetentionPolicy;
14use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 14use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
15use matrix_sdk::ruma::OwnedDeviceId; 15use matrix_sdk::ruma::OwnedDeviceId;
16use modalkit::crossterm;
16use modalkit::env::vim::VimMode; 17use modalkit::env::vim::VimMode;
17use modalkit::keybindings::InputKey; 18use modalkit::keybindings::InputKey;
18use ratatui_image::FilterType; 19use ratatui_image::FilterType;
@@ -1237,6 +1238,11 @@ pub struct ApplicationSettings {
1237 pub dirs: DirectoryValues, 1238 pub dirs: DirectoryValues,
1238 pub layout: Layout, 1239 pub layout: Layout,
1239 pub macros: Macros, 1240 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,
1240} 1246}
1241 1247
1242impl ApplicationSettings { 1248impl ApplicationSettings {
@@ -1380,11 +1386,31 @@ impl ApplicationSettings {
1380 dirs, 1386 dirs,
1381 layout, 1387 layout,
1382 macros, 1388 macros,
1389 enable_enhanced_keys: false,
1383 }; 1390 };
1384 1391
1385 Ok(settings) 1392 Ok(settings)
1386 } 1393 }
1387 1394
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
1388 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> { 1414 pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
1389 let file = File::open(path)?; 1415 let file = File::open(path)?;
1390 let reader = BufReader::new(file); 1416 let reader = BufReader::new(file);
src/main.rs +10 −81
@@ -28,24 +28,8 @@ use matrix_sdk::ruma::api::error::ErrorKind;
28use matrix_sdk_crypto::encrypt_room_key_export; 28use matrix_sdk_crypto::encrypt_room_key_export;
29use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer}; 29use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
30use modalkit::crossterm; 30use modalkit::crossterm;
31use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow}; 31use modalkit::crossterm::cursor::SetCursorStyle;
32use modalkit::crossterm::event::{ 32use modalkit::crossterm::event::{Event, KeyEventKind, MouseEventKind, poll, read};
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};
49use modalkit::editing::key::KeyManager; 33use modalkit::editing::key::KeyManager;
50use modalkit::editing::store::Store; 34use modalkit::editing::store::Store;
51use modalkit::keybindings::dialog::Pager; 35use modalkit::keybindings::dialog::Pager;
@@ -68,6 +52,7 @@ use crate::base::{HomeserverAction, KeysAction};
68use crate::completions::IambCompleter; 52use crate::completions::IambCompleter;
69use crate::config::{CursorShape, Iamb}; 53use crate::config::{CursorShape, Iamb};
70use crate::prelude::*; 54use crate::prelude::*;
55use crate::util::{restore_tty, setup_tty};
71use crate::windows::IambWindow; 56use crate::windows::IambWindow;
72use crate::worker::{ClientWorker, LoginStyle, create_room}; 57use crate::worker::{ClientWorker, LoginStyle, create_room};
73 58
@@ -992,60 +977,12 @@ async fn login_normal(
992 Ok(()) 977 Ok(())
993} 978}
994 979
995/// Set up the terminal for drawing the TUI, and getting additional info. 980async fn run(mut settings: ApplicationSettings) -> IambResult<()> {
996fn setup_tty(settings: &ApplicationSettings, enable_enhanced_keys: bool) -> std::io::Result<()> { 981 // Work out whether to use the Kitty keyboard protocol before anything
997 // Enable raw mode and enter the alternate screen. 982 // clones the settings, so that every copy agrees with the flags we push in
998 crossterm::terminal::enable_raw_mode()?; 983 // setup_tty() and pop in restore_tty().
999 crossterm::execute!(stdout(), EnterAlternateScreen)?; 984 settings.probe_enhanced_keys();
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}
1047 985
1048async fn run(settings: ApplicationSettings) -> IambResult<()> {
1049 // Get old keys the first time we run w/ the upgraded SDK. 986 // Get old keys the first time we run w/ the upgraded SDK.
1050 let import_keys = check_import_keys(&settings).await?; 987 let import_keys = check_import_keys(&settings).await?;
1051 988
@@ -1089,18 +1026,10 @@ async fn run(settings: ApplicationSettings) -> IambResult<()> {
1089 } 1026 }
1090 1027
1091 // Set up the terminal for drawing, and cleanup properly on panics. 1028 // Set up the terminal for drawing, and cleanup properly on panics.
1092 let enable_enhanced_keys = 1029 setup_tty(&settings)?;
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)?;
1102 1030
1103 let orig_hook = std::panic::take_hook(); 1031 let orig_hook = std::panic::take_hook();
1032 let enable_enhanced_keys = settings.enable_enhanced_keys;
1104 let enable_mouse = settings.tunables.mouse.enabled; 1033 let enable_mouse = settings.tunables.mouse.enabled;
1105 std::panic::set_hook(Box::new(move |panic_info| { 1034 std::panic::set_hook(Box::new(move |panic_info| {
1106 restore_tty(enable_enhanced_keys, enable_mouse); 1035 restore_tty(enable_enhanced_keys, enable_mouse);
src/tests.rs +1
@@ -220,6 +220,7 @@ pub fn mock_settings() -> ApplicationSettings {
220 dirs: mock_dirs(), 220 dirs: mock_dirs(),
221 layout: Default::default(), 221 layout: Default::default(),
222 macros: HashMap::default(), 222 macros: HashMap::default(),
223 enable_enhanced_keys: false,
223 } 224 }
224} 225}
225 226
src/util.rs +96
@@ -1,5 +1,21 @@
1//! # Utility functions 1//! # Utility functions
2 2
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};
3use regex::{Regex, RegexBuilder}; 19use regex::{Regex, RegexBuilder};
4 20
5use crate::prelude::*; 21use crate::prelude::*;
@@ -191,6 +207,86 @@ pub fn compile_search(pattern: &str, case_insensitive: bool) -> Result<Regex, re
191 RegexBuilder::new(pattern).case_insensitive(case_insensitive).build() 207 RegexBuilder::new(pattern).case_insensitive(case_insensitive).build()
192} 208}
193 209
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
194#[cfg(test)] 290#[cfg(test)]
195pub mod tests { 291pub mod tests {
196 use super::*; 292 use super::*;
src/windows/room/chat.rs +4
@@ -31,6 +31,7 @@ use crate::message::{
31 text_to_text_message_event_content, 31 text_to_text_message_event_content,
32}; 32};
33use crate::prelude::*; 33use crate::prelude::*;
34use crate::util::SuspendedTty;
34use crate::windows::room::scrollback::{Scrollback, ScrollbackState}; 35use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
35 36
36/// State needed for rendering [Chat]. 37/// State needed for rendering [Chat].
@@ -566,6 +567,9 @@ impl ChatState {
566 let msg = if let SendAction::SubmitFromEditor = act { 567 let msg = if let SendAction::SubmitFromEditor = act {
567 let suffix = 568 let suffix =
568 store.application.settings.tunables.external_edit_file_suffix.as_str(); 569 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);
569 let edited_msg = 573 let edited_msg =
570 external_edit(msg.trim_end().to_string(), Builder::new().suffix(suffix))? 574 external_edit(msg.trim_end().to_string(), Builder::new().suffix(suffix))?
571 .trim_end() 575 .trim_end()