-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
Copy pathscreenInfo.cpp
2951 lines (2594 loc) · 110 KB
/
screenInfo.cpp
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "screenInfo.hpp"
#include "dbcs.h"
#include "output.h"
#include "_output.h"
#include "misc.h"
#include "handle.h"
#include "../buffer/out/CharRow.hpp"
#include <math.h>
#include "../interactivity/inc/ServiceLocator.hpp"
#include "../types/inc/Viewport.hpp"
#include "../types/inc/GlyphWidth.hpp"
#include "../terminal/parser/OutputStateMachineEngine.hpp"
#include "../types/inc/convert.hpp"
#pragma hdrstop
using namespace Microsoft::Console;
using namespace Microsoft::Console::Types;
using namespace Microsoft::Console::Render;
using namespace Microsoft::Console::Interactivity;
using namespace Microsoft::Console::VirtualTerminal;
#pragma region Construct_Destruct
SCREEN_INFORMATION::SCREEN_INFORMATION(
_In_ IWindowMetrics* pMetrics,
_In_ IAccessibilityNotifier* pNotifier,
const TextAttribute popupAttributes,
const FontInfo fontInfo) :
OutputMode{ ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT },
ResizingWindow{ 0 },
WheelDelta{ 0 },
HWheelDelta{ 0 },
_textBuffer{ nullptr },
Next{ nullptr },
WriteConsoleDbcsLeadByte{ 0, 0 },
FillOutDbcsLeadChar{ 0 },
// LineChar initialized below.
ConvScreenInfo{ nullptr },
ScrollScale{ 1ul },
_pConsoleWindowMetrics{ pMetrics },
_pAccessibilityNotifier{ pNotifier },
_stateMachine{ nullptr },
_scrollMargins{ Viewport::FromCoord({ 0 }) },
_viewport(Viewport::Empty()),
_psiAlternateBuffer{ nullptr },
_psiMainBuffer{ nullptr },
_rcAltSavedClientNew{ 0 },
_rcAltSavedClientOld{ 0 },
_fAltWindowChanged{ false },
_PopupAttributes{ popupAttributes },
_tabStops{},
_virtualBottom{ 0 },
_renderTarget{ *this },
_currentFont{ fontInfo },
_desiredFont{ fontInfo }
{
LineChar[0] = UNICODE_BOX_DRAW_LIGHT_DOWN_AND_RIGHT;
LineChar[1] = UNICODE_BOX_DRAW_LIGHT_DOWN_AND_LEFT;
LineChar[2] = UNICODE_BOX_DRAW_LIGHT_HORIZONTAL;
LineChar[3] = UNICODE_BOX_DRAW_LIGHT_VERTICAL;
LineChar[4] = UNICODE_BOX_DRAW_LIGHT_UP_AND_RIGHT;
LineChar[5] = UNICODE_BOX_DRAW_LIGHT_UP_AND_LEFT;
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (gci.GetVirtTermLevel() != 0)
{
OutputMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
}
}
// Routine Description:
// - This routine frees the memory associated with a screen buffer.
// Arguments:
// - ScreenInfo - screen buffer data to free.
// Return Value:
// Note:
// - console handle table lock must be held when calling this routine
SCREEN_INFORMATION::~SCREEN_INFORMATION()
{
_FreeOutputStateMachine();
}
// Routine Description:
// - This routine allocates and initializes the data associated with a screen buffer.
// Arguments:
// - ScreenInformation - the new screen buffer.
// - coordWindowSize - the initial size of screen buffer's window (in rows/columns)
// - nFont - the initial font to generate text with.
// - dwScreenBufferSize - the initial size of the screen buffer (in rows/columns).
// Return Value:
[[nodiscard]] NTSTATUS SCREEN_INFORMATION::CreateInstance(_In_ COORD coordWindowSize,
const FontInfo fontInfo,
_In_ COORD coordScreenBufferSize,
const TextAttribute defaultAttributes,
const TextAttribute popupAttributes,
const UINT uiCursorSize,
_Outptr_ SCREEN_INFORMATION** const ppScreen)
{
*ppScreen = nullptr;
try
{
IWindowMetrics* pMetrics = ServiceLocator::LocateWindowMetrics();
THROW_IF_NULL_ALLOC(pMetrics);
IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier();
THROW_IF_NULL_ALLOC(pNotifier);
SCREEN_INFORMATION* const pScreen = new SCREEN_INFORMATION(pMetrics, pNotifier, popupAttributes, fontInfo);
// Set up viewport
pScreen->_viewport = Viewport::FromDimensions({ 0, 0 },
pScreen->_IsInPtyMode() ? coordScreenBufferSize : coordWindowSize);
pScreen->UpdateBottom();
// Set up text buffer
pScreen->_textBuffer = std::make_unique<TextBuffer>(coordScreenBufferSize,
defaultAttributes,
uiCursorSize,
pScreen->_renderTarget);
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
pScreen->_textBuffer->GetCursor().SetColor(gci.GetCursorColor());
pScreen->_textBuffer->GetCursor().SetType(gci.GetCursorType());
const NTSTATUS status = pScreen->_InitializeOutputStateMachine();
if (NT_SUCCESS(status))
{
*ppScreen = pScreen;
}
LOG_IF_NTSTATUS_FAILED(status);
return status;
}
catch (...)
{
return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException());
}
}
Viewport SCREEN_INFORMATION::GetBufferSize() const
{
return _textBuffer->GetSize();
}
// Method Description:
// - Returns the "terminal" dimensions of this buffer. If we're in Terminal
// Scrolling mode, this will return our Y dimension as only extending up to
// the _virtualBottom. The height of the returned viewport would then be
// (number of lines in scrollback) + (number of lines in viewport).
// If we're not in teminal scrolling mode, this will return our normal buffer
// size.
// Arguments:
// - <none>
// Return Value:
// - a viewport whos height is the height of the "terminal" portion of the
// buffer in terminal scrolling mode, and is the height of the full buffer
// in normal scrolling mode.
Viewport SCREEN_INFORMATION::GetTerminalBufferSize() const
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
Viewport v = _textBuffer->GetSize();
if (gci.IsTerminalScrolling() && v.Height() > _virtualBottom)
{
v = Viewport::FromDimensions({ 0, 0 }, v.Width(), _virtualBottom + 1);
}
return v;
}
const StateMachine& SCREEN_INFORMATION::GetStateMachine() const
{
return *_stateMachine;
}
StateMachine& SCREEN_INFORMATION::GetStateMachine()
{
return *_stateMachine;
}
// Method Description:
// - returns true if this buffer is in Virtual Terminal Output mode.
// Arguments:
// <none>
// Return Value:
// true iff this buffer is in Virtual Terminal Output mode.
bool SCREEN_INFORMATION::InVTMode() const
{
return WI_IsFlagSet(OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
// Routine Description:
// - This routine inserts the screen buffer pointer into the console's list of screen buffers.
// Arguments:
// - ScreenInfo - Pointer to screen information structure.
// Return Value:
// Note:
// - The console lock must be held when calling this routine.
void SCREEN_INFORMATION::s_InsertScreenBuffer(_In_ SCREEN_INFORMATION* const pScreenInfo)
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
FAIL_FAST_IF(!(gci.IsConsoleLocked()));
pScreenInfo->Next = gci.ScreenBuffers;
gci.ScreenBuffers = pScreenInfo;
}
// Routine Description:
// - This routine removes the screen buffer pointer from the console's list of screen buffers.
// Arguments:
// - ScreenInfo - Pointer to screen information structure.
// Return Value:
// Note:
// - The console lock must be held when calling this routine.
void SCREEN_INFORMATION::s_RemoveScreenBuffer(_In_ SCREEN_INFORMATION* const pScreenInfo)
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (pScreenInfo == gci.ScreenBuffers)
{
gci.ScreenBuffers = pScreenInfo->Next;
}
else
{
auto* Cur = gci.ScreenBuffers;
auto* Prev = Cur;
while (Cur != nullptr)
{
if (pScreenInfo == Cur)
{
break;
}
Prev = Cur;
Cur = Cur->Next;
}
FAIL_FAST_IF_NULL(Cur);
Prev->Next = Cur->Next;
}
if (pScreenInfo == gci.pCurrentScreenBuffer &&
gci.ScreenBuffers != gci.pCurrentScreenBuffer)
{
if (gci.ScreenBuffers != nullptr)
{
SetActiveScreenBuffer(*gci.ScreenBuffers);
}
else
{
gci.pCurrentScreenBuffer = nullptr;
}
}
delete pScreenInfo;
}
#pragma endregion
#pragma region Output State Machine
[[nodiscard]] NTSTATUS SCREEN_INFORMATION::_InitializeOutputStateMachine()
{
try
{
auto adapter = std::make_unique<AdaptDispatch>(new ConhostInternalGetSet{ *this },
new WriteBuffer{ *this });
THROW_IF_NULL_ALLOC(adapter.get());
// Note that at this point in the setup, we haven't determined if we're
// in VtIo mode or not yet. We'll set the OutputStateMachine's
// TerminalConnection later, in VtIo::StartIfNeeded
_stateMachine = std::make_shared<StateMachine>(new OutputStateMachineEngine(adapter.release()));
THROW_IF_NULL_ALLOC(_stateMachine.get());
}
catch (...)
{
// if any part of initialization failed, free the allocated ones.
_FreeOutputStateMachine();
return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException());
}
return STATUS_SUCCESS;
}
// If we're an alternate buffer, we want to give the GetSet back to our main
void SCREEN_INFORMATION::_FreeOutputStateMachine()
{
if (_psiMainBuffer == nullptr) // If this is a main buffer
{
if (_psiAlternateBuffer != nullptr)
{
s_RemoveScreenBuffer(_psiAlternateBuffer);
}
_stateMachine.reset();
}
}
#pragma endregion
#pragma region IIoProvider
// Method Description:
// - Return the active screen buffer of the console.
// Arguments:
// - <none>
// Return Value:
// - the active screen buffer of the console.
SCREEN_INFORMATION& SCREEN_INFORMATION::GetActiveOutputBuffer()
{
return GetActiveBuffer();
}
const SCREEN_INFORMATION& SCREEN_INFORMATION::GetActiveOutputBuffer() const
{
return GetActiveBuffer();
}
// Method Description:
// - Return the active input buffer of the console.
// Arguments:
// - <none>
// Return Value:
// - the active input buffer of the console.
InputBuffer* const SCREEN_INFORMATION::GetActiveInputBuffer() const
{
return ServiceLocator::LocateGlobals().getConsoleInformation().GetActiveInputBuffer();
}
#pragma endregion
#pragma region Get Data
bool SCREEN_INFORMATION::IsActiveScreenBuffer() const
{
// the following macro returns TRUE if the given screen buffer is the active screen buffer.
//#define ACTIVE_SCREEN_BUFFER(SCREEN_INFO) (gci.CurrentScreenBuffer == SCREEN_INFO)
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
return (gci.pCurrentScreenBuffer == this);
}
// Routine Description:
// - This routine returns data about the screen buffer.
// Arguments:
// - Size - Pointer to location in which to store screen buffer size.
// - CursorPosition - Pointer to location in which to store the cursor position.
// - ScrollPosition - Pointer to location in which to store the scroll position.
// - Attributes - Pointer to location in which to store the default attributes.
// - CurrentWindowSize - Pointer to location in which to store current window size.
// - MaximumWindowSize - Pointer to location in which to store maximum window size.
// Return Value:
// - None
void SCREEN_INFORMATION::GetScreenBufferInformation(_Out_ PCOORD pcoordSize,
_Out_ PCOORD pcoordCursorPosition,
_Out_ PSMALL_RECT psrWindow,
_Out_ PWORD pwAttributes,
_Out_ PCOORD pcoordMaximumWindowSize,
_Out_ PWORD pwPopupAttributes,
_Out_writes_(COLOR_TABLE_SIZE) LPCOLORREF lpColorTable) const
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
*pcoordSize = GetBufferSize().Dimensions();
*pcoordCursorPosition = _textBuffer->GetCursor().GetPosition();
*psrWindow = _viewport.ToInclusive();
*pwAttributes = gci.GenerateLegacyAttributes(GetAttributes());
*pwPopupAttributes = gci.GenerateLegacyAttributes(_PopupAttributes);
// the copy length must be constant for now to keep OACR happy with buffer overruns.
memmove(lpColorTable, gci.GetColorTable(), COLOR_TABLE_SIZE * sizeof(COLORREF));
*pcoordMaximumWindowSize = GetMaxWindowSizeInCharacters();
}
// Routine Description:
// - Gets the smallest possible client area in characters. Takes the window client area and divides by the active font dimensions.
// Arguments:
// - coordFontSize - The font size to use for calculation if a screen buffer is not yet attached.
// Return Value:
// - COORD containing the width and height representing the minimum character grid that can be rendered in the window.
COORD SCREEN_INFORMATION::GetMinWindowSizeInCharacters(const COORD coordFontSize /*= { 1, 1 }*/) const
{
FAIL_FAST_IF(coordFontSize.X == 0);
FAIL_FAST_IF(coordFontSize.Y == 0);
// prepare rectangle
RECT const rcWindowInPixels = _pConsoleWindowMetrics->GetMinClientRectInPixels();
// assign the pixel widths and heights to the final output
COORD coordClientAreaSize;
coordClientAreaSize.X = (SHORT)RECT_WIDTH(&rcWindowInPixels);
coordClientAreaSize.Y = (SHORT)RECT_HEIGHT(&rcWindowInPixels);
// now retrieve the font size and divide the pixel counts into character counts
COORD coordFont = coordFontSize; // by default, use the size we were given
// If text info has been set up, instead retrieve its font size
if (_textBuffer != nullptr)
{
coordFont = GetScreenFontSize();
}
FAIL_FAST_IF(coordFont.X == 0);
FAIL_FAST_IF(coordFont.Y == 0);
coordClientAreaSize.X /= coordFont.X;
coordClientAreaSize.Y /= coordFont.Y;
return coordClientAreaSize;
}
// Routine Description:
// - Gets the maximum client area in characters that would fit on the current monitor or given the current buffer size.
// Takes the monitor work area and divides by the active font dimensions then limits by buffer size.
// Arguments:
// - coordFontSize - The font size to use for calculation if a screen buffer is not yet attached.
// Return Value:
// - COORD containing the width and height representing the largest character
// grid that can be rendered on the current monitor and/or from the current buffer size.
COORD SCREEN_INFORMATION::GetMaxWindowSizeInCharacters(const COORD coordFontSize /*= { 1, 1 }*/) const
{
FAIL_FAST_IF(coordFontSize.X == 0);
FAIL_FAST_IF(coordFontSize.Y == 0);
const COORD coordScreenBufferSize = GetBufferSize().Dimensions();
COORD coordClientAreaSize = coordScreenBufferSize;
// Important re: headless consoles on onecore (for telnetd, etc.)
// GetConsoleScreenBufferInfoEx hits this to get the max size of the display.
// Because we're headless, we don't really care about the max size of the display.
// In that case, we'll just return the buffer size as the "max" window size.
if (!ServiceLocator::LocateGlobals().IsHeadless())
{
const COORD coordWindowRestrictedSize = GetLargestWindowSizeInCharacters(coordFontSize);
// If the buffer is smaller than what the max window would allow, then the max client area can only be as big as the
// buffer we have.
coordClientAreaSize.X = std::min(coordScreenBufferSize.X, coordWindowRestrictedSize.X);
coordClientAreaSize.Y = std::min(coordScreenBufferSize.Y, coordWindowRestrictedSize.Y);
}
return coordClientAreaSize;
}
// Routine Description:
// - Gets the largest possible client area in characters if the window were stretched as large as it could go.
// - Takes the window client area and divides by the active font dimensions.
// Arguments:
// - coordFontSize - The font size to use for calculation if a screen buffer is not yet attached.
// Return Value:
// - COORD containing the width and height representing the largest character
// grid that can be rendered on the current monitor with the maximum size window.
COORD SCREEN_INFORMATION::GetLargestWindowSizeInCharacters(const COORD coordFontSize /*= { 1, 1 }*/) const
{
FAIL_FAST_IF(coordFontSize.X == 0);
FAIL_FAST_IF(coordFontSize.Y == 0);
RECT const rcClientInPixels = _pConsoleWindowMetrics->GetMaxClientRectInPixels();
// first assign the pixel widths and heights to the final output
COORD coordClientAreaSize;
coordClientAreaSize.X = (SHORT)RECT_WIDTH(&rcClientInPixels);
coordClientAreaSize.Y = (SHORT)RECT_HEIGHT(&rcClientInPixels);
// now retrieve the font size and divide the pixel counts into character counts
COORD coordFont = coordFontSize; // by default, use the size we were given
// If renderer has been set up, instead retrieve its font size
if (ServiceLocator::LocateGlobals().pRender != nullptr)
{
coordFont = GetScreenFontSize();
}
FAIL_FAST_IF(coordFont.X == 0);
FAIL_FAST_IF(coordFont.Y == 0);
coordClientAreaSize.X /= coordFont.X;
coordClientAreaSize.Y /= coordFont.Y;
return coordClientAreaSize;
}
COORD SCREEN_INFORMATION::GetScrollBarSizesInCharacters() const
{
COORD coordFont = GetScreenFontSize();
SHORT vScrollSize = ServiceLocator::LocateGlobals().sVerticalScrollSize;
SHORT hScrollSize = ServiceLocator::LocateGlobals().sHorizontalScrollSize;
COORD coordBarSizes;
coordBarSizes.X = (vScrollSize / coordFont.X) + ((vScrollSize % coordFont.X) != 0 ? 1 : 0);
coordBarSizes.Y = (hScrollSize / coordFont.Y) + ((hScrollSize % coordFont.Y) != 0 ? 1 : 0);
return coordBarSizes;
}
void SCREEN_INFORMATION::GetRequiredConsoleSizeInPixels(_Out_ PSIZE const pRequiredSize) const
{
COORD const coordFontSize = GetCurrentFont().GetSize();
// TODO: Assert valid size boundaries
pRequiredSize->cx = GetViewport().Width() * coordFontSize.X;
pRequiredSize->cy = GetViewport().Height() * coordFontSize.Y;
}
COORD SCREEN_INFORMATION::GetScreenFontSize() const
{
// If we have no renderer, then we don't really need any sort of pixel math. so the "font size" for the scale factor
// (which is used almost everywhere around the code as * and / calls) should just be 1,1 so those operations will do
// effectively nothing.
COORD coordRet = { 1, 1 };
if (ServiceLocator::LocateGlobals().pRender != nullptr)
{
coordRet = GetCurrentFont().GetSize();
}
// For sanity's sake, make sure not to leak 0 out as a possible value. These values are used in division operations.
coordRet.X = std::max(coordRet.X, 1i16);
coordRet.Y = std::max(coordRet.Y, 1i16);
return coordRet;
}
#pragma endregion
#pragma region Set Data
void SCREEN_INFORMATION::RefreshFontWithRenderer()
{
if (IsActiveScreenBuffer())
{
// Hand the handle to our internal structure to the font change trigger in case it updates it based on what's appropriate.
if (ServiceLocator::LocateGlobals().pRender != nullptr)
{
ServiceLocator::LocateGlobals().pRender->TriggerFontChange(ServiceLocator::LocateGlobals().dpi,
GetDesiredFont(),
GetCurrentFont());
NotifyGlyphWidthFontChanged();
}
}
}
void SCREEN_INFORMATION::UpdateFont(const FontInfo* const pfiNewFont)
{
FontInfoDesired fiDesiredFont(*pfiNewFont);
GetDesiredFont() = fiDesiredFont;
RefreshFontWithRenderer();
// If we're the active screen buffer...
if (IsActiveScreenBuffer())
{
// If there is a window attached, let it know that it should try to update so the rows/columns are now accounting for the new font.
IConsoleWindow* const pWindow = ServiceLocator::LocateConsoleWindow();
if (nullptr != pWindow)
{
COORD coordViewport = GetViewport().Dimensions();
pWindow->UpdateWindowSize(coordViewport);
}
}
// If we're an alt buffer, also update our main buffer.
if (_psiMainBuffer)
{
_psiMainBuffer->UpdateFont(pfiNewFont);
}
}
// NOTE: This method was historically used to notify accessibility apps AND
// to aggregate drawing metadata to determine whether or not to use PolyTextOut.
// After the Nov 2015 graphics refactor, the metadata drawing flag calculation is no longer necessary.
// This now only notifies accessibility apps of a change.
void SCREEN_INFORMATION::NotifyAccessibilityEventing(const short sStartX,
const short sStartY,
const short sEndX,
const short sEndY)
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
// Fire off a winevent to let accessibility apps know what changed.
if (IsActiveScreenBuffer())
{
const COORD coordScreenBufferSize = GetBufferSize().Dimensions();
FAIL_FAST_IF(!(sEndX < coordScreenBufferSize.X));
if (sStartX == sEndX && sStartY == sEndY)
{
try
{
const auto cellData = GetCellDataAt({ sStartX, sStartY });
const LONG charAndAttr = MAKELONG(Utf16ToUcs2(cellData->Chars()),
gci.GenerateLegacyAttributes(cellData->TextAttr()));
_pAccessibilityNotifier->NotifyConsoleUpdateSimpleEvent(MAKELONG(sStartX, sStartY),
charAndAttr);
}
catch (...)
{
LOG_HR(wil::ResultFromCaughtException());
return;
}
}
else
{
_pAccessibilityNotifier->NotifyConsoleUpdateRegionEvent(MAKELONG(sStartX, sStartY),
MAKELONG(sEndX, sEndY));
}
IConsoleWindow* pConsoleWindow = ServiceLocator::LocateConsoleWindow();
if (pConsoleWindow)
{
LOG_IF_FAILED(pConsoleWindow->SignalUia(UIA_Text_TextChangedEventId));
// TODO MSFT 7960168 do we really need this event to not signal?
//pConsoleWindow->SignalUia(UIA_LayoutInvalidatedEventId);
}
}
}
#pragma endregion
#pragma region UI_Refresh
VOID SCREEN_INFORMATION::UpdateScrollBars()
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (!IsActiveScreenBuffer())
{
return;
}
if (gci.Flags & CONSOLE_UPDATING_SCROLL_BARS)
{
return;
}
gci.Flags |= CONSOLE_UPDATING_SCROLL_BARS;
if (ServiceLocator::LocateConsoleWindow() != nullptr)
{
ServiceLocator::LocateConsoleWindow()->PostUpdateScrollBars();
}
}
VOID SCREEN_INFORMATION::InternalUpdateScrollBars()
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
IConsoleWindow* const pWindow = ServiceLocator::LocateConsoleWindow();
WI_ClearFlag(gci.Flags, CONSOLE_UPDATING_SCROLL_BARS);
if (!IsActiveScreenBuffer())
{
return;
}
ResizingWindow++;
if (pWindow != nullptr)
{
const auto buffer = GetBufferSize();
// If this is the main buffer, make sure we enable both of the scroll bars.
// The alt buffer likely disabled the scroll bars, this is the only
// way to re-enable it.
if (!_IsAltBuffer())
{
pWindow->EnableBothScrollBars();
}
pWindow->UpdateScrollBar(true,
_IsAltBuffer() || gci.IsTerminalScrolling(),
_viewport.Height(),
gci.IsTerminalScrolling() ? _virtualBottom : buffer.BottomInclusive(),
_viewport.Top());
pWindow->UpdateScrollBar(false,
_IsAltBuffer(),
_viewport.Width(),
buffer.RightInclusive(),
_viewport.Left());
}
// Fire off an event to let accessibility apps know the layout has changed.
_pAccessibilityNotifier->NotifyConsoleLayoutEvent();
ResizingWindow--;
}
// Routine Description:
// - Modifies the size of the current viewport to match the width/height of the request given.
// - This will act like a resize operation from the bottom right corner of the window.
// Arguments:
// - pcoordSize - Requested viewport width/heights in characters
// Return Value:
// - <none>
void SCREEN_INFORMATION::SetViewportSize(const COORD* const pcoordSize)
{
// If this is the alt buffer or a VT I/O buffer:
// first resize ourselves to match the new viewport
// then also make sure that the main buffer gets the same call
// (if necessary)
if (_IsInPtyMode())
{
LOG_IF_FAILED(ResizeScreenBuffer(*pcoordSize, TRUE));
if (_psiMainBuffer)
{
const auto bufferSize = GetBufferSize().Dimensions();
_psiMainBuffer->SetViewportSize(&bufferSize);
}
}
_InternalSetViewportSize(pcoordSize, false, false);
}
// Method Description:
// - Update the origin of the buffer's viewport. You can either move the
// viewport with a delta relative to its current location, or set its
// absolute origin. Either way leaves the dimensions of the viewport
// unchanged. Also potentially updates our "virtual bottom", the last real
// location of the viewport in the buffer.
// Also notifies the window implementation to update its scrollbars.
// Arguments:
// - fAbsolute: If true, coordWindowOrigin is the absolute location of the origin of the new viewport.
// If false, coordWindowOrigin is a delta to move the viewport relative to its current position.
// - coordWindowOrigin: Either the new absolute position of the origin of the
// viewport, or a delta to add to the current viewport location.
// - updateBottom: If true, update our virtual bottom position. This should be
// false if we're moving the viewport in response to the users scrolling up
// and down in the buffer, but API calls should set this to true.
// Return Value:
// - STATUS_INVALID_PARAMETER if the new viewport would be outside the buffer,
// else STATUS_SUCCESS
[[nodiscard]] NTSTATUS SCREEN_INFORMATION::SetViewportOrigin(const bool fAbsolute,
const COORD coordWindowOrigin,
const bool updateBottom)
{
// calculate window size
COORD WindowSize = _viewport.Dimensions();
SMALL_RECT NewWindow;
// if relative coordinates, figure out absolute coords.
if (!fAbsolute)
{
if (coordWindowOrigin.X == 0 && coordWindowOrigin.Y == 0)
{
return STATUS_SUCCESS;
}
NewWindow.Left = _viewport.Left() + coordWindowOrigin.X;
NewWindow.Top = _viewport.Top() + coordWindowOrigin.Y;
}
else
{
if (coordWindowOrigin == _viewport.Origin())
{
return STATUS_SUCCESS;
}
NewWindow.Left = coordWindowOrigin.X;
NewWindow.Top = coordWindowOrigin.Y;
}
NewWindow.Right = (SHORT)(NewWindow.Left + WindowSize.X - 1);
NewWindow.Bottom = (SHORT)(NewWindow.Top + WindowSize.Y - 1);
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
// If we're in terminal scrolling mode, and we're rying to set the viewport
// below the logical viewport, without updating our virtual bottom
// (the logical viewport's position), dont.
// Instead move us to the bottom of the logical viewport.
if (gci.IsTerminalScrolling() && !updateBottom && NewWindow.Bottom > _virtualBottom)
{
const short delta = _virtualBottom - NewWindow.Bottom;
NewWindow.Top += delta;
NewWindow.Bottom += delta;
}
// see if new window origin would extend window beyond extent of screen buffer
const COORD coordScreenBufferSize = GetBufferSize().Dimensions();
if (NewWindow.Left < 0 ||
NewWindow.Top < 0 ||
NewWindow.Right < 0 ||
NewWindow.Bottom < 0 ||
NewWindow.Right >= coordScreenBufferSize.X ||
NewWindow.Bottom >= coordScreenBufferSize.Y)
{
return STATUS_INVALID_PARAMETER;
}
if (IsActiveScreenBuffer() && ServiceLocator::LocateConsoleWindow() != nullptr)
{
// Tell the window that it needs to set itself to the new origin if we're the active buffer.
ServiceLocator::LocateConsoleWindow()->ChangeViewport(NewWindow);
}
else
{
// Otherwise, just store the new position and go on.
_viewport = Viewport::FromInclusive(NewWindow);
Tracing::s_TraceWindowViewport(_viewport);
}
// Update our internal virtual bottom tracker if requested. This helps keep
// the viewport's logical position consistent from the perspective of a
// VT client application, even if the user scrolls the viewport with the mouse.
if (updateBottom)
{
UpdateBottom();
}
return STATUS_SUCCESS;
}
bool SCREEN_INFORMATION::SendNotifyBeep() const
{
if (IsActiveScreenBuffer())
{
if (ServiceLocator::LocateConsoleWindow() != nullptr)
{
return ServiceLocator::LocateConsoleWindow()->SendNotifyBeep();
}
}
return false;
}
bool SCREEN_INFORMATION::PostUpdateWindowSize() const
{
if (IsActiveScreenBuffer())
{
if (ServiceLocator::LocateConsoleWindow() != nullptr)
{
return ServiceLocator::LocateConsoleWindow()->PostUpdateWindowSize();
}
}
return false;
}
// Routine Description:
// - Modifies the screen buffer and viewport dimensions when the available client area rendering space changes.
// Arguments:
// - prcClientNew - Client rectangle in pixels after this update
// - prcClientOld - Client rectangle in pixels before this update
// Return Value:
// - <none>
void SCREEN_INFORMATION::ProcessResizeWindow(const RECT* const prcClientNew,
const RECT* const prcClientOld)
{
if (_IsAltBuffer())
{
// Stash away the size of the window, we'll need to do this to the main when we pop back
// We set this on the main, so that main->alt(resize)->alt keeps the resize
_psiMainBuffer->_fAltWindowChanged = true;
_psiMainBuffer->_rcAltSavedClientNew = *prcClientNew;
_psiMainBuffer->_rcAltSavedClientOld = *prcClientOld;
}
// 1.a In some modes, the screen buffer size needs to change on window size,
// so do that first.
// _AdjustScreenBuffer might hide the commandline. If it does so, it'll
// return S_OK instead of S_FALSE. In that case, we'll need to re-show
// the commandline ourselves once the viewport size is updated.
// (See 1.b below)
const HRESULT adjustBufferSizeResult = _AdjustScreenBuffer(prcClientNew);
LOG_IF_FAILED(adjustBufferSizeResult);
// 2. Now calculate how large the new viewport should be
COORD coordViewportSize;
_CalculateViewportSize(prcClientNew, &coordViewportSize);
// 3. And adjust the existing viewport to match the same dimensions.
// The old/new comparison is to figure out which side the window was resized from.
_AdjustViewportSize(prcClientNew, prcClientOld, &coordViewportSize);
// 1.b If we did actually change the buffer size, then we need to show the
// commandline again. We hid it during _AdjustScreenBuffer, but we
// couldn't turn it back on until the Viewport was updated to the new
// size. See MSFT:19976291
if (SUCCEEDED(adjustBufferSizeResult) && adjustBufferSizeResult != S_FALSE)
{
CommandLine& commandLine = CommandLine::Instance();
commandLine.Show();
}
// 4. Finally, update the scroll bars.
UpdateScrollBars();
FAIL_FAST_IF(!(_viewport.Top() >= 0));
// TODO MSFT: 17663344 - Audit call sites for this precondition. Extremely tiny offscreen windows.
//FAIL_FAST_IF(!(_viewport.IsValid()));
}
#pragma endregion
#pragma region Support_Calculation
// Routine Description:
// - This helper converts client pixel areas into the number of characters that could fit into the client window.
// - It requires the buffer size to figure out whether it needs to reserve space for the scroll bars (or not).
// Arguments:
// - prcClientNew - Client region of window in pixels
// - coordBufferOld - Size of backing buffer in characters
// - pcoordClientNewCharacters - The maximum number of characters X by Y that can be displayed in the window with the given backing buffer.
// Return Value:
// - S_OK if math was successful. Check with SUCCEEDED/FAILED macro.
[[nodiscard]] HRESULT SCREEN_INFORMATION::_AdjustScreenBufferHelper(const RECT* const prcClientNew,
const COORD coordBufferOld,
_Out_ COORD* const pcoordClientNewCharacters)
{
// Get the font size ready.
COORD const coordFontSize = GetScreenFontSize();
// We cannot operate if the font size is 0. This shouldn't happen, but stop early if it does.
RETURN_HR_IF(E_NOT_VALID_STATE, 0 == coordFontSize.X || 0 == coordFontSize.Y);
// Find out how much client space we have to work with in the new area.
SIZE sizeClientNewPixels = { 0 };
sizeClientNewPixels.cx = RECT_WIDTH(prcClientNew);
sizeClientNewPixels.cy = RECT_HEIGHT(prcClientNew);
// Subtract out scroll bar space if scroll bars will be necessary.
bool fIsHorizontalVisible = false;
bool fIsVerticalVisible = false;
s_CalculateScrollbarVisibility(prcClientNew, &coordBufferOld, &coordFontSize, &fIsHorizontalVisible, &fIsVerticalVisible);
if (fIsHorizontalVisible)
{
sizeClientNewPixels.cy -= ServiceLocator::LocateGlobals().sHorizontalScrollSize;
}
if (fIsVerticalVisible)
{
sizeClientNewPixels.cx -= ServiceLocator::LocateGlobals().sVerticalScrollSize;
}
// Now with the scroll bars removed, calculate how many characters could fit into the new window area.
pcoordClientNewCharacters->X = (SHORT)(sizeClientNewPixels.cx / coordFontSize.X);
pcoordClientNewCharacters->Y = (SHORT)(sizeClientNewPixels.cy / coordFontSize.Y);
// If the new client is too tiny, our viewport will be 1x1.
pcoordClientNewCharacters->X = std::max(pcoordClientNewCharacters->X, 1i16);
pcoordClientNewCharacters->Y = std::max(pcoordClientNewCharacters->Y, 1i16);
return S_OK;
}
// Routine Description:
// - Modifies the size of the backing text buffer when the window changes to support "intuitive" resizing modes by grabbing the window edges.
// - This function will compensate for scroll bars.
// - Buffer size changes will happen internally to this function.
// Arguments:
// - prcClientNew - Client rectangle in pixels after this update
// Return Value:
// - appropriate HRESULT
[[nodiscard]] HRESULT SCREEN_INFORMATION::_AdjustScreenBuffer(const RECT* const prcClientNew)
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
// Prepare the buffer sizes.
// We need the main's size here to maintain the right scrollbar visibility.
COORD const coordBufferSizeOld = _IsAltBuffer() ? _psiMainBuffer->GetBufferSize().Dimensions() : GetBufferSize().Dimensions();
COORD coordBufferSizeNew = coordBufferSizeOld;
// First figure out how many characters we could fit into the new window given the old buffer size
COORD coordClientNewCharacters;
RETURN_IF_FAILED(_AdjustScreenBufferHelper(prcClientNew, coordBufferSizeOld, &coordClientNewCharacters));
// If we're in wrap text mode, then we want to be fixed to the window size. So use the character calculation we just got
// to fix the buffer and window width together.
if (gci.GetWrapText())
{
coordBufferSizeNew.X = coordClientNewCharacters.X;
}
// Reanalyze scroll bars in case we fixed the edge together for word wrap.
// Use the new buffer client size.
RETURN_IF_FAILED(_AdjustScreenBufferHelper(prcClientNew, coordBufferSizeNew, &coordClientNewCharacters));
// Now reanalyze the buffer size and grow if we can fit more characters into the window no matter the console mode.
if (_IsInPtyMode())
{
// The alt buffer always wants to be exactly the size of the screen, never more or less.
// This prevents scrollbars when you increase the alt buffer size, then decrease it.
// Can't have a buffer dimension of 0 - that'll cause divide by zeros in the future.
coordBufferSizeNew.X = std::max(coordClientNewCharacters.X, 1i16);
coordBufferSizeNew.Y = std::max(coordClientNewCharacters.Y, 1i16);
}
else
{
if (coordClientNewCharacters.X > coordBufferSizeNew.X)
{
coordBufferSizeNew.X = coordClientNewCharacters.X;
}