-
Notifications
You must be signed in to change notification settings - Fork 25
/
illwill.nim
1659 lines (1433 loc) · 52.4 KB
/
illwill.nim
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## :Authors: John Novak
##
## This is a *curses* inspired simple terminal library that aims to make
## writing cross-platform text mode applications easier. The main features are:
##
## * Non-blocking keyboard input
## * Support for key combinations and special keys available in the standard
## Windows Console (`cmd.exe`) and most common POSIX terminals
## * Virtual terminal buffers with double-buffering support (only
## display changes from the previous frame and minimise the number of
## attribute changes to reduce CPU usage)
## * Simple graphics using UTF-8 box drawing symbols
## * Full-screen support with restoring the contents of the terminal after
## exit (restoring works only on POSIX)
## * Basic suspend/continue (`SIGTSTP`, `SIGCONT`) support on POSIX
## * Basic mouse support
##
## The module depends only on the standard `terminal
## <https://nim-lang.org/docs/terminal.html>`_ module. However, you
## should not use any terminal functions directly, neither should you use
## `echo`, `write` or other similar functions for output. You should **only**
## use the interface provided by the module to interact with the terminal.
##
## The following symbols are exported from the terminal_ module (these are
## safe to use):
##
## * `terminalWidth() <https://nim-lang.org/docs/terminal.html#terminalWidth>`_
## * `terminalHeight() <https://nim-lang.org/docs/terminal.html#terminalHeight>`_
## * `terminalSize() <https://nim-lang.org/docs/terminal.html#terminalSize>`_
## * `hideCursor() <https://nim-lang.org/docs/terminal.html#hideCursor.t>`_
## * `showCursor() <https://nim-lang.org/docs/terminal.html#showCursor.t>`_
## * `Style <https://nim-lang.org/docs/terminal.html#Style>`_
##
import macros, os, terminal, unicode, bitops
export terminal.terminalWidth
export terminal.terminalHeight
export terminal.terminalSize
export terminal.hideCursor
export terminal.showCursor
export terminal.Style
type
ForegroundColor* = enum ## Foreground colors
fgNone = 0, ## default
fgBlack = 30, ## black
fgRed, ## red
fgGreen, ## green
fgYellow, ## yellow
fgBlue, ## blue
fgMagenta, ## magenta
fgCyan, ## cyan
fgWhite ## white
BackgroundColor* = enum ## Background colors
bgNone = 0, ## default (transparent)
bgBlack = 40, ## black
bgRed, ## red
bgGreen, ## green
bgYellow, ## yellow
bgBlue, ## blue
bgMagenta, ## magenta
bgCyan, ## cyan
bgWhite ## white
Key* {.pure.} = enum ## Supported single key presses and key combinations
None = (-1, "None"),
# Special ASCII characters
CtrlA = (1, "CtrlA"),
CtrlB = (2, "CtrlB"),
CtrlC = (3, "CtrlC"),
CtrlD = (4, "CtrlD"),
CtrlE = (5, "CtrlE"),
CtrlF = (6, "CtrlF"),
CtrlG = (7, "CtrlG"),
CtrlH = (8, "CtrlH"),
Tab = (9, "Tab"), # Ctrl-I
CtrlJ = (10, "CtrlJ"),
CtrlK = (11, "CtrlK"),
CtrlL = (12, "CtrlL"),
Enter = (13, "Enter"), # Ctrl-M
CtrlN = (14, "CtrlN"),
CtrlO = (15, "CtrlO"),
CtrlP = (16, "CtrlP"),
CtrlQ = (17, "CtrlQ"),
CtrlR = (18, "CtrlR"),
CtrlS = (19, "CtrlS"),
CtrlT = (20, "CtrlT"),
CtrlU = (21, "CtrlU"),
CtrlV = (22, "CtrlV"),
CtrlW = (23, "CtrlW"),
CtrlX = (24, "CtrlX"),
CtrlY = (25, "CtrlY"),
CtrlZ = (26, "CtrlZ"),
Escape = (27, "Escape"),
CtrlBackslash = (28, "CtrlBackslash"),
CtrlRightBracket = (29, "CtrlRightBracket"),
# Printable ASCII characters
Space = (32, "Space"),
ExclamationMark = (33, "ExclamationMark"),
DoubleQuote = (34, "DoubleQuote"),
Hash = (35, "Hash"),
Dollar = (36, "Dollar"),
Percent = (37, "Percent"),
Ampersand = (38, "Ampersand"),
SingleQuote = (39, "SingleQuote"),
LeftParen = (40, "LeftParen"),
RightParen = (41, "RightParen"),
Asterisk = (42, "Asterisk"),
Plus = (43, "Plus"),
Comma = (44, "Comma"),
Minus = (45, "Minus"),
Dot = (46, "Dot"),
Slash = (47, "Slash"),
Zero = (48, "Zero"),
One = (49, "One"),
Two = (50, "Two"),
Three = (51, "Three"),
Four = (52, "Four"),
Five = (53, "Five"),
Six = (54, "Six"),
Seven = (55, "Seven"),
Eight = (56, "Eight"),
Nine = (57, "Nine"),
Colon = (58, "Colon"),
Semicolon = (59, "Semicolon"),
LessThan = (60, "LessThan"),
Equals = (61, "Equals"),
GreaterThan = (62, "GreaterThan"),
QuestionMark = (63, "QuestionMark"),
At = (64, "At"),
ShiftA = (65, "ShiftA"),
ShiftB = (66, "ShiftB"),
ShiftC = (67, "ShiftC"),
ShiftD = (68, "ShiftD"),
ShiftE = (69, "ShiftE"),
ShiftF = (70, "ShiftF"),
ShiftG = (71, "ShiftG"),
ShiftH = (72, "ShiftH"),
ShiftI = (73, "ShiftI"),
ShiftJ = (74, "ShiftJ"),
ShiftK = (75, "ShiftK"),
ShiftL = (76, "ShiftL"),
ShiftM = (77, "ShiftM"),
ShiftN = (78, "ShiftN"),
ShiftO = (79, "ShiftO"),
ShiftP = (80, "ShiftP"),
ShiftQ = (81, "ShiftQ"),
ShiftR = (82, "ShiftR"),
ShiftS = (83, "ShiftS"),
ShiftT = (84, "ShiftT"),
ShiftU = (85, "ShiftU"),
ShiftV = (86, "ShiftV"),
ShiftW = (87, "ShiftW"),
ShiftX = (88, "ShiftX"),
ShiftY = (89, "ShiftY"),
ShiftZ = (90, "ShiftZ"),
LeftBracket = (91, "LeftBracket"),
Backslash = (92, "Backslash"),
RightBracket = (93, "RightBracket"),
Caret = (94, "Caret"),
Underscore = (95, "Underscore"),
GraveAccent = (96, "GraveAccent"),
A = (97, "A"),
B = (98, "B"),
C = (99, "C"),
D = (100, "D"),
E = (101, "E"),
F = (102, "F"),
G = (103, "G"),
H = (104, "H"),
I = (105, "I"),
J = (106, "J"),
K = (107, "K"),
L = (108, "L"),
M = (109, "M"),
N = (110, "N"),
O = (111, "O"),
P = (112, "P"),
Q = (113, "Q"),
R = (114, "R"),
S = (115, "S"),
T = (116, "T"),
U = (117, "U"),
V = (118, "V"),
W = (119, "W"),
X = (120, "X"),
Y = (121, "Y"),
Z = (122, "Z"),
LeftBrace = (123, "LeftBrace"),
Pipe = (124, "Pipe"),
RightBrace = (125, "RightBrace"),
Tilde = (126, "Tilde"),
Backspace = (127, "Backspace"),
# Special characters with virtual keycodes
Up = (1001, "Up"),
Down = (1002, "Down"),
Right = (1003, "Right"),
Left = (1004, "Left"),
Home = (1005, "Home"),
Insert = (1006, "Insert"),
Delete = (1007, "Delete"),
End = (1008, "End"),
PageUp = (1009, "PageUp"),
PageDown = (1010, "PageDown"),
F1 = (1011, "F1"),
F2 = (1012, "F2"),
F3 = (1013, "F3"),
F4 = (1014, "F4"),
F5 = (1015, "F5"),
F6 = (1016, "F6"),
F7 = (1017, "F7"),
F8 = (1018, "F8"),
F9 = (1019, "F9"),
F10 = (1020, "F10"),
F11 = (1021, "F11"),
F12 = (1022, "F12"),
Mouse = (5000, "Mouse")
IllwillError* = object of CatchableError
type
MouseButtonAction* {.pure.} = enum
mbaNone, mbaPressed, mbaReleased
MouseInfo* = object
x*: int ## X mouse position
y*: int ## Y mouse position
button*: MouseButton ## which button was pressed
action*: MouseButtonAction ## if button was released or pressed
ctrl*: bool ## was Ctrl down
shift*: bool ## was Shift down
scroll*: bool ## if this is a mouse scroll event
scrollDir*: ScrollDirection ## scroll direction
move*: bool ## if this is a mouse move event
MouseButton* {.pure.} = enum
mbNone, mbLeft, mbMiddle, mbRight
ScrollDirection* {.pure.} = enum
sdNone, sdUp, sdDown
var
gMouseInfo = MouseInfo()
gMouse: bool = false
proc getMouse*(): MouseInfo =
## When the library is initialised with `illwillInit(mouse=true)`, mouse
## events are captured and can be retrieved by calling this function.
##
## See `MouseInfo` for further details.
##
## Example:
##
## .. code-block::
##
## import illwill, os
##
## proc exitProc() {.noconv.} =
## illwillDeinit()
## showCursor()
## quit(0)
##
## setControlCHook(exitProc)
## illwillInit(mouse=true)
##
## var tb = newTerminalBuffer(terminalWidth(), terminalHeight())
##
## while true:
## var key = getKey()
## if key == Key.Mouse:
## echo getMouse()
## tb.display()
## sleep(10)
return gMouseInfo
{.push warning[HoleEnumConv]:off.}
func toKey(c: int): Key =
try:
result = Key(c)
except RangeDefect: # ignore unknown keycodes
result = Key.None
{.pop}
var gIllwillInitialised = false
var gFullScreen = false
var gFullRedrawNextFrame = false
when defined(windows):
import encodings, winlean
proc getConsoleMode(hConsoleHandle: Handle, dwMode: ptr DWORD): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "GetConsoleMode".}
proc setConsoleMode(hConsoleHandle: Handle, dwMode: DWORD): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
# Mouse
const
INPUT_BUFFER_LEN = 512
const
ENABLE_MOUSE_INPUT = 0x10
ENABLE_WINDOW_INPUT = 0x8
ENABLE_QUICK_EDIT_MODE = 0x40
ENABLE_EXTENDED_FLAGS = 0x80
MOUSE_EVENT = 0x0002
const
FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001
FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004
RIGHTMOST_BUTTON_PRESSED = 0x0002
const
LEFT_CTRL_PRESSED = 0x0008
RIGHT_CTRL_PRESSED = 0x0004
SHIFT_PRESSED = 0x0010
const
MOUSE_WHEELED = 0x0004
type
WCHAR = WinChar
CHAR = char
BOOL = WINBOOL
WORD = uint16
UINT = cint
SHORT = int16
# Windows console input structuress
type
KEY_EVENT_RECORD_UNION* {.bycopy, union.} = object
UnicodeChar*: WCHAR
AsciiChar*: CHAR
INPUT_RECORD_UNION* {.bycopy, union.} = object
KeyEvent*: KEY_EVENT_RECORD
MouseEvent*: MOUSE_EVENT_RECORD
WindowBufferSizeEvent*: WINDOW_BUFFER_SIZE_RECORD
MenuEvent*: MENU_EVENT_RECORD
FocusEvent*: FOCUS_EVENT_RECORD
COORD* {.bycopy.} = object
X*: SHORT
Y*: SHORT
PCOORD* = ptr COORD
FOCUS_EVENT_RECORD* {.bycopy.} = object
bSetFocus*: BOOL
MENU_EVENT_RECORD* {.bycopy.} = object
dwCommandId*: UINT
PMENU_EVENT_RECORD* = ptr MENU_EVENT_RECORD
MOUSE_EVENT_RECORD* {.bycopy.} = object
dwMousePosition*: COORD
dwButtonState*: DWORD
dwControlKeyState*: DWORD
dwEventFlags*: DWORD
WINDOW_BUFFER_SIZE_RECORD* {.bycopy.} = object
dwSize*: COORD
INPUT_RECORD* {.bycopy.} = object
EventType*: WORD
Event*: INPUT_RECORD_UNION
type
PINPUT_RECORD = ptr array[INPUT_BUFFER_LEN, INPUT_RECORD]
LPDWORD = PDWORD
proc peekConsoleInputA(hConsoleInput: HANDLE, lpBuffer: PINPUT_RECORD,
nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL
{.stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".}
const
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002
var gOldConsoleModeInput: DWORD
var gOldConsoleMode: DWORD
proc consoleInit() =
discard getConsoleMode(getStdHandle(STD_INPUT_HANDLE), gOldConsoleModeInput.addr)
if gFullScreen:
if getConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), gOldConsoleMode.addr) != 0:
var mode = gOldConsoleMode and (not ENABLE_WRAP_AT_EOL_OUTPUT)
discard setConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), mode)
else:
discard getConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), gOldConsoleMode.addr)
proc consoleDeinit() =
if gOldConsoleMode != 0:
discard setConsoleMode(getStdHandle(STD_OUTPUT_HANDLE), gOldConsoleMode)
proc getchTimeout(ms: int32): KEY_EVENT_RECORD =
let fd = getStdHandle(STD_INPUT_HANDLE)
var keyEvent = KEY_EVENT_RECORD()
var numRead: cint
while true:
case waitForSingleObject(fd, ms)
of WAIT_TIMEOUT:
keyEvent.eventType = -1
return
of WAIT_OBJECT_0:
doAssert(readConsoleInput(fd, addr(keyEvent), 1, addr(numRead)) != 0)
if numRead == 0 or keyEvent.eventType != 1 or keyEvent.bKeyDown == 0:
continue
return keyEvent
else:
doAssert(false)
proc getKeyAsync(ms: int): Key =
let event = getchTimeout(int32(ms))
if event.eventType == -1:
return Key.None
if event.uChar != 0:
return toKey((event.uChar))
else:
case event.wVirtualScanCode
of 8: return Key.Backspace
of 9: return Key.Tab
of 13: return Key.Enter
of 32: return Key.Space
of 59: return Key.F1
of 60: return Key.F2
of 61: return Key.F3
of 62: return Key.F4
of 63: return Key.F5
of 64: return Key.F6
of 65: return Key.F7
of 66: return Key.F8
of 67: return Key.F9
of 68: return Key.F10
of 71: return Key.Home
of 72: return Key.Up
of 73: return Key.PageUp
of 75: return Key.Left
of 77: return Key.Right
of 79: return Key.End
of 80: return Key.Down
of 81: return Key.PageDown
of 82: return Key.Insert
of 83: return Key.Delete
of 87: return Key.F11
of 88: return Key.F12
else: return Key.None
proc writeConsole(hConsoleOutput: HANDLE, lpBuffer: pointer,
nNumberOfCharsToWrite: DWORD,
lpNumberOfCharsWritten: ptr DWORD,
lpReserved: pointer): WINBOOL {.
stdcall, dynlib: "kernel32", importc: "WriteConsoleW".}
var hStdout = getStdHandle(STD_OUTPUT_HANDLE)
var utf16LEConverter = open(destEncoding = "utf-16", srcEncoding = "UTF-8")
proc put(s: string) =
var us = utf16LEConverter.convert(s)
var numWritten: DWORD
discard writeConsole(hStdout, pointer(us[0].addr), DWORD(s.runeLen),
numWritten.addr, nil)
else: # OS X & Linux
import posix, tables, termios
import strutils, strformat
proc consoleInit()
proc consoleDeinit()
# References:
# https://de.wikipedia.org/wiki/ANSI-Escapesequenz
# https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates
const
CSI = 0x1B.chr & 0x5B.chr
SET_BTN_EVENT_MOUSE = "1002"
SET_ANY_EVENT_MOUSE = "1003"
SET_SGR_EXT_MODE_MOUSE = "1006"
# SET_URXVT_EXT_MODE_MOUSE = "1015"
ENABLE = "h"
DISABLE = "l"
MouseTrackAny = fmt"{CSI}?{SET_BTN_EVENT_MOUSE}{ENABLE}{CSI}?{SET_ANY_EVENT_MOUSE}{ENABLE}{CSI}?{SET_SGR_EXT_MODE_MOUSE}{ENABLE}"
DisableMouseTrackAny = fmt"{CSI}?{SET_BTN_EVENT_MOUSE}{DISABLE}{CSI}?{SET_ANY_EVENT_MOUSE}{DISABLE}{CSI}?{SET_SGR_EXT_MODE_MOUSE}{DISABLE}"
KEYS_D = [Key.Up, Key.Down, Key.Right, Key.Left, Key.None, Key.End, Key.None, Key.Home]
KEYS_E = [Key.Delete, Key.End, Key.PageUp, Key.PageDown, Key.Home, Key.End]
KEYS_F = [Key.F1, Key.F2, Key.F3, Key.F4, Key.F5, Key.None, Key.F6, Key.F7, Key.F8]
KEYS_G = [Key.F9, Key.F10, Key.None, Key.F11, Key.F12]
# Adapted from:
# https://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_24.html#SEC499
proc SIGTSTP_handler(sig: cint) {.noconv.} =
signal(SIGTSTP, SIG_DFL)
# XXX why don't the below 3 lines seem to have any effect?
resetAttributes()
showCursor()
consoleDeinit()
discard posix.raise(SIGTSTP)
proc SIGCONT_handler(sig: cint) {.noconv.} =
signal(SIGCONT, SIGCONT_handler)
signal(SIGTSTP, SIGTSTP_handler)
gFullRedrawNextFrame = true
consoleInit()
hideCursor()
proc installSignalHandlers() =
signal(SIGCONT, SIGCONT_handler)
signal(SIGTSTP, SIGTSTP_handler)
proc nonblock(enabled: bool) =
var ttyState: Termios
# get the terminal state
discard tcGetAttr(STDIN_FILENO, ttyState.addr)
if enabled:
# turn off canonical mode & echo
ttyState.c_lflag = ttyState.c_lflag and not Cflag(ICANON or ECHO)
# minimum of number input read
ttyState.c_cc[VMIN] = 0.char
else:
# turn on canonical mode & echo
ttyState.c_lflag = ttyState.c_lflag or ICANON or ECHO
# set the terminal attributes.
discard tcSetAttr(STDIN_FILENO, TCSANOW, ttyState.addr)
proc kbhit(ms: int): cint =
var tv: Timeval
tv.tv_sec = Time(ms div 1000)
tv.tv_usec = 1000 * (int32(ms) mod 1000) # int32 because of macos
var fds: TFdSet
FD_ZERO(fds)
FD_SET(STDIN_FILENO, fds)
discard select(STDIN_FILENO+1, fds.addr, nil, nil, tv.addr)
return FD_ISSET(STDIN_FILENO, fds)
proc consoleInit() =
nonblock(true)
installSignalHandlers()
proc consoleDeinit() =
nonblock(false)
# surely a 100 char buffer is more than enough; the longest
# keycode sequence I've seen was 6 chars
const KeySequenceMaxLen = 100
# global keycode buffer
var keyBuf {.threadvar.}: array[KeySequenceMaxLen, int]
proc splitInputs(inp: openarray[int], max: Natural): seq[seq[int]] =
## splits the input buffer to extract mouse coordinates
var parts: seq[seq[int]] = @[]
var cur: seq[int] = @[]
for ch in inp[CSI.len+1 .. max-1]:
if ch == ord('M'):
# Button press
parts.add(cur)
gMouseInfo.action = mbaPressed
break
elif ch == ord('m'):
# Button release
parts.add(cur)
gMouseInfo.action = mbaReleased
break
elif ch != ord(';'):
cur.add(ch)
else:
parts.add(cur)
cur = @[]
return parts
proc getPos(inp: seq[int]): int =
var str = ""
for ch in inp:
str &= $(ch.chr)
result = parseInt(str)
proc fillGlobalMouseInfo(keyBuf: array[KeySequenceMaxLen, int]) =
let parts = splitInputs(keyBuf, keyBuf.len)
gMouseInfo.x = parts[1].getPos() - 1
gMouseInfo.y = parts[2].getPos() - 1
let bitset = parts[0].getPos()
gMouseInfo.ctrl = bitset.testBit(4)
gMouseInfo.shift = bitset.testBit(2)
gMouseInfo.move = bitset.testBit(5)
case ((bitset.uint8 shl 6) shr 6).int
of 0: gMouseInfo.button = MouseButton.mbLeft
of 1: gMouseInfo.button = MouseButton.mbMiddle
of 2: gMouseInfo.button = MouseButton.mbRight
else:
gMouseInfo.action = MouseButtonAction.mbaNone
# Move sends 3, but we ignore
gMouseInfo.button = MouseButton.mbNone
gMouseInfo.scroll = bitset.testBit(6)
if gMouseInfo.scroll:
# On scroll button=3 is reported, but we want no button pressed
gMouseInfo.button = MouseButton.mbNone
if bitset.testBit(0): gMouseInfo.scrollDir = ScrollDirection.sdDown
else: gMouseInfo.scrollDir = ScrollDirection.sdUp
else:
gMouseInfo.scrollDir = ScrollDirection.sdNone
proc parseStdin[T](input: T): Key =
var ch1, ch2, ch3, ch4, ch5: char
result = Key.None
if read(input, ch1.addr, 1) > 0:
case ch1
of '\e':
if read(input, ch2.addr, 1) > 0:
if ch2 == 'O' and read(input, ch3.addr, 1) > 0:
if ch3 in "ABCDFH":
result = KEYS_D[int(ch3) - int('A')]
elif ch3 in "PQRS":
result = KEYS_F[int(ch3) - int('P')]
elif ch2 == '[' and read(input, ch3.addr, 1) > 0:
if ch3 in "ABCDFH":
result = KEYS_D[int(ch3) - int('A')]
elif ch3 in "PQRS":
result = KEYS_F[int(ch3) - int('P')]
elif ch3 == '1' and read(input, ch4.addr, 1) > 0:
if ch4 == '~':
result = Key.Home
elif ch4 in "12345789" and read(input, ch5.addr, 1) > 0 and ch5 == '~':
result = KEYS_F[int(ch4) - int('1')]
elif ch3 == '2' and read(input, ch4.addr, 1) > 0:
if ch4 == '~':
result = Key.Insert
elif ch4 in "0134" and read(input, ch5.addr, 1) > 0 and ch5 == '~':
result = KEYS_G[int(ch4) - int('0')]
elif ch3 in "345678" and read(input, ch4.addr, 1) > 0 and ch4 == '~':
result = KEYS_E[int(ch3) - int('3')]
else:
discard # if cannot parse full seq it is discarded
else:
discard # if cannot parse full seq it is discarded
else:
result = Key.Escape
of '\n':
result = Key.Enter
of '\b':
result = Key.Backspace
else:
result = toKey(int(ch1))
proc getKeyAsync(ms: int): Key =
result = Key.None
if kbhit(ms) > 0:
result = parseStdin(cint(STDIN_FILENO))
template put(s: string) = stdout.write s
when defined(posix):
const
XtermColor = "xterm-color"
Xterm256Color = "xterm-256color"
proc enterFullScreen() =
## Enters full-screen mode (clears the terminal).
when defined(posix):
case getEnv("TERM"):
of XtermColor:
stdout.write "\e7\e[?47h"
of Xterm256Color:
stdout.write "\e[?1049h"
else:
eraseScreen()
else:
eraseScreen()
proc exitFullScreen() =
## Exits full-screen mode (restores the previous contents of the terminal).
when defined(posix):
case getEnv("TERM"):
of XtermColor:
stdout.write "\e[2J\e[?47l\e8"
of Xterm256Color:
stdout.write "\e[?1049l"
else:
eraseScreen()
else:
eraseScreen()
setCursorPos(0, 0)
when defined(posix):
proc enableMouse() =
stdout.write(MouseTrackAny)
stdout.flushFile()
proc disableMouse() =
stdout.write(DisableMouseTrackAny)
stdout.flushFile()
else:
proc enableMouse(hConsoleInput: Handle) =
var currentMode: DWORD
discard getConsoleMode(hConsoleInput, currentMode.addr)
discard setConsoleMode(hConsoleInput,
ENABLE_WINDOW_INPUT or ENABLE_MOUSE_INPUT or ENABLE_EXTENDED_FLAGS or
(currentMode and ENABLE_QUICK_EDIT_MODE.bitnot())
)
proc disableMouse(hConsoleInput: Handle, oldConsoleMode: DWORD) =
# TODO remove mouse option only?
discard setConsoleMode(hConsoleInput, oldConsoleMode)
proc illwillInit*(fullScreen: bool=true, mouse: bool=false) =
## Initializes the terminal and enables non-blocking keyboard input. Needs
## to be called before doing anything with the library.
##
## If `mouse` is set to `true`, mouse events are captured and can be
## retrieved with `getMouse()`.
##
## If the module is already intialised, `IllwillError` is raised.
if gIllwillInitialised:
raise newException(IllwillError, "Illwill already initialised")
gFullScreen = fullScreen
if gFullScreen: enterFullScreen()
consoleInit()
gMouse = mouse
if gMouse:
when defined(posix):
enableMouse()
else:
enableMouse(getStdHandle(STD_INPUT_HANDLE))
gIllwillInitialised = true
resetAttributes()
proc checkInit() =
if not gIllwillInitialised:
raise newException(IllwillError, "Illwill not initialised")
proc illwillDeinit*() =
## Resets the terminal to its previous state. Needs to be called before
## exiting the application.
##
## If the module is not intialised, `IllwillError` is raised.
checkInit()
if gFullScreen: exitFullScreen()
if gMouse:
when defined(posix):
disableMouse()
else:
disableMouse(getStdHandle(STD_INPUT_HANDLE), gOldConsoleModeInput)
consoleDeinit()
gIllwillInitialised = false
resetAttributes()
showCursor()
when defined(windows):
template alias(newName: untyped, call: untyped) =
template newName(): untyped = call
var gLastMouseInfo = MouseInfo()
proc fillGlobalMouseInfo(inputRecord: INPUT_RECORD) =
alias(me, inputRecord.Event.MouseEvent)
gMouseInfo.x = me.dwMousePosition.X
gMouseInfo.y = me.dwMousePosition.Y
case me.dwButtonState
of FROM_LEFT_1ST_BUTTON_PRESSED: gMouseInfo.button = mbLeft
of FROM_LEFT_2ND_BUTTON_PRESSED: gMouseInfo.button = mbMiddle
of RIGHTMOST_BUTTON_PRESSED: gMouseInfo.button = mbRight
else: gMouseInfo.button = mbNone
if gMouseInfo.button != mbNone:
gMouseInfo.action = MouseButtonAction.mbaPressed
elif gMouseInfo.button == mbNone and gLastMouseInfo.button != mbNone:
gMouseInfo.action = MouseButtonAction.mbaReleased
else:
gMouseInfo.action = MouseButtonAction.mbaNone
if gLastMouseInfo.x != gMouseInfo.x or gLastMouseInfo.y != gMouseInfo.y:
gMouseInfo.move = true
else:
gMouseInfo.move = false
if bitand(me.dwEventFlags, MOUSE_WHEELED) == MOUSE_WHEELED:
gMouseInfo.scroll = true
if me.dwButtonState.testBit(31):
gMouseInfo.scrollDir = ScrollDirection.sdDown
else:
gMouseInfo.scrollDir = ScrollDirection.sdUp
else:
gMouseInfo.scroll = false
gMouseInfo.scrollDir = ScrollDirection.sdNone
gMouseInfo.ctrl = (
bitand(me.dwControlKeyState, LEFT_CTRL_PRESSED) == LEFT_CTRL_PRESSED or
bitand(me.dwControlKeyState, RIGHT_CTRL_PRESSED) == RIGHT_CTRL_PRESSED
)
gMouseInfo.shift = bitand(me.dwControlKeyState, SHIFT_PRESSED) == SHIFT_PRESSED
gLastMouseInfo = gMouseInfo
proc hasMouseInput(): bool =
var buffer: array[INPUT_BUFFER_LEN, INPUT_RECORD]
var numberOfEventsRead: DWORD
var toRead: int = 0
discard peekConsoleInputA(getStdHandle(STD_INPUT_HANDLE), buffer.addr,
buffer.len.DWORD, numberOfEventsRead.addr)
if numberOfEventsRead == 0: return false
for inputRecord in buffer[0..<numberOfEventsRead.int]:
toRead.inc()
if inputRecord.EventType == MOUSE_EVENT:
break
if toRead == 0: return false
discard readConsoleInput(getStdHandle(STD_INPUT_HANDLE), buffer.addr,
toRead.DWORD, numberOfEventsRead.addr)
if buffer[numberOfEventsRead - 1].EventType == MOUSE_EVENT:
fillGlobalMouseInfo(buffer[numberOfEventsRead - 1])
return true
else:
return false
proc getKey*(): Key =
## Reads the next keystroke in a non-blocking manner. If there are no
## keypress events in the buffer, `Key.None` is returned.
##
## If a mouse event was captured, `Key.Mouse` is returned. Call `getMouse()`
## to get the details about the event.
##
## If the module is not intialised, `IllwillError` is raised.
checkInit()
result = getKeyAsync(0)
when defined(windows):
if result == Key.None:
if hasMouseInput():
return Key.Mouse
proc getKeyWithTimeout*(ms = 1000): Key =
## Reads the next keystroke with a timeout. If there were no keypress events
## in the specified `ms` period, `Key.None` is returned.
##
## If a mouse event was captured, `Key.Mouse` is returned. Call `getMouse()`
## to get the details about the event.
##
## If the module is not intialised, `IllwillError` is raised.
checkInit()
result = getKeyAsync(ms)
when defined(windows):
if result == Key.None:
if hasMouseInput():
return Key.Mouse
type
TerminalChar* = object
## Represents a character in the terminal buffer, including color and
## style information.
##
## If `forceWrite` is set to `true`, the character is always output even
## when double buffering is enabled (this is a hack to achieve better
## continuity of horizontal lines when using UTF-8 box drawing symbols in
## the Windows Console).
ch*: Rune
fg*: ForegroundColor
bg*: BackgroundColor
style*: set[Style]
forceWrite*: bool
TerminalBuffer* = ref object
## A virtual terminal buffer of a fixed width and height. It remembers the
## current color and style settings and the current cursor position.
##
## Write to the terminal buffer with `TerminalBuffer.write()` or access
## the character buffer directly with the index operators.
##
## Example:
##
## .. code-block::
## import illwill, unicode
##
## # Initialise the console in non-fullscreen mode
## illwillInit(fullscreen=false)
##
## # Create a new terminal buffer
## var tb = newTerminalBuffer(terminalWidth(), terminalHeight())
##
## # Write the character "X" at position (5,5) then read it back
## tb[5,5] = TerminalChar(ch: "X".runeAt(0), fg: fgYellow, bg: bgNone, style: {})
## let ch = tb[5,5]
##
## # Write "foo" at position (10,10) in bright red
## tb.setForegroundColor(fgRed, bright=true)
## tb.setCursorPos(10, 10)
## tb.write("foo")
##
## # Write "bar" at position (15,12) in bright red, without changing
## # the current cursor position
## tb.write(15, 12, "bar")
##
## tb.write(0, 20, "Normal ", fgYellow, "ESC", fgWhite,
## " or ", fgYellow, "Q", fgWhite, " to quit")
##
## # Output the contents of the buffer to the terminal
## tb.display()
##
## # Clean up
## illwillDeinit()
##
width: int
height: int
buf: seq[TerminalChar]
currBg: BackgroundColor
currFg: ForegroundColor
currStyle: set[Style]
currX: Natural
currY: Natural
proc `[]=`*(tb: var TerminalBuffer, x, y: Natural, ch: TerminalChar) =
## Index operator to write a character into the terminal buffer at the
## specified location. Does nothing if the location is outside of the
## extents of the terminal buffer.
if x < tb.width and y < tb.height:
tb.buf[tb.width * y + x] = ch
proc `[]`*(tb: TerminalBuffer, x, y: Natural): TerminalChar =
## Index operator to read a character from the terminal buffer at the
## specified location. Returns nil if the location is outside of the extents
## of the terminal buffer.
if x < tb.width and y < tb.height:
result = tb.buf[tb.width * y + x]
proc fill*(tb: var TerminalBuffer, x1, y1, x2, y2: Natural, ch: string = " ") =
## Fills a rectangular area with the `ch` character using the current text
## attributes. The rectangle is clipped to the extends of the terminal
## buffer and the call can never fail.
if x1 < tb.width and y1 < tb.height:
let
c = TerminalChar(ch: ch.runeAt(0), fg: tb.currFg, bg: tb.currBg,
style: tb.currStyle)
xe = min(x2, tb.width-1)
ye = min(y2, tb.height-1)
for y in y1..ye:
for x in x1..xe:
tb[x, y] = c
proc clear*(tb: var TerminalBuffer, ch: string = " ") =
## Clears the contents of the terminal buffer with the `ch` character using
## the `fgNone` and `bgNone` attributes.
tb.fill(0, 0, tb.width-1, tb.height-1, ch)
proc initTerminalBuffer(tb: var TerminalBuffer, width, height: Natural) =
## Initializes a new terminal buffer object of a fixed `width` and `height`.
tb.width = width
tb.height = height
newSeq(tb.buf, width * height)
tb.currBg = bgNone
tb.currFg = fgNone
tb.currStyle = {}
proc newTerminalBuffer*(width, height: Natural): TerminalBuffer =
## Creates a new terminal buffer of a fixed `width` and `height`.
var tb = new TerminalBuffer
tb.initTerminalBuffer(width, height)
tb.clear()
result = tb