forked from adoxa/ansicon
/
ANSI.c
2275 lines (2031 loc) · 64.3 KB
/
ANSI.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
/*
ANSI.c - ANSI escape sequence console driver.
Jason Hood, 21 & 22 October, 2005.
Derived from ANSI.xs by Jean-Louis Morel, from his Perl package
Win32::Console::ANSI. I removed the codepage conversion ("\e(") and added
WriteConsole hooking.
v1.01, 11 & 12 March, 2006:
disable when console has disabled processed output;
\e[5m (blink) is the same as \e[4m (underline);
do not conceal control characters (0 to 31);
\e[m will restore original color.
v1.10, 22 February, 2009:
fix MyWriteConsoleW for strings longer than the buffer;
initialise attributes to current;
hook into child processes.
v1.11, 28 February, 2009:
fix hooking into child processes (only do console executables).
v1.12, 9 March, 2009:
really fix hooking (I didn't realise MinGW didn't generate relocations).
v1.13, 21 & 27 March, 2009:
alternate injection method, to work with DEP;
use Unicode and the current output code page (not OEMCP).
v1.14, 3 April, 2009:
fix test for empty import section.
v1.15, 17 May, 2009:
properly update lpNumberOfCharsWritten in MyWriteConsoleA.
v1.20, 26 & 29 May, 17 to 21 June, 2009:
create an ANSICON environment variable;
hook GetEnvironmentVariable to create ANSICON dynamically;
use another injection method.
v1.22, 5 October, 2009:
hook LoadLibrary to intercept the newly loaded functions.
v1.23, 11 November, 2009:
unload gracefully;
conceal characters by making foreground same as background;
reverse the bold/underline attributes, too.
v1.25, 15, 20 & 21 July, 2010:
hook LoadLibraryEx (now cscript works);
Win7 support.
v1.30, 3 August to 7 September, 2010:
x64 support.
v1.31, 13 & 19 November, 2010:
fix multibyte conversion problems.
v1.32, 4 to 22 December, 2010:
test for lpNumberOfCharsWritten/lpNumberOfBytesWritten being NULL;
recognise DSR and xterm window title;
ignore sequences starting with \e[? & \e[>;
close the handles opened by CreateProcess.
v1.40, 25 & 26 February, 1 March, 2011:
hook GetProcAddress, addresses issues with .NET (work with PowerShell);
implement SO & SI to use the DEC Special Graphics Character Set (enables
line drawing via ASCII); ignore \e(X & \e)X (where X is any character);
add \e[?25h & \e[?25l to show/hide the cursor (DECTCEM).
v1.50, 7 to 14 December, 2011:
added dynamic environment variable ANSICON_VER to return version;
read ANSICON_EXC environment variable to exclude selected modules;
read ANSICON_GUI environment variable to hook selected GUI programs;
read ANSICON_DEF environment variable to set the default GR;
transfer current GR to child, read it on exit.
v1.51, 15 January, 5, 22 & 24 February, 2012:
added log mask 16 to log all the imported modules of imported modules;
ignore the version within the core API DLL names;
fix 32-bit process trying to identify 64-bit process;
hook _lwrite & _hwrite.
v1.52, 10 April, 1 & 2 June, 2012:
use ansicon.exe to enable 32-bit to inject into 64-bit;
implement \e[39m & \e[49m (only setting color, nothing else);
added the character/line equivalents (keaj`) of the cursor movement
sequences (ABCDG), as well as vertical absolute (d) and erase characters
(X).
v1.53, 12 June, 2012:
fixed Update_GRM when running multiple processes (e.g. "cl /MP").
v1.60, 22 to 24 November, 2012:
alternative method to obtain LLW for 64->32 injection;
support for VC6 (remove section pragma, rename isdigit to is_digit).
v1.61, 14 February, 2013:
go back to using ANSI-LLW.exe for 64->32 injection.
v1.62, 17 & 18 July, 2013:
another method to obtain LLW for 64->32 injection.
v1.64, 2 August, 2013:
better method of determining a console handle (see IsConsoleHandle).
v1.65, 28 August, 2013:
fix \e[K (was using window, not buffer).
v1.66, 20 & 21 September, 2013:
fix 32-bit process trying to detect 64-bit process.
v1.70, 25 January to 26 February, 2014:
don't hook ourself from LoadLibrary or LoadLibraryEx;
update the LoadLibraryEx flags that should not cause hooking;
inject by manipulating the import directory table; for 64-bit AnyCPU use
ntdll's LdrLoadDll via CreateRemoteThread;
restore original attributes on detach (for LoadLibrary/FreeLibrary usage);
log: remove the quotes around the CreateProcess command line string and
distinguish NULL and "" args;
attributes (and saved position) are local to each console window;
exclude entire programs, by not using an extension in ANSICON_EXC;
hook modules injected via CreateRemoteThread+LoadLibrary;
hook all modules loaded due to LoadLibrary, not just the specified;
don't hook a module that's already hooked us;
better parsing of escape & CSI sequences;
ignore xterm 38 & 48 SGR values;
change G1 blank from space to U+00A0 - No-Break Space;
use window height, not buffer;
added more sequences;
don't add a newline immediately after a wrap;
restore cursor visibility on unload.
*/
#include "ansicon.h"
#include "version.h"
#include <tlhelp32.h>
#define is_digit(c) ('0' <= (c) && (c) <= '9')
// ========== Global variables and constants
HANDLE hConOut; // handle to CONOUT$
WORD orgattr; // original attributes
DWORD orgmode; // original mode
CONSOLE_CURSOR_INFO orgcci; // original cursor state
#define ESC '\x1B' // ESCape character
#define BEL '\x07'
#define SO '\x0E' // Shift Out
#define SI '\x0F' // Shift In
#define MAX_ARG 16 // max number of args in an escape sequence
int state; // automata state
TCHAR prefix; // escape sequence prefix ( '[', ']' or '(' );
TCHAR prefix2; // secondary prefix ( '?' or '>' );
TCHAR suffix; // escape sequence suffix
TCHAR suffix2; // escape sequence secondary suffix
int es_argc; // escape sequence args count
int es_argv[MAX_ARG]; // escape sequence args
TCHAR Pt_arg[MAX_PATH*2]; // text parameter for Operating System Command
int Pt_len;
BOOL shifted;
int screen_top = -1; // initial window top when cleared
// DEC Special Graphics Character Set from
// http://vt100.net/docs/vt220-rm/table2-4.html
// Some of these may not look right, depending on the font and code page (in
// particular, the Control Pictures probably won't work at all).
const WCHAR G1[] =
{
L'\x00a0', // _ - No-Break Space
L'\x2666', // ` - Black Diamond Suit
L'\x2592', // a - Medium Shade
L'\x2409', // b - HT
L'\x240c', // c - FF
L'\x240d', // d - CR
L'\x240a', // e - LF
L'\x00b0', // f - Degree Sign
L'\x00b1', // g - Plus-Minus Sign
L'\x2424', // h - NL
L'\x240b', // i - VT
L'\x2518', // j - Box Drawings Light Up And Left
L'\x2510', // k - Box Drawings Light Down And Left
L'\x250c', // l - Box Drawings Light Down And Right
L'\x2514', // m - Box Drawings Light Up And Right
L'\x253c', // n - Box Drawings Light Vertical And Horizontal
L'\x00af', // o - SCAN 1 - Macron
L'\x25ac', // p - SCAN 3 - Black Rectangle
L'\x2500', // q - SCAN 5 - Box Drawings Light Horizontal
L'_', // r - SCAN 7 - Low Line
L'_', // s - SCAN 9 - Low Line
L'\x251c', // t - Box Drawings Light Vertical And Right
L'\x2524', // u - Box Drawings Light Vertical And Left
L'\x2534', // v - Box Drawings Light Up And Horizontal
L'\x252c', // w - Box Drawings Light Down And Horizontal
L'\x2502', // x - Box Drawings Light Vertical
L'\x2264', // y - Less-Than Or Equal To
L'\x2265', // z - Greater-Than Or Equal To
L'\x03c0', // { - Greek Small Letter Pi
L'\x2260', // | - Not Equal To
L'\x00a3', // } - Pound Sign
L'\x00b7', // ~ - Middle Dot
};
#define FIRST_G1 '_'
#define LAST_G1 '~'
// color constants
#define FOREGROUND_BLACK 0
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#define BACKGROUND_BLACK 0
#define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
const BYTE foregroundcolor[8] =
{
FOREGROUND_BLACK, // black foreground
FOREGROUND_RED, // red foreground
FOREGROUND_GREEN, // green foreground
FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground
FOREGROUND_BLUE, // blue foreground
FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground
FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground
FOREGROUND_WHITE // white foreground
};
const BYTE backgroundcolor[8] =
{
BACKGROUND_BLACK, // black background
BACKGROUND_RED, // red background
BACKGROUND_GREEN, // green background
BACKGROUND_RED | BACKGROUND_GREEN, // yellow background
BACKGROUND_BLUE, // blue background
BACKGROUND_BLUE | BACKGROUND_RED, // magenta background
BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background
BACKGROUND_WHITE, // white background
};
const BYTE attr2ansi[8] = // map console attribute to ANSI number
{
0, // black
4, // blue
2, // green
6, // cyan
1, // red
5, // magenta
3, // yellow
7 // white
};
typedef struct
{
BYTE foreground; // ANSI base color (0 to 7; add 30)
BYTE background; // ANSI base color (0 to 7; add 40)
BYTE bold; // console FOREGROUND_INTENSITY bit
BYTE underline; // console BACKGROUND_INTENSITY bit
BYTE rvideo; // swap foreground/bold & background/underline
BYTE concealed; // set foreground/bold to background/underline
BYTE reverse; // swap console foreground & background attributes
BYTE crm; // showing control characters?
COORD SavePos; // saved cursor position
} STATE, *PSTATE;
PSTATE pState;
HANDLE hMap;
void set_ansicon( PCONSOLE_SCREEN_BUFFER_INFO );
void get_state( void )
{
TCHAR buf[64];
HWND hwnd;
BOOL init;
HANDLE hConOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
static STATE state; // on the odd chance file mapping fails
if (pState != NULL)
return;
hwnd = GetConsoleWindow();
if (hwnd == NULL)
return;
wsprintf( buf, L"ANSICON_State_%X", PtrToUint( hwnd ) );
hMap = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
0, sizeof(STATE), buf );
if (hMap == NULL)
{
no_go:
DEBUGSTR( 1, L"File mapping failed (%lu) - using default state",
GetLastError() );
pState = &state;
goto do_init;
}
init = (GetLastError() != ERROR_ALREADY_EXISTS);
pState = MapViewOfFile( hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0 );
if (pState == NULL)
{
CloseHandle( hMap );
goto no_go;
}
if (init)
{
do_init:
hConOut = CreateFile( L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, 0 );
if (!GetConsoleScreenBufferInfo( hConOut, &csbi ))
{
DEBUGSTR(1, L"Failed to get screen buffer info (%lu) - assuming defaults",
GetLastError() );
csbi.wAttributes = 7;
csbi.dwSize.X = 80;
csbi.dwSize.Y = 300;
csbi.srWindow.Left = 0;
csbi.srWindow.Right = 79;
csbi.srWindow.Top = 0;
csbi.srWindow.Bottom = 24;
}
if (GetEnvironmentVariable( L"ANSICON_REVERSE", NULL, 0 ))
{
SetEnvironmentVariable( L"ANSICON_REVERSE", NULL );
pState->reverse = TRUE;
pState->foreground = attr2ansi[(csbi.wAttributes >> 4) & 7];
pState->background = attr2ansi[csbi.wAttributes & 7];
pState->bold = (csbi.wAttributes & BACKGROUND_INTENSITY) >> 4;
pState->underline = (csbi.wAttributes & FOREGROUND_INTENSITY) << 4;
}
else
{
pState->foreground = attr2ansi[csbi.wAttributes & 7];
pState->background = attr2ansi[(csbi.wAttributes >> 4) & 7];
pState->bold = csbi.wAttributes & FOREGROUND_INTENSITY;
pState->underline = csbi.wAttributes & BACKGROUND_INTENSITY;
}
if (!GetEnvironmentVariable( L"ANSICON_DEF", NULL, 0 ))
{
TCHAR def[4];
LPTSTR a = def;
if (pState->reverse)
{
*a++ = '-';
csbi.wAttributes = ((csbi.wAttributes >> 4) & 15)
| ((csbi.wAttributes & 15) << 4);
}
wsprintf( a, L"%X", csbi.wAttributes & 255 );
SetEnvironmentVariable( L"ANSICON_DEF", def );
}
set_ansicon( &csbi );
CloseHandle( hConOut );
}
}
// Search an environment variable for a string.
BOOL search_env( LPCTSTR var, LPCTSTR val )
{
static LPTSTR env;
static DWORD env_len;
DWORD len;
BOOL not;
len = GetEnvironmentVariable( var, env, env_len );
if (len == 0)
return FALSE;
if (len > env_len)
{
LPTSTR tmp = realloc( env, TSIZE(len) );
if (tmp == NULL)
return FALSE;
env = tmp;
env_len = len;
GetEnvironmentVariable( var, env, env_len );
}
not = (*env == '!');
if (not && env[1] == '\0')
return TRUE;
for (var = wcstok( env + not, L";" ); var; var = wcstok( NULL, L";" ))
if (_wcsicmp( val, var ) == 0)
return !not;
return not;
}
// ========== Print Buffer functions
#define BUFFER_SIZE 2048
int nCharInBuffer;
WCHAR ChBuffer[BUFFER_SIZE];
WCHAR ChPrev;
BOOL fWrapped;
//-----------------------------------------------------------------------------
// FlushBuffer()
// Writes the buffer to the console and empties it.
//-----------------------------------------------------------------------------
void FlushBuffer( void )
{
DWORD nWritten;
if (nCharInBuffer <= 0) return;
if (pState->crm)
{
DWORD mode;
GetConsoleMode( hConOut, &mode );
SetConsoleMode( hConOut, mode & ~ENABLE_PROCESSED_OUTPUT );
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
SetConsoleMode( hConOut, mode );
}
else
{
HANDLE hConWrap;
CONSOLE_CURSOR_INFO cci;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (nCharInBuffer < 4)
{
LPWSTR b = ChBuffer;
do
{
WriteConsole( hConOut, b, 1, &nWritten, NULL );
if (*b != '\r' && *b != '\b' && *b != '\a')
{
GetConsoleScreenBufferInfo( hConOut, &csbi );
if (csbi.dwCursorPosition.X == 0)
fWrapped = TRUE;
}
} while (++b, --nCharInBuffer);
}
else
{
// To detect wrapping of multiple characters, create a new buffer, write
// to the top of it and see if the cursor changes line. This doesn't
// always work on the normal buffer, since if you're already on the last
// line, wrapping scrolls everything up and still leaves you on the last.
hConWrap = CreateConsoleScreenBuffer( GENERIC_READ|GENERIC_WRITE, 0, NULL,
CONSOLE_TEXTMODE_BUFFER, NULL );
// Even though the buffer isn't visible, the cursor still shows up.
cci.dwSize = 1;
cci.bVisible = FALSE;
SetConsoleCursorInfo( hConWrap, &cci );
// Ensure the buffer is the same width (it gets created using the window
// width) and more than one line.
GetConsoleScreenBufferInfo( hConOut, &csbi );
csbi.dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 2;
SetConsoleScreenBufferSize( hConWrap, csbi.dwSize );
// Put the cursor on the top line, in the same column.
csbi.dwCursorPosition.Y = 0;
SetConsoleCursorPosition( hConWrap, csbi.dwCursorPosition );
WriteConsole( hConWrap, ChBuffer, nCharInBuffer, &nWritten, NULL );
GetConsoleScreenBufferInfo( hConWrap, &csbi );
if (csbi.dwCursorPosition.Y != 0)
fWrapped = TRUE;
CloseHandle( hConWrap );
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
}
}
nCharInBuffer = 0;
}
//-----------------------------------------------------------------------------
// PushBuffer( WCHAR c )
// Adds a character in the buffer.
//-----------------------------------------------------------------------------
void PushBuffer( WCHAR c )
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD nWritten;
ChPrev = c;
if (c == '\n')
{
if (pState->crm)
ChBuffer[nCharInBuffer++] = c;
FlushBuffer();
// Avoid writing the newline if wrap has already occurred.
GetConsoleScreenBufferInfo( hConOut, &csbi );
if (pState->crm)
{
// If we're displaying controls, then the only way we can be on the left
// margin is if wrap occurred.
if (csbi.dwCursorPosition.X != 0)
WriteConsole( hConOut, L"\n", 1, &nWritten, NULL );
}
else
{
LPCWSTR nl = L"\n";
if (fWrapped)
{
// It's wrapped, but was anything more written? Look at the current
// row, checking that each character is space in current attributes.
// If it's all blank we can drop the newline. If the cursor isn't
// already at the margin, then it was spaces or tabs that caused the
// wrap, which can be ignored and overwritten.
CHAR_INFO blank;
PCHAR_INFO row;
row = malloc( csbi.dwSize.X * sizeof(CHAR_INFO) );
if (row != NULL)
{
COORD s, c;
SMALL_RECT r;
s.X = csbi.dwSize.X;
s.Y = 1;
c.X = c.Y = 0;
r.Left = 0;
r.Right = s.X - 1;
r.Top = r.Bottom = csbi.dwCursorPosition.Y;
ReadConsoleOutput( hConOut, row, s, c, &r );
blank.Char.UnicodeChar = ' ';
blank.Attributes = csbi.wAttributes;
while (*(PDWORD)&row[c.X] == *(PDWORD)&blank)
if (++c.X == s.X)
{
nl = (csbi.dwCursorPosition.X == 0) ? NULL : L"\r";
break;
}
free( row );
}
fWrapped = FALSE;
}
if (nl)
WriteConsole( hConOut, nl, 1, &nWritten, NULL );
}
}
else
{
if (shifted && c >= FIRST_G1 && c <= LAST_G1)
c = G1[c-FIRST_G1];
ChBuffer[nCharInBuffer] = c;
if (++nCharInBuffer == BUFFER_SIZE)
FlushBuffer();
}
}
//-----------------------------------------------------------------------------
// SendSequence( LPTSTR seq )
// Send the string to the input buffer.
//-----------------------------------------------------------------------------
void SendSequence( LPTSTR seq )
{
DWORD out;
INPUT_RECORD in;
HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
in.EventType = KEY_EVENT;
in.Event.KeyEvent.bKeyDown = TRUE;
in.Event.KeyEvent.wRepeatCount = 1;
in.Event.KeyEvent.wVirtualKeyCode = 0;
in.Event.KeyEvent.wVirtualScanCode = 0;
in.Event.KeyEvent.dwControlKeyState = 0;
for (; *seq; ++seq)
{
in.Event.KeyEvent.uChar.UnicodeChar = *seq;
WriteConsoleInput( hStdIn, &in, 1, &out );
}
}
// ========== Print functions
//-----------------------------------------------------------------------------
// InterpretEscSeq()
// Interprets the last escape sequence scanned by ParseAndPrintString
// prefix escape sequence prefix
// es_argc escape sequence args count
// es_argv[] escape sequence args array
// suffix escape sequence suffix
//
// for instance, with \e[33;45;1m we have
// prefix = '[',
// es_argc = 3, es_argv[0] = 33, es_argv[1] = 45, es_argv[2] = 1
// suffix = 'm'
//-----------------------------------------------------------------------------
void InterpretEscSeq( void )
{
int i;
WORD attribut;
CONSOLE_SCREEN_BUFFER_INFO Info;
CONSOLE_CURSOR_INFO CursInfo;
DWORD len, NumberOfCharsWritten;
COORD Pos;
SMALL_RECT Rect;
CHAR_INFO CharInfo;
DWORD mode;
#define WIDTH Info.dwSize.X
#define CUR Info.dwCursorPosition
#define WIN Info.srWindow
#define TOP WIN.Top
#define BOTTOM WIN.Bottom
#define LEFT 0
#define RIGHT (WIDTH - 1)
#define FillBlank( len, Pos ) \
FillConsoleOutputCharacter( hConOut, ' ', len, Pos, &NumberOfCharsWritten );\
FillConsoleOutputAttribute( hConOut, Info.wAttributes, len, Pos, \
&NumberOfCharsWritten )
if (prefix == '[')
{
if (prefix2 == '?' && (suffix == 'h' || suffix == 'l') && es_argc == 1)
{
switch (es_argv[0])
{
case 25:
GetConsoleCursorInfo( hConOut, &CursInfo );
CursInfo.bVisible = (suffix == 'h');
SetConsoleCursorInfo( hConOut, &CursInfo );
return;
case 7:
mode = ENABLE_PROCESSED_OUTPUT;
if (suffix == 'h')
mode |= ENABLE_WRAP_AT_EOL_OUTPUT;
SetConsoleMode( hConOut, mode );
return;
}
}
// Ignore any other private sequences.
if (prefix2 != 0)
return;
GetConsoleScreenBufferInfo( hConOut, &Info );
switch (suffix)
{
case 'm':
if (es_argc == 0) es_argv[es_argc++] = 0;
for (i = 0; i < es_argc; i++)
{
if (30 <= es_argv[i] && es_argv[i] <= 37)
{
pState->foreground = es_argv[i] - 30;
}
else if (40 <= es_argv[i] && es_argv[i] <= 47)
{
pState->background = es_argv[i] - 40;
}
else if (es_argv[i] == 38 || es_argv[i] == 48)
{
// This is technically incorrect, but it's what xterm does, so
// that's what we do. According to T.416 (ISO 8613-6), there is
// only one parameter, which is divided into elements. So where
// xterm does "38;2;R;G;B" it should really be "38;2:I:R:G:B" (I is
// a colour space identifier).
if (i+1 < es_argc)
{
if (es_argv[i+1] == 2) // rgb
i += 4;
else if (es_argv[i+1] == 5) // index
i += 2;
}
}
else switch (es_argv[i])
{
case 0:
case 39:
case 49:
{
TCHAR def[4];
int a;
*def = '7'; def[1] = '\0';
GetEnvironmentVariable( L"ANSICON_DEF", def, lenof(def) );
a = wcstol( def, NULL, 16 );
pState->reverse = FALSE;
if (a < 0)
{
pState->reverse = TRUE;
a = -a;
}
if (es_argv[i] != 49)
pState->foreground = attr2ansi[a & 7];
if (es_argv[i] != 39)
pState->background = attr2ansi[(a >> 4) & 7];
if (es_argv[i] == 0)
{
if (es_argc == 1)
{
pState->bold = a & FOREGROUND_INTENSITY;
pState->underline = a & BACKGROUND_INTENSITY;
}
else
{
pState->bold = 0;
pState->underline = 0;
}
pState->rvideo = 0;
pState->concealed = 0;
}
}
break;
case 1: pState->bold = FOREGROUND_INTENSITY; break;
case 5: // blink
case 4: pState->underline = BACKGROUND_INTENSITY; break;
case 7: pState->rvideo = 1; break;
case 8: pState->concealed = 1; break;
case 21: // oops, this actually turns on double underline
// but xterm turns off bold too, so that's alright
case 22: pState->bold = 0; break;
case 25:
case 24: pState->underline = 0; break;
case 27: pState->rvideo = 0; break;
case 28: pState->concealed = 0; break;
}
}
if (pState->concealed)
{
if (pState->rvideo)
{
attribut = foregroundcolor[pState->foreground]
| backgroundcolor[pState->foreground];
if (pState->bold)
attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
else
{
attribut = foregroundcolor[pState->background]
| backgroundcolor[pState->background];
if (pState->underline)
attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
}
else if (pState->rvideo)
{
attribut = foregroundcolor[pState->background]
| backgroundcolor[pState->foreground];
if (pState->bold)
attribut |= BACKGROUND_INTENSITY;
if (pState->underline)
attribut |= FOREGROUND_INTENSITY;
}
else
attribut = foregroundcolor[pState->foreground] | pState->bold
| backgroundcolor[pState->background] | pState->underline;
if (pState->reverse)
attribut = ((attribut >> 4) & 15) | ((attribut & 15) << 4);
SetConsoleTextAttribute( hConOut, attribut );
return;
case 'J':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0J erase from cursor to end of display
len = (BOTTOM - CUR.Y) * WIDTH + WIDTH - CUR.X;
FillBlank( len, CUR );
return;
case 1: // ESC[1J erase from start to cursor.
Pos.X = 0;
Pos.Y = TOP;
len = (CUR.Y - TOP) * WIDTH + CUR.X + 1;
FillBlank( len, Pos );
return;
case 2: // ESC[2J Clear screen and home cursor
if (TOP != screen_top || BOTTOM == Info.dwSize.Y - 1)
{
// Rather than clearing the existing window, make the current
// line the new top of the window (assuming this is the first
// thing a program does).
int range = BOTTOM - TOP;
if (CUR.Y + range < Info.dwSize.Y)
{
TOP = CUR.Y;
BOTTOM = TOP + range;
}
else
{
BOTTOM = Info.dwSize.Y - 1;
TOP = BOTTOM - range;
Rect.Left = LEFT;
Rect.Right = RIGHT;
Rect.Top = CUR.Y - TOP;
Rect.Bottom = CUR.Y - 1;
Pos.X = Pos.Y = 0;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo);
}
SetConsoleWindowInfo( hConOut, TRUE, &WIN );
screen_top = TOP;
}
Pos.X = LEFT;
Pos.Y = TOP;
len = (BOTTOM - TOP + 1) * WIDTH;
FillBlank( len, Pos );
// Not technically correct, but perhaps expected.
SetConsoleCursorPosition( hConOut, Pos );
return;
default:
return;
}
case 'K':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0K Clear to end of line
len = WIDTH - CUR.X;
FillBlank( len, CUR );
return;
case 1: // ESC[1K Clear from start of line to cursor
Pos.X = LEFT;
Pos.Y = CUR.Y;
FillBlank( CUR.X + 1, Pos );
return;
case 2: // ESC[2K Clear whole line.
Pos.X = LEFT;
Pos.Y = CUR.Y;
FillBlank( WIDTH, Pos );
return;
default:
return;
}
case 'X': // ESC[#X Erase # characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[X == ESC[1X
if (es_argc != 1) return;
FillBlank( es_argv[0], CUR );
return;
case 'L': // ESC[#L Insert # blank lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L
if (es_argc != 1) return;
Rect.Left = WIN.Left = LEFT;
Rect.Right = WIN.Right = RIGHT;
Rect.Top = CUR.Y;
Rect.Bottom = BOTTOM;
Pos.X = LEFT;
Pos.Y = CUR.Y + es_argv[0];
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, &WIN, Pos, &CharInfo );
// Technically should home the cursor, but perhaps not expected.
return;
case 'M': // ESC[#M Delete # lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M
if (es_argc != 1) return;
Rect.Left = WIN.Left = LEFT;
Rect.Right = WIN.Right = RIGHT;
Rect.Bottom = BOTTOM;
Rect.Top = CUR.Y - es_argv[0];
Pos.X = LEFT;
Pos.Y = TOP = CUR.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, &WIN, Pos, &CharInfo );
// Technically should home the cursor, but perhaps not expected.
return;
case 'P': // ESC[#P Delete # characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P
if (es_argc != 1) return;
Rect.Left = WIN.Left = CUR.X;
Rect.Right = WIN.Right = RIGHT;
Pos.X = CUR.X - es_argv[0];
Pos.Y =
Rect.Top =
Rect.Bottom = CUR.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, &WIN, Pos, &CharInfo );
return;
case '@': // ESC[#@ Insert # blank characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@
if (es_argc != 1) return;
Rect.Left = WIN.Left = CUR.X;
Rect.Right = WIN.Right = RIGHT;
Pos.X = CUR.X + es_argv[0];
Pos.Y =
Rect.Top =
Rect.Bottom = CUR.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, &WIN, Pos, &CharInfo );
return;
case 'k': // ESC[#k
case 'A': // ESC[#A Moves cursor up # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A
if (es_argc != 1) return;
Pos.Y = CUR.Y - es_argv[0];
if (Pos.Y < TOP) Pos.Y = TOP;
Pos.X = CUR.X;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'e': // ESC[#e
case 'B': // ESC[#B Moves cursor down # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B
if (es_argc != 1) return;
Pos.Y = CUR.Y + es_argv[0];
if (Pos.Y > BOTTOM) Pos.Y = BOTTOM;
Pos.X = CUR.X;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'a': // ESC[#a
case 'C': // ESC[#C Moves cursor forward # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C
if (es_argc != 1) return;
Pos.X = CUR.X + es_argv[0];
if (Pos.X > RIGHT) Pos.X = RIGHT;
Pos.Y = CUR.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'j': // ESC[#j
case 'D': // ESC[#D Moves cursor back # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D
if (es_argc != 1) return;
Pos.X = CUR.X - es_argv[0];
if (Pos.X < LEFT) Pos.X = LEFT;
Pos.Y = CUR.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'E': // ESC[#E Moves cursor down # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E
if (es_argc != 1) return;
Pos.Y = CUR.Y + es_argv[0];
if (Pos.Y > BOTTOM) Pos.Y = BOTTOM;
Pos.X = LEFT;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'F': // ESC[#F Moves cursor up # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F
if (es_argc != 1) return;
Pos.Y = CUR.Y - es_argv[0];
if (Pos.Y < TOP) Pos.Y = TOP;
Pos.X = LEFT;
SetConsoleCursorPosition( hConOut, Pos );
return;
case '`': // ESC[#`
case 'G': // ESC[#G Moves cursor column # in current row.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G
if (es_argc != 1) return;
Pos.X = es_argv[0] - 1;
if (Pos.X > RIGHT) Pos.X = RIGHT;
if (Pos.X < LEFT) Pos.X = LEFT;
Pos.Y = CUR.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'd': // ESC[#d Moves cursor row #, current column.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[d == ESC[1d
if (es_argc != 1) return;
Pos.Y = es_argv[0] - 1;
if (Pos.Y < TOP) Pos.Y = TOP;
if (Pos.Y > BOTTOM) Pos.Y = BOTTOM;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'f': // ESC[#;#f
case 'H': // ESC[#;#H Moves cursor to line #, column #
if (es_argc == 0)
es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H
if (es_argc == 1)
es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H
if (es_argc > 2) return;
Pos.X = es_argv[1] - 1;
if (Pos.X < LEFT) Pos.X = LEFT;
if (Pos.X > RIGHT) Pos.X = RIGHT;
Pos.Y = es_argv[0] - 1;
if (Pos.Y < TOP) Pos.Y = TOP;
if (Pos.Y > BOTTOM) Pos.Y = BOTTOM;
SetConsoleCursorPosition( hConOut, Pos );
return;