Code

From trunk
[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 <cstdlib>
21 #include <cstdio> // sprintf
22 #include <cstring>
23 #include <string>
24 #include <cassert>
25 #include <math.h>
26 #include <glib/gmem.h>
27 #include <glib.h> // g_assert
28 #include <glib/gmessages.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/ghash.h>
31 #include <glib/gutils.h>
32 #include <errno.h>
34 #include "strneq.h"
35 #include "preferences.h"
36 #include "svg-color.h"
37 #include "svg-icc-color.h"
39 using std::sprintf;
41 struct SPSVGColor {
42     unsigned long rgb;
43     char const *name;
44 };
46 /*
47  * These are the colors defined in the SVG standard
48  */
49 static SPSVGColor const sp_svg_color_named[] = {
50     { 0xF0F8FF, "aliceblue" },
51     { 0xFAEBD7, "antiquewhite" },
52     { 0x00FFFF, "aqua" },
53     { 0x7FFFD4, "aquamarine" },
54     { 0xF0FFFF, "azure" },
55     { 0xF5F5DC, "beige" },
56     { 0xFFE4C4, "bisque" },
57     { 0x000000, "black" },
58     { 0xFFEBCD, "blanchedalmond" },
59     { 0x0000FF, "blue" },
60     { 0x8A2BE2, "blueviolet" },
61     { 0xA52A2A, "brown" },
62     { 0xDEB887, "burlywood" },
63     { 0x5F9EA0, "cadetblue" },
64     { 0x7FFF00, "chartreuse" },
65     { 0xD2691E, "chocolate" },
66     { 0xFF7F50, "coral" },
67     { 0x6495ED, "cornflowerblue" },
68     { 0xFFF8DC, "cornsilk" },
69     { 0xDC143C, "crimson" },
70     { 0x00FFFF, "cyan" },
71     { 0x00008B, "darkblue" },
72     { 0x008B8B, "darkcyan" },
73     { 0xB8860B, "darkgoldenrod" },
74     { 0xA9A9A9, "darkgray" },
75     { 0x006400, "darkgreen" },
76     { 0xA9A9A9, "darkgrey" },
77     { 0xBDB76B, "darkkhaki" },
78     { 0x8B008B, "darkmagenta" },
79     { 0x556B2F, "darkolivegreen" },
80     { 0xFF8C00, "darkorange" },
81     { 0x9932CC, "darkorchid" },
82     { 0x8B0000, "darkred" },
83     { 0xE9967A, "darksalmon" },
84     { 0x8FBC8F, "darkseagreen" },
85     { 0x483D8B, "darkslateblue" },
86     { 0x2F4F4F, "darkslategray" },
87     { 0x2F4F4F, "darkslategrey" },
88     { 0x00CED1, "darkturquoise" },
89     { 0x9400D3, "darkviolet" },
90     { 0xFF1493, "deeppink" },
91     { 0x00BFFF, "deepskyblue" },
92     { 0x696969, "dimgray" },
93     { 0x696969, "dimgrey" },
94     { 0x1E90FF, "dodgerblue" },
95     { 0xB22222, "firebrick" },
96     { 0xFFFAF0, "floralwhite" },
97     { 0x228B22, "forestgreen" },
98     { 0xFF00FF, "fuchsia" },
99     { 0xDCDCDC, "gainsboro" },
100     { 0xF8F8FF, "ghostwhite" },
101     { 0xFFD700, "gold" },
102     { 0xDAA520, "goldenrod" },
103     { 0x808080, "gray" },
104     { 0x808080, "grey" },
105     { 0x008000, "green" },
106     { 0xADFF2F, "greenyellow" },
107     { 0xF0FFF0, "honeydew" },
108     { 0xFF69B4, "hotpink" },
109     { 0xCD5C5C, "indianred" },
110     { 0x4B0082, "indigo" },
111     { 0xFFFFF0, "ivory" },
112     { 0xF0E68C, "khaki" },
113     { 0xE6E6FA, "lavender" },
114     { 0xFFF0F5, "lavenderblush" },
115     { 0x7CFC00, "lawngreen" },
116     { 0xFFFACD, "lemonchiffon" },
117     { 0xADD8E6, "lightblue" },
118     { 0xF08080, "lightcoral" },
119     { 0xE0FFFF, "lightcyan" },
120     { 0xFAFAD2, "lightgoldenrodyellow" },
121     { 0xD3D3D3, "lightgray" },
122     { 0x90EE90, "lightgreen" },
123     { 0xD3D3D3, "lightgrey" },
124     { 0xFFB6C1, "lightpink" },
125     { 0xFFA07A, "lightsalmon" },
126     { 0x20B2AA, "lightseagreen" },
127     { 0x87CEFA, "lightskyblue" },
128     { 0x778899, "lightslategray" },
129     { 0x778899, "lightslategrey" },
130     { 0xB0C4DE, "lightsteelblue" },
131     { 0xFFFFE0, "lightyellow" },
132     { 0x00FF00, "lime" },
133     { 0x32CD32, "limegreen" },
134     { 0xFAF0E6, "linen" },
135     { 0xFF00FF, "magenta" },
136     { 0x800000, "maroon" },
137     { 0x66CDAA, "mediumaquamarine" },
138     { 0x0000CD, "mediumblue" },
139     { 0xBA55D3, "mediumorchid" },
140     { 0x9370DB, "mediumpurple" },
141     { 0x3CB371, "mediumseagreen" },
142     { 0x7B68EE, "mediumslateblue" },
143     { 0x00FA9A, "mediumspringgreen" },
144     { 0x48D1CC, "mediumturquoise" },
145     { 0xC71585, "mediumvioletred" },
146     { 0x191970, "midnightblue" },
147     { 0xF5FFFA, "mintcream" },
148     { 0xFFE4E1, "mistyrose" },
149     { 0xFFE4B5, "moccasin" },
150     { 0xFFDEAD, "navajowhite" },
151     { 0x000080, "navy" },
152     { 0xFDF5E6, "oldlace" },
153     { 0x808000, "olive" },
154     { 0x6B8E23, "olivedrab" },
155     { 0xFFA500, "orange" },
156     { 0xFF4500, "orangered" },
157     { 0xDA70D6, "orchid" },
158     { 0xEEE8AA, "palegoldenrod" },
159     { 0x98FB98, "palegreen" },
160     { 0xAFEEEE, "paleturquoise" },
161     { 0xDB7093, "palevioletred" },
162     { 0xFFEFD5, "papayawhip" },
163     { 0xFFDAB9, "peachpuff" },
164     { 0xCD853F, "peru" },
165     { 0xFFC0CB, "pink" },
166     { 0xDDA0DD, "plum" },
167     { 0xB0E0E6, "powderblue" },
168     { 0x800080, "purple" },
169     { 0xFF0000, "red" },
170     { 0xBC8F8F, "rosybrown" },
171     { 0x4169E1, "royalblue" },
172     { 0x8B4513, "saddlebrown" },
173     { 0xFA8072, "salmon" },
174     { 0xF4A460, "sandybrown" },
175     { 0x2E8B57, "seagreen" },
176     { 0xFFF5EE, "seashell" },
177     { 0xA0522D, "sienna" },
178     { 0xC0C0C0, "silver" },
179     { 0x87CEEB, "skyblue" },
180     { 0x6A5ACD, "slateblue" },
181     { 0x708090, "slategray" },
182     { 0x708090, "slategrey" },
183     { 0xFFFAFA, "snow" },
184     { 0x00FF7F, "springgreen" },
185     { 0x4682B4, "steelblue" },
186     { 0xD2B48C, "tan" },
187     { 0x008080, "teal" },
188     { 0xD8BFD8, "thistle" },
189     { 0xFF6347, "tomato" },
190     { 0x40E0D0, "turquoise" },
191     { 0xEE82EE, "violet" },
192     { 0xF5DEB3, "wheat" },
193     { 0xFFFFFF, "white" },
194     { 0xF5F5F5, "whitesmoke" },
195     { 0xFFFF00, "yellow" },
196     { 0x9ACD32, "yellowgreen" }
197 };
199 static GHashTable *sp_svg_create_color_hash();
201 guint32
202 sp_svg_read_color(gchar const *str, guint32 const dfl)
204     return sp_svg_read_color(str, NULL, dfl);
207 static guint32
208 internal_sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 def)
210     static GHashTable *colors = NULL;
211     guint32 val = 0;
213     if (str == NULL) return def;
214     while ((*str <= ' ') && *str) str++;
215     if (!*str) return def;
217     if (str[0] == '#') {
218         gint i;
219         for (i = 1; str[i]; i++) {
220             int hexval;
221             if (str[i] >= '0' && str[i] <= '9')
222                 hexval = str[i] - '0';
223             else if (str[i] >= 'A' && str[i] <= 'F')
224                 hexval = str[i] - 'A' + 10;
225             else if (str[i] >= 'a' && str[i] <= 'f')
226                 hexval = str[i] - 'a' + 10;
227             else
228                 break;
229             val = (val << 4) + hexval;
230         }
231         /* handle #rgb case */
232         if (i == 1 + 3) {
233             val = ((val & 0xf00) << 8) |
234                 ((val & 0x0f0) << 4) |
235                 (val & 0x00f);
236             val |= val << 4;
237         } else if (i != 1 + 6) {
238             /* must be either 3 or 6 digits. */
239             return def;
240         }
241         if (end_ptr) {
242             *end_ptr = str + i;
243         }
244     } else if (strneq(str, "rgb(", 4)) {
245         bool hasp, hasd;
246         gchar *s, *e;
247         gdouble r, g, b;
249         s = (gchar *) str + 4;
250         hasp = false;
251         hasd = false;
253         r = g_ascii_strtod(s, &e);
254         if (s == e) return def;
255         s = e;
256         if (*s == '%') {
257             hasp = true;
258             s += 1;
259         } else {
260             hasd = true;
261         }
262         while (*s && g_ascii_isspace(*s)) s += 1;
263         if (*s != ',') return def;
264         s += 1;
265         while (*s && g_ascii_isspace(*s)) s += 1;
266         g = g_ascii_strtod(s, &e);
267         if (s == e) return def;
268         s = e;
269         if (*s == '%') {
270             hasp = true;
271             s += 1;
272         } else {
273             hasd = true;
274         }
275         while (*s && g_ascii_isspace(*s)) s += 1;
276         if (*s != ',') return def;
277         s += 1;
278         while (*s && g_ascii_isspace(*s)) s += 1;
279         b = g_ascii_strtod(s, &e);
280         if (s == e) return def;
281         s = e;
282         if (*s == '%') {
283             hasp = true;
284             s += 1;
285         } else {
286             hasd = true;
287         }
288         while(*s && g_ascii_isspace(*s)) s += 1;
289         if (*s != ')') {
290             return def;
291         }
292         ++s;
293         if (hasp && hasd) return def;
294         if (hasp) {
295             val = (guint) floor(CLAMP(r, 0.0, 100.0) * 2.559999) << 24;
296             val |= ((guint) floor(CLAMP(g, 0.0, 100.0) * 2.559999) << 16);
297             val |= ((guint) floor(CLAMP(b, 0.0, 100.0) * 2.559999) << 8);
298         } else {
299             val = (guint) CLAMP(r, 0, 255) << 24;
300             val |= ((guint) CLAMP(g, 0, 255) << 16);
301             val |= ((guint) CLAMP(b, 0, 255) << 8);
302         }
303         if (end_ptr) {
304             *end_ptr = s;
305         }
306         return val;
307     } else {
308         gint i;
309         if (!colors) {
310             colors = sp_svg_create_color_hash();
311         }
312         gchar c[32];
313         for (i = 0; i < 31; i++) {
314             if (str[i] == ';' || g_ascii_isspace(str[i])) {
315                 c[i] = '\0';
316                 break;
317             }
318             c[i] = g_ascii_tolower(str[i]);
319             if (!str[i]) break;
320         }
321         c[31] = '\0';
323         gpointer const rgb_ptr = g_hash_table_lookup(colors, c);
324         if (rgb_ptr) {
325             val = *(static_cast<unsigned long *>(rgb_ptr));
326         } else {
327             return def;
328         }
329         if (end_ptr) {
330             *end_ptr = str + i;
331         }
332     }
334     return (val << 8);
337 guint32
338 sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 dfl)
340     /* I've been rather hurried in editing the above to add support for end_ptr, so I'm adding
341      * this check wrapper. */
342     gchar const *end = str;
343     guint32 const ret = internal_sp_svg_read_color(str, &end, dfl);
344     assert(ret == dfl && end == str
345            || (((ret & 0xff) == 0)
346                && str < end));
347     if (str < end) {
348         gchar *buf = (gchar *) g_malloc(end + 1 - str);
349         memcpy(buf, str, end - str);
350         buf[end - str] = '\0';
351         gchar const *buf_end = buf;
352         guint32 const check = internal_sp_svg_read_color(buf, &buf_end, 1);
353         assert(check == ret
354                && buf_end - buf == end - str);
355         g_free(buf);
357         if ( end_ptr ) {
358             *end_ptr = end;
359         }
360     }
361     return ret;
365 /**
366  * Converts an RGB colour expressed in form 0x00rrggbb to a CSS/SVG representation of that colour.
367  * The result is valid even in SVG Tiny or non-SVG CSS.
368  */
369 static void
370 rgb24_to_css(char *const buf, unsigned const rgb24)
372     assert(rgb24 < (1u << 24));
374     /* SVG 1.1 Full allows additional colour names not supported by SVG Tiny, but we don't bother
375      * with them: it's good for these colours to be copyable to non-SVG CSS stylesheets and for
376      * documents to be more viewable in SVG Tiny/Basic viewers; and some of the SVG Full names are
377      * less meaningful than hex equivalents anyway.  And it's easier for a person to map from the
378      * restricted set because the only component values are {00,80,ff}, other than silver 0xc0c0c0.
379      */
381     char const *src = NULL;
382     switch (rgb24) {
383         /* Extracted mechanically from the table at
384          * http://www.w3.org/TR/REC-html40/types.html#h-6.5 .*/
385         case 0x000000: src = "black"; break;            
386         case 0xc0c0c0: src = "silver"; break;           
387         case 0x808080: src = "gray"; break;             
388         case 0xffffff: src = "white"; break;            
389         case 0x800000: src = "maroon"; break;           
390         case 0xff0000: src = "red"; break;              
391         case 0x800080: src = "purple"; break;           
392         case 0xff00ff: src = "fuchsia"; break;          
393         case 0x008000: src = "green"; break; 
394         case 0x00ff00: src = "lime"; break;  
395         case 0x808000: src = "olive"; break; 
396         case 0xffff00: src = "yellow"; break;
397         case 0x000080: src = "navy"; break;  
398         case 0x0000ff: src = "blue"; break;  
399         case 0x008080: src = "teal"; break;  
400         case 0x00ffff: src = "aqua"; break;  
402         default: {
403             if ((rgb24 & 0xf0f0f) * 0x11 == rgb24) {
404                 /* Can use the shorter three-digit form #rgb instead of #rrggbb. */
405                 sprintf(buf, "#%x%x%x",
406                         (rgb24 >> 16) & 0xf,
407                         (rgb24 >> 8) & 0xf,
408                         rgb24 & 0xf);
409             } else {
410                 sprintf(buf, "#%06x", rgb24);
411             }
412             break;
413         }
414     }
415     if (src) {
416         strcpy(buf, src);
417     }
419     // assert(sp_svg_read_color(buf, 0xff) == (rgb24 << 8));
422 /**
423  * Converts an RGBA32 colour to a CSS/SVG representation of the RGB portion of that colour.  The
424  * result is valid even in SVG Tiny or non-SVG CSS.
425  *
426  * \param rgba32 Colour expressed in form 0xrrggbbaa.
427  * \pre buflen \>= 8.
428  */
429 void
430 sp_svg_write_color(gchar *buf, unsigned const buflen, guint32 const rgba32)
432     g_assert(8 <= buflen);
434     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
435     unsigned const rgb24 = rgba32 >> 8;
436     if (prefs->getBool("/options/svgoutput/usenamedcolors")) {
437         rgb24_to_css(buf, rgb24);
438     } else {
439         g_snprintf(buf, buflen, "#%06x", rgb24);
440     }
443 static GHashTable *
444 sp_svg_create_color_hash()
446     GHashTable *colors = g_hash_table_new(g_str_hash, g_str_equal);
448     for (unsigned i = 0 ; i < G_N_ELEMENTS(sp_svg_color_named) ; i++) {
449         g_hash_table_insert(colors,
450                             (gpointer)(sp_svg_color_named[i].name),
451                             (gpointer)(&sp_svg_color_named[i].rgb));
452     }
454     return colors;
458 bool sp_svg_read_icc_color( gchar const *str, gchar const **end_ptr, SVGICCColor* dest )
460     bool good = true;
462     if ( end_ptr ) {
463         *end_ptr = str;
464     }
465     if ( dest ) {
466         dest->colorProfile.clear();
467         dest->colors.clear();
468     }
470     if ( !str ) {
471         // invalid input
472         good = false;
473     } else {
474         while ( g_ascii_isspace(*str) ) {
475             str++;
476         }
478         good = strneq( str, "icc-color(", 10 );
480         if ( good ) {
481             str += 10;
482             while ( g_ascii_isspace(*str) ) {
483                 str++;
484             }
486             if ( !g_ascii_isalpha(*str)
487                  && ( !(0x080 & *str) ) ) {
488                 // Name must start with a certain type of character
489                 good = false;
490             } else {
491                 while ( g_ascii_isdigit(*str) || g_ascii_isalpha(*str) || (*str == '-') ) {
492                     if ( dest ) {
493                         dest->colorProfile += *str;
494                     }
495                     str++;
496                 }
497                 while ( g_ascii_isspace(*str) || *str == ',' ) {
498                     str++;
499                 }
500             }
501         }
503         if ( good ) {
504             while ( *str && *str != ')' ) {
505                 if ( g_ascii_isdigit(*str) || *str == '.' || *str == '-' || *str == '+') {
506                     gchar* endPtr = 0;
507                     gdouble dbl = g_ascii_strtod( str, &endPtr );
508                     if ( !errno ) {
509                         if ( dest ) {
510                             dest->colors.push_back( dbl );
511                         }
512                         str = endPtr;
513                     } else {
514                         good = false;
515                         break;
516                     }
518                     while ( g_ascii_isspace(*str) || *str == ',' ) {
519                         str++;
520                     }
521                 } else {
522                     break;
523                 }
524             }
525         }
527         // We need to have ended on a closing parenthesis
528         if ( good ) {
529             while ( g_ascii_isspace(*str) ) {
530                 str++;
531             }
532             good &= *str == ')';
533         }
534     }
536     if ( good ) {
537         if ( end_ptr ) {
538             *end_ptr = str;
539         }
540     } else {
541         if ( dest ) {
542             dest->colorProfile.clear();
543             dest->colors.clear();
544         }
545     }
547     return good;
550 /*
551   Local Variables:
552   mode:c++
553   c-file-style:"stroustrup"
554   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
555   indent-tabs-mode:nil
556   fill-column:99
557   End:
558 */
559 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :