Code

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