From 03e2e586423ada331ae433db7dea705a8b6ad3fe Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Fri, 20 Jan 2023 11:24:35 -0700 Subject: [PATCH] [hb-view] Improve color parsing Now supports 3, 4, 6, 8 digit colors. --- util/helper-cairo.hh | 13 +++++++------ util/options.hh | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/util/helper-cairo.hh b/util/helper-cairo.hh index fe4367aac..a066d6807 100644 --- a/util/helper-cairo.hh +++ b/util/helper-cairo.hh @@ -130,11 +130,12 @@ helper_cairo_create_scaled_font (const font_options_t *font_opts, { palette_index = HB_PAINT_PALETTE_INDEX_CUSTOM; char **entries = g_strsplit (view_opts->custom_palette, ",", -1); - for (unsigned int i = 0; entries[i]; i++) + for (unsigned i = 0; entries[i]; i++) { - unsigned int fr, fg, fb, fa; - if (sscanf (entries[i], "%2x%2x%2x%2x", &fr, &fg, &fb, &fa) == 4) - cairo_font_options_set_custom_palette_color (font_options, i, fr / 255., fg / 255., fb / 255., fa / 255.); + unsigned fr, fg, fb, fa; + fr = fg = fb = fa = 0; + parse_color (entries[i], fr, fg,fb, fa); + cairo_font_options_set_custom_palette_color (font_options, i, fr / 255., fg / 255., fb / 255., fa / 255.); } g_strfreev (entries); } @@ -510,10 +511,10 @@ helper_cairo_create_context (double w, double h, const char *color; br = bg = bb = ba = 255; color = view_opts->back ? view_opts->back : DEFAULT_BACK; - sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &br, &bg, &bb, &ba); + parse_color (color, br, bg, bb, ba); fr = fg = fb = 0; fa = 255; color = view_opts->fore ? view_opts->fore : DEFAULT_FORE; - sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &fr, &fg, &fb, &fa); + parse_color (color, fr, fg, fb, fa); if (content == CAIRO_CONTENT_ALPHA) { diff --git a/util/options.hh b/util/options.hh index 4336a1dcd..efce20c3a 100644 --- a/util/options.hh +++ b/util/options.hh @@ -242,4 +242,44 @@ __inline float scalbnf (float x, int exp) } #endif +static inline bool +parse_color (const char *s, + unsigned &r, + unsigned &g, + unsigned &b, + unsigned &a) +{ + bool ret = false; + + while (*s == ' ') s++; + if (*s == '#') s++; + + unsigned sr, sg, sb, sa; + sa = 255; + if (sscanf (s, "%2x%2x%2x%2x", &sr, &sg, &sb, &sa) <= 2) + { + if (sscanf (s, "%1x%1x%1x%1x", &sr, &sg, &sb, &sa) >= 3) + { + sr *= 17; + sg *= 17; + sb *= 17; + sa *= 17; + ret = true; + } + } + else + ret = true; + + if (ret) + { + r = sr; + g = sg; + b = sb; + a = sa; + } + + return ret; +} + + #endif