terminal/src/host/server.h
James Holderness b604117421
Standardize the color table order (#11602)
## Summary of the Pull Request

In the original implementation, we used two different orderings for the color tables. The WT color table used ANSI order, while the conhost color table used a Windows-specific order. This PR standardizes on the ANSI color order everywhere, so the usage of indexed colors is consistent across both parts of the code base, which will hopefully allow more of the code to be shared one day.

## References

This is another small step towards de-duplicating `AdaptDispatch` and `TerminalDispatch` for issue #3849, and is essentially a followup to the SGR dispatch refactoring in PR #6728.

## PR Checklist
* [x] Closes #11461
* [x] CLA signed.
* [x] Tests added/passed
* [ ] Documentation updated.
* [ ] Schema updated.
* [x] I've discussed this with core contributors already. Issue number where discussion took place: #11461

## Detailed Description of the Pull Request / Additional comments

Conhost still needs to deal with legacy attributes using Windows color order, so those values now need to be transposed to ANSI colors order when creating a `TextAttribute` object. This is done with a simple mapping table, which also handles the translation of the default color entries, so it's actually slightly faster than the original code.

And when converting `TextAttribute` values back to legacy console attributes, we were already using a mapping table to handle the narrowing of 256-color values down to 16 colors, so we just needed to adjust that table to account for the translation from ANSI to Windows, and then could make use of the same table for both 256-color and 16-color values.

There are also a few places in conhost that read from or write to the color tables, and those now need to transpose the index values. I've addressed this by creating separate `SetLegacyColorTableEntry` and `GetLegacyColorTableEntry` methods in the `Settings` class which take care of the mapping, so it's now clearer in which cases the code is dealing with legacy values, and which are ANSI values.

These methods are used in the `SetConsoleScreenBufferInfoEx` and `GetConsoleScreenBufferInfoEx` APIs, as well as a few place where color preferences are handled (the registry, shortcut links, and the properties dialog), none of which are particularly sensitive to performance. However, we also use the legacy table when looking up the default colors for rendering (which happens a lot), so I've refactored that code so the default color calculations now only occur once per frame.

The plus side of all of this is that the VT code doesn't need to do the index translation anymore, so we can finally get rid of all the calls to `XTermToWindowsIndex`, and we no longer need a separate color table initialization method for conhost, so I was able to merge a number of color initialization methods into one. We also no longer need to translate from legacy values to ANSI when generating VT sequences for conpty.

The one exception to that is the 16-color VT renderer, which uses the `TextColor::GetLegacyIndex` method to approximate 16-color equivalents for RGB and 256-color values. Since that method returns a legacy index, it still needs to be translated to ANSI before it can be used in a VT sequence. But this should be no worse than it was before.

One more special case is conhost's secret _Color Selection_ feature. That uses `Ctrl`+Number and `Alt`+Number key sequences to highlight parts of the buffer, and the mapping from number to color is based on the Windows color order. So that mapping now needs to be transposed, but that's also not performance sensitive.

The only thing that I haven't bothered to update is the trace logging code in the `Telemetry` class, which logs the first 16 entries in the color table. Those entries are now going to be in a different order, but I didn't think that would be of great concern to anyone.

## Validation Steps Performed

A lot of unit tests needed to be updated to use ANSI color constants when setting indexed colors, where before they might have been expecting values in Windows order. But this replaced a wild mix of different constants, sometimes having to use bit shifting, as well as values mapped with `XTermToWindowsIndex`, so I think the tests are a whole lot clearer now. Only a few cases have been left with literal numbers where that seemed more appropriate.

In addition to getting the unit tests working, I've also manually tested the behaviour of all the console APIs which I thought could be affected by these changes, and confirmed that they produced the same results in the new code as they did in the original implementation.

This includes:
- `WriteConsoleOutput`
- `ReadConsoleOutput`
- `SetConsoleTextAttribute` with `WriteConsoleOutputCharacter`
- `FillConsoleOutputAttribute` and `FillConsoleOutputCharacter` 
- `ScrollConsoleScreenBuffer`
- `GetConsoleScreenBufferInfo`
- `GetConsoleScreenBufferInfoEx`
- `SetConsoleScreenBufferInfoEx`

I've also manually tested changing colors via the console properties menu, the registry, and shortcut links, including setting default colors and popup colors. And I've tested that the "Quirks Mode" is still working as expected in PowerShell.

In terms of performance, I wrote a little test app that filled a 80x9999 buffer with random color combinations using `WriteConsoleOutput`, which I figured was likely to be the most performance sensitive call, and I think it now actually performs slightly better than the original implementation.

I've also tested similar code - just filling the visible window - with SGR VT sequences of various types, and the performance seems about the same as it was before.
2021-11-04 22:13:22 +00:00

177 lines
6.2 KiB
C++

/*++
Copyright (c) Microsoft Corporation
Licensed under the MIT license.
Module Name:
- server.h
Abstract:
- This module contains the internal structures and definitions used by the console server.
Author:
- Therese Stowell (ThereseS) 12-Nov-1990
Revision History:
--*/
#pragma once
#include "IIoProvider.hpp"
#include "settings.hpp"
#include "conimeinfo.h"
#include "VtIo.hpp"
#include "CursorBlinker.hpp"
#include "../server/ProcessList.h"
#include "../server/WaitQueue.h"
#include "../host/RenderData.hpp"
#include "../renderer/inc/BlinkingState.hpp"
// clang-format off
// Flags flags
#define CONSOLE_IS_ICONIC 0x00000001
#define CONSOLE_OUTPUT_SUSPENDED 0x00000002
#define CONSOLE_HAS_FOCUS 0x00000004
#define CONSOLE_IGNORE_NEXT_MOUSE_INPUT 0x00000008
#define CONSOLE_SELECTING 0x00000010
#define CONSOLE_SCROLLING 0x00000020
// unused (CONSOLE_DISABLE_CLOSE) 0x00000040
// unused (CONSOLE_USE_POLY_TEXT) 0x00000080
// Removed Oct 2017 - added a headless mode, which revealed that the consumption
// of this flag was redundant.
// unused (CONSOLE_NO_WINDOW) 0x00000100
// unused (CONSOLE_VDM_REGISTERED) 0x00000200
#define CONSOLE_UPDATING_SCROLL_BARS 0x00000400
#define CONSOLE_QUICK_EDIT_MODE 0x00000800
#define CONSOLE_CONNECTED_TO_EMULATOR 0x00002000
// unused (CONSOLE_FULLSCREEN_NOPAINT) 0x00004000
#define CONSOLE_QUIT_POSTED 0x00008000
#define CONSOLE_AUTO_POSITION 0x00010000
#define CONSOLE_IGNORE_NEXT_KEYUP 0x00020000
// unused (CONSOLE_WOW_REGISTERED) 0x00040000
#define CONSOLE_HISTORY_NODUP 0x00100000
#define CONSOLE_SCROLLBAR_TRACKING 0x00200000
#define CONSOLE_SETTING_WINDOW_SIZE 0x00800000
// unused (CONSOLE_VDM_HIDDEN_WINDOW) 0x01000000
// unused (CONSOLE_OS2_REGISTERED) 0x02000000
// unused (CONSOLE_OS2_OEM_FORMAT) 0x04000000
// unused (CONSOLE_JUST_VDM_UNREGISTERED) 0x08000000
// unused (CONSOLE_FULLSCREEN_INITIALIZED) 0x10000000
#define CONSOLE_USE_PRIVATE_FLAGS 0x20000000
// unused (CONSOLE_TSF_ACTIVATED) 0x40000000
#define CONSOLE_INITIALIZED 0x80000000
#define CONSOLE_SUSPENDED (CONSOLE_OUTPUT_SUSPENDED)
// clang-format on
class COOKED_READ_DATA;
class CommandHistory;
class CONSOLE_INFORMATION :
public Settings,
public Microsoft::Console::IIoProvider
{
public:
CONSOLE_INFORMATION();
~CONSOLE_INFORMATION();
CONSOLE_INFORMATION(const CONSOLE_INFORMATION& c) = delete;
CONSOLE_INFORMATION& operator=(const CONSOLE_INFORMATION& c) = delete;
ConsoleProcessList ProcessHandleList;
InputBuffer* pInputBuffer;
SCREEN_INFORMATION* ScreenBuffers; // singly linked list
ConsoleWaitQueue OutputQueue;
DWORD Flags;
std::atomic<WORD> PopupCount;
// the following fields are used for ansi-unicode translation
UINT CP;
UINT OutputCP;
ULONG CtrlFlags; // indicates outstanding ctrl requests
ULONG LimitingProcessId;
CPINFO CPInfo;
CPINFO OutputCPInfo;
ConsoleImeInfo ConsoleIme;
void LockConsole();
bool TryLockConsole();
void UnlockConsole();
bool IsConsoleLocked() const;
ULONG GetCSRecursionCount();
Microsoft::Console::VirtualTerminal::VtIo* GetVtIo();
SCREEN_INFORMATION& GetActiveOutputBuffer() override;
const SCREEN_INFORMATION& GetActiveOutputBuffer() const override;
bool HasActiveOutputBuffer() const;
InputBuffer* const GetActiveInputBuffer() const;
bool IsInVtIoMode() const;
bool HasPendingCookedRead() const noexcept;
const COOKED_READ_DATA& CookedReadData() const noexcept;
COOKED_READ_DATA& CookedReadData() noexcept;
void SetCookedReadData(COOKED_READ_DATA* readData) noexcept;
COLORREF GetDefaultForeground() const noexcept;
COLORREF GetDefaultBackground() const noexcept;
std::pair<COLORREF, COLORREF> LookupAttributeColors(const TextAttribute& attr) const noexcept;
std::pair<COLORREF, COLORREF> LookupAttributeColors(const TextAttribute& attr, const COLORREF defaultFg, const COLORREF defaultBg) const noexcept;
void SetTitle(const std::wstring_view newTitle);
void SetTitlePrefix(const std::wstring_view newTitlePrefix);
void SetOriginalTitle(const std::wstring_view originalTitle);
void SetLinkTitle(const std::wstring_view linkTitle);
const std::wstring_view GetTitle() const noexcept;
const std::wstring_view GetOriginalTitle() const noexcept;
const std::wstring_view GetLinkTitle() const noexcept;
const std::wstring_view GetTitleAndPrefix() const;
[[nodiscard]] static NTSTATUS AllocateConsole(const std::wstring_view title);
// MSFT:16886775 : get rid of friends
friend void SetActiveScreenBuffer(_Inout_ SCREEN_INFORMATION& screenInfo);
friend class SCREEN_INFORMATION;
friend class CommonState;
Microsoft::Console::CursorBlinker& GetCursorBlinker() noexcept;
Microsoft::Console::Render::BlinkingState& GetBlinkingState() const noexcept;
CHAR_INFO AsCharInfo(const OutputCellView& cell) const noexcept;
RenderData renderData;
private:
CRITICAL_SECTION _csConsoleLock; // serialize input and output using this
std::wstring _Title;
std::wstring _Prefix; // Eg Select, Mark - things that we manually prepend to the title.
std::wstring _TitleAndPrefix;
std::wstring _OriginalTitle;
std::wstring _LinkTitle; // Path to .lnk file
SCREEN_INFORMATION* pCurrentScreenBuffer;
COOKED_READ_DATA* _cookedReadData; // non-ownership pointer
Microsoft::Console::VirtualTerminal::VtIo _vtIo;
Microsoft::Console::CursorBlinker _blinker;
mutable Microsoft::Console::Render::BlinkingState _blinkingState;
};
#define ConsoleLocked() (ServiceLocator::LocateGlobals()->getConsoleInformation()->ConsoleLock.OwningThread == NtCurrentTeb()->ClientId.UniqueThread)
#define CONSOLE_STATUS_WAIT 0xC0030001
#define CONSOLE_STATUS_READ_COMPLETE 0xC0030002
#define CONSOLE_STATUS_WAIT_NO_BLOCK 0xC0030003
#include "../server/ObjectHandle.h"
void SetActiveScreenBuffer(SCREEN_INFORMATION& screenInfo);