Debian Codegraph @

helix-tui/src/backend/crossterm.rs

raw symbols SCIP
1 use crate::{backend::Backend, buffer::Cell, terminal::Config};
2 use crossterm::{
3 cursor::{Hide, MoveTo, SetCursorStyle, Show},
4 event::{
5 DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
6 EnableFocusChange, EnableMouseCapture, KeyboardEnhancementFlags,
7 PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
8 },
9 execute, queue,
10 style::{
11 Attribute as CAttribute, Color as CColor, Colors, Print, SetAttribute, SetBackgroundColor,
12 SetColors, SetForegroundColor,
13 },
14 terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
15 Command,
16 };
17 use helix_view::graphics::{Color, CursorKind, Modifier, Rect, UnderlineStyle};
18 use once_cell::sync::OnceCell;
19 use std::{
20 fmt,
21 io::{self, Write},
22 };
23 use termini::TermInfo;
24
25 fn term_program() -> Option<String> {
26 // Some terminals don't set $TERM_PROGRAM
27 match std::env::var("TERM_PROGRAM") {
28 Err(_) => std::env::var("TERM").ok(),
29 Ok(term_program) => Some(term_program),
30 }
31 }
32 fn vte_version() -> Option<usize> {
33 std::env::var("VTE_VERSION").ok()?.parse().ok()
34 }
35 fn reset_cursor_approach(terminfo: TermInfo) -> String {
36 let mut reset_str = String::new();
37
38 if let Some(termini::Value::Utf8String(se_str)) = terminfo.extended_cap("Se") {
39 reset_str.push_str(se_str);
40 };
41
42 reset_str.push_str(
43 terminfo
44 .utf8_string_cap(termini::StringCapability::CursorNormal)
45 .unwrap_or(""),
46 );
47
48 reset_str.push_str("\x1B[0 q");
49
50 reset_str
51 }
52
53 /// Describes terminal capabilities like extended underline, truecolor, etc.
54 #[derive(Clone, Debug)]
55 struct Capabilities {
56 /// Support for undercurled, underdashed, etc.
57 has_extended_underlines: bool,
58 /// Support for resetting the cursor style back to normal.
59 reset_cursor_command: String,
60 }
61
62 impl Default for Capabilities {
63 fn default() -> Self {
64 Self {
65 has_extended_underlines: false,
66 reset_cursor_command: "\x1B[0 q".to_string(),
67 }
68 }
69 }
70
71 impl Capabilities {
72 /// Detect capabilities from the terminfo database located based
73 /// on the $TERM environment variable. If detection fails, returns
74 /// a default value where no capability is supported, or just undercurl
75 /// if config.undercurl is set.
76 pub fn from_env_or_default(config: &Config) -> Self {
77 match termini::TermInfo::from_env() {
78 Err(_) => Capabilities {
79 has_extended_underlines: config.force_enable_extended_underlines,
80 ..Capabilities::default()
81 },
82 Ok(t) => Capabilities {
83 // Smulx, VTE: https://unix.stackexchange.com/a/696253/246284
84 // Su (used by kitty): https://sw.kovidgoyal.net/kitty/underlines
85 // WezTerm supports underlines but a lot of distros don't properly install its terminfo
86 has_extended_underlines: config.force_enable_extended_underlines
87 || t.extended_cap("Smulx").is_some()
88 || t.extended_cap("Su").is_some()
89 || vte_version() >= Some(5102)
90 || matches!(term_program().as_deref(), Some("WezTerm")),
91 reset_cursor_command: reset_cursor_approach(t),
92 },
93 }
94 }
95 }
96
97 /// Terminal backend supporting a wide variety of terminals
98 pub struct CrosstermBackend<W: Write> {
99 buffer: W,
100 config: Config,
101 capabilities: Capabilities,
102 supports_keyboard_enhancement_protocol: OnceCell<bool>,
103 mouse_capture_enabled: bool,
104 supports_bracketed_paste: bool,
105 }
106
107 impl<W> CrosstermBackend<W>
108 where
109 W: Write,
110 {
111 pub fn new(buffer: W, config: Config) -> CrosstermBackend<W> {
112 // helix is not usable without colors, but crossterm will disable
113 // them by default if NO_COLOR is set in the environment. Override
114 // this behaviour.
115 crossterm::style::force_color_output(true);
116 CrosstermBackend {
117 buffer,
118 capabilities: Capabilities::from_env_or_default(&config),
119 config,
120 supports_keyboard_enhancement_protocol: OnceCell::new(),
121 mouse_capture_enabled: false,
122 supports_bracketed_paste: true,
123 }
124 }
125
126 #[inline]
127 fn supports_keyboard_enhancement_protocol(&self) -> bool {
128 *self.supports_keyboard_enhancement_protocol
129 .get_or_init(|| {
130 use std::time::Instant;
131
132 let now = Instant::now();
133 let supported = matches!(terminal::supports_keyboard_enhancement(), Ok(true));
134 log::debug!(
135 "The keyboard enhancement protocol is {}supported in this terminal (checked in {:?})",
136 if supported { "" } else { "not " },
137 Instant::now().duration_since(now)
138 );
139 supported
140 })
141 }
142 }
143
144 impl<W> Write for CrosstermBackend<W>
145 where
146 W: Write,
147 {
148 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
149 self.buffer.write(buf)
150 }
151
152 fn flush(&mut self) -> io::Result<()> {
153 self.buffer.flush()
154 }
155 }
156
157 impl<W> Backend for CrosstermBackend<W>
158 where
159 W: Write,
160 {
161 fn claim(&mut self) -> io::Result<()> {
162 terminal::enable_raw_mode()?;
163 execute!(
164 self.buffer,
165 terminal::EnterAlternateScreen,
166 EnableFocusChange
167 )?;
168 match execute!(self.buffer, EnableBracketedPaste,) {
169 Err(err) if err.kind() == io::ErrorKind::Unsupported => {
170 log::warn!("Bracketed paste is not supported on this terminal.");
171 self.supports_bracketed_paste = false;
172 }
173 Err(err) => return Err(err),
174 Ok(_) => (),
175 };
176 execute!(self.buffer, terminal::Clear(terminal::ClearType::All))?;
177 if self.config.enable_mouse_capture {
178 execute!(self.buffer, EnableMouseCapture)?;
179 self.mouse_capture_enabled = true;
180 }
181 if self.supports_keyboard_enhancement_protocol() {
182 execute!(
183 self.buffer,
184 PushKeyboardEnhancementFlags(
185 KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
186 | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS
187 )
188 )?;
189 }
190 Ok(())
191 }
192
193 fn reconfigure(&mut self, config: Config) -> io::Result<()> {
194 if self.mouse_capture_enabled != config.enable_mouse_capture {
195 if config.enable_mouse_capture {
196 execute!(self.buffer, EnableMouseCapture)?;
197 } else {
198 execute!(self.buffer, DisableMouseCapture)?;
199 }
200 self.mouse_capture_enabled = config.enable_mouse_capture;
201 }
202 self.config = config;
203
204 Ok(())
205 }
206
207 fn restore(&mut self) -> io::Result<()> {
208 // reset cursor shape
209 self.buffer
210 .write_all(self.capabilities.reset_cursor_command.as_bytes())?;
211 if self.config.enable_mouse_capture {
212 execute!(self.buffer, DisableMouseCapture)?;
213 }
214 if self.supports_keyboard_enhancement_protocol() {
215 execute!(self.buffer, PopKeyboardEnhancementFlags)?;
216 }
217 if self.supports_bracketed_paste {
218 execute!(self.buffer, DisableBracketedPaste,)?;
219 }
220 execute!(
221 self.buffer,
222 DisableFocusChange,
223 terminal::LeaveAlternateScreen
224 )?;
225 terminal::disable_raw_mode()
226 }
227
228 fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
229 where
230 I: Iterator<Item = (u16, u16, &'a Cell)>,
231 {
232 let mut fg = Color::Reset;
233 let mut bg = Color::Reset;
234 let mut underline_color = Color::Reset;
235 let mut underline_style = UnderlineStyle::Reset;
236 let mut modifier = Modifier::empty();
237 let mut last_pos: Option<(u16, u16)> = None;
238 for (x, y, cell) in content {
239 // Move the cursor if the previous location was not (x - 1, y)
240 if !matches!(last_pos, Some(p) if x == p.0 + 1 && y == p.1) {
241 queue!(self.buffer, MoveTo(x, y))?;
242 }
243 last_pos = Some((x, y));
244 if cell.modifier != modifier {
245 let diff = ModifierDiff {
246 from: modifier,
247 to: cell.modifier,
248 };
249 diff.queue(&mut self.buffer)?;
250 modifier = cell.modifier;
251 }
252 if cell.fg != fg || cell.bg != bg {
253 queue!(
254 self.buffer,
255 SetColors(Colors::new(cell.fg.into(), cell.bg.into()))
256 )?;
257 fg = cell.fg;
258 bg = cell.bg;
259 }
260
261 let mut new_underline_style = cell.underline_style;
262 if self.capabilities.has_extended_underlines {
263 if cell.underline_color != underline_color {
264 let color = CColor::from(cell.underline_color);
265 queue!(self.buffer, SetUnderlineColor(color))?;
266 underline_color = cell.underline_color;
267 }
268 } else {
269 match new_underline_style {
270 UnderlineStyle::Reset | UnderlineStyle::Line => (),
271 _ => new_underline_style = UnderlineStyle::Line,
272 }
273 }
274
275 if new_underline_style != underline_style {
276 let attr = CAttribute::from(new_underline_style);
277 queue!(self.buffer, SetAttribute(attr))?;
278 underline_style = new_underline_style;
279 }
280
281 queue!(self.buffer, Print(&cell.symbol))?;
282 }
283
284 queue!(
285 self.buffer,
286 SetUnderlineColor(CColor::Reset),
287 SetForegroundColor(CColor::Reset),
288 SetBackgroundColor(CColor::Reset),
289 SetAttribute(CAttribute::Reset)
290 )
291 }
292
293 fn hide_cursor(&mut self) -> io::Result<()> {
294 queue!(self.buffer, Hide)
295 }
296
297 fn show_cursor(&mut self, kind: CursorKind) -> io::Result<()> {
298 let shape = match kind {
299 CursorKind::Block => SetCursorStyle::SteadyBlock,
300 CursorKind::Bar => SetCursorStyle::SteadyBar,
301 CursorKind::Underline => SetCursorStyle::SteadyUnderScore,
302 CursorKind::Hidden => unreachable!(),
303 };
304 queue!(self.buffer, Show, shape)
305 }
306
307 fn set_cursor(&mut self, x: u16, y: u16) -> io::Result<()> {
308 queue!(self.buffer, MoveTo(x, y))
309 }
310
311 fn clear(&mut self) -> io::Result<()> {
312 queue!(self.buffer, Clear(ClearType::All))
313 }
314
315 fn start_sync(&mut self) -> io::Result<()> {
316 queue!(self.buffer, BeginSynchronizedUpdate)
317 }
318
319 fn end_sync(&mut self) -> io::Result<()> {
320 queue!(self.buffer, EndSynchronizedUpdate)
321 }
322
323 fn size(&self) -> io::Result<Rect> {
324 let (width, height) =
325 terminal::size().map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
326
327 Ok(Rect::new(0, 0, width, height))
328 }
329
330 fn flush(&mut self) -> io::Result<()> {
331 self.buffer.flush()
332 }
333
334 fn supports_true_color(&self) -> bool {
335 false
336 }
337
338 fn get_theme_mode(&self) -> Option<helix_view::theme::Mode> {
339 None
340 }
341
342 fn set_background_color(&mut self, _color: Option<helix_view::theme::Color>) -> io::Result<()> {
343 Ok(())
344 }
345 }
346
347 #[derive(Debug)]
348 struct ModifierDiff {
349 pub from: Modifier,
350 pub to: Modifier,
351 }
352
353 impl ModifierDiff {
354 fn queue<W>(&self, mut w: W) -> io::Result<()>
355 where
356 W: io::Write,
357 {
358 //use crossterm::Attribute;
359 let removed = self.from - self.to;
360 if removed.contains(Modifier::REVERSED) {
361 queue!(w, SetAttribute(CAttribute::NoReverse))?;
362 }
363 if removed.contains(Modifier::BOLD) {
364 queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
365 if self.to.contains(Modifier::DIM) {
366 queue!(w, SetAttribute(CAttribute::Dim))?;
367 }
368 }
369 if removed.contains(Modifier::ITALIC) {
370 queue!(w, SetAttribute(CAttribute::NoItalic))?;
371 }
372 if removed.contains(Modifier::DIM) {
373 queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
374 }
375 if removed.contains(Modifier::CROSSED_OUT) {
376 queue!(w, SetAttribute(CAttribute::NotCrossedOut))?;
377 }
378 if removed.contains(Modifier::SLOW_BLINK) || removed.contains(Modifier::RAPID_BLINK) {
379 queue!(w, SetAttribute(CAttribute::NoBlink))?;
380 }
381 if removed.contains(Modifier::HIDDEN) {
382 queue!(w, SetAttribute(CAttribute::NoHidden))?;
383 }
384
385 let added = self.to - self.from;
386 if added.contains(Modifier::REVERSED) {
387 queue!(w, SetAttribute(CAttribute::Reverse))?;
388 }
389 if added.contains(Modifier::BOLD) {
390 queue!(w, SetAttribute(CAttribute::Bold))?;
391 }
392 if added.contains(Modifier::ITALIC) {
393 queue!(w, SetAttribute(CAttribute::Italic))?;
394 }
395 if added.contains(Modifier::DIM) {
396 queue!(w, SetAttribute(CAttribute::Dim))?;
397 }
398 if added.contains(Modifier::CROSSED_OUT) {
399 queue!(w, SetAttribute(CAttribute::CrossedOut))?;
400 }
401 if added.contains(Modifier::SLOW_BLINK) {
402 queue!(w, SetAttribute(CAttribute::SlowBlink))?;
403 }
404 if added.contains(Modifier::RAPID_BLINK) {
405 queue!(w, SetAttribute(CAttribute::RapidBlink))?;
406 }
407 if added.contains(Modifier::HIDDEN) {
408 queue!(w, SetAttribute(CAttribute::Hidden))?;
409 }
410
411 Ok(())
412 }
413 }
414
415 /// Crossterm uses semicolon as a separator for colors
416 /// this is actually not spec compliant (although commonly supported)
417 /// However the correct approach is to use colons as a separator.
418 /// This usually doesn't make a difference for emulators that do support colored underlines.
419 /// However terminals that do not support colored underlines will ignore underlines colors with colons
420 /// while escape sequences with semicolons are always processed which leads to weird visual artifacts.
421 /// See [this nvim issue](https://github.com/neovim/neovim/issues/9270) for details
422 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
423 pub struct SetUnderlineColor(pub CColor);
424
425 impl Command for SetUnderlineColor {
426 fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
427 let color = self.0;
428
429 if color == CColor::Reset {
430 write!(f, "\x1b[59m")?;
431 return Ok(());
432 }
433 f.write_str("\x1b[58:")?;
434
435 let res = match color {
436 CColor::Black => f.write_str("5:0"),
437 CColor::DarkGrey => f.write_str("5:8"),
438 CColor::Red => f.write_str("5:9"),
439 CColor::DarkRed => f.write_str("5:1"),
440 CColor::Green => f.write_str("5:10"),
441 CColor::DarkGreen => f.write_str("5:2"),
442 CColor::Yellow => f.write_str("5:11"),
443 CColor::DarkYellow => f.write_str("5:3"),
444 CColor::Blue => f.write_str("5:12"),
445 CColor::DarkBlue => f.write_str("5:4"),
446 CColor::Magenta => f.write_str("5:13"),
447 CColor::DarkMagenta => f.write_str("5:5"),
448 CColor::Cyan => f.write_str("5:14"),
449 CColor::DarkCyan => f.write_str("5:6"),
450 CColor::White => f.write_str("5:15"),
451 CColor::Grey => f.write_str("5:7"),
452 CColor::Rgb { r, g, b } => write!(f, "2::{}:{}:{}", r, g, b),
453 CColor::AnsiValue(val) => write!(f, "5:{}", val),
454 _ => Ok(()),
455 };
456 res?;
457 write!(f, "m")?;
458 Ok(())
459 }
460
461 #[cfg(windows)]
462 fn execute_winapi(&self) -> io::Result<()> {
463 Err(std::io::Error::new(
464 std::io::ErrorKind::Other,
465 "SetUnderlineColor not supported by winapi.",
466 ))
467 }
468 }