summaryrefslogtreecommitdiff
path: root/src/color.hh
blob: 151547c47e83c6e1ff543b4dedd583bfbdd63f41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifndef color_hh_INCLUDED
#define color_hh_INCLUDED

#include "exception.hh"
#include "hash.hh"
#include "meta.hh"
#include "assert.hh"

namespace Kakoune
{

class String;
class StringView;

struct Color
{
    enum NamedColor : unsigned char
    {
        Default,
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        BrightBlack,
        BrightRed,
        BrightGreen,
        BrightYellow,
        BrightBlue,
        BrightMagenta,
        BrightCyan,
        BrightWhite,
        RGB,
    };

    union
    {
        NamedColor color;
        unsigned char a;
    };
    unsigned char r = 0;
    unsigned char g = 0;
    unsigned char b = 0;

    constexpr bool isRGB() const { return a >= RGB; }

    constexpr Color() : Color{Default} {}
    constexpr Color(NamedColor c) : color{c} {}
    constexpr Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a = 255)
        : a{a}, r{r}, g{g}, b{b}
    {
        validate_alpha();
    }

private:
    constexpr void validate_alpha() {
        static_assert(RGB == 17);
        if (a < RGB)
            throw runtime_error("Colors alpha must be > 16");
    }
};

constexpr bool operator==(Color lhs, Color rhs)
{
    return lhs.color == rhs.color and
           lhs.r == rhs.r and lhs.g == rhs.g and lhs.b == rhs.b;
}

Color str_to_color(StringView color);
String to_string(Color color);

String option_to_string(Color color);
Color option_from_string(Meta::Type<Color>, StringView str);

bool is_color_name(StringView color);

constexpr size_t hash_value(const Color& val)
{
    return val.isRGB() ?
        hash_values(val.a, val.r, val.g, val.b)
      : hash_value(val.color);
}

}

#endif // color_hh_INCLUDED