forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terminal.d
9666 lines (8232 loc) · 283 KB
/
terminal.d
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
// for optional dependency
// for VT on Windows P s = 1 8 → Report the size of the text area in characters as CSI 8 ; height ; width t
// could be used to have the TE volunteer the size
// FIXME: the resume signal needs to be handled to set the terminal back in proper mode.
/++
Module for interacting with the user's terminal, including color output, cursor manipulation, and full-featured real-time mouse and keyboard input. Also includes high-level convenience methods, like [Terminal.getline], which gives the user a line editor with history, completion, etc. See the [#examples].
The main interface for this module is the Terminal struct, which
encapsulates the output functions and line-buffered input of the terminal, and
RealTimeConsoleInput, which gives real time input.
Creating an instance of these structs will perform console initialization. When the struct
goes out of scope, any changes in console settings will be automatically reverted and pending
output is flushed. Do not create a global Terminal, as this will skip the destructor. Also do
not create an instance inside a class or array, as again the destructor will be nondeterministic.
You should create the object as a local inside main (or wherever else will encapsulate its whole
usage lifetime), then pass borrowed pointers to it if needed somewhere else. This ensures the
construction and destruction is run in a timely manner.
$(PITFALL
Output is NOT flushed on \n! Output is buffered until:
$(LIST
* Terminal's destructor is run
* You request input from the terminal object
* You call `terminal.flush()`
)
If you want to see output immediately, always call `terminal.flush()`
after writing.
)
Note: on Posix, it traps SIGINT and translates it into an input event. You should
keep your event loop moving and keep an eye open for this to exit cleanly; simply break
your event loop upon receiving a UserInterruptionEvent. (Without
the signal handler, ctrl+c can leave your terminal in a bizarre state.)
As a user, if you have to forcibly kill your program and the event doesn't work, there's still ctrl+\
On old Mac Terminal btw, a lot of hacks are needed and mouse support doesn't work on older versions.
Most functions work now with newer Mac OS versions though.
Future_Roadmap:
$(LIST
* The CharacterEvent and NonCharacterKeyEvent types will be removed. Instead, use KeyboardEvent
on new programs.
* The ScrollbackBuffer will be expanded to be easier to use to partition your screen. It might even
handle input events of some sort. Its API may change.
* getline I want to be really easy to use both for code and end users. It will need multi-line support
eventually.
* I might add an expandable event loop and base level widget classes. This may be Linux-specific in places and may overlap with similar functionality in simpledisplay.d. If I can pull it off without a third module, I want them to be compatible with each other too so the two modules can be combined easily. (Currently, they are both compatible with my eventloop.d and can be easily combined through it, but that is a third module.)
* More advanced terminal features as functions, where available, like cursor changing and full-color functions.
* More documentation.
)
WHAT I WON'T DO:
$(LIST
* support everything under the sun. If it isn't default-installed on an OS I or significant number of other people
might actually use, and isn't written by me, I don't really care about it. This means the only supported terminals are:
$(LIST
* xterm (and decently xterm compatible emulators like Konsole)
* Windows console
* rxvt (to a lesser extent)
* Linux console
* My terminal emulator family of applications https://github.com/adamdruppe/terminal-emulator
)
Anything else is cool if it does work, but I don't want to go out of my way for it.
* Use other libraries, unless strictly optional. terminal.d is a stand-alone module by default and
always will be.
* Do a full TUI widget set. I might do some basics and lay a little groundwork, but a full TUI
is outside the scope of this module (unless I can do it really small.)
)
History:
On December 29, 2020 the structs and their destructors got more protection against in-GC finalization errors and duplicate executions.
This should not affect your code.
+/
module arsd.terminal;
// FIXME: needs to support VT output on Windows too in certain situations
// detect VT on windows by trying to set the flag. if this succeeds, ask it for caps. if this replies with my code we good to do extended output.
/++
$(H3 Get Line)
This example will demonstrate the high-level [Terminal.getline] interface.
The user will be able to type a line and navigate around it with cursor keys and even the mouse on some systems, as well as perform editing as they expect (e.g. the backspace and delete keys work normally) until they press enter. Then, the final line will be returned to your program, which the example will simply print back to the user.
+/
unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
string line = terminal.getline();
terminal.writeln("You wrote: ", line);
// new on October 11, 2021: you can change the echo char
// for password masking now. Also pass `0` there to get unix-style
// total silence.
string pwd = terminal.getline("Password: ", '*');
terminal.writeln("Your password is: ", pwd);
}
version(demos) main; // exclude from docs
}
/++
$(H3 Color)
This example demonstrates color output, using [Terminal.color]
and the output functions like [Terminal.writeln].
+/
unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
terminal.color(Color.green, Color.black);
terminal.writeln("Hello world, in green on black!");
terminal.color(Color.DEFAULT, Color.DEFAULT);
terminal.writeln("And back to normal.");
}
version(demos) main; // exclude from docs
}
/++
$(H3 Single Key)
This shows how to get one single character press using
the [RealTimeConsoleInput] structure.
+/
unittest {
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
terminal.writeln("Press any key to continue...");
auto ch = input.getch();
terminal.writeln("You pressed ", ch);
}
version(demos) main; // exclude from docs
}
/++
$(H3 Full screen)
This shows how to use the cellular (full screen) mode and pass terminal to functions.
+/
unittest {
import arsd.terminal;
// passing terminals must be done by ref or by pointer
void helper(Terminal* terminal) {
terminal.moveTo(0, 1);
terminal.getline("Press enter to exit...");
}
void main() {
// ask for cellular mode, it will go full screen
auto terminal = Terminal(ConsoleOutputType.cellular);
// it is automatically cleared upon entry
terminal.write("Hello upper left corner");
// pass it by pointer to other functions
helper(&terminal);
// since at the end of main, Terminal's destructor
// resets the terminal to how it was before for the
// user
}
}
/*
Widgets:
tab widget
scrollback buffer
partitioned canvas
*/
// FIXME: ctrl+d eof on stdin
// FIXME: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686016%28v=vs.85%29.aspx
/++
A function the sigint handler will call (if overridden - which is the
case when [RealTimeConsoleInput] is active on Posix or if you compile with
`TerminalDirectToEmulator` version on any platform at this time) in addition
to the library's default handling, which is to set a flag for the event loop
to inform you.
Remember, this is called from a signal handler and/or from a separate thread,
so you are not allowed to do much with it and need care when setting TLS variables.
I suggest you only set a `__gshared bool` flag as many other operations will risk
undefined behavior.
$(WARNING
This function is never called on the default Windows console
configuration in the current implementation. You can use
`-version=TerminalDirectToEmulator` to guarantee it is called there
too by causing the library to pop up a gui window for your application.
)
History:
Added March 30, 2020. Included in release v7.1.0.
+/
__gshared void delegate() nothrow @nogc sigIntExtension;
import core.stdc.stdio;
version(TerminalDirectToEmulator) {
version=WithEncapsulatedSignals;
private __gshared bool windowGone = false;
private bool forceTerminationTried = false;
private void forceTermination() {
if(forceTerminationTried) {
// why are we still here?! someone must be catching the exception and calling back.
// there's no recovery so time to kill this program.
import core.stdc.stdlib;
abort();
} else {
// give them a chance to cleanly exit...
forceTerminationTried = true;
throw new HangupException();
}
}
}
version(Posix) {
enum SIGWINCH = 28;
__gshared bool windowSizeChanged = false;
__gshared bool interrupted = false; /// you might periodically check this in a long operation and abort if it is set. Remember it is volatile. It is also sent through the input event loop via RealTimeConsoleInput
__gshared bool hangedUp = false; /// similar to interrupted.
__gshared bool continuedFromSuspend = false; /// SIGCONT was just received, the terminal state may have changed. Added Feb 18, 2021.
version=WithSignals;
version(with_eventloop)
struct SignalFired {}
extern(C)
void sizeSignalHandler(int sigNumber) nothrow {
windowSizeChanged = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
}
extern(C)
void interruptSignalHandler(int sigNumber) nothrow {
interrupted = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
if(sigIntExtension)
sigIntExtension();
}
extern(C)
void hangupSignalHandler(int sigNumber) nothrow {
hangedUp = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
}
extern(C)
void continueSignalHandler(int sigNumber) nothrow {
continuedFromSuspend = true;
version(with_eventloop) {
import arsd.eventloop;
try
send(SignalFired());
catch(Exception) {}
}
}
}
// parts of this were taken from Robik's ConsoleD
// https://github.com/robik/ConsoleD/blob/master/consoled.d
// Uncomment this line to get a main() to demonstrate this module's
// capabilities.
//version = Demo
version(TerminalDirectToEmulator) {
version=VtEscapeCodes;
} else version(Windows) {
version(VtEscapeCodes) {} // cool
version=Win32Console;
}
version(Windows)
import core.sys.windows.windows;
version(Win32Console) {
private {
enum RED_BIT = 4;
enum GREEN_BIT = 2;
enum BLUE_BIT = 1;
}
pragma(lib, "user32");
}
version(Posix) {
version=VtEscapeCodes;
import core.sys.posix.termios;
import core.sys.posix.unistd;
import unix = core.sys.posix.unistd;
import core.sys.posix.sys.types;
import core.sys.posix.sys.time;
import core.stdc.stdio;
import core.sys.posix.sys.ioctl;
}
version(VtEscapeCodes) {
enum UseVtSequences = true;
version(TerminalDirectToEmulator) {
private {
enum RED_BIT = 1;
enum GREEN_BIT = 2;
enum BLUE_BIT = 4;
}
} else version(Windows) {} else
private {
enum RED_BIT = 1;
enum GREEN_BIT = 2;
enum BLUE_BIT = 4;
}
struct winsize {
ushort ws_row;
ushort ws_col;
ushort ws_xpixel;
ushort ws_ypixel;
}
// I'm taking this from the minimal termcap from my Slackware box (which I use as my /etc/termcap) and just taking the most commonly used ones (for me anyway).
// this way we'll have some definitions for 99% of typical PC cases even without any help from the local operating system
enum string builtinTermcap = `
# Generic VT entry.
vg|vt-generic|Generic VT entries:\
:bs:mi:ms:pt:xn:xo:it#8:\
:RA=\E[?7l:SA=\E?7h:\
:bl=^G:cr=^M:ta=^I:\
:cm=\E[%i%d;%dH:\
:le=^H:up=\E[A:do=\E[B:nd=\E[C:\
:LE=\E[%dD:RI=\E[%dC:UP=\E[%dA:DO=\E[%dB:\
:ho=\E[H:cl=\E[H\E[2J:ce=\E[K:cb=\E[1K:cd=\E[J:sf=\ED:sr=\EM:\
:ct=\E[3g:st=\EH:\
:cs=\E[%i%d;%dr:sc=\E7:rc=\E8:\
:ei=\E[4l:ic=\E[@:IC=\E[%d@:al=\E[L:AL=\E[%dL:\
:dc=\E[P:DC=\E[%dP:dl=\E[M:DL=\E[%dM:\
:so=\E[7m:se=\E[m:us=\E[4m:ue=\E[m:\
:mb=\E[5m:mh=\E[2m:md=\E[1m:mr=\E[7m:me=\E[m:\
:sc=\E7:rc=\E8:kb=\177:\
:ku=\E[A:kd=\E[B:kr=\E[C:kl=\E[D:
# Slackware 3.1 linux termcap entry (Sat Apr 27 23:03:58 CDT 1996):
lx|linux|console|con80x25|LINUX System Console:\
:do=^J:co#80:li#25:cl=\E[H\E[J:sf=\ED:sb=\EM:\
:le=^H:bs:am:cm=\E[%i%d;%dH:nd=\E[C:up=\E[A:\
:ce=\E[K:cd=\E[J:so=\E[7m:se=\E[27m:us=\E[36m:ue=\E[m:\
:md=\E[1m:mr=\E[7m:mb=\E[5m:me=\E[m:is=\E[1;25r\E[25;1H:\
:ll=\E[1;25r\E[25;1H:al=\E[L:dc=\E[P:dl=\E[M:\
:it#8:ku=\E[A:kd=\E[B:kr=\E[C:kl=\E[D:kb=^H:ti=\E[r\E[H:\
:ho=\E[H:kP=\E[5~:kN=\E[6~:kH=\E[4~:kh=\E[1~:kD=\E[3~:kI=\E[2~:\
:k1=\E[[A:k2=\E[[B:k3=\E[[C:k4=\E[[D:k5=\E[[E:k6=\E[17~:\
:F1=\E[23~:F2=\E[24~:\
:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:K1=\E[1~:K2=\E[5~:\
:K4=\E[4~:K5=\E[6~:\
:pt:sr=\EM:vt#3:xn:km:bl=^G:vi=\E[?25l:ve=\E[?25h:vs=\E[?25h:\
:sc=\E7:rc=\E8:cs=\E[%i%d;%dr:\
:r1=\Ec:r2=\Ec:r3=\Ec:
# Some other, commonly used linux console entries.
lx|con80x28:co#80:li#28:tc=linux:
lx|con80x43:co#80:li#43:tc=linux:
lx|con80x50:co#80:li#50:tc=linux:
lx|con100x37:co#100:li#37:tc=linux:
lx|con100x40:co#100:li#40:tc=linux:
lx|con132x43:co#132:li#43:tc=linux:
# vt102 - vt100 + insert line etc. VT102 does not have insert character.
v2|vt102|DEC vt102 compatible:\
:co#80:li#24:\
:ic@:IC@:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:ks=:ke=:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:\
:tc=vt-generic:
# vt100 - really vt102 without insert line, insert char etc.
vt|vt100|DEC vt100 compatible:\
:im@:mi@:al@:dl@:ic@:dc@:AL@:DL@:IC@:DC@:\
:tc=vt102:
# Entry for an xterm. Insert mode has been disabled.
vs|xterm|tmux|tmux-256color|xterm-kitty|screen|screen.xterm|screen-256color|screen.xterm-256color|xterm-color|xterm-256color|vs100|xterm terminal emulator (X Window System):\
:am:bs:mi@:km:co#80:li#55:\
:im@:ei@:\
:cl=\E[H\E[J:\
:ct=\E[3k:ue=\E[m:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:vi=\E[?25l:ve=\E[?25h:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:kI=\E[2~:kD=\E[3~:kP=\E[5~:kN=\E[6~:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:\
:F1=\E[23~:F2=\E[24~:\
:kh=\E[H:kH=\E[F:\
:ks=:ke=:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:\
:tc=vt-generic:
#rxvt, added by me
rxvt|rxvt-unicode|rxvt-unicode-256color:\
:am:bs:mi@:km:co#80:li#55:\
:im@:ei@:\
:ct=\E[3k:ue=\E[m:\
:is=\E[m\E[?1l\E>:\
:rs=\E[m\E[?1l\E>:\
:vi=\E[?25l:\
:ve=\E[?25h:\
:eA=\E)0:as=^N:ae=^O:ac=aaffggjjkkllmmnnooqqssttuuvvwwxx:\
:kI=\E[2~:kD=\E[3~:kP=\E[5~:kN=\E[6~:\
:k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:k0=\E[21~:\
:F1=\E[23~:F2=\E[24~:\
:kh=\E[7~:kH=\E[8~:\
:ks=:ke=:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:\
:tc=vt-generic:
# Some other entries for the same xterm.
v2|xterms|vs100s|xterm small window:\
:co#80:li#24:tc=xterm:
vb|xterm-bold|xterm with bold instead of underline:\
:us=\E[1m:tc=xterm:
vi|xterm-ins|xterm with insert mode:\
:mi:im=\E[4h:ei=\E[4l:tc=xterm:
Eterm|Eterm Terminal Emulator (X11 Window System):\
:am:bw:eo:km:mi:ms:xn:xo:\
:co#80:it#8:li#24:lm#0:pa#64:Co#8:AF=\E[3%dm:AB=\E[4%dm:op=\E[39m\E[49m:\
:AL=\E[%dL:DC=\E[%dP:DL=\E[%dM:DO=\E[%dB:IC=\E[%d@:\
:K1=\E[7~:K2=\EOu:K3=\E[5~:K4=\E[8~:K5=\E[6~:LE=\E[%dD:\
:RI=\E[%dC:UP=\E[%dA:ae=^O:al=\E[L:as=^N:bl=^G:cd=\E[J:\
:ce=\E[K:cl=\E[H\E[2J:cm=\E[%i%d;%dH:cr=^M:\
:cs=\E[%i%d;%dr:ct=\E[3g:dc=\E[P:dl=\E[M:do=\E[B:\
:ec=\E[%dX:ei=\E[4l:ho=\E[H:i1=\E[?47l\E>\E[?1l:ic=\E[@:\
:im=\E[4h:is=\E[r\E[m\E[2J\E[H\E[?7h\E[?1;3;4;6l\E[4l:\
:k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~:k5=\E[15~:\
:k6=\E[17~:k7=\E[18~:k8=\E[19~:k9=\E[20~:kD=\E[3~:\
:kI=\E[2~:kN=\E[6~:kP=\E[5~:kb=^H:kd=\E[B:ke=:kh=\E[7~:\
:kl=\E[D:kr=\E[C:ks=:ku=\E[A:le=^H:mb=\E[5m:md=\E[1m:\
:me=\E[m\017:mr=\E[7m:nd=\E[C:rc=\E8:\
:sc=\E7:se=\E[27m:sf=^J:so=\E[7m:sr=\EM:st=\EH:ta=^I:\
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:ue=\E[24m:up=\E[A:\
:us=\E[4m:vb=\E[?5h\E[?5l:ve=\E[?25h:vi=\E[?25l:\
:ac=aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~:
# DOS terminal emulator such as Telix or TeleMate.
# This probably also works for the SCO console, though it's incomplete.
an|ansi|ansi-bbs|ANSI terminals (emulators):\
:co#80:li#24:am:\
:is=:rs=\Ec:kb=^H:\
:as=\E[m:ae=:eA=:\
:ac=0\333+\257,\256.\031-\030a\261f\370g\361j\331k\277l\332m\300n\305q\304t\264u\303v\301w\302x\263~\025:\
:kD=\177:kH=\E[Y:kN=\E[U:kP=\E[V:kh=\E[H:\
:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\EOT:\
:k6=\EOU:k7=\EOV:k8=\EOW:k9=\EOX:k0=\EOY:\
:tc=vt-generic:
`;
} else {
enum UseVtSequences = false;
}
/// A modifier for [Color]
enum Bright = 0x08;
/// Defines the list of standard colors understood by Terminal.
/// See also: [Bright]
enum Color : ushort {
black = 0, /// .
red = RED_BIT, /// .
green = GREEN_BIT, /// .
yellow = red | green, /// .
blue = BLUE_BIT, /// .
magenta = red | blue, /// .
cyan = blue | green, /// .
white = red | green | blue, /// .
DEFAULT = 256,
}
/// When capturing input, what events are you interested in?
///
/// Note: these flags can be OR'd together to select more than one option at a time.
///
/// Ctrl+C and other keyboard input is always captured, though it may be line buffered if you don't use raw.
/// The rationale for that is to ensure the Terminal destructor has a chance to run, since the terminal is a shared resource and should be put back before the program terminates.
enum ConsoleInputFlags {
raw = 0, /// raw input returns keystrokes immediately, without line buffering
echo = 1, /// do you want to automatically echo input back to the user?
mouse = 2, /// capture mouse events
paste = 4, /// capture paste events (note: without this, paste can come through as keystrokes)
size = 8, /// window resize events
releasedKeys = 64, /// key release events. Not reliable on Posix.
allInputEvents = 8|4|2, /// subscribe to all input events. Note: in previous versions, this also returned release events. It no longer does, use allInputEventsWithRelease if you want them.
allInputEventsWithRelease = allInputEvents|releasedKeys, /// subscribe to all input events, including (unreliable on Posix) key release events.
noEolWrap = 128,
selectiveMouse = 256, /// Uses arsd terminal emulator's proprietary extension to select mouse input only for special cases, intended to enhance getline while keeping default terminal mouse behavior in other places. If it is set, it overrides [mouse] event flag. If not using the arsd terminal emulator, this will disable application mouse input.
}
/// Defines how terminal output should be handled.
enum ConsoleOutputType {
linear = 0, /// do you want output to work one line at a time?
cellular = 1, /// or do you want access to the terminal screen as a grid of characters?
//truncatedCellular = 3, /// cellular, but instead of wrapping output to the next line automatically, it will truncate at the edges
minimalProcessing = 255, /// do the least possible work, skips most construction and desturction tasks. Only use if you know what you're doing here
}
alias ConsoleOutputMode = ConsoleOutputType;
/// Some methods will try not to send unnecessary commands to the screen. You can override their judgement using a ForceOption parameter, if present
enum ForceOption {
automatic = 0, /// automatically decide what to do (best, unless you know for sure it isn't right)
neverSend = -1, /// never send the data. This will only update Terminal's internal state. Use with caution.
alwaysSend = 1, /// always send the data, even if it doesn't seem necessary
}
///
enum TerminalCursor {
DEFAULT = 0, ///
insert = 1, ///
block = 2 ///
}
// we could do it with termcap too, getenv("TERMCAP") then split on : and replace \E with \033 and get the pieces
/// Encapsulates the I/O capabilities of a terminal.
///
/// Warning: do not write out escape sequences to the terminal. This won't work
/// on Windows and will confuse Terminal's internal state on Posix.
struct Terminal {
///
@disable this();
@disable this(this);
private ConsoleOutputType type;
version(TerminalDirectToEmulator) {
private bool windowSizeChanged = false;
private bool interrupted = false; /// you might periodically check this in a long operation and abort if it is set. Remember it is volatile. It is also sent through the input event loop via RealTimeConsoleInput
private bool hangedUp = false; /// similar to interrupted.
}
private TerminalCursor currentCursor_;
version(Windows) private CONSOLE_CURSOR_INFO originalCursorInfo;
/++
Changes the current cursor.
+/
void cursor(TerminalCursor what, ForceOption force = ForceOption.automatic) {
if(force == ForceOption.neverSend) {
currentCursor_ = what;
return;
} else {
if(what != currentCursor_ || force == ForceOption.alwaysSend) {
currentCursor_ = what;
version(Win32Console) {
final switch(what) {
case TerminalCursor.DEFAULT:
SetConsoleCursorInfo(hConsole, &originalCursorInfo);
break;
case TerminalCursor.insert:
case TerminalCursor.block:
CONSOLE_CURSOR_INFO info;
GetConsoleCursorInfo(hConsole, &info);
info.dwSize = what == TerminalCursor.insert ? 1 : 100;
SetConsoleCursorInfo(hConsole, &info);
break;
}
} else {
final switch(what) {
case TerminalCursor.DEFAULT:
if(terminalInFamily("linux"))
writeStringRaw("\033[?0c");
else
writeStringRaw("\033[0 q");
break;
case TerminalCursor.insert:
if(terminalInFamily("linux"))
writeStringRaw("\033[?2c");
else if(terminalInFamily("xterm"))
writeStringRaw("\033[6 q");
else
writeStringRaw("\033[4 q");
break;
case TerminalCursor.block:
if(terminalInFamily("linux"))
writeStringRaw("\033[?6c");
else
writeStringRaw("\033[2 q");
break;
}
}
}
}
}
/++
Terminal is only valid to use on an actual console device or terminal
handle. You should not attempt to construct a Terminal instance if this
returns false. Real time input is similarly impossible if `!stdinIsTerminal`.
+/
static bool stdoutIsTerminal() {
version(TerminalDirectToEmulator) {
version(Windows) {
// if it is null, it was a gui subsystem exe. But otherwise, it
// might be explicitly redirected and we should respect that for
// compatibility with normal console expectations (even though like
// we COULD pop up a gui and do both, really that isn't the normal
// use of this library so don't wanna go too nuts)
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
return hConsole is null || GetFileType(hConsole) == FILE_TYPE_CHAR;
} else version(Posix) {
// same as normal here since thee is no gui subsystem really
import core.sys.posix.unistd;
return cast(bool) isatty(1);
} else static assert(0);
} else version(Posix) {
import core.sys.posix.unistd;
return cast(bool) isatty(1);
} else version(Win32Console) {
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
return GetFileType(hConsole) == FILE_TYPE_CHAR;
/+
auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO originalSbi;
if(GetConsoleScreenBufferInfo(hConsole, &originalSbi) == 0)
return false;
else
return true;
+/
} else static assert(0);
}
///
static bool stdinIsTerminal() {
version(TerminalDirectToEmulator) {
version(Windows) {
auto hConsole = GetStdHandle(STD_INPUT_HANDLE);
return hConsole is null || GetFileType(hConsole) == FILE_TYPE_CHAR;
} else version(Posix) {
// same as normal here since thee is no gui subsystem really
import core.sys.posix.unistd;
return cast(bool) isatty(0);
} else static assert(0);
} else version(Posix) {
import core.sys.posix.unistd;
return cast(bool) isatty(0);
} else version(Win32Console) {
auto hConsole = GetStdHandle(STD_INPUT_HANDLE);
return GetFileType(hConsole) == FILE_TYPE_CHAR;
} else static assert(0);
}
version(Posix) {
private int fdOut;
private int fdIn;
private int[] delegate() getSizeOverride;
void delegate(in void[]) _writeDelegate; // used to override the unix write() system call, set it magically
}
bool terminalInFamily(string[] terms...) {
import std.process;
import std.string;
version(TerminalDirectToEmulator)
auto term = "xterm";
else
auto term = environment.get("TERM");
foreach(t; terms)
if(indexOf(term, t) != -1)
return true;
return false;
}
version(Posix) {
// This is a filthy hack because Terminal.app and OS X are garbage who don't
// work the way they're advertised. I just have to best-guess hack and hope it
// doesn't break anything else. (If you know a better way, let me know!)
bool isMacTerminal() {
// it gives 1,2 in getTerminalCapabilities...
// FIXME
import std.process;
import std.string;
auto term = environment.get("TERM");
return term == "xterm-256color";
}
} else
bool isMacTerminal() { return false; }
static string[string] termcapDatabase;
static void readTermcapFile(bool useBuiltinTermcap = false) {
import std.file;
import std.stdio;
import std.string;
//if(!exists("/etc/termcap"))
useBuiltinTermcap = true;
string current;
void commitCurrentEntry() {
if(current is null)
return;
string names = current;
auto idx = indexOf(names, ":");
if(idx != -1)
names = names[0 .. idx];
foreach(name; split(names, "|"))
termcapDatabase[name] = current;
current = null;
}
void handleTermcapLine(in char[] line) {
if(line.length == 0) { // blank
commitCurrentEntry();
return; // continue
}
if(line[0] == '#') // comment
return; // continue
size_t termination = line.length;
if(line[$-1] == '\\')
termination--; // cut off the \\
current ~= strip(line[0 .. termination]);
// termcap entries must be on one logical line, so if it isn't continued, we know we're done
if(line[$-1] != '\\')
commitCurrentEntry();
}
if(useBuiltinTermcap) {
version(VtEscapeCodes)
foreach(line; splitLines(builtinTermcap)) {
handleTermcapLine(line);
}
} else {
foreach(line; File("/etc/termcap").byLine()) {
handleTermcapLine(line);
}
}
}
static string getTermcapDatabase(string terminal) {
import std.string;
if(termcapDatabase is null)
readTermcapFile();
auto data = terminal in termcapDatabase;
if(data is null)
return null;
auto tc = *data;
auto more = indexOf(tc, ":tc=");
if(more != -1) {
auto tcKey = tc[more + ":tc=".length .. $];
auto end = indexOf(tcKey, ":");
if(end != -1)
tcKey = tcKey[0 .. end];
tc = getTermcapDatabase(tcKey) ~ tc;
}
return tc;
}
string[string] termcap;
void readTermcap(string t = null) {
version(TerminalDirectToEmulator)
if(usingDirectEmulator)
t = "xterm";
import std.process;
import std.string;
import std.array;
string termcapData = environment.get("TERMCAP");
if(termcapData.length == 0) {
if(t is null) {
t = environment.get("TERM");
}
// loosen the check so any xterm variety gets
// the same termcap. odds are this is right
// almost always
if(t.indexOf("xterm") != -1)
t = "xterm";
if(t.indexOf("putty") != -1)
t = "xterm";
if(t.indexOf("tmux") != -1)
t = "tmux";
if(t.indexOf("screen") != -1)
t = "screen";
termcapData = getTermcapDatabase(t);
}
auto e = replace(termcapData, "\\\n", "\n");
termcap = null;
foreach(part; split(e, ":")) {
// FIXME: handle numeric things too
auto things = split(part, "=");
if(things.length)
termcap[things[0]] =
things.length > 1 ? things[1] : null;
}
}
string findSequenceInTermcap(in char[] sequenceIn) {
char[10] sequenceBuffer;
char[] sequence;
if(sequenceIn.length > 0 && sequenceIn[0] == '\033') {
if(!(sequenceIn.length < sequenceBuffer.length - 1))
return null;
sequenceBuffer[1 .. sequenceIn.length + 1] = sequenceIn[];
sequenceBuffer[0] = '\\';
sequenceBuffer[1] = 'E';
sequence = sequenceBuffer[0 .. sequenceIn.length + 1];
} else {
sequence = sequenceBuffer[1 .. sequenceIn.length + 1];
}
import std.array;
foreach(k, v; termcap)
if(v == sequence)
return k;
return null;
}
string getTermcap(string key) {
auto k = key in termcap;
if(k !is null) return *k;
return null;
}
// Looks up a termcap item and tries to execute it. Returns false on failure
bool doTermcap(T...)(string key, T t) {
import std.conv;
auto fs = getTermcap(key);
if(fs is null)
return false;
int swapNextTwo = 0;
R getArg(R)(int idx) {
if(swapNextTwo == 2) {
idx ++;
swapNextTwo--;
} else if(swapNextTwo == 1) {
idx --;
swapNextTwo--;
}
foreach(i, arg; t) {
if(i == idx)
return to!R(arg);
}
assert(0, to!string(idx) ~ " is out of bounds working " ~ fs);
}
char[256] buffer;
int bufferPos = 0;
void addChar(char c) {
import std.exception;
enforce(bufferPos < buffer.length);
buffer[bufferPos++] = c;
}
void addString(in char[] c) {
import std.exception;
enforce(bufferPos + c.length < buffer.length);
buffer[bufferPos .. bufferPos + c.length] = c[];
bufferPos += c.length;
}
void addInt(int c, int minSize) {
import std.string;
auto str = format("%0"~(minSize ? to!string(minSize) : "")~"d", c);
addString(str);
}
bool inPercent;
int argPosition = 0;
int incrementParams = 0;
bool skipNext;
bool nextIsChar;
bool inBackslash;
foreach(char c; fs) {
if(inBackslash) {
if(c == 'E')
addChar('\033');
else
addChar(c);
inBackslash = false;
} else if(nextIsChar) {
if(skipNext)
skipNext = false;
else
addChar(cast(char) (c + getArg!int(argPosition) + (incrementParams ? 1 : 0)));
if(incrementParams) incrementParams--;
argPosition++;
inPercent = false;
} else if(inPercent) {
switch(c) {
case '%':
addChar('%');
inPercent = false;
break;
case '2':
case '3':
case 'd':
if(skipNext)
skipNext = false;
else
addInt(getArg!int(argPosition) + (incrementParams ? 1 : 0),
c == 'd' ? 0 : (c - '0')
);
if(incrementParams) incrementParams--;
argPosition++;
inPercent = false;
break;
case '.':
if(skipNext)
skipNext = false;
else
addChar(cast(char) (getArg!int(argPosition) + (incrementParams ? 1 : 0)));
if(incrementParams) incrementParams--;
argPosition++;
break;
case '+':
nextIsChar = true;
inPercent = false;
break;
case 'i':
incrementParams = 2;
inPercent = false;