开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (3)
标签 (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
master
分支 (3)
标签 (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (3)
标签 (3)
master
zadjii-msft-patch-readme
richturn/retarget-echocon
1904.29002
1810.02002
1708.14008
Terminal
/
src
/
host
/
_stream.cpp
Terminal
/
src
/
host
/
_stream.cpp
_stream.cpp 57.94 KB
一键复制 编辑 原始数据 按行查看 历史
Dustin Howett 提交于 2019年05月03日 06:29 +08:00 . Initial release of the Windows Terminal source code
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
// 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 "utf8ToWidecharParser.hpp"
#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;
// 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 COORD 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
{
coordCursor.X = screenInfo.GetTextBuffer().GetCursor().GetPosition().X;
}
}
const auto bufferAttributes = screenInfo.GetAttributes();
const auto relativeMargins = screenInfo.GetRelativeScrollMargins();
auto viewport = screenInfo.GetViewport();
SMALL_RECT srMargins = screenInfo.GetAbsoluteScrollMargins().ToInclusive();
const bool fMarginsSet = srMargins.Bottom > srMargins.Top;
COORD currentCursor = screenInfo.GetTextBuffer().GetCursor().GetPosition();
const int iCurrentCursorY = currentCursor.Y;
const bool inVtMode = WI_IsFlagSet(screenInfo.OutputMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING);
const bool fCursorInMargins = iCurrentCursorY <= srMargins.Bottom && iCurrentCursorY >= srMargins.Top;
const bool cursorAboveViewport = coordCursor.Y < 0 && inVtMode;
const bool fScrollDown = fMarginsSet && fCursorInMargins && (coordCursor.Y > srMargins.Bottom);
bool fScrollUp = fMarginsSet && fCursorInMargins && (coordCursor.Y < srMargins.Top);
const bool 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 bool 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 };
// Unset the margins to scroll the content below the margins,
// then restore them after.
screenInfo.SetScrollMargins(Viewport::FromInclusive({0}));
try
{
ScrollRegion(screenInfo, scrollRect, std::nullopt, newPostMarginsOrigin, UNICODE_SPACE, bufferAttributes);
}
CATCH_LOG();
screenInfo.SetScrollMargins(relativeMargins);
// 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())
{
Viewport invalid = Viewport::FromDimensions(viewport.Origin(), {viewport.Width(), delta});
screenInfo.GetRenderTarget().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 = screenInfo.GetViewport().Left(); // NOTE: Left/Right Scroll margins don't do anything currently.
scrollRect.Right = screenInfo.GetViewport().RightInclusive();
COORD dest;
dest.X = scrollRect.Left;
dest.Y = scrollRect.Top - diff;
SMALL_RECT clipRect = scrollRect;
// Typically ScrollRegion() clips by the scroll margins. However, if
// we're scrolling down at the top of the viewport, we'll need to
// not clip at the margins, instead move the contents of the margins
// up above the viewport. So we'll clear out the current margins, and
// set them to the viewport+(#diff rows above the viewport).
if (scrollDownAtTop)
{
clipRect.Top -= diff;
auto fakeMargins = srMargins;
fakeMargins.Top -= diff;
auto fakeRelative = viewport.ConvertToOrigin(Viewport::FromInclusive(fakeMargins));
screenInfo.SetScrollMargins(fakeRelative);
}
try
{
ScrollRegion(screenInfo, scrollRect, clipRect, dest, UNICODE_SPACE, bufferAttributes);
}
CATCH_LOG();
if (scrollDownAtTop)
{
// Undo the fake margins we set above
screenInfo.SetScrollMargins(relativeMargins);
}
coordCursor.Y -= diff;
}
NTSTATUS 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 bool cursorMovedPastViewport = coordCursor.Y > screenInfo.GetViewport().BottomInclusive();
const bool 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_ECHO if called by Read (echoing characters)
// 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 CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
TextBuffer& textBuffer = screenInfo.GetTextBuffer();
Cursor& cursor = textBuffer.GetCursor();
COORD CursorPosition = cursor.GetPosition();
NTSTATUS Status = STATUS_SUCCESS;
SHORT XPosition;
WCHAR LocalBuffer[LOCAL_BUFFER_SIZE];
size_t TempNumSpaces = 0;
const bool fUnprocessed = WI_IsFlagClear(screenInfo.OutputMode, ENABLE_PROCESSED_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 TextAttribute Attributes = screenInfo.GetAttributes();
const size_t BufferSize = *pcb;
*pcb = 0;
const wchar_t* lpString = pwchRealUnicode;
const COORD coordScreenBufferSize = screenInfo.GetBufferSize().Dimensions();
while (*pcb < BufferSize)
{
// correct for delayed EOL
if (cursor.IsDelayedEOLWrap())
{
const COORD 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)
{
bool fDoEolWrap = false;
if (WI_IsFlagSet(dwFlags, WC_DELAY_EOL_WRAP))
{
// Correct if it's a printable character and whoever called us still understands/wants delayed EOL wrap.
if (*lpString >= UNICODE_SPACE)
{
fDoEolWrap = true;
}
else if (*lpString == UNICODE_BACKSPACE)
{
// if we have an active wrap and a backspace comes in, process it by moving the cursor
// back one cell position unless it's already at the start of a row.
*pcb += sizeof(WCHAR);
lpString++;
pwchRealUnicode++;
if (CursorPosition.X != 0)
{
--CursorPosition.X;
Status = AdjustCursorPosition(screenInfo, CursorPosition, WI_IsFlagSet(dwFlags, WC_KEEP_CURSOR_VISIBLE), psScrollY);
CursorPosition = cursor.GetPosition();
}
continue;
}
}
else
{
// Uh oh, we've hit a consumer that doesn't know about delayed end of lines. To rectify this, just quickly jump
// forward to the next line as if we had done it earlier, then let everything else play out normally.
fDoEolWrap = true;
}
if (fDoEolWrap)
{
CursorPosition.X = 0;
CursorPosition.Y++;
Status = AdjustCursorPosition(screenInfo, CursorPosition, WI_IsFlagSet(dwFlags, WC_KEEP_CURSOR_VISIBLE), psScrollY);
CursorPosition = cursor.GetPosition();
}
}
}
if (screenInfo.InVTMode())
{
// if we're at the beginning of a row and we get a backspace and told to limit backspacing, skip it
if (*lpString == UNICODE_BACKSPACE && CursorPosition.X == 0 && WI_IsFlagSet(dwFlags, WC_LIMIT_BACKSPACE))
{
*pcb += sizeof(wchar_t);
++lpString;
++pwchRealUnicode;
continue;
}
}
// As an optimization, collect characters in buffer and print out all at once.
XPosition = cursor.GetPosition().X;
size_t i = 0;
wchar_t* 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 wchar_t Char = *lpString;
const wchar_t RealUnicodeChar = *pwchRealUnicode;
if (!IS_GLYPH_CHAR(RealUnicodeChar) || fUnprocessed)
{
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_ECHO)
{
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:
if (screenInfo.InVTMode())
{
goto EndWhile;
}
else
{
const ULONG TabSize = NUMBER_OF_SPACES_IN_TAB(XPosition);
XPosition = (SHORT)(XPosition + TabSize);
if (XPosition >= coordScreenBufferSize.X || WI_IsFlagSet(dwFlags, WC_NONDESTRUCTIVE_TAB))
{
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_ECHO) && (IS_CONTROL_CHAR(RealUnicodeChar)))
{
CtrlChar:
if (i < (LOCAL_BUFFER_SIZE - 1))
{
*LocalBufPtr = (WCHAR)'^';
LocalBufPtr++;
XPosition++;
i++;
*LocalBufPtr = (WCHAR)(RealUnicodeChar + (WCHAR)'@');
LocalBufPtr++;
XPosition++;
i++;
pwchBuffer++;
}
else
{
goto EndWhile;
}
}
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 (CharType == C1_CNTRL)
{
ConvertOutputToUnicode(gci.OutputCP,
(LPSTR)&RealUnicodeChar,
1,
LocalBufPtr,
1);
}
else if (Char == UNICODE_NULL)
{
*LocalBufPtr = UNICODE_SPACE;
}
else
{
*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.
if (i > (ULONG)coordScreenBufferSize.X - CursorPosition.X)
{
i = (ULONG)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
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);
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)
{
// 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);
}
if (*pcb == BufferSize)
{
if (nullptr != pcSpaces)
{
*pcSpaces = TempNumSpaces;
}
return STATUS_SUCCESS;
}
continue;
}
else if (*pcb >= BufferSize)
{
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 seperate 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).GetCharRow().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 && (screenInfo.OutputMode & ENABLE_WRAP_AT_EOL_OUTPUT) && pwchBuffer > pwchBufferBackupLimit)
{
if (CheckBisectProcessW(screenInfo,
pwchBufferBackupLimit,
pwchBuffer + 1 - pwchBufferBackupLimit,
coordScreenBufferSize.X - sOriginalXPosition,
sOriginalXPosition,
dwFlags & WC_ECHO))
{
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).GetCharRow().SetWrapForced(false);
Status = AdjustCursorPosition(screenInfo, CursorPosition, dwFlags & WC_KEEP_CURSOR_VISIBLE, psScrollY);
}
}
break;
}
case UNICODE_TAB:
{
// if VT-style tabs are set, then handle them the VT way, including not inserting spaces.
// just move the cursor to the next tab stop.
if (screenInfo.InVTMode())
{
const COORD cCursorOld = cursor.GetPosition();
// Get Forward tab handles tabbing past the end of the buffer
CursorPosition = screenInfo.GetForwardTab(cCursorOld);
}
else
{
const size_t TabSize = 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).GetCharRow().SetWrapForced(true);
}
else
{
NumChars = gsl::narrow<size_t>(CursorPosition.X - cursor.GetPosition().X);
CursorPosition.Y = cursor.GetPosition().Y;
}
if (!WI_IsFlagSet(dwFlags, WC_NONDESTRUCTIVE_TAB))
{
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).GetCharRow().SetWrapForced(false);
}
Status = AdjustCursorPosition(screenInfo, CursorPosition, (dwFlags & WC_KEEP_CURSOR_VISIBLE) != 0, psScrollY);
break;
}
default:
{
const wchar_t Char = *lpString;
if (Char >= UNICODE_SPACE &&
IsGlyphFullWidth(Char) &&
XPosition >= (coordScreenBufferSize.X - 1) &&
(screenInfo.OutputMode & ENABLE_WRAP_AT_EOL_OUTPUT))
{
const COORD TargetPoint = cursor.GetPosition();
ROW& Row = textBuffer.GetRowByOffset(TargetPoint.Y);
CharRow& 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
charRow.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).
charRow.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_ECHO if called by Read (echoing characters)
// 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);
}
NTSTATUS Status = STATUS_SUCCESS;
size_t const 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)));
StateMachine& machine = screenInfo.GetStateMachine();
size_t const 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:
// - Console lock must be held when calling this routine
// - String has been translated to unicode at this point.
// Arguments:
// - pwchBuffer - wide character text to be inserted into buffer
// - pcbBuffer - byte count of pwchBuffer on the way in, number of bytes consumed on the way out.
// - screenInfo - Screen Information class to write the text into at the current cursor position
// - ppWaiter - If writing to the console is blocked for whatever reason, this will be filled with a pointer to context
// that can be used by the server to resume the call at a later time.
// Return Value:
// - STATUS_SUCCESS if OK.
// - CONSOLE_STATUS_WAIT if we couldn't finish now and need to be called back later (see ppWaiter).
// - Or a suitable NTSTATUS format error code for memory/string/math failures.
[[nodiscard]]
NTSTATUS DoWriteConsole(_In_reads_bytes_(*pcbBuffer) PWCHAR pwchBuffer,
_Inout_ size_t* const pcbBuffer,
SCREEN_INFORMATION& screenInfo,
std::unique_ptr<WriteData>& waiter)
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
if (WI_IsAnyFlagSet(gci.Flags, (CONSOLE_SUSPENDED | CONSOLE_SELECTING | CONSOLE_SCROLLBAR_TRACKING)))
{
try
{
waiter = std::make_unique<WriteData>(screenInfo,
pwchBuffer,
*pcbBuffer,
gci.OutputCP);
}
catch (...)
{
return NTSTATUS_FROM_HRESULT(wil::ResultFromCaughtException());
}
return CONSOLE_STATUS_WAIT;
}
const auto& textBuffer = screenInfo.GetTextBuffer();
return WriteChars(screenInfo,
pwchBuffer,
pwchBuffer,
pwchBuffer,
pcbBuffer,
nullptr,
textBuffer.GetCursor().GetPosition().X,
WC_LIMIT_BACKSPACE,
nullptr);
}
// Routine Description:
// - This method performs the actual work of attempting to write to the console, converting data types as necessary
// to adapt from the server types to the legacy internal host types.
// - It operates on Unicode data only. It's assumed the text is translated by this point.
// Arguments:
// - OutContext - the console output object to write the new text into
// - pwsTextBuffer - wide character text buffer provided by client application to insert
// - cchTextBufferLength - text buffer counted in characters
// - pcchTextBufferRead - character count of the number of characters we were able to insert before returning
// - ppWaiter - If we are blocked from writing now and need to wait, this is filled with contextual data for the server to restore the call later
// Return Value:
// - S_OK if successful.
// - S_OK if we need to wait (check if ppWaiter is not nullptr).
// - Or a suitable HRESULT code for math/string/memory failures.
[[nodiscard]]
HRESULT WriteConsoleWImplHelper(IConsoleOutputObject& context,
const std::wstring_view buffer,
size_t& read,
std::unique_ptr<WriteData>& waiter) noexcept
{
try
{
// Set out variables in case we exit early.
read = 0;
waiter.reset();
// Convert characters to bytes to give to DoWriteConsole.
size_t cbTextBufferLength;
RETURN_IF_FAILED(SizeTMult(buffer.size(), sizeof(wchar_t), &cbTextBufferLength));
NTSTATUS Status = DoWriteConsole(const_cast<wchar_t*>(buffer.data()), &cbTextBufferLength, context, waiter);
// Convert back from bytes to characters for the resulting string length written.
read = cbTextBufferLength / sizeof(wchar_t);
if (Status == CONSOLE_STATUS_WAIT)
{
FAIL_FAST_IF_NULL(waiter.get());
Status = STATUS_SUCCESS;
}
RETURN_NTSTATUS(Status);
}
CATCH_RETURN();
}
// Routine Description:
// - Writes non-Unicode formatted data into the given console output object.
// - This method will convert from the given input into wide characters before chain calling the wide character version of the function.
// It uses the current Output Codepage for conversions (set via SetConsoleOutputCP).
// - NOTE: This may be blocked for various console states and will return a wait context pointer if necessary.
// Arguments:
// - context - the console output object to write the new text into
// - buffer - char/byte text buffer provided by client application to insert
// - read - character count of the number of characters (also bytes because A version) we were able to insert before returning
// - waiter - If we are blocked from writing now and need to wait, this is filled with contextual data for the server to restore the call later
// Return Value:
// - S_OK if successful.
// - S_OK if we need to wait (check if ppWaiter is not nullptr).
// - Or a suitable HRESULT code for math/string/memory failures.
[[nodiscard]]
HRESULT ApiRoutines::WriteConsoleAImpl(IConsoleOutputObject& context,
const std::string_view buffer,
size_t& read,
std::unique_ptr<IWaitRoutine>& waiter) noexcept
{
try
{
const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation();
// Ensure output variables are initialized.
read = 0;
waiter.reset();
bool fLeadByteCaptured = false;
bool fLeadByteConsumed = false;
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
if (buffer.size() == 0)
{
return S_OK;
}
const auto codepage = gci.OutputCP;
// Convert our input parameters to Unicode
std::unique_ptr<wchar_t[]> wideCharBuffer{ nullptr };
static Utf8ToWideCharParser parser{ gci.OutputCP };
// update current codepage in case it was changed from last time
// this was called. We do this outside the UTF-8 check because the parser drops its state
// when the codepage changes.
parser.SetCodePage(gci.OutputCP);
SCREEN_INFORMATION& ScreenInfo = context.GetActiveBuffer();
wchar_t* pwchBuffer;
size_t cchBuffer;
if (codepage == CP_UTF8)
{
wideCharBuffer.release();
unsigned int charCount;
unsigned int charsConsumed;
unsigned int charsGenerated;
RETURN_IF_FAILED(SizeTToUInt(buffer.size(), &charCount));
RETURN_IF_FAILED(parser.Parse(reinterpret_cast<const byte*>(buffer.data()),
charCount,
charsConsumed,
wideCharBuffer,
charsGenerated));
pwchBuffer = reinterpret_cast<wchar_t*>(wideCharBuffer.get());
cchBuffer = charsGenerated;
read = charsConsumed;
}
else
{
NTSTATUS Status = STATUS_SUCCESS;
PWCHAR TransBuffer;
PWCHAR TransBufferOriginalLocation;
DWORD Length;
ULONG dbcsNumBytes = 0;
ULONG BufPtrNumBytes = 0;
const char* BufPtr = buffer.data();
// (cchTextBufferLength + 2) I think because we might be shoving another unicode char
// from ScreenInfo->WriteConsoleDbcsLeadByte in front
TransBuffer = new WCHAR[buffer.size() + 2];
RETURN_IF_NULL_ALLOC(TransBuffer);
ZeroMemory(TransBuffer, sizeof(WCHAR) * (buffer.size() + 2));
TransBufferOriginalLocation = TransBuffer;
unsigned int uiTextBufferLength;
RETURN_IF_FAILED(SizeTToUInt(buffer.size(), &uiTextBufferLength));
if (!ScreenInfo.WriteConsoleDbcsLeadByte[0] || *(PUCHAR)BufPtr < (UCHAR) ' ')
{
dbcsNumBytes = 0;
BufPtrNumBytes = uiTextBufferLength;
}
else if (buffer.size())
{
// there was a portion of a dbcs character stored from a previous
// call so we take the 2nd half from BufPtr[0], put them together
// and write the wide char to TransBuffer[0]
ScreenInfo.WriteConsoleDbcsLeadByte[1] = *(PCHAR)BufPtr;
try
{
const std::string_view leadByte(reinterpret_cast<const char* const>(ScreenInfo.WriteConsoleDbcsLeadByte),
ARRAYSIZE(ScreenInfo.WriteConsoleDbcsLeadByte));
const std::wstring converted = ConvertToW(gci.OutputCP, leadByte);
FAIL_FAST_IF(converted.size() != 1);
dbcsNumBytes = sizeof(wchar_t);
TransBuffer[0] = converted.at(0);
BufPtr++;
}
catch (...)
{
Status = STATUS_UNSUCCESSFUL;
dbcsNumBytes = 0;
}
// this looks weird to be always incrementing even if the conversion failed, but this is the
// original behavior so it's left unchanged.
TransBuffer++;
BufPtrNumBytes = uiTextBufferLength - 1;
// Note that we used a stored lead byte from a previous call in order to complete this write
// Use this to offset the "number of bytes consumed" calculation at the end by -1 to account
// for using a byte we had internally, not off the stream.
fLeadByteConsumed = true;
}
else
{
// nothing in ScreenInfo->WriteConsoleDbcsLeadByte and nothing in BufPtr
BufPtrNumBytes = 0;
}
ScreenInfo.WriteConsoleDbcsLeadByte[0] = 0;
// if the last byte in BufPtr is a lead byte for the current code page,
// save it for the next time this function is called and we can piece it
// back together then
__analysis_assume(BufPtrNumBytes <= uiTextBufferLength);
if (BufPtrNumBytes && CheckBisectStringA((PCHAR)BufPtr, BufPtrNumBytes, &gci.OutputCPInfo))
{
ScreenInfo.WriteConsoleDbcsLeadByte[0] = *((PCHAR)BufPtr + BufPtrNumBytes - 1);
BufPtrNumBytes--;
// Note that we captured a lead byte during this call, but won't actually draw it until later.
// Use this to offset the "number of bytes consumed" calculation at the end by +1 to account
// for taking a byte off the stream.
fLeadByteCaptured = true;
}
if (BufPtrNumBytes != 0)
{
// convert the remaining bytes in BufPtr to wide chars
Length = sizeof(WCHAR) * MultiByteToWideChar(gci.OutputCP,
0,
(LPCCH)BufPtr,
BufPtrNumBytes,
TransBuffer,
BufPtrNumBytes);
if (Length == 0)
{
Status = STATUS_UNSUCCESSFUL;
}
BufPtrNumBytes = Length;
}
pwchBuffer = TransBufferOriginalLocation;
cchBuffer = (dbcsNumBytes + BufPtrNumBytes) / sizeof(wchar_t);
}
// Make the W version of the call
size_t cchBufferRead;
// Hold the specific version of the waiter locally so we can tinker with it if we must to store additional context.
std::unique_ptr<WriteData> writeDataWaiter;
HRESULT const hr = WriteConsoleWImplHelper(ScreenInfo, { pwchBuffer, cchBuffer }, cchBufferRead, writeDataWaiter);
// If there is no waiter, process the byte count now.
if (nullptr == writeDataWaiter.get())
{
// Calculate how many bytes of the original A buffer were consumed in the W version of the call to satisfy pcchTextBufferRead.
// For UTF-8 conversions, we've already returned this information above.
if (CP_UTF8 != codepage)
{
size_t cchTextBufferRead = 0;
// Start by counting the number of A bytes we used in printing our W string to the screen.
try
{
cchTextBufferRead = GetALengthFromW(codepage, { pwchBuffer, cchBufferRead });
}
CATCH_LOG();
// If we captured a byte off the string this time around up above, it means we didn't feed
// it into the WriteConsoleW above, and therefore its consumption isn't accounted for
// in the count we just made. Add +1 to compensate.
if (fLeadByteCaptured)
{
cchTextBufferRead++;
}
// If we consumed an internally-stored lead byte this time around up above, it means that we
// fed a byte into WriteConsoleW that wasn't a part of this particular call's request.
// We need to -1 to compensate and tell the caller the right number of bytes consumed this request.
if (fLeadByteConsumed)
{
cchTextBufferRead--;
}
read = cchTextBufferRead;
}
}
else
{
// If there is a waiter, then we need to stow some additional information in the wait structure so
// we can synthesize the correct byte count later when the wait routine is triggered.
if (CP_UTF8 != codepage)
{
// For non-UTF8 codepages, save the lead byte captured/consumed data so we can +1 or -1 the final decoded count
// in the WaitData::Notify method later.
writeDataWaiter->SetLeadByteAdjustmentStatus(fLeadByteCaptured, fLeadByteConsumed);
}
else
{
// For UTF8 codepages, just remember the consumption count from the UTF-8 parser.
writeDataWaiter->SetUtf8ConsumedCharacters(read);
}
}
// Free remaining data
if (codepage != CP_UTF8)
{
delete[] pwchBuffer;
}
// Give back the waiter now that we're done with tinkering with it.
waiter.reset(writeDataWaiter.release());
return hr;
}
CATCH_RETURN();
}
// Routine Description:
// - Writes Unicode formatted data into the given console output object.
// - NOTE: This may be blocked for various console states and will return a wait context pointer if necessary.
// Arguments:
// - OutContext - the console output object to write the new text into
// - pwsTextBuffer - wide character text buffer provided by client application to insert
// - cchTextBufferLength - text buffer counted in characters
// - pcchTextBufferRead - character count of the number of characters we were able to insert before returning
// - ppWaiter - If we are blocked from writing now and need to wait, this is filled with contextual data for the server to restore the call later
// Return Value:
// - S_OK if successful.
// - S_OK if we need to wait (check if ppWaiter is not nullptr).
// - Or a suitable HRESULT code for math/string/memory failures.
[[nodiscard]]
HRESULT ApiRoutines::WriteConsoleWImpl(IConsoleOutputObject& context,
const std::wstring_view buffer,
size_t& read,
std::unique_ptr<IWaitRoutine>& waiter) noexcept
{
try
{
LockConsole();
auto Unlock = wil::scope_exit([&] { UnlockConsole(); });
std::unique_ptr<WriteData> writeDataWaiter;
RETURN_IF_FAILED(WriteConsoleWImplHelper(context.GetActiveBuffer(), buffer, read, writeDataWaiter));
// Transfer specific waiter pointer into the generic interface wrapper.
waiter.reset(writeDataWaiter.release());
return S_OK;
}
CATCH_RETURN();
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

The new Windows Terminal, and the original Windows console host -- all in the same place!
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/AbstractFactory/Terminal.git
git@gitee.com:AbstractFactory/Terminal.git
AbstractFactory
Terminal
Terminal
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /