color.cc (2591B)
1 #include "color.hh" 2 3 #include "exception.hh" 4 #include "ranges.hh" 5 #include "format.hh" 6 7 #include <cstdio> 8 9 namespace Kakoune 10 { 11 12 static constexpr const char* color_names[] = { 13 "default", 14 "black", 15 "red", 16 "green", 17 "yellow", 18 "blue", 19 "magenta", 20 "cyan", 21 "white", 22 "bright-black", 23 "bright-red", 24 "bright-green", 25 "bright-yellow", 26 "bright-blue", 27 "bright-magenta", 28 "bright-cyan", 29 "bright-white", 30 }; 31 32 bool is_color_name(StringView color) 33 { 34 return contains(color_names, color); 35 } 36 37 Color str_to_color(StringView color) 38 { 39 auto it = find_if(color_names, [&](const char* c){ return color == c; }); 40 if (it != std::end(color_names)) 41 return static_cast<Color::NamedColor>(it - color_names); 42 43 auto hval = [&color](char c) -> int 44 { 45 if (c >= 'A' and c <= 'F') 46 return 10 + c - 'A'; 47 else if (c >= 'a' and c <= 'f') 48 return 10 + c - 'a'; 49 else if (c >= '0' and c <= '9') 50 return c - '0'; 51 throw runtime_error(format("invalid digit '{}' in '{}'", c, color)); 52 }; 53 54 if (color.length() == 10 and color.substr(0_byte, 4_byte) == "rgb:") 55 return { (unsigned char)(hval(color[4]) * 16 + hval(color[5])), 56 (unsigned char)(hval(color[6]) * 16 + hval(color[7])), 57 (unsigned char)(hval(color[8]) * 16 + hval(color[9])) }; 58 if (color.length() == 13 and color.substr(0_byte, 5_byte) == "rgba:") 59 return { (unsigned char)(hval(color[5]) * 16 + hval(color[6])), 60 (unsigned char)(hval(color[7]) * 16 + hval(color[8])), 61 (unsigned char)(hval(color[9]) * 16 + hval(color[10])), 62 (unsigned char)(hval(color[11]) * 16 + hval(color[12])) }; 63 64 throw runtime_error(format("unable to parse color: '{}'", color)); 65 return Color::Default; 66 } 67 68 String to_string(Color color) 69 { 70 if (color.isRGB()) 71 { 72 char buffer[14]; 73 if (color.a == 255) 74 format_to(buffer, "rgb:{:02}{:02}{:02}", hex(color.r), hex(color.g), hex(color.b)); 75 else 76 format_to(buffer, "rgba:{:02}{:02}{:02}{:02}", hex(color.r), hex(color.g), hex(color.b), hex(color.a)); 77 return buffer; 78 } 79 else 80 { 81 size_t index = static_cast<size_t>(color.color); 82 kak_assert(index < std::end(color_names) - std::begin(color_names)); 83 return color_names[index]; 84 } 85 } 86 87 String option_to_string(Color color) 88 { 89 return to_string(color); 90 } 91 92 Color option_from_string(Meta::Type<Color>, StringView str) 93 { 94 return str_to_color(str); 95 } 96 97 }