-
Notifications
You must be signed in to change notification settings - Fork 130
/
ANSI.c
4197 lines (3816 loc) · 114 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.
v1.71, 23 October, 2015:
add _CRT_NON_CONFORMING_WCSTOK define for VS2015.
v1.72, 14 to 24 December, 2015:
recognize the standard handle defines in WriteFile;
minor speed improvement by caching GetConsoleMode;
keep track of three handles (ostensibly stdout, stderr and a file);
test a DOS header exists before writing to e_oemid;
more flexible/robust handling of data directories;
files writing to the console will always succeed;
log: use API file functions and a custom printf;
add a blank line between processes;
set function name for MyWriteConsoleA;
scan imports from "kernel32" (without extension);
added dynamic environment variable CLICOLOR;
removed _hwrite (it's the same address as _lwrite);
join multibyte characters split across separate writes;
remove wcstok, avoiding potential interference with the host;
similarly, use a private heap instead of malloc.
v1.80, 26 October to 24 December, 2017:
fix unloading;
revert back to (re)storing buffer cursor position;
increase cache to five handles;
hook CreateFile & CreateConsoleScreenBuffer to enable readable handles;
fix cursor report with duplicated digits (e.g. "11" was just "1");
preserve escape that isn't part of a sequence;
fix escape followed by CRM in control mode;
use the system default sound for the bell;
add DECPS Play Sound;
use intermediate byte '+' to use buffer, not window;
ESC followed by a control character will display that character;
added palette sequences;
change the scan lines in the graphics set to their actual Unicode chars;
added IND, NEL & RI (using buffer, in keeping with LF);
added DA, DECCOLM, DECNCSM, DECSC & DECRC (with SGR & G0);
partially support SCS (just G0 as DEC special & ASCII);
an explicit zero parameter should still default to one;
restrict parameters to a maximum value of 32767;
added tab handling;
added the bright SGR colors, recognised the system indices;
added insert mode;
BS/CR/CUB/HPB after wrap will move back to the previous line(s);
added DECOM, DECSTBM, SD & SU;
only flush before accessing the console, adding a mode to flush immediately;
added DECSTR & RIS;
fix state problems with windowless processes.
v1.81, 26 to 28 December, 2017:
combine multiple CRs as one (to ignore all CRs before LF);
don't process CR or BS during CRM;
don't flush CR immediately (to catch following LF);
fix CRM with all partial RM sequences;
check for the empty buffer within the critical section;
palette improvements.
v1.82, 12 & 13 February, 2018:
add ANSICON_WRAP environment variable for programs that expect the wrap;
flush and invalidate the cache on CloseHandle;
make IsConsoleHandle a critical section, for multithreaded processes;
use APIConsole for all console functions (needed for Windows 10).
v1.83, 16 February, 2018:
create the flush thread on first use.
v1.84, 17 February, 26 April to 10 May, 2018:
close the flush handles on detach;
dynamically load WINMM.DLL;
remove dependency on the CRT and USER32.DLL;
replace bsearch (in procrva.c) with specific code;
if the primary thread is detached exit the process;
get real WriteFile handle before testing for console;
use remote load on Win8+ when the process has no IAT;
increase heap to 256KiB to fix logging of really long command lines;
default to 7 or -7 if ANSICON_DEF could not be parsed;
scrolling will use the default attribute for new lines;
workaround Windows 10 1803 console bug.
v1.85, 22 & 23 August, 2018:
fix creating the wrap buffer;
always inject from ansicon.exe, even if it's GUI or excluded;
log CreateFile calls;
preserve last error.
v1.86, 4 November, 2018:
always unhook, even on terminate;
check the DLL still exists before adding to imports.
v1.87, 3 February, 2019:
some hooked functions are not imported, so myimport wasn't set;
add missing SetCurrentConsoleFontEx to list of hooks.
v1.88, 1 March, 2019:
a detached process has no console handle (fixes set_ansicon).
v1.89, 29 April, 2019:
an eight-digit window handle would break my custom printf.
*/
#include "ansicon.h"
#include "version.h"
#include <mmsystem.h>
#ifndef SND_SENTRY
#define SND_SENTRY 0x80000
#endif
#undef PlaySound
typedef BOOL (WINAPI *FnPlaySound)( LPCWSTR, HMODULE, DWORD );
FnPlaySound PlaySound;
HMODULE winmm;
#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
HANDLE hHeap; // local memory heap
HANDLE hBell, hFlush;
BOOL ansicon; // are we in ansicon.exe?
#define CACHE 5
struct Cache
{
HANDLE h;
DWORD mode;
} cache[CACHE];
#define ESC '\x1B' // ESCape character
#define BEL '\x07' // BELl
#define HT '\x09' // Horizontal Tabulation
#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 ( one of '<=>?' );
TCHAR suffix; // escape sequence final byte
TCHAR suffix2; // escape sequence intermediate byte
int ibytes; // count of intermediate bytes
int es_argc; // escape sequence args count
int es_argv[MAX_ARG]; // escape sequence args
TCHAR Pt_arg[4096]; // text parameter for Operating System Command
int Pt_len;
BOOL shifted, G0_special, SaveG0;
BOOL wm = FALSE; // does program detect wrap itself?
BOOL awm = TRUE; // autowrap mode
BOOL im; // insert mode
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'\x23ba', // o - Horizontal Scan Line-1
L'\x23bb', // p - Horizontal Scan Line-3
L'\x2500', // q - Box Drawings Light Horizontal (SCAN 5)
L'\x23bc', // r - Horizontal Scan Line-7
L'\x23bd', // s - Horizontal Scan Line-9
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[16] =
{
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
FOREGROUND_INTENSITY | FOREGROUND_BLACK,
FOREGROUND_INTENSITY | FOREGROUND_RED,
FOREGROUND_INTENSITY | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_BLUE,
FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_RED,
FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_WHITE
};
const BYTE backgroundcolor[16] =
{
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
BACKGROUND_INTENSITY | BACKGROUND_BLACK,
BACKGROUND_INTENSITY | BACKGROUND_RED,
BACKGROUND_INTENSITY | BACKGROUND_GREEN,
BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN,
BACKGROUND_INTENSITY | BACKGROUND_BLUE,
BACKGROUND_INTENSITY | BACKGROUND_BLUE | BACKGROUND_RED,
BACKGROUND_INTENSITY | BACKGROUND_BLUE | BACKGROUND_GREEN,
BACKGROUND_INTENSITY | BACKGROUND_WHITE
};
const BYTE attr2ansi[16] = // map console attribute to ANSI number
{ // or vice versa
0, // black
4, // blue
2, // green
6, // cyan
1, // red
5, // magenta
3, // yellow
7, // white
8, // bright black
12, // bright blue
10, // bright green
14, // bright cyan
9, // bright red
13, // bright magenta
11, // bright yellow
15, // bright white
};
typedef struct _CONSOLE_SCREEN_BUFFER_INFOX {
ULONG cbSize;
COORD dwSize;
COORD dwCursorPosition;
WORD wAttributes;
SMALL_RECT srWindow;
COORD dwMaximumWindowSize;
WORD wPopupAttributes;
BOOL bFullscreenSupported;
COLORREF ColorTable[16];
} CONSOLE_SCREEN_BUFFER_INFOX, *PCONSOLE_SCREEN_BUFFER_INFOX;
typedef BOOL (WINAPI *PHCSBIX)(
HANDLE hConsoleOutput,
PCONSOLE_SCREEN_BUFFER_INFOX lpConsoleScreenBufferInfoEx
);
PHCSBIX GetConsoleScreenBufferInfoX, SetConsoleScreenBufferInfoX;
BOOL WINAPI GetConsoleScreenBufferInfoEx_repl( HANDLE h,
PCONSOLE_SCREEN_BUFFER_INFOX i )
{
return FALSE;
}
typedef struct _CONSOLE_FONT_INFOX {
ULONG cbSize;
DWORD nFont;
COORD dwFontSize;
UINT FontFamily;
UINT FontWeight;
WCHAR FaceName[LF_FACESIZE];
} CONSOLE_FONT_INFOX, *PCONSOLE_FONT_INFOX;
typedef BOOL (WINAPI *PHBCFIX)(
HANDLE hConsoleOutput,
BOOL bMaximumWindow,
PCONSOLE_FONT_INFOX lpConsoleCurrentFontEx
);
PHBCFIX SetCurrentConsoleFontX;
// Reduce verbosity.
#define CURPOS dwCursorPosition
#define ATTR Info.wAttributes
#define WIDTH Info.dwSize.X
#define HEIGHT Info.dwSize.Y
#define CUR Info.CURPOS
#define WIN Info.srWindow
#define TOP WIN.Top
#define BOTTOM WIN.Bottom
#define LAST (HEIGHT - 1)
#define LEFT 0
#define RIGHT (WIDTH - 1)
#define MAX_TABS 2048
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
} SGR;
SGR orgsgr; // original SGR
typedef struct
{
SGR sgr, SaveSgr;
WORD SaveAttr;
BYTE fm; // flush mode
BYTE crm; // showing control characters?
BYTE om; // origin mode
BYTE tb_margins; // top/bottom margins set?
SHORT top_margin;
SHORT bot_margin;
COORD SavePos; // saved cursor position
COLORREF o_palette[16]; // original palette, for resetting
COLORREF x_palette[240]; // xterm 256-color palette, less 16 system colors
SHORT buf_width; // buffer width prior to setting 132 columns
SHORT win_width; // window width prior to setting 132 columns
BYTE noclear; // don't clear the screen on column mode change
BYTE tabs; // handle tabs directly
BYTE tab_stop[MAX_TABS];
} STATE, *PSTATE;
STATE default_state; // for when there's no window or file mapping
PSTATE pState = &default_state;
BOOL valid_state;
HANDLE hMap;
#include "palette.h"
void set_ansicon( PCONSOLE_SCREEN_BUFFER_INFO );
void get_state( void )
{
TCHAR buf[64];
HWND hwnd;
BOOL init;
HANDLE hConOut;
CONSOLE_SCREEN_BUFFER_INFO Info;
CONSOLE_SCREEN_BUFFER_INFOX csbix;
if (valid_state)
return;
hwnd = GetConsoleWindow();
if (hwnd == NULL)
return;
valid_state = TRUE;
ac_wprintf( buf, "ANSICON_State_%X", PtrToUint( hwnd ) );
hMap = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
0, sizeof(STATE), buf );
init = (GetLastError() != ERROR_ALREADY_EXISTS);
pState = MapViewOfFile( hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0 );
if (pState == NULL)
{
DEBUGSTR( 1, "File mapping failed (%u) - using default state",
GetLastError() );
pState = &default_state;
CloseHandle( hMap );
hMap = NULL;
}
if (init)
{
hConOut = CreateFile( L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL );
csbix.cbSize = sizeof(csbix);
if (GetConsoleScreenBufferInfoX( hConOut, &csbix ))
{
arrcpy( pState->o_palette, csbix.ColorTable );
ATTR = csbix.wAttributes;
}
else
{
arrcpy( pState->o_palette, legacy_palette );
if (!GetConsoleScreenBufferInfo( hConOut, &Info ))
ATTR = 7;
}
arrcpy( pState->x_palette, xterm_palette );
pState->sgr.foreground = attr2ansi[ATTR & 7];
pState->sgr.background = attr2ansi[(ATTR >> 4) & 7];
pState->sgr.bold = ATTR & FOREGROUND_INTENSITY;
pState->sgr.underline = ATTR & BACKGROUND_INTENSITY;
CloseHandle( hConOut );
}
if (!GetEnvironmentVariable( L"ANSICON_DEF", NULL, 0 ))
{
TCHAR def[4];
LPTSTR a = def;
hConOut = CreateFile( L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL );
if (!GetConsoleScreenBufferInfo( hConOut, &Info ))
{
RtlZeroMemory( &Info, sizeof(Info) );
ATTR = 7;
}
if (pState->sgr.reverse)
{
*a++ = '-';
ATTR = ((ATTR >> 4) & 15) | ((ATTR & 15) << 4);
}
ac_wprintf( a, "%X", ATTR & 255 );
SetEnvironmentVariable( L"ANSICON_DEF", def );
set_ansicon( &Info );
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;
LPTSTR end;
len = GetEnvironmentVariable( var, env, env_len );
if (len == 0)
return FALSE;
if (len > env_len)
{
LPTSTR tmp = (env == NULL) ? HeapAlloc( hHeap, 0, TSIZE(len) )
: HeapReAlloc( hHeap, 0, env, TSIZE(len) );
if (tmp == NULL)
return FALSE;
env = tmp;
env_len = (DWORD)HeapSize( hHeap, 0, env );
GetEnvironmentVariable( var, env, env_len );
}
not = (*env == '!');
if (not && env[1] == '\0')
return TRUE;
end = env + not;
while (*end != '\0')
{
var = end;
do
{
if (*end++ == ';')
{
end[-1] = '\0';
break;
}
} while (*end != '\0');
if (lstrcmpi( val, var ) == 0)
return !not;
}
return not;
}
// ========== Print Buffer functions
#define BUFFER_SIZE 2048
int nCharInBuffer;
WCHAR ChBuffer[BUFFER_SIZE];
WCHAR ChPrev;
int nWrapped;
CRITICAL_SECTION CritSect;
HANDLE hFlushTimer;
void MoveDown( BOOL home );
// Well, this is annoying. Setting the cursor position on any buffer always
// displays the cursor on the active buffer (at least on 7). Since there's no
// way to tell which buffer is active (hooking SetConsoleActiveScreenBuffer
// isn't sufficient, since multiple handles could refer to the same buffer),
// hide the cursor, do the move and restore the cursor.
BOOL SetConsoleCursorPos( HANDLE hConsoleOutput, COORD dwCursorPosition )
{
CONSOLE_CURSOR_INFO CursInfo;
BOOL rc;
GetConsoleCursorInfo( hConsoleOutput, &CursInfo );
if (CursInfo.bVisible)
{
CursInfo.bVisible = FALSE;
SetConsoleCursorInfo( hConsoleOutput, &CursInfo );
rc = SetConsoleCursorPosition( hConsoleOutput, dwCursorPosition );
CursInfo.bVisible = TRUE;
SetConsoleCursorInfo( hConsoleOutput, &CursInfo );
}
else
rc = SetConsoleCursorPosition( hConsoleOutput, dwCursorPosition );
return rc;
}
// Set the cursor position, resetting the wrap flag.
void set_pos( int x, int y )
{
COORD pos = { x, y };
SetConsoleCursorPos( hConOut, pos );
nWrapped = 0;
}
// Get the default attribute, as-is if !ATTR (i.e. preserve negative), else for
// the console (swap foreground/background if negative).
int get_default_attr( BOOL attr )
{
TCHAR def[4];
int a;
*def = '7'; def[1] = '\0';
GetEnvironmentVariable( L"ANSICON_DEF", def, lenof(def) );
a = ac_wcstol( def, NULL, 16 );
if (a == 0)
a = (*def == '-') ? -7 : 7;
if (a > 0 || !attr)
return a;
a = -a;
return ((a >> 4) & 15) | ((a & 15) << 4);
}
//-----------------------------------------------------------------------------
// FlushBuffer()
// Writes the buffer to the console and empties it.
//-----------------------------------------------------------------------------
void FlushBuffer( void )
{
DWORD nWritten;
EnterCriticalSection( &CritSect );
if (nCharInBuffer <= 0)
{
LeaveCriticalSection( &CritSect );
return;
}
if ((wm || !awm) && !im && !pState->tb_margins)
{
if (pState->crm)
{
SetConsoleMode( hConOut, cache[0].mode & ~ENABLE_PROCESSED_OUTPUT );
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
SetConsoleMode( hConOut, cache[0].mode );
}
else
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
}
else
{
HANDLE hConWrap;
CONSOLE_CURSOR_INFO cci;
CONSOLE_SCREEN_BUFFER_INFO Info, wi;
if (nCharInBuffer < 4 && !im && !pState->tb_margins)
{
LPWSTR b = ChBuffer;
if (pState->crm)
SetConsoleMode( hConOut, cache[0].mode & ~ENABLE_PROCESSED_OUTPUT );
do
{
WriteConsole( hConOut, b, 1, &nWritten, NULL );
if (pState->crm || (*b != '\r' && *b != '\b' && *b != '\a'))
{
GetConsoleScreenBufferInfo( hConOut, &Info );
if (CUR.X == 0)
++nWrapped;
}
} while (++b, --nCharInBuffer);
if (pState->crm)
SetConsoleMode( hConOut, cache[0].mode );
}
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 contains sufficient lines.
GetConsoleScreenBufferInfo( hConOut, &Info );
wi.dwSize.X = WIDTH;
wi.dwSize.Y = 0;
if (WIN.Right - WIN.Left + 1 != WIDTH)
wi.dwSize.Y = BOTTOM - TOP + 1;
if (BOTTOM - TOP < 2 * nCharInBuffer / WIDTH)
wi.dwSize.Y = 2 * nCharInBuffer / WIDTH + 1;
if (wi.dwSize.Y)
SetConsoleScreenBufferSize( hConWrap, wi.dwSize );
// Put the cursor on the top line, in the same column.
wi.CURPOS.X = CUR.X;
wi.CURPOS.Y = 0;
SetConsoleCursorPosition( hConWrap, wi.CURPOS );
if (pState->crm)
SetConsoleMode( hConWrap, (awm) ? ENABLE_WRAP_AT_EOL_OUTPUT : 0 );
else if (!awm)
SetConsoleMode( hConWrap, ENABLE_PROCESSED_OUTPUT );
else if (cache[0].mode & 4) // ENABLE_VIRTUAL_TERMINAL_PROCESSING
{
// Windows 10 1803 writes to the active buffer if VT is enabled.
SetConsoleMode( hConWrap, cache[0].mode & ~4 );
}
WriteConsole( hConWrap, ChBuffer, nCharInBuffer, &nWritten, NULL );
GetConsoleScreenBufferInfo( hConWrap, &wi );
if (pState->tb_margins && CUR.Y + wi.CURPOS.Y > TOP + pState->bot_margin)
{
if (CUR.Y > TOP + pState->bot_margin)
{
// If we're at the bottom of the window, outside the margins, then
// just keep overwriting the last line.
if (CUR.Y + wi.CURPOS.Y > BOTTOM)
{
PCHAR_INFO row = HeapAlloc( hHeap, 0, WIDTH * sizeof(CHAR_INFO) );
if (row != NULL)
{
COORD s, c;
SMALL_RECT r;
s.X = WIDTH;
s.Y = 1;
c.X = c.Y = 0;
for (r.Top = 0; r.Top <= wi.CURPOS.Y; ++r.Top)
{
if (r.Top == 0)
{
r.Left = CUR.X;
r.Right = RIGHT;
}
else if (r.Top == wi.CURPOS.Y)
{
r.Left = LEFT;
r.Right = wi.CURPOS.X - 1;
}
else
{
r.Left = LEFT;
r.Right = RIGHT;
}
r.Bottom = r.Top;
ReadConsoleOutput( hConWrap, row, s, c, &r );
r.Top = r.Bottom = CUR.Y;
WriteConsoleOutput( hConOut, row, s, c, &r );
if (CUR.Y != BOTTOM)
++CUR.Y;
}
HeapFree( hHeap, 0, row );
CloseHandle( hConWrap );
nWrapped = 0;
goto done;
}
}
}
else if (wi.CURPOS.Y > pState->bot_margin - pState->top_margin)
{
// The line is bigger than the scroll region, copy that portion.
PCHAR_INFO row = HeapAlloc( hHeap, 0,
(pState->bot_margin - pState->top_margin + 1)
* WIDTH * sizeof(CHAR_INFO) );
if (row != NULL)
{
COORD s, c;
SMALL_RECT r;
s.X = WIDTH;
s.Y = pState->bot_margin - pState->top_margin + 1;
c.X = c.Y = 0;
r.Left = LEFT;
r.Right = RIGHT;
r.Bottom = wi.CURPOS.Y;
r.Top = r.Bottom - (pState->bot_margin - pState->top_margin);
ReadConsoleOutput( hConWrap, row, s, c, &r );
r.Top = TOP + pState->top_margin;
r.Bottom = TOP + pState->bot_margin;
WriteConsoleOutput( hConOut, row, s, c, &r );
HeapFree( hHeap, 0, row );
CloseHandle( hConWrap );
nWrapped = pState->bot_margin - pState->top_margin;
goto done;
}
}
else
{
// Scroll the region, then write as normal.
SMALL_RECT sr;
COORD c;
CHAR_INFO ci;
ci.Char.UnicodeChar = ' ';
ci.Attributes = get_default_attr( TRUE );
c.X =
sr.Left = LEFT;
sr.Right = RIGHT;
sr.Top = TOP + pState->top_margin;
sr.Bottom = TOP + pState->bot_margin;
c.Y = sr.Top - wi.CURPOS.Y;
ScrollConsoleScreenBuffer( hConOut, &sr, &sr, c, &ci );
CUR.Y -= wi.CURPOS.Y;
SetConsoleCursorPos( hConOut, CUR );
}
}
nWrapped += wi.CURPOS.Y;
CloseHandle( hConWrap );
if (im && !nWrapped)
{
SMALL_RECT sr, cr;
CHAR_INFO ci; // unused, but necessary
cr.Top = cr.Bottom = sr.Top = sr.Bottom = CUR.Y;
cr.Right = sr.Right = RIGHT;
sr.Left = CUR.X;
cr.Left = CUR.X = wi.CURPOS.X;
ScrollConsoleScreenBuffer( hConOut, &sr, &cr, CUR, &ci );
}
else if (nWrapped && CUR.Y + nWrapped > LAST)
{
// The buffer is going to scroll; do it manually in order to use the
// default attribute, not current.
SMALL_RECT sr;
COORD c;
CHAR_INFO ci;
ci.Char.UnicodeChar = ' ';
ci.Attributes = get_default_attr( TRUE );
c.X =
sr.Left = LEFT;
sr.Right = RIGHT;
sr.Top = 0;
sr.Bottom = LAST;
c.Y = -wi.CURPOS.Y;
ScrollConsoleScreenBuffer( hConOut, &sr, &sr, c, &ci );
CUR.Y -= wi.CURPOS.Y;
SetConsoleCursorPos( hConOut, CUR );
}
if (pState->crm)
{
SetConsoleMode( hConOut, cache[0].mode & ~ENABLE_PROCESSED_OUTPUT );
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
SetConsoleMode( hConOut, cache[0].mode );
}
else
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
}
}
done:
nCharInBuffer = 0;
LeaveCriticalSection( &CritSect );
}
//-----------------------------------------------------------------------------
// PushBuffer( WCHAR c )
// Adds a character in the buffer.
//-----------------------------------------------------------------------------
void PushBuffer( WCHAR c )
{
CONSOLE_SCREEN_BUFFER_INFO Info;
ChPrev = c;
if (c == '\n')
{
if (pState->crm)
ChBuffer[nCharInBuffer++] = c;
FlushBuffer();
if (wm)
{
MoveDown( TRUE );
return;
}
// Avoid writing the newline if wrap has already occurred.
GetConsoleScreenBufferInfo( hConOut, &Info );
if (pState->crm)
{
// If we're displaying controls, then the only way we can be on the left
// margin is if wrap occurred.
if (CUR.X != 0)
MoveDown( TRUE );
}
else
{
BOOL nl = TRUE;
if (nWrapped)
{
// 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 = HeapAlloc( hHeap, 0, WIDTH * sizeof(CHAR_INFO) );
if (row != NULL)
{
COORD s, c;
SMALL_RECT r;
s.X = WIDTH;
s.Y = 1;
c.X = c.Y = 0;
r.Left = LEFT;
r.Right = RIGHT;
r.Top = r.Bottom = CUR.Y;
ReadConsoleOutput( hConOut, row, s, c, &r );
blank.Char.UnicodeChar = ' ';
blank.Attributes = ATTR;
while (*(PDWORD)&row[c.X] == *(PDWORD)&blank)
{
if (++c.X == s.X)
{
if (CUR.X != 0)
{
CUR.X = 0;
SetConsoleCursorPos( hConOut, CUR );