Debian Codegraph @

Xtermina/docs/windows-vt.md

raw symbols SCIP
1 # Reading Virtual Terminal sequences from the Windows Console
2
3 Since the addition of [ConPTY](https://devblogs.microsoft.com/commandline/windows-command-line-introducing-the-windows-pseudo-console-conpty/), it is now possible to interact with the Windows Console API with escape sequences like a *NIX PTY. There aren't many good examples on doing this though. This doc will show code snippets for reading VT sequences from the Windows Console.
4
5 This doc assumes you have Rust experience, especially with calling into system APIs, for example the `libc`, `rustix` or `windows-sys` crates. In this doc I will gloss over all error handling. To reference how these system calls are handled in Termina see `src/terminal/windows.rs` and `src/event/source/windows.rs`.
6
7 ### Opening handles
8
9 The first step is opening the input and output Console handles.
10
11 ```rust
12 use std::{io, fs};
13
14 fn open_pty() -> io::Result<(OwnedHandle, OwnedHandle)> {
15 let input = fs::OpenOptions::new().read(true).write(true).open("CONIN$")?.into();
16 let output = fs::OpenOptions::new().read(true).write(true).open("CONOUT$")?.into();
17 Ok((input, output))
18 }
19 ```
20
21 ### Setting code pages
22
23 Then we want to set the "code pages" (encodings) that we will speak to/from these handles using the `SetConsoleCP` and `SetConsoleOutputCP` functions from the Windows Console API. When "speaking VT" we want this encoding to be UTF-8 so we use the `CP_UTF8` code page ID.
24
25 ```rust
26 use std::os::windows::io::AsRawHandle;
27 use windows_sys::Win32::{Globalization::CP_UTF8, System::Console}
28
29 unsafe { Console::SetConsoleCP(input.as_raw_handle(), CP_UTF8) };
30 unsafe { Console::SetConsoleOutputCP(output.as_raw_handle(), CP_UTF8) };
31 ```
32
33 ### Setting console modes
34
35 Then we have to alter the [console modes](https://learn.microsoft.com/en-us/windows/console/high-level-console-modes) of the handles. This is somewhat similar to [termios(3)](https://www.man7.org/linux/man-pages/man3/termios.3.html) in *NIX which is used to set raw or cooked modes. There are a few flags we want to enable/disable off the bat.
36
37 ```rust
38 use windows_sys::Win32::System::Console;
39
40 let mut original_input_mode = 0;
41 let mut original_output_mode = 0;
42
43 unsafe {
44 Console::GetConsoleMode(input.as_raw_handle(), &mut original_input_mode);
45 Console::GetConsoleMode(output.as_raw_handle(), &mut original_output_mode);
46 }
47
48 let desired_input_mode = original_input_mode | Console::ENABLE_VIRTUAL_TERMINAL_INPUT;
49 let desired_output_mode = original_output_mode
50 | Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING
51 | Console::DISABLE_NEWLINE_AUTO_RETURN;
52
53 unsafe {
54 Console::SetConsoleMode(input.as_raw_handle(), desired_input_mode);
55 Console::SetConsoleMode(output.as_raw_handle(), desired_output_mode);
56 }
57 ```
58
59 Now we've done what the Microsoft docs say: we've instructed our input and output handles to speak UTF-8 encoded VT. This is all the setup we need and now we can talk about reading and writing our input and output handles.
60
61 ### Writing VT
62
63 Writing escape sequences is fairly straightforward. We'll add a bit of machinery around the `OwnedHandle` used for the output so we can implement the `std::io::Write` trait and use `write!` in the future.
64
65 ```rust
66 use windows_sys::Win32::Storage::FileSystem::WriteFile;
67 use std::ptr;
68
69 struct OutputHandle {
70 handle: OwnedHandle,
71 }
72
73 impl io::Write for OutputHandle {
74 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
75 let mut num_written = 0;
76 if unsafe {
77 WriteFile(
78 self.handle.as_raw_handle(),
79 buf.as_ptr(),
80 buf.len() as u32,
81 &mut num_written,
82 ptr::null_mut();
83 )
84 } == 0 {
85 Err(io::Error::last_error())
86 } else {
87 Ok(num_written as usize)
88 }
89 }
90
91 fn flush(&mut self) -> io::Result<()> {
92 Ok(())
93 }
94 }
95 ```
96
97 Now we can write escape sequences like so:
98
99 ```rust
100 let output = OutputHandle { handle: output };
101 write!(output, "\x1b[32mHello, world!\x1b[0m");
102 ```
103
104 So this works just like how you'd interact with a *NIX PTY: you write the UTF-8 encoded VT bytes to the output file/device.
105
106 ### Reading VT
107
108 Reading is trickier. We could similarly use `ReadFile` or `ReadConsole` on the `CONIN$` handle but the Microsoft docs have a [note about this](https://learn.microsoft.com/en-us/windows/console/classic-vs-vt#exceptions-for-using-windows-console-apis):
109
110 > Applications that must be aware of window size changes will still need to use `ReadConsoleInput` to receive them interleaved with key events as `ReadConsole` alone will discard them.
111
112 `ReadConsoleInput` would otherwise be considered legacy: it's what you would use to read events before ConPTY. We need it though if we want to receive resizing events. Using `ReadConsole` or `ReadFile` would cause these events to be discarded. So how does this work exactly then?
113
114 ```rust
115 use windows_sys::Win32::System::Console::{
116 GetNumberOfConsoleInputEvents, KEY_EVENT, INPUT_RECORD, ReadConsoleInputA,
117 WINDOW_BUFFER_SIZE_EVENT,
118 };
119 use std::mem;
120
121 let mut capacity = 128;
122 let mut records = Vec::with_capacity(capacity);
123 let zeroed: INPUT_RECORD = unsafe { mem::zeroed() };
124 records.resize(capacity, zeroed);
125 let mut num_read = 0;
126 unsafe {
127 ReadConsoleInputA(output.handle.as_raw_handle(), records.as_mut_ptr(), new_to_read, &mut num_read);
128 records.set_len(num_read as usize);
129 }
130
131 let mut buffer = Vec::new();
132 for record in records {
133 match record.EventType as u32 {
134 KEY_EVENT => {
135 let record = unsafe { record.Event.KeyEvent };
136 if record.bKeyDown == 0 {
137 continue;
138 }
139 buffer.push(unsafe { record.uChar.AsciiChar } as u8);
140 }
141 WINDOW_BUFFER_SIZE_EVENT => {
142 let record = unsafe { record.Event.WindowBufferSizeEvent };
143 // NOTE: Unix sizes are one-indexed. We `+ 1` to normalize to that convention.
144 let rows = (record.dwSize.Y + 1) as u16;
145 let cols = (record.dwSize.X + 1) as u16;
146 todo!("resized to ({rows}, {cols})");
147 }
148 _ => (),
149 }
150 }
151 ```
152
153 First we check the number of available records with `GetNumberOfConsoleInputEvents` and then fill a buffer of [`INPUT_RECORD`](https://learn.microsoft.com/en-us/windows/console/input-record-str)s with `ReadConsoleInputA`. The [Microsoft docs say](https://learn.microsoft.com/en-us/windows/console/classic-vs-vt#unicode) that `ReadConsoleInputA` is the way to receive UTF-8 encoded text after we've enabled `CP_UTF8`:
154
155 > UTF-8 support in the console can be utilized via the `A` variant of Console APIs against console handles after setting the codepage to `65001` or `CP_UTF8` with the `SetConsoleOutputCP` and `SetConsoleCP` methods, as appropriate.
156
157 In that buffer of input records be care about two events: key events and window resizes. For [`KEY_EVENT_RECORD`](https://learn.microsoft.com/en-us/windows/console/key-event-record-str)s we don't actually care about the virtual key codes. We would if we were reading with the legacy Console API but since we've enabled VT processing on the input, we can expect that the key event record is actually just a byte that we should add to our input buffer. For example if we type the character 'a' then we can expect that the byte 97 arrives as this `record.uChar.AsciiChar`.
158
159 That's the story for reading. Now the input buffer can be parsed the same as the bytes read from a *NIX PTY device.