Skip to main content

indigo_term/
terminal.rs

1#![allow(clippy::uninlined_format_args)]
2#![cfg_attr(not(test), expect(clippy::wildcard_imports))]
3
4use crate::{
5    Reader, Tty,
6    input::*,
7    output::{KeyboardEnhancementFlags as KEF, *},
8};
9use std::{
10    collections::VecDeque,
11    io::{self, Write},
12};
13
14// NOTE: All these flags must be enabled to get full keyboard functionality, since the raw/legacy
15// keys are intentionally not supported.
16const KEYBOARD_FLAGS: KeyboardEnhancementFlags = KEF::DISAMBIGUATE
17    .union(KEF::REPORT_EVENTS)
18    .union(KEF::REPORT_ALL_KEYS);
19
20pub struct Terminal {
21    tty: Tty,
22    reader: Reader,
23    events: VecDeque<Event>,
24    alternate_screen: bool,
25}
26
27impl Terminal {
28    pub fn init() -> io::Result<Self> {
29        let mut this = Self {
30            tty: Tty::init()?,
31            reader: Reader::new(),
32            events: VecDeque::new(),
33            alternate_screen: false,
34        };
35
36        this.tty.enable_raw_mode()?;
37
38        if !this.enable_mode(IN_BAND_RESIZE_MODE)? {
39            drop(this);
40            panic!("terminal does not support in-band resize");
41        }
42        write!(this.tty, "{}", IN_BAND_RESIZE_SET)?;
43        this.tty.flush()?;
44
45        if !this.query_mode(SYNC_UPDATE_MODE)?.is_configurable() {
46            drop(this);
47            panic!("terminal does not support synchronized update");
48        }
49
50        if this.query_keyboard_flags()?.is_none() {
51            drop(this);
52            panic!("terminal does not support kitty keyboard protocol");
53        }
54        write!(this.tty, "{}", KeyboardEnhancementFlagsPush(KEYBOARD_FLAGS))?;
55
56        if !this.enable_mode(BRACKETED_PASTE_MODE)? {
57            drop(this);
58            panic!("terminal does not support bracketed paste");
59        }
60
61        Ok(this)
62    }
63
64    pub fn query_mode(&mut self, mode: u16) -> io::Result<ModeSetting> {
65        write!(self.tty, "{}{}", ModeQuery(mode), DA1_QUERY)?;
66        self.tty.flush()?;
67
68        let mut setting = ModeSetting::NotRecognized;
69
70        loop {
71            // We record the setting from the reply, but continue reading events until a DA1 event
72            // is consumed. Leaving it in the event stream would confuse future queries.
73            match self.reader.read_event(&mut self.tty)? {
74                Event::Decrpm {
75                    mode: event_mode,
76                    setting: event_setting,
77                } if mode == event_mode => setting = event_setting,
78                Event::Da1 => return Ok(setting),
79                event => self.events.push_back(event),
80            }
81        }
82    }
83
84    pub fn enable_mode(&mut self, mode: u16) -> io::Result<bool> {
85        #[cfg_attr(not(test), expect(clippy::enum_glob_use))]
86        use ModeSetting::*;
87
88        match self.query_mode(mode)? {
89            NotRecognized | PermanentlyReset => Ok(false),
90            Set | PermanentlySet => Ok(true),
91            Reset => {
92                write!(self.tty, "{}", ModeSet(mode))?;
93                self.tty.flush()?;
94                Ok(true)
95            }
96        }
97    }
98
99    pub fn disable_mode(&mut self, mode: u16) -> io::Result<bool> {
100        #[cfg_attr(not(test), expect(clippy::enum_glob_use))]
101        use ModeSetting::*;
102
103        match self.query_mode(mode)? {
104            NotRecognized | Reset | PermanentlyReset => Ok(true),
105            PermanentlySet => Ok(false),
106            Set => {
107                write!(self.tty, "{}", ModeReset(mode))?;
108                self.tty.flush()?;
109                Ok(true)
110            }
111        }
112    }
113
114    pub fn query_keyboard_flags(&mut self) -> io::Result<Option<KeyboardEnhancementFlags>> {
115        write!(
116            self.tty,
117            "{}{}",
118            KEYBOARD_ENHANCEMENT_FLAGS_QUERY, DA1_QUERY
119        )?;
120        self.tty.flush()?;
121
122        let mut flags = None;
123
124        loop {
125            // We record the setting from the reply, but continue reading events until a DA1 event
126            // is consumed. Leaving it in the event stream would confuse future queries.
127            match self.reader.read_event(&mut self.tty)? {
128                Event::KeyboardEnhancementFlags(event_flags) => flags = Some(event_flags),
129                Event::Da1 => return Ok(flags),
130                event => self.events.push_back(event),
131            }
132        }
133    }
134
135    pub fn push_keyboard_flags(&mut self, flags: KeyboardEnhancementFlags) -> io::Result<()> {
136        write!(self.tty, "{}", KeyboardEnhancementFlagsPush(flags))?;
137        self.tty.flush()?;
138        Ok(())
139    }
140
141    pub fn pop_keyboard_flags(&mut self) -> io::Result<()> {
142        write!(self.tty, "{}", KeyboardEnhancementFlagsPop)?;
143        self.tty.flush()?;
144        Ok(())
145    }
146
147    pub fn begin_sync_update(&mut self) -> io::Result<()> {
148        write!(self.tty, "{}", SYNC_UPDATE_SET)?;
149        self.tty.flush()?;
150        Ok(())
151    }
152
153    pub fn end_sync_update(&mut self) -> io::Result<()> {
154        write!(self.tty, "{}", SYNC_UPDATE_RESET)?;
155        self.tty.flush()?;
156        Ok(())
157    }
158
159    pub fn enter_alternate_screen(&mut self) -> io::Result<()> {
160        if self.alternate_screen {
161            return Ok(());
162        }
163        // The alternate screen has its own stack of keyboard flags
164        write!(
165            self.tty,
166            "{}{}",
167            ALTERNATE_SCREEN_SET,
168            KeyboardEnhancementFlagsPush(KEYBOARD_FLAGS)
169        )?;
170        self.tty.flush()?;
171        self.alternate_screen = true;
172        Ok(())
173    }
174
175    pub fn leave_alternate_screen(&mut self) -> io::Result<()> {
176        if !self.alternate_screen {
177            return Ok(());
178        }
179        write!(
180            self.tty,
181            "{}{}",
182            KeyboardEnhancementFlagsPop, ALTERNATE_SCREEN_RESET
183        )?;
184        self.tty.flush()?;
185        self.alternate_screen = false;
186        Ok(())
187    }
188
189    pub fn size(&self) -> io::Result<(u16, u16)> {
190        self.tty.size()
191    }
192
193    pub fn pixel_size(&self) -> io::Result<(u16, u16)> {
194        self.tty.pixel_size()
195    }
196
197    pub fn query_cursor_position(&mut self) -> io::Result<Option<(u16, u16)>> {
198        write!(self.tty, "{}{}", CURSOR_POSITION_QUERY, DA1_QUERY)?;
199        self.tty.flush()?;
200
201        let mut position = None;
202
203        loop {
204            // We record the position from the reply, but continue reading events until a DA1 event
205            // is consumed. Leaving it in the event stream would confuse future queries.
206            match self.reader.read_event(&mut self.tty)? {
207                Event::CursorPosition { row, column } => position = Some((row, column)),
208                Event::Da1 => return Ok(position),
209                event => self.events.push_back(event),
210            }
211        }
212    }
213
214    pub fn read_event(&mut self) -> io::Result<Event> {
215        if let Some(event) = self.events.pop_front() {
216            Ok(event)
217        } else {
218            self.reader.read_event(&mut self.tty)
219        }
220    }
221}
222
223impl Write for Terminal {
224    #[inline]
225    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
226        self.tty.write(buf)
227    }
228
229    #[inline]
230    fn flush(&mut self) -> io::Result<()> {
231        self.tty.flush()
232    }
233}
234
235impl Drop for Terminal {
236    fn drop(&mut self) {
237        let _ = self.leave_alternate_screen();
238        let _ = write!(self.tty, "{}", SYNC_UPDATE_RESET);
239        let _ = write!(self.tty, "{}", IN_BAND_RESIZE_RESET);
240        let _ = write!(self.tty, "{}", KeyboardEnhancementFlagsPop);
241        let _ = write!(self.tty, "{}", BRACKETED_PASTE_RESET);
242        let _ = self.tty.flush();
243    }
244}