face.hh (2547B)
1 #ifndef face_hh_INCLUDED 2 #define face_hh_INCLUDED 3 4 #include "color.hh" 5 #include "flags.hh" 6 7 namespace Kakoune 8 { 9 10 enum class Attribute : int 11 { 12 Normal = 0, 13 Underline = 1 << 1, 14 CurlyUnderline = 1 << 2, 15 DoubleUnderline = 1 << 3, 16 Reverse = 1 << 4, 17 Blink = 1 << 5, 18 Bold = 1 << 6, 19 Dim = 1 << 7, 20 Italic = 1 << 8, 21 Strikethrough = 1 << 9, 22 FinalFg = 1 << 10, 23 FinalBg = 1 << 11, 24 FinalAttr = 1 << 12, 25 Final = FinalFg | FinalBg | FinalAttr 26 }; 27 28 constexpr bool with_bit_ops(Meta::Type<Attribute>) { return true; } 29 30 struct Face 31 { 32 Color fg = Color::Default; 33 Color bg = Color::Default; 34 Attribute attributes = Attribute::Normal; 35 Color underline = Color::Default; 36 37 friend constexpr bool operator==(const Face& lhs, const Face& rhs) = default; 38 39 friend constexpr size_t hash_value(const Face& val) 40 { 41 return hash_values(val.fg, val.bg, val.underline, val.attributes); 42 } 43 }; 44 45 inline Face merge_faces(const Face& base, const Face& face) 46 { 47 auto alpha_blend = [](Color base, Color color) { 48 auto blend = [&](unsigned char Color::*field) { 49 int blended = (base.*field * (255 - color.a) + color.*field * color.a) / 255; 50 return static_cast<unsigned char>(blended <= 255 ? blended : 255); 51 }; 52 int alpha = color.a + base.a * (255 - color.a) / 255; 53 return Color{blend(&Color::r), blend(&Color::g), blend(&Color::b), 54 static_cast<unsigned char>(alpha <= 255 ? alpha : 255)}; 55 }; 56 57 auto choose = [&](Color Face::*color, Attribute final_attr) { 58 if (face.attributes & final_attr) 59 return face.*color; 60 if (base.attributes & final_attr) 61 return base.*color; 62 if (face.*color == Color::Default) 63 return base.*color; 64 if ((base.*color).isRGB() and (face.*color).isRGB() and (face.*color).a != 255) 65 return alpha_blend(base.*color, face.*color); 66 return face.*color; 67 }; 68 69 return Face{ choose(&Face::fg, Attribute::FinalFg), 70 choose(&Face::bg, Attribute::FinalBg), 71 face.attributes & Attribute::FinalAttr ? face.attributes | Attribute{base.attributes & Attribute::Final} : 72 base.attributes & Attribute::FinalAttr ? base.attributes : 73 face.attributes | base.attributes, 74 choose(&Face::underline, Attribute{0}) }; 75 } 76 77 } 78 79 #endif // face_hh_INCLUDED