-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathprim_tty_nif.c
More file actions
1331 lines (1172 loc) · 42.9 KB
/
Copy pathprim_tty_nif.c
File metadata and controls
1331 lines (1172 loc) · 42.9 KB
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
/*
* %CopyrightBegin%
*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Ericsson AB 2022-2026. All Rights Reserved.
* Copyright Ericsson 2015-2024. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/*
* Purpose: NIF library for interacting with the tty
*
*/
#define STATIC_ERLANG_NIF 1
#ifndef WANT_NONBLOCKING
#define WANT_NONBLOCKING
#endif
#include "config.h"
#include "sys.h"
#include "erl_nif.h"
#include "erl_driver.h"
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <wchar.h>
#include <stdio.h>
#include <signal.h>
#include <locale.h>
#if defined(HAVE_TERMCAP)
#include <termios.h>
#if defined(HAVE_NCURSES_CURSES_H)
#include <ncurses/curses.h>
#include <ncurses/term.h>
#elif defined(HAVE_CURSES_H) && defined(HAVE_TERM_H)
#include <curses.h>
#include <term.h>
#else
/* We detected TERMCAP support, but could not find the correct headers to include */
#undef HAVE_TERMCAP
#endif
#endif
#ifndef __WIN32__
#include <unistd.h>
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#if defined IOV_MAX
#define MAXIOV IOV_MAX
#elif defined UIO_MAXIOV
#define MAXIOV UIO_MAXIOV
#else
#define MAXIOV 16
#endif
#if !defined(HAVE_SETLOCALE) || !defined(HAVE_NL_LANGINFO) || !defined(HAVE_LANGINFO_H)
#define PRIMITIVE_UTF8_CHECK 1
#else
#include <langinfo.h>
#endif
#ifdef VALGRIND
# include <valgrind/memcheck.h>
#endif
#define DEF_HEIGHT 24
#define DEF_WIDTH 80
enum TTYState {
unavailable,
disabled,
enabled
};
typedef struct {
#ifdef __WIN32__
HANDLE ofd;
HANDLE ifd;
DWORD dwOriginalOutMode;
DWORD dwOriginalInMode;
DWORD dwOutMode;
DWORD dwInMode;
#else
int ofd; /* stdout */
int ifd; /* stdin */
#endif
ErlNifPid self;
ErlNifPid reader;
enum TTYState tty; /* if the tty is initialized */
#ifdef HAVE_TERMCAP
struct termios tty_smode;
struct termios tty_rmode;
#endif
} TTYResource;
// #define HARD_DEBUG
#ifdef HARD_DEBUG
static FILE *logFile = NULL;
#define debug(fmt, ...) do { if (logFile) { erts_fprintf(logFile, fmt, __VA_ARGS__); fflush(logFile); } } while(0)
#else
#define debug(...) do { } while(0)
#endif
static ErlNifResourceType *tty_rt;
/* The NIFs: */
static ERL_NIF_TERM isatty_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_create_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_init_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_is_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM setlocale_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_select_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_write_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_encoding_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_read_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM isprint_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM wcwidth_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM wcswidth_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM sizeof_wchar_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_window_size_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_setupterm_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_tigetnum_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_tigetflag_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_tinfo_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_tigetstr_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM tty_tputs_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ErlNifFunc nif_funcs[] = {
{"isatty", 1, isatty_nif},
{"tty_create", 1, tty_create_nif},
{"tty_init", 2, tty_init_nif},
{"setlocale", 1, setlocale_nif},
{"tty_is_open", 2, tty_is_open},
{"tty_select", 2, tty_select_nif},
{"tty_window_size", 1, tty_window_size_nif},
{"write_nif", 2, tty_write_nif, ERL_NIF_DIRTY_JOB_IO_BOUND},
{"tty_encoding", 1, tty_encoding_nif},
{"read_nif", 3, tty_read_nif, ERL_NIF_DIRTY_JOB_IO_BOUND},
{"isprint", 1, isprint_nif},
{"wcwidth", 1, wcwidth_nif},
{"wcswidth", 1, wcswidth_nif},
{"sizeof_wchar", 0, sizeof_wchar_nif},
{"setupterm_nif", 0, tty_setupterm_nif},
{"tigetnum_nif", 1, tty_tigetnum_nif},
{"tigetflag_nif", 1, tty_tigetflag_nif},
{"tinfo_nif", 0, tty_tinfo_nif},
{"tigetstr_nif", 1, tty_tigetstr_nif},
{"tputs_nif", 2, tty_tputs_nif}
};
/* NIF interface declarations */
static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info);
static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info);
static void unload(ErlNifEnv* env, void* priv_data);
ERL_NIF_INIT(prim_tty, nif_funcs, load, NULL, upgrade, unload)
#define ATOMS \
ATOM_DECL(canon); \
ATOM_DECL(echo); \
ATOM_DECL(ebadf); \
ATOM_DECL(undefined); \
ATOM_DECL(error); \
ATOM_DECL(true); \
ATOM_DECL(stdout); \
ATOM_DECL(ok); \
ATOM_DECL(input); \
ATOM_DECL(false); \
ATOM_DECL(stdin); \
ATOM_DECL(stdout); \
ATOM_DECL(stderr); \
ATOM_DECL(select); \
ATOM_DECL(raw); \
ATOM_DECL(sig);
#define ATOM_DECL(A) static ERL_NIF_TERM atom_##A
ATOMS
#undef ATOM_DECL
static ERL_NIF_TERM make_error(ErlNifEnv *env, ERL_NIF_TERM reason) {
return enif_make_tuple2(env, atom_error, reason);
}
static ERL_NIF_TERM make_enotsup(ErlNifEnv *env) {
return make_error(env, enif_make_atom(env, "enotsup"));
}
static ERL_NIF_TERM make_errno(ErlNifEnv *env) {
#ifdef __WIN32__
return enif_make_atom(env, last_error());
#else
return enif_make_atom(env, erl_errno_id(errno));
#endif
}
static ERL_NIF_TERM make_errno_error(ErlNifEnv *env, const char *function) {
return make_error(
env, enif_make_tuple2(
env, enif_make_atom(env, function), make_errno(env)));
}
static int tty_get_fd(ErlNifEnv *env, ERL_NIF_TERM atom, int *fd) {
if (enif_is_identical(atom, atom_stdout)) {
*fd = fileno(stdout);
} else if (enif_is_identical(atom, atom_stdin)) {
*fd = fileno(stdin);
} else if (enif_is_identical(atom, atom_stderr)) {
*fd = fileno(stderr);
} else {
return 0;
}
return 1;
}
#ifdef __WIN32__
static HANDLE tty_get_handle(ErlNifEnv *env, ERL_NIF_TERM atom) {
HANDLE handle = INVALID_HANDLE_VALUE;
int fd;
if (tty_get_fd(env, atom, &fd)) {
switch (fd) {
case 0: handle = GetStdHandle(STD_INPUT_HANDLE); break;
case 1: handle = GetStdHandle(STD_OUTPUT_HANDLE); break;
case 2: handle = GetStdHandle(STD_ERROR_HANDLE); break;
}
}
return handle;
}
#endif
static ERL_NIF_TERM isatty_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef __WIN32__
HANDLE handle = tty_get_handle(env, argv[0]);
if (handle == INVALID_HANDLE_VALUE)
return atom_ebadf;
switch (GetFileType(handle)) {
case FILE_TYPE_CHAR: return atom_true;
case FILE_TYPE_PIPE:
case FILE_TYPE_DISK: return atom_false;
default: return atom_ebadf;
}
#else
int fd;
if (tty_get_fd(env, argv[0], &fd)) {
if (isatty(fd)) {
return atom_true;
} else if (errno == EINVAL || errno == ENOTTY) {
return atom_false;
}
else {
return atom_ebadf;
}
}
#endif
return enif_make_badarg(env);
}
static ERL_NIF_TERM tty_encoding_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef __WIN32__
TTYResource *tty;
if (!enif_get_resource(env, argv[0], tty_rt, (void **)&tty))
return enif_make_badarg(env);
if (GetFileType(tty->ifd) == FILE_TYPE_CHAR)
return enif_make_tuple2(env, enif_make_atom(env, "utf16"),
enif_make_atom(env, "little"));
#endif
return enif_make_atom(env, "utf8");
}
static ERL_NIF_TERM isprint_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
int i;
if (enif_get_int(env, argv[0], &i)) {
ASSERT(i >= 0 && i < 256);
return isprint((char)i) ? atom_true : atom_false;
}
return enif_make_badarg(env);
}
static ERL_NIF_TERM wcwidth_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
int i;
if (enif_get_int(env, argv[0], &i)) {
#ifndef __WIN32__
int width;
ASSERT(i > 0 && i < (1l << 21));
width = wcwidth((wchar_t)i);
if (width == -1) {
return make_error(env, enif_make_atom(env, "not_printable"));
}
return enif_make_int(env, width);
#else
return make_enotsup(env);
#endif
}
return enif_make_badarg(env);
}
static ERL_NIF_TERM wcswidth_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
ErlNifBinary bin;
if (enif_inspect_iolist_as_binary(env, argv[0], &bin)) {
wchar_t *chars = (wchar_t*)bin.data;
int width;
#ifdef DEBUG
for (int i = 0; i < bin.size / sizeof(wchar_t); i++) {
ASSERT(chars[i] >= 0 && chars[i] < (1l << 21));
}
#endif
#ifndef __WIN32__
width = wcswidth(chars, bin.size / sizeof(wchar_t));
#else
width = bin.size / sizeof(wchar_t);
#endif
if (width == -1) {
return make_error(env, enif_make_atom(env, "not_printable"));
}
return enif_make_tuple2(env, atom_ok, enif_make_int(env, width));
}
return enif_make_badarg(env);
}
static ERL_NIF_TERM sizeof_wchar_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
return enif_make_int(env, sizeof(wchar_t));
}
static ERL_NIF_TERM tty_write_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
ERL_NIF_TERM head = argv[1], tail;
ErlNifIOQueue *q = NULL;
ErlNifIOVec vec, *iovec = &vec;
SysIOVec *iov;
int iovcnt;
TTYResource *tty;
ssize_t res = 0;
size_t size;
if (!enif_get_resource(env, argv[0], tty_rt, (void **)&tty))
return enif_make_badarg(env);
while (!enif_is_identical(head, enif_make_list(env, 0))) {
if (!enif_inspect_iovec(env, MAXIOV, head, &tail, &iovec))
return enif_make_badarg(env);
head = tail;
iov = iovec->iov;
size = iovec->size;
iovcnt = iovec->iovcnt;
do {
#ifndef __WIN32__
do {
res = writev(tty->ofd, iov, iovcnt);
} while(res < 0 && (errno == EINTR || errno == EAGAIN));
#else
res = 0;
for (int i = 0; i < iovcnt; i++) {
ssize_t written;
#ifdef HARD_DEBUG
for (int y = 0; y < iov[i].iov_len; y++)
debug("Write %u\r\n",iov[i].iov_base[y]);
#endif
BOOL r = WriteFile(tty->ofd, iov[i].iov_base,
iov[i].iov_len, &written, NULL);
if (!r) {
res = -1;
break;
}
res += written;
#ifdef DEBUG
/* In debug we simulate a partial write in order to test
the code that handles it */
break;
#endif
}
#endif
if (res < 0) {
if (q) enif_ioq_destroy(q);
return make_error(env, make_errno(env));
}
if (res != size) {
if (!q) {
q = enif_ioq_create(ERL_NIF_IOQ_NORMAL);
enif_ioq_enqv(q, iovec, 0);
}
}
if (q) {
enif_ioq_deq(q, res, &size);
if (size == 0) {
enif_ioq_destroy(q);
q = NULL;
} else {
iov = enif_ioq_peek(q, &iovcnt);
}
}
} while(q);
};
return atom_ok;
}
static ERL_NIF_TERM tty_read_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
TTYResource *tty;
ErlNifBinary bin;
ERL_NIF_TERM res_term;
Uint64 n;
ssize_t res = 0;
#ifdef __WIN32__
HANDLE select_event;
#else
int select_event;
#endif
ASSERT(argc == 3);
if (!enif_get_resource(env, argv[0], tty_rt, (void **)&tty))
return enif_make_badarg(env);
if (!enif_get_uint64(env, argv[2], &n))
return enif_make_badarg(env);
n = n > 1024 ? 1024 : n;
select_event = tty->ifd;
debug("tty_read_nif(%T, %T, %T)\r\n",argv[0],argv[1],argv[2]);
#ifdef __WIN32__
/**
* We have three different read scenarios we need to deal with
* using different approaches.
*
* ### New Shell / Raw NoShell
*
* Here characters need to be delivered as they are typed and we
* also need to handle terminal resize events. So we use ReadConsoleInputW
* to read.
*
* ### Input is a terminal, but there is noshell, or old shell
*
* Here we should operate in "line mode", that is characters should only
* be delivered when the user hits enter. Here we used to use OVERLAPPED ReadFile,
* but that caused unicode to not work, so instead we use ReadFile.
*
* This call will block a single dirty io schedulers until the user hits Enter.
*
* ### Input is an anonymous pipe
*
* Since ReadConsoleInputW and OVERLAPPED ReadFile do not work on pipes
* we use blocking ReadFile calls to read from pipes. On pipes the ReadFile
* call will not block until a full line is complete, so this is safe to do.
*
**/
if (GetFileType(tty->ifd) == FILE_TYPE_CHAR && tty->tty == enabled) {
/* Input is a terminal and we are in "new shell"/"raw" mode */
ssize_t inputs_read, num_characters = 0;
wchar_t *characters = NULL;
INPUT_RECORD inputs[128];
n = MIN(n, sizeof(inputs) / sizeof(inputs[0]));
ASSERT(tty->tty == enabled);
if (!ReadConsoleInputW(tty->ifd, inputs, n, &inputs_read)) {
return make_errno_error(env, "ReadConsoleInput");
}
/**
* Reading keyevents using ReadConsoleInput is a bit fragile as
* different consoles and different input modes cause events to
* be triggered in different ways. I've so far identified four
* different input methods that work slightly differently and
* two classes of consoles that also work slightly differently.
*
* The input methods are:
* - Normal key presses
* - Microsoft IME
* - Pasting into console
* - Using Alt+ modifiers
*
* ### Normal key presses
*
* When typing normally both key down and up events are sent with
* the typed character. If typing a Unicode character (for instance if
* you are using a keyboard with Cyrillic layout), that character also
* is sent as both key up and key down. This behavior is the same on all
* consoles.
*
* ### Microsoft IME
*
* When typing Japanese, Chinese and many other languages it is common to
* use a "Input Method Editor". Basically what it does is that if you type
* "sushi" using the Japanese IME it convert that to "すし". All characters
* typed using IME end up as only keydown events on cmd.exe and powershell,
* while in Windows Terminal and Alacritty both keydown and keyup events
* are sent.
*
* ### Pasting into console
*
* When text pasting into the console, any ascii text pasted ends up as both
* keydown and keyup events. Any non-ascii text pasted seem to be sent using
* a keydown event with UnicodeChar set to 0 and then immediately followed by a
* keyup event with the non-ascii text.
*
* ### Using Alt+ modifiers
*
* A very old way of inputting Unicode characters on Windows is to press
* the left alt key and then some numbers on the number pad. For instance
* you can type Alt+1 to write a ☺. When doing this first a keydown
* with 0 is sent and then some events later a keyup with the character
* is sent. This behavior seems to only work on cmd.exe and powershell.
*
*
* So to summarize:
* - Normal presses -- Always keydown and keyup events
* - IME -- Always keydown, sometimes keyup
* - Pasting -- Always keydown=0 directly followed by keyup=value
* - Alt+ -- Sometimes keydown=0 followed eventually by keyup=value
*
* So in order to read characters we should always read the keydown event,
* except when it is 0, then we should read the adjacent keyup event.
* This covers all modes and consoles except Alt+. If we want Alt+ to work
* we probably have to use PeekConsoleInput to make sure the correct events
* are available and inspect the state of the key event somehow.
**/
for (int i = 0; i < inputs_read; i++) {
if (inputs[i].EventType == KEY_EVENT) {
if (inputs[i].Event.KeyEvent.bKeyDown) {
if (inputs[i].Event.KeyEvent.uChar.UnicodeChar != 0) {
num_characters++;
} else if (i + 1 < inputs_read && !inputs[i+1].Event.KeyEvent.bKeyDown) {
num_characters++;
}
}
}
}
enif_alloc_binary(num_characters * sizeof(wchar_t), &bin);
characters = (wchar_t*)bin.data;
for (int i = 0; i < inputs_read; i++) {
switch (inputs[i].EventType)
{
case KEY_EVENT:
if (inputs[i].Event.KeyEvent.bKeyDown) {
if (inputs[i].Event.KeyEvent.uChar.UnicodeChar != 0) {
debug("Read %u\r\n",inputs[i].Event.KeyEvent.uChar.UnicodeChar);
characters[res++] = inputs[i].Event.KeyEvent.uChar.UnicodeChar;
} else if (i + 1 < inputs_read && !inputs[i+1].Event.KeyEvent.bKeyDown) {
debug("Read %u\r\n",inputs[i+1].Event.KeyEvent.uChar.UnicodeChar);
characters[res++] = inputs[i+1].Event.KeyEvent.uChar.UnicodeChar;
}
}
break;
case WINDOW_BUFFER_SIZE_EVENT:
enif_send(env, &tty->self, NULL,
enif_make_tuple2(env, argv[1],
enif_make_tuple2(env,
enif_make_atom(env, "signal"),
enif_make_atom(env, "resize"))));
break;
case MOUSE_EVENT:
/* We don't do anything with the mouse event */
break;
case MENU_EVENT:
case FOCUS_EVENT:
/* Should be ignored according to
https://docs.microsoft.com/en-us/windows/console/input-record-str */
break;
default:
fprintf(stderr,"Unknown event: %d\r\n", inputs[i].EventType);
break;
}
}
res *= sizeof(wchar_t);
} else {
/* Input is not a terminal or we are in "cooked" mode */
DWORD bytesTransferred;
BOOL readRes;
const char *errorFunction;
if (GetFileType(tty->ifd) == FILE_TYPE_CHAR) {
/* This ReadConsoleW call may hang until Enter is pressed.
* This will block one dirty io schedulers, but that should be ok as it will
* only happen if the application wants to read data, i.e. it is reasonable to
* expect and enter to be hit "soon".
*
* NOTE: I've tried various things to try to figure out if ReadFile/ReadConsole
* will block or not, but one of the crazy thing with ReadFile/ReadConsole is
* that you need to call it before the characters on the terminal are echoed,
* so we need this call to be blocking. What we could do is move the read to another
* thread so that we don't consume a dirty io scheduler, but I've opted to keep
* it simple and not do that.
*/
enif_alloc_binary(n * sizeof(wchar_t), &bin);
readRes = ReadConsoleW(tty->ifd, bin.data, n, &bytesTransferred, NULL);
bytesTransferred *= sizeof(wchar_t);
errorFunction = "ReadConsoleW";
}
else {
enif_alloc_binary(n, &bin);
readRes = ReadFile(tty->ifd, bin.data, bin.size, &bytesTransferred, NULL);
errorFunction = "ReadFile";
}
if (readRes) {
res = bytesTransferred;
if (res == 0) {
enif_release_binary(&bin);
return make_error(env, enif_make_atom(env, "closed"));
}
} else {
DWORD error = GetLastError();
enif_release_binary(&bin);
if (error == ERROR_BROKEN_PIPE)
return make_error(env, enif_make_atom(env, "closed"));
return make_errno_error(env, errorFunction);
}
}
#else
enif_alloc_binary(n, &bin);
res = read(tty->ifd, bin.data, bin.size);
if (res < 0) {
if (errno != EAGAIN && errno != EINTR) {
enif_release_binary(&bin);
return make_errno_error(env, "read");
}
res = 0;
} else if (res == 0) {
enif_release_binary(&bin);
return make_error(env, enif_make_atom(env, "closed"));
}
#endif
debug("select on %d\r\n",select_event);
enif_select(env, select_event, ERL_NIF_SELECT_READ, tty, NULL, argv[1]);
if (res == bin.size) {
res_term = enif_make_binary(env, &bin);
} else if (res < bin.size / 2) {
unsigned char *buff = enif_make_new_binary(env, res, &res_term);
if (res > 0) {
memcpy(buff, bin.data, res);
}
enif_release_binary(&bin);
} else {
enif_realloc_binary(&bin, res);
res_term = enif_make_binary(env, &bin);
}
return enif_make_tuple2(env, atom_ok, res_term);
}
/* Poll if stdin/stdout/stderr are still open. */
static ERL_NIF_TERM tty_is_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
TTYResource *tty;
#ifdef __WIN32__
HANDLE handle;
#else
int fd;
#endif
if (!enif_get_resource(env, argv[0], tty_rt, (void **)&tty))
return enif_make_badarg(env);
#ifdef __WIN32__
handle = tty_get_handle(env, argv[1]);
if (handle != INVALID_HANDLE_VALUE) {
DWORD bytesAvailable = 0;
switch (GetFileType(handle)) {
case FILE_TYPE_CHAR: {
DWORD eventsAvailable;
if (!GetNumberOfConsoleInputEvents(handle, &eventsAvailable)) {
return atom_false;
}
return atom_true;
}
case FILE_TYPE_DISK: {
return atom_true;
}
default: {
DWORD bytesAvailable = 0;
// Check the state of the pipe
if (!PeekNamedPipe(handle, NULL, 0, NULL, &bytesAvailable, NULL)) {
DWORD err = GetLastError();
// If the error is ERROR_BROKEN_PIPE, it means stdin has been closed
if (err == ERROR_BROKEN_PIPE) {
return atom_false;
}
else {
return make_errno_error(env, "PeekNamedPipe");
}
}
return atom_true;
}
}
}
#else
if (tty_get_fd(env, argv[1], &fd)) {
struct pollfd fds[1];
int ret;
fds[0].fd = fd;
fds[0].events = POLLHUP;
fds[0].revents = 0;
ret = poll(fds, 1, 0);
if (ret < 0) {
return make_errno_error(env, __FUNCTION__);
} else if (ret == 0) {
return atom_true;
} else if (ret == 1 && fds[0].revents & POLLHUP) {
return atom_false;
}
}
#endif
return enif_make_badarg(env);
}
static ERL_NIF_TERM setlocale_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef __WIN32__
TTYResource *tty;
if (!enif_get_resource(env, argv[0], tty_rt, (void **)&tty))
return enif_make_badarg(env);
if (tty->dwOutMode)
{
if (!SetConsoleOutputCP(CP_UTF8)) {
return make_errno_error(env, "SetConsoleOutputCP");
}
}
return atom_true;
#elif defined(PRIMITIVE_UTF8_CHECK)
setlocale(LC_CTYPE, ""); /* Set international environment,
ignore result */
return enif_make_atom(env, "primitive");
#else
char *l = setlocale(LC_CTYPE, ""); /* Set international environment */
if (l != NULL) {
if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)
return atom_true;
}
return atom_false;
#endif
}
#ifdef HAVE_TERMCAP
static TERMINAL *saved_term = NULL;
#endif
static ERL_NIF_TERM tty_setupterm_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
int errret;
if (setupterm(NULL, -1, &errret) < 0) {
return make_errno_error(env, "setupterm");
}
if (saved_term) {
del_curterm(saved_term);
}
saved_term = cur_term;
return atom_ok;
#else
return make_enotsup(env);
#endif
}
#ifdef HAVE_TERMCAP
static ERL_NIF_TERM tty_tinfo_make_map(ErlNifEnv* env,
NCURSES_CONST char * const* names,
NCURSES_CONST char * const* codes,
NCURSES_CONST char * const* fnames) {
ERL_NIF_TERM res = enif_make_list(env, 0);
ERL_NIF_TERM ks[3] = {
enif_make_atom(env, "name"),
enif_make_atom(env, "code"),
enif_make_atom(env, "full_name")
};
for (int i = 0; names[i] && codes[i] && fnames[i]; i++) {
ERL_NIF_TERM map;
ERL_NIF_TERM vs[3] = {
enif_make_string(env, names[i], ERL_NIF_LATIN1),
enif_make_string(env, codes[i], ERL_NIF_LATIN1),
enif_make_string(env, fnames[i], ERL_NIF_LATIN1)
};
enif_make_map_from_arrays(env, ks, vs, 3, &map);
res = enif_make_list_cell(env, map, res);
}
return res;
}
#endif
static ERL_NIF_TERM tty_tinfo_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
ERL_NIF_TERM ks[3] = {
enif_make_atom(env, "bool"),
enif_make_atom(env, "num"),
enif_make_atom(env, "str")
};
ERL_NIF_TERM vs[3] = {
tty_tinfo_make_map(env, (NCURSES_CONST char * const*)boolnames, (NCURSES_CONST char * const*)boolcodes, (NCURSES_CONST char * const*)boolfnames),
tty_tinfo_make_map(env, (NCURSES_CONST char * const*)numnames, (NCURSES_CONST char * const*)numcodes, (NCURSES_CONST char * const*)numfnames),
tty_tinfo_make_map(env, (NCURSES_CONST char * const*)strnames, (NCURSES_CONST char * const*)strcodes, (NCURSES_CONST char * const*)strfnames)
};
ERL_NIF_TERM res;
enif_make_map_from_arrays(env, ks, vs, 3, &res);
return res;
#else
return make_enotsup(env);
#endif
}
static ERL_NIF_TERM tty_tigetnum_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
ErlNifBinary CAP;
if (!enif_inspect_iolist_as_binary(env, argv[0], &CAP))
return enif_make_badarg(env);
return enif_make_int(env, tgetnum((char*)CAP.data));
#else
return make_enotsup(env);
#endif
}
static ERL_NIF_TERM tty_tigetflag_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
ErlNifBinary CAP;
if (!enif_inspect_iolist_as_binary(env, argv[0], &CAP))
return enif_make_badarg(env);
if (tgetflag((char*)CAP.data))
return atom_true;
return atom_false;
#else
return make_enotsup(env);
#endif
}
static ERL_NIF_TERM tty_tigetstr_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
ErlNifBinary CAP, ret;
char *str;
if (!enif_inspect_iolist_as_binary(env, argv[0], &CAP))
return enif_make_badarg(env);
str = tigetstr((char*)CAP.data);
if (!str) return atom_false; /* Not supported by terminal */
if (str == (char*)-1) return enif_make_badarg(env); /* Invalid capability */
enif_alloc_binary(strlen(str), &ret);
memcpy(ret.data, str, strlen(str));
return enif_make_tuple2(
env, atom_ok, enif_make_binary(env, &ret));
#else
return make_enotsup(env);
#endif
}
static int library_refc = 0;
#ifdef HAVE_TERMCAP
static ErlNifMutex *tputs_mutex;
static int tputs_buffer_index;
static int tputs_buffer_size;
#ifdef DEBUG
static unsigned char static_tputs_buffer[2];
#else
static unsigned char static_tputs_buffer[1024];
#endif
static unsigned char *tputs_buffer;
#if defined(__sun) && defined(__SVR4) /* Solaris */
static int tty_puts_putc(char c) {
#else
static int tty_puts_putc(int c) {
#endif
/* If we have a terminal that does a lot of padding, then it might be
that a lot of text is generated here. Those types of terminals are
ancient and most likely not in use anymore, but just to be safe we
handle it by dynamically resizing the buffer. */
if (tputs_buffer_index == tputs_buffer_size) {
if (tputs_buffer == static_tputs_buffer) {
tputs_buffer = enif_alloc(tputs_buffer_size * 2);
memcpy(tputs_buffer, static_tputs_buffer, tputs_buffer_size);
tputs_buffer_size *= 2;
} else {
tputs_buffer = enif_realloc(tputs_buffer, tputs_buffer_size * 2);
tputs_buffer_size *= 2;
}
}
tputs_buffer[tputs_buffer_index++] = (unsigned char)c;
return 0;
}
#endif
static ERL_NIF_TERM tty_tputs_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
#ifdef HAVE_TERMCAP
ErlNifBinary cap;
ERL_NIF_TERM ret;
char *ent;
unsigned char *buff;
long params[9] = { 0 };
int slot = 0;
if (!enif_inspect_iolist_as_binary(env, argv[0], &cap))
return enif_make_badarg(env);
{
ERL_NIF_TERM head, tail = argv[1];
while(enif_get_list_cell(env, tail, &head, &tail)) {
if (!enif_get_long(env, head, params + slot)) {
return enif_make_badarg(env);
}
slot++;
}
if (!enif_is_empty_list(env, tail)) {
enif_make_badarg(env);
}
}
/* Neither tparm nor tputs are thread safe.. */
enif_mutex_lock(tputs_mutex);
/* If the capability has arguments, we call tparm */
if (slot) {
/* The https://linux.die.net/man/3/tparm specifies that although tparm uses
a vararg prototype on Linux, to be portable we should always call it with
9 arguments as some implementation have a static prototype.
*/
ent = tparm((char*)cap.data, params[0], params[1], params[2], params[3],
params[4], params[5], params[6], params[7], params[8]);
if (!ent) {
enif_mutex_unlock(tputs_mutex);
return make_errno_error(env, "tparm");
}
} else {
ent = (char*)cap.data;
}
tputs_buffer_index = 0;
tputs_buffer_size = sizeof(static_tputs_buffer);
tputs_buffer = static_tputs_buffer;
(void)tputs(ent, 1, tty_puts_putc); /* tputs only fails if ent is null,
which is cannot be. */
buff = enif_make_new_binary(env, tputs_buffer_index, &ret);
memcpy(buff, tputs_buffer, tputs_buffer_index);
if (tputs_buffer != static_tputs_buffer) {
enif_free(tputs_buffer);
}
enif_mutex_unlock(tputs_mutex);
return enif_make_tuple2(env, atom_ok, ret);
#else
return make_enotsup(env);
#endif
}
static ERL_NIF_TERM tty_create_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
TTYResource *tty = enif_alloc_resource(tty_rt, sizeof(TTYResource));
ERL_NIF_TERM tty_term;
memset(tty, 0, sizeof(*tty));
#ifdef HARD_DEBUG
logFile = fopen("tty.log","w+");
#endif
tty->tty = unavailable;
#ifndef __WIN32__