11 #define ARRAY_SIZE(X) (sizeof(X) / sizeof((X)[0]))
19 #define TB_YELLOW 0x03
21 #define TB_MAGENTA 0x05
27 static const rgb_t defcolors
[] = {
28 [TB_BLACK
] = RGB3(BLACK
),
30 [TB_GREEN
] = RGB3(GREEN
),
31 [TB_YELLOW
] = RGB3(YELLOW
),
32 [TB_BLUE
] = RGB3(BLUE
),
33 [TB_MAGENTA
] = RGB3(MAGENTA
),
34 [TB_CYAN
] = RGB3(CYAN
),
35 [TB_WHITE
] = RGB3(WHITE
),
38 #define ABS(X) ((X) < 0 ? (X) * -1 : (X))
39 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
40 static int getNearestColor(rgb_t col
) {
41 unsigned dist
[ARRAY_SIZE(defcolors
)];
43 unsigned nearest
= 0xFFFFFFFF;
44 unsigned brightestcol
= 0;
45 if(col
.r
== col
.g
&& col
.r
== col
.b
) {
46 if(col
.r
< 128) return TB_BLACK
;
49 brightestcol
= MAX(brightestcol
, col
.r
);
50 brightestcol
= MAX(brightestcol
, col
.g
);
51 brightestcol
= MAX(brightestcol
, col
.b
);
52 brightestcol
= MAX(brightestcol
, 1);
53 int scale
= (255*256) / brightestcol
;
54 for(i
= 0; i
< ARRAY_SIZE(defcolors
); i
++) {
55 dist
[i
] = ABS(defcolors
[i
].r
* 256 - col
.r
* scale
) +
56 ABS(defcolors
[i
].g
* 256 - col
.g
* scale
) +
57 ABS(defcolors
[i
].b
* 256 - col
.b
* scale
);
58 if(dist
[i
] == 0) return i
;
59 if(dist
[i
] < nearest
) nearest
= dist
[i
];
61 for(i
= 0; i
< ARRAY_SIZE(defcolors
); i
++) {
62 if(dist
[i
] == nearest
) return i
;
69 int console_setcolor(struct Console
* self
, int is_fg
, rgb_t mycolor
) {
70 struct TbConsole
*c
= &self
->backend
.tb
;
71 int *dest
= is_fg
? &c
->fgcolor
: &c
->bgcolor
;
72 *dest
= getNearestColor(mycolor
);