terminal/src/terminal/adapter/adaptDispatchGraphics.cpp
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

311 lines
11 KiB
C++

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include <precomp.h>
#include "adaptDispatch.hpp"
#include "conGetSet.hpp"
#include "../../types/inc/utils.hpp"
#define ENABLE_INTSAFE_SIGNED_FUNCTIONS
#include <intsafe.h>
using namespace Microsoft::Console::VirtualTerminal;
using namespace Microsoft::Console::VirtualTerminal::DispatchTypes;
// Routine Description:
// - Helper to parse extended graphics options, which start with 38 (FG) or 48 (BG)
// These options are followed by either a 2 (RGB) or 5 (xterm index)
// RGB sequences then take 3 MORE params to designate the R, G, B parts of the color
// Xterm index will use the param that follows to use a color from the preset 256 color xterm color table.
// Arguments:
// - options - An array of options that will be used to generate the RGB color
// - attr - The attribute that will be updated with the parsed color.
// - isForeground - Whether or not the parsed color is for the foreground.
// Return Value:
// - The number of options consumed, not including the initial 38/48.
size_t AdaptDispatch::_SetRgbColorsHelper(const VTParameters options,
TextAttribute& attr,
const bool isForeground) noexcept
{
size_t optionsConsumed = 1;
const DispatchTypes::GraphicsOptions typeOpt = options.at(0);
if (typeOpt == DispatchTypes::GraphicsOptions::RGBColorOrFaint)
{
optionsConsumed = 4;
const size_t red = options.at(1).value_or(0);
const size_t green = options.at(2).value_or(0);
const size_t blue = options.at(3).value_or(0);
// ensure that each value fits in a byte
if (red <= 255 && green <= 255 && blue <= 255)
{
const COLORREF rgbColor = RGB(red, green, blue);
attr.SetColor(rgbColor, isForeground);
}
}
else if (typeOpt == DispatchTypes::GraphicsOptions::BlinkOrXterm256Index)
{
optionsConsumed = 2;
const size_t tableIndex = options.at(1).value_or(0);
if (tableIndex <= 255)
{
const auto adjustedIndex = gsl::narrow_cast<BYTE>(tableIndex);
if (isForeground)
{
attr.SetIndexedForeground256(adjustedIndex);
}
else
{
attr.SetIndexedBackground256(adjustedIndex);
}
}
}
return optionsConsumed;
}
// Routine Description:
// - SGR - Modifies the graphical rendering options applied to the next
// characters written into the buffer.
// - Options include colors, invert, underlines, and other "font style"
// type options.
// Arguments:
// - options - An array of options that will be applied from 0 to N, in order,
// one at a time by setting or removing flags in the font style properties.
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::SetGraphicsRendition(const VTParameters options)
{
TextAttribute attr;
bool success = _pConApi->PrivateGetTextAttributes(attr);
if (success)
{
// Run through the graphics options and apply them
for (size_t i = 0; i < options.size(); i++)
{
const GraphicsOptions opt = options.at(i);
switch (opt)
{
case Off:
attr.SetDefaultForeground();
attr.SetDefaultBackground();
attr.SetDefaultMetaAttrs();
break;
case ForegroundDefault:
attr.SetDefaultForeground();
break;
case BackgroundDefault:
attr.SetDefaultBackground();
break;
case BoldBright:
attr.SetBold(true);
break;
case RGBColorOrFaint:
attr.SetFaint(true);
break;
case NotBoldOrFaint:
attr.SetBold(false);
attr.SetFaint(false);
break;
case Italics:
attr.SetItalic(true);
break;
case NotItalics:
attr.SetItalic(false);
break;
case BlinkOrXterm256Index:
case RapidBlink: // We just interpret rapid blink as an alias of blink.
attr.SetBlinking(true);
break;
case Steady:
attr.SetBlinking(false);
break;
case Invisible:
attr.SetInvisible(true);
break;
case Visible:
attr.SetInvisible(false);
break;
case CrossedOut:
attr.SetCrossedOut(true);
break;
case NotCrossedOut:
attr.SetCrossedOut(false);
break;
case Negative:
attr.SetReverseVideo(true);
break;
case Positive:
attr.SetReverseVideo(false);
break;
case Underline:
attr.SetUnderlined(true);
break;
case DoublyUnderlined:
attr.SetDoublyUnderlined(true);
break;
case NoUnderline:
attr.SetUnderlined(false);
attr.SetDoublyUnderlined(false);
break;
case Overline:
attr.SetOverlined(true);
break;
case NoOverline:
attr.SetOverlined(false);
break;
case ForegroundBlack:
attr.SetIndexedForeground(TextColor::DARK_BLACK);
break;
case ForegroundBlue:
attr.SetIndexedForeground(TextColor::DARK_BLUE);
break;
case ForegroundGreen:
attr.SetIndexedForeground(TextColor::DARK_GREEN);
break;
case ForegroundCyan:
attr.SetIndexedForeground(TextColor::DARK_CYAN);
break;
case ForegroundRed:
attr.SetIndexedForeground(TextColor::DARK_RED);
break;
case ForegroundMagenta:
attr.SetIndexedForeground(TextColor::DARK_MAGENTA);
break;
case ForegroundYellow:
attr.SetIndexedForeground(TextColor::DARK_YELLOW);
break;
case ForegroundWhite:
attr.SetIndexedForeground(TextColor::DARK_WHITE);
break;
case BackgroundBlack:
attr.SetIndexedBackground(TextColor::DARK_BLACK);
break;
case BackgroundBlue:
attr.SetIndexedBackground(TextColor::DARK_BLUE);
break;
case BackgroundGreen:
attr.SetIndexedBackground(TextColor::DARK_GREEN);
break;
case BackgroundCyan:
attr.SetIndexedBackground(TextColor::DARK_CYAN);
break;
case BackgroundRed:
attr.SetIndexedBackground(TextColor::DARK_RED);
break;
case BackgroundMagenta:
attr.SetIndexedBackground(TextColor::DARK_MAGENTA);
break;
case BackgroundYellow:
attr.SetIndexedBackground(TextColor::DARK_YELLOW);
break;
case BackgroundWhite:
attr.SetIndexedBackground(TextColor::DARK_WHITE);
break;
case BrightForegroundBlack:
attr.SetIndexedForeground(TextColor::BRIGHT_BLACK);
break;
case BrightForegroundBlue:
attr.SetIndexedForeground(TextColor::BRIGHT_BLUE);
break;
case BrightForegroundGreen:
attr.SetIndexedForeground(TextColor::BRIGHT_GREEN);
break;
case BrightForegroundCyan:
attr.SetIndexedForeground(TextColor::BRIGHT_CYAN);
break;
case BrightForegroundRed:
attr.SetIndexedForeground(TextColor::BRIGHT_RED);
break;
case BrightForegroundMagenta:
attr.SetIndexedForeground(TextColor::BRIGHT_MAGENTA);
break;
case BrightForegroundYellow:
attr.SetIndexedForeground(TextColor::BRIGHT_YELLOW);
break;
case BrightForegroundWhite:
attr.SetIndexedForeground(TextColor::BRIGHT_WHITE);
break;
case BrightBackgroundBlack:
attr.SetIndexedBackground(TextColor::BRIGHT_BLACK);
break;
case BrightBackgroundBlue:
attr.SetIndexedBackground(TextColor::BRIGHT_BLUE);
break;
case BrightBackgroundGreen:
attr.SetIndexedBackground(TextColor::BRIGHT_GREEN);
break;
case BrightBackgroundCyan:
attr.SetIndexedBackground(TextColor::BRIGHT_CYAN);
break;
case BrightBackgroundRed:
attr.SetIndexedBackground(TextColor::BRIGHT_RED);
break;
case BrightBackgroundMagenta:
attr.SetIndexedBackground(TextColor::BRIGHT_MAGENTA);
break;
case BrightBackgroundYellow:
attr.SetIndexedBackground(TextColor::BRIGHT_YELLOW);
break;
case BrightBackgroundWhite:
attr.SetIndexedBackground(TextColor::BRIGHT_WHITE);
break;
case ForegroundExtended:
i += _SetRgbColorsHelper(options.subspan(i + 1), attr, true);
break;
case BackgroundExtended:
i += _SetRgbColorsHelper(options.subspan(i + 1), attr, false);
break;
}
}
success = _pConApi->PrivateSetTextAttributes(attr);
}
return success;
}
// Method Description:
// - Saves the current text attributes to an internal stack.
// Arguments:
// - options: if not empty, specify which portions of the current text attributes should
// be saved. Options that are not supported are ignored. If no options are specified,
// all attributes are stored.
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::PushGraphicsRendition(const VTParameters options)
{
bool success = true;
TextAttribute currentAttributes;
success = _pConApi->PrivateGetTextAttributes(currentAttributes);
if (success)
{
_sgrStack.Push(currentAttributes, options);
}
return success;
}
// Method Description:
// - Restores text attributes from the internal stack. If only portions of text attributes
// were saved, combines those with the current attributes.
// Arguments:
// - <none>
// Return Value:
// - True if handled successfully. False otherwise.
bool AdaptDispatch::PopGraphicsRendition()
{
bool success = true;
TextAttribute currentAttributes;
success = _pConApi->PrivateGetTextAttributes(currentAttributes);
if (success)
{
success = _pConApi->PrivateSetTextAttributes(_sgrStack.Pop(currentAttributes));
}
return success;
}