Debian Codegraph @

src/cursor/sys/windows.rs

raw
1 //! WinAPI related logic to cursor manipulation.
2
3 use std::convert::TryFrom;
4 use std::io;
5 use std::sync::atomic::{AtomicU64, Ordering};
6
7 use crossterm_winapi::{result, Coord, Handle, HandleType, ScreenBuffer};
8 use winapi::{
9 shared::minwindef::{FALSE, TRUE},
10 um::wincon::{SetConsoleCursorInfo, SetConsoleCursorPosition, CONSOLE_CURSOR_INFO, COORD},
11 };
12
13 /// The position of the cursor, written when you save the cursor's position.
14 ///
15 /// This is `u64::MAX` initially. Otherwise, it stores the cursor's x position bit-shifted left 16
16 /// times or-ed with the cursor's y position, where both are `i16`s.
17 static SAVED_CURSOR_POS: AtomicU64 = AtomicU64::new(u64::MAX);
18
19 // The 'y' position of the cursor is not relative to the window but absolute to screen buffer.
20 // We can calculate the relative cursor position by subtracting the top position of the terminal window from the y position.
21 // This results in an 1-based coord zo subtract 1 to make cursor position 0-based.
22 pub fn parse_relative_y(y: i16) -> std::io::Result<i16> {
23 let window = ScreenBuffer::current()?.info()?;
24
25 let window_size = window.terminal_window();
26 let screen_size = window.terminal_size();
27
28 if y <= screen_size.height {
29 Ok(y)
30 } else {
31 Ok(y - window_size.top)
32 }
33 }
34
35 /// Returns the cursor position (column, row).
36 ///
37 /// The top left cell is represented `0,0`.
38 pub fn position() -> io::Result<(u16, u16)> {
39 let cursor = ScreenBufferCursor::output()?;
40 let mut position = cursor.position()?;
41 // if position.y != 0 {
42 position.y = parse_relative_y(position.y)?;
43 // }
44 Ok(position.into())
45 }
46
47 pub(crate) fn show_cursor(show_cursor: bool) -> std::io::Result<()> {
48 ScreenBufferCursor::from(Handle::current_out_handle()?).set_visibility(show_cursor)
49 }
50
51 pub(crate) fn move_to(column: u16, row: u16) -> std::io::Result<()> {
52 let cursor = ScreenBufferCursor::output()?;
53 cursor.move_to(column as i16, row as i16)?;
54 Ok(())
55 }
56
57 pub(crate) fn move_up(count: u16) -> std::io::Result<()> {
58 let (column, row) = position()?;
59 move_to(column, row - count)?;
60 Ok(())
61 }
62
63 pub(crate) fn move_right(count: u16) -> std::io::Result<()> {
64 let (column, row) = position()?;
65 move_to(column + count, row)?;
66 Ok(())
67 }
68
69 pub(crate) fn move_down(count: u16) -> std::io::Result<()> {
70 let (column, row) = position()?;
71 move_to(column, row + count)?;
72 Ok(())
73 }
74
75 pub(crate) fn move_left(count: u16) -> std::io::Result<()> {
76 let (column, row) = position()?;
77 move_to(column - count, row)?;
78 Ok(())
79 }
80
81 pub(crate) fn move_to_column(new_column: u16) -> std::io::Result<()> {
82 let (_, row) = position()?;
83 move_to(new_column, row)?;
84 Ok(())
85 }
86
87 pub(crate) fn move_to_row(new_row: u16) -> std::io::Result<()> {
88 let (col, _) = position()?;
89 move_to(col, new_row)?;
90 Ok(())
91 }
92
93 pub(crate) fn move_to_next_line(count: u16) -> std::io::Result<()> {
94 let (_, row) = position()?;
95 move_to(0, row + count)?;
96 Ok(())
97 }
98
99 pub(crate) fn move_to_previous_line(count: u16) -> std::io::Result<()> {
100 let (_, row) = position()?;
101 move_to(0, row - count)?;
102 Ok(())
103 }
104
105 pub(crate) fn save_position() -> std::io::Result<()> {
106 ScreenBufferCursor::output()?.save_position()?;
107 Ok(())
108 }
109
110 pub(crate) fn restore_position() -> std::io::Result<()> {
111 ScreenBufferCursor::output()?.restore_position()?;
112 Ok(())
113 }
114
115 /// WinAPI wrapper over terminal cursor behaviour.
116 struct ScreenBufferCursor {
117 screen_buffer: ScreenBuffer,
118 }
119
120 impl ScreenBufferCursor {
121 fn output() -> std::io::Result<ScreenBufferCursor> {
122 Ok(ScreenBufferCursor {
123 screen_buffer: ScreenBuffer::from(Handle::new(HandleType::CurrentOutputHandle)?),
124 })
125 }
126
127 fn position(&self) -> std::io::Result<Coord> {
128 Ok(self.screen_buffer.info()?.cursor_pos())
129 }
130
131 fn move_to(&self, x: i16, y: i16) -> std::io::Result<()> {
132 if x < 0 {
133 return Err(io::Error::new(
134 io::ErrorKind::Other,
135 format!("Argument Out of Range Exception when setting cursor position to X: {x}"),
136 ));
137 }
138
139 if y < 0 {
140 return Err(io::Error::new(
141 io::ErrorKind::Other,
142 format!("Argument Out of Range Exception when setting cursor position to Y: {y}"),
143 ));
144 }
145
146 let position = COORD { X: x, Y: y };
147
148 unsafe {
149 if result(SetConsoleCursorPosition(
150 **self.screen_buffer.handle(),
151 position,
152 ))
153 .is_err()
154 {
155 return Err(io::Error::last_os_error());
156 }
157 }
158 Ok(())
159 }
160
161 fn set_visibility(&self, visible: bool) -> std::io::Result<()> {
162 let cursor_info = CONSOLE_CURSOR_INFO {
163 dwSize: 100,
164 bVisible: if visible { TRUE } else { FALSE },
165 };
166
167 unsafe {
168 if result(SetConsoleCursorInfo(
169 **self.screen_buffer.handle(),
170 &cursor_info,
171 ))
172 .is_err()
173 {
174 return Err(io::Error::last_os_error());
175 }
176 }
177 Ok(())
178 }
179
180 fn restore_position(&self) -> std::io::Result<()> {
181 if let Ok(val) = u32::try_from(SAVED_CURSOR_POS.load(Ordering::Relaxed)) {
182 let x = (val >> 16) as i16;
183 let y = val as i16;
184 self.move_to(x, y)?;
185 }
186
187 Ok(())
188 }
189
190 fn save_position(&self) -> std::io::Result<()> {
191 let position = self.position()?;
192
193 let upper = u32::from(position.x as u16) << 16;
194 let lower = u32::from(position.y as u16);
195 let bits = u64::from(upper | lower);
196 SAVED_CURSOR_POS.store(bits, Ordering::Relaxed);
197
198 Ok(())
199 }
200 }
201
202 impl From<Handle> for ScreenBufferCursor {
203 fn from(handle: Handle) -> Self {
204 ScreenBufferCursor {
205 screen_buffer: ScreenBuffer::from(handle),
206 }
207 }
208 }
209
210 #[cfg(test)]
211 mod tests {
212 use super::{
213 move_down, move_left, move_right, move_to, move_to_column, move_to_next_line,
214 move_to_previous_line, move_to_row, move_up, position, restore_position, save_position,
215 };
216 use crate::terminal::sys::temp_screen_buffer;
217 use serial_test::serial;
218
219 #[test]
220 #[serial]
221 fn test_move_to_winapi() {
222 let _test_screen = temp_screen_buffer().unwrap();
223
224 let (saved_x, saved_y) = position().unwrap();
225
226 move_to(saved_x + 1, saved_y + 1).unwrap();
227 assert_eq!(position().unwrap(), (saved_x + 1, saved_y + 1));
228
229 move_to(saved_x, saved_y).unwrap();
230 assert_eq!(position().unwrap(), (saved_x, saved_y));
231 }
232
233 #[test]
234 #[serial]
235 fn test_move_right_winapi() {
236 let _test_screen = temp_screen_buffer().unwrap();
237
238 let (saved_x, saved_y) = position().unwrap();
239 move_right(1).unwrap();
240 assert_eq!(position().unwrap(), (saved_x + 1, saved_y));
241 }
242
243 #[test]
244 #[serial]
245 fn test_move_left_winapi() {
246 let _test_screen = temp_screen_buffer().unwrap();
247
248 move_to(2, 0).unwrap();
249
250 move_left(2).unwrap();
251
252 assert_eq!(position().unwrap(), (0, 0));
253 }
254
255 #[test]
256 #[serial]
257 fn test_move_up_winapi() {
258 let _test_screen = temp_screen_buffer().unwrap();
259
260 move_to(0, 2).unwrap();
261
262 move_up(2).unwrap();
263
264 assert_eq!(position().unwrap(), (0, 0));
265 }
266
267 #[test]
268 #[serial]
269 fn test_move_to_next_line_winapi() {
270 let _test_screen = temp_screen_buffer().unwrap();
271
272 move_to(0, 2).unwrap();
273
274 move_to_next_line(2).unwrap();
275
276 assert_eq!(position().unwrap(), (0, 4));
277 }
278
279 #[test]
280 #[serial]
281 fn test_move_to_previous_line_winapi() {
282 let _test_screen = temp_screen_buffer().unwrap();
283
284 move_to(0, 2).unwrap();
285
286 move_to_previous_line(2).unwrap();
287
288 assert_eq!(position().unwrap(), (0, 0));
289 }
290
291 #[test]
292 #[serial]
293 fn test_move_to_column_winapi() {
294 let _test_screen = temp_screen_buffer().unwrap();
295
296 move_to(0, 2).unwrap();
297
298 move_to_column(12).unwrap();
299
300 assert_eq!(position().unwrap(), (12, 2));
301 }
302
303 #[test]
304 #[serial]
305 fn test_move_to_row_winapi() {
306 let _test_screen = temp_screen_buffer().unwrap();
307
308 move_to(0, 2).unwrap();
309
310 move_to_row(5).unwrap();
311
312 assert_eq!(position().unwrap(), (0, 5));
313 }
314
315 #[test]
316 #[serial]
317 fn test_move_down_winapi() {
318 let _test_screen = temp_screen_buffer().unwrap();
319
320 move_to(0, 0).unwrap();
321
322 move_down(2).unwrap();
323
324 assert_eq!(position().unwrap(), (0, 2));
325 }
326
327 #[test]
328 #[serial]
329 fn test_save_restore_position_winapi() {
330 let _test_screen = temp_screen_buffer().unwrap();
331
332 let (saved_x, saved_y) = position().unwrap();
333
334 save_position().unwrap();
335 move_to(saved_x + 1, saved_y + 1).unwrap();
336 restore_position().unwrap();
337
338 let (x, y) = position().unwrap();
339
340 assert_eq!(x, saved_x);
341 assert_eq!(y, saved_y);
342 }
343 }