-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathansi_win.py
74 lines (64 loc) · 1.9 KB
/
ansi_win.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from ctypes.wintypes import DWORD
from enum import Enum
import ctypes
class KeyCodes(Enum):
# KeyCodes {{{
SPACE = "\x20"
QUIT = "\x11"
UP = "k"
DOWN = "j"
LEFT = "h"
RIGHT = "l"
EXPAND = "e"
COPY = "c"
# }}}
# Input Constants
STD_INPUT_HANDLE = -10
ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200
# Output Constants
STD_OUTPUT_HANDLE = -11
ENABLE_PROCESSED_OUTPUT = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
def initialize() -> (ctypes.c_long, ctypes.c_long):
"""
In certain environments, this function may not
be needed, such as running PowerShell in Windows
Terminal. In other situations, such as running
Windows CMD 'straight', this allows the escape
characters to function properly.
Returns (output, input)
"""
# initialize {{{
kernel = ctypes.windll.kernel32
stdin = kernel.GetStdHandle(STD_INPUT_HANDLE)
stdout = kernel.GetStdHandle(STD_OUTPUT_HANDLE)
istate = DWORD()
ostate = DWORD()
kernel.GetConsoleMode(stdin, ctypes.byref(istate))
kernel.GetConsoleMode(stdout, ctypes.byref(ostate))
kernel.SetConsoleMode(
stdin,
ENABLE_VIRTUAL_TERMINAL_INPUT
)
kernel.SetConsoleMode(
stdout,
ENABLE_PROCESSED_OUTPUT |
ENABLE_WRAP_AT_EOL_OUTPUT |
ENABLE_VIRTUAL_TERMINAL_PROCESSING
)
return (ostate, istate)
# }}}
def reset(ostate: ctypes.c_long, istate: ctypes.c_long) -> None:
"""
Though not strictly necessary, this function is used as a
means to ensure the user's terminal is returned to the
way it was before using this application.
"""
# reset {{{
kernel = ctypes.windll.kernel32
stdin = kernel.GetStdHandle(STD_INPUT_HANDLE)
stdout = kernel.GetStdHandle(STD_OUTPUT_HANDLE)
kernel.SetConsoleMode(stdin, istate)
kernel.SetConsoleMode(stdout, ostate)
# }}}