home/src/color.cc

98 lines
2.5 KiB
C++
Raw Normal View History

#include "color.hh"
#include "exception.hh"
#include "ranges.hh"
#include "string_utils.hh"
2014-11-12 22:27:07 +01:00
#include <cstdio>
namespace Kakoune
{
2014-12-27 13:09:28 +01:00
static constexpr const char* color_names[] = {
"default",
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
2017-10-25 05:08:22 +02:00
"bright-black",
"bright-red",
"bright-green",
"bright-yellow",
"bright-blue",
"bright-magenta",
"bright-cyan",
"bright-white",
2014-12-27 13:09:28 +01:00
};
bool is_color_name(StringView color)
{
2014-12-27 13:09:28 +01:00
return contains(color_names, color);
}
Color str_to_color(StringView color)
{
2014-12-27 13:09:28 +01:00
auto it = find_if(color_names, [&](const char* c){ return color == c; });
if (it != std::end(color_names))
return static_cast<Color::NamedColor>(it - color_names);
2015-04-02 22:27:41 +02:00
auto hval = [&color](char c) -> int
{
2015-04-02 22:27:41 +02:00
if (c >= 'A' and c <= 'F')
return 10 + c - 'A';
else if (c >= 'a' and c <= 'f')
return 10 + c - 'a';
else if (c >= '0' and c <= '9')
return c - '0';
throw runtime_error(format("invalid digit '{}' in '{}'", c, color));
};
if (color.length() == 10 and color.substr(0_byte, 4_byte) == "rgb:")
return { (unsigned char)(hval(color[4]) * 16 + hval(color[5])),
(unsigned char)(hval(color[6]) * 16 + hval(color[7])),
(unsigned char)(hval(color[8]) * 16 + hval(color[9])) };
if (color.length() == 13 and color.substr(0_byte, 5_byte) == "rgba:")
return { (unsigned char)(hval(color[5]) * 16 + hval(color[6])),
(unsigned char)(hval(color[7]) * 16 + hval(color[8])),
(unsigned char)(hval(color[9]) * 16 + hval(color[10])),
(unsigned char)(hval(color[11]) * 16 + hval(color[12])) };
2015-04-02 22:27:41 +02:00
2018-04-06 16:56:53 +02:00
throw runtime_error(format("unable to parse color: '{}'", color));
return Color::Default;
}
String to_string(Color color)
{
if (color.isRGB())
2014-12-27 13:09:28 +01:00
{
char buffer[14];
if (color.a == 255)
sprintf(buffer, "rgb:%02x%02x%02x", color.r, color.g, color.b);
else
sprintf(buffer, "rgba:%02x%02x%02x%02x", color.r, color.g, color.b, color.a);
2014-12-27 13:09:28 +01:00
return buffer;
}
else
{
2014-12-27 13:09:28 +01:00
size_t index = static_cast<size_t>(color.color);
kak_assert(index < std::end(color_names) - std::begin(color_names));
return color_names[index];
}
}
2013-07-26 00:26:43 +02:00
String option_to_string(Color color)
{
return to_string(color);
}
Color option_from_string(Meta::Type<Color>, StringView str)
{
return str_to_color(str);
}
}