-
Notifications
You must be signed in to change notification settings - Fork 9.6k
Expand file tree
/
Copy pathgetset.cpp
More file actions
1683 lines (1465 loc) · 67.6 KB
/
Copy pathgetset.cpp
File metadata and controls
1683 lines (1465 loc) · 67.6 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "getset.h"
#include "ApiRoutines.h"
#include "directio.h"
#include "handle.h"
#include "misc.h"
#include "output.h"
#include "_output.h"
#include "_stream.h"
#include "../interactivity/inc/ServiceLocator.hpp"
#include "../terminal/parser/InputStateMachineEngine.hpp"
#include "../types/inc/convert.hpp"
#include "../types/inc/viewport.hpp"
#pragma hdrstop
// The following mask is used to test for valid text attributes.
#define VALID_TEXT_ATTRIBUTES (FG_ATTRS | BG_ATTRS | META_ATTRS)
#define INPUT_MODES (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT | ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_VIRTUAL_TERMINAL_INPUT)
#define OUTPUT_MODES (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN | ENABLE_LVB_GRID_WORLDWIDE)
#define PRIVATE_MODES (ENABLE_INSERT_MODE | ENABLE_QUICK_EDIT_MODE | ENABLE_AUTO_POSITION | ENABLE_EXTENDED_FLAGS)
using namespace Microsoft::Console::Types;
using namespace Microsoft::Console::Interactivity;
// Routine Description:
// - Retrieves the console input mode (settings that apply when manipulating the input buffer)
// Arguments:
// - context - The input buffer concerned
// - mode - Receives the mode flags set
void ApiRoutines::GetConsoleInputModeImpl(InputBuffer& context, ULONG& mode) noexcept
{
try
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
mode = context.InputMode;
if (WI_IsFlagSet(gci.Flags, CONSOLE_USE_PRIVATE_FLAGS))
{
WI_SetFlag(mode, ENABLE_EXTENDED_FLAGS);
WI_SetFlagIf(mode, ENABLE_INSERT_MODE, gci.GetInsertMode());
WI_SetFlagIf(mode, ENABLE_QUICK_EDIT_MODE, WI_IsFlagSet(gci.Flags, CONSOLE_QUICK_EDIT_MODE));
WI_SetFlagIf(mode, ENABLE_AUTO_POSITION, WI_IsFlagSet(gci.Flags, CONSOLE_AUTO_POSITION));
}
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves the console output mode (settings that apply when manipulating the output buffer)
// Arguments:
// - context - The output buffer concerned
// - mode - Receives the mode flags set
void ApiRoutines::GetConsoleOutputModeImpl(SCREEN_INFORMATION& context, ULONG& mode) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
mode = context.GetActiveBuffer().OutputMode;
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves the number of console event items in the input queue right now
// Arguments:
// - context - The input buffer concerned
// - event - The count of events in the queue
// Return Value:
// - S_OK or math failure.
[[nodiscard]] HRESULT ApiRoutines::GetNumberOfConsoleInputEventsImpl(const InputBuffer& context, ULONG& events) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const auto readyEventCount = context.GetNumberOfReadyEvents();
RETURN_IF_FAILED(SizeTToULong(readyEventCount, &events));
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves metadata associated with the output buffer (size, default colors, etc.)
// Arguments:
// - context - The output buffer concerned
// - data - Receives structure filled with metadata about the output buffer
void ApiRoutines::GetConsoleScreenBufferInfoExImpl(const SCREEN_INFORMATION& context,
CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
data.bFullscreenSupported = FALSE; // traditional full screen with the driver support is no longer supported.
// see MSFT: 19918103
// Make sure to use the active buffer here. There are clients that will
// use WINDOW_SIZE_EVENTs as a signal to then query the console
// with GetConsoleScreenBufferInfoEx to get the actual viewport
// size.
// If they're in the alt buffer, then when they query in that way, the
// value they'll get is the main buffer's size, which isn't updated
// until we switch back to it.
til::size dwSize;
til::point dwCursorPosition;
til::inclusive_rect srWindow;
til::size dwMaximumWindowSize;
context.GetActiveBuffer().GetScreenBufferInformation(&dwSize,
&dwCursorPosition,
&srWindow,
&data.wAttributes,
&dwMaximumWindowSize,
&data.wPopupAttributes,
data.ColorTable);
// Callers of this function expect to receive an exclusive rect, not an
// inclusive one. The driver will mangle this value for us
// - For GetConsoleScreenBufferInfoEx, it will re-decrement these values
// to return an inclusive rect.
// - For GetConsoleScreenBufferInfo, it will leave these values
// untouched, returning an exclusive rect.
srWindow.right += 1;
srWindow.bottom += 1;
data.dwSize = til::unwrap_coord_size(dwSize);
data.dwCursorPosition = til::unwrap_coord(dwCursorPosition);
data.srWindow = til::unwrap_small_rect(srWindow);
data.dwMaximumWindowSize = til::unwrap_coord_size(dwMaximumWindowSize);
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves information about the console cursor's display state
// Arguments:
// - context - The output buffer concerned
// - size - The size as a percentage of the total possible height (0-100 for percentages).
// - isVisible - Whether the cursor is displayed or hidden
void ApiRoutines::GetConsoleCursorInfoImpl(const SCREEN_INFORMATION& context,
ULONG& size,
bool& isVisible) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
size = context.GetActiveBuffer().GetTextBuffer().GetCursor().GetSize();
isVisible = context.GetTextBuffer().GetCursor().IsVisible();
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves information about the selected area in the console
// Arguments:
// - consoleSelectionInfo - contains flags, anchors, and area to describe selection area
void ApiRoutines::GetConsoleSelectionInfoImpl(CONSOLE_SELECTION_INFO& consoleSelectionInfo) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const auto& selection = Selection::Instance();
if (selection.IsInSelectingState())
{
consoleSelectionInfo.dwFlags = selection.GetPublicSelectionFlags();
WI_SetFlag(consoleSelectionInfo.dwFlags, CONSOLE_SELECTION_IN_PROGRESS);
consoleSelectionInfo.dwSelectionAnchor = til::unwrap_coord(selection.GetSelectionAnchor());
consoleSelectionInfo.srSelection = til::unwrap_small_rect(selection.GetSelectionRectangle());
}
else
{
ZeroMemory(&consoleSelectionInfo, sizeof(consoleSelectionInfo));
}
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves the number of buttons on the mouse as reported by the system
// Arguments:
// - buttons - Count of buttons
void ApiRoutines::GetNumberOfConsoleMouseButtonsImpl(ULONG& buttons) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
buttons = ServiceLocator::LocateSystemConfigurationProvider()->GetNumberOfMouseButtons();
}
CATCH_LOG();
}
// Routine Description:
// - Retrieves information about a known font based on index
// Arguments:
// - context - The output buffer concerned
// - index - We only accept 0 now as we don't keep a list of fonts in memory.
// - size - The X by Y pixel size of the font
// Return Value:
// - S_OK, E_INVALIDARG or code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetConsoleFontSizeImpl(const SCREEN_INFORMATION& context,
const DWORD index,
til::size& size) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
if (index == 0)
{
// As of the November 2015 renderer system, we only have a single font at index 0.
size = context.GetActiveBuffer().GetCurrentFont().GetUnscaledSize();
return S_OK;
}
else
{
// Invalid font is 0,0 with STATUS_INVALID_PARAMETER
size = {};
return E_INVALIDARG;
}
}
CATCH_RETURN();
}
// Routine Description:
// - Retrieves information about the console cursor's display state
// Arguments:
// - context - The output buffer concerned
// - isForMaximumWindowSize - Returns the maximum number of characters in the largest window size if true. Otherwise, it's the size of the font.
// - consoleFontInfoEx - structure containing font information like size, family, weight, etc.
// Return Value:
// - S_OK, string copy failure code or code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::GetCurrentConsoleFontExImpl(const SCREEN_INFORMATION& context,
const bool isForMaximumWindowSize,
CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const auto& activeScreenInfo = context.GetActiveBuffer();
til::size WindowSize;
if (isForMaximumWindowSize)
{
WindowSize = activeScreenInfo.GetMaxWindowSizeInCharacters();
}
else
{
WindowSize = activeScreenInfo.GetCurrentFont().GetUnscaledSize();
}
consoleFontInfoEx.dwFontSize = til::unwrap_coord_size(WindowSize);
consoleFontInfoEx.nFont = 0;
const auto& fontInfo = activeScreenInfo.GetCurrentFont();
consoleFontInfoEx.FontFamily = fontInfo.GetFamily();
consoleFontInfoEx.FontWeight = fontInfo.GetWeight();
fontInfo.FillLegacyNameBuffer(consoleFontInfoEx.FaceName);
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the current font to be used for drawing
// Arguments:
// - context - The output buffer concerned
// - isForMaximumWindowSize - Obsolete.
// - consoleFontInfoEx - structure containing font information like size, family, weight, etc.
// Return Value:
// - S_OK, string copy failure code or code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetCurrentConsoleFontExImpl(IConsoleOutputObject& context,
const bool /*isForMaximumWindowSize*/,
const CONSOLE_FONT_INFOEX& consoleFontInfoEx) noexcept
{
try
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& activeScreenInfo = context.GetActiveBuffer();
WCHAR FaceName[ARRAYSIZE(consoleFontInfoEx.FaceName)];
RETURN_IF_FAILED(StringCchCopyW(FaceName, ARRAYSIZE(FaceName), consoleFontInfoEx.FaceName));
FontInfo fi(FaceName,
gsl::narrow_cast<unsigned char>(consoleFontInfoEx.FontFamily),
consoleFontInfoEx.FontWeight,
til::wrap_coord_size(consoleFontInfoEx.dwFontSize),
gci.OutputCP);
// TODO: MSFT: 9574827 - should this have a failure case?
activeScreenInfo.UpdateFont(&fi);
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the input mode for the console
// Arguments:
// - context - The input buffer concerned
// - mode - flags that change behavior of the buffer
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleInputModeImpl(InputBuffer& context, const ULONG mode) noexcept
{
try
{
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const auto oldQuickEditMode{ WI_IsFlagSet(gci.Flags, CONSOLE_QUICK_EDIT_MODE) };
if (WI_IsAnyFlagSet(mode, PRIVATE_MODES))
{
WI_SetFlag(gci.Flags, CONSOLE_USE_PRIVATE_FLAGS);
WI_UpdateFlag(gci.Flags, CONSOLE_QUICK_EDIT_MODE, WI_IsFlagSet(mode, ENABLE_QUICK_EDIT_MODE));
WI_UpdateFlag(gci.Flags, CONSOLE_AUTO_POSITION, WI_IsFlagSet(mode, ENABLE_AUTO_POSITION));
const auto PreviousInsertMode = gci.GetInsertMode();
gci.SetInsertMode(WI_IsFlagSet(mode, ENABLE_INSERT_MODE));
if (gci.GetInsertMode() != PreviousInsertMode)
{
gci.GetActiveOutputBuffer().SetCursorDBMode(false);
if (gci.HasPendingCookedRead())
{
gci.CookedReadData().SetInsertMode(gci.GetInsertMode());
}
}
}
else
{
WI_ClearFlag(gci.Flags, CONSOLE_USE_PRIVATE_FLAGS);
}
if (auto writer = gci.GetVtWriter())
{
auto oldMode = context.InputMode;
auto newMode = mode;
// Mouse input should be received when mouse mode is on and quick edit mode is off
// (for more information regarding the quirks of mouse mode and why/how it relates
// to quick edit mode, see GH#9970)
const auto newQuickEditMode{ WI_IsFlagSet(gci.Flags, CONSOLE_QUICK_EDIT_MODE) };
WI_ClearFlagIf(oldMode, ENABLE_MOUSE_INPUT, oldQuickEditMode);
WI_ClearFlagIf(newMode, ENABLE_MOUSE_INPUT, newQuickEditMode);
if (const auto diff = oldMode ^ newMode)
{
if (WI_IsFlagSet(diff, ENABLE_MOUSE_INPUT))
{
writer.WriteSGR1006(WI_IsFlagSet(newMode, ENABLE_MOUSE_INPUT));
}
}
writer.Submit();
}
context.InputMode = mode;
WI_ClearAllFlags(context.InputMode, PRIVATE_MODES);
// NOTE: For compatibility reasons, we need to set the modes and then return the error codes, not the other way around
// as might be expected.
// This is a bug from a long time ago and some applications depend on this functionality to operate properly.
// ---
// A prime example of this is that PSReadline module in Powershell will set the invalid mode 0x1e4
// which includes 0x4 for ECHO_INPUT but turns off 0x2 for LINE_INPUT. This is invalid, but PSReadline
// relies on it to properly receive the ^C printout and make a new line when the user presses Ctrl+C.
{
// Flags we don't understand are invalid.
RETURN_HR_IF(E_INVALIDARG, WI_IsAnyFlagSet(mode, ~(INPUT_MODES | PRIVATE_MODES)));
// ECHO on with LINE off is invalid.
RETURN_HR_IF_EXPECTED(E_INVALIDARG, WI_IsFlagSet(mode, ENABLE_ECHO_INPUT) && WI_IsFlagClear(mode, ENABLE_LINE_INPUT));
}
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the output mode for the console
// Arguments:
// - context - The output buffer concerned
// - mode - flags that change behavior of the buffer
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleOutputModeImpl(SCREEN_INFORMATION& context, const ULONG mode) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Flags we don't understand are invalid.
RETURN_HR_IF(E_INVALIDARG, WI_IsAnyFlagSet(mode, ~OUTPUT_MODES));
auto& screenInfo = context.GetActiveBuffer();
const auto dwOldMode = screenInfo.OutputMode;
const auto dwNewMode = mode;
const auto diff = dwOldMode ^ dwNewMode;
screenInfo.OutputMode = dwNewMode;
// if we're moving from VT on->off
if (WI_IsFlagClear(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) &&
WI_IsFlagSet(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
// jiggle the handle
screenInfo.GetStateMachine().ResetState();
}
// if we changed rendering modes then redraw the output buffer.
if (WI_IsAnyFlagSet(diff, ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_LVB_GRID_WORLDWIDE))
{
if (const auto pRender = ServiceLocator::LocateGlobals().pRender)
{
pRender->TriggerRedrawAll();
}
}
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (auto writer = gci.GetVtWriterForBuffer(&context))
{
if (WI_IsFlagSet(diff, ENABLE_WRAP_AT_EOL_OUTPUT))
{
writer.WriteDECAWM(WI_IsFlagSet(dwNewMode, ENABLE_WRAP_AT_EOL_OUTPUT));
}
writer.Submit();
}
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the given output buffer as the active one
// Arguments:
// - context - The output buffer concerned
void ApiRoutines::SetConsoleActiveScreenBufferImpl(SCREEN_INFORMATION& newContext) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (&newContext.GetActiveBuffer() == &gci.GetActiveOutputBuffer())
{
return;
}
if (auto writer = gci.GetVtWriter())
{
const auto oldSize = gci.GetActiveOutputBuffer().GetBufferSize().Dimensions();
writer.WriteScreenInfo(newContext, oldSize);
writer.Submit();
}
SetActiveScreenBuffer(newContext.GetActiveBuffer());
}
CATCH_LOG();
}
// Routine Description:
// - Clears all items out of the input buffer queue
// Arguments:
// - context - The input buffer concerned
void ApiRoutines::FlushConsoleInputBuffer(InputBuffer& context) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
context.Flush();
}
CATCH_LOG();
}
// Routine Description:
// - Gets the largest possible window size in characters.
// Arguments:
// - context - The output buffer concerned
// - size - receives the size in character count (rows/columns)
void ApiRoutines::GetLargestConsoleWindowSizeImpl(const SCREEN_INFORMATION& context,
til::size& size) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const auto& screenInfo = context.GetActiveBuffer();
size = screenInfo.GetLargestWindowSizeInCharacters();
}
CATCH_LOG();
}
// Routine Description:
// - Sets the size of the output buffer (screen buffer) in rows/columns
// Arguments:
// - context - The output buffer concerned
// - size - size in character rows and columns
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleScreenBufferSizeImpl(SCREEN_INFORMATION& context,
const til::size size) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& screenInfo = context.GetActiveBuffer();
// microsoft/terminal#3907 - We shouldn't resize the buffer to be
// smaller than the viewport. This was previously erroneously checked
// when the host was not in conpty mode.
RETURN_HR_IF(E_INVALIDARG, (size.width < screenInfo.GetViewport().Width() || size.height < screenInfo.GetViewport().Height()));
// see MSFT:17415266
// We only really care about the minimum window size if we have a head.
if (!ServiceLocator::LocateGlobals().IsHeadless())
{
const auto coordMin = screenInfo.GetMinWindowSizeInCharacters();
// Make sure requested screen buffer size isn't smaller than the window.
RETURN_HR_IF(E_INVALIDARG, (size.height < coordMin.height || size.width < coordMin.width));
}
// Ensure the requested size isn't larger than we can handle in our data type.
RETURN_HR_IF(E_INVALIDARG, (size.width == SHORT_MAX || size.height == SHORT_MAX));
// Only do the resize if we're actually changing one of the dimensions
const auto coordScreenBufferSize = screenInfo.GetBufferSize().Dimensions();
if (size.width != coordScreenBufferSize.width || size.height != coordScreenBufferSize.height)
{
RETURN_IF_NTSTATUS_FAILED(screenInfo.ResizeScreenBuffer(size, TRUE));
}
// Make sure the viewport doesn't now overflow the buffer dimensions.
auto overflow = screenInfo.GetViewport().BottomRightExclusive() - screenInfo.GetBufferSize().Dimensions();
if (overflow.x > 0 || overflow.y > 0)
{
overflow = { -std::max(overflow.x, 0), -std::max(overflow.y, 0) };
RETURN_IF_NTSTATUS_FAILED(screenInfo.SetViewportOrigin(false, overflow, false));
}
// And also that the cursor position is clamped within the buffer boundaries.
auto& cursor = screenInfo.GetTextBuffer().GetCursor();
auto clampedCursorPosition = cursor.GetPosition();
screenInfo.GetBufferSize().Clamp(clampedCursorPosition);
if (clampedCursorPosition != cursor.GetPosition())
{
cursor.SetPosition(clampedCursorPosition);
}
// TODO GH#5094: This could use xterm's XTWINOPS "\e[8;<height>;<width>t" escape sequence here.
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets metadata information on the output buffer
// Arguments:
// - context - The output buffer concerned
// - data - metadata information structure like buffer size, viewport size, colors, and more.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleScreenBufferInfoExImpl(SCREEN_INFORMATION& context,
const CONSOLE_SCREEN_BUFFER_INFOEX& data) noexcept
{
try
{
// clang-format off
RETURN_HR_IF(E_INVALIDARG, (data.dwSize.X == 0 ||
data.dwSize.Y == 0 ||
data.dwSize.X == SHRT_MAX ||
data.dwSize.Y == SHRT_MAX));
// clang-format on
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& g = ServiceLocator::LocateGlobals();
auto& gci = g.getConsoleInformation();
const auto coordScreenBufferSize = context.GetBufferSize().Dimensions();
const auto requestedBufferSize = til::wrap_coord_size(data.dwSize);
if (requestedBufferSize != coordScreenBufferSize)
{
LOG_IF_FAILED(context.ResizeScreenBuffer(requestedBufferSize, TRUE));
}
const auto newBufferSize = context.GetBufferSize().Dimensions();
bool changedOneTableEntry = false;
for (size_t i = 0; i < std::size(data.ColorTable); i++)
{
// Check if we actually changed a palette color
const auto& newColor{ data.ColorTable[i] };
changedOneTableEntry = changedOneTableEntry || (newColor != gci.GetColorTableEntry(i));
// Set the new value.
gci.SetLegacyColorTableEntry(i, newColor);
}
// GH#399: Trigger a redraw, so that updated colors are repainted, but
// only do this if we're not in conpty mode. ConPTY will update the
// colors of the palette elsewhere (after TODO GH#10639)
//
// Only do this if we actually changed the value of the palette though -
// this API gets called all the time to change all sorts of things, but
// not necessarily the palette.
if (changedOneTableEntry)
{
if (auto* pRender{ ServiceLocator::LocateGlobals().pRender })
{
pRender->TriggerRedrawAll();
}
}
context.SetDefaultAttributes(TextAttribute{ data.wAttributes }, TextAttribute{ data.wPopupAttributes });
const auto requestedViewport = Viewport::FromExclusive(til::wrap_exclusive_small_rect(data.srWindow));
auto NewSize = requestedViewport.Dimensions();
// If we have a window, clamp the requested viewport to the max window size
if (!ServiceLocator::LocateGlobals().IsHeadless())
{
NewSize.width = std::min<til::CoordType>(NewSize.width, data.dwMaximumWindowSize.X);
NewSize.height = std::min<til::CoordType>(NewSize.height, data.dwMaximumWindowSize.Y);
}
// If wrap text is on, then the window width must be the same size as the buffer width
if (gci.GetWrapText())
{
NewSize.width = newBufferSize.width;
}
if (NewSize.width != context.GetViewport().Width() ||
NewSize.height != context.GetViewport().Height())
{
context.SetViewportSize(&NewSize);
const auto pWindow = ServiceLocator::LocateConsoleWindow();
if (pWindow != nullptr)
{
pWindow->UpdateWindowSize(NewSize);
}
}
// Despite the fact that this API takes in a srWindow for the viewport, it traditionally actually doesn't set
// anything using that member - for moving the viewport, you need SetConsoleWindowInfo
// (see https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx and DoSrvSetConsoleWindowInfo)
// Note that it also doesn't set cursor position.
// However, we do need to make sure the viewport doesn't now overflow the buffer dimensions.
auto overflow = context.GetViewport().BottomRightExclusive() - context.GetBufferSize().Dimensions();
if (overflow.x > 0 || overflow.y > 0)
{
overflow = { -std::max(overflow.x, 0), -std::max(overflow.y, 0) };
RETURN_IF_NTSTATUS_FAILED(context.SetViewportOrigin(false, overflow, false));
}
// And also that the cursor position is clamped within the buffer boundaries.
auto& cursor = context.GetTextBuffer().GetCursor();
auto clampedCursorPosition = cursor.GetPosition();
context.GetBufferSize().Clamp(clampedCursorPosition);
if (clampedCursorPosition != cursor.GetPosition())
{
cursor.SetPosition(clampedCursorPosition);
}
// TODO GH#5094: This could use xterm's XTWINOPS "\e[8;<height>;<width>t" escape sequence here.
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the cursor position in the given output buffer
// Arguments:
// - context - The output buffer concerned
// - position - The X/Y (row/column) position in the buffer to place the cursor
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleCursorPositionImpl(SCREEN_INFORMATION& context,
const til::point position) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& buffer = context.GetActiveBuffer();
const auto coordScreenBufferSize = buffer.GetBufferSize().Dimensions();
// clang-format off
RETURN_HR_IF(E_INVALIDARG, (position.x >= coordScreenBufferSize.width ||
position.y >= coordScreenBufferSize.height ||
position.x < 0 ||
position.y < 0));
// clang-format on
// MSFT: 15813316 - Try to use this SetCursorPosition call to inherit the cursor position.
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (auto writer = gci.GetVtWriterForBuffer(&context))
{
writer.WriteCUP(position);
writer.Submit();
}
RETURN_IF_NTSTATUS_FAILED(buffer.SetCursorPosition(position));
// Attempt to "snap" the viewport to the cursor position. If the cursor
// is not in the current viewport, we'll try and move the viewport so
// that the cursor is visible.
// GH#1222 and GH#9754 - Use the "virtual" viewport here, so that the
// viewport snaps back to the virtual viewport's location.
const auto currentViewport = buffer.GetVirtualViewport().ToInclusive();
til::point delta;
{
// When evaluating the X offset, we must convert the buffer position to
// equivalent screen coordinates, taking line rendition into account.
const auto lineRendition = buffer.GetTextBuffer().GetLineRendition(position.y);
const auto screenPosition = BufferToScreenLine(til::inclusive_rect{ position.x, position.y, position.x, position.y }, lineRendition);
if (currentViewport.left > screenPosition.left)
{
delta.x = screenPosition.left - currentViewport.left;
}
else if (currentViewport.right < screenPosition.right)
{
delta.x = screenPosition.right - currentViewport.right;
}
if (currentViewport.top > position.y)
{
delta.y = position.y - currentViewport.top;
}
else if (currentViewport.bottom < position.y)
{
delta.y = position.y - currentViewport.bottom;
}
}
til::point newWindowOrigin;
newWindowOrigin.x = currentViewport.left + delta.x;
newWindowOrigin.y = currentViewport.top + delta.y;
// SetViewportOrigin will worry about clamping these values to the
// buffer for us.
RETURN_IF_NTSTATUS_FAILED(buffer.SetViewportOrigin(true, newWindowOrigin, true));
// SetViewportOrigin will only move the virtual bottom down, but in
// this particular case we also need to allow the virtual bottom to
// be moved up, so we have to call UpdateBottom explicitly. This is
// how the cmd shell's CLS command resets the buffer.
buffer.UpdateBottom();
auto& an = ServiceLocator::LocateGlobals().accessibilityNotifier;
an.CursorChanged(buffer.GetTextBuffer().GetCursor().GetPosition(), false);
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets metadata on the cursor
// Arguments:
// - context - The output buffer concerned
// - size - Height percentage of the displayed cursor (when visible)
// - isVisible - Whether or not the cursor should be displayed
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleCursorInfoImpl(SCREEN_INFORMATION& context,
const ULONG size,
const bool isVisible) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// If more than 100% or less than 0% cursor height, reject it.
RETURN_HR_IF(E_INVALIDARG, (size > 100 || size == 0));
context.SetCursorInformation(size, isVisible);
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (auto writer = gci.GetVtWriterForBuffer(&context))
{
writer.WriteDECTCEM(isVisible);
writer.Submit();
}
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Sets the viewport/window information for displaying a portion of the output buffer visually
// Arguments:
// - context - The output buffer concerned
// - isAbsolute - Coordinates are based on the entire screen buffer (origin 0,0) if true.
// - If false, coordinates are a delta from the existing viewport position
// - windowRect - Updated viewport rectangle information
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleWindowInfoImpl(SCREEN_INFORMATION& context,
const bool isAbsolute,
const til::inclusive_rect& windowRect) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& g = ServiceLocator::LocateGlobals();
auto Window = windowRect;
if (!isAbsolute)
{
auto currentViewport = context.GetViewport().ToInclusive();
Window.left += currentViewport.left;
Window.right += currentViewport.right;
Window.top += currentViewport.top;
Window.bottom += currentViewport.bottom;
}
RETURN_HR_IF(E_INVALIDARG, (Window.right < Window.left || Window.bottom < Window.top));
til::size NewWindowSize;
NewWindowSize.width = CalcWindowSizeX(Window);
NewWindowSize.height = CalcWindowSizeY(Window);
// see MSFT:17415266
// If we have an actual head, we care about the maximum size the window can be.
// if we're headless, not so much. However, GetMaxWindowSizeInCharacters
// will only return the buffer size, so we can't use that to clip the arg here.
// So only clip the requested size if we're not headless
if (g.getConsoleInformation().IsInVtIoMode())
{
// SetViewportRect doesn't cause the buffer to resize. Manually resize the buffer.
RETURN_IF_NTSTATUS_FAILED(context.ResizeScreenBuffer(Viewport::FromInclusive(Window).Dimensions(), false));
}
if (!g.IsHeadless())
{
const auto coordMax = context.GetMaxWindowSizeInCharacters();
RETURN_HR_IF(E_INVALIDARG, (NewWindowSize.width > coordMax.width || NewWindowSize.height > coordMax.height));
}
// Even if it's the same size, we need to post an update in case the scroll bars need to go away.
context.SetViewport(Viewport::FromInclusive(Window), true);
if (context.IsActiveScreenBuffer())
{
// TODO: MSFT: 9574827 - shouldn't we be looking at or at least logging the failure codes here? (Or making them non-void?)
context.PostUpdateWindowSize();
// Use WriteToScreen to invalidate the viewport with the renderer.
WriteToScreen(context, context.GetViewport());
}
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Moves a portion of text from one part of the output buffer to another
// Arguments:
// - context - The output buffer concerned
// - source - The rectangular region to copy from
// - target - The top left corner of the destination to paste the copy (source)
// - clip - The rectangle inside which all operations should be bounded (or no bounds if not given)
// - fillCharacter - Fills in the region left behind when the source is "lifted" out of its original location. The symbol to display.
// - fillAttribute - Fills in the region left behind when the source is "lifted" out of its original location. The color to use.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::ScrollConsoleScreenBufferAImpl(SCREEN_INFORMATION& context,
const til::inclusive_rect& source,
const til::point target,
std::optional<til::inclusive_rect> clip,
const char fillCharacter,
const WORD fillAttribute) noexcept
{
try
{
const auto unicodeFillCharacter = CharToWchar(&fillCharacter, 1);
return ScrollConsoleScreenBufferWImpl(context, source, target, clip, unicodeFillCharacter, fillAttribute);
}
CATCH_RETURN();
}
// Routine Description:
// - Moves a portion of text from one part of the output buffer to another
// Arguments:
// - context - The output buffer concerned
// - source - The rectangular region to copy from
// - target - The top left corner of the destination to paste the copy (source)
// - clip - The rectangle inside which all operations should be bounded (or no bounds if not given)
// - fillCharacter - Fills in the region left behind when the source is "lifted" out of its original location. The symbol to display.
// - fillAttribute - Fills in the region left behind when the source is "lifted" out of its original location. The color to use.
// - enableCmdShim - true iff the client process that's calling this
// method is "cmd.exe". Used to enable certain compatibility shims for
// conpty mode. See GH#3126.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context,
const til::inclusive_rect& source,
const til::point target,
std::optional<til::inclusive_rect> clip,
wchar_t fillCharacter,
WORD fillAttribute,
const bool enableCmdShim) noexcept
{
try
{
// Just in case if the client application didn't check if this request is useless.
// Checking if the source is empty also prevents bugs where we use the size of calculations.
if ((source.left == target.x && source.top == target.y) ||
source.left > source.right || source.top > source.bottom)
{
return S_OK;
}
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto& buffer = context.GetActiveBuffer();
const auto bufferSize = buffer.GetBufferSize();
auto writer = gci.GetVtWriterForBuffer(&context);
// Applications like to pass 0/0 for the fill char/attribute.
// What they want is the whitespace and current attributes.
if (fillCharacter == UNICODE_NULL && fillAttribute == 0)
{
fillAttribute = buffer.GetAttributes().GetLegacyAttributes();
}
// Avoid writing control characters into the buffer.
// A null character will get translated to whitespace.
fillCharacter = Microsoft::Console::VirtualTerminal::VtIo::SanitizeUCS2(fillCharacter);
// GH#3126 - This is a shim for cmd's `cls` function. In the
// legacy console, `cls` is supposed to clear the entire buffer.
// We always use a VT sequence, even if ConPTY isn't used, because those are faster nowadays.
if (enableCmdShim &&
source.left <= 0 && source.top <= 0 &&
source.right >= bufferSize.RightInclusive() && source.bottom >= bufferSize.BottomInclusive() &&
target.x == 0 && target.y <= -bufferSize.BottomExclusive() &&
!clip &&
fillCharacter == UNICODE_SPACE && fillAttribute == buffer.GetAttributes().GetLegacyAttributes())
{
WriteClearScreen(context);
}
else if (writer)
{
const auto clipViewport = clip ? Viewport::FromInclusive(*clip).Clamp(bufferSize) : bufferSize;
const auto sourceViewport = Viewport::FromInclusive(source);