Skip to content

Commit

Permalink
Add support for short hex color codes like #CCC (#2658)
Browse files Browse the repository at this point in the history
This adds a few lines to support shorthand color hex codes like #ABC. They are treated as equivalent of #AABBCC.

Fixes #2639.
  • Loading branch information
kojoru authored and DHowett committed Sep 4, 2019
1 parent 21067a7 commit 51f5353
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/cascadia/ut_app/JsonTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ namespace TerminalAppUnitTests
"\"name\" : \"Campbell\","
"\"purple\" : \"#881798\","
"\"red\" : \"#C50F1F\","
"\"white\" : \"#CCCCCC\","
"\"white\" : \"#CCC\","
"\"yellow\" : \"#C19C00\""
"}" };

Expand Down
23 changes: 18 additions & 5 deletions src/types/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,20 +83,33 @@ std::string Utils::ColorToHexString(const COLORREF color)
}

// Function Description:
// - Parses a color from a string. The string should be in the format "#RRGGBB"
// - Parses a color from a string. The string should be in the format "#RRGGBB" or "#RGB"
// Arguments:
// - str: a string representation of the COLORREF to parse
// Return Value:
// - A COLORREF if the string could successfully be parsed. If the string is not
// the correct format, throws E_INVALIDARG
COLORREF Utils::ColorFromHexString(const std::string str)
{
THROW_HR_IF(E_INVALIDARG, str.size() < 7 || str.size() >= 8);
THROW_HR_IF(E_INVALIDARG, str.size() != 7 && str.size() != 4);
THROW_HR_IF(E_INVALIDARG, str[0] != '#');

std::string rStr{ &str[1], 2 };
std::string gStr{ &str[3], 2 };
std::string bStr{ &str[5], 2 };
std::string rStr;
std::string gStr;
std::string bStr;

if (str.size() == 4)
{
rStr = std::string(2, str[1]);
gStr = std::string(2, str[2]);
bStr = std::string(2, str[3]);
}
else
{
rStr = std::string(&str[1], 2);
gStr = std::string(&str[3], 2);
bStr = std::string(&str[5], 2);
}

BYTE r = static_cast<BYTE>(std::stoul(rStr, nullptr, 16));
BYTE g = static_cast<BYTE>(std::stoul(gStr, nullptr, 16));
Expand Down

0 comments on commit 51f5353

Please sign in to comment.