-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
_stream.cpp
1333 lines (1189 loc) · 57.9 KB
/
_stream.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 "ApiRoutines.h"
#include "_stream.h"
#include "stream.h"
#include "writeData.hpp"
#include "_output.h"
#include "output.h"
#include "dbcs.h"
#include "handle.h"
#include "misc.h"
#include "../types/inc/convert.hpp"
#include "../types/inc/GlyphWidth.hpp"
#include "../types/inc/Viewport.hpp"
#include "../interactivity/inc/ServiceLocator.hpp"
#pragma hdrstop
using namespace Microsoft::Console::Types;
using Microsoft::Console::Interactivity::ServiceLocator;
using Microsoft::Console::VirtualTerminal::StateMachine;
// Used by WriteCharsLegacy.
#define IS_GLYPH_CHAR(wch) (((wch) >= L' ') && ((wch) != 0x007F))
// Routine Description:
// - This routine updates the cursor position. Its input is the non-special
// cased new location of the cursor. For example, if the cursor were being
// moved one space backwards from the left edge of the screen, the X
// coordinate would be -1. This routine would set the X coordinate to
// the right edge of the screen and decrement the Y coordinate by one.
// Arguments:
// - screenInfo - reference to screen buffer information structure.
// - coordCursor - New location of cursor.
// - fKeepCursorVisible - TRUE if changing window origin desirable when hit right edge
// Return Value:
[[nodiscard]] NTSTATUS AdjustCursorPosition(SCREEN_INFORMATION& screenInfo,
_In_ COORD coordCursor,
const BOOL fKeepCursorVisible,
_Inout_opt_ PSHORT psScrollY)
{
const auto inVtMode = WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING);
const auto bufferSize = screenInfo.GetBufferSize().Dimensions();
if (coordCursor.X < 0)
{
if (coordCursor.Y > 0)
{
coordCursor.X = (SHORT)(bufferSize.X + coordCursor.X);
coordCursor.Y = (SHORT)(coordCursor.Y - 1);
}
else
{
coordCursor.X = 0;
}
}
else if (coordCursor.X >= bufferSize.X)
{
// at end of line. if wrap mode, wrap cursor. otherwise leave it where it is.
if (screenInfo.OutputMode & ENABLE_WRAP_AT_EOL_OUTPUT)
{
coordCursor.Y += coordCursor.X / bufferSize.X;
coordCursor.X = coordCursor.X % bufferSize.X;
}
else
{
if (inVtMode)
{
// In VT mode, the cursor must be left in the last column.
coordCursor.X = bufferSize.X - 1;
}
else
{
// For legacy apps, it is left where it was at the start of the write.
coordCursor.X = screenInfo.GetTextBuffer().GetCursor().GetPosition().X;
}
}
}
// The VT standard requires the lines revealed when scrolling are filled
// with the current background color, but with no meta attributes set.
auto fillAttributes = screenInfo.GetAttributes();
fillAttributes.SetStandardErase();
const auto relativeMargins = screenInfo.GetRelativeScrollMargins();
auto viewport = screenInfo.GetViewport();
auto srMargins = screenInfo.GetAbsoluteScrollMargins().ToInclusive();
const auto fMarginsSet = srMargins.Bottom > srMargins.Top;
auto currentCursor = screenInfo.GetTextBuffer().GetCursor().GetPosition();
const int iCurrentCursorY = currentCursor.Y;
const auto fCursorInMargins = iCurrentCursorY <= srMargins.Bottom && iCurrentCursorY >= srMargins.Top;
const auto cursorAboveViewport = coordCursor.Y < 0 && inVtMode;
const auto fScrollDown = fMarginsSet && fCursorInMargins && (coordCursor.Y > srMargins.Bottom);
auto fScrollUp = fMarginsSet && fCursorInMargins && (coordCursor.Y < srMargins.Top);
const auto fScrollUpWithoutMargins = (!fMarginsSet) && cursorAboveViewport;
// if we're in VT mode, AND MARGINS AREN'T SET and a Reverse Line Feed took the cursor up past the top of the viewport,
// VT style scroll the contents of the screen.
// This can happen in applications like `less`, that don't set margins, because they're going to
// scroll the entire screen anyways, so no need for them to ever set the margins.
if (fScrollUpWithoutMargins)
{
fScrollUp = true;
srMargins.Top = 0;
srMargins.Bottom = screenInfo.GetViewport().BottomInclusive();
}
const auto scrollDownAtTop = fScrollDown && relativeMargins.Top() == 0;
if (scrollDownAtTop)
{
// We're trying to scroll down, and the top margin is at the top of the viewport.
// In this case, we want the lines that are "scrolled off" to appear in
// the scrollback instead of being discarded.
// To do this, we're going to scroll everything starting at the bottom
// margin down, then move the viewport down.
const SHORT delta = coordCursor.Y - srMargins.Bottom;
SMALL_RECT scrollRect{ 0 };
scrollRect.Left = 0;
scrollRect.Top = srMargins.Bottom + 1; // One below margins
scrollRect.Bottom = bufferSize.Y - 1; // -1, otherwise this would be an exclusive rect.
scrollRect.Right = bufferSize.X - 1; // -1, otherwise this would be an exclusive rect.
// This is the Y position we're moving the contents below the bottom margin to.
SHORT moveToYPosition = scrollRect.Top + delta;
// This is where the viewport will need to be to give the effect of
// scrolling the contents in the margins.
SHORT newViewTop = viewport.Top() + delta;
// This is how many new lines need to be added to the buffer to support this operation.
const SHORT newRows = (viewport.BottomExclusive() + delta) - bufferSize.Y;
// If we're near the bottom of the buffer, we might need to insert some
// new rows at the bottom.
// If we do this, then the viewport is now one line higher than it used
// to be, so it needs to move down by one less line.
for (auto i = 0; i < newRows; i++)
{
screenInfo.GetTextBuffer().IncrementCircularBuffer();
moveToYPosition--;
newViewTop--;
scrollRect.Top--;
}
const COORD newPostMarginsOrigin = { 0, moveToYPosition };
const COORD newViewOrigin = { 0, newViewTop };
try
{
ScrollRegion(screenInfo, scrollRect, std::nullopt, newPostMarginsOrigin, UNICODE_SPACE, fillAttributes);
}
CATCH_LOG();
// Move the viewport down
auto hr = screenInfo.SetViewportOrigin(true, newViewOrigin, true);
if (FAILED(hr))
{
return NTSTATUS_FROM_HRESULT(hr);
}
// If we didn't actually move the viewport, it's because we're at the
// bottom of the buffer, and the top lines of the viewport have
// changed. Manually invalidate here, to make sure the screen
// displays the correct text.
if (newViewOrigin == viewport.Origin())
{
// Inside this block, we're shifting down at the bottom.
// This means that we had something like this:
// AAAA
// BBBB
// CCCC
// DDDD
// EEEE
//
// Our margins were set for lines A-D, but not on line E.
// So we circled the whole buffer up by one:
// BBBB
// CCCC
// DDDD
// EEEE
// <blank, was AAAA>
//
// Then we scrolled the contents of everything OUTSIDE the margin frame down.
// BBBB
// CCCC
// DDDD
// <blank, filled during scroll down of EEEE>
// EEEE
//
// And now we need to report that only the bottom line didn't "move" as we put the EEEE
// back where it started, but everything else moved.
// In this case, delta was 1. So the amount that moved is the entire viewport height minus the delta.
Viewport invalid = Viewport::FromDimensions(viewport.Origin(), { viewport.Width(), viewport.Height() - delta });
screenInfo.GetTextBuffer().TriggerRedraw(invalid);
}
// reset where our local viewport is, and recalculate the cursor and
// margin positions.
viewport = screenInfo.GetViewport();
if (newRows > 0)
{
currentCursor.Y -= newRows;
coordCursor.Y -= newRows;
}
srMargins = screenInfo.GetAbsoluteScrollMargins().ToInclusive();
}
// If we did the above scrollDownAtTop case, then we've already scrolled
// the margins content, and we can skip this.
if (fScrollUp || (fScrollDown && !scrollDownAtTop))
{
SHORT diff = coordCursor.Y - (fScrollUp ? srMargins.Top : srMargins.Bottom);
SMALL_RECT scrollRect = { 0 };
scrollRect.Top = srMargins.Top;
scrollRect.Bottom = srMargins.Bottom;
scrollRect.Left = 0; // NOTE: Left/Right Scroll margins don't do anything currently.
scrollRect.Right = bufferSize.X - 1; // -1, otherwise this would be an exclusive rect.
COORD dest;
dest.X = scrollRect.Left;
dest.Y = scrollRect.Top - diff;
try
{
ScrollRegion(screenInfo, scrollRect, scrollRect, dest, UNICODE_SPACE, fillAttributes);
}
CATCH_LOG();
coordCursor.Y -= diff;
}
// If the margins are set, then it shouldn't be possible for the cursor to
// move below the bottom of the viewport. Either it should be constrained
// inside the margins by one of the scrollDown cases handled above, or
// we'll need to clamp it inside the viewport here.
if (fMarginsSet && coordCursor.Y > viewport.BottomInclusive())
{
coordCursor.Y = viewport.BottomInclusive();
}
auto Status = STATUS_SUCCESS;
if (coordCursor.Y >= bufferSize.Y)
{
// At the end of the buffer. Scroll contents of screen buffer so new position is visible.
FAIL_FAST_IF(!(coordCursor.Y == bufferSize.Y));
if (!StreamScrollRegion(screenInfo))
{
Status = STATUS_NO_MEMORY;
}
if (nullptr != psScrollY)
{
*psScrollY += (SHORT)(bufferSize.Y - coordCursor.Y - 1);
}
coordCursor.Y += (SHORT)(bufferSize.Y - coordCursor.Y - 1);
}
const auto cursorMovedPastViewport = coordCursor.Y > screenInfo.GetViewport().BottomInclusive();
const auto cursorMovedPastVirtualViewport = coordCursor.Y > screenInfo.GetVirtualViewport().BottomInclusive();
if (NT_SUCCESS(Status))
{
// if at right or bottom edge of window, scroll right or down one char.
if (cursorMovedPastViewport)
{
COORD WindowOrigin;
WindowOrigin.X = 0;
WindowOrigin.Y = coordCursor.Y - screenInfo.GetViewport().BottomInclusive();
Status = screenInfo.SetViewportOrigin(false, WindowOrigin, true);
}
}
if (NT_SUCCESS(Status))
{
if (fKeepCursorVisible)
{
screenInfo.MakeCursorVisible(coordCursor);
}
Status = screenInfo.SetCursorPosition(coordCursor, !!fKeepCursorVisible);
// MSFT:19989333 - Only re-initialize the cursor row if the cursor moved
// below the terminal section of the buffer (the virtual viewport),
// and the visible part of the buffer (the actual viewport).
// If this is only cursorMovedPastViewport, and you scroll up, then type
// a character, we'll re-initialize the line the cursor is on.
// If this is only cursorMovedPastVirtualViewport and you scroll down,
// (with terminal scrolling disabled) then all lines newly exposed
// will get their attributes constantly cleared out.
// Both cursorMovedPastViewport and cursorMovedPastVirtualViewport works
if (inVtMode && cursorMovedPastViewport && cursorMovedPastVirtualViewport)
{
screenInfo.InitializeCursorRowAttributes();
}
}
return Status;
}
// Routine Description:
// - This routine writes a string to the screen, processing any embedded
// unicode characters. The string is also copied to the input buffer, if
// the output mode is line mode.
// Arguments:
// - screenInfo - reference to screen buffer information structure.
// - pwchBufferBackupLimit - Pointer to beginning of buffer.
// - pwchBuffer - Pointer to buffer to copy string to. assumed to be at least as long as pwchRealUnicode.
// This pointer is updated to point to the next position in the buffer.
// - pwchRealUnicode - Pointer to string to write.
// - pcb - On input, number of bytes to write. On output, number of bytes written.
// - pcSpaces - On output, the number of spaces consumed by the written characters.
// - dwFlags -
// WC_DESTRUCTIVE_BACKSPACE backspace overwrites characters.
// WC_KEEP_CURSOR_VISIBLE change window origin desirable when hit rt. edge
// WC_PRINTABLE_CONTROL_CHARS if control characters should be expanded (as in, to "^X")
// Return Value:
// Note:
// - This routine does not process tabs and backspace properly. That code will be implemented as part of the line editing services.
[[nodiscard]] NTSTATUS WriteCharsLegacy(SCREEN_INFORMATION& screenInfo,
_In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit,
_In_ const wchar_t* pwchBuffer,
_In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode,
_Inout_ size_t* const pcb,
_Out_opt_ size_t* const pcSpaces,
const SHORT sOriginalXPosition,
const DWORD dwFlags,
_Inout_opt_ PSHORT const psScrollY)
{
const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
auto& textBuffer = screenInfo.GetTextBuffer();
auto& cursor = textBuffer.GetCursor();
auto CursorPosition = cursor.GetPosition();
auto Status = STATUS_SUCCESS;
SHORT XPosition;
size_t TempNumSpaces = 0;
const auto fUnprocessed = WI_IsFlagClear(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT);
const auto fWrapAtEOL = WI_IsFlagSet(screenInfo.OutputMode, ENABLE_WRAP_AT_EOL_OUTPUT);
// Must not adjust cursor here. It has to stay on for many write scenarios. Consumers should call for the
// cursor to be turned off if they want that.
const auto Attributes = screenInfo.GetAttributes();
const auto BufferSize = *pcb;
*pcb = 0;
auto lpString = pwchRealUnicode;
auto coordScreenBufferSize = screenInfo.GetBufferSize().Dimensions();
// In VT mode, the width at which we wrap is determined by the line rendition attribute.
if (WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
coordScreenBufferSize.X = textBuffer.GetLineWidth(CursorPosition.Y);
}
static constexpr unsigned int LOCAL_BUFFER_SIZE = 1024;
WCHAR LocalBuffer[LOCAL_BUFFER_SIZE];
while (*pcb < BufferSize)
{
// correct for delayed EOL
if (cursor.IsDelayedEOLWrap() && fWrapAtEOL)
{
const auto coordDelayedAt = cursor.GetDelayedAtPosition();
cursor.ResetDelayEOLWrap();
// Only act on a delayed EOL if we didn't move the cursor to a different position from where the EOL was marked.
if (coordDelayedAt.X == CursorPosition.X && coordDelayedAt.Y == CursorPosition.Y)
{
CursorPosition.X = 0;
CursorPosition.Y++;
Status = AdjustCursorPosition(screenInfo, CursorPosition, WI_IsFlagSet(dwFlags, WC_KEEP_CURSOR_VISIBLE), psScrollY);
CursorPosition = cursor.GetPosition();
// In VT mode, we need to recalculate the width when moving to a new line.
if (WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
coordScreenBufferSize.X = textBuffer.GetLineWidth(CursorPosition.Y);
}
}
}
// As an optimization, collect characters in buffer and print out all at once.
XPosition = cursor.GetPosition().X;
size_t i = 0;
auto LocalBufPtr = LocalBuffer;
while (*pcb < BufferSize && i < LOCAL_BUFFER_SIZE && XPosition < coordScreenBufferSize.X)
{
#pragma prefast(suppress : 26019, "Buffer is taken in multiples of 2. Validation is ok.")
const auto Char = *lpString;
// WCL-NOTE: We believe RealUnicodeChar to be identical to Char, because we believe pwchRealUnicode
// WCL-NOTE: to be identical to lpString. They are incremented in lockstep, never separately, and lpString
// WCL-NOTE: is initialized from pwchRealUnicode.
const auto RealUnicodeChar = *pwchRealUnicode;
if (IS_GLYPH_CHAR(RealUnicodeChar) || fUnprocessed)
{
// WCL-NOTE: This operates on a single code unit instead of a whole codepoint. It will mis-measure surrogate pairs.
if (IsGlyphFullWidth(Char))
{
if (i < (LOCAL_BUFFER_SIZE - 1) && XPosition < (coordScreenBufferSize.X - 1))
{
*LocalBufPtr++ = Char;
// cursor adjusted by 2 because the char is double width
XPosition += 2;
i += 1;
pwchBuffer++;
}
else
{
goto EndWhile;
}
}
else
{
*LocalBufPtr = Char;
LocalBufPtr++;
XPosition++;
i++;
pwchBuffer++;
}
}
else
{
FAIL_FAST_IF(!(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT)));
switch (RealUnicodeChar)
{
case UNICODE_BELL:
if (dwFlags & WC_PRINTABLE_CONTROL_CHARS)
{
goto CtrlChar;
}
else
{
screenInfo.SendNotifyBeep();
}
break;
case UNICODE_BACKSPACE:
// automatically go to EndWhile. this is because
// backspace is not destructive, so "aBkSp" prints
// a with the cursor on the "a". we could achieve
// this behavior staying in this loop and figuring out
// the string that needs to be printed, but it would
// be expensive and it's the exceptional case.
goto EndWhile;
break;
case UNICODE_TAB:
{
const ULONG TabSize = NUMBER_OF_SPACES_IN_TAB(XPosition);
XPosition = (SHORT)(XPosition + TabSize);
if (XPosition >= coordScreenBufferSize.X)
{
goto EndWhile;
}
for (ULONG j = 0; j < TabSize && i < LOCAL_BUFFER_SIZE; j++, i++)
{
*LocalBufPtr = UNICODE_SPACE;
LocalBufPtr++;
}
pwchBuffer++;
break;
}
case UNICODE_LINEFEED:
case UNICODE_CARRIAGERETURN:
goto EndWhile;
default:
// if char is ctrl char, write ^char.
if ((dwFlags & WC_PRINTABLE_CONTROL_CHARS) && (IS_CONTROL_CHAR(RealUnicodeChar)))
{
CtrlChar:
if (i < (LOCAL_BUFFER_SIZE - 1))
{
// WCL-NOTE: We do not properly measure that there is space for two characters
// WCL-NOTE: left on the screen.
*LocalBufPtr = (WCHAR)'^';
LocalBufPtr++;
XPosition++;
i++;
*LocalBufPtr = (WCHAR)(RealUnicodeChar + (WCHAR)'@');
LocalBufPtr++;
XPosition++;
i++;
pwchBuffer++;
}
else
{
goto EndWhile;
}
}
else
{
if (Char == UNICODE_NULL)
{
*LocalBufPtr = UNICODE_SPACE;
}
else
{
// As a special favor to incompetent apps that attempt to display control chars,
// convert to corresponding OEM Glyph Chars
WORD CharType;
GetStringTypeW(CT_CTYPE1, &RealUnicodeChar, 1, &CharType);
if (WI_IsFlagSet(CharType, C1_CNTRL))
{
ConvertOutputToUnicode(gci.OutputCP,
(LPSTR)&RealUnicodeChar,
1,
LocalBufPtr,
1);
}
else
{
// WCL-NOTE: We should never hit this.
// WCL-NOTE: 1. Normal characters are handled via the early check for IS_GLYPH_CHAR
// WCL-NOTE: 2. Control characters are handled via the CtrlChar label (if WC_PRINTABLE_CONTROL_CHARS is on)
// WCL-NOTE: And if they are control characters they will trigger the C1_CNTRL check above.
*LocalBufPtr = Char;
}
}
LocalBufPtr++;
XPosition++;
i++;
pwchBuffer++;
}
}
}
lpString++;
pwchRealUnicode++;
*pcb += sizeof(WCHAR);
}
EndWhile:
if (i != 0)
{
CursorPosition = cursor.GetPosition();
// Make sure we don't write past the end of the buffer.
// WCL-NOTE: This check uses a code unit count instead of a column count. That is incorrect.
if (i > gsl::narrow_cast<size_t>(coordScreenBufferSize.X) - CursorPosition.X)
{
i = gsl::narrow_cast<size_t>(coordScreenBufferSize.X) - CursorPosition.X;
}
// line was wrapped if we're writing up to the end of the current row
OutputCellIterator it(std::wstring_view(LocalBuffer, i), Attributes);
const auto itEnd = screenInfo.Write(it);
// Notify accessibility
if (screenInfo.HasAccessibilityEventing())
{
screenInfo.NotifyAccessibilityEventing(CursorPosition.X, CursorPosition.Y, CursorPosition.X + gsl::narrow<SHORT>(i - 1), CursorPosition.Y);
}
// The number of "spaces" or "cells" we have consumed needs to be reported and stored for later
// when/if we need to erase the command line.
TempNumSpaces += itEnd.GetCellDistance(it);
// WCL-NOTE: We are using the "estimated" X position delta instead of the actual delta from
// WCL-NOTE: the iterator. It is not clear why. If they differ, the cursor ends up in the
// WCL-NOTE: wrong place (typically inside another character).
CursorPosition.X = XPosition;
// enforce a delayed newline if we're about to pass the end and the WC_DELAY_EOL_WRAP flag is set.
if (WI_IsFlagSet(dwFlags, WC_DELAY_EOL_WRAP) && CursorPosition.X >= coordScreenBufferSize.X && fWrapAtEOL)
{
// Our cursor position as of this time is going to remain on the last position in this column.
CursorPosition.X = coordScreenBufferSize.X - 1;
// Update in the structures that we're still pointing to the last character in the row
cursor.SetPosition(CursorPosition);
// Record for the delay comparison that we're delaying on the last character in the row
cursor.DelayEOLWrap(CursorPosition);
}
else
{
Status = AdjustCursorPosition(screenInfo, CursorPosition, WI_IsFlagSet(dwFlags, WC_KEEP_CURSOR_VISIBLE), psScrollY);
}
// WCL-NOTE: If we have processed the entire input string during our "fast one-line print" handler,
// WCL-NOTE: we are done as there is nothing more to do. Neat!
if (*pcb == BufferSize)
{
if (nullptr != pcSpaces)
{
*pcSpaces = TempNumSpaces;
}
return STATUS_SUCCESS;
}
continue;
}
else if (*pcb >= BufferSize)
{
// WCL-NOTE: This case looks like it is never encountered, but it *is* if WC_PRINTABLE_CONTROL_CHARS is off.
// WCL-NOTE: If the string is entirely nonprinting control characters, there will be
// WCL-NOTE: no output in the buffer (LocalBuffer; i == 0) but we will have processed
// WCL-NOTE: "every" character. We can just bail out and report the number of spaces consumed.
FAIL_FAST_IF(!(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT)));
// this catches the case where the number of backspaces == the number of characters.
if (nullptr != pcSpaces)
{
*pcSpaces = TempNumSpaces;
}
return STATUS_SUCCESS;
}
FAIL_FAST_IF(!(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT)));
switch (*lpString)
{
case UNICODE_BACKSPACE:
{
// move cursor backwards one space. overwrite current char with blank.
// we get here because we have to backspace from the beginning of the line
TempNumSpaces -= 1;
if (pwchBuffer == pwchBufferBackupLimit)
{
CursorPosition.X -= 1;
}
else
{
const wchar_t* Tmp;
wchar_t* Tmp2 = nullptr;
WCHAR LastChar;
const size_t bufferSize = pwchBuffer - pwchBufferBackupLimit;
std::unique_ptr<wchar_t[]> buffer;
try
{
buffer = std::make_unique<wchar_t[]>(bufferSize);
std::fill_n(buffer.get(), bufferSize, UNICODE_NULL);
}
catch (...)
{
return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException());
}
for (i = 0, Tmp2 = buffer.get(), Tmp = pwchBufferBackupLimit;
i < bufferSize;
i++, Tmp++)
{
// see 18120085, these two need to be separate if statements
if (*Tmp == UNICODE_BACKSPACE)
{
//it is important we do nothing in the else case for
// this one instead of falling through to the below else.
if (Tmp2 > buffer.get())
{
Tmp2--;
}
}
else
{
FAIL_FAST_IF(!(Tmp2 >= buffer.get()));
*Tmp2++ = *Tmp;
}
}
if (Tmp2 == buffer.get())
{
LastChar = UNICODE_SPACE;
}
else
{
#pragma prefast(suppress : 26001, "This is fine. Tmp2 has to have advanced or it would equal pBuffer.")
LastChar = *(Tmp2 - 1);
}
if (LastChar == UNICODE_TAB)
{
CursorPosition.X -= (SHORT)(RetrieveNumberOfSpaces(sOriginalXPosition,
pwchBufferBackupLimit,
(ULONG)(pwchBuffer - pwchBufferBackupLimit - 1)));
if (CursorPosition.X < 0)
{
CursorPosition.X = (coordScreenBufferSize.X - 1) / TAB_SIZE;
CursorPosition.X *= TAB_SIZE;
CursorPosition.X += 1;
CursorPosition.Y -= 1;
// since you just backspaced yourself back up into the previous row, unset the wrap
// flag on the prev row if it was set
textBuffer.GetRowByOffset(CursorPosition.Y).SetWrapForced(false);
}
}
else if (IS_CONTROL_CHAR(LastChar))
{
CursorPosition.X -= 1;
TempNumSpaces -= 1;
// overwrite second character of ^x sequence.
if (dwFlags & WC_DESTRUCTIVE_BACKSPACE)
{
try
{
screenInfo.Write(OutputCellIterator(UNICODE_SPACE, Attributes, 1), CursorPosition);
Status = STATUS_SUCCESS;
}
CATCH_LOG();
}
CursorPosition.X -= 1;
}
else if (IsGlyphFullWidth(LastChar))
{
CursorPosition.X -= 1;
TempNumSpaces -= 1;
Status = AdjustCursorPosition(screenInfo, CursorPosition, dwFlags & WC_KEEP_CURSOR_VISIBLE, psScrollY);
if (dwFlags & WC_DESTRUCTIVE_BACKSPACE)
{
try
{
screenInfo.Write(OutputCellIterator(UNICODE_SPACE, Attributes, 1), CursorPosition);
Status = STATUS_SUCCESS;
}
CATCH_LOG();
}
CursorPosition.X -= 1;
}
else
{
CursorPosition.X--;
}
}
if ((dwFlags & WC_LIMIT_BACKSPACE) && (CursorPosition.X < 0))
{
CursorPosition.X = 0;
OutputDebugStringA(("CONSRV: Ignoring backspace to previous line\n"));
}
Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY);
if (dwFlags & WC_DESTRUCTIVE_BACKSPACE)
{
try
{
screenInfo.Write(OutputCellIterator(UNICODE_SPACE, Attributes, 1), cursor.GetPosition());
}
CATCH_LOG();
}
if (cursor.GetPosition().X == 0 && fWrapAtEOL && pwchBuffer > pwchBufferBackupLimit)
{
if (CheckBisectProcessW(screenInfo,
pwchBufferBackupLimit,
pwchBuffer + 1 - pwchBufferBackupLimit,
gsl::narrow_cast<size_t>(coordScreenBufferSize.X) - sOriginalXPosition,
sOriginalXPosition,
dwFlags & WC_PRINTABLE_CONTROL_CHARS))
{
CursorPosition.X = coordScreenBufferSize.X - 1;
CursorPosition.Y = (SHORT)(cursor.GetPosition().Y - 1);
// since you just backspaced yourself back up into the previous row, unset the wrap flag
// on the prev row if it was set
textBuffer.GetRowByOffset(CursorPosition.Y).SetWrapForced(false);
Status = AdjustCursorPosition(screenInfo, CursorPosition, dwFlags & WC_KEEP_CURSOR_VISIBLE, psScrollY);
}
}
// Notify accessibility to read the backspaced character.
// See GH:12735, MSFT:31748387
if (screenInfo.HasAccessibilityEventing())
{
if (auto pConsoleWindow = ServiceLocator::LocateConsoleWindow())
{
LOG_IF_FAILED(pConsoleWindow->SignalUia(UIA_Text_TextChangedEventId));
}
}
break;
}
case UNICODE_TAB:
{
const auto TabSize = gsl::narrow_cast<size_t>(NUMBER_OF_SPACES_IN_TAB(cursor.GetPosition().X));
CursorPosition.X = (SHORT)(cursor.GetPosition().X + TabSize);
// move cursor forward to next tab stop. fill space with blanks.
// we get here when the tab extends beyond the right edge of the
// window. if the tab goes wraps the line, set the cursor to the first
// position in the next line.
pwchBuffer++;
TempNumSpaces += TabSize;
size_t NumChars = 0;
if (CursorPosition.X >= coordScreenBufferSize.X)
{
NumChars = gsl::narrow<size_t>(coordScreenBufferSize.X - cursor.GetPosition().X);
CursorPosition.X = 0;
CursorPosition.Y = cursor.GetPosition().Y + 1;
// since you just tabbed yourself past the end of the row, set the wrap
textBuffer.GetRowByOffset(cursor.GetPosition().Y).SetWrapForced(true);
}
else
{
NumChars = gsl::narrow<size_t>(CursorPosition.X - cursor.GetPosition().X);
CursorPosition.Y = cursor.GetPosition().Y;
}
try
{
const OutputCellIterator it(UNICODE_SPACE, Attributes, NumChars);
const auto done = screenInfo.Write(it, cursor.GetPosition());
NumChars = done.GetCellDistance(it);
}
CATCH_LOG();
Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY);
break;
}
case UNICODE_CARRIAGERETURN:
{
// Carriage return moves the cursor to the beginning of the line.
// We don't need to worry about handling cr or lf for
// backspace because input is sent to the user on cr or lf.
pwchBuffer++;
CursorPosition.X = 0;
CursorPosition.Y = cursor.GetPosition().Y;
Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY);
break;
}
case UNICODE_LINEFEED:
{
// move cursor to the next line.
pwchBuffer++;
if (gci.IsReturnOnNewlineAutomatic())
{
// Traditionally, we reset the X position to 0 with a newline automatically.
// Some things might not want this automatic "ONLCR line discipline" (for example, things that are expecting a *NIX behavior.)
// They will turn it off with an output mode flag.
CursorPosition.X = 0;
}
CursorPosition.Y = (SHORT)(cursor.GetPosition().Y + 1);
{
// since we explicitly just moved down a row, clear the wrap status on the row we just came from
textBuffer.GetRowByOffset(cursor.GetPosition().Y).SetWrapForced(false);
}
Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY);
break;
}
default:
{
const auto Char = *lpString;
if (Char >= UNICODE_SPACE &&
IsGlyphFullWidth(Char) &&
XPosition >= (coordScreenBufferSize.X - 1) &&
fWrapAtEOL)
{
const auto TargetPoint = cursor.GetPosition();
auto& Row = textBuffer.GetRowByOffset(TargetPoint.Y);
const auto& charRow = Row.GetCharRow();
try
{
// If we're on top of a trailing cell, clear it and the previous cell.
if (charRow.DbcsAttrAt(TargetPoint.X).IsTrailing())
{
// Space to clear for 2 cells.
OutputCellIterator it(UNICODE_SPACE, 2);
// Back target point up one.
auto writeTarget = TargetPoint;
writeTarget.X--;
// Write 2 clear cells.
screenInfo.Write(it, writeTarget);
}
}
catch (...)
{
return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException());
}
CursorPosition.X = 0;
CursorPosition.Y = (SHORT)(TargetPoint.Y + 1);
// since you just moved yourself down onto the next row with 1 character, that sounds like a
// forced wrap so set the flag
Row.SetWrapForced(true);
// Additionally, this padding is only called for IsConsoleFullWidth (a.k.a. when a character
// is too wide to fit on the current line).
Row.SetDoubleBytePadded(true);
Status = AdjustCursorPosition(screenInfo, CursorPosition, dwFlags & WC_KEEP_CURSOR_VISIBLE, psScrollY);
continue;
}
break;
}
}
if (!NT_SUCCESS(Status))
{
return Status;
}
*pcb += sizeof(WCHAR);
lpString++;
pwchRealUnicode++;
}
if (nullptr != pcSpaces)
{
*pcSpaces = TempNumSpaces;
}
return STATUS_SUCCESS;
}
// Routine Description:
// - This routine writes a string to the screen, processing any embedded
// unicode characters. The string is also copied to the input buffer, if
// the output mode is line mode.
// Arguments:
// - screenInfo - reference to screen buffer information structure.
// - pwchBufferBackupLimit - Pointer to beginning of buffer.
// - pwchBuffer - Pointer to buffer to copy string to. assumed to be at least as long as pwchRealUnicode.
// This pointer is updated to point to the next position in the buffer.
// - pwchRealUnicode - Pointer to string to write.
// - pcb - On input, number of bytes to write. On output, number of bytes written.
// - pcSpaces - On output, the number of spaces consumed by the written characters.
// - dwFlags -
// WC_DESTRUCTIVE_BACKSPACE backspace overwrites characters.
// WC_KEEP_CURSOR_VISIBLE change window origin (viewport) desirable when hit rt. edge
// WC_PRINTABLE_CONTROL_CHARS if control characters should be expanded (as in, to "^X")
// Return Value:
// Note:
// - This routine does not process tabs and backspace properly. That code will be implemented as part of the line editing services.
[[nodiscard]] NTSTATUS WriteChars(SCREEN_INFORMATION& screenInfo,
_In_range_(<=, pwchBuffer) const wchar_t* const pwchBufferBackupLimit,
_In_ const wchar_t* pwchBuffer,
_In_reads_bytes_(*pcb) const wchar_t* pwchRealUnicode,
_Inout_ size_t* const pcb,
_Out_opt_ size_t* const pcSpaces,
const SHORT sOriginalXPosition,
const DWORD dwFlags,
_Inout_opt_ PSHORT const psScrollY)
{
if (!WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING) ||
!WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT))
{
return WriteCharsLegacy(screenInfo,
pwchBufferBackupLimit,
pwchBuffer,
pwchRealUnicode,
pcb,
pcSpaces,
sOriginalXPosition,
dwFlags,
psScrollY);
}
auto Status = STATUS_SUCCESS;
const auto BufferSize = *pcb;
*pcb = 0;
{
size_t TempNumSpaces = 0;
{
if (NT_SUCCESS(Status))
{
FAIL_FAST_IF(!(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_PROCESSED_OUTPUT)));
FAIL_FAST_IF(!(WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING)));
// defined down in the WriteBuffer default case hiding on the other end of the state machine. See outputStream.cpp
// This is the only mode used by DoWriteConsole.
FAIL_FAST_IF(!(WI_IsFlagSet(dwFlags, WC_LIMIT_BACKSPACE)));
auto& machine = screenInfo.GetStateMachine();
const auto cch = BufferSize / sizeof(WCHAR);
machine.ProcessString({ pwchRealUnicode, cch });
*pcb += BufferSize;
}
}
if (nullptr != pcSpaces)
{
*pcSpaces = TempNumSpaces;
}
}
return Status;
}
// Routine Description:
// - Takes the given text and inserts it into the given screen buffer.
// Note: