util: move the colorprint to util-color

And extend it a bit to be more flexible.

Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net>
This commit is contained in:
Peter Hutterer 2020-08-27 11:09:22 +10:00
parent 4ae108fbff
commit c169e10af7

View file

@ -27,6 +27,12 @@
#include "config.h"
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <unistd.h>
#define COLOR_SET \
X(RESET, "\x1B[0m") \
X(BLACK, "\x1B[0;30m") \
@ -73,3 +79,90 @@ __attribute__((unused)) = {
/* ANSI escape sequence for true RBB colors */
#define ANSI_FG_RGB(r, g, b) "\x1B[38;2;" #r ";" #g ";" #b "m"
#define ANSI_BG_RGB(r, g, b) "\x1B[48;2;" #r ";" #g ";" #b "m"
#define RGB(r_, g_, b_) ((r_ << 16) | (g_ << 8) | b_)
#define RGB_BG(r_, g_, b_) (((r_ << 16) | (g_ << 8) | b_) << 32)
static inline uint64_t
rgb(uint8_t r, uint8_t g, uint8_t b)
{
return (r << 16) | (g << 8) | b;
}
static inline uint64_t
rgb_bg(uint8_t r, uint8_t g, uint8_t b)
{
return (((uint64_t)r << 16) | ((uint64_t)g << 8) | (uint64_t)b) << 32;
}
static inline bool
__attribute__((format(printf, 3, 0)))
cvdprintf(int fd, uint64_t rgb, const char *format, va_list args)
{
char buf[1024];
int rc = vsnprintf(buf, sizeof(buf), format, args);
if (rc < 0 || (size_t)rc >= sizeof(buf))
return false;
if (!isatty(fd)) {
dprintf(fd, "%s", buf);
} else {
uint32_t fg = rgb & 0xffffff;
uint32_t bg = (rgb >> 32) & 0xffffff;
uint8_t r = (fg & 0xff0000) >> 16,
g = (fg & 0x00ff00) >> 8,
b = (fg & 0x0000ff);
uint8_t bgr = (bg & 0xff0000) >> 16,
bgg = (bg & 0x00ff00) >> 8,
bgb = (bg & 0x0000ff);
const char *color_fg = "",
*color_bg = "";
static const char *reset = ansi_colorcode[RESET];
char fgstr[64];
char bgstr[64];
if (fg) {
snprintf(fgstr, sizeof(fgstr),
"\x1B[38;2;%u;%u;%um", r, g, b);
color_fg = fgstr;
}
if (bg) {
snprintf(bgstr, sizeof(bgstr),
"\x1B[48;2;%u;%u;%um", bgr, bgg, bgb);
color_bg = bgstr;
}
dprintf(fd, "%s%s%s%s", color_bg, color_fg, buf, reset);
}
return true;
}
static inline void
__attribute__((format(printf, 3, 4)))
cdprintf(int fd, uint64_t rgb, const char *format, ...)
{
va_list args;
va_start(args, format);
cvdprintf(fd, rgb, format, args);
va_end(args);
}
static inline void
__attribute__((format(printf, 2, 3)))
cprintf(uint64_t rgb, const char *format, ...)
{
va_list args;
va_start(args, format);
cvdprintf(STDOUT_FILENO, rgb, format, args);
va_end(args);
}
static inline void
__attribute__((format(printf, 3, 4)))
cfprintf(FILE *fp, uint64_t rgb, const char *format, ...)
{
va_list args;
va_start(args, format);
cvdprintf(fileno(fp), rgb, format, args);
va_end(args);
}