-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
tty.c
2333 lines (1929 loc) Β· 72.9 KB
/
tty.c
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
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <assert.h>
#include <io.h>
#include <string.h>
#include <stdlib.h>
#if defined(_MSC_VER) && _MSC_VER < 1600
# include "uv/stdint-msvc2008.h"
#else
# include <stdint.h>
#endif
#ifndef COMMON_LVB_REVERSE_VIDEO
# define COMMON_LVB_REVERSE_VIDEO 0x4000
#endif
#include "uv.h"
#include "internal.h"
#include "handle-inl.h"
#include "stream-inl.h"
#include "req-inl.h"
#ifndef InterlockedOr
# define InterlockedOr _InterlockedOr
#endif
#define UNICODE_REPLACEMENT_CHARACTER (0xfffd)
#define ANSI_NORMAL 0x00
#define ANSI_ESCAPE_SEEN 0x02
#define ANSI_CSI 0x04
#define ANSI_ST_CONTROL 0x08
#define ANSI_IGNORE 0x10
#define ANSI_IN_ARG 0x20
#define ANSI_IN_STRING 0x40
#define ANSI_BACKSLASH_SEEN 0x80
#define MAX_INPUT_BUFFER_LENGTH 8192
#define MAX_CONSOLE_CHAR 8192
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info);
static void uv_tty_update_virtual_window(CONSOLE_SCREEN_BUFFER_INFO* info);
static int uv__cancel_read_console(uv_tty_t* handle);
/* Null uv_buf_t */
static const uv_buf_t uv_null_buf_ = { 0, NULL };
enum uv__read_console_status_e {
NOT_STARTED,
IN_PROGRESS,
TRAP_REQUESTED,
COMPLETED
};
static volatile LONG uv__read_console_status = NOT_STARTED;
static volatile LONG uv__restore_screen_state;
static CONSOLE_SCREEN_BUFFER_INFO uv__saved_screen_state;
/*
* The console virtual window.
*
* Normally cursor movement in windows is relative to the console screen buffer,
* e.g. the application is allowed to overwrite the 'history'. This is very
* inconvenient, it makes absolute cursor movement pretty useless. There is
* also the concept of 'client rect' which is defined by the actual size of
* the console window and the scroll position of the screen buffer, but it's
* very volatile because it changes when the user scrolls.
*
* To make cursor movement behave sensibly we define a virtual window to which
* cursor movement is confined. The virtual window is always as wide as the
* console screen buffer, but it's height is defined by the size of the
* console window. The top of the virtual window aligns with the position
* of the caret when the first stdout/err handle is created, unless that would
* mean that it would extend beyond the bottom of the screen buffer - in that
* that case it's located as far down as possible.
*
* When the user writes a long text or many newlines, such that the output
* reaches beyond the bottom of the virtual window, the virtual window is
* shifted downwards, but not resized.
*
* Since all tty i/o happens on the same console, this window is shared
* between all stdout/stderr handles.
*/
static int uv_tty_virtual_offset = -1;
static int uv_tty_virtual_height = -1;
static int uv_tty_virtual_width = -1;
/* The console window size
* We keep this separate from uv_tty_virtual_*. We use those values to only
* handle signalling SIGWINCH
*/
static HANDLE uv__tty_console_handle = INVALID_HANDLE_VALUE;
static int uv__tty_console_height = -1;
static int uv__tty_console_width = -1;
static DWORD WINAPI uv__tty_console_resize_message_loop_thread(void* param);
static void CALLBACK uv__tty_console_resize_event(HWINEVENTHOOK hWinEventHook,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD dwEventThread,
DWORD dwmsEventTime);
/* We use a semaphore rather than a mutex or critical section because in some
cases (uv__cancel_read_console) we need take the lock in the main thread and
release it in another thread. Using a semaphore ensures that in such
scenario the main thread will still block when trying to acquire the lock. */
static uv_sem_t uv_tty_output_lock;
static WORD uv_tty_default_text_attributes =
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
static char uv_tty_default_fg_color = 7;
static char uv_tty_default_bg_color = 0;
static char uv_tty_default_fg_bright = 0;
static char uv_tty_default_bg_bright = 0;
static char uv_tty_default_inverse = 0;
typedef enum {
UV_SUPPORTED,
UV_UNCHECKED,
UV_UNSUPPORTED
} uv_vtermstate_t;
/* Determine whether or not ANSI support is enabled. */
static uv_vtermstate_t uv__vterm_state = UV_UNCHECKED;
static void uv__determine_vterm_state(HANDLE handle);
void uv_console_init(void) {
if (uv_sem_init(&uv_tty_output_lock, 1))
abort();
uv__tty_console_handle = CreateFileW(L"CONOUT$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
0);
if (uv__tty_console_handle != NULL) {
QueueUserWorkItem(uv__tty_console_resize_message_loop_thread,
NULL,
WT_EXECUTELONGFUNCTION);
}
}
int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) {
HANDLE handle;
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
uv__once_init();
handle = (HANDLE) uv__get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return UV_EBADF;
if (fd <= 2) {
/* In order to avoid closing a stdio file descriptor 0-2, duplicate the
* underlying OS handle and forget about the original fd.
* We could also opt to use the original OS handle and just never close it,
* but then there would be no reliable way to cancel pending read operations
* upon close.
*/
if (!DuplicateHandle(INVALID_HANDLE_VALUE,
handle,
INVALID_HANDLE_VALUE,
&handle,
0,
FALSE,
DUPLICATE_SAME_ACCESS))
return uv_translate_sys_error(GetLastError());
fd = -1;
}
if (!readable) {
/* Obtain the screen buffer info with the output handle. */
if (!GetConsoleScreenBufferInfo(handle, &screen_buffer_info)) {
return uv_translate_sys_error(GetLastError());
}
/* Obtain the tty_output_lock because the virtual window state is shared
* between all uv_tty_t handles. */
uv_sem_wait(&uv_tty_output_lock);
if (uv__vterm_state == UV_UNCHECKED)
uv__determine_vterm_state(handle);
/* Remember the original console text attributes. */
uv_tty_capture_initial_style(&screen_buffer_info);
uv_tty_update_virtual_window(&screen_buffer_info);
uv_sem_post(&uv_tty_output_lock);
}
uv_stream_init(loop, (uv_stream_t*) tty, UV_TTY);
uv_connection_init((uv_stream_t*) tty);
tty->handle = handle;
tty->u.fd = fd;
tty->reqs_pending = 0;
tty->flags |= UV_HANDLE_BOUND;
if (readable) {
/* Initialize TTY input specific fields. */
tty->flags |= UV_HANDLE_TTY_READABLE | UV_HANDLE_READABLE;
/* TODO: remove me in v2.x. */
tty->tty.rd.unused_ = NULL;
tty->tty.rd.read_line_buffer = uv_null_buf_;
tty->tty.rd.read_raw_wait = NULL;
/* Init keycode-to-vt100 mapper state. */
tty->tty.rd.last_key_len = 0;
tty->tty.rd.last_key_offset = 0;
tty->tty.rd.last_utf16_high_surrogate = 0;
memset(&tty->tty.rd.last_input_record, 0, sizeof tty->tty.rd.last_input_record);
} else {
/* TTY output specific fields. */
tty->flags |= UV_HANDLE_WRITABLE;
/* Init utf8-to-utf16 conversion state. */
tty->tty.wr.utf8_bytes_left = 0;
tty->tty.wr.utf8_codepoint = 0;
/* Initialize eol conversion state */
tty->tty.wr.previous_eol = 0;
/* Init ANSI parser state. */
tty->tty.wr.ansi_parser_state = ANSI_NORMAL;
}
return 0;
}
/* Set the default console text attributes based on how the console was
* configured when libuv started.
*/
static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info) {
static int style_captured = 0;
/* Only do this once.
Assumption: Caller has acquired uv_tty_output_lock. */
if (style_captured)
return;
/* Save raw win32 attributes. */
uv_tty_default_text_attributes = info->wAttributes;
/* Convert black text on black background to use white text. */
if (uv_tty_default_text_attributes == 0)
uv_tty_default_text_attributes = 7;
/* Convert Win32 attributes to ANSI colors. */
uv_tty_default_fg_color = 0;
uv_tty_default_bg_color = 0;
uv_tty_default_fg_bright = 0;
uv_tty_default_bg_bright = 0;
uv_tty_default_inverse = 0;
if (uv_tty_default_text_attributes & FOREGROUND_RED)
uv_tty_default_fg_color |= 1;
if (uv_tty_default_text_attributes & FOREGROUND_GREEN)
uv_tty_default_fg_color |= 2;
if (uv_tty_default_text_attributes & FOREGROUND_BLUE)
uv_tty_default_fg_color |= 4;
if (uv_tty_default_text_attributes & BACKGROUND_RED)
uv_tty_default_bg_color |= 1;
if (uv_tty_default_text_attributes & BACKGROUND_GREEN)
uv_tty_default_bg_color |= 2;
if (uv_tty_default_text_attributes & BACKGROUND_BLUE)
uv_tty_default_bg_color |= 4;
if (uv_tty_default_text_attributes & FOREGROUND_INTENSITY)
uv_tty_default_fg_bright = 1;
if (uv_tty_default_text_attributes & BACKGROUND_INTENSITY)
uv_tty_default_bg_bright = 1;
if (uv_tty_default_text_attributes & COMMON_LVB_REVERSE_VIDEO)
uv_tty_default_inverse = 1;
style_captured = 1;
}
int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
DWORD flags;
unsigned char was_reading;
uv_alloc_cb alloc_cb;
uv_read_cb read_cb;
int err;
if (!(tty->flags & UV_HANDLE_TTY_READABLE)) {
return UV_EINVAL;
}
if (!!mode == !!(tty->flags & UV_HANDLE_TTY_RAW)) {
return 0;
}
switch (mode) {
case UV_TTY_MODE_NORMAL:
flags = ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
break;
case UV_TTY_MODE_RAW:
flags = ENABLE_WINDOW_INPUT;
break;
case UV_TTY_MODE_IO:
return UV_ENOTSUP;
default:
return UV_EINVAL;
}
/* If currently reading, stop, and restart reading. */
if (tty->flags & UV_HANDLE_READING) {
was_reading = 1;
alloc_cb = tty->alloc_cb;
read_cb = tty->read_cb;
err = uv_tty_read_stop(tty);
if (err) {
return uv_translate_sys_error(err);
}
} else {
was_reading = 0;
}
uv_sem_wait(&uv_tty_output_lock);
if (!SetConsoleMode(tty->handle, flags)) {
err = uv_translate_sys_error(GetLastError());
uv_sem_post(&uv_tty_output_lock);
return err;
}
uv_sem_post(&uv_tty_output_lock);
/* Update flag. */
tty->flags &= ~UV_HANDLE_TTY_RAW;
tty->flags |= mode ? UV_HANDLE_TTY_RAW : 0;
/* If we just stopped reading, restart. */
if (was_reading) {
err = uv_tty_read_start(tty, alloc_cb, read_cb);
if (err) {
return uv_translate_sys_error(err);
}
}
return 0;
}
int uv_is_tty(uv_file file) {
DWORD result;
return GetConsoleMode((HANDLE) _get_osfhandle(file), &result) != 0;
}
int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(tty->handle, &info)) {
return uv_translate_sys_error(GetLastError());
}
uv_sem_wait(&uv_tty_output_lock);
uv_tty_update_virtual_window(&info);
uv_sem_post(&uv_tty_output_lock);
*width = uv_tty_virtual_width;
*height = uv_tty_virtual_height;
return 0;
}
static void CALLBACK uv_tty_post_raw_read(void* data, BOOLEAN didTimeout) {
uv_loop_t* loop;
uv_tty_t* handle;
uv_req_t* req;
assert(data);
assert(!didTimeout);
req = (uv_req_t*) data;
handle = (uv_tty_t*) req->data;
loop = handle->loop;
UnregisterWait(handle->tty.rd.read_raw_wait);
handle->tty.rd.read_raw_wait = NULL;
SET_REQ_SUCCESS(req);
POST_COMPLETION_FOR_REQ(loop, req);
}
static void uv_tty_queue_read_raw(uv_loop_t* loop, uv_tty_t* handle) {
uv_read_t* req;
BOOL r;
assert(handle->flags & UV_HANDLE_READING);
assert(!(handle->flags & UV_HANDLE_READ_PENDING));
assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE);
handle->tty.rd.read_line_buffer = uv_null_buf_;
req = &handle->read_req;
memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
r = RegisterWaitForSingleObject(&handle->tty.rd.read_raw_wait,
handle->handle,
uv_tty_post_raw_read,
(void*) req,
INFINITE,
WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
if (!r) {
handle->tty.rd.read_raw_wait = NULL;
SET_REQ_ERROR(req, GetLastError());
uv_insert_pending_req(loop, (uv_req_t*)req);
}
handle->flags |= UV_HANDLE_READ_PENDING;
handle->reqs_pending++;
}
static DWORD CALLBACK uv_tty_line_read_thread(void* data) {
uv_loop_t* loop;
uv_tty_t* handle;
uv_req_t* req;
DWORD bytes, read_bytes;
WCHAR utf16[MAX_INPUT_BUFFER_LENGTH / 3];
DWORD chars, read_chars;
LONG status;
COORD pos;
BOOL read_console_success;
assert(data);
req = (uv_req_t*) data;
handle = (uv_tty_t*) req->data;
loop = handle->loop;
assert(handle->tty.rd.read_line_buffer.base != NULL);
assert(handle->tty.rd.read_line_buffer.len > 0);
/* ReadConsole can't handle big buffers. */
if (handle->tty.rd.read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) {
bytes = handle->tty.rd.read_line_buffer.len;
} else {
bytes = MAX_INPUT_BUFFER_LENGTH;
}
/* At last, unicode! One utf-16 codeunit never takes more than 3 utf-8
* codeunits to encode. */
chars = bytes / 3;
status = InterlockedExchange(&uv__read_console_status, IN_PROGRESS);
if (status == TRAP_REQUESTED) {
SET_REQ_SUCCESS(req);
req->u.io.overlapped.InternalHigh = 0;
POST_COMPLETION_FOR_REQ(loop, req);
return 0;
}
read_console_success = ReadConsoleW(handle->handle,
(void*) utf16,
chars,
&read_chars,
NULL);
if (read_console_success) {
read_bytes = WideCharToMultiByte(CP_UTF8,
0,
utf16,
read_chars,
handle->tty.rd.read_line_buffer.base,
bytes,
NULL,
NULL);
SET_REQ_SUCCESS(req);
req->u.io.overlapped.InternalHigh = read_bytes;
} else {
SET_REQ_ERROR(req, GetLastError());
}
status = InterlockedExchange(&uv__read_console_status, COMPLETED);
if (status == TRAP_REQUESTED) {
/* If we canceled the read by sending a VK_RETURN event, restore the
screen state to undo the visual effect of the VK_RETURN */
if (read_console_success && InterlockedOr(&uv__restore_screen_state, 0)) {
HANDLE active_screen_buffer;
active_screen_buffer = CreateFileA("conout$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (active_screen_buffer != INVALID_HANDLE_VALUE) {
pos = uv__saved_screen_state.dwCursorPosition;
/* If the cursor was at the bottom line of the screen buffer, the
VK_RETURN would have caused the buffer contents to scroll up by one
line. The right position to reset the cursor to is therefore one line
higher */
if (pos.Y == uv__saved_screen_state.dwSize.Y - 1)
pos.Y--;
SetConsoleCursorPosition(active_screen_buffer, pos);
CloseHandle(active_screen_buffer);
}
}
uv_sem_post(&uv_tty_output_lock);
}
POST_COMPLETION_FOR_REQ(loop, req);
return 0;
}
static void uv_tty_queue_read_line(uv_loop_t* loop, uv_tty_t* handle) {
uv_read_t* req;
BOOL r;
assert(handle->flags & UV_HANDLE_READING);
assert(!(handle->flags & UV_HANDLE_READ_PENDING));
assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE);
req = &handle->read_req;
memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));
handle->tty.rd.read_line_buffer = uv_buf_init(NULL, 0);
handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->tty.rd.read_line_buffer);
if (handle->tty.rd.read_line_buffer.base == NULL ||
handle->tty.rd.read_line_buffer.len == 0) {
handle->read_cb((uv_stream_t*) handle,
UV_ENOBUFS,
&handle->tty.rd.read_line_buffer);
return;
}
assert(handle->tty.rd.read_line_buffer.base != NULL);
/* Reset flags No locking is required since there cannot be a line read
in progress. We are also relying on the memory barrier provided by
QueueUserWorkItem*/
uv__restore_screen_state = FALSE;
uv__read_console_status = NOT_STARTED;
r = QueueUserWorkItem(uv_tty_line_read_thread,
(void*) req,
WT_EXECUTELONGFUNCTION);
if (!r) {
SET_REQ_ERROR(req, GetLastError());
uv_insert_pending_req(loop, (uv_req_t*)req);
}
handle->flags |= UV_HANDLE_READ_PENDING;
handle->reqs_pending++;
}
static void uv_tty_queue_read(uv_loop_t* loop, uv_tty_t* handle) {
if (handle->flags & UV_HANDLE_TTY_RAW) {
uv_tty_queue_read_raw(loop, handle);
} else {
uv_tty_queue_read_line(loop, handle);
}
}
static const char* get_vt100_fn_key(DWORD code, char shift, char ctrl,
size_t* len) {
#define VK_CASE(vk, normal_str, shift_str, ctrl_str, shift_ctrl_str) \
case (vk): \
if (shift && ctrl) { \
*len = sizeof shift_ctrl_str; \
return "\033" shift_ctrl_str; \
} else if (shift) { \
*len = sizeof shift_str ; \
return "\033" shift_str; \
} else if (ctrl) { \
*len = sizeof ctrl_str; \
return "\033" ctrl_str; \
} else { \
*len = sizeof normal_str; \
return "\033" normal_str; \
}
switch (code) {
/* These mappings are the same as Cygwin's. Unmodified and alt-modified
* keypad keys comply with linux console, modifiers comply with xterm
* modifier usage. F1. f12 and shift-f1. f10 comply with linux console, f6.
* f12 with and without modifiers comply with rxvt. */
VK_CASE(VK_INSERT, "[2~", "[2;2~", "[2;5~", "[2;6~")
VK_CASE(VK_END, "[4~", "[4;2~", "[4;5~", "[4;6~")
VK_CASE(VK_DOWN, "[B", "[1;2B", "[1;5B", "[1;6B")
VK_CASE(VK_NEXT, "[6~", "[6;2~", "[6;5~", "[6;6~")
VK_CASE(VK_LEFT, "[D", "[1;2D", "[1;5D", "[1;6D")
VK_CASE(VK_CLEAR, "[G", "[1;2G", "[1;5G", "[1;6G")
VK_CASE(VK_RIGHT, "[C", "[1;2C", "[1;5C", "[1;6C")
VK_CASE(VK_UP, "[A", "[1;2A", "[1;5A", "[1;6A")
VK_CASE(VK_HOME, "[1~", "[1;2~", "[1;5~", "[1;6~")
VK_CASE(VK_PRIOR, "[5~", "[5;2~", "[5;5~", "[5;6~")
VK_CASE(VK_DELETE, "[3~", "[3;2~", "[3;5~", "[3;6~")
VK_CASE(VK_NUMPAD0, "[2~", "[2;2~", "[2;5~", "[2;6~")
VK_CASE(VK_NUMPAD1, "[4~", "[4;2~", "[4;5~", "[4;6~")
VK_CASE(VK_NUMPAD2, "[B", "[1;2B", "[1;5B", "[1;6B")
VK_CASE(VK_NUMPAD3, "[6~", "[6;2~", "[6;5~", "[6;6~")
VK_CASE(VK_NUMPAD4, "[D", "[1;2D", "[1;5D", "[1;6D")
VK_CASE(VK_NUMPAD5, "[G", "[1;2G", "[1;5G", "[1;6G")
VK_CASE(VK_NUMPAD6, "[C", "[1;2C", "[1;5C", "[1;6C")
VK_CASE(VK_NUMPAD7, "[A", "[1;2A", "[1;5A", "[1;6A")
VK_CASE(VK_NUMPAD8, "[1~", "[1;2~", "[1;5~", "[1;6~")
VK_CASE(VK_NUMPAD9, "[5~", "[5;2~", "[5;5~", "[5;6~")
VK_CASE(VK_DECIMAL, "[3~", "[3;2~", "[3;5~", "[3;6~")
VK_CASE(VK_F1, "[[A", "[23~", "[11^", "[23^" )
VK_CASE(VK_F2, "[[B", "[24~", "[12^", "[24^" )
VK_CASE(VK_F3, "[[C", "[25~", "[13^", "[25^" )
VK_CASE(VK_F4, "[[D", "[26~", "[14^", "[26^" )
VK_CASE(VK_F5, "[[E", "[28~", "[15^", "[28^" )
VK_CASE(VK_F6, "[17~", "[29~", "[17^", "[29^" )
VK_CASE(VK_F7, "[18~", "[31~", "[18^", "[31^" )
VK_CASE(VK_F8, "[19~", "[32~", "[19^", "[32^" )
VK_CASE(VK_F9, "[20~", "[33~", "[20^", "[33^" )
VK_CASE(VK_F10, "[21~", "[34~", "[21^", "[34^" )
VK_CASE(VK_F11, "[23~", "[23$", "[23^", "[23@" )
VK_CASE(VK_F12, "[24~", "[24$", "[24^", "[24@" )
default:
*len = 0;
return NULL;
}
#undef VK_CASE
}
void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle,
uv_req_t* req) {
/* Shortcut for handle->tty.rd.last_input_record.Event.KeyEvent. */
#define KEV handle->tty.rd.last_input_record.Event.KeyEvent
DWORD records_left, records_read;
uv_buf_t buf;
off_t buf_used;
assert(handle->type == UV_TTY);
assert(handle->flags & UV_HANDLE_TTY_READABLE);
handle->flags &= ~UV_HANDLE_READ_PENDING;
if (!(handle->flags & UV_HANDLE_READING) ||
!(handle->flags & UV_HANDLE_TTY_RAW)) {
goto out;
}
if (!REQ_SUCCESS(req)) {
/* An error occurred while waiting for the event. */
if ((handle->flags & UV_HANDLE_READING)) {
handle->flags &= ~UV_HANDLE_READING;
handle->read_cb((uv_stream_t*)handle,
uv_translate_sys_error(GET_REQ_ERROR(req)),
&uv_null_buf_);
}
goto out;
}
/* Fetch the number of events */
if (!GetNumberOfConsoleInputEvents(handle->handle, &records_left)) {
handle->flags &= ~UV_HANDLE_READING;
DECREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb((uv_stream_t*)handle,
uv_translate_sys_error(GetLastError()),
&uv_null_buf_);
goto out;
}
/* Windows sends a lot of events that we're not interested in, so buf will be
* allocated on demand, when there's actually something to emit. */
buf = uv_null_buf_;
buf_used = 0;
while ((records_left > 0 || handle->tty.rd.last_key_len > 0) &&
(handle->flags & UV_HANDLE_READING)) {
if (handle->tty.rd.last_key_len == 0) {
/* Read the next input record */
if (!ReadConsoleInputW(handle->handle,
&handle->tty.rd.last_input_record,
1,
&records_read)) {
handle->flags &= ~UV_HANDLE_READING;
DECREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb((uv_stream_t*) handle,
uv_translate_sys_error(GetLastError()),
&buf);
goto out;
}
records_left--;
/* Ignore other events that are not key events. */
if (handle->tty.rd.last_input_record.EventType != KEY_EVENT) {
continue;
}
/* Ignore keyup events, unless the left alt key was held and a valid
* unicode character was emitted. */
if (!KEV.bKeyDown && !(((KEV.dwControlKeyState & LEFT_ALT_PRESSED) ||
KEV.wVirtualKeyCode==VK_MENU) && KEV.uChar.UnicodeChar != 0)) {
continue;
}
/* Ignore keypresses to numpad number keys if the left alt is held
* because the user is composing a character, or windows simulating this.
*/
if ((KEV.dwControlKeyState & LEFT_ALT_PRESSED) &&
!(KEV.dwControlKeyState & ENHANCED_KEY) &&
(KEV.wVirtualKeyCode == VK_INSERT ||
KEV.wVirtualKeyCode == VK_END ||
KEV.wVirtualKeyCode == VK_DOWN ||
KEV.wVirtualKeyCode == VK_NEXT ||
KEV.wVirtualKeyCode == VK_LEFT ||
KEV.wVirtualKeyCode == VK_CLEAR ||
KEV.wVirtualKeyCode == VK_RIGHT ||
KEV.wVirtualKeyCode == VK_HOME ||
KEV.wVirtualKeyCode == VK_UP ||
KEV.wVirtualKeyCode == VK_PRIOR ||
KEV.wVirtualKeyCode == VK_NUMPAD0 ||
KEV.wVirtualKeyCode == VK_NUMPAD1 ||
KEV.wVirtualKeyCode == VK_NUMPAD2 ||
KEV.wVirtualKeyCode == VK_NUMPAD3 ||
KEV.wVirtualKeyCode == VK_NUMPAD4 ||
KEV.wVirtualKeyCode == VK_NUMPAD5 ||
KEV.wVirtualKeyCode == VK_NUMPAD6 ||
KEV.wVirtualKeyCode == VK_NUMPAD7 ||
KEV.wVirtualKeyCode == VK_NUMPAD8 ||
KEV.wVirtualKeyCode == VK_NUMPAD9)) {
continue;
}
if (KEV.uChar.UnicodeChar != 0) {
int prefix_len, char_len;
/* Character key pressed */
if (KEV.uChar.UnicodeChar >= 0xD800 &&
KEV.uChar.UnicodeChar < 0xDC00) {
/* UTF-16 high surrogate */
handle->tty.rd.last_utf16_high_surrogate = KEV.uChar.UnicodeChar;
continue;
}
/* Prefix with \u033 if alt was held, but alt was not used as part a
* compose sequence. */
if ((KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
&& !(KEV.dwControlKeyState & (LEFT_CTRL_PRESSED |
RIGHT_CTRL_PRESSED)) && KEV.bKeyDown) {
handle->tty.rd.last_key[0] = '\033';
prefix_len = 1;
} else {
prefix_len = 0;
}
if (KEV.uChar.UnicodeChar >= 0xDC00 &&
KEV.uChar.UnicodeChar < 0xE000) {
/* UTF-16 surrogate pair */
WCHAR utf16_buffer[2] = { handle->tty.rd.last_utf16_high_surrogate,
KEV.uChar.UnicodeChar};
char_len = WideCharToMultiByte(CP_UTF8,
0,
utf16_buffer,
2,
&handle->tty.rd.last_key[prefix_len],
sizeof handle->tty.rd.last_key,
NULL,
NULL);
} else {
/* Single UTF-16 character */
char_len = WideCharToMultiByte(CP_UTF8,
0,
&KEV.uChar.UnicodeChar,
1,
&handle->tty.rd.last_key[prefix_len],
sizeof handle->tty.rd.last_key,
NULL,
NULL);
}
/* Whatever happened, the last character wasn't a high surrogate. */
handle->tty.rd.last_utf16_high_surrogate = 0;
/* If the utf16 character(s) couldn't be converted something must be
* wrong. */
if (!char_len) {
handle->flags &= ~UV_HANDLE_READING;
DECREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb((uv_stream_t*) handle,
uv_translate_sys_error(GetLastError()),
&buf);
goto out;
}
handle->tty.rd.last_key_len = (unsigned char) (prefix_len + char_len);
handle->tty.rd.last_key_offset = 0;
continue;
} else {
/* Function key pressed */
const char* vt100;
size_t prefix_len, vt100_len;
vt100 = get_vt100_fn_key(KEV.wVirtualKeyCode,
!!(KEV.dwControlKeyState & SHIFT_PRESSED),
!!(KEV.dwControlKeyState & (
LEFT_CTRL_PRESSED |
RIGHT_CTRL_PRESSED)),
&vt100_len);
/* If we were unable to map to a vt100 sequence, just ignore. */
if (!vt100) {
continue;
}
/* Prefix with \x033 when the alt key was held. */
if (KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) {
handle->tty.rd.last_key[0] = '\033';
prefix_len = 1;
} else {
prefix_len = 0;
}
/* Copy the vt100 sequence to the handle buffer. */
assert(prefix_len + vt100_len < sizeof handle->tty.rd.last_key);
memcpy(&handle->tty.rd.last_key[prefix_len], vt100, vt100_len);
handle->tty.rd.last_key_len = (unsigned char) (prefix_len + vt100_len);
handle->tty.rd.last_key_offset = 0;
continue;
}
} else {
/* Copy any bytes left from the last keypress to the user buffer. */
if (handle->tty.rd.last_key_offset < handle->tty.rd.last_key_len) {
/* Allocate a buffer if needed */
if (buf_used == 0) {
buf = uv_buf_init(NULL, 0);
handle->alloc_cb((uv_handle_t*) handle, 1024, &buf);
if (buf.base == NULL || buf.len == 0) {
handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &buf);
goto out;
}
assert(buf.base != NULL);
}
buf.base[buf_used++] = handle->tty.rd.last_key[handle->tty.rd.last_key_offset++];
/* If the buffer is full, emit it */
if ((size_t) buf_used == buf.len) {
handle->read_cb((uv_stream_t*) handle, buf_used, &buf);
buf = uv_null_buf_;
buf_used = 0;
}
continue;
}
/* Apply dwRepeat from the last input record. */
if (--KEV.wRepeatCount > 0) {
handle->tty.rd.last_key_offset = 0;
continue;
}
handle->tty.rd.last_key_len = 0;
continue;
}
}
/* Send the buffer back to the user */
if (buf_used > 0) {
handle->read_cb((uv_stream_t*) handle, buf_used, &buf);
}
out:
/* Wait for more input events. */
if ((handle->flags & UV_HANDLE_READING) &&
!(handle->flags & UV_HANDLE_READ_PENDING)) {
uv_tty_queue_read(loop, handle);
}
DECREASE_PENDING_REQ_COUNT(handle);
#undef KEV
}
void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle,
uv_req_t* req) {
uv_buf_t buf;
assert(handle->type == UV_TTY);
assert(handle->flags & UV_HANDLE_TTY_READABLE);
buf = handle->tty.rd.read_line_buffer;
handle->flags &= ~UV_HANDLE_READ_PENDING;
handle->tty.rd.read_line_buffer = uv_null_buf_;
if (!REQ_SUCCESS(req)) {
/* Read was not successful */
if (handle->flags & UV_HANDLE_READING) {
/* Real error */
handle->flags &= ~UV_HANDLE_READING;
DECREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb((uv_stream_t*) handle,
uv_translate_sys_error(GET_REQ_ERROR(req)),
&buf);
} else {
/* The read was cancelled, or whatever we don't care */
handle->read_cb((uv_stream_t*) handle, 0, &buf);
}
} else {
if (!(handle->flags & UV_HANDLE_CANCELLATION_PENDING)) {
/* Read successful. TODO: read unicode, convert to utf-8 */
DWORD bytes = req->u.io.overlapped.InternalHigh;
handle->read_cb((uv_stream_t*) handle, bytes, &buf);
} else {
handle->flags &= ~UV_HANDLE_CANCELLATION_PENDING;
handle->read_cb((uv_stream_t*) handle, 0, &buf);
}
}
/* Wait for more input events. */
if ((handle->flags & UV_HANDLE_READING) &&
!(handle->flags & UV_HANDLE_READ_PENDING)) {
uv_tty_queue_read(loop, handle);
}
DECREASE_PENDING_REQ_COUNT(handle);
}
void uv_process_tty_read_req(uv_loop_t* loop, uv_tty_t* handle,
uv_req_t* req) {
assert(handle->type == UV_TTY);
assert(handle->flags & UV_HANDLE_TTY_READABLE);
/* If the read_line_buffer member is zero, it must have been an raw read.
* Otherwise it was a line-buffered read. FIXME: This is quite obscure. Use a
* flag or something. */
if (handle->tty.rd.read_line_buffer.len == 0) {
uv_process_tty_read_raw_req(loop, handle, req);
} else {
uv_process_tty_read_line_req(loop, handle, req);
}
}
int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb,
uv_read_cb read_cb) {
uv_loop_t* loop = handle->loop;
if (!(handle->flags & UV_HANDLE_TTY_READABLE)) {
return ERROR_INVALID_PARAMETER;
}
handle->flags |= UV_HANDLE_READING;
INCREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb = read_cb;
handle->alloc_cb = alloc_cb;