Repository navigation
Expand file tree
/
Copy pathConsoleHandler.cpp
More file actions
2133 lines (1732 loc) · 62.7 KB
/
Copy pathConsoleHandler.cpp
File metadata and controls
2133 lines (1732 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#include "../shared/SharedMemNames.h"
#include "ConsoleHandler.h"
#define GET_STD_OUT_READ_ONLY StdOutHandle hStdOut(true); if( hStdOut == INVALID_HANDLE_VALUE ) return;
#define GET_STD_OUT_READ_WRITE StdOutHandle hStdOut(false); if( hStdOut == INVALID_HANDLE_VALUE ) return;
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ConsoleHandler::ConsoleHandler()
: m_consoleParams()
, m_consoleInfo()
, m_cursorInfo()
, m_consoleBuffer()
, m_consoleCopyInfo()
, m_consoleMouseEvent()
, m_newConsoleSize()
, m_newScrollPos()
, m_hMonitorThread()
, m_hMonitorThreadExit(std::shared_ptr<void>(::CreateEvent(NULL, FALSE, FALSE, NULL), ::CloseHandle))
, m_dwScreenBufferSize(0)
, m_dwWaitingTime(INFINITE)
, m_timePoint(std::chrono::system_clock::now())
, m_hStdOut(true)
{
m_szConsoleTitle[0] = 0;
}
ConsoleHandler::~ConsoleHandler()
{
StopMonitorThread();
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
DWORD ConsoleHandler::StartMonitorThread()
{
DWORD dwThreadId = 0;
m_hMonitorThread = std::shared_ptr<void>(
::CreateThread(
NULL,
0,
MonitorThreadStatic,
reinterpret_cast<void*>(this),
0,
&dwThreadId),
::CloseHandle);
return dwThreadId;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void ConsoleHandler::StopMonitorThread()
{
::SetEvent(m_hMonitorThreadExit.get());
::WaitForSingleObject(m_hMonitorThread.get(), 10000);
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ConsoleHandler::OpenSharedObjects()
{
try
{
// open startup params memory object
DWORD dwProcessId = ::GetCurrentProcessId();
// TODO: error handling
m_consoleParams.Open((SharedMemNames::formatConsoleParams % dwProcessId).str(), syncObjRequest);
// open console info shared memory object
m_consoleInfo.Open((SharedMemNames::formatInfo % dwProcessId).str(), syncObjRequest);
// open console info shared memory object
m_cursorInfo.Open((SharedMemNames::formatCursorInfo % dwProcessId).str(), syncObjRequest);
// open console buffer shared memory object
m_consoleBuffer.Open((SharedMemNames::formatBuffer % dwProcessId).str(), syncObjRequest);
// copy info
m_consoleCopyInfo.Open((SharedMemNames::formatCopyInfo % dwProcessId).str(), syncObjBoth);
// mouse event
m_consoleMouseEvent.Open((SharedMemNames::formatMouseEvent % dwProcessId).str(), syncObjBoth);
// open new console size shared memory object
m_newConsoleSize.Open((SharedMemNames::formatNewConsoleSize % dwProcessId).str(), syncObjRequest);
// new scroll position
m_newScrollPos.Open((SharedMemNames::formatNewScrollPos % dwProcessId).str(), syncObjRequest);
// message pipe (workaround for User Interface Privilege Isolation messages filtering)
m_consoleMsgPipe.Open((SharedMemNames::formatPipeName % dwProcessId).str());
// multiple info :
// current directory
// process list
m_multipleInfo.Open((SharedMemNames::formatMultipleInfo % dwProcessId).str(), syncObjBoth);
}
catch(Win32Exception& ex)
{
fprintf(stderr, "/!\\ ConsoleZ: can't open shared objects (reason: %s)\n", ex.what());
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void ConsoleHandler::ReadConsoleBuffer()
{
auto timePoint2 = std::chrono::system_clock::now();
DWORD dwElapsedTime = static_cast<DWORD>(
std::chrono::duration_cast<std::chrono::milliseconds>(timePoint2 - m_timePoint).count());
DWORD dwNotificationTimeout = m_consoleParams->dwNotificationTimeout;
if(dwElapsedTime >= dwNotificationTimeout)
{
// notification timeout expired
ForceReadConsoleBuffer();
}
else
{
// wait more
m_dwWaitingTime = dwNotificationTimeout - dwElapsedTime;
}
}
void ConsoleHandler::ForceReadConsoleBuffer()
{
RealReadConsoleBuffer();
m_dwWaitingTime = INFINITE;
m_timePoint = std::chrono::system_clock::now();
}
void ConsoleHandler::RealReadConsoleBuffer()
{
// we take a fresh STDOUT handle - seems to work better (in case a program
// has opened a new screen output buffer)
GET_STD_OUT_READ_ONLY
CONSOLE_SCREEN_BUFFER_INFO csbiConsole;
COORD coordConsoleSize;
if(!::GetConsoleScreenBufferInfo(hStdOut, &csbiConsole))
{
Win32Exception err("GetConsoleScreenBufferInfo", ::GetLastError());
TRACE(L"GetConsoleScreenBufferInfo(%p) returns error (%lu) : %S\n", hStdOut, err.GetErrorCode(), err.what());
return;
}
// check for inconsistent values
if(csbiConsole.srWindow.Right < csbiConsole.srWindow.Left || csbiConsole.srWindow.Bottom < csbiConsole.srWindow.Top)
return;
coordConsoleSize.X = csbiConsole.srWindow.Right - csbiConsole.srWindow.Left + 1;
coordConsoleSize.Y = csbiConsole.srWindow.Bottom - csbiConsole.srWindow.Top + 1;
/*
TRACE(L"ReadConsoleBuffer console buffer size: %ix%i\n", csbiConsole.dwSize.X, csbiConsole.dwSize.Y);
TRACE(L"ReadConsoleBuffer console rect: %ix%i - %ix%i\n", csbiConsole.srWindow.Left, csbiConsole.srWindow.Top, csbiConsole.srWindow.Right, csbiConsole.srWindow.Bottom);
TRACE(L"console window rect: (%i, %i) - (%i, %i)\n", csbiConsole.srWindow.Top, csbiConsole.srWindow.Left, csbiConsole.srWindow.Bottom, csbiConsole.srWindow.Right);
*/
// do console output buffer reading
DWORD dwScreenBufferSize = coordConsoleSize.X * coordConsoleSize.Y;
DWORD dwScreenBufferOffset = 0;
std::unique_ptr<CHAR_INFO[]> pScreenBuffer(new CHAR_INFO[dwScreenBufferSize]);
COORD coordBufferSize;
// start coordinates for the buffer are always (0, 0) - we use offset
COORD coordStart = {0, 0};
SMALL_RECT srBuffer;
//TRACE(L"===================================================================\n");
// ReadConsoleOutput seems to fail for large (around 6k CHAR_INFO's) buffers
// here we calculate max buffer size (row count) for safe reading
coordBufferSize.X = csbiConsole.srWindow.Right - csbiConsole.srWindow.Left + 1;
coordBufferSize.Y = 6144 / coordBufferSize.X;
// initialize reading rectangle
srBuffer.Top = csbiConsole.srWindow.Top;
srBuffer.Bottom = csbiConsole.srWindow.Top + coordBufferSize.Y - 1;
srBuffer.Left = csbiConsole.srWindow.Left;
srBuffer.Right = csbiConsole.srWindow.Left + csbiConsole.srWindow.Right - csbiConsole.srWindow.Left;
/*
TRACE(L"Buffer size for loop reads: %ix%i\n", coordBufferSize.X, coordBufferSize.Y);
TRACE(L"-------------------------------------------------------------------\n");
*/
// read rows 'chunks'
SHORT i = 0;
for(; i < coordConsoleSize.Y / coordBufferSize.Y; ++i)
{
//TRACE(L"Reading region: (%i, %i) - (%i, %i)\n", srBuffer.Left, srBuffer.Top, srBuffer.Right, srBuffer.Bottom);
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get() + dwScreenBufferOffset,
coordBufferSize,
coordStart,
&srBuffer);
srBuffer.Top = srBuffer.Top + coordBufferSize.Y;
srBuffer.Bottom = srBuffer.Bottom + coordBufferSize.Y;
dwScreenBufferOffset += coordBufferSize.X * coordBufferSize.Y;
}
// read the last 'chunk', we need to calculate the number of rows in the
// last chunk and update bottom coordinate for the region
coordBufferSize.Y = coordConsoleSize.Y - i * coordBufferSize.Y;
srBuffer.Bottom = csbiConsole.srWindow.Bottom;
/*
TRACE(L"Buffer size for last read: %ix%i\n", coordBufferSize.X, coordBufferSize.Y);
TRACE(L"-------------------------------------------------------------------\n");
TRACE(L"Reading region: (%i, %i) - (%i, %i)\n", srBuffer.Left, srBuffer.Top, srBuffer.Right, srBuffer.Bottom);
*/
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get() + dwScreenBufferOffset,
coordBufferSize,
coordStart,
&srBuffer);
//TRACE(L"===================================================================\n");
unsigned long long ullProgressCompleted = 0ULL;
unsigned long long ullProgressTotal = 0ULL;
GetPowerShellProgress(hStdOut, csbiConsole, ullProgressCompleted, ullProgressTotal);
// compare previous buffer, and if different notify ConsoleZ
SharedMemoryLock consoleInfoLock(m_consoleInfo);
SharedMemoryLock bufferLock(m_consoleBuffer);
::GetConsoleCursorInfo(hStdOut, m_cursorInfo.Get());
bool somethingChanged = false;
// compare text
if(m_dwScreenBufferSize != dwScreenBufferSize
||
::memcmp(m_consoleBuffer.Get(), pScreenBuffer.get(), dwScreenBufferSize * sizeof(CHAR_INFO)) != 0)
{
::CopyMemory(m_consoleBuffer.Get(), pScreenBuffer.get(), dwScreenBufferSize * sizeof(CHAR_INFO));
somethingChanged = true;
// only ConsoleZ sets the flags to false
m_consoleInfo->textChanged = true;
}
// compare previous console title
wchar_t szNewConsoleTitle[ARRAYSIZE(m_szConsoleTitle)] = L"";
if(::GetConsoleTitle(szNewConsoleTitle, ARRAYSIZE(m_szConsoleTitle))
&&
wcscmp(szNewConsoleTitle, m_szConsoleTitle))
{
wcscpy_s<ARRAYSIZE(m_szConsoleTitle)>(m_szConsoleTitle, szNewConsoleTitle);
somethingChanged = true;
// only ConsoleZ sets the flags to false
m_consoleInfo->titleChanged = true;
}
// compare console buffer information
if(::memcmp(&m_consoleInfo->csbi, &csbiConsole, sizeof(CONSOLE_SCREEN_BUFFER_INFO))
||
m_dwScreenBufferSize != dwScreenBufferSize)
{
// update screen buffer variables
m_dwScreenBufferSize = dwScreenBufferSize;
::CopyMemory(&m_consoleInfo->csbi, &csbiConsole, sizeof(CONSOLE_SCREEN_BUFFER_INFO));
somethingChanged = true;
// only ConsoleZ sets the flags to false
m_consoleInfo->csbiChanged = true;
}
// compare progress
if(ullProgressCompleted != m_consoleInfo->ullProgressCompleted || ullProgressTotal != m_consoleInfo->ullProgressTotal)
{
m_consoleInfo->ullProgressCompleted = ullProgressCompleted;
m_consoleInfo->ullProgressTotal = ullProgressTotal;
somethingChanged = true;
// only ConsoleZ sets the flags to false
m_consoleInfo->progressChanged = true;
}
// if something changed then event is alerted
if(somethingChanged)
{
m_consoleBuffer.SetReqEvent();
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ConsoleHandler::GetPowerShellProgress(HANDLE hStdOut, CONSOLE_SCREEN_BUFFER_INFO& csbiConsole, unsigned long long & ullProgressCompleted, unsigned long long & ullProgressTotal)
{
// if we are in another screen buffer
// we avoid the progress bar detection
if( hStdOut != m_hStdOut ) return false;
SHORT sBufferColumns = csbiConsole.dwSize.X;
SHORT sBufferRows = csbiConsole.dwSize.Y;
// buffer width is too small to display a progress bar!
if( sBufferColumns <= 12 )
return false;
// we search the empty line of color 3e
// this line is in third row
// of the window containing the cursor
SHORT sMinRow = csbiConsole.dwCursorPosition.Y
- (csbiConsole.srWindow.Bottom - csbiConsole.srWindow.Top)
+ 2;
if( sMinRow < 2 ) sMinRow = 2;
SHORT sMaxRow = csbiConsole.dwCursorPosition.Y + 2;
if( sMaxRow >= sBufferRows ) sMaxRow = sBufferRows - 1;
COORD coordFrom = {0, 0};
COORD coordBufferSize = {sBufferColumns, 1};
SMALL_RECT srBuffer;
srBuffer.Left = 0;
srBuffer.Right = sBufferColumns - 1;
std::unique_ptr<CHAR_INFO[]> pScreenBuffer(new CHAR_INFO[sBufferColumns]);
TRACE(L"GetPowerShellProgress from %hd to %hd\n", sMinRow, sMaxRow);
for( SHORT sRow = sMinRow; sRow <= sMaxRow; ++sRow )
{
srBuffer.Top = sRow;
srBuffer.Bottom = sRow;
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get(),
coordBufferSize,
coordFrom,
&srBuffer);
bool bEmpty = true;
for( SHORT i = srBuffer.Left; i < srBuffer.Right; ++i )
{
if( pScreenBuffer[i].Attributes != 0x3e || pScreenBuffer[i].Char.UnicodeChar != L' ' )
{
bEmpty = false;
break;
}
}
if( bEmpty )
{
// we search " [ooo...ooo ... ]"
for( SHORT sRow2 = sRow + 3; sRow2 < min(sMaxRow + 10, sBufferRows); ++sRow2 )
{
srBuffer.Top = sRow2;
srBuffer.Bottom = sRow2;
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get(),
coordBufferSize,
coordFrom,
&srBuffer);
if( pScreenBuffer[0].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[1].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[2].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[3].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[4].Char.UnicodeChar != L'[' ) continue;
if( pScreenBuffer[sBufferColumns - 1].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 2].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 3].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 4].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 5].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 6].Char.UnicodeChar != L' ' ) continue;
if( pScreenBuffer[sBufferColumns - 7].Char.UnicodeChar != L']' ) continue;
int nBarLength = 0;
for(SHORT sCol = 5; sCol < sBufferColumns - 7; ++sCol)
{
if( pScreenBuffer[sCol].Char.UnicodeChar == L'o' ) nBarLength++;
else if ( pScreenBuffer[sCol].Char.UnicodeChar != L' ' ) return false;
}
TRACE(L"GetPowerShellProgress progress = %i/%i\n",
nBarLength,
sBufferColumns - 12);
ullProgressCompleted = nBarLength;
ullProgressTotal = sBufferColumns - 12;
return true;
}
return false;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void ConsoleHandler::ResizeConsoleWindow(DWORD& dwColumns, DWORD& dwRows, DWORD dwResizeWindowEdge)
{
GET_STD_OUT_READ_WRITE
CONSOLE_SCREEN_BUFFER_INFO csbi;
::GetConsoleScreenBufferInfo(hStdOut, &csbi);
TRACE(L"Console size: %ix%i\n", csbi.dwSize.X, csbi.dwSize.Y);
TRACE(L"Old win pos: %ix%i - %ix%i\n", csbi.srWindow.Left, csbi.srWindow.Top, csbi.srWindow.Right, csbi.srWindow.Bottom);
bool boolCursorVisible =
csbi.dwCursorPosition.X >= csbi.srWindow.Left &&
csbi.dwCursorPosition.X <= csbi.srWindow.Right &&
csbi.dwCursorPosition.Y >= csbi.srWindow.Top &&
csbi.dwCursorPosition.Y <= csbi.srWindow.Bottom;
// check against max size
TRACE(L"Columns: %i\n", dwColumns);
TRACE(L"Max columns: %i\n", m_consoleParams->dwMaxColumns);
TRACE(L"Rows: %i\n", dwRows);
TRACE(L"Max rows: %i\n", m_consoleParams->dwMaxRows);
TRACE(L"Cursor X: %i\n", csbi.dwCursorPosition.X);
TRACE(L"Cursor Y: %i\n", csbi.dwCursorPosition.Y);
TRACE(L"boolCursorVisible: %s\n", boolCursorVisible? L"true" : L"false");
if (dwColumns > m_consoleParams->dwMaxColumns) dwColumns = m_consoleParams->dwMaxColumns;
if (dwRows > m_consoleParams->dwMaxRows) dwRows = m_consoleParams->dwMaxRows;
COORD coordBufferSize;
SMALL_RECT srConsoleRect;
TRACE(L"Screen buffer: %ix%i\n", m_consoleParams->dwBufferRows, m_consoleParams->dwBufferColumns);
// determine new buffer size
if (m_consoleParams->dwBufferColumns == 0)
{
coordBufferSize.X = static_cast<SHORT>(dwColumns);
}
else
{
coordBufferSize.X = static_cast<SHORT>(m_consoleParams->dwBufferColumns);
}
if (m_consoleParams->dwBufferRows == 0)
{
coordBufferSize.Y = static_cast<SHORT>(dwRows);
}
else
{
coordBufferSize.Y = static_cast<SHORT>(m_consoleParams->dwBufferRows);
}
// determine new window size
// vertical size
switch (dwResizeWindowEdge)
{
case WMSZ_TOP :
case WMSZ_TOPLEFT :
case WMSZ_TOPRIGHT :
{
if ((csbi.srWindow.Top == 0) || (csbi.srWindow.Bottom - static_cast<SHORT>(dwRows - 1) <= 0))
{
srConsoleRect.Top = 0;
srConsoleRect.Bottom = static_cast<SHORT>(dwRows - 1);
}
else
{
srConsoleRect.Top = csbi.srWindow.Bottom - static_cast<SHORT>(dwRows - 1);
srConsoleRect.Bottom = csbi.srWindow.Bottom;
}
break;
}
case WMSZ_BOTTOM :
case WMSZ_BOTTOMLEFT :
case WMSZ_BOTTOMRIGHT :
{
if ((m_consoleParams->dwBufferRows > 0) && (csbi.srWindow.Top + static_cast<SHORT>(dwRows) > static_cast<SHORT>(m_consoleParams->dwBufferRows)))
{
srConsoleRect.Top = static_cast<SHORT>(m_consoleParams->dwBufferRows - dwRows);
srConsoleRect.Bottom = static_cast<SHORT>(m_consoleParams->dwBufferRows - 1);
}
else
{
srConsoleRect.Top = csbi.srWindow.Top;
srConsoleRect.Bottom = csbi.srWindow.Top + static_cast<SHORT>(dwRows - 1);
}
break;
}
default :
{
srConsoleRect.Top = csbi.srWindow.Top;
srConsoleRect.Bottom = csbi.srWindow.Top + static_cast<SHORT>(dwRows - 1);
}
}
if( boolCursorVisible &&
( csbi.dwCursorPosition.Y < srConsoleRect.Top ||
csbi.dwCursorPosition.Y > srConsoleRect.Bottom ) )
{
if( csbi.dwCursorPosition.Y < static_cast<SHORT>(dwRows) )
{
srConsoleRect.Top = 0;
srConsoleRect.Bottom = static_cast<SHORT>(dwRows - 1);
}
else
{
srConsoleRect.Top = csbi.dwCursorPosition.Y - static_cast<SHORT>(dwRows - 1);
srConsoleRect.Bottom = csbi.dwCursorPosition.Y;
}
}
// horizontal size
switch (dwResizeWindowEdge)
{
case WMSZ_LEFT :
case WMSZ_TOPLEFT :
case WMSZ_BOTTOMLEFT :
{
if ((csbi.srWindow.Left == 0) || (csbi.srWindow.Right - static_cast<SHORT>(dwColumns - 1) <= 0))
{
srConsoleRect.Left = 0;
srConsoleRect.Right = static_cast<SHORT>(dwColumns - 1);
}
else
{
srConsoleRect.Left = csbi.srWindow.Right - static_cast<SHORT>(dwColumns - 1);
srConsoleRect.Right = csbi.srWindow.Right;
}
break;
}
case WMSZ_RIGHT :
case WMSZ_TOPRIGHT :
case WMSZ_BOTTOMRIGHT :
{
if ((m_consoleParams->dwBufferColumns != 0) && (csbi.srWindow.Left + static_cast<SHORT>(dwColumns) > static_cast<SHORT>(m_consoleParams->dwBufferColumns)))
{
srConsoleRect.Left = static_cast<SHORT>(m_consoleParams->dwBufferColumns - dwColumns);
srConsoleRect.Right = static_cast<SHORT>(m_consoleParams->dwBufferColumns - 1);
}
else
{
srConsoleRect.Left = csbi.srWindow.Left;
srConsoleRect.Right = csbi.srWindow.Left + static_cast<SHORT>(dwColumns - 1);
}
break;
}
default :
{
srConsoleRect.Left = csbi.srWindow.Left;
srConsoleRect.Right = csbi.srWindow.Left + static_cast<SHORT>(dwColumns - 1);
}
}
if( boolCursorVisible &&
( csbi.dwCursorPosition.X < srConsoleRect.Left ||
csbi.dwCursorPosition.X > srConsoleRect.Right ) )
{
if( csbi.dwCursorPosition.X < static_cast<SHORT>(dwColumns) )
{
srConsoleRect.Left = 0;
srConsoleRect.Right = static_cast<SHORT>(dwColumns - 1);
}
else
{
srConsoleRect.Left = csbi.dwCursorPosition.X - static_cast<SHORT>(dwColumns - 1);
srConsoleRect.Right = csbi.dwCursorPosition.X;
}
}
TRACE(L"New win pos: %ix%i - %ix%i\n", srConsoleRect.Left, srConsoleRect.Top, srConsoleRect.Right, srConsoleRect.Bottom);
TRACE(L"Buffer size: %ix%i\n", coordBufferSize.X, coordBufferSize.Y);
COORD finalCoordBufferSize;
SMALL_RECT finalConsoleRect;
// first, resize rows
finalCoordBufferSize.X = csbi.dwSize.X;
finalCoordBufferSize.Y = coordBufferSize.Y;
finalConsoleRect.Left = csbi.srWindow.Left;
finalConsoleRect.Right = csbi.srWindow.Right;
finalConsoleRect.Top = srConsoleRect.Top;
finalConsoleRect.Bottom = srConsoleRect.Bottom;
if (coordBufferSize.Y > csbi.dwSize.Y)
{
// if new buffer size is > than old one, we need to resize the buffer first
::SetConsoleScreenBufferSize(hStdOut, finalCoordBufferSize);
::SetConsoleWindowInfo(hStdOut, TRUE, &finalConsoleRect);
}
else
{
::SetConsoleWindowInfo(hStdOut, TRUE, &finalConsoleRect);
::SetConsoleScreenBufferSize(hStdOut, finalCoordBufferSize);
}
// then, resize columns
finalCoordBufferSize.X = coordBufferSize.X;
finalConsoleRect.Left = srConsoleRect.Left;
finalConsoleRect.Right = srConsoleRect.Right;
if (coordBufferSize.X > csbi.dwSize.X)
{
// if new buffer size is > than old one, we need to resize the buffer first
::SetConsoleScreenBufferSize(hStdOut, finalCoordBufferSize);
::SetConsoleWindowInfo(hStdOut, TRUE, &finalConsoleRect);
}
else
{
::SetConsoleWindowInfo(hStdOut, TRUE, &finalConsoleRect);
::SetConsoleScreenBufferSize(hStdOut, finalCoordBufferSize);
}
TRACE(L"console buffer size: %ix%i\n", coordBufferSize.X, coordBufferSize.Y);
TRACE(L"console rect: %ix%i - %ix%i\n", finalConsoleRect.Left, finalConsoleRect.Top, finalConsoleRect.Right, finalConsoleRect.Bottom);
::GetConsoleScreenBufferInfo(hStdOut, &csbi);
dwColumns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
dwRows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
TRACE(L"Columns: %i\n", dwColumns);
TRACE(L"Rows: %i\n", dwRows);
// TRACE(L"console buffer size: %ix%i\n", csbi.dwSize.X, csbi.dwSize.Y);
// TRACE(L"console rect: %ix%i - %ix%i\n", csbi.srWindow.Left, csbi.srWindow.Top, csbi.srWindow.Right, csbi.srWindow.Bottom);
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
class ClipboardData
{
public:
ClipboardData(void) {}
virtual ~ClipboardData(void) {}
virtual void StartRow(void) = 0;
virtual void EndRow(void) = 0;
virtual void AddChar(PCHAR_INFO) = 0;
virtual bool IsEOL(DWORD dwEOLSpaces) = 0;
virtual size_t GetRowLength(void) = 0;
virtual void TrimRight(void) = 0;
virtual void Wrap(CopyNewlineChar) = 0;
virtual void Publish(ClipboardHelper&) = 0;
};
class ClipboardDataUnicode : public ClipboardData
{
public:
ClipboardDataUnicode(void):strText(L"") {}
virtual ~ClipboardDataUnicode(void) {}
virtual void StartRow(void)
{
strRow = L"";
}
virtual void EndRow(void)
{
strText += strRow;
}
virtual void AddChar(PCHAR_INFO p)
{
strRow += p->Char.UnicodeChar;
}
virtual bool IsEOL(DWORD dwEOLSpaces)
{
size_t len = strRow.length();
if( len < dwEOLSpaces ) return false;
for(size_t i = (len - dwEOLSpaces); i < len; ++i)
if( strRow[i] != L' ' )
return false;
return true;
}
size_t GetRowLength(void)
{
return strRow.length();
}
virtual void TrimRight(void)
{
boost::trim_right(strRow);
}
virtual void Wrap(CopyNewlineChar copyNewlineChar)
{
switch(copyNewlineChar)
{
case newlineCRLF: strRow += wstring(L"\r\n"); break;
case newlineLF: strRow += wstring(L"\n"); break;
default: strRow += wstring(L"\r\n"); break;
}
}
virtual void Publish(ClipboardHelper& clipboard)
{
clipboard.setData(CF_UNICODETEXT, strText.c_str(), (strText.length() + 1) * sizeof(wchar_t));
}
const wchar_t * GetText(void) const
{
return strText.c_str();
}
size_t GetTextLength(void) const
{
return strText.length();
}
private:
wstring strText;
wstring strRow;
};
class ClipboardDataRtf : public ClipboardData
{
public:
ClipboardDataRtf(ConsoleCopy* pconsoleCopy):sizeRtfLen(0)
{
strRtf = "{\\rtf\\ansi\\deff0";
strRtf += "{\\fonttbl{\\f0\\fnil ";
strRtf += pconsoleCopy->szFontName;
strRtf += ";}}";
strRtf += "{\\colortbl\n";
for(int i = 0; i < 16; i ++)
{
char szColor[64];
_snprintf_s(
szColor, sizeof(szColor),
_TRUNCATE,
"\\red%lu\\green%lu\\blue%lu;\n",
GetRValue(pconsoleCopy->consoleColors[i]),
GetGValue(pconsoleCopy->consoleColors[i]),
GetBValue(pconsoleCopy->consoleColors[i]));
strRtf += szColor;
}
strRtf += "}";
char szFont[64];
_snprintf_s(
szFont, sizeof(szFont),
_TRUNCATE,
"\\f0\\fs%lu%s%s\n",
pconsoleCopy->dwSize,
pconsoleCopy->bBold ? "\\b" : "",
pconsoleCopy->bItalic ? "\\i" : "");
strRtf += szFont;
}
virtual ~ClipboardDataRtf(void) {}
virtual void StartRow(void)
{
strRowRtf.clear();
sizeRowLen = 0;
}
virtual void EndRow(void)
{
strRtf += strRowRtf;
strRtf += strTrimRowRtf;
strTrimRowRtf.clear();
}
virtual void AddChar(PCHAR_INFO p)
{
char szDummy[32];
WORD wCharForegroundAttributes = p->Attributes & 0x000f;
WORD wCharBackgroundAttributes = (p->Attributes >> 4) & 0x000f;
if( sizeRtfLen == 0 )
{
wLastCharForegroundAttributes = ~wCharForegroundAttributes;
wLastCharBackgroundAttributes = ~wCharBackgroundAttributes;
}
bool trim = std::isspace<wchar_t>(p->Char.UnicodeChar, std::locale());
std::string& strRowRtfRef = (trim)?strTrimRowRtf:strRowRtf;
if( trim )
{
if( strTrimRowRtf.empty() )
{
wLastTrimCharForegroundAttributes = wLastCharForegroundAttributes;
wLastTrimCharBackgroundAttributes = wLastCharBackgroundAttributes;
}
}
else
{
strRowRtf += strTrimRowRtf;
strTrimRowRtf.clear();
}
if( wLastCharBackgroundAttributes != wCharBackgroundAttributes )
{
_snprintf_s(
szDummy, sizeof(szDummy),
_TRUNCATE,
"\\highlight%hu ",
wCharBackgroundAttributes);
strRowRtfRef += szDummy;
}
if( wLastCharForegroundAttributes != wCharForegroundAttributes )
{
_snprintf_s(
szDummy, sizeof(szDummy),
_TRUNCATE,
"\\cf%hu ",
wCharForegroundAttributes);
strRowRtfRef += szDummy;
}
wLastCharForegroundAttributes = wCharForegroundAttributes;
wLastCharBackgroundAttributes = wCharBackgroundAttributes;
WCHAR wc = p->Char.UnicodeChar;
if( wc == L'\\' ) strRowRtfRef += "\\\\";
else if( wc == L'{' ) strRowRtfRef += "\\{";
else if( wc == L'}' ) strRowRtfRef += "\\}";
else if( wc <= 0x7f ) strRowRtfRef += p->Char.AsciiChar;
else
{
_snprintf_s(szDummy, sizeof(szDummy), _TRUNCATE, "\\u%u?", wc);
strRowRtfRef += szDummy;
}
sizeRowLen ++;
sizeRtfLen ++;
}
virtual bool IsEOL(DWORD /*dwEOLSpaces*/)
{
return !strTrimRowRtf.empty();
}
size_t GetRowLength(void)
{
return sizeRowLen;
}
virtual void TrimRight(void)
{
if( !strTrimRowRtf.empty() )
{
strTrimRowRtf.clear();
wLastCharForegroundAttributes = wLastTrimCharForegroundAttributes;
wLastCharBackgroundAttributes = wLastTrimCharBackgroundAttributes;
}
}
virtual void Wrap(CopyNewlineChar /*copyNewlineChar*/)
{
strTrimRowRtf += "\\line\n";
}
virtual void Publish(ClipboardHelper& clipboard)
{
strRtf += "}";
clipboard.setData(::RegisterClipboardFormat(L"Rich Text Format"), strRtf.c_str(), strRtf.length() + 1);
}
private:
string strRtf;
string strRowRtf;
string strTrimRowRtf;
size_t sizeRtfLen;
size_t sizeRowLen;
WORD wLastCharForegroundAttributes;
WORD wLastCharBackgroundAttributes;
WORD wLastTrimCharForegroundAttributes;
WORD wLastTrimCharBackgroundAttributes;
};
void ConsoleHandler::CopyConsoleTextLine(HANDLE hStdOut, std::unique_ptr<ClipboardData> clipboardDataPtr[], size_t clipboardDataCount)
{
COORD& coordStart = m_consoleCopyInfo->coordStart;
COORD& coordEnd = m_consoleCopyInfo->coordEnd;
COORD coordFrom = {0, 0};
COORD coordBufferSize = {(m_consoleParams->dwBufferColumns > 0) ? static_cast<SHORT>(m_consoleParams->dwBufferColumns) : static_cast<SHORT>(m_consoleParams->dwColumns), 1};
std::unique_ptr<CHAR_INFO[]> pScreenBuffer(new CHAR_INFO[coordBufferSize.X]);
// suppress end empty lines
bool emptyLine = true;
for (SHORT i = coordEnd.Y; i > coordStart.Y && emptyLine; --i)
{
SMALL_RECT srBuffer;
srBuffer.Left = 0;
srBuffer.Top = i;
srBuffer.Right = (i == coordEnd.Y) ? coordEnd.X : (m_consoleParams->dwBufferColumns > 0) ? static_cast<SHORT>(m_consoleParams->dwBufferColumns - 1) : static_cast<SHORT>(m_consoleParams->dwColumns - 1);
srBuffer.Bottom = i;
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get(),
coordBufferSize,
coordFrom,
&srBuffer);
for (SHORT x = 0; x <= srBuffer.Right - srBuffer.Left && emptyLine; ++x)
{
if( pScreenBuffer[x].Char.UnicodeChar != L' ' )
emptyLine = false;
}
if( emptyLine )
{
coordEnd.Y --;
coordEnd.X = coordBufferSize.X - 1;
}
}
for (SHORT i = coordStart.Y; i <= coordEnd.Y; ++i)
{
SMALL_RECT srBuffer;
srBuffer.Left = (i == coordStart.Y) ? coordStart.X : 0;
srBuffer.Top = i;
srBuffer.Right = (i == coordEnd.Y) ? coordEnd.X : (m_consoleParams->dwBufferColumns > 0) ? static_cast<SHORT>(m_consoleParams->dwBufferColumns - 1) : static_cast<SHORT>(m_consoleParams->dwColumns - 1);
srBuffer.Bottom = i;
::ReadConsoleOutput(
hStdOut,
pScreenBuffer.get(),
coordBufferSize,
coordFrom,
&srBuffer);
for(size_t clipboardDataIndex = 0; clipboardDataIndex < clipboardDataCount; clipboardDataIndex ++)
clipboardDataPtr[clipboardDataIndex]->StartRow();
bool bWrap = true;
bool bTrimSpaces = m_consoleCopyInfo->bTrimSpaces;
for (SHORT x = 0; x <= srBuffer.Right - srBuffer.Left; ++x)
{
if (pScreenBuffer[x].Attributes & COMMON_LVB_TRAILING_BYTE) continue;
for(size_t clipboardDataIndex = 0; clipboardDataIndex < clipboardDataCount; clipboardDataIndex ++)