forked from microsoft/terminal
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathadaptDispatch.cpp
More file actions
5050 lines (4663 loc) · 193 KB
/
adaptDispatch.cpp
File metadata and controls
5050 lines (4663 loc) · 193 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 "adaptDispatch.hpp"
#include "../../renderer/base/renderer.hpp"
#include "../../types/inc/Viewport.hpp"
#include "../../types/inc/utils.hpp"
#include "../../inc/unicode.hpp"
#include "../parser/ascii.hpp"
using namespace Microsoft::Console::Types;
using namespace Microsoft::Console::Render;
using namespace Microsoft::Console::VirtualTerminal;
static constexpr std::wstring_view whitespace{ L" " };
AdaptDispatch::AdaptDispatch(ITerminalApi& api, Renderer& renderer, RenderSettings& renderSettings, TerminalInput& terminalInput) noexcept :
_api{ api },
_renderer{ renderer },
_renderSettings{ renderSettings },
_terminalInput{ terminalInput },
_usingAltBuffer(false),
_termOutput(),
_pages{ api, renderer }
{
}
// Routine Description:
// - Translates and displays a single character
// Arguments:
// - wchPrintable - Printable character
// Return Value:
// - <none>
void AdaptDispatch::Print(const wchar_t wchPrintable)
{
const auto wchTranslated = _termOutput.TranslateKey(wchPrintable);
// By default the DEL character is meant to be ignored in the same way as a
// NUL character. However, it's possible that it could be translated to a
// printable character in a 96-character set. This condition makes sure that
// a character is only output if the DEL is translated to something else.
if (wchTranslated != AsciiChars::DEL)
{
_WriteToBuffer({ &wchTranslated, 1 });
}
}
// Routine Description
// - Forward an entire string through. May translate, if necessary, to key input sequences
// based on the locale
// Arguments:
// - string - Text to display
// Return Value:
// - <none>
void AdaptDispatch::PrintString(const std::wstring_view string)
{
if (_termOutput.NeedToTranslate())
{
std::wstring buffer;
buffer.reserve(string.size());
for (auto& wch : string)
{
buffer.push_back(_termOutput.TranslateKey(wch));
}
_WriteToBuffer(buffer);
}
else
{
_WriteToBuffer(string);
}
}
void AdaptDispatch::_WriteToBuffer(const std::wstring_view string)
{
auto page = _pages.ActivePage();
auto& textBuffer = page.Buffer();
auto& cursor = page.Cursor();
auto cursorPosition = cursor.GetPosition();
const auto wrapAtEOL = _api.GetSystemMode(ITerminalApi::Mode::AutoWrap);
const auto& attributes = page.Attributes();
auto [topMargin, bottomMargin] = _GetVerticalMargins(page, true);
const auto [leftMargin, rightMargin] = _GetHorizontalMargins(page.Width());
auto lineWidth = textBuffer.GetLineWidth(cursorPosition.y);
if (cursorPosition.x <= rightMargin && cursorPosition.y >= topMargin && cursorPosition.y <= bottomMargin)
{
lineWidth = std::min(lineWidth, rightMargin + 1);
}
// Turn off the cursor until we're done, so it isn't refreshed unnecessarily.
cursor.SetIsOn(false);
RowWriteState state{
.text = string,
.columnLimit = lineWidth,
};
while (!state.text.empty())
{
if (cursor.IsDelayedEOLWrap() && wrapAtEOL)
{
const auto delayedCursorPosition = 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 (delayedCursorPosition == cursorPosition)
{
if (_DoLineFeed(page, true, true))
{
// If the line feed caused the viewport to move down, we
// need to adjust the page viewport and margins to match.
page.MoveViewportDown();
std::tie(topMargin, bottomMargin) = _GetVerticalMargins(page, true);
}
cursorPosition = cursor.GetPosition();
// We need to recalculate the width when moving to a new line.
lineWidth = textBuffer.GetLineWidth(cursorPosition.y);
if (cursorPosition.y >= topMargin && cursorPosition.y <= bottomMargin)
{
lineWidth = std::min(lineWidth, rightMargin + 1);
}
state.columnLimit = lineWidth;
}
}
state.columnBegin = cursorPosition.x;
const auto textPositionBefore = state.text.data();
if (_modes.test(Mode::InsertReplace))
{
textBuffer.Insert(cursorPosition.y, attributes, state);
}
else
{
textBuffer.Replace(cursorPosition.y, attributes, state);
}
const auto textPositionAfter = state.text.data();
// TODO: A row should not be marked as wrapped just because we wrote the last column.
// It should be marked whenever we write _past_ it (above, _DoLineFeed call). See GH#15602.
if (wrapAtEOL && state.columnEnd >= state.columnLimit)
{
textBuffer.SetWrapForced(cursorPosition.y, true);
}
if (state.columnBeginDirty != state.columnEndDirty)
{
const til::rect changedRect{ state.columnBeginDirty, cursorPosition.y, state.columnEndDirty, cursorPosition.y + 1 };
_api.NotifyAccessibilityChange(changedRect);
}
// If we're past the end of the line, we need to clamp the cursor
// back into range, and if wrapping is enabled, set the delayed wrap
// flag. The wrapping only occurs once another character is output.
const auto isWrapping = state.columnEnd >= state.columnLimit;
cursorPosition.x = isWrapping ? state.columnLimit - 1 : state.columnEnd;
cursor.SetPosition(cursorPosition);
if (isWrapping)
{
// We want to wrap, but we failed to write even a single character into the row.
// ROW::Write() returns the lineWidth and leaves stringIterator untouched. To prevent a
// deadlock, because stringIterator never advances, we need to throw that glyph away.
//
// This can happen under two circumstances:
// * The glyph is wider than the buffer and can never be inserted in
// the first place. There's no good way to detect this, so we check
// whether the begin column is the left margin, which is the column
// at which any legit insertion should work at a minimum.
// * The DECAWM Autowrap mode is disabled ("\x1b[?7l", !wrapAtEOL) and
// we tried writing a wide glyph into the last column which can't work.
if (textPositionBefore == textPositionAfter && (state.columnBegin == 0 || !wrapAtEOL))
{
state.text = state.text.substr(textBuffer.GraphemeNext(state.text, 0));
}
if (wrapAtEOL)
{
cursor.DelayEOLWrap();
}
}
}
_ApplyCursorMovementFlags(cursor);
// Notify terminal and UIA of new text.
// It's important to do this here instead of in TextBuffer, because here you
// have access to the entire line of text, whereas TextBuffer writes it one
// character at a time via the OutputCellIterator.
textBuffer.TriggerNewTextNotification(string);
}
// Routine Description:
// - CUU - Handles cursor upward movement by given distance.
// CUU and CUD are handled separately from other CUP sequences, because they are
// constrained by the margins.
// See: https://vt100.net/docs/vt510-rm/CUU.html
// "The cursor stops at the top margin. If the cursor is already above the top
// margin, then the cursor stops at the top line."
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorUp(const VTInt distance)
{
return _CursorMovePosition(Offset::Backward(distance), Offset::Unchanged(), true);
}
// Routine Description:
// - CUD - Handles cursor downward movement by given distance
// CUU and CUD are handled separately from other CUP sequences, because they are
// constrained by the margins.
// See: https://vt100.net/docs/vt510-rm/CUD.html
// "The cursor stops at the bottom margin. If the cursor is already above the
// bottom margin, then the cursor stops at the bottom line."
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorDown(const VTInt distance)
{
return _CursorMovePosition(Offset::Forward(distance), Offset::Unchanged(), true);
}
// Routine Description:
// - CUF - Handles cursor forward movement by given distance
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorForward(const VTInt distance)
{
return _CursorMovePosition(Offset::Unchanged(), Offset::Forward(distance), true);
}
// Routine Description:
// - CUB - Handles cursor backward movement by given distance
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorBackward(const VTInt distance)
{
return _CursorMovePosition(Offset::Unchanged(), Offset::Backward(distance), true);
}
// Routine Description:
// - CNL - Handles cursor movement to the following line (or N lines down)
// - Moves to the beginning X/Column position of the line.
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorNextLine(const VTInt distance)
{
return _CursorMovePosition(Offset::Forward(distance), Offset::Absolute(1), true);
}
// Routine Description:
// - CPL - Handles cursor movement to the previous line (or N lines up)
// - Moves to the beginning X/Column position of the line.
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::CursorPrevLine(const VTInt distance)
{
return _CursorMovePosition(Offset::Backward(distance), Offset::Absolute(1), true);
}
// Routine Description:
// - Returns the coordinates of the vertical scroll margins.
// Arguments:
// - page - The page that the margins will apply to.
// - absolute - Should coordinates be absolute or relative to the page top.
// Return Value:
// - A std::pair containing the top and bottom coordinates (inclusive).
std::pair<int, int> AdaptDispatch::_GetVerticalMargins(const Page& page, const bool absolute) noexcept
{
// If the top is out of range, reset the margins completely.
const auto bottommostRow = page.Height() - 1;
if (_scrollMargins.top >= bottommostRow)
{
_scrollMargins.top = _scrollMargins.bottom = 0;
}
// If margins aren't set, use the full extent of the page.
const auto marginsSet = _scrollMargins.top < _scrollMargins.bottom;
auto topMargin = marginsSet ? _scrollMargins.top : 0;
auto bottomMargin = marginsSet ? _scrollMargins.bottom : bottommostRow;
// If the bottom is out of range, clamp it to the bottommost row.
bottomMargin = std::min(bottomMargin, bottommostRow);
if (absolute)
{
topMargin += page.Top();
bottomMargin += page.Top();
}
return { topMargin, bottomMargin };
}
// Routine Description:
// - Returns the coordinates of the horizontal scroll margins.
// Arguments:
// - pageWidth - The width of the page
// Return Value:
// - A std::pair containing the left and right coordinates (inclusive).
std::pair<int, int> AdaptDispatch::_GetHorizontalMargins(const til::CoordType pageWidth) noexcept
{
// If the left is out of range, reset the margins completely.
const auto rightmostColumn = pageWidth - 1;
if (_scrollMargins.left >= rightmostColumn)
{
_scrollMargins.left = _scrollMargins.right = 0;
}
// If margins aren't set, use the full extent of the buffer.
const auto marginsSet = _scrollMargins.left < _scrollMargins.right;
auto leftMargin = marginsSet ? _scrollMargins.left : 0;
auto rightMargin = marginsSet ? _scrollMargins.right : rightmostColumn;
// If the right is out of range, clamp it to the rightmost column.
rightMargin = std::min(rightMargin, rightmostColumn);
return { leftMargin, rightMargin };
}
// Routine Description:
// - Generalizes cursor movement to a specific position, which can be absolute or relative.
// Arguments:
// - rowOffset - The row to move to
// - colOffset - The column to move to
// - clampInMargins - Should the position be clamped within the scrolling margins
// Return Value:
// - True.
bool AdaptDispatch::_CursorMovePosition(const Offset rowOffset, const Offset colOffset, const bool clampInMargins)
{
// First retrieve some information about the buffer
const auto page = _pages.ActivePage();
auto& cursor = page.Cursor();
const auto pageWidth = page.Width();
const auto cursorPosition = cursor.GetPosition();
const auto [topMargin, bottomMargin] = _GetVerticalMargins(page, true);
const auto [leftMargin, rightMargin] = _GetHorizontalMargins(pageWidth);
// For relative movement, the given offsets will be relative to
// the current cursor position.
auto row = cursorPosition.y;
auto col = cursorPosition.x;
// But if the row is absolute, it will be relative to the top of the
// page, or the top margin, depending on the origin mode.
if (rowOffset.IsAbsolute)
{
row = _modes.test(Mode::Origin) ? topMargin : page.Top();
}
// And if the column is absolute, it'll be relative to column 0,
// or the left margin, depending on the origin mode.
// Horizontal positions are not affected by the viewport.
if (colOffset.IsAbsolute)
{
col = _modes.test(Mode::Origin) ? leftMargin : 0;
}
// Adjust the base position by the given offsets and clamp the results.
// The row is constrained within the page's vertical boundaries,
// while the column is constrained by the buffer width.
row = std::clamp(row + rowOffset.Value, page.Top(), page.Bottom() - 1);
col = std::clamp(col + colOffset.Value, 0, pageWidth - 1);
// If the operation needs to be clamped inside the margins, or the origin
// mode is relative (which always requires margin clamping), then the row
// and column may need to be adjusted further.
if (clampInMargins || _modes.test(Mode::Origin))
{
// Vertical margins only apply if the original position is inside the
// horizontal margins. Also, the cursor will only be clamped inside the
// top margin if it was already below the top margin to start with, and
// it will only be clamped inside the bottom margin if it was already
// above the bottom margin to start with.
if (cursorPosition.x >= leftMargin && cursorPosition.x <= rightMargin)
{
if (cursorPosition.y >= topMargin)
{
row = std::max(row, topMargin);
}
if (cursorPosition.y <= bottomMargin)
{
row = std::min(row, bottomMargin);
}
}
// Similarly, horizontal margins only apply if the new row is inside the
// vertical margins. And the cursor is only clamped inside the horizontal
// margins if it was already inside to start with.
if (row >= topMargin && row <= bottomMargin)
{
if (cursorPosition.x >= leftMargin)
{
col = std::max(col, leftMargin);
}
if (cursorPosition.x <= rightMargin)
{
col = std::min(col, rightMargin);
}
}
}
// Finally, attempt to set the adjusted cursor position back into the console.
cursor.SetPosition(page.Buffer().ClampPositionWithinLine({ col, row }));
_ApplyCursorMovementFlags(cursor);
return true;
}
// Routine Description:
// - Helper method which applies a bunch of flags that are typically set whenever
// the cursor is moved. The IsOn flag is set to true, and the Delay flag to false,
// to force a blinking cursor to be visible, so the user can immediately see the
// new position. The HasMoved flag is set to let the accessibility notifier know
// that there was movement that needs to be reported.
// Arguments:
// - cursor - The cursor instance to be updated
// Return Value:
// - <none>
void AdaptDispatch::_ApplyCursorMovementFlags(Cursor& cursor) noexcept
{
cursor.SetDelay(false);
cursor.SetIsOn(true);
cursor.SetHasMoved(true);
}
// Routine Description:
// - CHA - Moves the cursor to an exact X/Column position on the current line.
// Arguments:
// - column - Specific X/Column position to move to
// Return Value:
// - True.
bool AdaptDispatch::CursorHorizontalPositionAbsolute(const VTInt column)
{
return _CursorMovePosition(Offset::Unchanged(), Offset::Absolute(column), false);
}
// Routine Description:
// - VPA - Moves the cursor to an exact Y/row position on the current column.
// Arguments:
// - line - Specific Y/Row position to move to
// Return Value:
// - True.
bool AdaptDispatch::VerticalLinePositionAbsolute(const VTInt line)
{
return _CursorMovePosition(Offset::Absolute(line), Offset::Unchanged(), false);
}
// Routine Description:
// - HPR - Handles cursor forward movement by given distance
// - Unlike CUF, this is not constrained by margin settings.
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::HorizontalPositionRelative(const VTInt distance)
{
return _CursorMovePosition(Offset::Unchanged(), Offset::Forward(distance), false);
}
// Routine Description:
// - VPR - Handles cursor downward movement by given distance
// - Unlike CUD, this is not constrained by margin settings.
// Arguments:
// - distance - Distance to move
// Return Value:
// - True.
bool AdaptDispatch::VerticalPositionRelative(const VTInt distance)
{
return _CursorMovePosition(Offset::Forward(distance), Offset::Unchanged(), false);
}
// Routine Description:
// - CUP - Moves the cursor to an exact X/Column and Y/Row/Line coordinate position.
// Arguments:
// - line - Specific Y/Row/Line position to move to
// - column - Specific X/Column position to move to
// Return Value:
// - True.
bool AdaptDispatch::CursorPosition(const VTInt line, const VTInt column)
{
return _CursorMovePosition(Offset::Absolute(line), Offset::Absolute(column), false);
}
// Routine Description:
// - DECSC - Saves the current "cursor state" into a memory buffer. This
// includes the cursor position, origin mode, graphic rendition, and
// active character set.
// Arguments:
// - <none>
// Return Value:
// - True.
bool AdaptDispatch::CursorSaveState()
{
// First retrieve some information about the buffer
const auto page = _pages.ActivePage();
// The cursor is given to us by the API as relative to the whole buffer.
// But in VT speak, the cursor row should be relative to the current page top.
auto cursorPosition = page.Cursor().GetPosition();
cursorPosition.y -= page.Top();
// Although if origin mode is set, the cursor is relative to the margin origin.
if (_modes.test(Mode::Origin))
{
cursorPosition.x -= _GetHorizontalMargins(page.Width()).first;
cursorPosition.y -= _GetVerticalMargins(page, false).first;
}
// VT is also 1 based, not 0 based, so correct by 1.
auto& savedCursorState = _savedCursorState.at(_usingAltBuffer);
savedCursorState.Column = cursorPosition.x + 1;
savedCursorState.Row = cursorPosition.y + 1;
savedCursorState.Page = page.Number();
savedCursorState.IsDelayedEOLWrap = page.Cursor().IsDelayedEOLWrap();
savedCursorState.IsOriginModeRelative = _modes.test(Mode::Origin);
savedCursorState.Attributes = page.Attributes();
savedCursorState.TermOutput = _termOutput;
return true;
}
// Routine Description:
// - DECRC - Restores a saved "cursor state" from the DECSC command back into
// the console state. This includes the cursor position, origin mode, graphic
// rendition, and active character set.
// Arguments:
// - <none>
// Return Value:
// - True.
bool AdaptDispatch::CursorRestoreState()
{
auto& savedCursorState = _savedCursorState.at(_usingAltBuffer);
// Restore the origin mode first, since the cursor coordinates may be relative.
_modes.set(Mode::Origin, savedCursorState.IsOriginModeRelative);
// Restore the page number.
PagePositionAbsolute(savedCursorState.Page);
// We can then restore the position with a standard CUP operation.
CursorPosition(savedCursorState.Row, savedCursorState.Column);
// If the delayed wrap flag was set when the cursor was saved, we need to restore that now.
const auto page = _pages.ActivePage();
if (savedCursorState.IsDelayedEOLWrap)
{
page.Cursor().DelayEOLWrap();
}
// Restore text attributes.
page.SetAttributes(savedCursorState.Attributes, &_api);
// Restore designated character sets.
_termOutput.RestoreFrom(savedCursorState.TermOutput);
return true;
}
// Routine Description:
// - Returns the attributes that should be used when erasing the buffer. When
// the Erase Color mode is set, we use the default attributes, but when reset,
// we use the active color attributes with the character attributes cleared.
// Arguments:
// - page - Target page that is being erased.
// Return Value:
// - The erase TextAttribute value.
TextAttribute AdaptDispatch::_GetEraseAttributes(const Page& page) const noexcept
{
if (_modes.test(Mode::EraseColor))
{
return {};
}
else
{
auto eraseAttributes = page.Attributes();
eraseAttributes.SetStandardErase();
return eraseAttributes;
}
}
// Routine Description:
// - Scrolls an area of the buffer in a vertical direction.
// Arguments:
// - page - Target page to be scrolled.
// - fillRect - Area of the page that will be affected.
// - delta - Distance to move (positive is down, negative is up).
// Return Value:
// - <none>
void AdaptDispatch::_ScrollRectVertically(const Page& page, const til::rect& scrollRect, const VTInt delta)
{
auto& textBuffer = page.Buffer();
const auto absoluteDelta = std::min(std::abs(delta), scrollRect.height());
if (absoluteDelta < scrollRect.height())
{
const auto top = delta > 0 ? scrollRect.top : scrollRect.top + absoluteDelta;
const auto width = scrollRect.width();
const auto height = scrollRect.height() - absoluteDelta;
const auto actualDelta = delta > 0 ? absoluteDelta : -absoluteDelta;
if (width == page.Width())
{
// If the scrollRect is the full width of the buffer, we can scroll
// more efficiently by rotating the row storage.
textBuffer.ScrollRows(top, height, actualDelta);
textBuffer.TriggerRedraw(Viewport::FromExclusive(scrollRect));
}
else
{
// Otherwise we have to move the content up or down by copying the
// requested buffer range one cell at a time.
const auto srcOrigin = til::point{ scrollRect.left, top };
const auto dstOrigin = til::point{ scrollRect.left, top + actualDelta };
const auto srcView = Viewport::FromDimensions(srcOrigin, width, height);
const auto dstView = Viewport::FromDimensions(dstOrigin, width, height);
const auto walkDirection = Viewport::DetermineWalkDirection(srcView, dstView);
auto srcPos = srcView.GetWalkOrigin(walkDirection);
auto dstPos = dstView.GetWalkOrigin(walkDirection);
do
{
const auto current = OutputCell(*textBuffer.GetCellDataAt(srcPos));
textBuffer.WriteLine(OutputCellIterator({ ¤t, 1 }), dstPos);
srcView.WalkInBounds(srcPos, walkDirection);
} while (dstView.WalkInBounds(dstPos, walkDirection));
}
}
// Rows revealed by the scroll are filled with standard erase attributes.
auto eraseRect = scrollRect;
eraseRect.top = delta > 0 ? scrollRect.top : (scrollRect.bottom - absoluteDelta);
eraseRect.bottom = eraseRect.top + absoluteDelta;
const auto eraseAttributes = _GetEraseAttributes(page);
_FillRect(page, eraseRect, whitespace, eraseAttributes);
// Also reset the line rendition for the erased rows.
textBuffer.ResetLineRenditionRange(eraseRect.top, eraseRect.bottom);
}
// Routine Description:
// - Scrolls an area of the buffer in a horizontal direction.
// Arguments:
// - page - Target page to be scrolled.
// - fillRect - Area of the page that will be affected.
// - delta - Distance to move (positive is right, negative is left).
// Return Value:
// - <none>
void AdaptDispatch::_ScrollRectHorizontally(const Page& page, const til::rect& scrollRect, const VTInt delta)
{
auto& textBuffer = page.Buffer();
const auto absoluteDelta = std::min(std::abs(delta), scrollRect.width());
if (absoluteDelta < scrollRect.width())
{
const auto left = delta > 0 ? scrollRect.left : (scrollRect.left + absoluteDelta);
const auto top = scrollRect.top;
const auto width = scrollRect.width() - absoluteDelta;
const auto height = scrollRect.height();
const auto actualDelta = delta > 0 ? absoluteDelta : -absoluteDelta;
const auto source = Viewport::FromDimensions({ left, top }, width, height);
const auto target = Viewport::Offset(source, { actualDelta, 0 });
const auto walkDirection = Viewport::DetermineWalkDirection(source, target);
auto sourcePos = source.GetWalkOrigin(walkDirection);
auto targetPos = target.GetWalkOrigin(walkDirection);
// Note that we read two cells from the source before we start writing
// to the target, so a two-cell DBCS character can't accidentally delete
// itself when moving one cell horizontally.
auto next = OutputCell(*textBuffer.GetCellDataAt(sourcePos));
do
{
const auto current = next;
source.WalkInBounds(sourcePos, walkDirection);
next = OutputCell(*textBuffer.GetCellDataAt(sourcePos));
textBuffer.WriteLine(OutputCellIterator({ ¤t, 1 }), targetPos);
} while (target.WalkInBounds(targetPos, walkDirection));
}
// Columns revealed by the scroll are filled with standard erase attributes.
auto eraseRect = scrollRect;
eraseRect.left = delta > 0 ? scrollRect.left : (scrollRect.right - absoluteDelta);
eraseRect.right = eraseRect.left + absoluteDelta;
const auto eraseAttributes = _GetEraseAttributes(page);
_FillRect(page, eraseRect, whitespace, eraseAttributes);
}
// Routine Description:
// - This helper will do the work of performing an insert or delete character operation
// - Both operations are similar in that they cut text and move it left or right in the buffer, padding the leftover area with spaces.
// Arguments:
// - delta - Number of characters to modify (positive if inserting, negative if deleting).
// Return Value:
// - <none>
void AdaptDispatch::_InsertDeleteCharacterHelper(const VTInt delta)
{
const auto page = _pages.ActivePage();
const auto row = page.Cursor().GetPosition().y;
const auto col = page.Cursor().GetPosition().x;
const auto lineWidth = page.Buffer().GetLineWidth(row);
const auto [topMargin, bottomMargin] = _GetVerticalMargins(page, true);
const auto [leftMargin, rightMargin] = (row >= topMargin && row <= bottomMargin) ?
_GetHorizontalMargins(lineWidth) :
std::make_pair(0, lineWidth - 1);
if (col >= leftMargin && col <= rightMargin)
{
_ScrollRectHorizontally(page, { col, row, rightMargin + 1, row + 1 }, delta);
// The ICH and DCH controls are expected to reset the delayed wrap flag.
page.Cursor().ResetDelayEOLWrap();
}
}
// Routine Description:
// ICH - Insert Character - Blank/default attribute characters will be inserted at the current cursor position.
// - Each inserted character will push all text in the row to the right.
// Arguments:
// - count - The number of characters to insert
// Return Value:
// - True.
bool AdaptDispatch::InsertCharacter(const VTInt count)
{
_InsertDeleteCharacterHelper(count);
return true;
}
// Routine Description:
// DCH - Delete Character - The character at the cursor position will be deleted. Blank/attribute characters will
// be inserted from the right edge of the current line.
// Arguments:
// - count - The number of characters to delete
// Return Value:
// - True.
bool AdaptDispatch::DeleteCharacter(const VTInt count)
{
_InsertDeleteCharacterHelper(-count);
return true;
}
// Routine Description:
// - Fills an area of the buffer with a given character and attributes.
// Arguments:
// - page - Target page to be filled.
// - fillRect - Area of the page that will be affected.
// - fillChar - Character to be written to the buffer.
// - fillAttrs - Attributes to be written to the buffer.
// Return Value:
// - <none>
void AdaptDispatch::_FillRect(const Page& page, const til::rect& fillRect, const std::wstring_view& fillChar, const TextAttribute& fillAttrs) const
{
page.Buffer().FillRect(fillRect, fillChar, fillAttrs);
_api.NotifyAccessibilityChange(fillRect);
}
// Routine Description:
// - ECH - Erase Characters from the current cursor position, by replacing
// them with a space. This will only erase characters in the current line,
// and won't wrap to the next. The attributes of any erased positions
// receive the currently selected attributes.
// Arguments:
// - numChars - The number of characters to erase.
// Return Value:
// - True.
bool AdaptDispatch::EraseCharacters(const VTInt numChars)
{
const auto page = _pages.ActivePage();
const auto row = page.Cursor().GetPosition().y;
const auto startCol = page.Cursor().GetPosition().x;
const auto endCol = std::min<VTInt>(startCol + numChars, page.Buffer().GetLineWidth(row));
// The ECH control is expected to reset the delayed wrap flag.
page.Cursor().ResetDelayEOLWrap();
const auto eraseAttributes = _GetEraseAttributes(page);
_FillRect(page, { startCol, row, endCol, row + 1 }, whitespace, eraseAttributes);
return true;
}
// Routine Description:
// - ED - Erases a portion of the current page of the console.
// Arguments:
// - eraseType - Determines whether to erase:
// From beginning (top-left corner) to the cursor
// From cursor to end (bottom-right corner)
// The entire page
// The scrollback (outside the page area)
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::EraseInDisplay(const DispatchTypes::EraseType eraseType)
{
RETURN_BOOL_IF_FALSE(eraseType <= DispatchTypes::EraseType::Scrollback);
// First things first. If this is a "Scrollback" clear, then just do that.
// Scrollback clears erase everything in the "scrollback" of a *nix terminal
// Everything that's scrolled off the screen so far.
// Or if it's an Erase All, then we also need to handle that specially
// by moving the current contents of the page into the scrollback.
if (eraseType == DispatchTypes::EraseType::Scrollback)
{
return _EraseScrollback();
}
else if (eraseType == DispatchTypes::EraseType::All)
{
return _EraseAll();
}
const auto page = _pages.ActivePage();
auto& textBuffer = page.Buffer();
const auto pageWidth = page.Width();
const auto row = page.Cursor().GetPosition().y;
const auto col = page.Cursor().GetPosition().x;
// The ED control is expected to reset the delayed wrap flag.
// The special case variants above ("erase all" and "erase scrollback")
// take care of that themselves when they set the cursor position.
page.Cursor().ResetDelayEOLWrap();
const auto eraseAttributes = _GetEraseAttributes(page);
// When erasing the display, every line that is erased in full should be
// reset to single width. When erasing to the end, this could include
// the current line, if the cursor is in the first column. When erasing
// from the beginning, though, the current line would never be included,
// because the cursor could never be in the rightmost column (assuming
// the line is double width).
if (eraseType == DispatchTypes::EraseType::FromBeginning)
{
textBuffer.ResetLineRenditionRange(page.Top(), row);
_FillRect(page, { 0, page.Top(), pageWidth, row }, whitespace, eraseAttributes);
_FillRect(page, { 0, row, col + 1, row + 1 }, whitespace, eraseAttributes);
}
if (eraseType == DispatchTypes::EraseType::ToEnd)
{
textBuffer.ResetLineRenditionRange(col > 0 ? row + 1 : row, page.Bottom());
_FillRect(page, { col, row, pageWidth, row + 1 }, whitespace, eraseAttributes);
_FillRect(page, { 0, row + 1, pageWidth, page.Bottom() }, whitespace, eraseAttributes);
}
return true;
}
// Routine Description:
// - EL - Erases the line that the cursor is currently on.
// Arguments:
// - eraseType - Determines whether to erase: From beginning (left edge) to the cursor, from cursor to end (right edge), or the entire line.
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::EraseInLine(const DispatchTypes::EraseType eraseType)
{
const auto page = _pages.ActivePage();
const auto& textBuffer = page.Buffer();
const auto row = page.Cursor().GetPosition().y;
const auto col = page.Cursor().GetPosition().x;
// The EL control is expected to reset the delayed wrap flag.
page.Cursor().ResetDelayEOLWrap();
const auto eraseAttributes = _GetEraseAttributes(page);
switch (eraseType)
{
case DispatchTypes::EraseType::FromBeginning:
_FillRect(page, { 0, row, col + 1, row + 1 }, whitespace, eraseAttributes);
return true;
case DispatchTypes::EraseType::ToEnd:
_FillRect(page, { col, row, textBuffer.GetLineWidth(row), row + 1 }, whitespace, eraseAttributes);
return true;
case DispatchTypes::EraseType::All:
_FillRect(page, { 0, row, textBuffer.GetLineWidth(row), row + 1 }, whitespace, eraseAttributes);
return true;
default:
return false;
}
}
// Routine Description:
// - Selectively erases unprotected cells in an area of the buffer.
// Arguments:
// - page - Target page to be erased.
// - eraseRect - Area of the page that will be affected.
// Return Value:
// - <none>
void AdaptDispatch::_SelectiveEraseRect(const Page& page, const til::rect& eraseRect)
{
if (eraseRect)
{
for (auto row = eraseRect.top; row < eraseRect.bottom; row++)
{
auto& rowBuffer = page.Buffer().GetMutableRowByOffset(row);
for (auto col = eraseRect.left; col < eraseRect.right; col++)
{
// Only unprotected cells are affected.
if (!rowBuffer.GetAttrByColumn(col).IsProtected())
{
// The text is cleared but the attributes are left as is.
rowBuffer.ClearCell(col);
page.Buffer().TriggerRedraw(Viewport::FromCoord({ col, row }));
}
}
}
_api.NotifyAccessibilityChange(eraseRect);
}
}
// Routine Description:
// - DECSED - Selectively erases unprotected cells in a portion of the page.
// Arguments:
// - eraseType - Determines whether to erase:
// From beginning (top-left corner) to the cursor
// From cursor to end (bottom-right corner)
// The entire page area
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::SelectiveEraseInDisplay(const DispatchTypes::EraseType eraseType)
{
const auto page = _pages.ActivePage();
const auto pageWidth = page.Width();
const auto row = page.Cursor().GetPosition().y;
const auto col = page.Cursor().GetPosition().x;
// The DECSED control is expected to reset the delayed wrap flag.
page.Cursor().ResetDelayEOLWrap();
switch (eraseType)
{
case DispatchTypes::EraseType::FromBeginning:
_SelectiveEraseRect(page, { 0, page.Top(), pageWidth, row });
_SelectiveEraseRect(page, { 0, row, col + 1, row + 1 });
return true;
case DispatchTypes::EraseType::ToEnd:
_SelectiveEraseRect(page, { col, row, pageWidth, row + 1 });
_SelectiveEraseRect(page, { 0, row + 1, pageWidth, page.Bottom() });
return true;
case DispatchTypes::EraseType::All:
_SelectiveEraseRect(page, { 0, page.Top(), pageWidth, page.Bottom() });
return true;
default:
return false;
}
}
// Routine Description:
// - DECSEL - Selectively erases unprotected cells on line with the cursor.
// Arguments:
// - eraseType - Determines whether to erase:
// From beginning (left edge) to the cursor
// From cursor to end (right edge)
// The entire line.
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::SelectiveEraseInLine(const DispatchTypes::EraseType eraseType)
{
const auto page = _pages.ActivePage();
const auto& textBuffer = page.Buffer();
const auto row = page.Cursor().GetPosition().y;
const auto col = page.Cursor().GetPosition().x;
// The DECSEL control is expected to reset the delayed wrap flag.
page.Cursor().ResetDelayEOLWrap();
switch (eraseType)
{
case DispatchTypes::EraseType::FromBeginning:
_SelectiveEraseRect(page, { 0, row, col + 1, row + 1 });
return true;
case DispatchTypes::EraseType::ToEnd:
_SelectiveEraseRect(page, { col, row, textBuffer.GetLineWidth(row), row + 1 });
return true;
case DispatchTypes::EraseType::All:
_SelectiveEraseRect(page, { 0, row, textBuffer.GetLineWidth(row), row + 1 });
return true;
default:
return false;
}
}
// Routine Description:
// - Changes the attributes of each cell in a rectangular area of the buffer.
// Arguments:
// - page - Target page to be changed.
// - changeRect - A rectangular area of the page that will be affected.
// - changeOps - Changes that will be applied to each of the attributes.
// Return Value:
// - <none>
void AdaptDispatch::_ChangeRectAttributes(const Page& page, const til::rect& changeRect, const ChangeOps& changeOps)
{
if (changeRect)
{
for (auto row = changeRect.top; row < changeRect.bottom; row++)
{
auto& rowBuffer = page.Buffer().GetMutableRowByOffset(row);
for (auto col = changeRect.left; col < changeRect.right; col++)
{
auto attr = rowBuffer.GetAttrByColumn(col);
auto characterAttributes = attr.GetCharacterAttributes();
characterAttributes &= changeOps.andAttrMask;
characterAttributes ^= changeOps.xorAttrMask;
attr.SetCharacterAttributes(characterAttributes);
if (changeOps.foreground)
{
attr.SetForeground(*changeOps.foreground);