Debian Codegraph @

helix-tui/src/terminal.rs

raw symbols SCIP
1 //! Terminal interface provided through the [Terminal] type.
2 //! Frontend for [Backend]
3
4 use crate::{backend::Backend, buffer::Buffer};
5 use helix_view::editor::{Config as EditorConfig, KittyKeyboardProtocolConfig};
6 use helix_view::graphics::{CursorKind, Rect};
7 use std::io;
8
9 #[derive(Debug, Clone, PartialEq)]
10 /// UNSTABLE
11 enum ResizeBehavior {
12 Fixed,
13 Auto,
14 }
15
16 #[derive(Debug, Clone, PartialEq)]
17 /// UNSTABLE
18 pub struct Viewport {
19 area: Rect,
20 resize_behavior: ResizeBehavior,
21 }
22
23 /// Terminal configuration
24 #[derive(Debug)]
25 pub struct Config {
26 pub enable_mouse_capture: bool,
27 pub force_enable_extended_underlines: bool,
28 pub kitty_keyboard_protocol: KittyKeyboardProtocolConfig,
29 }
30
31 impl From<&EditorConfig> for Config {
32 fn from(config: &EditorConfig) -> Self {
33 Self {
34 enable_mouse_capture: config.mouse,
35 force_enable_extended_underlines: config.undercurl,
36 kitty_keyboard_protocol: config.kitty_keyboard_protocol,
37 }
38 }
39 }
40
41 impl Viewport {
42 /// UNSTABLE
43 pub fn fixed(area: Rect) -> Viewport {
44 Viewport {
45 area,
46 resize_behavior: ResizeBehavior::Fixed,
47 }
48 }
49 }
50
51 #[derive(Debug, Clone, PartialEq)]
52 /// Options to pass to [`Terminal::with_options`]
53 pub struct TerminalOptions {
54 /// Viewport used to draw to the terminal
55 pub viewport: Viewport,
56 }
57
58 /// Interface to the terminal backed by crossterm
59 #[derive(Debug)]
60 pub struct Terminal<B>
61 where
62 B: Backend,
63 {
64 backend: B,
65 /// Holds the results of the current and previous draw calls. The two are compared at the end
66 /// of each draw pass to output the necessary updates to the terminal
67 buffers: [Buffer; 2],
68 /// Index of the current buffer in the previous array
69 current: usize,
70 /// Kind of cursor (hidden or others)
71 cursor_kind: CursorKind,
72 /// Viewport
73 viewport: Viewport,
74 /// Set to request a full clear. The erase is deferred to the next `flush` so it is emitted
75 /// inside the same synchronized-output frame as the repaint to avoid painting blank frames
76 force_clear: bool,
77 }
78
79 /// Default terminal size: 80 columns, 24 lines
80 pub const DEFAULT_TERMINAL_SIZE: Rect = Rect {
81 x: 0,
82 y: 0,
83 width: 80,
84 height: 24,
85 };
86
87 impl<B> Terminal<B>
88 where
89 B: Backend,
90 {
91 /// Wrapper around Terminal initialization. Each buffer is initialized with a blank string and
92 /// default colors for the foreground and the background
93 pub fn new(backend: B) -> io::Result<Terminal<B>> {
94 let size = backend.size().unwrap_or(DEFAULT_TERMINAL_SIZE);
95 Terminal::with_options(
96 backend,
97 TerminalOptions {
98 viewport: Viewport {
99 area: size,
100 resize_behavior: ResizeBehavior::Auto,
101 },
102 },
103 )
104 }
105
106 /// UNSTABLE
107 pub fn with_options(backend: B, options: TerminalOptions) -> io::Result<Terminal<B>> {
108 Ok(Terminal {
109 backend,
110 buffers: [
111 Buffer::empty(options.viewport.area),
112 Buffer::empty(options.viewport.area),
113 ],
114 current: 0,
115 cursor_kind: CursorKind::Block,
116 viewport: options.viewport,
117 force_clear: false,
118 })
119 }
120
121 pub fn claim(&mut self) -> io::Result<()> {
122 self.backend.claim()
123 }
124
125 pub fn reconfigure(&mut self, config: Config) -> io::Result<()> {
126 self.backend.reconfigure(config)
127 }
128
129 pub fn restore(&mut self) -> io::Result<()> {
130 self.backend.restore()
131 }
132
133 // /// Get a Frame object which provides a consistent view into the terminal state for rendering.
134 // pub fn get_frame(&mut self) -> Frame<B> {
135 // Frame {
136 // terminal: self,
137 // cursor_position: None,
138 // }
139 // }
140
141 pub fn current_buffer_mut(&mut self) -> &mut Buffer {
142 &mut self.buffers[self.current]
143 }
144
145 pub fn backend(&self) -> &B {
146 &self.backend
147 }
148
149 pub fn backend_mut(&mut self) -> &mut B {
150 &mut self.backend
151 }
152
153 /// Obtains a difference between the previous and the current buffer and passes it to the
154 /// current backend for drawing.
155 pub fn flush(&mut self) -> io::Result<()> {
156 if self.force_clear {
157 self.backend.clear()?;
158 self.force_clear = false;
159 }
160 let previous_buffer = &self.buffers[1 - self.current];
161 let current_buffer = &self.buffers[self.current];
162 let updates = previous_buffer.diff(current_buffer);
163 self.backend.draw(updates.into_iter())
164 }
165
166 /// Updates the Terminal so that internal buffers match the requested size. Requested size will
167 /// be saved so the size can remain consistent when rendering.
168 pub fn resize(&mut self, area: Rect) -> io::Result<()> {
169 self.buffers[self.current].resize(area);
170 self.buffers[1 - self.current].resize(area);
171 self.viewport.area = area;
172 self.clear()
173 }
174
175 /// Queries the backend for size and resizes if it doesn't match the previous size.
176 pub fn autoresize(&mut self) -> io::Result<Rect> {
177 let size = self.size();
178 if size != self.viewport.area {
179 self.resize(size)?;
180 };
181 Ok(size)
182 }
183
184 /// Synchronizes terminal size, calls the rendering closure, flushes the current internal state
185 /// and prepares for the next draw call.
186 pub fn draw(
187 &mut self,
188 cursor_position: Option<(u16, u16)>,
189 cursor_kind: CursorKind,
190 ) -> io::Result<()> {
191 // // Autoresize - otherwise we get glitches if shrinking or potential desync between widgets
192 // // and the terminal (if growing), which may OOB.
193 // self.autoresize()?;
194
195 // let mut frame = self.get_frame();
196 // f(&mut frame);
197 // // We can't change the cursor position right away because we have to flush the frame to
198 // // stdout first. But we also can't keep the frame around, since it holds a &mut to
199 // // Terminal. Thus, we're taking the important data out of the Frame and dropping it.
200 // let cursor_position = frame.cursor_position;
201
202 // One synchronized frame for the whole draw
203 self.backend.start_sync()?;
204
205 // Draw to stdout
206 self.flush()?;
207
208 if let Some((x, y)) = cursor_position {
209 self.set_cursor(x, y)?;
210 }
211
212 match cursor_kind {
213 CursorKind::Hidden => self.hide_cursor()?,
214 kind => self.show_cursor(kind)?,
215 }
216
217 self.backend.end_sync()?;
218
219 // Swap buffers
220 self.buffers[1 - self.current].reset();
221 self.current = 1 - self.current;
222
223 // Flush
224 self.backend.flush()?;
225 Ok(())
226 }
227
228 #[inline]
229 pub fn cursor_kind(&self) -> CursorKind {
230 self.cursor_kind
231 }
232
233 pub fn hide_cursor(&mut self) -> io::Result<()> {
234 self.backend.hide_cursor()?;
235 self.cursor_kind = CursorKind::Hidden;
236 Ok(())
237 }
238
239 pub fn show_cursor(&mut self, kind: CursorKind) -> io::Result<()> {
240 self.backend.show_cursor(kind)?;
241 self.cursor_kind = kind;
242 Ok(())
243 }
244
245 pub fn set_cursor(&mut self, x: u16, y: u16) -> io::Result<()> {
246 self.backend.set_cursor(x, y)
247 }
248
249 /// Clear the terminal and force a full redraw on the next draw call.
250 ///
251 /// The physical erase is deferred to the next `flush` so it shares a
252 /// synchronized frame with the repaint.
253 pub fn clear(&mut self) -> io::Result<()> {
254 self.force_clear = true;
255 // Reset the back buffer to make sure the next update will redraw everything.
256 self.buffers[1 - self.current].reset();
257 Ok(())
258 }
259
260 /// Queries the real size of the backend.
261 pub fn size(&self) -> Rect {
262 self.backend.size().unwrap_or(DEFAULT_TERMINAL_SIZE)
263 }
264 }