forked from Im-Beast/deno_tui
/
key_reader.ts
48 lines (40 loc) 路 1.45 KB
/
key_reader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2022 Im-Beast. All rights reserved. MIT license.
import { decodeWindowsBuffer } from "./key_reader/windows.ts";
import { decodeUnixBuffer } from "./key_reader/unix.ts";
import type { KeyPress, MousePress, Stdin } from "./types.ts";
/**
* Read keypresses from given stdin (except for Windows) and then parse them.
* On Windows keys are read by calling `_getch()` in `msvcrt.dll`.
* It yields array of either KeyPress or MousePress
*/
export async function* readKeypresses(stdin: Stdin): AsyncGenerator<(KeyPress | MousePress)[], void, void> {
switch (Deno.build.os) {
case "windows": {
const dll = Deno.dlopen("C:\\Windows\\System32\\msvcrt.dll", {
"_getch": { parameters: [], result: "i32", nonblocking: true },
});
try {
stdin.setRaw(true);
} catch { /**/ }
while (true) {
let char = await dll.symbols._getch();
let special: number;
if (char === 0 || char === 224) {
special = char;
char = await dll.symbols._getch();
}
yield [decodeWindowsBuffer(char, special!)];
}
}
default:
try {
stdin.setRaw(true, { cbreak: true });
} catch { /**/ }
while (true) {
const buffer = new Uint8Array(1024);
const byteLength = await stdin.read(buffer).catch(() => null);
if (typeof byteLength !== "number") continue;
yield [...decodeUnixBuffer(buffer.subarray(0, byteLength))];
}
}
}