-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
Copy pathgetset.cpp
2293 lines (2022 loc) · 88.9 KB
/
getset.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 "getset.h"
#include "_output.h"
#include "_stream.h"
#include "output.h"
#include "dbcs.h"
#include "handle.h"
#include "misc.h"
#include "cmdline.h"
#include "../types/inc/convert.hpp"
#include "../types/inc/viewport.hpp"
#include "ApiRoutines.h"
#include "..\interactivity\inc\ServiceLocator.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
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleMode);
const CONSOLE_INFORMATION& 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.
context.GetActiveBuffer().GetScreenBufferInformation(&data.dwSize,
&data.dwCursorPosition,
&data.srWindow,
&data.wAttributes,
&data.dwMaximumWindowSize,
&data.wPopupAttributes,
data.ColorTable);
// Callers of this function expect to receive an exclusive rect, not an inclusive one.
data.srWindow.Right += 1;
data.srWindow.Bottom += 1;
}
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 = selection.GetSelectionAnchor();
consoleSelectionInfo.srSelection = 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,
COORD& 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 = { 0 };
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 SCREEN_INFORMATION& activeScreenInfo = context.GetActiveBuffer();
COORD WindowSize;
if (isForMaximumWindowSize)
{
WindowSize = activeScreenInfo.GetMaxWindowSizeInCharacters();
}
else
{
WindowSize = activeScreenInfo.GetCurrentFont().GetUnscaledSize();
}
consoleFontInfoEx.dwFontSize = WindowSize;
consoleFontInfoEx.nFont = 0;
const FontInfo& fontInfo = activeScreenInfo.GetCurrentFont();
consoleFontInfoEx.FontFamily = fontInfo.GetFamily();
consoleFontInfoEx.FontWeight = fontInfo.GetWeight();
RETURN_IF_FAILED(fontInfo.FillLegacyNameBuffer(gsl::make_span(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 CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
SCREEN_INFORMATION& 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,
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
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
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 bool 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);
}
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(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
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
// Flags we don't understand are invalid.
RETURN_HR_IF(E_INVALIDARG, WI_IsAnyFlagSet(mode, ~OUTPUT_MODES));
SCREEN_INFORMATION& screenInfo = context.GetActiveBuffer();
const DWORD dwOldMode = screenInfo.OutputMode;
const DWORD dwNewMode = mode;
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();
screenInfo.ClearTabStops();
}
// if we're moving from VT off->on
else if (WI_IsFlagSet(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) &&
WI_IsFlagClear(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
screenInfo.SetDefaultVtTabStops();
}
gci.SetVirtTermLevel(WI_IsFlagSet(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) ? 1 : 0);
gci.SetAutomaticReturnOnNewline(WI_IsFlagSet(screenInfo.OutputMode, DISABLE_NEWLINE_AUTO_RETURN) ? false : true);
gci.SetGridRenderingAllowedWorldwide(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_LVB_GRID_WORLDWIDE));
// if we changed rendering modes then redraw the output buffer,
// but only do this if we're not in conpty mode.
if (!gci.IsInVtIoMode() &&
(WI_IsFlagSet(dwNewMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) != WI_IsFlagSet(dwOldMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) ||
WI_IsFlagSet(dwNewMode, ENABLE_LVB_GRID_WORLDWIDE) != WI_IsFlagSet(dwOldMode, ENABLE_LVB_GRID_WORLDWIDE)))
{
auto* pRender = ServiceLocator::LocateGlobals().pRender;
if (pRender)
{
pRender->TriggerRedrawAll();
}
}
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(); });
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,
COORD& size) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
const SCREEN_INFORMATION& 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 COORD size) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
SCREEN_INFORMATION& screenInfo = context.GetActiveBuffer();
// see MSFT:17415266
// We only really care about the minimum window size if we have a head.
if (!ServiceLocator::LocateGlobals().IsHeadless())
{
COORD const coordMin = screenInfo.GetMinWindowSizeInCharacters();
// clang-format off
// Make sure requested screen buffer size isn't smaller than the window.
RETURN_HR_IF(E_INVALIDARG, (size.X < screenInfo.GetViewport().Width() ||
size.Y < screenInfo.GetViewport().Height() ||
size.Y < coordMin.Y ||
size.X < coordMin.X));
// clang-format on
}
// Ensure the requested size isn't larger than we can handle in our data type.
RETURN_HR_IF(E_INVALIDARG, (size.X == SHORT_MAX || size.Y == SHORT_MAX));
// Only do the resize if we're actually changing one of the dimensions
COORD const coordScreenBufferSize = screenInfo.GetBufferSize().Dimensions();
if (size.X != coordScreenBufferSize.X || size.Y != coordScreenBufferSize.Y)
{
RETURN_NTSTATUS(screenInfo.ResizeScreenBuffer(size, TRUE));
}
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(); });
Globals& g = ServiceLocator::LocateGlobals();
CONSOLE_INFORMATION& gci = g.getConsoleInformation();
const COORD coordScreenBufferSize = context.GetBufferSize().Dimensions();
const COORD requestedBufferSize = data.dwSize;
if (requestedBufferSize.X != coordScreenBufferSize.X ||
requestedBufferSize.Y != coordScreenBufferSize.Y)
{
CommandLine& commandLine = CommandLine::Instance();
commandLine.Hide(FALSE);
LOG_IF_FAILED(context.ResizeScreenBuffer(data.dwSize, TRUE));
commandLine.Show();
}
const COORD newBufferSize = context.GetBufferSize().Dimensions();
gci.SetColorTable(data.ColorTable, ARRAYSIZE(data.ColorTable));
context.SetDefaultAttributes({ data.wAttributes }, { data.wPopupAttributes });
const Viewport requestedViewport = Viewport::FromExclusive(data.srWindow);
COORD NewSize = requestedViewport.Dimensions();
// If we have a window, clamp the requested viewport to the max window size
if (!ServiceLocator::LocateGlobals().IsHeadless())
{
NewSize.X = std::min(NewSize.X, data.dwMaximumWindowSize.X);
NewSize.Y = std::min(NewSize.Y, 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.X = newBufferSize.X;
}
if (NewSize.X != context.GetViewport().Width() ||
NewSize.Y != context.GetViewport().Height())
{
context.SetViewportSize(&NewSize);
IConsoleWindow* const 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.
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 COORD position) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto& buffer = context.GetActiveBuffer();
const COORD coordScreenBufferSize = buffer.GetBufferSize().Dimensions();
// clang-format off
RETURN_HR_IF(E_INVALIDARG, (position.X >= coordScreenBufferSize.X ||
position.Y >= coordScreenBufferSize.Y ||
position.X < 0 ||
position.Y < 0));
// clang-format on
// MSFT: 15813316 - Try to use this SetCursorPosition call to inherit the cursor position.
RETURN_IF_FAILED(gci.GetVtIo()->SetCursorPosition(position));
RETURN_IF_NTSTATUS_FAILED(buffer.SetCursorPosition(position, true));
LOG_IF_FAILED(ConsoleImeResizeCompStrView());
// 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.
// microsoft/terminal#1222 - Use the "virtual" viewport here, so that
// when the console is in terminal-scrolling mode, the viewport snaps
// back to the virtual viewport's location.
const SMALL_RECT currentViewport = gci.IsTerminalScrolling() ?
buffer.GetVirtualViewport().ToInclusive() :
buffer.GetViewport().ToInclusive();
COORD delta{ 0 };
{
if (currentViewport.Left > position.X)
{
delta.X = position.X - currentViewport.Left;
}
else if (currentViewport.Right < position.X)
{
delta.X = position.X - 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;
}
}
COORD newWindowOrigin{ 0 };
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));
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);
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 SMALL_RECT& windowRect) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
Globals& g = ServiceLocator::LocateGlobals();
SMALL_RECT Window = windowRect;
if (!isAbsolute)
{
SMALL_RECT 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));
COORD NewWindowSize;
NewWindowSize.X = (SHORT)(CalcWindowSizeX(Window));
NewWindowSize.Y = (SHORT)(CalcWindowSizeY(Window));
// see MSFT:17415266
// If we have a 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.IsHeadless())
{
COORD const coordMax = context.GetMaxWindowSizeInCharacters();
RETURN_HR_IF(E_INVALIDARG, (NewWindowSize.X > coordMax.X || NewWindowSize.Y > coordMax.Y));
}
else 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));
}
// 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();
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 SMALL_RECT& source,
const COORD target,
std::optional<SMALL_RECT> clip,
const char fillCharacter,
const WORD fillAttribute) noexcept
{
try
{
wchar_t const 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.
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::ScrollConsoleScreenBufferWImpl(SCREEN_INFORMATION& context,
const SMALL_RECT& source,
const COORD target,
std::optional<SMALL_RECT> clip,
const wchar_t fillCharacter,
const WORD fillAttribute) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
auto& buffer = context.GetActiveBuffer();
TextAttribute useThisAttr(fillAttribute);
// Here we're being a little clever - similar to FillConsoleOutputAttributeImpl
// Because RGB/default color can't roundtrip the API, certain VT
// sequences will forget the RGB color because their first call to
// GetScreenBufferInfo returned a legacy attr.
// If they're calling this with the legacy attrs version of our current
// attributes, they likely wanted to use the full version of
// our current attributes, whether that be RGB or _default_ colored.
// This could create a scenario where someone emitted RGB with VT,
// THEN used the API to ScrollConsoleOutput with the legacy attrs,
// and DIDN'T want the RGB color. As in FillConsoleOutputAttribute,
// this scenario is highly unlikely, and we can reasonably do this
// on their behalf.
// see MSFT:19853701
if (buffer.InVTMode())
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
const auto currentAttributes = buffer.GetAttributes();
const auto bufferLegacy = gci.GenerateLegacyAttributes(currentAttributes);
if (bufferLegacy == fillAttribute)
{
useThisAttr = currentAttributes;
}
}
ScrollRegion(buffer, source, clip, target, fillCharacter, useThisAttr);
return S_OK;
}
CATCH_RETURN();
}
// Routine Description:
// - Adjusts the default color used for future text written to this output buffer
// Arguments:
// - context - The output buffer concerned
// - attribute - Color information
// Return Value:
// - S_OK, E_INVALIDARG, or failure code from thrown exception
[[nodiscard]] HRESULT ApiRoutines::SetConsoleTextAttributeImpl(SCREEN_INFORMATION& context,
const WORD attribute) noexcept
{
CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
RETURN_HR_IF(E_INVALIDARG, WI_IsAnyFlagSet(attribute, ~VALID_TEXT_ATTRIBUTES));
const TextAttribute attr{ attribute };
context.SetAttributes(attr);
gci.ConsoleIme.RefreshAreaAttributes();
return S_OK;
}
CATCH_RETURN();
}
void DoSrvPrivateSetLegacyAttributes(SCREEN_INFORMATION& screenInfo,
const WORD Attribute,
const bool fForeground,
const bool fBackground,
const bool fMeta)
{
auto& buffer = screenInfo.GetActiveBuffer();
const TextAttribute OldAttributes = buffer.GetAttributes();
TextAttribute NewAttributes = OldAttributes;
NewAttributes.SetLegacyAttributes(Attribute, fForeground, fBackground, fMeta);
buffer.SetAttributes(NewAttributes);
}
void DoSrvPrivateSetDefaultAttributes(SCREEN_INFORMATION& screenInfo,
const bool fForeground,
const bool fBackground)
{
auto& buffer = screenInfo.GetActiveBuffer();
TextAttribute NewAttributes = buffer.GetAttributes();
if (fForeground)
{
NewAttributes.SetDefaultForeground();
}
if (fBackground)
{
NewAttributes.SetDefaultBackground();
}
buffer.SetAttributes(NewAttributes);
}
void DoSrvPrivateSetConsoleXtermTextAttribute(SCREEN_INFORMATION& screenInfo,
const int iXtermTableEntry,
const bool fIsForeground)
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto& buffer = screenInfo.GetActiveBuffer();
TextAttribute NewAttributes = buffer.GetAttributes();
COLORREF rgbColor;
if (iXtermTableEntry < COLOR_TABLE_SIZE)
{
//Convert the xterm index to the win index
WORD iWinEntry = ::XtermToWindowsIndex(iXtermTableEntry);
rgbColor = gci.GetColorTableEntry(iWinEntry);
}
else
{
rgbColor = gci.GetColorTableEntry(iXtermTableEntry);
}
NewAttributes.SetColor(rgbColor, fIsForeground);
buffer.SetAttributes(NewAttributes);
}
void DoSrvPrivateSetConsoleRGBTextAttribute(SCREEN_INFORMATION& screenInfo,
const COLORREF rgbColor,
const bool fIsForeground)
{
auto& buffer = screenInfo.GetActiveBuffer();
TextAttribute NewAttributes = buffer.GetAttributes();
NewAttributes.SetColor(rgbColor, fIsForeground);
buffer.SetAttributes(NewAttributes);
}
void DoSrvPrivateBoldText(SCREEN_INFORMATION& screenInfo, const bool bolded)
{
auto& buffer = screenInfo.GetActiveBuffer();
auto attrs = buffer.GetAttributes();
if (bolded)
{
attrs.Embolden();
}
else
{
attrs.Debolden();
}
buffer.SetAttributes(attrs);
}
// Method Description:
// - Retrieves the active ExtendedAttributes (italic, underline, etc.) of the
// given screen buffer. Text written to this buffer will be written with these
// attributes.
// Arguments:
// - screenInfo: The buffer to get the extended attrs from.
// Return Value:
// - the currently active ExtendedAttributes.
ExtendedAttributes DoSrvPrivateGetExtendedTextAttributes(SCREEN_INFORMATION& screenInfo)
{
auto& buffer = screenInfo.GetActiveBuffer();
auto attrs = buffer.GetAttributes();
return attrs.GetExtendedAttributes();
}
// Method Description:
// - Sets the active ExtendedAttributes (italic, underline, etc.) of the given