Code

fix to return the end pointer when desired
[inkscape.git] / src / svg / svg-color.cpp
1 #define __SP_SVG_COLOR_C__
3 /**
4  * \file
5  * Reading \& writing of SVG/CSS colors.
6  */
7 /*
8  * Authors:
9  *   Lauris Kaplinski <lauris@kaplinski.com>
10  *
11  * Copyright (C) 1999-2002 Lauris Kaplinski
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 #ifdef HAVE_CONFIG_H
17 # include "config.h"
18 #endif
20 #include "svg-color.h"
21 #include <cassert>
22 #include <math.h>
23 #include <glib/gmem.h>
24 #include <glib/gmessages.h>
25 #include <glib/gstrfuncs.h>
26 #include <glib/ghash.h>
27 #include <glib/gutils.h>
28 #include <cstdio> // sprintf
29 #include "strneq.h"
30 using std::sprintf;
32 struct SPSVGColor {
33     unsigned long rgb;
34     char const *name;
35 };
37 /*
38  * These are the colors defined in the SVG standard
39  */
40 static SPSVGColor const sp_svg_color_named[] = {
41     { 0xF0F8FF, "aliceblue" },
42     { 0xFAEBD7, "antiquewhite" },
43     { 0x00FFFF, "aqua" },
44     { 0x7FFFD4, "aquamarine" },
45     { 0xF0FFFF, "azure" },
46     { 0xF5F5DC, "beige" },
47     { 0xFFE4C4, "bisque" },
48     { 0x000000, "black" },
49     { 0xFFEBCD, "blanchedalmond" },
50     { 0x0000FF, "blue" },
51     { 0x8A2BE2, "blueviolet" },
52     { 0xA52A2A, "brown" },
53     { 0xDEB887, "burlywood" },
54     { 0x5F9EA0, "cadetblue" },
55     { 0x7FFF00, "chartreuse" },
56     { 0xD2691E, "chocolate" },
57     { 0xFF7F50, "coral" },
58     { 0x6495ED, "cornflowerblue" },
59     { 0xFFF8DC, "cornsilk" },
60     { 0xDC143C, "crimson" },
61     { 0x00FFFF, "cyan" },
62     { 0x00008B, "darkblue" },
63     { 0x008B8B, "darkcyan" },
64     { 0xB8860B, "darkgoldenrod" },
65     { 0xA9A9A9, "darkgray" },
66     { 0x006400, "darkgreen" },
67     { 0xA9A9A9, "darkgrey" },
68     { 0xBDB76B, "darkkhaki" },
69     { 0x8B008B, "darkmagenta" },
70     { 0x556B2F, "darkolivegreen" },
71     { 0xFF8C00, "darkorange" },
72     { 0x9932CC, "darkorchid" },
73     { 0x8B0000, "darkred" },
74     { 0xE9967A, "darksalmon" },
75     { 0x8FBC8F, "darkseagreen" },
76     { 0x483D8B, "darkslateblue" },
77     { 0x2F4F4F, "darkslategray" },
78     { 0x2F4F4F, "darkslategrey" },
79     { 0x00CED1, "darkturquoise" },
80     { 0x9400D3, "darkviolet" },
81     { 0xFF1493, "deeppink" },
82     { 0x00BFFF, "deepskyblue" },
83     { 0x696969, "dimgray" },
84     { 0x696969, "dimgrey" },
85     { 0x1E90FF, "dodgerblue" },
86     { 0xB22222, "firebrick" },
87     { 0xFFFAF0, "floralwhite" },
88     { 0x228B22, "forestgreen" },
89     { 0xFF00FF, "fuchsia" },
90     { 0xDCDCDC, "gainsboro" },
91     { 0xF8F8FF, "ghostwhite" },
92     { 0xFFD700, "gold" },
93     { 0xDAA520, "goldenrod" },
94     { 0x808080, "gray" },
95     { 0x808080, "grey" },
96     { 0x008000, "green" },
97     { 0xADFF2F, "greenyellow" },
98     { 0xF0FFF0, "honeydew" },
99     { 0xFF69B4, "hotpink" },
100     { 0xCD5C5C, "indianred" },
101     { 0x4B0082, "indigo" },
102     { 0xFFFFF0, "ivory" },
103     { 0xF0E68C, "khaki" },
104     { 0xE6E6FA, "lavender" },
105     { 0xFFF0F5, "lavenderblush" },
106     { 0x7CFC00, "lawngreen" },
107     { 0xFFFACD, "lemonchiffon" },
108     { 0xADD8E6, "lightblue" },
109     { 0xF08080, "lightcoral" },
110     { 0xE0FFFF, "lightcyan" },
111     { 0xFAFAD2, "lightgoldenrodyellow" },
112     { 0xD3D3D3, "lightgray" },
113     { 0x90EE90, "lightgreen" },
114     { 0xD3D3D3, "lightgrey" },
115     { 0xFFB6C1, "lightpink" },
116     { 0xFFA07A, "lightsalmon" },
117     { 0x20B2AA, "lightseagreen" },
118     { 0x87CEFA, "lightskyblue" },
119     { 0x778899, "lightslategray" },
120     { 0x778899, "lightslategrey" },
121     { 0xB0C4DE, "lightsteelblue" },
122     { 0xFFFFE0, "lightyellow" },
123     { 0x00FF00, "lime" },
124     { 0x32CD32, "limegreen" },
125     { 0xFAF0E6, "linen" },
126     { 0xFF00FF, "magenta" },
127     { 0x800000, "maroon" },
128     { 0x66CDAA, "mediumaquamarine" },
129     { 0x0000CD, "mediumblue" },
130     { 0xBA55D3, "mediumorchid" },
131     { 0x9370DB, "mediumpurple" },
132     { 0x3CB371, "mediumseagreen" },
133     { 0x7B68EE, "mediumslateblue" },
134     { 0x00FA9A, "mediumspringgreen" },
135     { 0x48D1CC, "mediumturquoise" },
136     { 0xC71585, "mediumvioletred" },
137     { 0x191970, "midnightblue" },
138     { 0xF5FFFA, "mintcream" },
139     { 0xFFE4E1, "mistyrose" },
140     { 0xFFE4B5, "moccasin" },
141     { 0xFFDEAD, "navajowhite" },
142     { 0x000080, "navy" },
143     { 0xFDF5E6, "oldlace" },
144     { 0x808000, "olive" },
145     { 0x6B8E23, "olivedrab" },
146     { 0xFFA500, "orange" },
147     { 0xFF4500, "orangered" },
148     { 0xDA70D6, "orchid" },
149     { 0xEEE8AA, "palegoldenrod" },
150     { 0x98FB98, "palegreen" },
151     { 0xAFEEEE, "paleturquoise" },
152     { 0xDB7093, "palevioletred" },
153     { 0xFFEFD5, "papayawhip" },
154     { 0xFFDAB9, "peachpuff" },
155     { 0xCD853F, "peru" },
156     { 0xFFC0CB, "pink" },
157     { 0xDDA0DD, "plum" },
158     { 0xB0E0E6, "powderblue" },
159     { 0x800080, "purple" },
160     { 0xFF0000, "red" },
161     { 0xBC8F8F, "rosybrown" },
162     { 0x4169E1, "royalblue" },
163     { 0x8B4513, "saddlebrown" },
164     { 0xFA8072, "salmon" },
165     { 0xF4A460, "sandybrown" },
166     { 0x2E8B57, "seagreen" },
167     { 0xFFF5EE, "seashell" },
168     { 0xA0522D, "sienna" },
169     { 0xC0C0C0, "silver" },
170     { 0x87CEEB, "skyblue" },
171     { 0x6A5ACD, "slateblue" },
172     { 0x708090, "slategray" },
173     { 0x708090, "slategrey" },
174     { 0xFFFAFA, "snow" },
175     { 0x00FF7F, "springgreen" },
176     { 0x4682B4, "steelblue" },
177     { 0xD2B48C, "tan" },
178     { 0x008080, "teal" },
179     { 0xD8BFD8, "thistle" },
180     { 0xFF6347, "tomato" },
181     { 0x40E0D0, "turquoise" },
182     { 0xEE82EE, "violet" },
183     { 0xF5DEB3, "wheat" },
184     { 0xFFFFFF, "white" },
185     { 0xF5F5F5, "whitesmoke" },
186     { 0xFFFF00, "yellow" },
187     { 0x9ACD32, "yellowgreen" }
188 };
190 static GHashTable *sp_svg_create_color_hash();
192 guint32
193 sp_svg_read_color(gchar const *str, guint32 const dfl)
195     return sp_svg_read_color(str, NULL, dfl);
198 static guint32
199 internal_sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 def)
201     static GHashTable *colors = NULL;
202     guint32 val = 0;
204     if (str == NULL) return def;
205     while ((*str <= ' ') && *str) str++;
206     if (!*str) return def;
208     if (str[0] == '#') {
209         gint i;
210         for (i = 1; str[i]; i++) {
211             int hexval;
212             if (str[i] >= '0' && str[i] <= '9')
213                 hexval = str[i] - '0';
214             else if (str[i] >= 'A' && str[i] <= 'F')
215                 hexval = str[i] - 'A' + 10;
216             else if (str[i] >= 'a' && str[i] <= 'f')
217                 hexval = str[i] - 'a' + 10;
218             else
219                 break;
220             val = (val << 4) + hexval;
221         }
222         /* handle #rgb case */
223         if (i == 1 + 3) {
224             val = ((val & 0xf00) << 8) |
225                 ((val & 0x0f0) << 4) |
226                 (val & 0x00f);
227             val |= val << 4;
228         } else if (i != 1 + 6) {
229             /* must be either 3 or 6 digits. */
230             return def;
231         }
232         if (end_ptr) {
233             *end_ptr = str + i;
234         }
235     } else if (strneq(str, "rgb(", 4)) {
236         gboolean hasp, hasd;
237         gchar *s, *e;
238         gdouble r, g, b;
240         s = (gchar *) str + 4;
241         hasp = FALSE;
242         hasd = FALSE;
244         r = g_ascii_strtod(s, &e);
245         if (s == e) return def;
246         s = e;
247         if (*s == '%') {
248             hasp = TRUE;
249             s += 1;
250         } else {
251             hasd = TRUE;
252         }
253         while (*s && g_ascii_isspace(*s)) s += 1;
254         if (*s != ',') return def;
255         s += 1;
256         while (*s && g_ascii_isspace(*s)) s += 1;
257         g = g_ascii_strtod(s, &e);
258         if (s == e) return def;
259         s = e;
260         if (*s == '%') {
261             hasp = TRUE;
262             s += 1;
263         } else {
264             hasd = TRUE;
265         }
266         while (*s && g_ascii_isspace(*s)) s += 1;
267         if (*s != ',') return def;
268         s += 1;
269         while (*s && g_ascii_isspace(*s)) s += 1;
270         b = g_ascii_strtod(s, &e);
271         if (s == e) return def;
272         s = e;
273         if (*s == '%') {
274             hasp = TRUE;
275         } else {
276             hasd = TRUE;
277         }
278         while(*s && g_ascii_isspace(*s)) s += 1;
279         if (*s != ')') {
280             return def;
281         }
282         ++s;
283         if (hasp && hasd) return def;
284         if (hasp) {
285             val = (guint) floor(CLAMP(r, 0.0, 100.0) * 2.559999) << 24;
286             val |= ((guint) floor(CLAMP(g, 0.0, 100.0) * 2.559999) << 16);
287             val |= ((guint) floor(CLAMP(b, 0.0, 100.0) * 2.559999) << 8);
288         } else {
289             val = (guint) CLAMP(r, 0, 255) << 24;
290             val |= ((guint) CLAMP(g, 0, 255) << 16);
291             val |= ((guint) CLAMP(b, 0, 255) << 8);
292         }
293         if (end_ptr) {
294             *end_ptr = s;
295         }
296         return val;
297     } else {
298         gint i;
299         if (!colors) {
300             colors = sp_svg_create_color_hash();
301         }
302         gchar c[32];
303         for (i = 0; i < 31; i++) {
304             if (str[i] == ';' || g_ascii_isspace(str[i])) {
305                 c[i] = '\0';
306                 break;
307             }
308             c[i] = g_ascii_tolower(str[i]);
309             if (!str[i]) break;
310         }
311         c[31] = '\0';
313         gpointer const rgb_ptr = g_hash_table_lookup(colors, c);
314         if (rgb_ptr) {
315             val = *(static_cast<unsigned long *>(rgb_ptr));
316         } else {
317             return def;
318         }
319         if (end_ptr) {
320             *end_ptr = str + i;
321         }
322     }
324     return (val << 8);
327 guint32
328 sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 dfl)
330     /* I've been rather hurried in editing the above to add support for end_ptr, so I'm adding
331      * this check wrapper. */
332     gchar const *end = str;
333     guint32 const ret = internal_sp_svg_read_color(str, &end, dfl);
334     assert(ret == dfl && end == str
335            || (((ret & 0xff) == 0)
336                && str < end));
337     if (str < end) {
338         gchar *buf = (gchar *) g_malloc(end + 1 - str);
339         memcpy(buf, str, end - str);
340         buf[end - str] = '\0';
341         gchar const *buf_end = buf;
342         guint32 const check = internal_sp_svg_read_color(buf, &buf_end, 1);
343         assert(check == ret
344                && buf_end - buf == end - str);
345         g_free(buf);
347         if ( end_ptr ) {
348             *end_ptr = end;
349         }
350     }
351     return ret;
355 /**
356  * Converts an RGB colour expressed in form 0x00rrggbb to a CSS/SVG representation of that colour.
357  * The result is valid even in SVG Tiny or non-SVG CSS.
358  */
359 static void
360 rgb24_to_css(char *const buf, unsigned const rgb24)
362     assert(rgb24 < (1u << 24));
364     /* SVG 1.1 Full allows additional colour names not supported by SVG Tiny, but we don't bother
365      * with them: it's good for these colours to be copyable to non-SVG CSS stylesheets and for
366      * documents to be more viewable in SVG Tiny/Basic viewers; and some of the SVG Full names are
367      * less meaningful than hex equivalents anyway.  And it's easier for a person to map from the
368      * restricted set because the only component values are {00,80,ff}, other than silver 0xc0c0c0.
369      */
371     char const *src = NULL;
372     switch (rgb24) {
373         /* Extracted mechanically from the table at
374          * http://www.w3.org/TR/REC-html40/types.html#h-6.5 .*/
375         case 0x000000: src = "black"; break;            
376         case 0xc0c0c0: src = "silver"; break;           
377         case 0x808080: src = "gray"; break;             
378         case 0xffffff: src = "white"; break;            
379         case 0x800000: src = "maroon"; break;           
380         case 0xff0000: src = "red"; break;              
381         case 0x800080: src = "purple"; break;           
382         case 0xff00ff: src = "fuchsia"; break;          
383         case 0x008000: src = "green"; break; 
384         case 0x00ff00: src = "lime"; break;  
385         case 0x808000: src = "olive"; break; 
386         case 0xffff00: src = "yellow"; break;
387         case 0x000080: src = "navy"; break;  
388         case 0x0000ff: src = "blue"; break;  
389         case 0x008080: src = "teal"; break;  
390         case 0x00ffff: src = "aqua"; break;  
392         default: {
393             if ((rgb24 & 0xf0f0f) * 0x11 == rgb24) {
394                 /* Can use the shorter three-digit form #rgb instead of #rrggbb. */
395                 sprintf(buf, "#%x%x%x",
396                         (rgb24 >> 16) & 0xf,
397                         (rgb24 >> 8) & 0xf,
398                         rgb24 & 0xf);
399             } else {
400                 sprintf(buf, "#%06x", rgb24);
401             }
402             break;
403         }
404     }
405     if (src) {
406         strcpy(buf, src);
407     }
409     assert(sp_svg_read_color(buf, 0xff) == (rgb24 << 8));
412 /**
413  * Converts an RGBA32 colour to a CSS/SVG representation of the RGB portion of that colour.  The
414  * result is valid even in SVG Tiny or non-SVG CSS.
415  *
416  * \param rgba32 Colour expressed in form 0xrrggbbaa.
417  * \pre buflen \>= 8.
418  */
419 void
420 sp_svg_write_color(gchar *buf, unsigned const buflen, guint32 const rgba32)
422     g_assert(8 <= buflen);
424     unsigned const rgb24 = rgba32 >> 8;
425     rgb24_to_css(buf, rgb24);
428 static GHashTable *
429 sp_svg_create_color_hash()
431     GHashTable *colors = g_hash_table_new(g_str_hash, g_str_equal);
433     for (unsigned i = 0 ; i < G_N_ELEMENTS(sp_svg_color_named) ; i++) {
434         g_hash_table_insert(colors,
435                             (gpointer)(sp_svg_color_named[i].name),
436                             (gpointer)(&sp_svg_color_named[i].rgb));
437     }
439     return colors;
442 /*
443   Local Variables:
444   mode:c++
445   c-file-style:"stroustrup"
446   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
447   indent-tabs-mode:nil
448   fill-column:99
449   End:
450 */
451 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :