Code

SPDocument->Document
[inkscape.git] / src / style.cpp
1 #define __SP_STYLE_C__
3 /** @file
4  * @brief SVG stylesheets implementation.
5  */
6 /* Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Peter Moulder <pmoulder@mail.csse.monash.edu.au>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 2001-2002 Lauris Kaplinski
12  * Copyright (C) 2001 Ximian, Inc.
13  * Copyright (C) 2005 Monash University
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
22 #include <cstring>
23 #include <string>
25 #include "libcroco/cr-sel-eng.h"
26 #include "xml/croco-node-iface.h"
28 #include "svg/svg.h"
29 #include "svg/svg-color.h"
30 #include "svg/svg-icc-color.h"
32 #include "display/canvas-bpath.h"
33 #include "attributes.h"
34 #include "document.h"
35 #include "extract-uri.h"
36 #include "uri-references.h"
37 #include "uri.h"
38 #include "sp-paint-server.h"
39 #include "streq.h"
40 #include "strneq.h"
41 #include "style.h"
42 #include "svg/css-ostringstream.h"
43 #include "xml/repr.h"
44 #include "xml/simple-document.h"
45 #include "unit-constants.h"
46 #include "2geom/isnan.h"
47 #include "macros.h"
48 #include "preferences.h"
50 #include "sp-filter-reference.h"
52 #include <sigc++/functors/ptr_fun.h>
53 #include <sigc++/adaptors/bind.h>
55 using Inkscape::CSSOStringStream;
56 using std::vector;
58 #define BMAX 8192
60 class SPStyleEnum;
62 /*#########################
63 ## FORWARD DECLARATIONS
64 #########################*/
65 static void sp_style_clear(SPStyle *style);
67 static void sp_style_merge_property(SPStyle *style, gint id, gchar const *val);
69 static void sp_style_merge_ipaint(SPStyle *style, SPIPaint *paint, SPIPaint const *parent);
70 static void sp_style_merge_ifilter(SPStyle *style, SPIFilter const *parent);
71 static void sp_style_read_dash(SPStyle *style, gchar const *str);
73 static SPTextStyle *sp_text_style_new(void);
74 static void sp_text_style_clear(SPTextStyle *ts);
75 static SPTextStyle *sp_text_style_unref(SPTextStyle *st);
76 static SPTextStyle *sp_text_style_duplicate_unset(SPTextStyle *st);
77 static guint sp_text_style_write(gchar *p, guint len, SPTextStyle const *st, guint flags = SP_STYLE_FLAG_IFSET);
78 static void sp_style_privatize_text(SPStyle *style);
80 static void sp_style_read_ifloat(SPIFloat *val, gchar const *str);
81 static void sp_style_read_iscale24(SPIScale24 *val, gchar const *str);
82 static void sp_style_read_ienum(SPIEnum *val, gchar const *str, SPStyleEnum const *dict, bool can_explicitly_inherit);
83 static void sp_style_read_istring(SPIString *val, gchar const *str);
84 static void sp_style_read_ilength(SPILength *val, gchar const *str);
85 static void sp_style_read_ilengthornormal(SPILengthOrNormal *val, gchar const *str);
86 static void sp_style_read_itextdecoration(SPITextDecoration *val, gchar const *str);
87 static void sp_style_read_icolor(SPIPaint *paint, gchar const *str, SPStyle *style, Document *document);
88 static void sp_style_read_ipaint(SPIPaint *paint, gchar const *str, SPStyle *style, Document *document);
89 static void sp_style_read_ifontsize(SPIFontSize *val, gchar const *str);
90 static void sp_style_read_ifilter(gchar const *str, SPStyle *style, Document *document);
92 static void sp_style_read_penum(SPIEnum *val, Inkscape::XML::Node *repr, gchar const *key, SPStyleEnum const *dict, bool can_explicitly_inherit);
93 static void sp_style_read_plength(SPILength *val, Inkscape::XML::Node *repr, gchar const *key);
94 static void sp_style_read_pfontsize(SPIFontSize *val, Inkscape::XML::Node *repr, gchar const *key);
95 static void sp_style_read_pfloat(SPIFloat *val, Inkscape::XML::Node *repr, gchar const *key);
97 static gint sp_style_write_ifloat(gchar *p, gint len, gchar const *key, SPIFloat const *val, SPIFloat const *base, guint flags);
98 static gint sp_style_write_iscale24(gchar *p, gint len, gchar const *key, SPIScale24 const *val, SPIScale24 const *base, guint flags);
99 static gint sp_style_write_ienum(gchar *p, gint len, gchar const *key, SPStyleEnum const *dict, SPIEnum const *val, SPIEnum const *base, guint flags);
100 static gint sp_style_write_istring(gchar *p, gint len, gchar const *key, SPIString const *val, SPIString const *base, guint flags);
101 static gint sp_style_write_ilength(gchar *p, gint len, gchar const *key, SPILength const *val, SPILength const *base, guint flags);
102 static gint sp_style_write_ipaint(gchar *b, gint len, gchar const *key, SPIPaint const *paint, SPIPaint const *base, guint flags);
103 static gint sp_style_write_ifontsize(gchar *p, gint len, gchar const *key, SPIFontSize const *val, SPIFontSize const *base, guint flags);
104 static gint sp_style_write_ilengthornormal(gchar *p, gint const len, gchar const *const key, SPILengthOrNormal const *const val, SPILengthOrNormal const *const base, guint const flags);
105 static gint sp_style_write_itextdecoration(gchar *p, gint const len, gchar const *const key, SPITextDecoration const *const val, SPITextDecoration const *const base, guint const flags);
106 static gint sp_style_write_ifilter(gchar *b, gint len, gchar const *key, SPIFilter const *filter, SPIFilter const *base, guint flags);
108 static void sp_style_filter_clear(SPStyle *style);
110 #define SPS_READ_IENUM_IF_UNSET(v,s,d,i) if (!(v)->set) {sp_style_read_ienum((v), (s), (d), (i));}
111 #define SPS_READ_PENUM_IF_UNSET(v,r,k,d,i) if (!(v)->set) {sp_style_read_penum((v), (r), (k), (d), (i));}
113 #define SPS_READ_ILENGTH_IF_UNSET(v,s) if (!(v)->set) {sp_style_read_ilength((v), (s));}
114 #define SPS_READ_PLENGTH_IF_UNSET(v,r,k) if (!(v)->set) {sp_style_read_plength((v), (r), (k));}
116 #define SPS_READ_PFLOAT_IF_UNSET(v,r,k) if (!(v)->set) {sp_style_read_pfloat((v), (r), (k));}
118 #define SPS_READ_IFONTSIZE_IF_UNSET(v,s) if (!(v)->set) {sp_style_read_ifontsize((v), (s));}
119 #define SPS_READ_PFONTSIZE_IF_UNSET(v,r,k) if (!(v)->set) {sp_style_read_pfontsize((v), (r), (k));}
121 static void sp_style_merge_from_object_stylesheet(SPStyle *, SPObject const *);
123 struct SPStyleEnum {
124     gchar const *key;
125     gint value;
126 };
128 static SPStyleEnum const enum_fill_rule[] = {
129     {"nonzero", SP_WIND_RULE_NONZERO},
130     {"evenodd", SP_WIND_RULE_EVENODD},
131     {NULL, -1}
132 };
134 static SPStyleEnum const enum_stroke_linecap[] = {
135     {"butt", SP_STROKE_LINECAP_BUTT},
136     {"round", SP_STROKE_LINECAP_ROUND},
137     {"square", SP_STROKE_LINECAP_SQUARE},
138     {NULL, -1}
139 };
141 static SPStyleEnum const enum_stroke_linejoin[] = {
142     {"miter", SP_STROKE_LINEJOIN_MITER},
143     {"round", SP_STROKE_LINEJOIN_ROUND},
144     {"bevel", SP_STROKE_LINEJOIN_BEVEL},
145     {NULL, -1}
146 };
148 static SPStyleEnum const enum_font_style[] = {
149     {"normal", SP_CSS_FONT_STYLE_NORMAL},
150     {"italic", SP_CSS_FONT_STYLE_ITALIC},
151     {"oblique", SP_CSS_FONT_STYLE_OBLIQUE},
152     {NULL, -1}
153 };
155 static SPStyleEnum const enum_font_size[] = {
156     {"xx-small", SP_CSS_FONT_SIZE_XX_SMALL},
157     {"x-small", SP_CSS_FONT_SIZE_X_SMALL},
158     {"small", SP_CSS_FONT_SIZE_SMALL},
159     {"medium", SP_CSS_FONT_SIZE_MEDIUM},
160     {"large", SP_CSS_FONT_SIZE_LARGE},
161     {"x-large", SP_CSS_FONT_SIZE_X_LARGE},
162     {"xx-large", SP_CSS_FONT_SIZE_XX_LARGE},
163     {"smaller", SP_CSS_FONT_SIZE_SMALLER},
164     {"larger", SP_CSS_FONT_SIZE_LARGER},
165     {NULL, -1}
166 };
168 static SPStyleEnum const enum_font_variant[] = {
169     {"normal", SP_CSS_FONT_VARIANT_NORMAL},
170     {"small-caps", SP_CSS_FONT_VARIANT_SMALL_CAPS},
171     {NULL, -1}
172 };
174 static SPStyleEnum const enum_font_weight[] = {
175     {"100", SP_CSS_FONT_WEIGHT_100},
176     {"200", SP_CSS_FONT_WEIGHT_200},
177     {"300", SP_CSS_FONT_WEIGHT_300},
178     {"400", SP_CSS_FONT_WEIGHT_400},
179     {"500", SP_CSS_FONT_WEIGHT_500},
180     {"600", SP_CSS_FONT_WEIGHT_600},
181     {"700", SP_CSS_FONT_WEIGHT_700},
182     {"800", SP_CSS_FONT_WEIGHT_800},
183     {"900", SP_CSS_FONT_WEIGHT_900},
184     {"normal", SP_CSS_FONT_WEIGHT_NORMAL},
185     {"bold", SP_CSS_FONT_WEIGHT_BOLD},
186     {"lighter", SP_CSS_FONT_WEIGHT_LIGHTER},
187     {"bolder", SP_CSS_FONT_WEIGHT_BOLDER},
188     {NULL, -1}
189 };
191 static SPStyleEnum const enum_font_stretch[] = {
192     {"ultra-condensed", SP_CSS_FONT_STRETCH_ULTRA_CONDENSED},
193     {"extra-condensed", SP_CSS_FONT_STRETCH_EXTRA_CONDENSED},
194     {"condensed", SP_CSS_FONT_STRETCH_CONDENSED},
195     {"semi-condensed", SP_CSS_FONT_STRETCH_SEMI_CONDENSED},
196     {"normal", SP_CSS_FONT_STRETCH_NORMAL},
197     {"semi-expanded", SP_CSS_FONT_STRETCH_SEMI_EXPANDED},
198     {"expanded", SP_CSS_FONT_STRETCH_EXPANDED},
199     {"extra-expanded", SP_CSS_FONT_STRETCH_EXTRA_EXPANDED},
200     {"ultra-expanded", SP_CSS_FONT_STRETCH_ULTRA_EXPANDED},
201     {"narrower", SP_CSS_FONT_STRETCH_NARROWER},
202     {"wider", SP_CSS_FONT_STRETCH_WIDER},
203     {NULL, -1}
204 };
206 static SPStyleEnum const enum_text_align[] = {
207     {"start", SP_CSS_TEXT_ALIGN_START},
208     {"end", SP_CSS_TEXT_ALIGN_END},
209     {"left", SP_CSS_TEXT_ALIGN_LEFT},
210     {"right", SP_CSS_TEXT_ALIGN_RIGHT},
211     {"center", SP_CSS_TEXT_ALIGN_CENTER},
212     {"justify", SP_CSS_TEXT_ALIGN_JUSTIFY},
213     {NULL, -1}
214 };
216 static SPStyleEnum const enum_text_transform[] = {
217     {"capitalize", SP_CSS_TEXT_TRANSFORM_CAPITALIZE},
218     {"uppercase", SP_CSS_TEXT_TRANSFORM_UPPERCASE},
219     {"lowercase", SP_CSS_TEXT_TRANSFORM_LOWERCASE},
220     {"none", SP_CSS_TEXT_TRANSFORM_NONE},
221     {NULL, -1}
222 };
224 static SPStyleEnum const enum_text_anchor[] = {
225     {"start", SP_CSS_TEXT_ANCHOR_START},
226     {"middle", SP_CSS_TEXT_ANCHOR_MIDDLE},
227     {"end", SP_CSS_TEXT_ANCHOR_END},
228     {NULL, -1}
229 };
231 static SPStyleEnum const enum_direction[] = {
232     {"ltr", SP_CSS_DIRECTION_LTR},
233     {"rtl", SP_CSS_DIRECTION_RTL},
234     {NULL, -1}
235 };
237 static SPStyleEnum const enum_block_progression[] = {
238     {"tb", SP_CSS_BLOCK_PROGRESSION_TB},
239     {"rl", SP_CSS_BLOCK_PROGRESSION_RL},
240     {"lr", SP_CSS_BLOCK_PROGRESSION_LR},
241     {NULL, -1}
242 };
244 static SPStyleEnum const enum_writing_mode[] = {
245     /* Note that using the same enumerator for lr as lr-tb means we write as lr-tb even if the
246      * input file said lr.  We prefer writing lr-tb on the grounds that the spec says the initial
247      * value is lr-tb rather than lr.
248      *
249      * ECMA scripts may be surprised to find tb-rl in DOM if they set the attribute to rl, so
250      * sharing enumerators for different strings may be a bug (once we support ecma script).
251      */
252     {"lr-tb", SP_CSS_WRITING_MODE_LR_TB},
253     {"rl-tb", SP_CSS_WRITING_MODE_RL_TB},
254     {"tb-rl", SP_CSS_WRITING_MODE_TB_RL},
255     {"lr", SP_CSS_WRITING_MODE_LR_TB},
256     {"rl", SP_CSS_WRITING_MODE_RL_TB},
257     {"tb", SP_CSS_WRITING_MODE_TB_RL},
258     {NULL, -1}
259 };
261 static SPStyleEnum const enum_visibility[] = {
262     {"hidden", SP_CSS_VISIBILITY_HIDDEN},
263     {"collapse", SP_CSS_VISIBILITY_COLLAPSE},
264     {"visible", SP_CSS_VISIBILITY_VISIBLE},
265     {NULL, -1}
266 };
268 static SPStyleEnum const enum_overflow[] = {
269     {"visible", SP_CSS_OVERFLOW_VISIBLE},
270     {"hidden", SP_CSS_OVERFLOW_HIDDEN},
271     {"scroll", SP_CSS_OVERFLOW_SCROLL},
272     {"auto", SP_CSS_OVERFLOW_AUTO},
273     {NULL, -1}
274 };
276 static SPStyleEnum const enum_display[] = {
277     {"none",      SP_CSS_DISPLAY_NONE},
278     {"inline",    SP_CSS_DISPLAY_INLINE},
279     {"block",     SP_CSS_DISPLAY_BLOCK},
280     {"list-item", SP_CSS_DISPLAY_LIST_ITEM},
281     {"run-in",    SP_CSS_DISPLAY_RUN_IN},
282     {"compact",   SP_CSS_DISPLAY_COMPACT},
283     {"marker",    SP_CSS_DISPLAY_MARKER},
284     {"table",     SP_CSS_DISPLAY_TABLE},
285     {"inline-table",  SP_CSS_DISPLAY_INLINE_TABLE},
286     {"table-row-group",    SP_CSS_DISPLAY_TABLE_ROW_GROUP},
287     {"table-header-group", SP_CSS_DISPLAY_TABLE_HEADER_GROUP},
288     {"table-footer-group", SP_CSS_DISPLAY_TABLE_FOOTER_GROUP},
289     {"table-row",     SP_CSS_DISPLAY_TABLE_ROW},
290     {"table-column-group", SP_CSS_DISPLAY_TABLE_COLUMN_GROUP},
291     {"table-column",  SP_CSS_DISPLAY_TABLE_COLUMN},
292     {"table-cell",    SP_CSS_DISPLAY_TABLE_CELL},
293     {"table-caption", SP_CSS_DISPLAY_TABLE_CAPTION},
294     {NULL, -1}
295 };
297 static SPStyleEnum const enum_shape_rendering[] = {
298     {"auto", 0},
299     {"optimizeSpeed", 0},
300     {"crispEdges", 0},
301     {"geometricPrecision", 0},
302     {NULL, -1}
303 };
305 static SPStyleEnum const enum_color_rendering[] = {
306     {"auto", 0},
307     {"optimizeSpeed", 0},
308     {"optimizeQuality", 0},
309     {NULL, -1}
310 };
312 static SPStyleEnum const *const enum_image_rendering = enum_color_rendering;
314 static SPStyleEnum const enum_text_rendering[] = {
315     {"auto", 0},
316     {"optimizeSpeed", 0},
317     {"optimizeLegibility", 0},
318     {"geometricPrecision", 0},
319     {NULL, -1}
320 };
322 static SPStyleEnum const enum_enable_background[] = {
323     {"accumulate", SP_CSS_BACKGROUND_ACCUMULATE},
324     {"new", SP_CSS_BACKGROUND_NEW},
325     {NULL, -1}
326 };
328 /**
329  * Release callback.
330  */
331 static void
332 sp_style_object_release(SPObject *object, SPStyle *style)
334     (void)object; // TODO
335     style->object = NULL;
338 /**
339  * Emit style modified signal on style's object if the filter changed.
340  */
341 static void
342 sp_style_filter_ref_modified(SPObject *obj, guint flags, SPStyle *style)
344     (void)flags; // TODO
345     SPFilter *filter=static_cast<SPFilter *>(obj);
346     if (style->getFilter() == filter)
347     {
348         if (style->object) {
349             style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
350         }
351     }
354 /**
355  * Gets called when the filter is (re)attached to the style
356  */
357 static void
358 sp_style_filter_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style)
360     if (old_ref) {
361         style->filter_modified_connection.disconnect();
362     }
363     if ( SP_IS_FILTER(ref))
364     {
365         style->filter_modified_connection = 
366            ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_filter_ref_modified), style));
367     }
369     sp_style_filter_ref_modified(ref, 0, style);
372 /**
373  * Emit style modified signal on style's object if server is style's fill
374  * or stroke paint server.
375  */
376 static void
377 sp_style_paint_server_ref_modified(SPObject *obj, guint flags, SPStyle *style)
379     (void)flags; // TODO
380     SPPaintServer *server = static_cast<SPPaintServer *>(obj);
382     if ((style->fill.isPaintserver())
383         && style->getFillPaintServer() == server)
384     {
385         if (style->object) {
386             /** \todo
387              * fixme: I do not know, whether it is optimal - we are
388              * forcing reread of everything (Lauris)
389              */
390             /** \todo
391              * fixme: We have to use object_modified flag, because parent
392              * flag is only available downstreams.
393              */
394             style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
395         }
396     } else if ((style->stroke.isPaintserver())
397         && style->getStrokePaintServer() == server)
398     {
399         if (style->object) {
400             /// \todo fixme:
401             style->object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
402         }
403     } else if (server) {
404         g_assert_not_reached();
405     }
408 /**
409  * Gets called when the paintserver is (re)attached to the style
410  */
411 static void
412 sp_style_fill_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style)
414     if (old_ref) {
415         style->fill_ps_modified_connection.disconnect();
416     }
417     if (SP_IS_PAINT_SERVER(ref)) {
418         style->fill_ps_modified_connection = 
419            ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style));
420     }
422     sp_style_paint_server_ref_modified(ref, 0, style);
425 /**
426  * Gets called when the paintserver is (re)attached to the style
427  */
428 static void
429 sp_style_stroke_paint_server_ref_changed(SPObject *old_ref, SPObject *ref, SPStyle *style)
431     if (old_ref) {
432         style->stroke_ps_modified_connection.disconnect();
433     }
434     if (SP_IS_PAINT_SERVER(ref)) {
435         style->stroke_ps_modified_connection = 
436           ref->connectModified(sigc::bind(sigc::ptr_fun(&sp_style_paint_server_ref_modified), style));
437     }
439     sp_style_paint_server_ref_modified(ref, 0, style);
442 /**
443  * Returns a new SPStyle object with settings as per sp_style_clear().
444  */
445 SPStyle *
446 sp_style_new(Document *document)
448     SPStyle *const style = g_new0(SPStyle, 1);
450     style->refcount = 1;
451     style->object = NULL;
452     style->document = document;
453     style->text = sp_text_style_new();
454     style->text_private = TRUE;
456     sp_style_clear(style);
458     style->cloned = false;
460     new (&style->release_connection) sigc::connection();
461     new (&style->filter_modified_connection) sigc::connection();
462     new (&style->fill_ps_modified_connection) sigc::connection();
463     new (&style->stroke_ps_modified_connection) sigc::connection();
465     return style;
469 /**
470  * Creates a new SPStyle object, and attaches it to the specified SPObject.
471  */
472 SPStyle *
473 sp_style_new_from_object(SPObject *object)
475     g_return_val_if_fail(object != NULL, NULL);
476     g_return_val_if_fail(SP_IS_OBJECT(object), NULL);
478     SPStyle *style = sp_style_new(SP_OBJECT_DOCUMENT(object));
479     style->object = object;
480     style->release_connection = object->connectRelease(sigc::bind<1>(sigc::ptr_fun(&sp_style_object_release), style));
482     if (object && SP_OBJECT_IS_CLONED(object)) {
483         style->cloned = true;
484     }
486     return style;
490 /**
491  * Increase refcount of style.
492  */
493 SPStyle *
494 sp_style_ref(SPStyle *style)
496     g_return_val_if_fail(style != NULL, NULL);
497     g_return_val_if_fail(style->refcount > 0, NULL);
499     style->refcount += 1;
501     return style;
505 /**
506  * Decrease refcount of style with possible destruction.
507  */
508 SPStyle *
509 sp_style_unref(SPStyle *style)
511     g_return_val_if_fail(style != NULL, NULL);
512     g_return_val_if_fail(style->refcount > 0, NULL);
514     style->refcount -= 1;
516     if (style->refcount < 1) {
517         style->release_connection.disconnect();
518         style->release_connection.~connection();
519         if (style->text) sp_text_style_unref(style->text);
521          if (style->fill.value.href) {
522              style->fill_ps_modified_connection.disconnect();
523              delete style->fill.value.href;
524              style->fill.value.href = NULL;
525          }
526          if (style->stroke.value.href) {
527              style->stroke_ps_modified_connection.disconnect();
528              delete style->stroke.value.href;
529              style->stroke.value.href = NULL;
530          }
531          if (style->filter.href) {
532              style->filter_modified_connection.disconnect();
533              delete style->filter.href;
534              style->filter.href = NULL;
535          }
537         style->filter_modified_connection.~connection();
538         style->fill_ps_modified_connection.~connection();
539         style->stroke_ps_modified_connection.~connection();
541         style->fill.clear();
542         style->stroke.clear();
543         sp_style_filter_clear(style);
545         g_free(style->stroke_dash.dash);
546         g_free(style);
547     }
549     return NULL;
552 /**
553  *  Reads the various style parameters for an object from repr.
554  */
555 static void
556 sp_style_read(SPStyle *style, SPObject *object, Inkscape::XML::Node *repr)
558     g_assert(style != NULL);
559     g_assert(repr != NULL);
560     g_assert(!object || (SP_OBJECT_REPR(object) == repr));
562     sp_style_clear(style);
564     if (object && SP_OBJECT_IS_CLONED(object)) {
565         style->cloned = true;
566     }
568     /* 1. Style attribute */
569     gchar const *val = repr->attribute("style");
570     if (val != NULL) {
571         sp_style_merge_from_style_string(style, val);
572     }
574     if (object) {
575         sp_style_merge_from_object_stylesheet(style, object);
576     } else {
577         /** \todo No stylesheet information. Find out under what circumstances
578          * this occurs, and handle accordingly.  (If we really wanted to, we
579          * could probably get stylesheets by going through repr->doc.)
580          */
581     }
583     /* 2. Presentation attributes */
584     /* CSS2 */
585     SPS_READ_PENUM_IF_UNSET(&style->visibility, repr, "visibility", enum_visibility, true);
586     SPS_READ_PENUM_IF_UNSET(&style->display, repr, "display", enum_display, true);
587     SPS_READ_PENUM_IF_UNSET(&style->overflow, repr, "overflow", enum_overflow, true);
588     /* Font */
589     SPS_READ_PFONTSIZE_IF_UNSET(&style->font_size, repr, "font-size");
590     SPS_READ_PENUM_IF_UNSET(&style->font_style, repr, "font-style", enum_font_style, true);
591     SPS_READ_PENUM_IF_UNSET(&style->font_variant, repr, "font-variant", enum_font_variant, true);
592     SPS_READ_PENUM_IF_UNSET(&style->font_weight, repr, "font-weight", enum_font_weight, true);
593     SPS_READ_PENUM_IF_UNSET(&style->font_stretch, repr, "font-stretch", enum_font_stretch, true);
594     /* Text (css2 chapter 16) */
595     SPS_READ_PLENGTH_IF_UNSET(&style->text_indent, repr, "text-indent");
596     SPS_READ_PENUM_IF_UNSET(&style->text_align, repr, "text-align", enum_text_align, true);
597     if (!style->text_decoration.set) {
598         val = repr->attribute("text-decoration");
599         if (val) {
600             sp_style_read_itextdecoration(&style->text_decoration, val);
601         }
602     }
603     if (!style->line_height.set) {
604         val = repr->attribute("line-height");
605         if (val) {
606             sp_style_read_ilengthornormal(&style->line_height, val);
607         }
608     }
609     if (!style->letter_spacing.set) {
610         val = repr->attribute("letter-spacing");
611         if (val) {
612             sp_style_read_ilengthornormal(&style->letter_spacing, val);
613         }
614     }
615     if (!style->word_spacing.set) {
616         val = repr->attribute("word-spacing");
617         if (val) {
618             sp_style_read_ilengthornormal(&style->word_spacing, val);
619         }
620     }
621     SPS_READ_PENUM_IF_UNSET(&style->text_transform, repr, "text-transform", enum_text_transform, true);
622     SPS_READ_PENUM_IF_UNSET(&style->direction, repr, "direction", enum_direction, true);
623     SPS_READ_PENUM_IF_UNSET(&style->block_progression, repr, "block_progression", enum_block_progression, true);
625     /* SVG */
626     SPS_READ_PENUM_IF_UNSET(&style->writing_mode, repr, "writing-mode",
627                             enum_writing_mode, true);
628     SPS_READ_PENUM_IF_UNSET(&style->text_anchor, repr, "text-anchor",
629                             enum_text_anchor, true);
631     /* opacity */
632     if (!style->opacity.set) {
633         val = repr->attribute("opacity");
634         if (val) {
635             sp_style_read_iscale24(&style->opacity, val);
636         }
637     }
638     /* color */
639     if (!style->color.set) {
640         val = repr->attribute("color");
641         if (val) {
642             sp_style_read_icolor(&style->color, val, style, ( object
643                                                               ? SP_OBJECT_DOCUMENT(object)
644                                                               : NULL ));
645         }
646     }
647     /* fill */
648     if (!style->fill.set) {
649         val = repr->attribute("fill");
650         if (val) {
651             sp_style_read_ipaint(&style->fill, val, style, (object) ? SP_OBJECT_DOCUMENT(object) : NULL);
652         }
653     }
654     /* fill-opacity */
655     if (!style->fill_opacity.set) {
656         val = repr->attribute("fill-opacity");
657         if (val) {
658             sp_style_read_iscale24(&style->fill_opacity, val);
659         }
660     }
661     /* fill-rule */
662     SPS_READ_PENUM_IF_UNSET(&style->fill_rule, repr, "fill-rule", enum_fill_rule, true);
663     /* stroke */
664     if (!style->stroke.set) {
665         val = repr->attribute("stroke");
666         if (val) {
667             sp_style_read_ipaint(&style->stroke, val, style, (object) ? SP_OBJECT_DOCUMENT(object) : NULL);
668         }
669     }
670     SPS_READ_PLENGTH_IF_UNSET(&style->stroke_width, repr, "stroke-width");
671     SPS_READ_PENUM_IF_UNSET(&style->stroke_linecap, repr, "stroke-linecap", enum_stroke_linecap, true);
672     SPS_READ_PENUM_IF_UNSET(&style->stroke_linejoin, repr, "stroke-linejoin", enum_stroke_linejoin, true);
673     SPS_READ_PFLOAT_IF_UNSET(&style->stroke_miterlimit, repr, "stroke-miterlimit");
675     /* markers */
676     if (!style->marker[SP_MARKER_LOC].set) {
677         val = repr->attribute("marker");
678         if (val) {
679             sp_style_read_istring(&style->marker[SP_MARKER_LOC], val);
680         }
681     }
682     if (!style->marker[SP_MARKER_LOC_START].set) {
683         val = repr->attribute("marker-start");
684         if (val) {
685             sp_style_read_istring(&style->marker[SP_MARKER_LOC_START], val);
686         }
687     }
688     if (!style->marker[SP_MARKER_LOC_MID].set) {
689         val = repr->attribute("marker-mid");
690         if (val) {
691             sp_style_read_istring(&style->marker[SP_MARKER_LOC_MID], val);
692         }
693     }
694     if (!style->marker[SP_MARKER_LOC_END].set) {
695         val = repr->attribute("marker-end");
696         if (val) {
697             sp_style_read_istring(&style->marker[SP_MARKER_LOC_END], val);
698         }
699     }
701     /* stroke-opacity */
702     if (!style->stroke_opacity.set) {
703         val = repr->attribute("stroke-opacity");
704         if (val) {
705             sp_style_read_iscale24(&style->stroke_opacity, val);
706         }
707     }
708     if (!style->stroke_dasharray_set) {
709         val = repr->attribute("stroke-dasharray");
710         if (val) {
711             sp_style_read_dash(style, val);
712         }
713     }
714     if (!style->stroke_dashoffset_set) {
715         /* fixme */
716         val = repr->attribute("stroke-dashoffset");
717         if (sp_svg_number_read_d(val, &style->stroke_dash.offset)) {
718             style->stroke_dashoffset_set = TRUE;
719         } else {
720             style->stroke_dashoffset_set = FALSE;
721         }
722     }
723     
724     /* -inkscape-font-specification */
725     if (!style->text_private || !style->text->font_specification.set) {
726         val = repr->attribute("-inkscape-font-specification");
727         if (val) {
728             if (!style->text_private) sp_style_privatize_text(style);
729             gchar *val_unquoted = attribute_unquote(val);
730             sp_style_read_istring(&style->text->font_specification, val_unquoted);
731             if (val_unquoted) g_free (val_unquoted);
732         }
733     }
735     /* font-family */
736     if (!style->text_private || !style->text->font_family.set) {
737         val = repr->attribute("font-family");
738         if (val) {
739             if (!style->text_private) sp_style_privatize_text(style);
740             gchar *val_unquoted = attribute_unquote(val);
741             sp_style_read_istring(&style->text->font_family, val_unquoted);
742             if (val_unquoted) g_free (val_unquoted);
743         }
744     }
746     /* filter effects */
747     if (!style->filter.set) {
748         val = repr->attribute("filter");
749         if (val) {
750                       sp_style_read_ifilter(val, style, (object) ? SP_OBJECT_DOCUMENT(object) : NULL);
751         }
752     }
753     SPS_READ_PENUM_IF_UNSET(&style->enable_background, repr,
754                             "enable-background", enum_enable_background, true);
756     /* 3. Merge from parent */
757     if (object) {
758         if (object->parent) {
759             sp_style_merge_from_parent(style, SP_OBJECT_STYLE(object->parent));
760         }
761     } else {
762         if (sp_repr_parent(repr)) {
763             /// \todo fixme: This is not the prettiest thing (Lauris)
764             SPStyle *parent = sp_style_new(NULL);
765             sp_style_read(parent, NULL, sp_repr_parent(repr));
766             sp_style_merge_from_parent(style, parent);
767             sp_style_unref(parent);
768         }
769     }
773 /**
774  * Read style properties from object's repr.
775  *
776  * 1. Reset existing object style
777  * 2. Load current effective object style
778  * 3. Load i attributes from immediate parent (which has to be up-to-date)
779  */
780 void
781 sp_style_read_from_object(SPStyle *style, SPObject *object)
783     g_return_if_fail(style != NULL);
784     g_return_if_fail(object != NULL);
785     g_return_if_fail(SP_IS_OBJECT(object));
787     Inkscape::XML::Node *repr = SP_OBJECT_REPR(object);
788     g_return_if_fail(repr != NULL);
790     sp_style_read(style, object, repr);
794 /**
795  * Read style properties from preferences.
796  * @param style The style to write to
797  * @param path Preferences directory from which the style should be read
798  */
799 void
800 sp_style_read_from_prefs(SPStyle *style, Glib::ustring const &path)
802     g_return_if_fail(style != NULL);
803     g_return_if_fail(path != "");
804     
805     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
807     // not optimal: we reconstruct the node based on the prefs, then pass it to
808     // sp_style_read for actual processing.
809     Inkscape::XML::SimpleDocument *tempdoc = new Inkscape::XML::SimpleDocument;
810     Inkscape::XML::Node *tempnode = tempdoc->createElement("temp");
811     
812     std::vector<Inkscape::Preferences::Entry> attrs = prefs->getAllEntries(path);
813     for (std::vector<Inkscape::Preferences::Entry>::iterator i = attrs.begin(); i != attrs.end(); ++i) {
814         tempnode->setAttribute(i->getEntryName().data(), i->getString().data());
815     }
817     sp_style_read(style, NULL, tempnode);
818     
819     Inkscape::GC::release(tempnode);
820     Inkscape::GC::release(tempdoc);
821     delete tempdoc;
826 /**
827  *
828  */
829 static void
830 sp_style_privatize_text(SPStyle *style)
832     SPTextStyle *text = style->text;
833     style->text = sp_text_style_duplicate_unset(style->text);
834     sp_text_style_unref(text);
835     style->text_private = TRUE;
839 /**
840  * Merge property into style.
841  *
842  * Should be called in order of highest to lowest precedence.
843  * E.g. for a single style string, call from the last declaration to the first,
844  * as CSS says that later declarations override earlier ones.
845  *
846  * \pre val != NULL.
847  */
848 static void
849 sp_style_merge_property(SPStyle *style, gint id, gchar const *val)
851     g_return_if_fail(val != NULL);
853     switch (id) {
854         case SP_PROP_INKSCAPE_FONT_SPEC:
855             if (!style->text_private) sp_style_privatize_text(style);
856             if (!style->text->font_specification.set) {
857                 gchar *val_unquoted = attribute_unquote(val);
858                 sp_style_read_istring(&style->text->font_specification, val_unquoted);
859                 if (val_unquoted) g_free (val_unquoted);
860             }
861             break;
862         /* CSS2 */
863         /* Font */
864         case SP_PROP_FONT_FAMILY:
865             if (!style->text_private) sp_style_privatize_text(style);
866             if (!style->text->font_family.set) {
867                 gchar *val_unquoted = attribute_unquote(val);
868                 sp_style_read_istring(&style->text->font_family, val_unquoted);
869                 if (val_unquoted) g_free (val_unquoted);
870             }
871             break;
872         case SP_PROP_FONT_SIZE:
873             SPS_READ_IFONTSIZE_IF_UNSET(&style->font_size, val);
874             break;
875         case SP_PROP_FONT_SIZE_ADJUST:
876             if (strcmp(val, "none") != 0) {
877                 g_warning("Unimplemented style property id SP_PROP_FONT_SIZE_ADJUST: value: %s", val);
878             }
879             break;
880         case SP_PROP_FONT_STYLE:
881             SPS_READ_IENUM_IF_UNSET(&style->font_style, val, enum_font_style, true);
882             break;
883         case SP_PROP_FONT_VARIANT:
884             SPS_READ_IENUM_IF_UNSET(&style->font_variant, val, enum_font_variant, true);
885             break;
886         case SP_PROP_FONT_WEIGHT:
887             SPS_READ_IENUM_IF_UNSET(&style->font_weight, val, enum_font_weight, true);
888             break;
889         case SP_PROP_FONT_STRETCH:
890             SPS_READ_IENUM_IF_UNSET(&style->font_stretch, val, enum_font_stretch, true);
891             break;
892         case SP_PROP_FONT:
893             if (!style->text_private) sp_style_privatize_text(style);
894             if (!style->text->font.set) {
895                 g_free(style->text->font.value);
896                 style->text->font.value = g_strdup(val);
897                 style->text->font.set = TRUE;
898                 style->text->font.inherit = (val && !strcmp(val, "inherit"));
899             }
900             break;
901             /* Text */
902         case SP_PROP_TEXT_INDENT:
903             SPS_READ_ILENGTH_IF_UNSET(&style->text_indent, val);
904             break;
905         case SP_PROP_TEXT_ALIGN:
906             SPS_READ_IENUM_IF_UNSET(&style->text_align, val, enum_text_align, true);
907             break;
908         case SP_PROP_TEXT_DECORATION:
909             if (!style->text_decoration.set) {
910                 sp_style_read_itextdecoration(&style->text_decoration, val);
911             }
912             break;
913         case SP_PROP_LINE_HEIGHT:
914             if (!style->line_height.set) {
915                 sp_style_read_ilengthornormal(&style->line_height, val);
916             }
917             break;
918         case SP_PROP_LETTER_SPACING:
919             if (!style->letter_spacing.set) {
920                 sp_style_read_ilengthornormal(&style->letter_spacing, val);
921             }
922             break;
923         case SP_PROP_WORD_SPACING:
924             if (!style->word_spacing.set) {
925                 sp_style_read_ilengthornormal(&style->word_spacing, val);
926             }
927             break;
928         case SP_PROP_TEXT_TRANSFORM:
929             SPS_READ_IENUM_IF_UNSET(&style->text_transform, val, enum_text_transform, true);
930             break;
931             /* Text (css3) */
932         case SP_PROP_DIRECTION:
933             SPS_READ_IENUM_IF_UNSET(&style->direction, val, enum_direction, true);
934             break;
935         case SP_PROP_BLOCK_PROGRESSION:
936             SPS_READ_IENUM_IF_UNSET(&style->block_progression, val, enum_block_progression, true);
937             break;
938         case SP_PROP_WRITING_MODE:
939             SPS_READ_IENUM_IF_UNSET(&style->writing_mode, val, enum_writing_mode, true);
940             break;
941         case SP_PROP_TEXT_ANCHOR:
942             SPS_READ_IENUM_IF_UNSET(&style->text_anchor, val, enum_text_anchor, true);
943             break;
944             /* Text (unimplemented) */
945         case SP_PROP_TEXT_RENDERING: {
946             /* Ignore the hint. */
947             SPIEnum dummy;
948             SPS_READ_IENUM_IF_UNSET(&dummy, val, enum_text_rendering, true);
949             break;
950         }
951         case SP_PROP_ALIGNMENT_BASELINE:
952             g_warning("Unimplemented style property SP_PROP_ALIGNMENT_BASELINE: value: %s", val);
953             break;
954         case SP_PROP_BASELINE_SHIFT:
955             g_warning("Unimplemented style property SP_PROP_BASELINE_SHIFT: value: %s", val);
956             break;
957         case SP_PROP_DOMINANT_BASELINE:
958             g_warning("Unimplemented style property SP_PROP_DOMINANT_BASELINE: value: %s", val);
959             break;
960         case SP_PROP_GLYPH_ORIENTATION_HORIZONTAL:
961             g_warning("Unimplemented style property SP_PROP_ORIENTATION_HORIZONTAL: value: %s", val);
962             break;
963         case SP_PROP_GLYPH_ORIENTATION_VERTICAL:
964             g_warning("Unimplemented style property SP_PROP_ORIENTATION_VERTICAL: value: %s", val);
965             break;
966         case SP_PROP_KERNING:
967             g_warning("Unimplemented style property SP_PROP_KERNING: value: %s", val);
968             break;
969             /* Misc */
970         case SP_PROP_CLIP:
971             g_warning("Unimplemented style property SP_PROP_CLIP: value: %s", val);
972             break;
973         case SP_PROP_COLOR:
974             if (!style->color.set) {
975                 sp_style_read_icolor(&style->color, val, style, (style->object) ? SP_OBJECT_DOCUMENT(style->object) : NULL);
976             }
977             break;
978         case SP_PROP_CURSOR:
979             g_warning("Unimplemented style property SP_PROP_CURSOR: value: %s", val);
980             break;
981         case SP_PROP_DISPLAY:
982             SPS_READ_IENUM_IF_UNSET(&style->display, val, enum_display, true);
983             break;
984         case SP_PROP_OVERFLOW:
985             /** \todo
986              * FIXME: not supported properly yet, we just read and write it,
987              * but act as if it is always "display".
988              */
989             SPS_READ_IENUM_IF_UNSET(&style->overflow, val, enum_overflow, true);
990             break;
991         case SP_PROP_VISIBILITY:
992             SPS_READ_IENUM_IF_UNSET(&style->visibility, val, enum_visibility, true);
993             break;
994             /* SVG */
995             /* Clip/Mask */
996         case SP_PROP_CLIP_PATH:
997             /** \todo
998              * This is a workaround. Inkscape only supports 'clip-path' as SVG attribute, not as
999              * style property. By having both CSS and SVG attribute set, editing of clip-path
1000              * will fail, since CSS always overwrites SVG attributes.
1001              * Fixes Bug #324849
1002              */
1003             g_warning("attribute 'clip-path' given as CSS");
1004             style->object->repr->setAttribute("clip-path", val);
1005             break;
1006         case SP_PROP_CLIP_RULE:
1007             g_warning("Unimplemented style property SP_PROP_CLIP_RULE: value: %s", val);
1008             break;
1009         case SP_PROP_MASK:
1010             /** \todo
1011              * See comment for SP_PROP_CLIP_PATH
1012              */
1013             g_warning("attribute 'mask' given as CSS");
1014             style->object->repr->setAttribute("mask", val);
1015             break;
1016         case SP_PROP_OPACITY:
1017             if (!style->opacity.set) {
1018                 sp_style_read_iscale24(&style->opacity, val);
1019             }
1020             break;
1021         case SP_PROP_ENABLE_BACKGROUND:
1022             SPS_READ_IENUM_IF_UNSET(&style->enable_background, val,
1023                                     enum_enable_background, true);
1024             break;
1025             /* Filter */
1026         case SP_PROP_FILTER:
1027             if (!style->filter.set && !style->filter.inherit) {
1028                 sp_style_read_ifilter(val, style, (style->object) ? SP_OBJECT_DOCUMENT(style->object) : NULL);
1029             }
1030             break;
1031         case SP_PROP_FLOOD_COLOR:
1032             g_warning("Unimplemented style property SP_PROP_FLOOD_COLOR: value: %s", val);
1033             break;
1034         case SP_PROP_FLOOD_OPACITY:
1035             g_warning("Unimplemented style property SP_PROP_FLOOD_OPACITY: value: %s", val);
1036             break;
1037         case SP_PROP_LIGHTING_COLOR:
1038             g_warning("Unimplemented style property SP_PROP_LIGHTING_COLOR: value: %s", val);
1039             break;
1040             /* Gradient */
1041         case SP_PROP_STOP_COLOR:
1042             g_warning("Unimplemented style property SP_PROP_STOP_COLOR: value: %s", val);
1043             break;
1044         case SP_PROP_STOP_OPACITY:
1045             g_warning("Unimplemented style property SP_PROP_STOP_OPACITY: value: %s", val);
1046             break;
1047             /* Interactivity */
1048         case SP_PROP_POINTER_EVENTS:
1049             g_warning("Unimplemented style property SP_PROP_POINTER_EVENTS: value: %s", val);
1050             break;
1051             /* Paint */
1052         case SP_PROP_COLOR_INTERPOLATION:
1053             g_warning("Unimplemented style property SP_PROP_COLOR_INTERPOLATION: value: %s", val);
1054             break;
1055         case SP_PROP_COLOR_INTERPOLATION_FILTERS:
1056             g_warning("Unimplemented style property SP_PROP_INTERPOLATION_FILTERS: value: %s", val);
1057             break;
1058         case SP_PROP_COLOR_PROFILE:
1059             g_warning("Unimplemented style property SP_PROP_COLOR_PROFILE: value: %s", val);
1060             break;
1061         case SP_PROP_COLOR_RENDERING: {
1062             /* Ignore the hint. */
1063             SPIEnum dummy;
1064             SPS_READ_IENUM_IF_UNSET(&dummy, val, enum_color_rendering, true);
1065             break;
1066         }
1067         case SP_PROP_FILL:
1068             if (!style->fill.set) {
1069                 sp_style_read_ipaint(&style->fill, val, style, (style->object) ? SP_OBJECT_DOCUMENT(style->object) : NULL);
1070             }
1071             break;
1072         case SP_PROP_FILL_OPACITY:
1073             if (!style->fill_opacity.set) {
1074                 sp_style_read_iscale24(&style->fill_opacity, val);
1075             }
1076             break;
1077         case SP_PROP_FILL_RULE:
1078             if (!style->fill_rule.set) {
1079                 sp_style_read_ienum(&style->fill_rule, val, enum_fill_rule, true);
1080             }
1081             break;
1082         case SP_PROP_IMAGE_RENDERING: {
1083             /* Ignore the hint. */
1084             SPIEnum dummy;
1085             SPS_READ_IENUM_IF_UNSET(&dummy, val, enum_image_rendering, true);
1086             break;
1087         }
1088         case SP_PROP_MARKER:
1089             /* TODO:  Call sp_uri_reference_resolve(Document *document, guchar const *uri) */
1090             /* style->marker[SP_MARKER_LOC] = g_quark_from_string(val); */
1091             if (!style->marker[SP_MARKER_LOC].set) {
1092                 g_free(style->marker[SP_MARKER_LOC].value);
1093                 style->marker[SP_MARKER_LOC].value = g_strdup(val);
1094                 style->marker[SP_MARKER_LOC].set = TRUE;
1095                 style->marker[SP_MARKER_LOC].inherit = (val && !strcmp(val, "inherit"));
1096             }
1097             break;
1099         case SP_PROP_MARKER_START:
1100             /* TODO:  Call sp_uri_reference_resolve(Document *document, guchar const *uri) */
1101             if (!style->marker[SP_MARKER_LOC_START].set) {
1102                 g_free(style->marker[SP_MARKER_LOC_START].value);
1103                 style->marker[SP_MARKER_LOC_START].value = g_strdup(val);
1104                 style->marker[SP_MARKER_LOC_START].set = TRUE;
1105                 style->marker[SP_MARKER_LOC_START].inherit = (val && !strcmp(val, "inherit"));
1106             }
1107             break;
1108         case SP_PROP_MARKER_MID:
1109             /* TODO:  Call sp_uri_reference_resolve(Document *document, guchar const *uri) */
1110             if (!style->marker[SP_MARKER_LOC_MID].set) {
1111                 g_free(style->marker[SP_MARKER_LOC_MID].value);
1112                 style->marker[SP_MARKER_LOC_MID].value = g_strdup(val);
1113                 style->marker[SP_MARKER_LOC_MID].set = TRUE;
1114                 style->marker[SP_MARKER_LOC_MID].inherit = (val && !strcmp(val, "inherit"));
1115             }
1116             break;
1117         case SP_PROP_MARKER_END:
1118             /* TODO:  Call sp_uri_reference_resolve(Document *document, guchar const *uri) */
1119             if (!style->marker[SP_MARKER_LOC_END].set) {
1120                 g_free(style->marker[SP_MARKER_LOC_END].value);
1121                 style->marker[SP_MARKER_LOC_END].value = g_strdup(val);
1122                 style->marker[SP_MARKER_LOC_END].set = TRUE;
1123                 style->marker[SP_MARKER_LOC_END].inherit = (val && !strcmp(val, "inherit"));
1124             }
1125             break;
1127         case SP_PROP_SHAPE_RENDERING: {
1128             /* Ignore the hint. */
1129             SPIEnum dummy;
1130             SPS_READ_IENUM_IF_UNSET(&dummy, val, enum_shape_rendering, true);
1131             break;
1132         }
1134         case SP_PROP_STROKE:
1135             if (!style->stroke.set) {
1136                 sp_style_read_ipaint(&style->stroke, val, style, (style->object) ? SP_OBJECT_DOCUMENT(style->object) : NULL);
1137             }
1138             break;
1139         case SP_PROP_STROKE_WIDTH:
1140             SPS_READ_ILENGTH_IF_UNSET(&style->stroke_width, val);
1141             break;
1142         case SP_PROP_STROKE_DASHARRAY:
1143             if (!style->stroke_dasharray_set) {
1144                 sp_style_read_dash(style, val);
1145             }
1146             break;
1147         case SP_PROP_STROKE_DASHOFFSET:
1148             if (!style->stroke_dashoffset_set) {
1149                 /* fixme */
1150                 if (sp_svg_number_read_d(val, &style->stroke_dash.offset)) {
1151                     style->stroke_dashoffset_set = TRUE;
1152                 } else {
1153                     style->stroke_dashoffset_set = FALSE;
1154                 }
1155             }
1156             break;
1157         case SP_PROP_STROKE_LINECAP:
1158             if (!style->stroke_linecap.set) {
1159                 sp_style_read_ienum(&style->stroke_linecap, val, enum_stroke_linecap, true);
1160             }
1161             break;
1162         case SP_PROP_STROKE_LINEJOIN:
1163             if (!style->stroke_linejoin.set) {
1164                 sp_style_read_ienum(&style->stroke_linejoin, val, enum_stroke_linejoin, true);
1165             }
1166             break;
1167         case SP_PROP_STROKE_MITERLIMIT:
1168             if (!style->stroke_miterlimit.set) {
1169                 sp_style_read_ifloat(&style->stroke_miterlimit, val);
1170             }
1171             break;
1172         case SP_PROP_STROKE_OPACITY:
1173             if (!style->stroke_opacity.set) {
1174                 sp_style_read_iscale24(&style->stroke_opacity, val);
1175             }
1176             break;
1178         default:
1179             g_warning("Invalid style property id: %d value: %s", id, val);
1180             break;
1181     }
1184 static void
1185 sp_style_merge_style_from_decl(SPStyle *const style, CRDeclaration const *const decl)
1187     /** \todo Ensure that property is lcased, as per
1188      * http://www.w3.org/TR/REC-CSS2/syndata.html#q4.
1189      * Should probably be done in libcroco.
1190      */
1191     unsigned const prop_idx = sp_attribute_lookup(decl->property->stryng->str);
1192     if (prop_idx != SP_ATTR_INVALID) {
1193         /** \todo
1194          * effic: Test whether the property is already set before trying to
1195          * convert to string. Alternatively, set from CRTerm directly rather
1196          * than converting to string.
1197          */
1198         guchar *const str_value_unsigned = cr_term_to_string(decl->value);
1199         gchar *const str_value = reinterpret_cast<gchar *>(str_value_unsigned);
1200         sp_style_merge_property(style, prop_idx, str_value);
1201         g_free(str_value);
1202     }
1205 static void
1206 sp_style_merge_from_props(SPStyle *const style, CRPropList *const props)
1208 #if 0 /* forwards */
1209     for (CRPropList const *cur = props; cur; cur = cr_prop_list_get_next(cur)) {
1210         CRDeclaration *decl = NULL;
1211         cr_prop_list_get_decl(cur, &decl);
1212         sp_style_merge_style_from_decl(style, decl);
1213     }
1214 #else /* in reverse order, as we need later declarations to take precedence over earlier ones. */
1215     if (props) {
1216         sp_style_merge_from_props(style, cr_prop_list_get_next(props));
1217         CRDeclaration *decl = NULL;
1218         cr_prop_list_get_decl(props, &decl);
1219         sp_style_merge_style_from_decl(style, decl);
1220     }
1221 #endif
1224 /**
1225  * \pre decl_list != NULL
1226  */
1227 static void
1228 sp_style_merge_from_decl_list(SPStyle *const style, CRDeclaration const *const decl_list)
1230     // read the decls from end to start, using head recursion, so that latter declarations override
1231     // (Ref: http://www.w3.org/TR/REC-CSS2/cascade.html#cascading-order point 4.)
1232     // because sp_style_merge_style_from_decl only sets properties that are unset
1233     if (decl_list->next) {
1234         sp_style_merge_from_decl_list(style, decl_list->next);
1235     }
1236     sp_style_merge_style_from_decl(style, decl_list);
1239 static CRSelEng *
1240 sp_repr_sel_eng()
1242     CRSelEng *const ret = cr_sel_eng_new();
1243     cr_sel_eng_set_node_iface(ret, &Inkscape::XML::croco_node_iface);
1245     /** \todo
1246      * Check whether we need to register any pseudo-class handlers.
1247      * libcroco has its own default handlers for first-child and lang.
1248      *
1249      * We probably want handlers for link and arguably visited (though
1250      * inkscape can't visit links at the time of writing).  hover etc.
1251      * more useful in inkview than the editor inkscape.
1252      *
1253      * http://www.w3.org/TR/SVG11/styling.html#StylingWithCSS says that
1254      * the following should be honoured, at least by inkview:
1255      * :hover, :active, :focus, :visited, :link.
1256      */
1258     g_assert(ret);
1259     return ret;
1262 static void
1263 sp_style_merge_from_object_stylesheet(SPStyle *const style, SPObject const *const object)
1265     static CRSelEng *sel_eng = NULL;
1266     if (!sel_eng) {
1267         sel_eng = sp_repr_sel_eng();
1268     }
1270     CRPropList *props = NULL;
1271     CRStatus status = cr_sel_eng_get_matched_properties_from_cascade(sel_eng,
1272                                                                      object->document->style_cascade,
1273                                                                      object->repr,
1274                                                                      &props);
1275     g_return_if_fail(status == CR_OK);
1276     /// \todo Check what errors can occur, and handle them properly.
1277     if (props) {
1278         sp_style_merge_from_props(style, props);
1279         cr_prop_list_destroy(props);
1280     }
1283 /**
1284  * Parses a style="..." string and merges it with an existing SPStyle.
1285  */
1286 void
1287 sp_style_merge_from_style_string(SPStyle *const style, gchar const *const p)
1289     /*
1290      * Reference: http://www.w3.org/TR/SVG11/styling.html#StyleAttribute:
1291      * ``When CSS styling is used, CSS inline style is specified by including
1292      * semicolon-separated property declarations of the form "name : value"
1293      * within the style attribute''.
1294      *
1295      * That's fairly ambiguous.  Is a `value' allowed to contain semicolons?
1296      * Why does it say "including", what else is allowed in the style
1297      * attribute value?
1298      */
1300     CRDeclaration *const decl_list
1301         = cr_declaration_parse_list_from_buf(reinterpret_cast<guchar const *>(p), CR_UTF_8);
1302     if (decl_list) {
1303         sp_style_merge_from_decl_list(style, decl_list);
1304         cr_declaration_destroy(decl_list);
1305     }
1308 /** Indexed by SP_CSS_FONT_SIZE_blah. */
1309 static float const font_size_table[] = {6.0, 8.0, 10.0, 12.0, 14.0, 18.0, 24.0};
1311 static void
1312 sp_style_merge_font_size_from_parent(SPIFontSize &child, SPIFontSize const &parent)
1314     /* 'font-size' */
1315     if (!child.set || child.inherit) {
1316         /* Inherit the computed value.  Reference: http://www.w3.org/TR/SVG11/styling.html#Inheritance */
1317         child.computed = parent.computed;
1318     } else if (child.type == SP_FONT_SIZE_LITERAL) {
1319         /** \todo
1320          * fixme: SVG and CSS do not specify clearly, whether we should use
1321          * user or screen coordinates (Lauris)
1322          */
1323         if (child.value < SP_CSS_FONT_SIZE_SMALLER) {
1324             child.computed = font_size_table[child.value];
1325         } else if (child.value == SP_CSS_FONT_SIZE_SMALLER) {
1326             child.computed = parent.computed / 1.2;
1327         } else if (child.value == SP_CSS_FONT_SIZE_LARGER) {
1328             child.computed = parent.computed * 1.2;
1329         } else {
1330             /* Illegal value */
1331         }
1332     } else if (child.type == SP_FONT_SIZE_PERCENTAGE) {
1333         /* Unlike most other lengths, percentage for font size is relative to parent computed value
1334          * rather than viewport. */
1335         child.computed = parent.computed * SP_F8_16_TO_FLOAT(child.value);
1336     }
1339 /**
1340  * Sets computed values in \a style, which may involve inheriting from (or in some other way
1341  * calculating from) corresponding computed values of \a parent.
1342  *
1343  * References: http://www.w3.org/TR/SVG11/propidx.html shows what properties inherit by default.
1344  * http://www.w3.org/TR/SVG11/styling.html#Inheritance gives general rules as to what it means to
1345  * inherit a value.  http://www.w3.org/TR/REC-CSS2/cascade.html#computed-value is more precise
1346  * about what the computed value is (not obvious for lengths).
1347  *
1348  * \pre \a parent's computed values are already up-to-date.
1349  */
1350 void
1351 sp_style_merge_from_parent(SPStyle *const style, SPStyle const *const parent)
1353     g_return_if_fail(style != NULL);
1355     /** \todo
1356      * fixme: Check for existing callers that might pass null parent.
1357      * This should probably be g_return_if_fail, or else we should make a
1358      * best attempt to set computed values correctly without having a parent
1359      * (i.e., by assuming parent has initial values).
1360      */
1361     if (!parent)
1362         return;
1364     /* CSS2 */
1365     /* Font */
1366     sp_style_merge_font_size_from_parent(style->font_size, parent->font_size);
1368     /* 'font-style' */
1369     if (!style->font_style.set || style->font_style.inherit) {
1370         style->font_style.computed = parent->font_style.computed;
1371     }
1373     /* 'font-variant' */
1374     if (!style->font_variant.set || style->font_variant.inherit) {
1375         style->font_variant.computed = parent->font_variant.computed;
1376     }
1378     /* 'font-weight' */
1379     if (!style->font_weight.set || style->font_weight.inherit) {
1380         style->font_weight.computed = parent->font_weight.computed;
1381     } else if (style->font_weight.value == SP_CSS_FONT_WEIGHT_NORMAL) {
1382         /** \todo
1383          * fixme: This is unconditional, i.e., happens even if parent not
1384          * present.
1385          */
1386         style->font_weight.computed = SP_CSS_FONT_WEIGHT_400;
1387     } else if (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) {
1388         style->font_weight.computed = SP_CSS_FONT_WEIGHT_700;
1389     } else if (style->font_weight.value == SP_CSS_FONT_WEIGHT_LIGHTER) {
1390         unsigned const parent_val = parent->font_weight.computed;
1391         g_assert(SP_CSS_FONT_WEIGHT_100 == 0);
1392         // strictly, 'bolder' and 'lighter' should go to the next weight
1393         // expressible in the current font family, but that's difficult to
1394         // find out, so jumping by 3 seems an appropriate approximation
1395         style->font_weight.computed = (parent_val <= SP_CSS_FONT_WEIGHT_100 + 3
1396                                        ? (unsigned)SP_CSS_FONT_WEIGHT_100
1397                                        : parent_val - 3);
1398         g_assert(style->font_weight.computed <= (unsigned) SP_CSS_FONT_WEIGHT_900);
1399     } else if (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLDER) {
1400         unsigned const parent_val = parent->font_weight.computed;
1401         g_assert(parent_val <= SP_CSS_FONT_WEIGHT_900);
1402         style->font_weight.computed = (parent_val >= SP_CSS_FONT_WEIGHT_900 - 3
1403                                        ? (unsigned)SP_CSS_FONT_WEIGHT_900
1404                                        : parent_val + 3);
1405         g_assert(style->font_weight.computed <= (unsigned) SP_CSS_FONT_WEIGHT_900);
1406     }
1408     /* 'font-stretch' */
1409     if (!style->font_stretch.set || style->font_stretch.inherit) {
1410         style->font_stretch.computed = parent->font_stretch.computed;
1411     } else if (style->font_stretch.value == SP_CSS_FONT_STRETCH_NARROWER) {
1412         unsigned const parent_val = parent->font_stretch.computed;
1413         style->font_stretch.computed = (parent_val == SP_CSS_FONT_STRETCH_ULTRA_CONDENSED
1414                                         ? parent_val
1415                                         : parent_val - 1);
1416         g_assert(style->font_stretch.computed <= (unsigned) SP_CSS_FONT_STRETCH_ULTRA_EXPANDED);
1417     } else if (style->font_stretch.value == SP_CSS_FONT_STRETCH_WIDER) {
1418         unsigned const parent_val = parent->font_stretch.computed;
1419         g_assert(parent_val <= SP_CSS_FONT_STRETCH_ULTRA_EXPANDED);
1420         style->font_stretch.computed = (parent_val == SP_CSS_FONT_STRETCH_ULTRA_EXPANDED
1421                                         ? parent_val
1422                                         : parent_val + 1);
1423         g_assert(style->font_stretch.computed <= (unsigned) SP_CSS_FONT_STRETCH_ULTRA_EXPANDED);
1424     }
1426     /* text (css2) */
1427     if (!style->text_indent.set || style->text_indent.inherit) {
1428         style->text_indent.computed = parent->text_indent.computed;
1429     }
1431     if (!style->text_align.set || style->text_align.inherit) {
1432         style->text_align.computed = parent->text_align.computed;
1433     }
1435     if (!style->text_decoration.set || style->text_decoration.inherit) {
1436         style->text_decoration.underline = parent->text_decoration.underline;
1437         style->text_decoration.overline = parent->text_decoration.overline;
1438         style->text_decoration.line_through = parent->text_decoration.line_through;
1439         style->text_decoration.blink = parent->text_decoration.blink;
1440     }
1442     if (!style->line_height.set || style->line_height.inherit) {
1443         style->line_height.computed = parent->line_height.computed;
1444         style->line_height.normal = parent->line_height.normal;
1445     }
1447     if (!style->letter_spacing.set || style->letter_spacing.inherit) {
1448         style->letter_spacing.computed = parent->letter_spacing.computed;
1449         style->letter_spacing.normal = parent->letter_spacing.normal;
1450     }
1452     if (!style->word_spacing.set || style->word_spacing.inherit) {
1453         style->word_spacing.computed = parent->word_spacing.computed;
1454         style->word_spacing.normal = parent->word_spacing.normal;
1455     }
1457     if (!style->text_transform.set || style->text_transform.inherit) {
1458         style->text_transform.computed = parent->text_transform.computed;
1459     }
1461     if (!style->direction.set || style->direction.inherit) {
1462         style->direction.computed = parent->direction.computed;
1463     }
1465     if (!style->block_progression.set || style->block_progression.inherit) {
1466         style->block_progression.computed = parent->block_progression.computed;
1467     }
1469     if (!style->writing_mode.set || style->writing_mode.inherit) {
1470         style->writing_mode.computed = parent->writing_mode.computed;
1471     }
1473     if (!style->text_anchor.set || style->text_anchor.inherit) {
1474         style->text_anchor.computed = parent->text_anchor.computed;
1475     }
1477     if (style->opacity.inherit) {
1478         style->opacity.value = parent->opacity.value;
1479     }
1481     /* Color */
1482     if (!style->color.set || style->color.inherit) {
1483         sp_style_merge_ipaint(style, &style->color, &parent->color);
1484     }
1486     /* Fill */
1487     if (!style->fill.set || style->fill.inherit || style->fill.currentcolor) {
1488         sp_style_merge_ipaint(style, &style->fill, &parent->fill);
1489     }
1491     if (!style->fill_opacity.set || style->fill_opacity.inherit) {
1492         style->fill_opacity.value = parent->fill_opacity.value;
1493     }
1495     if (!style->fill_rule.set || style->fill_rule.inherit) {
1496         style->fill_rule.computed = parent->fill_rule.computed;
1497     }
1499     /* Stroke */
1500     if (!style->stroke.set || style->stroke.inherit || style->stroke.currentcolor) {
1501         sp_style_merge_ipaint(style, &style->stroke, &parent->stroke);
1502     }
1504     if (!style->stroke_width.set || style->stroke_width.inherit) {
1505         style->stroke_width.computed = parent->stroke_width.computed;
1506     } else {
1507         /* Update computed value for any change in font inherited from parent. */
1508         double const em = style->font_size.computed;
1509         if (style->stroke_width.unit == SP_CSS_UNIT_EM) {
1510             style->stroke_width.computed = style->stroke_width.value * em;
1511         } else if (style->stroke_width.unit == SP_CSS_UNIT_EX) {
1512             double const ex = em * 0.5;  // fixme: Get x height from libnrtype or pango.
1513             style->stroke_width.computed = style->stroke_width.value * ex;
1514         }
1515     }
1517     if (!style->stroke_linecap.set || style->stroke_linecap.inherit) {
1518         style->stroke_linecap.computed = parent->stroke_linecap.computed;
1519     }
1521     if (!style->stroke_linejoin.set || style->stroke_linejoin.inherit) {
1522         style->stroke_linejoin.computed = parent->stroke_linejoin.computed;
1523     }
1525     if (!style->stroke_miterlimit.set || style->stroke_miterlimit.inherit) {
1526         style->stroke_miterlimit.value = parent->stroke_miterlimit.value;
1527     }
1529     if (!style->stroke_dasharray_set && parent->stroke_dasharray_set) {
1530         /** \todo
1531          * This code looks wrong.  Why does the logic differ from the
1532          * above properties? Similarly dashoffset below.
1533          */
1534         style->stroke_dash.n_dash = parent->stroke_dash.n_dash;
1535         if (style->stroke_dash.n_dash > 0) {
1536             style->stroke_dash.dash = g_new(gdouble, style->stroke_dash.n_dash);
1537             memcpy(style->stroke_dash.dash, parent->stroke_dash.dash, style->stroke_dash.n_dash * sizeof(gdouble));
1538         }
1539     }
1541     if (!style->stroke_dashoffset_set && parent->stroke_dashoffset_set) {
1542         style->stroke_dash.offset = parent->stroke_dash.offset;
1543     }
1545     if (!style->stroke_opacity.set || style->stroke_opacity.inherit) {
1546         style->stroke_opacity.value = parent->stroke_opacity.value;
1547     }
1549     if (style->text && parent->text) {
1550         if (!style->text->font_family.set || style->text->font_family.inherit) {
1551             g_free(style->text->font_family.value);
1552             style->text->font_family.value = g_strdup(parent->text->font_family.value);
1553         }
1554     }
1556     if (style->text && parent->text) {
1557         if (!style->text->font_specification.set || style->text->font_specification.inherit) {
1558             g_free(style->text->font_specification.value);
1559             style->text->font_specification.value = g_strdup(parent->text->font_specification.value);
1560         }
1561     }
1563     /* Markers - Free the old value and make copy of the new */
1564     for (unsigned i = SP_MARKER_LOC; i < SP_MARKER_LOC_QTY; i++) {
1565         if (!style->marker[i].set || style->marker[i].inherit) {
1566             g_free(style->marker[i].value);
1567             style->marker[i].value = g_strdup(parent->marker[i].value);
1568         }
1569     }
1571     /* Filter effects */
1572     if (style->filter.inherit) {
1573         sp_style_merge_ifilter(style, &parent->filter);
1574     }
1576     if(style->enable_background.inherit) {
1577         style->enable_background.value = parent->enable_background.value;
1578     }
1581 template <typename T>
1582 static void
1583 sp_style_merge_prop_from_dying_parent(T &child, T const &parent)
1585     if ( ( !(child.set) || child.inherit )
1586          && parent.set && !(parent.inherit) )
1587     {
1588         child = parent;
1589     }
1592 /**
1593  * Copy SPIString from parent to child.
1594  */
1595 static void
1596 sp_style_merge_string_prop_from_dying_parent(SPIString &child, SPIString const &parent)
1598     if ( ( !(child.set) || child.inherit )
1599          && parent.set && !(parent.inherit) )
1600     {
1601         g_free(child.value);
1602         child.value = g_strdup(parent.value);
1603         child.set = parent.set;
1604         child.inherit = parent.inherit;
1605     }
1608 static void
1609 sp_style_merge_paint_prop_from_dying_parent(SPStyle *style,
1610                                             SPIPaint &child, SPIPaint const &parent)
1612     /** \todo
1613      * I haven't given this much attention.  See comments below about
1614      * currentColor, colorProfile, and relative URIs.
1615      */
1616     if (!child.set || child.inherit) {
1617         sp_style_merge_ipaint(style, &child, &parent);
1618         child.set = parent.set;
1619         child.inherit = parent.inherit;
1620     }
1623 static void
1624 sp_style_merge_rel_enum_prop_from_dying_parent(SPIEnum &child, SPIEnum const &parent,
1625                                                unsigned const max_computed_val,
1626                                                unsigned const smaller_val)
1628     /* We assume that min computed val is 0, contiguous up to max_computed_val,
1629        then zero or more other absolute values, then smaller_val then larger_val. */
1630     unsigned const min_computed_val = 0;
1631     unsigned const larger_val = smaller_val + 1;
1632     g_return_if_fail(min_computed_val < max_computed_val);
1633     g_return_if_fail(max_computed_val < smaller_val);
1635     if (parent.set && !parent.inherit) {
1636         if (!child.set || child.inherit) {
1637             child.value = parent.value;
1638             child.set = parent.set;  // i.e. true
1639             child.inherit = parent.inherit;  // i.e. false
1640         } else if (child.value < smaller_val) {
1641             /* Child has absolute value: leave as is. */
1642         } else if ( ( child.value == smaller_val
1643                       && parent.value == larger_val )
1644                     || ( parent.value == smaller_val
1645                          && child.value == larger_val ) )
1646         {
1647             child.set = false;
1648             /*
1649              * Note that this can result in a change in computed value in the
1650              * rare case that the parent's setting was a no-op (i.e. if the
1651              * parent's parent's computed value was already ultra-condensed or
1652              * ultra-expanded).  However, I'd guess that the change is for the
1653              * better: I'd guess that if the properties were specified
1654              * relatively, then the intent is to counteract parent's effect.
1655              * I.e. I believe this is the best code even in that case.
1656              */
1657         } else if (child.value == parent.value) {
1658             /* Leave as is. */
1659             /** \todo
1660              * It's unclear what to do if style and parent specify the same
1661              * relative directive (narrower or wider).  We can either convert
1662              * to absolute specification or coalesce to a single relative
1663              * request (of half the strength of the original pair).
1664              *
1665              * Converting to a single level of relative specification is a
1666              * better choice if the newly-unlinked clone is itself cloned to
1667              * other contexts (inheriting different font stretchiness): it
1668              * would preserve the effect that it will be narrower than
1669              * the inherited context in each case.  The disadvantage is that
1670              * it will ~certainly affect the computed value of the
1671              * newly-unlinked clone.
1672              */
1673         } else {
1674             unsigned const parent_val = parent.computed;
1675             child.value = ( child.value == smaller_val
1676                             ? ( parent_val == min_computed_val
1677                                 ? parent_val
1678                                 : parent_val - 1 )
1679                             : ( parent_val == max_computed_val
1680                                 ? parent_val
1681                                 : parent_val + 1 ) );
1682             g_assert(child.value <= max_computed_val);
1683             child.inherit = false;
1684             g_assert(child.set);
1685         }
1686     }
1689 template <typename LengthT>
1690 static void
1691 sp_style_merge_length_prop_from_dying_parent(LengthT &child, LengthT const &parent,
1692                                              double const parent_child_em_ratio)
1694     if ( ( !(child.set) || child.inherit )
1695          && parent.set && !(parent.inherit) )
1696     {
1697         child = parent;
1698         switch (parent.unit) {
1699             case SP_CSS_UNIT_EM:
1700             case SP_CSS_UNIT_EX:
1701                 child.value *= parent_child_em_ratio;
1702                 /** \todo
1703                  * fixme: Have separate ex ratio parameter.
1704                  * Get x height from libnrtype or pango.
1705                  */
1706                 if (!IS_FINITE(child.value)) {
1707                     child.value = child.computed;
1708                     child.unit = SP_CSS_UNIT_NONE;
1709                 }
1710                 break;
1712             default:
1713                 break;
1714         }
1715     }
1718 static double
1719 get_relative_font_size_frac(SPIFontSize const &font_size)
1721     switch (font_size.type) {
1722         case SP_FONT_SIZE_LITERAL: {
1723             switch (font_size.value) {
1724                 case SP_CSS_FONT_SIZE_SMALLER:
1725                     return 5.0 / 6.0;
1727                 case SP_CSS_FONT_SIZE_LARGER:
1728                     return 6.0 / 5.0;
1730                 default:
1731                     g_assert_not_reached();
1732             }
1733         }
1735         case SP_FONT_SIZE_PERCENTAGE:
1736             return SP_F8_16_TO_FLOAT(font_size.value);
1738         case SP_FONT_SIZE_LENGTH:
1739             g_assert_not_reached();
1740     }
1741     g_assert_not_reached();
1744 /**
1745  * Combine \a style and \a parent style specifications into a single style specification that
1746  * preserves (as much as possible) the effect of the existing \a style being a child of \a parent.
1747  *
1748  * Called when the parent repr is to be removed (e.g. the parent is a \<use\> element that is being
1749  * unlinked), in which case we copy/adapt property values that are explicitly set in \a parent,
1750  * trying to retain the same visual appearance once the parent is removed.  Interesting cases are
1751  * when there is unusual interaction with the parent's value (opacity, display) or when the value
1752  * can be specified as relative to the parent computed value (font-size, font-weight etc.).
1753  *
1754  * Doesn't update computed values of \a style.  For correctness, you should subsequently call
1755  * sp_style_merge_from_parent against the new parent (presumably \a parent's parent) even if \a
1756  * style was previously up-to-date wrt \a parent.
1757  *
1758  * \pre \a parent's computed values are already up-to-date.
1759  *   (\a style's computed values needn't be up-to-date.)
1760  */
1761 void
1762 sp_style_merge_from_dying_parent(SPStyle *const style, SPStyle const *const parent)
1764     /** \note
1765      * The general rule for each property is as follows:
1766      *
1767      *   If style is set to an absolute value, then leave it as is.
1768      *
1769      *   Otherwise (i.e. if style has a relative value):
1770      *
1771      *     If parent is set to an absolute value, then set style to the computed value.
1772      *
1773      *     Otherwise, calculate the combined relative value (e.g. multiplying the two percentages).
1774      */
1776     /* We do font-size first, to ensure that em size is up-to-date. */
1777     /** \todo
1778      * fixme: We'll need to have more font-related things up the top once
1779      * we're getting x-height from pango or libnrtype.
1780      */
1782     /* Some things that allow relative specifications. */
1783     {
1784         /* font-size.  Note that we update the computed font-size of style,
1785            to assist in em calculations later in this function. */
1786         if (parent->font_size.set && !parent->font_size.inherit) {
1787             if (!style->font_size.set || style->font_size.inherit) {
1788                 /* font_size inherits the computed value, so we can use the parent value
1789                  * verbatim. */
1790                 style->font_size = parent->font_size;
1791             } else if ( style->font_size.type == SP_FONT_SIZE_LENGTH ) {
1792                 /* Child already has absolute size (stored in computed value), so do nothing. */
1793             } else if ( style->font_size.type == SP_FONT_SIZE_LITERAL
1794                         && style->font_size.value < SP_CSS_FONT_SIZE_SMALLER ) {
1795                 /* Child already has absolute size, but we ensure that the computed value
1796                    is up-to-date. */
1797                 unsigned const ix = style->font_size.value;
1798                 g_assert(ix < G_N_ELEMENTS(font_size_table));
1799                 style->font_size.computed = font_size_table[ix];
1800             } else {
1801                 /* Child has relative size. */
1802                 double const child_frac(get_relative_font_size_frac(style->font_size));
1803                 style->font_size.set = true;
1804                 style->font_size.inherit = false;
1805                 style->font_size.computed = parent->font_size.computed * child_frac;
1807                 if ( ( parent->font_size.type == SP_FONT_SIZE_LITERAL
1808                        && parent->font_size.value < SP_CSS_FONT_SIZE_SMALLER )
1809                      || parent->font_size.type == SP_FONT_SIZE_LENGTH )
1810                 {
1811                     /* Absolute value. */
1812                     style->font_size.type = SP_FONT_SIZE_LENGTH;
1813                     /* .value is unused for SP_FONT_SIZE_LENGTH. */
1814                 } else {
1815                     /* Relative value. */
1816                     double const parent_frac(get_relative_font_size_frac(parent->font_size));
1817                     style->font_size.type = SP_FONT_SIZE_PERCENTAGE;
1818                     style->font_size.value = SP_F8_16_FROM_FLOAT(parent_frac * child_frac);
1819                 }
1820             }
1821         }
1823         /* 'font-stretch' */
1824         sp_style_merge_rel_enum_prop_from_dying_parent(style->font_stretch,
1825                                                        parent->font_stretch,
1826                                                        SP_CSS_FONT_STRETCH_ULTRA_EXPANDED,
1827                                                        SP_CSS_FONT_STRETCH_NARROWER);
1829         /* font-weight */
1830         sp_style_merge_rel_enum_prop_from_dying_parent(style->font_weight,
1831                                                        parent->font_weight,
1832                                                        SP_CSS_FONT_WEIGHT_900,
1833                                                        SP_CSS_FONT_WEIGHT_LIGHTER);
1834     }
1837     /* Enum values that don't have any relative settings (other than `inherit'). */
1838     {
1839         SPIEnum SPStyle::*const fields[] = {
1840             //nyi: SPStyle::clip_rule,
1841             //nyi: SPStyle::color_interpolation,
1842             //nyi: SPStyle::color_interpolation_filters,
1843             //nyi: SPStyle::color_rendering,
1844             &SPStyle::direction,
1845             &SPStyle::fill_rule,
1846             &SPStyle::font_style,
1847             &SPStyle::font_variant,
1848             //nyi: SPStyle::image_rendering,
1849             //nyi: SPStyle::pointer_events,
1850             //nyi: SPStyle::shape_rendering,
1851             &SPStyle::stroke_linecap,
1852             &SPStyle::stroke_linejoin,
1853             &SPStyle::text_anchor,
1854             //nyi: &SPStyle::text_rendering,
1855             &SPStyle::visibility,
1856             &SPStyle::writing_mode
1857         };
1859         for (unsigned i = 0; i < G_N_ELEMENTS(fields); ++i) {
1860             SPIEnum SPStyle::*const fld = fields[i];
1861             sp_style_merge_prop_from_dying_parent<SPIEnum>(style->*fld, parent->*fld);
1862         }
1863     }
1865     /* A few other simple inheritance properties. */
1866     {
1867         sp_style_merge_prop_from_dying_parent<SPIScale24>(style->fill_opacity, parent->fill_opacity);
1868         sp_style_merge_prop_from_dying_parent<SPIScale24>(style->stroke_opacity, parent->stroke_opacity);
1869         sp_style_merge_prop_from_dying_parent<SPIFloat>(style->stroke_miterlimit, parent->stroke_miterlimit);
1871         /** \todo
1872          * We currently treat text-decoration as if it were a simple inherited
1873          * property (fixme). This code may need changing once we do the
1874          * special fill/stroke inheritance mentioned by the spec.
1875          */
1876         sp_style_merge_prop_from_dying_parent<SPITextDecoration>(style->text_decoration,
1877                                                                  parent->text_decoration);
1879         //nyi: font-size-adjust,  // <number> | none | inherit
1880         //nyi: glyph-orientation-horizontal,
1881         //nyi: glyph-orientation-vertical,
1882     }
1884     /* Properties that involve length but are easy in other respects. */
1885     {
1886         /* The difficulty with lengths is that font-relative units need adjusting if the font
1887          * varies between parent & child.
1888          *
1889          * Lengths specified in the existing child can stay as they are: its computed font
1890          * specification should stay unchanged, so em & ex lengths should continue to mean the same
1891          * size.
1892          *
1893          * Lengths specified in the dying parent in em or ex need to be scaled according to the
1894          * ratio of em or ex size between parent & child.
1895          */
1896         double const parent_child_em_ratio = parent->font_size.computed / style->font_size.computed;
1898         SPILength SPStyle::*const lfields[] = {
1899             &SPStyle::stroke_width,
1900             &SPStyle::text_indent
1901         };
1902         for (unsigned i = 0; i < G_N_ELEMENTS(lfields); ++i) {
1903             SPILength SPStyle::*fld = lfields[i];
1904             sp_style_merge_length_prop_from_dying_parent<SPILength>(style->*fld,
1905                                                                     parent->*fld,
1906                                                                     parent_child_em_ratio);
1907         }
1909         SPILengthOrNormal SPStyle::*const nfields[] = {
1910             &SPStyle::letter_spacing,
1911             &SPStyle::line_height,
1912             &SPStyle::word_spacing
1913         };
1914         for (unsigned i = 0; i < G_N_ELEMENTS(nfields); ++i) {
1915             SPILengthOrNormal SPStyle::*fld = nfields[i];
1916             sp_style_merge_length_prop_from_dying_parent<SPILengthOrNormal>(style->*fld,
1917                                                                             parent->*fld,
1918                                                                             parent_child_em_ratio);
1919         }
1921         //nyi: &SPStyle::kerning: length or `auto'
1923         /* fixme: Move stroke-dash and stroke-dash-offset here once they
1924            can accept units. */
1925     }
1927     /* Properties that involve a URI but are easy in other respects. */
1928     {
1929         /** \todo
1930          * Could cause problems if original object was in another document
1931          * and it used a relative URL.  (At the time of writing, we don't
1932          * allow hrefs to other documents, so this isn't a problem yet.)
1933          * Paint properties also allow URIs.
1934          */
1935         //nyi: cursor,   // may involve change in effect, but we can't do much better
1936         //nyi: color-profile,
1938         // Markers (marker-start, marker-mid, marker-end).
1939         for (unsigned i = SP_MARKER_LOC; i < SP_MARKER_LOC_QTY; i++) {
1940             sp_style_merge_string_prop_from_dying_parent(style->marker[i], parent->marker[i]);
1941         }
1942     }
1944     /* CSS2 */
1945     /* Font */
1947     if (style->text && parent->text) {
1948         sp_style_merge_string_prop_from_dying_parent(style->text->font_specification,
1949                                                      parent->text->font_specification);
1950         
1951         sp_style_merge_string_prop_from_dying_parent(style->text->font_family,
1952                                                      parent->text->font_family);
1953     }
1956     /* Properties that don't inherit by default.  Most of these need special handling. */
1957     {
1958         /*
1959          * opacity's effect is cumulative; we set the new value to the combined effect.  The
1960          * default value for opacity is 1.0, not inherit.  (Note that stroke-opacity and
1961          * fill-opacity are quite different from opacity, and don't need any special handling.)
1962          *
1963          * Cases:
1964          * - parent & child were each previously unset, in which case the effective
1965          *   opacity value is 1.0, and style should remain unset.
1966          * - parent was previously unset (so computed opacity value of 1.0)
1967          *   and child was set to inherit.  The merged child should
1968          *   get a value of 1.0, and shouldn't inherit (lest the new parent
1969          *   has a different opacity value).  Given that opacity's default
1970          *   value is 1.0 (rather than inherit), we might as well have the
1971          *   merged child's opacity be unset.
1972          * - parent was previously unset (so opacity 1.0), and child was set to a number.
1973          *   The merged child should retain its existing settings (though it doesn't matter
1974          *   if we make it unset if that number was 1.0).
1975          * - parent was inherit and child was unset.  Merged child should be set to inherit.
1976          * - parent was inherit and child was inherit.  (We can't in general reproduce this
1977          *   effect (short of introducing a new group), but setting opacity to inherit is rare.)
1978          *   If the inherited value was strictly between 0.0 and 1.0 (exclusive) then the merged
1979          *   child's value should be set to the product of the two, i.e. the square of the
1980          *   inherited value, and should not be marked as inherit.  (This decision assumes that it
1981          *   is more important to retain the effective opacity than to retain the inheriting
1982          *   effect, and assumes that the inheriting effect either isn't important enough to create
1983          *   a group or isn't common enough to bother maintaining the code to create a group.)  If
1984          *   the inherited value was 0.0 or 1.0, then marking the merged child as inherit comes
1985          *   closer to maintaining the effect.
1986          * - parent was inherit and child was set to a numerical value.  If the child's value
1987          *   was 1.0, then the merged child should have the same settings as the parent.
1988          *   If the child's value was 0, then the merged child should also be set to 0.
1989          *   If the child's value was anything else, then we do the same as for the inherit/inherit
1990          *   case above: have the merged child set to the product of the two opacities and not
1991          *   marked as inherit, for the same reasons as for that case.
1992          * - parent was set to a value, and child was unset.  The merged child should have
1993          *   parent's settings.
1994          * - parent was set to a value, and child was inherit.  The merged child should
1995          *   be set to the product, i.e. the square of the parent's value.
1996          * - parent & child are each set to a value.  The merged child should be set to the
1997          *   product.
1998          */
1999         if ( !style->opacity.set
2000              || ( !style->opacity.inherit
2001                   && style->opacity.value == SP_SCALE24_MAX ) )
2002         {
2003             style->opacity = parent->opacity;
2004         } else {
2005             /* Ensure that style's computed value is up-to-date. */
2006             if (style->opacity.inherit) {
2007                 style->opacity.value = parent->opacity.value;
2008             }
2010             /* Multiplication of opacities occurs even if a child's opacity is set to inherit. */
2011             style->opacity.value = SP_SCALE24_MUL(style->opacity.value,
2012                                                   parent->opacity.value);
2014             style->opacity.inherit = (parent->opacity.inherit
2015                                       && style->opacity.inherit
2016                                       && (parent->opacity.value == 0 ||
2017                                           parent->opacity.value == SP_SCALE24_MAX));
2018             style->opacity.set = ( style->opacity.inherit
2019                                    || style->opacity.value < SP_SCALE24_MAX );
2020         }
2022         /* display is in principle similar to opacity, but implementation is easier. */
2023         if ( parent->display.set && !parent->display.inherit
2024              && parent->display.value == SP_CSS_DISPLAY_NONE ) {
2025             style->display.value = SP_CSS_DISPLAY_NONE;
2026             style->display.set = true;
2027             style->display.inherit = false;
2028         } else if (style->display.inherit) {
2029             style->display.value = parent->display.value;
2030             style->display.set = parent->display.set;
2031             style->display.inherit = parent->display.inherit;
2032         } else {
2033             /* Leave as is.  (display doesn't inherit by default.) */
2034         }
2036         /* enable-background - this is rather complicated, because
2037          * it is valid only when applied to container elements.
2038          * Let's check a simple case anyhow. */
2039         if (parent->enable_background.set
2040             && !parent->enable_background.inherit
2041             && style->enable_background.inherit)
2042         {
2043             style->enable_background.set = true;
2044             style->enable_background.inherit = false;
2045             style->enable_background.value = parent->enable_background.value;
2046         }
2048         if (!style->filter.set || style->filter.inherit)
2049         {
2050             sp_style_merge_ifilter(style, &parent->filter);
2051         }
2053         /** \todo
2054          * fixme: Check that we correctly handle all properties that don't
2055          * inherit by default (as shown in
2056          * http://www.w3.org/TR/SVG11/propidx.html for most SVG 1.1 properties).
2057          */
2058     }
2060     /* SPIPaint properties (including color). */
2061     {
2062         /** \todo
2063          * Think about the issues involved if specified as currentColor or
2064          * if specified relative to colorProfile, and if the currentColor or
2065          * colorProfile differs between parent \& child.  See also comments
2066          * elsewhere in this function about URIs.
2067          */
2068         SPIPaint SPStyle::*const fields[] = {
2069             &SPStyle::color,
2070             &SPStyle::fill,
2071             &SPStyle::stroke
2072         };
2073         for (unsigned i = 0; i < G_N_ELEMENTS(fields); ++i) {
2074             SPIPaint SPStyle::*const fld = fields[i];
2075             sp_style_merge_paint_prop_from_dying_parent(style, style->*fld, parent->*fld);
2076         }
2077     }
2079     /* Things from SVG 1.2 or CSS3. */
2080     {
2081         /* Note: If we ever support setting string values for text-align then we'd need strdup
2082          * handling here. */
2083         sp_style_merge_prop_from_dying_parent<SPIEnum>(style->text_align, parent->text_align);
2085         sp_style_merge_prop_from_dying_parent<SPIEnum>(style->text_transform, parent->text_transform);
2086         sp_style_merge_prop_from_dying_parent<SPIEnum>(style->block_progression, parent->block_progression);
2087     }
2089     /* Note: this will need length handling once dasharray supports units. */
2090     if ( ( !style->stroke_dasharray_set || style->stroke_dasharray_inherit )
2091          && parent->stroke_dasharray_set && !parent->stroke_dasharray_inherit )
2092     {
2093         style->stroke_dash.n_dash = parent->stroke_dash.n_dash;
2094         if (style->stroke_dash.n_dash > 0) {
2095             style->stroke_dash.dash = g_new(gdouble, style->stroke_dash.n_dash);
2096             memcpy(style->stroke_dash.dash, parent->stroke_dash.dash, style->stroke_dash.n_dash * sizeof(gdouble));
2097         }
2098         style->stroke_dasharray_set = parent->stroke_dasharray_set;
2099         style->stroke_dasharray_inherit = parent->stroke_dasharray_inherit;
2100     }
2102     /* Note: this will need length handling once dasharray_offset supports units. */
2103     if (!style->stroke_dashoffset_set && parent->stroke_dashoffset_set) {
2104         style->stroke_dash.offset = parent->stroke_dash.offset;
2105         style->stroke_dashoffset_set = parent->stroke_dashoffset_set;
2106         /* fixme: we don't currently allow stroke-dashoffset to be `inherit'.  TODO: Try to
2107          * represent it as a normal SPILength; though will need to do something about existing
2108          * users of stroke_dash.offset and stroke_dashoffset_set. */
2109     }
2113 static void
2114 sp_style_set_ipaint_to_uri(SPStyle *style, SPIPaint *paint, const Inkscape::URI *uri, Document *document)
2116     // it may be that this style's SPIPaint has not yet created its URIReference;
2117     // now that we have a document, we can create it here
2118     if (!paint->value.href && document) {
2119         paint->value.href = new SPPaintServerReference(document);
2120         paint->value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun((paint == &style->fill)? sp_style_fill_paint_server_ref_changed : sp_style_stroke_paint_server_ref_changed), style));
2121     }
2123     if (paint->value.href && paint->value.href->getObject())
2124         paint->value.href->detach();
2126     if (paint->value.href) {
2127         try {
2128             paint->value.href->attach(*uri);
2129         } catch (Inkscape::BadURIException &e) {
2130             g_warning("%s", e.what());
2131             paint->value.href->detach();
2132         }
2133     }
2136 static void
2137 sp_style_set_ipaint_to_uri_string (SPStyle *style, SPIPaint *paint, const gchar *uri)
2139     try {
2140         const Inkscape::URI IURI(uri);
2141         sp_style_set_ipaint_to_uri(style, paint, &IURI, style->document);
2142     } catch (...) {
2143         g_warning("URI failed to parse: %s", uri);
2144     }
2147 void
2148 sp_style_set_to_uri_string (SPStyle *style, bool isfill, const gchar *uri)
2150     sp_style_set_ipaint_to_uri_string (style, isfill? &style->fill : &style->stroke, uri);
2153 /**
2154  *
2155  */
2156 static void
2157 sp_style_merge_ipaint(SPStyle *style, SPIPaint *paint, SPIPaint const *parent)
2159     if ((paint->set && paint->currentcolor) || parent->currentcolor) {
2160         bool isset = paint->set;
2161         paint->clear();
2162         paint->set = isset;
2163         paint->currentcolor = TRUE;
2164         paint->setColor(style->color.value.color);
2165         return;
2166     }
2168     paint->clear();
2169     if ( parent->isPaintserver() ) {
2170         if (parent->value.href) {
2171             sp_style_set_ipaint_to_uri(style, paint, parent->value.href->getURI(), parent->value.href->getOwnerDocument());
2172         } else {
2173             g_warning("Expected paint server not found.");
2174         }
2175     } else if ( parent->isColor() ) {
2176         paint->setColor( parent->value.color );
2177     } else if ( parent->isNoneSet() ) {
2178         paint->noneSet = TRUE;
2179     } else if ( parent->isNone() ) {
2180         //
2181     } else {
2182         g_assert_not_reached();
2183     }
2187 /**
2188  * Merge filter style from parent.
2189  * Filter effects do not inherit by default
2190  */
2191 static void
2192 sp_style_merge_ifilter(SPStyle *style, SPIFilter const *parent)
2194     // FIXME:
2195     // instead of just copying over, we need to _really merge_ the two filters by combining their
2196     // filter primitives
2198     sp_style_filter_clear(style);
2199     style->filter.set = parent->set;
2200     style->filter.inherit = parent->inherit;
2202     if (style->filter.href && style->filter.href->getObject())
2203        style->filter.href->detach();
2205     // it may be that this style has not yet created its SPFilterReference
2206     if (!style->filter.href && style->object && SP_OBJECT_DOCUMENT(style->object)) {
2207             style->filter.href = new SPFilterReference(SP_OBJECT_DOCUMENT(style->object));
2208             style->filter.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style));
2209     }
2211     if (style->filter.href && parent->href && parent->href->getObject()) {
2212         try {
2213             style->filter.href->attach(*parent->href->getURI());
2214         } catch (Inkscape::BadURIException &e) {
2215             g_warning("%s", e.what());
2216             style->filter.href->detach();
2217         }
2218     }
2221 /**
2222  * Dumps the style to a CSS string, with either SP_STYLE_FLAG_IFSET or
2223  * SP_STYLE_FLAG_ALWAYS flags. Used with Always for copying an object's
2224  * complete cascaded style to style_clipboard. When you need a CSS string
2225  * for an object in the document tree, you normally call
2226  * sp_style_write_difference instead to take into account the object's parent.
2227  *
2228  * \pre style != NULL.
2229  * \pre flags in {IFSET, ALWAYS}.
2230  * \post ret != NULL.
2231  */
2232 gchar *
2233 sp_style_write_string(SPStyle const *const style, guint const flags)
2235     /** \todo
2236      * Merge with write_difference, much duplicate code!
2237      */
2238     g_return_val_if_fail(style != NULL, NULL);
2239     g_return_val_if_fail(((flags == SP_STYLE_FLAG_IFSET) ||
2240                           (flags == SP_STYLE_FLAG_ALWAYS)  ),
2241                          NULL);
2243     gchar c[BMAX];
2244     gchar *p = c;
2245     *p = '\0';
2247     p += sp_style_write_ifontsize(p, c + BMAX - p, "font-size", &style->font_size, NULL, flags);
2248     p += sp_style_write_ienum(p, c + BMAX - p, "font-style", enum_font_style, &style->font_style, NULL, flags);
2249     p += sp_style_write_ienum(p, c + BMAX - p, "font-variant", enum_font_variant, &style->font_variant, NULL, flags);
2250     p += sp_style_write_ienum(p, c + BMAX - p, "font-weight", enum_font_weight, &style->font_weight, NULL, flags);
2251     p += sp_style_write_ienum(p, c + BMAX - p, "font-stretch", enum_font_stretch, &style->font_stretch, NULL, flags);
2253     /* Text */
2254     p += sp_style_write_ilength(p, c + BMAX - p, "text-indent", &style->text_indent, NULL, flags);
2255     p += sp_style_write_ienum(p, c + BMAX - p, "text-align", enum_text_align, &style->text_align, NULL, flags);
2256     p += sp_style_write_itextdecoration(p, c + BMAX - p, "text-decoration", &style->text_decoration, NULL, flags);
2257     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "line-height", &style->line_height, NULL, flags);
2258     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "letter-spacing", &style->letter_spacing, NULL, flags);
2259     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "word-spacing", &style->word_spacing, NULL, flags);
2260     p += sp_style_write_ienum(p, c + BMAX - p, "text-transform", enum_text_transform, &style->text_transform, NULL, flags);
2261     p += sp_style_write_ienum(p, c + BMAX - p, "direction", enum_direction, &style->direction, NULL, flags);
2262     p += sp_style_write_ienum(p, c + BMAX - p, "block-progression", enum_block_progression, &style->block_progression, NULL, flags);
2263     p += sp_style_write_ienum(p, c + BMAX - p, "writing-mode", enum_writing_mode, &style->writing_mode, NULL, flags);
2265     p += sp_style_write_ienum(p, c + BMAX - p, "text-anchor", enum_text_anchor, &style->text_anchor, NULL, flags);
2267     /// \todo fixme: Per type methods need default flag too (lauris)
2269     if (style->opacity.value != SP_SCALE24_MAX) {
2270         p += sp_style_write_iscale24(p, c + BMAX - p, "opacity", &style->opacity, NULL, flags);
2271     }
2273     if (!style->color.noneSet) { // CSS does not permit "none" for color
2274         p += sp_style_write_ipaint(p, c + BMAX - p, "color", &style->color, NULL, flags);
2275     }
2277     p += sp_style_write_ipaint(p, c + BMAX - p, "fill", &style->fill, NULL, flags);
2278     // if fill:none, skip writing fill properties
2279     if (!style->fill.noneSet) {
2280         p += sp_style_write_iscale24(p, c + BMAX - p, "fill-opacity", &style->fill_opacity, NULL, flags);
2281         p += sp_style_write_ienum(p, c + BMAX - p, "fill-rule", enum_fill_rule, &style->fill_rule, NULL, flags);
2282     }
2284     p += sp_style_write_ipaint(p, c + BMAX - p, "stroke", &style->stroke, NULL, flags);
2286     // stroke width affects markers, so write it if there's stroke OR any markers
2287     if (!style->stroke.noneSet || 
2288         style->marker[SP_MARKER_LOC].set ||
2289         style->marker[SP_MARKER_LOC_START].set ||
2290         style->marker[SP_MARKER_LOC_MID].set || 
2291         style->marker[SP_MARKER_LOC_END].set) {
2292         p += sp_style_write_ilength(p, c + BMAX - p, "stroke-width", &style->stroke_width, NULL, flags);
2293     }
2295     // if stroke:none, skip writing stroke properties
2296     if (!style->stroke.noneSet) {
2297         p += sp_style_write_ienum(p, c + BMAX - p, "stroke-linecap", enum_stroke_linecap, &style->stroke_linecap, NULL, flags);
2298         p += sp_style_write_ienum(p, c + BMAX - p, "stroke-linejoin", enum_stroke_linejoin, &style->stroke_linejoin, NULL, flags);
2299         p += sp_style_write_ifloat(p, c + BMAX - p, "stroke-miterlimit", &style->stroke_miterlimit, NULL, flags);
2300         p += sp_style_write_iscale24(p, c + BMAX - p, "stroke-opacity", &style->stroke_opacity, NULL, flags);
2302         /** \todo fixme: */
2303         if ((flags == SP_STYLE_FLAG_ALWAYS)
2304             || style->stroke_dasharray_set)
2305         {
2306             if (style->stroke_dasharray_inherit) {
2307                 p += g_snprintf(p, c + BMAX - p, "stroke-dasharray:inherit;");
2308             } else if (style->stroke_dash.n_dash && style->stroke_dash.dash) {
2309                 p += g_snprintf(p, c + BMAX - p, "stroke-dasharray:");
2310                 gint i;
2311                 for (i = 0; i < style->stroke_dash.n_dash; i++) {
2312                     Inkscape::CSSOStringStream os;
2313                     if (i) {
2314                         os << ", ";
2315                     }
2316                     os << style->stroke_dash.dash[i];
2317                     p += g_strlcpy(p, os.str().c_str(), c + BMAX - p);
2318                 }
2319                 if (p < c + BMAX) {
2320                     *p++ = ';';
2321                 }
2322             } else {
2323                 p += g_snprintf(p, c + BMAX - p, "stroke-dasharray:none;");
2324             }
2325         }
2327         /** \todo fixme: */
2328         if (style->stroke_dashoffset_set) {
2329             Inkscape::CSSOStringStream os;
2330             os << "stroke-dashoffset:" << style->stroke_dash.offset << ";";
2331             p += g_strlcpy(p, os.str().c_str(), c + BMAX - p);
2332         } else if (flags == SP_STYLE_FLAG_ALWAYS) {
2333             p += g_snprintf(p, c + BMAX - p, "stroke-dashoffset:0;");
2334         }
2335     }
2337     bool marker_none = false;
2338     gchar *master = style->marker[SP_MARKER_LOC].value;
2339     if (style->marker[SP_MARKER_LOC].set) {
2340         p += g_snprintf(p, c + BMAX - p, "marker:%s;", style->marker[SP_MARKER_LOC].value);
2341     } else if (flags == SP_STYLE_FLAG_ALWAYS) {
2342         p += g_snprintf(p, c + BMAX - p, "marker:none;");
2343         marker_none = true;
2344     }
2345     if (style->marker[SP_MARKER_LOC_START].set 
2346        && (!master || strcmp(master, style->marker[SP_MARKER_LOC_START].value))) {
2347         p += g_snprintf(p, c + BMAX - p, "marker-start:%s;", style->marker[SP_MARKER_LOC_START].value);
2348     } else if (flags == SP_STYLE_FLAG_ALWAYS && !marker_none) {
2349         p += g_snprintf(p, c + BMAX - p, "marker-start:none;");
2350     }
2351     if (style->marker[SP_MARKER_LOC_MID].set
2352        && (!master || strcmp(master, style->marker[SP_MARKER_LOC_MID].value))) {
2353         p += g_snprintf(p, c + BMAX - p, "marker-mid:%s;", style->marker[SP_MARKER_LOC_MID].value);
2354     } else if (flags == SP_STYLE_FLAG_ALWAYS && !marker_none) {
2355         p += g_snprintf(p, c + BMAX - p, "marker-mid:none;");
2356     }
2357     if (style->marker[SP_MARKER_LOC_END].set
2358        && (!master || strcmp(master, style->marker[SP_MARKER_LOC_END].value))) {
2359         p += g_snprintf(p, c + BMAX - p, "marker-end:%s;", style->marker[SP_MARKER_LOC_END].value);
2360     } else if (flags == SP_STYLE_FLAG_ALWAYS && !marker_none) {
2361         p += g_snprintf(p, c + BMAX - p, "marker-end:none;");
2362     }
2364     p += sp_style_write_ienum(p, c + BMAX - p, "visibility", enum_visibility, &style->visibility, NULL, flags);
2365     p += sp_style_write_ienum(p, c + BMAX - p, "display", enum_display, &style->display, NULL, flags);
2366     p += sp_style_write_ienum(p, c + BMAX - p, "overflow", enum_overflow, &style->overflow, NULL, flags);
2368     /* filter: */
2369     p += sp_style_write_ifilter(p, c + BMAX - p, "filter", &style->filter, NULL, flags);
2371     p += sp_style_write_ienum(p, c + BMAX - p, "enable-background", enum_enable_background, &style->enable_background, NULL, flags);
2373     /* fixme: */
2374     p += sp_text_style_write(p, c + BMAX - p, style->text, flags);
2376     /* Get rid of trailing `;'. */
2377     if (p != c) {
2378         --p;
2379         if (*p == ';') {
2380             *p = '\0';
2381         }
2382     }
2384     return g_strdup(c);
2388 #define STYLE_BUF_MAX
2391 /**
2392  * Dumps style to CSS string, see sp_style_write_string()
2393  *
2394  * \pre from != NULL.
2395  * \pre to != NULL.
2396  * \post ret != NULL.
2397  */
2398 gchar *
2399 sp_style_write_difference(SPStyle const *const from, SPStyle const *const to)
2401     g_return_val_if_fail(from != NULL, NULL);
2402     g_return_val_if_fail(to != NULL, NULL);
2404     gchar c[BMAX], *p = c;
2405     *p = '\0';
2407     p += sp_style_write_ifontsize(p, c + BMAX - p, "font-size", &from->font_size, &to->font_size, SP_STYLE_FLAG_IFDIFF);
2408     p += sp_style_write_ienum(p, c + BMAX - p, "font-style", enum_font_style, &from->font_style, &to->font_style, SP_STYLE_FLAG_IFDIFF);
2409     p += sp_style_write_ienum(p, c + BMAX - p, "font-variant", enum_font_variant, &from->font_variant, &to->font_variant, SP_STYLE_FLAG_IFDIFF);
2410     p += sp_style_write_ienum(p, c + BMAX - p, "font-weight", enum_font_weight, &from->font_weight, &to->font_weight, SP_STYLE_FLAG_IFDIFF);
2411     p += sp_style_write_ienum(p, c + BMAX - p, "font-stretch", enum_font_stretch, &from->font_stretch, &to->font_stretch, SP_STYLE_FLAG_IFDIFF);
2413     /* Text */
2414     p += sp_style_write_ilength(p, c + BMAX - p, "text-indent", &from->text_indent, &to->text_indent, SP_STYLE_FLAG_IFDIFF);
2415     p += sp_style_write_ienum(p, c + BMAX - p, "text-align", enum_text_align, &from->text_align, &to->text_align, SP_STYLE_FLAG_IFDIFF);
2416     p += sp_style_write_itextdecoration(p, c + BMAX - p, "text-decoration", &from->text_decoration, &to->text_decoration, SP_STYLE_FLAG_IFDIFF);
2417     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "line-height", &from->line_height, &to->line_height, SP_STYLE_FLAG_IFDIFF);
2418     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "letter-spacing", &from->letter_spacing, &to->letter_spacing, SP_STYLE_FLAG_IFDIFF);
2419     p += sp_style_write_ilengthornormal(p, c + BMAX - p, "word-spacing", &from->word_spacing, &to->word_spacing, SP_STYLE_FLAG_IFDIFF);
2420     p += sp_style_write_ienum(p, c + BMAX - p, "text-transform", enum_text_transform, &from->text_transform, &to->text_transform, SP_STYLE_FLAG_IFDIFF);
2421     p += sp_style_write_ienum(p, c + BMAX - p, "direction", enum_direction, &from->direction, &to->direction, SP_STYLE_FLAG_IFDIFF);
2422     p += sp_style_write_ienum(p, c + BMAX - p, "block-progression", enum_block_progression, &from->block_progression, &to->block_progression, SP_STYLE_FLAG_IFDIFF);
2423     p += sp_style_write_ienum(p, c + BMAX - p, "writing-mode", enum_writing_mode, &from->writing_mode, &to->writing_mode, SP_STYLE_FLAG_IFDIFF);
2425     p += sp_style_write_ienum(p, c + BMAX - p, "text-anchor", enum_text_anchor, &from->text_anchor, &to->text_anchor, SP_STYLE_FLAG_IFDIFF);
2427     /// \todo fixme: Per type methods need default flag too
2428     if (from->opacity.set && from->opacity.value != SP_SCALE24_MAX) {
2429         p += sp_style_write_iscale24(p, c + BMAX - p, "opacity", &from->opacity, &to->opacity, SP_STYLE_FLAG_IFSET);
2430     }
2432     if (!from->color.noneSet) { // CSS does not permit "none" for color
2433         p += sp_style_write_ipaint(p, c + BMAX - p, "color", &from->color, &to->color, SP_STYLE_FLAG_IFSET);
2434     }
2436     p += sp_style_write_ipaint(p, c + BMAX - p, "fill", &from->fill, &to->fill, SP_STYLE_FLAG_IFDIFF);
2437     // if fill:none, skip writing fill properties
2438     if (!from->fill.noneSet) {
2439         p += sp_style_write_iscale24(p, c + BMAX - p, "fill-opacity", &from->fill_opacity, &to->fill_opacity, SP_STYLE_FLAG_IFDIFF);
2440         p += sp_style_write_ienum(p, c + BMAX - p, "fill-rule", enum_fill_rule, &from->fill_rule, &to->fill_rule, SP_STYLE_FLAG_IFDIFF);
2441     }
2443     p += sp_style_write_ipaint(p, c + BMAX - p, "stroke", &from->stroke, &to->stroke, SP_STYLE_FLAG_IFDIFF);
2445     // stroke width affects markers, so write it if there's stroke OR any markers
2446     if (!from->stroke.noneSet || 
2447         from->marker[SP_MARKER_LOC].set ||
2448         from->marker[SP_MARKER_LOC_START].set ||
2449         from->marker[SP_MARKER_LOC_MID].set || 
2450         from->marker[SP_MARKER_LOC_END].set) {
2451         p += sp_style_write_ilength(p, c + BMAX - p, "stroke-width", &from->stroke_width, &to->stroke_width, SP_STYLE_FLAG_IFDIFF);
2452     }
2454     // if stroke:none, skip writing stroke properties
2455     if (!from->stroke.noneSet) {
2456         p += sp_style_write_ienum(p, c + BMAX - p, "stroke-linecap", enum_stroke_linecap,
2457                                   &from->stroke_linecap, &to->stroke_linecap, SP_STYLE_FLAG_IFDIFF);
2458         p += sp_style_write_ienum(p, c + BMAX - p, "stroke-linejoin", enum_stroke_linejoin,
2459                                   &from->stroke_linejoin, &to->stroke_linejoin, SP_STYLE_FLAG_IFDIFF);
2460         p += sp_style_write_ifloat(p, c + BMAX - p, "stroke-miterlimit",
2461                                    &from->stroke_miterlimit, &to->stroke_miterlimit, SP_STYLE_FLAG_IFDIFF);
2462         /** \todo fixme: */
2463         if (from->stroke_dasharray_set) {
2464             if (from->stroke_dasharray_inherit) {
2465                 p += g_snprintf(p, c + BMAX - p, "stroke-dasharray:inherit;");
2466             } else if (from->stroke_dash.n_dash && from->stroke_dash.dash) {
2467                 p += g_snprintf(p, c + BMAX - p, "stroke-dasharray:");
2468                 for (gint i = 0; i < from->stroke_dash.n_dash; i++) {
2469                     Inkscape::CSSOStringStream os;
2470                     if (i) {
2471                         os << ", ";
2472                     }
2473                     os << from->stroke_dash.dash[i];
2474                     p += g_strlcpy(p, os.str().c_str(), c + BMAX - p);
2475                 }
2476                 p += g_snprintf(p, c + BMAX - p, ";");
2477             }
2478         }
2479         /* fixme: */
2480         if (from->stroke_dashoffset_set) {
2481             Inkscape::CSSOStringStream os;
2482             os << "stroke-dashoffset:" << from->stroke_dash.offset << ";";
2483             p += g_strlcpy(p, os.str().c_str(), c + BMAX - p);
2484         }
2485         p += sp_style_write_iscale24(p, c + BMAX - p, "stroke-opacity", &from->stroke_opacity, &to->stroke_opacity, SP_STYLE_FLAG_IFDIFF);
2486     }
2488     /* markers */
2489     gchar *master = from->marker[SP_MARKER_LOC].value;
2490     if (master != NULL) {
2491         p += g_snprintf(p, c + BMAX - p, "marker:%s;", master);
2492     }
2493     if (from->marker[SP_MARKER_LOC_START].value != NULL && (!master || strcmp(master, from->marker[SP_MARKER_LOC_START].value))) {
2494         p += g_snprintf(p, c + BMAX - p, "marker-start:%s;", from->marker[SP_MARKER_LOC_START].value);
2495     }
2496     if (from->marker[SP_MARKER_LOC_MID].value != NULL && (!master || strcmp(master, from->marker[SP_MARKER_LOC_MID].value))) {
2497         p += g_snprintf(p, c + BMAX - p, "marker-mid:%s;",   from->marker[SP_MARKER_LOC_MID].value);
2498     }
2499     if (from->marker[SP_MARKER_LOC_END].value != NULL && (!master || strcmp(master, from->marker[SP_MARKER_LOC_END].value))) {
2500         p += g_snprintf(p, c + BMAX - p, "marker-end:%s;",   from->marker[SP_MARKER_LOC_END].value);
2501     }
2503     p += sp_style_write_ienum(p, c + BMAX - p, "visibility", enum_visibility, &from->visibility, &to->visibility, SP_STYLE_FLAG_IFSET);
2504     p += sp_style_write_ienum(p, c + BMAX - p, "display", enum_display, &from->display, &to->display, SP_STYLE_FLAG_IFSET);
2505     p += sp_style_write_ienum(p, c + BMAX - p, "overflow", enum_overflow, &from->overflow, &to->overflow, SP_STYLE_FLAG_IFSET);
2507     /* filter: */
2508     p += sp_style_write_ifilter(p, c + BMAX - p, "filter", &from->filter, &to->filter, SP_STYLE_FLAG_IFDIFF);
2510     p += sp_style_write_ienum(p, c + BMAX - p, "enable-background", enum_enable_background, &from->enable_background, &to->enable_background, SP_STYLE_FLAG_IFSET);
2512     p += sp_text_style_write(p, c + BMAX - p, from->text, SP_STYLE_FLAG_IFDIFF);
2514     /** \todo
2515      * The reason we use IFSET rather than IFDIFF is the belief that the IFDIFF
2516      * flag is mainly only for attributes that don't handle explicit unset well.
2517      * We may need to revisit the behaviour of this routine.
2518      */
2520     /* Get rid of trailing `;'. */
2521     if (p != c) {
2522         --p;
2523         if (*p == ';') {
2524             *p = '\0';
2525         }
2526     }
2528     return g_strdup(c);
2533 /**
2534  * Reset all style properties.
2535  */
2536 static void
2537 sp_style_clear(SPStyle *style)
2539     g_return_if_fail(style != NULL);
2541     style->fill.clear();
2542     style->stroke.clear();
2543     sp_style_filter_clear(style);
2545     if (style->fill.value.href) {
2546         delete style->fill.value.href;
2547         style->fill.value.href = NULL;
2548     }
2549     if (style->stroke.value.href) {
2550         delete style->stroke.value.href;
2551         style->stroke.value.href = NULL;
2552     }
2553     if (style->filter.href) {
2554         delete style->filter.href;
2555         style->filter.href = NULL;
2556     }
2558     if (style->stroke_dash.dash) {
2559         g_free(style->stroke_dash.dash);
2560     }
2562     /** \todo fixme: Do that text manipulation via parents */
2563     SPObject *object = style->object;
2564     Document *document = style->document;
2565     gint const refcount = style->refcount;
2566     SPTextStyle *text = style->text;
2567     unsigned const text_private = style->text_private;
2569     memset(style, 0, sizeof(SPStyle));
2571     style->refcount = refcount;
2572     style->object = object;
2573     style->document = document;
2575     if (document) {
2576         style->filter.href = new SPFilterReference(document);
2577         style->filter.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style));
2579         style->fill.value.href = new SPPaintServerReference(document);
2580         style->fill.value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_fill_paint_server_ref_changed), style));
2582         style->stroke.value.href = new SPPaintServerReference(document);
2583         style->stroke.value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_stroke_paint_server_ref_changed), style));
2584     }
2586     style->text = text;
2587     style->text_private = text_private;
2589     style->text->font_specification.set = FALSE;
2590     style->text->font.set = FALSE;
2591     style->text->font_family.set = FALSE;
2593     style->font_size.set = FALSE;
2594     style->font_size.type = SP_FONT_SIZE_LITERAL;
2595     style->font_size.value = SP_CSS_FONT_SIZE_MEDIUM;
2596     style->font_size.computed = 12.0;
2597     style->font_style.set = FALSE;
2598     style->font_style.value = style->font_style.computed = SP_CSS_FONT_STYLE_NORMAL;
2599     style->font_variant.set = FALSE;
2600     style->font_variant.value = style->font_variant.computed = SP_CSS_FONT_VARIANT_NORMAL;
2601     style->font_weight.set = FALSE;
2602     style->font_weight.value = SP_CSS_FONT_WEIGHT_NORMAL;
2603     style->font_weight.computed = SP_CSS_FONT_WEIGHT_400;
2604     style->font_stretch.set = FALSE;
2605     style->font_stretch.value = style->font_stretch.computed = SP_CSS_FONT_STRETCH_NORMAL;
2607     /* text */
2608     style->text_indent.set = FALSE;
2609     style->text_indent.unit = SP_CSS_UNIT_NONE;
2610     style->text_indent.computed = 0.0;
2612     style->text_align.set = FALSE;
2613     style->text_align.value = style->text_align.computed = SP_CSS_TEXT_ALIGN_START;
2615     style->text_decoration.set = FALSE;
2616     style->text_decoration.underline = FALSE;
2617     style->text_decoration.overline = FALSE;
2618     style->text_decoration.line_through = FALSE;
2619     style->text_decoration.blink = FALSE;
2621     style->line_height.set = FALSE;
2622     style->line_height.unit = SP_CSS_UNIT_PERCENT;
2623     style->line_height.normal = TRUE;
2624     style->line_height.value = style->line_height.computed = 1.0;
2626     style->letter_spacing.set = FALSE;
2627     style->letter_spacing.unit = SP_CSS_UNIT_NONE;
2628     style->letter_spacing.normal = TRUE;
2629     style->letter_spacing.value = style->letter_spacing.computed = 0.0;
2631     style->word_spacing.set = FALSE;
2632     style->word_spacing.unit = SP_CSS_UNIT_NONE;
2633     style->word_spacing.normal = TRUE;
2634     style->word_spacing.value = style->word_spacing.computed = 0.0;
2636     style->text_transform.set = FALSE;
2637     style->text_transform.value = style->text_transform.computed = SP_CSS_TEXT_TRANSFORM_NONE;
2639     style->direction.set = FALSE;
2640     style->direction.value = style->direction.computed = SP_CSS_DIRECTION_LTR;
2642     style->block_progression.set = FALSE;
2643     style->block_progression.value = style->block_progression.computed = SP_CSS_BLOCK_PROGRESSION_TB;
2645     style->writing_mode.set = FALSE;
2646     style->writing_mode.value = style->writing_mode.computed = SP_CSS_WRITING_MODE_LR_TB;
2649     style->text_anchor.set = FALSE;
2650     style->text_anchor.value = style->text_anchor.computed = SP_CSS_TEXT_ANCHOR_START;
2653     style->opacity.value = SP_SCALE24_MAX;
2654     style->visibility.set = FALSE;
2655     style->visibility.value = style->visibility.computed = SP_CSS_VISIBILITY_VISIBLE;
2656     style->display.set = FALSE;
2657     style->display.value = style->display.computed = SP_CSS_DISPLAY_INLINE;
2658     style->overflow.set = FALSE;
2659     style->overflow.value = style->overflow.computed = SP_CSS_OVERFLOW_VISIBLE;
2661     style->color.clear();
2662     style->color.setColor(0.0, 0.0, 0.0);
2664     style->fill.clear();
2665     style->fill.setColor(0.0, 0.0, 0.0);
2666     style->fill_opacity.value = SP_SCALE24_MAX;
2667     style->fill_rule.value = style->fill_rule.computed = SP_WIND_RULE_NONZERO;
2669     style->stroke.clear();
2670     style->stroke_opacity.value = SP_SCALE24_MAX;
2672     style->stroke_width.set = FALSE;
2673     style->stroke_width.unit = SP_CSS_UNIT_NONE;
2674     style->stroke_width.computed = 1.0;
2676     style->stroke_linecap.set = FALSE;
2677     style->stroke_linecap.value = style->stroke_linecap.computed = SP_STROKE_LINECAP_BUTT;
2678     style->stroke_linejoin.set = FALSE;
2679     style->stroke_linejoin.value = style->stroke_linejoin.computed = SP_STROKE_LINEJOIN_MITER;
2681     style->stroke_miterlimit.set = FALSE;
2682     style->stroke_miterlimit.value = 4.0;
2684     style->stroke_dash.n_dash = 0;
2685     style->stroke_dash.dash = NULL;
2686     style->stroke_dash.offset = 0.0;
2688     for (unsigned i = SP_MARKER_LOC; i < SP_MARKER_LOC_QTY; i++) {
2689         g_free(style->marker[i].value);
2690         style->marker[i].set = FALSE;
2691     }
2693     style->enable_background.value = SP_CSS_BACKGROUND_ACCUMULATE;
2694     style->enable_background.set = false;
2695     style->enable_background.inherit = false;
2700 /**
2701  *
2702  */
2703 static void
2704 sp_style_read_dash(SPStyle *style, gchar const *str)
2706     /* Ref: http://www.w3.org/TR/SVG11/painting.html#StrokeDasharrayProperty */
2707     style->stroke_dasharray_set = TRUE;
2709     if (strcmp(str, "inherit") == 0) {
2710         style->stroke_dasharray_inherit = true;
2711         return;
2712     }
2713     style->stroke_dasharray_inherit = false;
2715     NRVpathDash &dash = style->stroke_dash;
2716     g_free(dash.dash);
2717     dash.dash = NULL;
2719     if (strcmp(str, "none") == 0) {
2720         dash.n_dash = 0;
2721         return;
2722     }
2724     gint n_dash = 0;
2725     gdouble d[64];
2726     gchar *e = NULL;
2728     bool LineSolid=true;
2729     while (e != str && n_dash < 64) {
2730         /* TODO: Should allow <length> rather than just a unitless (px) number. */
2731         d[n_dash] = g_ascii_strtod(str, (char **) &e);
2732         if (d[n_dash] > 0.00000001)
2733             LineSolid = false;
2734         if (e != str) {
2735             n_dash += 1;
2736             str = e;
2737         }
2738         while (str && *str && !isalnum(*str)) str += 1;
2739     }
2741     if (LineSolid) {
2742         dash.n_dash = 0;
2743         return;
2744     }
2746     if (n_dash > 0) {
2747         dash.dash = g_new(gdouble, n_dash);
2748         memcpy(dash.dash, d, sizeof(gdouble) * n_dash);
2749         dash.n_dash = n_dash;
2750     }
2754 /*#########################
2755 ## SPTextStyle operations
2756 #########################*/
2759 /**
2760  * Return new SPTextStyle object with default settings.
2761  */
2762 static SPTextStyle *
2763 sp_text_style_new()
2765     SPTextStyle *ts = g_new0(SPTextStyle, 1);
2766     ts->refcount = 1;
2767     sp_text_style_clear(ts);
2769     ts->font_specification.value = g_strdup("Bitstream Vera Sans");
2770     ts->font.value = g_strdup("Bitstream Vera Sans");
2771     ts->font_family.value = g_strdup("Bitstream Vera Sans");
2773     return ts;
2777 /**
2778  * Clear text style settings.
2779  */
2780 static void
2781 sp_text_style_clear(SPTextStyle *ts)
2783     ts->font_specification.set = FALSE;
2784     ts->font.set = FALSE;
2785     ts->font_family.set = FALSE;
2790 /**
2791  * Reduce refcount of text style and possibly free it.
2792  */
2793 static SPTextStyle *
2794 sp_text_style_unref(SPTextStyle *st)
2796     st->refcount -= 1;
2798     if (st->refcount < 1) {
2799         g_free(st->font_specification.value);
2800         g_free(st->font.value);
2801         g_free(st->font_family.value);
2802         g_free(st);
2803     }
2805     return NULL;
2810 /**
2811  * Return duplicate of text style.
2812  */
2813 static SPTextStyle *
2814 sp_text_style_duplicate_unset(SPTextStyle *st)
2816     SPTextStyle *nt = g_new0(SPTextStyle, 1);
2817     nt->refcount = 1;
2819     nt->font_specification.value = g_strdup(st->font_specification.value);
2820     nt->font.value = g_strdup(st->font.value);
2821     nt->font_family.value = g_strdup(st->font_family.value);
2823     return nt;
2828 /**
2829  * Write SPTextStyle object into string.
2830  */
2831 static guint
2832 sp_text_style_write(gchar *p, guint const len, SPTextStyle const *const st, guint flags)
2834     gint d = 0;
2836     // We do not do diffing for text style
2837     if (flags == SP_STYLE_FLAG_IFDIFF)
2838         flags = SP_STYLE_FLAG_IFSET;
2840     d += sp_style_write_istring(p + d, len - d, "font-family", &st->font_family, NULL, flags);
2841     d += sp_style_write_istring(p + d, len - d, "-inkscape-font-specification", &st->font_specification, NULL, flags);
2842     return d;
2847 /* The following sp_tyle_read_* functions ignore invalid values, as per
2848  * http://www.w3.org/TR/REC-CSS2/syndata.html#parsing-errors.
2849  *
2850  * [However, the SVG spec is somewhat unclear as to whether the style attribute should
2851  * be handled as per CSS2 rules or whether it must simply be a set of PROPERTY:VALUE
2852  * pairs, in which case SVG's error-handling rules
2853  * http://www.w3.org/TR/SVG11/implnote.html#ErrorProcessing should instead be applied.]
2854  */
2857 /**
2858  * Set SPIFloat object from string.
2859  */
2860 static void
2861 sp_style_read_ifloat(SPIFloat *val, gchar const *str)
2863     if (!strcmp(str, "inherit")) {
2864         val->set = TRUE;
2865         val->inherit = TRUE;
2866     } else {
2867         gfloat value;
2868         if (sp_svg_number_read_f(str, &value)) {
2869             val->set = TRUE;
2870             val->inherit = FALSE;
2871             val->value = value;
2872         }
2873     }
2878 /**
2879  * Set SPIScale24 object from string.
2880  */
2881 static void
2882 sp_style_read_iscale24(SPIScale24 *val, gchar const *str)
2884     if (!strcmp(str, "inherit")) {
2885         val->set = TRUE;
2886         val->inherit = TRUE;
2887     } else {
2888         gfloat value;
2889         if (sp_svg_number_read_f(str, &value)) {
2890             val->set = TRUE;
2891             val->inherit = FALSE;
2892             value = CLAMP(value, 0.0, 1.0);
2893             val->value = SP_SCALE24_FROM_FLOAT(value);
2894         }
2895     }
2898 /**
2899  * Reads a style value and performs lookup based on the given style value enumerations.
2900  */
2901 static void
2902 sp_style_read_ienum(SPIEnum *val, gchar const *str, SPStyleEnum const *dict,
2903                     bool const can_explicitly_inherit)
2905     if ( can_explicitly_inherit && !strcmp(str, "inherit") ) {
2906         val->set = TRUE;
2907         val->inherit = TRUE;
2908     } else {
2909         for (unsigned i = 0; dict[i].key; i++) {
2910             if (!strcmp(str, dict[i].key)) {
2911                 val->set = TRUE;
2912                 val->inherit = FALSE;
2913                 val->value = dict[i].value;
2914                 /* Save copying for values not needing it */
2915                 val->computed = val->value;
2916                 break;
2917             }
2918         }
2919     }
2924 /**
2925  * Set SPIString object from string.
2926  */
2927 static void
2928 sp_style_read_istring(SPIString *val, gchar const *str)
2930     g_free(val->value);
2932     if (!strcmp(str, "inherit")) {
2933         val->set = TRUE;
2934         val->inherit = TRUE;
2935         val->value = NULL;
2936     } else {
2937         val->set = TRUE;
2938         val->inherit = FALSE;
2939         val->value = g_strdup(str);
2940     }
2945 /**
2946  * Set SPILength object from string.
2947  */
2948 static void
2949 sp_style_read_ilength(SPILength *val, gchar const *str)
2951     if (!strcmp(str, "inherit")) {
2952         val->set = TRUE;
2953         val->inherit = TRUE;
2954     } else {
2955         gdouble value;
2956         gchar *e;
2957         /** \todo fixme: Move this to standard place (Lauris) */
2958         value = g_ascii_strtod(str, &e);
2959         if ((gchar const *) e != str) {
2960             /** \todo
2961              * Allow the number of px per inch to vary (document preferences,
2962              * X server or whatever).  E.g. don't fill in computed here, do
2963              * it at the same time as percentage units are done.
2964              */
2965             if (!*e) {
2966                 /* Userspace */
2967                 val->unit = SP_CSS_UNIT_NONE;
2968                 val->computed = value;
2969             } else if (!strcmp(e, "px")) {
2970                 /* Userspace */
2971                 val->unit = SP_CSS_UNIT_PX;
2972                 val->computed = value;
2973             } else if (!strcmp(e, "pt")) {
2974                 /* Userspace / DEVICESCALE */
2975                 val->unit = SP_CSS_UNIT_PT;
2976                 val->computed = value * PX_PER_PT;
2977             } else if (!strcmp(e, "pc")) {
2978                 /* 1 pica = 12pt; FIXME: add it to SPUnit */
2979                 val->unit = SP_CSS_UNIT_PC;
2980                 val->computed = value * PX_PER_PT * 12;
2981             } else if (!strcmp(e, "mm")) {
2982                 val->unit = SP_CSS_UNIT_MM;
2983                 val->computed = value * PX_PER_MM;
2984             } else if (!strcmp(e, "cm")) {
2985                 val->unit = SP_CSS_UNIT_CM;
2986                 val->computed = value * PX_PER_CM;
2987             } else if (!strcmp(e, "in")) {
2988                 val->unit = SP_CSS_UNIT_IN;
2989                 val->computed = value * PX_PER_IN;
2990             } else if (!strcmp(e, "em")) {
2991                 /* EM square */
2992                 val->unit = SP_CSS_UNIT_EM;
2993                 val->value = value;
2994             } else if (!strcmp(e, "ex")) {
2995                 /* ex square */
2996                 val->unit = SP_CSS_UNIT_EX;
2997                 val->value = value;
2998             } else if (!strcmp(e, "%")) {
2999                 /* Percentage */
3000                 val->unit = SP_CSS_UNIT_PERCENT;
3001                 val->value = value * 0.01;
3002             } else {
3003                 /* Invalid */
3004                 return;
3005             }
3006             val->set = TRUE;
3007             val->inherit = FALSE;
3008         }
3009     }
3012 /**
3013  * Set SPILengthOrNormal object from string.
3014  */
3015 static void
3016 sp_style_read_ilengthornormal(SPILengthOrNormal *val, gchar const *str)
3018     if (!strcmp(str, "normal")) {
3019         val->set = TRUE;
3020         val->inherit = FALSE;
3021         val->normal = TRUE;
3022         val->unit = SP_CSS_UNIT_NONE;
3023         val->value = val->computed = 0.0;
3024     } else {
3025         SPILength length;
3026         sp_style_read_ilength(&length, str);
3027         val->set = length.set;
3028         val->inherit = length.inherit;
3029         val->normal = FALSE;
3030         val->unit = length.unit;
3031         val->value = length.value;
3032         val->computed = length.computed;
3033     }
3036 /**
3037  * Set SPITextDecoration object from string.
3038  */
3039 static void
3040 sp_style_read_itextdecoration(SPITextDecoration *val, gchar const *str)
3042     if (!strcmp(str, "inherit")) {
3043         val->set = TRUE;
3044         val->inherit = TRUE;
3045     } else if (!strcmp(str, "none")) {
3046         val->set = TRUE;
3047         val->inherit = FALSE;
3048         val->underline = FALSE;
3049         val->overline = FALSE;
3050         val->line_through = FALSE;
3051         val->blink = FALSE;
3052     } else {
3053         bool found_underline = false;
3054         bool found_overline = false;
3055         bool found_line_through = false;
3056         bool found_blink = false;
3057         for ( ; *str ; str++ ) {
3058             if (*str == ' ') continue;
3059             if (strneq(str, "underline", 9) && (str[9] == ' ' || str[9] == '\0')) {
3060                 found_underline = true;
3061                 str += 9;
3062             } else if (strneq(str, "overline", 8) && (str[8] == ' ' || str[8] == '\0')) {
3063                 found_overline = true;
3064                 str += 8;
3065             } else if (strneq(str, "line-through", 12) && (str[12] == ' ' || str[12] == '\0')) {
3066                 found_line_through = true;
3067                 str += 12;
3068             } else if (strneq(str, "blink", 5) && (str[5] == ' ' || str[5] == '\0')) {
3069                 found_blink = true;
3070                 str += 5;
3071             } else {
3072                 return;  // invalid value
3073             }
3074         }
3075         if (!(found_underline || found_overline || found_line_through || found_blink)) {
3076             return;  // invalid value: empty
3077         }
3078         val->set = TRUE;
3079         val->inherit = FALSE;
3080         val->underline = found_underline;
3081         val->overline = found_overline;
3082         val->line_through = found_line_through;
3083         val->blink = found_blink;
3084     }
3087 /**
3088  * Set SPIPaint object from string containing an integer value.
3089  * \param document Ignored
3090  */
3091 static void
3092 sp_style_read_icolor(SPIPaint *paint, gchar const *str, SPStyle *style, Document *document)
3094     (void)style; // TODO
3095     (void)document; // TODO
3096     paint->currentcolor = FALSE;  /* currentColor not a valid <color>. */
3097     if (!strcmp(str, "inherit")) {
3098         paint->set = TRUE;
3099         paint->inherit = TRUE;
3100     } else {
3101         guint32 const rgb0 = sp_svg_read_color(str, 0xff);
3102         if (rgb0 != 0xff) {
3103             paint->setColor(rgb0);
3104             paint->set = TRUE;
3105             paint->inherit = FALSE;
3106         }
3107     }
3111 /**
3112  * Set SPIPaint object from string.
3113  *
3114  * \pre paint == \&style.fill || paint == \&style.stroke.
3115  */
3116 static void
3117 sp_style_read_ipaint(SPIPaint *paint, gchar const *str, SPStyle *style, Document *document)
3119     while (g_ascii_isspace(*str)) {
3120         ++str;
3121     }
3123     paint->clear();
3125     if (streq(str, "inherit")) {
3126         paint->set = TRUE;
3127         paint->inherit = TRUE;
3128     } else {
3129         if ( strneq(str, "url", 3) ) {
3130             gchar *uri = extract_uri( str, &str );
3131             while ( g_ascii_isspace(*str) ) {
3132                 ++str;
3133             }
3134             // TODO check on and comment the comparrison "paint != &style->color".
3135             if ( uri && *uri && (paint != &style->color) ) {
3136                 paint->set = TRUE;
3138                 // it may be that this style's SPIPaint has not yet created its URIReference;
3139                 // now that we have a document, we can create it here
3140                 if (!paint->value.href && document) {
3141                     paint->value.href = new SPPaintServerReference(document);
3142                     paint->value.href->changedSignal().connect(sigc::bind(sigc::ptr_fun((paint == &style->fill)? sp_style_fill_paint_server_ref_changed : sp_style_stroke_paint_server_ref_changed), style));
3143                 }
3145                 // TODO check what this does in light of move away from union
3146                 sp_style_set_ipaint_to_uri_string (style, paint, uri);
3147             }
3148             g_free( uri );
3149         }
3151         if (streq(str, "currentColor") && paint != &style->color) {
3152             paint->set = TRUE;
3153             paint->currentcolor = TRUE;
3154         } else if (streq(str, "none") && paint != &style->color) {
3155             paint->set = TRUE;
3156             paint->noneSet = TRUE;
3157         } else {
3158             guint32 const rgb0 = sp_svg_read_color(str, &str, 0xff);
3159             if (rgb0 != 0xff) {
3160                 paint->setColor( rgb0 );
3161                 paint->set = TRUE;
3163                 while (g_ascii_isspace(*str)) {
3164                     ++str;
3165                 }
3166                 if (strneq(str, "icc-color(", 10)) {
3167                     SVGICCColor* tmp = new SVGICCColor();
3168                     if ( ! sp_svg_read_icc_color( str, &str, tmp ) ) {
3169                         delete tmp;
3170                         tmp = 0;
3171                     }
3172                     paint->value.color.icc = tmp;
3173                 }
3174             }
3175         }
3176     }
3181 /**
3182  * Set SPIFontSize object from string.
3183  */
3184 static void
3185 sp_style_read_ifontsize(SPIFontSize *val, gchar const *str)
3187     if (!strcmp(str, "inherit")) {
3188         val->set = TRUE;
3189         val->inherit = TRUE;
3190     } else if ((*str == 'x') || (*str == 's') || (*str == 'm') || (*str == 'l')) {
3191         for (unsigned i = 0; enum_font_size[i].key; i++) {
3192             if (!strcmp(str, enum_font_size[i].key)) {
3193                 val->set = TRUE;
3194                 val->inherit = FALSE;
3195                 val->type = SP_FONT_SIZE_LITERAL;
3196                 val->value = enum_font_size[i].value;
3197                 return;
3198             }
3199         }
3200         /* Invalid */
3201         return;
3202     } else {
3203         gdouble value;
3204         gchar *e;
3205         /* fixme: Move this to standard place (Lauris) */
3206         value = g_ascii_strtod(str, &e);
3207         if ((gchar const *) e != str) {
3208             if (!*e) {
3209                 /* Userspace */
3210             } else if (!strcmp(e, "px")) {
3211                 /* Userspace */
3212             } else if (!strcmp(e, "pt")) {
3213                 /* Userspace * DEVICESCALE */
3214                 value *= PX_PER_PT;
3215             } else if (!strcmp(e, "pc")) {
3216                 /* 12pt */
3217                 value *= PX_PER_PT * 12.0;
3218             } else if (!strcmp(e, "mm")) {
3219                 value *= PX_PER_MM;
3220             } else if (!strcmp(e, "cm")) {
3221                 value *= PX_PER_CM;
3222             } else if (!strcmp(e, "in")) {
3223                 value *= PX_PER_IN;
3224             } else if (!strcmp(e, "%")) {
3225                 /* Percentage */
3226                 val->set = TRUE;
3227                 val->inherit = FALSE;
3228                 val->type = SP_FONT_SIZE_PERCENTAGE;
3229                 val->value = SP_F8_16_FROM_FLOAT(value / 100.0);
3230                 return;
3231             } else {
3232                 /* Invalid */
3233                 return;
3234             }
3235             /* Length */
3236             val->set = TRUE;
3237             val->inherit = FALSE;
3238             val->type = SP_FONT_SIZE_LENGTH;
3239             val->computed = value;
3240             return;
3241         }
3242     }
3247 /**
3248  * Set SPIFilter object from string.
3249  */
3250 static void
3251 sp_style_read_ifilter(gchar const *str, SPStyle * style, Document *document)
3253     SPIFilter *f = &(style->filter);
3254     /* Try all possible values: inherit, none, uri */
3255     if (streq(str, "inherit")) {
3256         f->set = TRUE;
3257         f->inherit = TRUE;
3258         if (f->href && f->href->getObject())
3259             f->href->detach(); 
3260     } else if(streq(str, "none")) {
3261         f->set = TRUE;
3262         f->inherit = FALSE;
3263         if (f->href && f->href->getObject())
3264            f->href->detach(); 
3265     } else if (strneq(str, "url", 3)) {
3266         char *uri = extract_uri(str);
3267         if(uri == NULL || uri[0] == '\0') {
3268             g_warning("Specified filter url is empty");
3269             f->set = TRUE;
3270             f->inherit = FALSE;
3271             return;
3272         }
3273         f->set = TRUE;
3274         f->inherit = FALSE;
3275         if (f->href && f->href->getObject())
3276             f->href->detach();
3278         // it may be that this style has not yet created its SPFilterReference;
3279         // now that we have a document, we can create it here
3280         if (!f->href && document) {
3281             f->href = new SPFilterReference(document);
3282             f->href->changedSignal().connect(sigc::bind(sigc::ptr_fun(sp_style_filter_ref_changed), style));
3283         }
3285         try {
3286             f->href->attach(Inkscape::URI(uri));
3287         } catch (Inkscape::BadURIException &e) {
3288             g_warning("%s", e.what());
3289             f->href->detach();
3290         }
3291         g_free (uri);
3293     } else {
3294         /* We shouldn't reach this if SVG input is well-formed */
3295         f->set = FALSE;
3296         f->inherit = FALSE;
3297         if (f->href && f->href->getObject())
3298             f->href->detach(); 
3299     }
3302 /**
3303  * Set SPIEnum object from repr attribute.
3304  */
3305 static void
3306 sp_style_read_penum(SPIEnum *val, Inkscape::XML::Node *repr,
3307                     gchar const *key, SPStyleEnum const *dict,
3308                     bool const can_explicitly_inherit)
3310     gchar const *str = repr->attribute(key);
3311     if (str) {
3312         sp_style_read_ienum(val, str, dict, can_explicitly_inherit);
3313     }
3318 /**
3319  * Set SPILength object from repr attribute.
3320  */
3321 static void
3322 sp_style_read_plength(SPILength *val, Inkscape::XML::Node *repr, gchar const *key)
3324     gchar const *str = repr->attribute(key);
3325     if (str) {
3326         sp_style_read_ilength(val, str);
3327     }
3330 /**
3331  * Set SPIFontSize object from repr attribute.
3332  */
3333 static void
3334 sp_style_read_pfontsize(SPIFontSize *val, Inkscape::XML::Node *repr, gchar const *key)
3336     gchar const *str = repr->attribute(key);
3337     if (str) {
3338         sp_style_read_ifontsize(val, str);
3339     }
3343 /**
3344  * Set SPIFloat object from repr attribute.
3345  */
3346 static void
3347 sp_style_read_pfloat(SPIFloat *val, Inkscape::XML::Node *repr, gchar const *key)
3349     gchar const *str = repr->attribute(key);
3350     if (str) {
3351         sp_style_read_ifloat(val, str);
3352     }
3356 /**
3357  * Write SPIFloat object into string.
3358  */
3359 static gint
3360 sp_style_write_ifloat(gchar *p, gint const len, gchar const *const key,
3361                       SPIFloat const *const val, SPIFloat const *const base, guint const flags)
3363     Inkscape::CSSOStringStream os;
3365     if ((flags & SP_STYLE_FLAG_ALWAYS)
3366         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3367         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3368             && (!base->set || (val->value != base->value))))
3369     {
3370         if (val->inherit) {
3371             return g_snprintf(p, len, "%s:inherit;", key);
3372         } else {
3373             os << key << ":" << val->value << ";";
3374             return g_strlcpy(p, os.str().c_str(), len);
3375         }
3376     }
3377     return 0;
3381 /**
3382  * Write SPIScale24 object into string.
3383  */
3384 static gint
3385 sp_style_write_iscale24(gchar *p, gint const len, gchar const *const key,
3386                         SPIScale24 const *const val, SPIScale24 const *const base,
3387                         guint const flags)
3389     Inkscape::CSSOStringStream os;
3391     if ((flags & SP_STYLE_FLAG_ALWAYS)
3392         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3393         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3394             && (!base->set || (val->value != base->value))))
3395     {
3396         if (val->inherit) {
3397             return g_snprintf(p, len, "%s:inherit;", key);
3398         } else {
3399             os << key << ":" << SP_SCALE24_TO_FLOAT(val->value) << ";";
3400             return g_strlcpy(p, os.str().c_str(), len);
3401         }
3402     }
3403     return 0;
3407 /**
3408  * Write SPIEnum object into string.
3409  */
3410 static gint
3411 sp_style_write_ienum(gchar *p, gint const len, gchar const *const key,
3412                      SPStyleEnum const *const dict,
3413                      SPIEnum const *const val, SPIEnum const *const base, guint const flags)
3415     if ((flags & SP_STYLE_FLAG_ALWAYS)
3416         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3417         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3418             && (!base->set || (val->computed != base->computed))))
3419     {
3420         if (val->inherit) {
3421             return g_snprintf(p, len, "%s:inherit;", key);
3422         }
3423         for (unsigned i = 0; dict[i].key; i++) {
3424             if (dict[i].value == static_cast< gint > (val->value) ) {
3425                 return g_snprintf(p, len, "%s:%s;", key, dict[i].key);
3426             }
3427         }
3428     }
3429     return 0;
3434 /**
3435  * Write SPIString object into string.
3436  */
3437 static gint
3438 sp_style_write_istring(gchar *p, gint const len, gchar const *const key,
3439                        SPIString const *const val, SPIString const *const base, guint const flags)
3441     if ((flags & SP_STYLE_FLAG_ALWAYS)
3442         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3443         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3444             && (!base->set || strcmp(val->value, base->value))))
3445     {
3446         if (val->inherit) {
3447             return g_snprintf(p, len, "%s:inherit;", key);
3448         } else {
3449             gchar *val_quoted = css2_escape_quote(val->value);
3450             if (val_quoted) {
3451                 return g_snprintf(p, len, "%s:%s;", key, val_quoted);
3452                 g_free (val_quoted);
3453             }
3454         }
3455     }
3456     return 0;
3460 /**
3461  *
3462  */
3463 static bool
3464 sp_length_differ(SPILength const *const a, SPILength const *const b)
3466     if (a->unit != b->unit) {
3467         if (a->unit == SP_CSS_UNIT_EM) return true;
3468         if (a->unit == SP_CSS_UNIT_EX) return true;
3469         if (a->unit == SP_CSS_UNIT_PERCENT) return true;
3470         if (b->unit == SP_CSS_UNIT_EM) return true;
3471         if (b->unit == SP_CSS_UNIT_EX) return true;
3472         if (b->unit == SP_CSS_UNIT_PERCENT) return true;
3473     }
3475     return (a->computed != b->computed);
3480 /**
3481  * Write SPILength object into string.
3482  */
3483 static gint
3484 sp_style_write_ilength(gchar *p, gint const len, gchar const *const key,
3485                        SPILength const *const val, SPILength const *const base, guint const flags)
3487     Inkscape::CSSOStringStream os;
3489     if ((flags & SP_STYLE_FLAG_ALWAYS)
3490         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3491         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3492             && (!base->set || sp_length_differ(val, base))))
3493     {
3494         if (val->inherit) {
3495             return g_snprintf(p, len, "%s:inherit;", key);
3496         } else {
3497             switch (val->unit) {
3498                 case SP_CSS_UNIT_NONE:
3499                     os << key << ":" << val->computed << ";";
3500                     return g_strlcpy(p, os.str().c_str(), len);
3501                     break;
3502                 case SP_CSS_UNIT_PX:
3503                     os << key << ":" << val->computed << "px;";
3504                     return g_strlcpy(p, os.str().c_str(), len);
3505                     break;
3506                 case SP_CSS_UNIT_PT:
3507                     os << key << ":" << val->computed * PT_PER_PX << "pt;";
3508                     return g_strlcpy(p, os.str().c_str(), len);
3509                     break;
3510                 case SP_CSS_UNIT_PC:
3511                     os << key << ":" << val->computed * PT_PER_PX / 12.0 << "pc;";
3512                     return g_strlcpy(p, os.str().c_str(), len);
3513                     break;
3514                 case SP_CSS_UNIT_MM:
3515                     os << key << ":" << val->computed * MM_PER_PX << "mm;";
3516                     return g_strlcpy(p, os.str().c_str(), len);
3517                     break;
3518                 case SP_CSS_UNIT_CM:
3519                     os << key << ":" << val->computed * CM_PER_PX << "cm;";
3520                     return g_strlcpy(p, os.str().c_str(), len);
3521                     break;
3522                 case SP_CSS_UNIT_IN:
3523                     os << key << ":" << val->computed * IN_PER_PX << "in;";
3524                     return g_strlcpy(p, os.str().c_str(), len);
3525                     break;
3526                 case SP_CSS_UNIT_EM:
3527                     os << key << ":" << val->value << "em;";
3528                     return g_strlcpy(p, os.str().c_str(), len);
3529                     break;
3530                 case SP_CSS_UNIT_EX:
3531                     os << key << ":" << val->value << "ex;";
3532                     return g_strlcpy(p, os.str().c_str(), len);
3533                     break;
3534                 case SP_CSS_UNIT_PERCENT:
3535                     os << key << ":" << (val->value * 100.0) << "%;";
3536                     return g_strlcpy(p, os.str().c_str(), len);
3537                     break;
3538                 default:
3539                     /* Invalid */
3540                     break;
3541             }
3542         }
3543     }
3544     return 0;
3548 /**
3549  *
3550  */
3551 static bool
3552 sp_lengthornormal_differ(SPILengthOrNormal const *const a, SPILengthOrNormal const *const b)
3554     if (a->normal != b->normal) return true;
3555     if (a->normal) return false;
3557     if (a->unit != b->unit) {
3558         if (a->unit == SP_CSS_UNIT_EM) return true;
3559         if (a->unit == SP_CSS_UNIT_EX) return true;
3560         if (a->unit == SP_CSS_UNIT_PERCENT) return true;
3561         if (b->unit == SP_CSS_UNIT_EM) return true;
3562         if (b->unit == SP_CSS_UNIT_EX) return true;
3563         if (b->unit == SP_CSS_UNIT_PERCENT) return true;
3564     }
3566     return (a->computed != b->computed);
3569 /**
3570  * Write SPILengthOrNormal object into string.
3571  */
3572 static gint
3573 sp_style_write_ilengthornormal(gchar *p, gint const len, gchar const *const key,
3574                                SPILengthOrNormal const *const val,
3575                                SPILengthOrNormal const *const base,
3576                                guint const flags)
3578     if ((flags & SP_STYLE_FLAG_ALWAYS)
3579         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3580         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3581             && (!base->set || sp_lengthornormal_differ(val, base))))
3582     {
3583         if (val->normal) {
3584             return g_snprintf(p, len, "%s:normal;", key);
3585         } else {
3586             SPILength length;
3587             length.set = val->set;
3588             length.inherit = val->inherit;
3589             length.unit = val->unit;
3590             length.value = val->value;
3591             length.computed = val->computed;
3592             return sp_style_write_ilength(p, len, key, &length, NULL, SP_STYLE_FLAG_ALWAYS);
3593         }
3594     }
3595     return 0;
3598 /**
3599  *
3600  */
3601 static bool
3602 sp_textdecoration_differ(SPITextDecoration const *const a, SPITextDecoration const *const b)
3604     return    a->underline != b->underline
3605            || a->overline != b->overline
3606            || a->line_through != b->line_through
3607            || a->blink != b->blink;
3610 /**
3611  * Write SPITextDecoration object into string.
3612  */
3613 static gint
3614 sp_style_write_itextdecoration(gchar *p, gint const len, gchar const *const key,
3615                                SPITextDecoration const *const val,
3616                                SPITextDecoration const *const base,
3617                                guint const flags)
3619     Inkscape::CSSOStringStream os;
3621     if ((flags & SP_STYLE_FLAG_ALWAYS)
3622         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3623         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3624             && (!base->set || sp_textdecoration_differ(val, base))))
3625     {
3626         if (val->inherit) {
3627             return g_snprintf(p, len, "%s:inherit;", key);
3628         } else {
3629             os << key << ":";
3630             if (val->underline || val->overline || val->line_through || val->blink) {
3631                 if (val->underline) os << " underline";
3632                 if (val->overline) os << " overline";
3633                 if (val->line_through) os << " line-through";
3634                 if (val->blink) os << " blink";
3635             } else
3636                 os << "none";
3637             os << ";";
3638             return g_strlcpy(p, os.str().c_str(), len);
3639         }
3640     }
3641     return 0;
3644 /**
3645  *
3646  */
3647 static bool
3648 sp_paint_differ(SPIPaint const *const a, SPIPaint const *const b)
3650     if ( (a->isColor() != b->isColor())
3651          || (a->isPaintserver() != b->isPaintserver())
3652          || (a->set != b->set)
3653          || (a->currentcolor != b->currentcolor)
3654          || (a->inherit!= b->inherit) ) {
3655         return true;
3656     }
3658     // TODO refactor to allow for mixed paints (rgb() *and* url(), etc)
3660     if ( a->isPaintserver() ) {
3661         return (a->value.href == NULL || b->value.href == NULL || a->value.href->getObject() != b->value.href->getObject());
3662     }
3664     if ( a->isColor() ) {
3665         return !( (a->value.color == b->value.color)
3666                  && ((a->value.color.icc == b->value.color.icc)
3667                      || (a->value.color.icc && b->value.color.icc
3668                          && (a->value.color.icc->colorProfile == b->value.color.icc->colorProfile)
3669                          && (a->value.color.icc->colors == b->value.color.icc->colors))));
3670     /* todo: Allow for epsilon differences in iccColor->colors, e.g. changes small enough not to show up
3671      * in the string representation. */
3672     }
3674     return false;
3679 /**
3680  * Write SPIPaint object into string.
3681  */
3682 static gint
3683 sp_style_write_ipaint(gchar *b, gint const len, gchar const *const key,
3684                       SPIPaint const *const paint, SPIPaint const *const base, guint const flags)
3686     int retval = 0;
3688     if ((flags & SP_STYLE_FLAG_ALWAYS)
3689         || ((flags & SP_STYLE_FLAG_IFSET) && paint->set)
3690         || ((flags & SP_STYLE_FLAG_IFDIFF) && paint->set
3691             && (!base->set || sp_paint_differ(paint, base))))
3692     {
3693         CSSOStringStream css;
3695         if (paint->inherit) {
3696             css << "inherit";
3697         } else {
3698             if ( paint->value.href && paint->value.href->getURI() ) {
3699                 const gchar* uri = paint->value.href->getURI()->toString();
3700                 css << "url(" << uri << ")";
3701             }
3703             if ( paint->noneSet ) {
3704                 if ( !css.str().empty() ) {
3705                     css << " ";
3706                 }
3707                 css << "none";
3708             }
3710             if ( paint->currentcolor ) {
3711                 if ( !css.str().empty() ) {
3712                     css << " ";
3713                 }
3714                 css << "currentColor";
3715             }
3717             if ( paint->colorSet && !paint->currentcolor ) {
3718                 if ( !css.str().empty() ) {
3719                     css << " ";
3720                 }
3721                 char color_buf[8];
3722                 sp_svg_write_color(color_buf, sizeof(color_buf), paint->value.color.toRGBA32( 0 ));
3723                 css << color_buf;
3724             }
3726             if (paint->value.color.icc && !paint->currentcolor) {
3727                 if ( !css.str().empty() ) {
3728                     css << " ";
3729                 }
3730                 css << "icc-color(" << paint->value.color.icc->colorProfile;
3731                 for (vector<double>::const_iterator i(paint->value.color.icc->colors.begin()),
3732                          iEnd(paint->value.color.icc->colors.end());
3733                      i != iEnd; ++i) {
3734                     css << ", " << *i;
3735                 }
3736                 css << ')';
3737             }
3738         }
3740         if ( !css.str().empty() ) {
3741             retval = g_snprintf( b, len, "%s:%s;", key, css.str().c_str() );
3742         }
3743     }
3745     return retval;
3749 /**
3750  *
3751  */
3752 static bool
3753 sp_fontsize_differ(SPIFontSize const *const a, SPIFontSize const *const b)
3755     if (a->type != b->type)
3756         return true;
3757     if (a->type == SP_FONT_SIZE_LENGTH) {
3758         if (a->computed != b->computed)
3759             return true;
3760     } else {
3761         if (a->value != b->value)
3762             return true;
3763     }
3764     return false;
3768 /**
3769  * Write SPIFontSize object into string.
3770  */
3771 static gint
3772 sp_style_write_ifontsize(gchar *p, gint const len, gchar const *key,
3773                          SPIFontSize const *const val, SPIFontSize const *const base,
3774                          guint const flags)
3776     if ((flags & SP_STYLE_FLAG_ALWAYS)
3777         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3778         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set
3779             && (!base->set || sp_fontsize_differ(val, base))))
3780     {
3781         if (val->inherit) {
3782             return g_snprintf(p, len, "%s:inherit;", key);
3783         } else if (val->type == SP_FONT_SIZE_LITERAL) {
3784             for (unsigned i = 0; enum_font_size[i].key; i++) {
3785                 if (enum_font_size[i].value == static_cast< gint > (val->value) ) {
3786                     return g_snprintf(p, len, "%s:%s;", key, enum_font_size[i].key);
3787                 }
3788             }
3789         } else if (val->type == SP_FONT_SIZE_LENGTH) {
3790             Inkscape::CSSOStringStream os;
3791             os << key << ":" << val->computed << "px;";      // must specify px, see inkscape bug 1221626, mozilla bug 234789
3792             return g_strlcpy(p, os.str().c_str(), len);
3793         } else if (val->type == SP_FONT_SIZE_PERCENTAGE) {
3794             Inkscape::CSSOStringStream os;
3795             os << key << ":" << (SP_F8_16_TO_FLOAT(val->value) * 100.0) << "%;";
3796             return g_strlcpy(p, os.str().c_str(), len);
3797         }
3798     }
3799     return 0;
3803 /**
3804  * Write SPIFilter object into string.
3805  */
3806 static gint
3807 sp_style_write_ifilter(gchar *p, gint const len, gchar const *key,
3808                          SPIFilter const *const val, SPIFilter const *const base,
3809                          guint const flags)
3811     (void)base; // TODO
3812     if ((flags & SP_STYLE_FLAG_ALWAYS)
3813         || ((flags & SP_STYLE_FLAG_IFSET) && val->set)
3814         || ((flags & SP_STYLE_FLAG_IFDIFF) && val->set))
3815     {
3816         if (val->inherit) {
3817             return g_snprintf(p, len, "%s:inherit;", key);
3818         } else if (val->href && val->href->getURI()) {
3819             return g_snprintf(p, len, "%s:url(%s);", key, val->href->getURI()->toString());
3820         }
3821     }
3824     return 0;
3828 void SPIPaint::clear()
3830     set = false;
3831     inherit = false;
3832     currentcolor = false;
3833     colorSet = false;
3834     noneSet = false;
3835     value.color.set( 0 );
3836     if ( value.href && value.href->getObject() )
3837     {
3838         value.href->detach();
3839     }
3843 /**
3844  * Clear filter object, and disconnect style from paintserver (if present).
3845  */
3846 static void
3847 sp_style_filter_clear(SPStyle *style)
3849     if (style->filter.href && style->filter.href->getObject())
3850         style->filter.href->detach();
3854 // FIXME: Everything below this line belongs in a different file - css-chemistry?
3856 void
3857 sp_style_set_property_url (SPObject *item, gchar const *property, SPObject *linked, bool recursive)
3859     Inkscape::XML::Node *repr = SP_OBJECT_REPR(item);
3861     if (repr == NULL) return;
3863     SPCSSAttr *css = sp_repr_css_attr_new();
3864     if (linked) {
3865         gchar *val = g_strdup_printf("url(#%s)", SP_OBJECT_ID(linked));
3866         sp_repr_css_set_property(css, property, val);
3867         g_free(val);
3868     } else {
3869         sp_repr_css_unset_property(css, "filter");
3870     }
3872     if (recursive) {
3873         sp_repr_css_change_recursive(repr, css, "style");
3874     } else {
3875         sp_repr_css_change(repr, css, "style");
3876     }
3877     sp_repr_css_attr_unref(css);
3881 /**
3882  * Clear all style property attributes in object.
3883  */
3884 void
3885 sp_style_unset_property_attrs(SPObject *o)
3887     if (!o) return;
3889     SPStyle *style = SP_OBJECT_STYLE(o);
3890     if (!style) return;
3892     Inkscape::XML::Node *repr = SP_OBJECT_REPR(o);
3893     if (!repr) return;
3895     if (style->opacity.set) {
3896         repr->setAttribute("opacity", NULL);
3897     }
3898     if (style->color.set) {
3899         repr->setAttribute("color", NULL);
3900     }
3901     if (style->fill.set) {
3902         repr->setAttribute("fill", NULL);
3903     }
3904     if (style->fill_opacity.set) {
3905         repr->setAttribute("fill-opacity", NULL);
3906     }
3907     if (style->fill_rule.set) {
3908         repr->setAttribute("fill-rule", NULL);
3909     }
3910     if (style->stroke.set) {
3911         repr->setAttribute("stroke", NULL);
3912     }
3913     if (style->stroke_width.set) {
3914         repr->setAttribute("stroke-width", NULL);
3915     }
3916     if (style->stroke_linecap.set) {
3917         repr->setAttribute("stroke-linecap", NULL);
3918     }
3919     if (style->stroke_linejoin.set) {
3920         repr->setAttribute("stroke-linejoin", NULL);
3921     }
3922     if (style->marker[SP_MARKER_LOC].set) {
3923         repr->setAttribute("marker", NULL);
3924     }
3925     if (style->marker[SP_MARKER_LOC_START].set) {
3926         repr->setAttribute("marker-start", NULL);
3927     }
3928     if (style->marker[SP_MARKER_LOC_MID].set) {
3929         repr->setAttribute("marker-mid", NULL);
3930     }
3931     if (style->marker[SP_MARKER_LOC_END].set) {
3932         repr->setAttribute("marker-end", NULL);
3933     }
3934     if (style->stroke_opacity.set) {
3935         repr->setAttribute("stroke-opacity", NULL);
3936     }
3937     if (style->stroke_dasharray_set) {
3938         repr->setAttribute("stroke-dasharray", NULL);
3939     }
3940     if (style->stroke_dashoffset_set) {
3941         repr->setAttribute("stroke-dashoffset", NULL);
3942     }
3943     if (style->text_private && style->text->font_specification.set) {
3944         repr->setAttribute("-inkscape-font-specification", NULL);
3945     }
3946     if (style->text_private && style->text->font_family.set) {
3947         repr->setAttribute("font-family", NULL);
3948     }
3949     if (style->text_anchor.set) {
3950         repr->setAttribute("text-anchor", NULL);
3951     }
3952     if (style->writing_mode.set) {
3953         repr->setAttribute("writing_mode", NULL);
3954     }
3955     if (style->filter.set) {
3956         repr->setAttribute("filter", NULL);
3957     }
3958     if (style->enable_background.set) {
3959         repr->setAttribute("enable-background", NULL);
3960     }
3963 /**
3964  * \pre style != NULL.
3965  * \pre flags in {IFSET, ALWAYS}.
3966  */
3967 SPCSSAttr *
3968 sp_css_attr_from_style(SPStyle const *const style, guint const flags)
3970     g_return_val_if_fail(style != NULL, NULL);
3971     g_return_val_if_fail(((flags == SP_STYLE_FLAG_IFSET) ||
3972                           (flags == SP_STYLE_FLAG_ALWAYS)  ),
3973                          NULL);
3974     gchar *style_str = sp_style_write_string(style, flags);
3975     SPCSSAttr *css = sp_repr_css_attr_new();
3976     sp_repr_css_attr_add_from_string(css, style_str);
3977     g_free(style_str);
3978     return css;
3982 /**
3983  * \pre object != NULL
3984  * \pre flags in {IFSET, ALWAYS}.
3985  */
3986 SPCSSAttr *
3987 sp_css_attr_from_object(SPObject *object, guint const flags)
3989     g_return_val_if_fail(((flags == SP_STYLE_FLAG_IFSET) ||
3990                           (flags == SP_STYLE_FLAG_ALWAYS)  ),
3991                          NULL);
3992     SPStyle const *const style = SP_OBJECT_STYLE(object);
3993     if (style == NULL)
3994         return NULL;
3995     return sp_css_attr_from_style(style, flags);
3998 /**
3999  * Unset any text-related properties
4000  */
4001 SPCSSAttr *
4002 sp_css_attr_unset_text(SPCSSAttr *css)
4004     sp_repr_css_set_property(css, "font", NULL); // not implemented yet
4005     sp_repr_css_set_property(css, "-inkscape-font-specification", NULL);
4006     sp_repr_css_set_property(css, "font-size", NULL);
4007     sp_repr_css_set_property(css, "font-size-adjust", NULL); // not implemented yet
4008     sp_repr_css_set_property(css, "font-style", NULL);
4009     sp_repr_css_set_property(css, "font-variant", NULL);
4010     sp_repr_css_set_property(css, "font-weight", NULL);
4011     sp_repr_css_set_property(css, "font-stretch", NULL);
4012     sp_repr_css_set_property(css, "font-family", NULL);
4013     sp_repr_css_set_property(css, "text-indent", NULL);
4014     sp_repr_css_set_property(css, "text-align", NULL);
4015     sp_repr_css_set_property(css, "text-decoration", NULL);
4016     sp_repr_css_set_property(css, "line-height", NULL);
4017     sp_repr_css_set_property(css, "letter-spacing", NULL);
4018     sp_repr_css_set_property(css, "word-spacing", NULL);
4019     sp_repr_css_set_property(css, "text-transform", NULL);
4020     sp_repr_css_set_property(css, "direction", NULL);
4021     sp_repr_css_set_property(css, "block-progression", NULL);
4022     sp_repr_css_set_property(css, "writing-mode", NULL);
4023     sp_repr_css_set_property(css, "text-anchor", NULL);
4024     sp_repr_css_set_property(css, "kerning", NULL); // not implemented yet
4025     sp_repr_css_set_property(css, "dominant-baseline", NULL); // not implemented yet
4026     sp_repr_css_set_property(css, "alignment-baseline", NULL); // not implemented yet
4027     sp_repr_css_set_property(css, "baseline-shift", NULL); // not implemented yet
4029     return css;
4032 bool
4033 is_url(char const *p)
4035     if (p == NULL)
4036         return false;
4037 /** \todo
4038  * FIXME: I'm not sure if this applies to SVG as well, but CSS2 says any URIs
4039  * in property values must start with 'url('.
4040  */
4041     return (g_ascii_strncasecmp(p, "url(", 4) == 0);
4044 /**
4045  * Unset any properties that contain URI values.
4046  *
4047  * Used for storing style that will be reused across documents when carrying
4048  * the referenced defs is impractical.
4049  */
4050 SPCSSAttr *
4051 sp_css_attr_unset_uris(SPCSSAttr *css)
4053 // All properties that may hold <uri> or <paint> according to SVG 1.1
4054     if (is_url(sp_repr_css_property(css, "clip-path", NULL))) sp_repr_css_set_property(css, "clip-path", NULL);
4055     if (is_url(sp_repr_css_property(css, "color-profile", NULL))) sp_repr_css_set_property(css, "color-profile", NULL);
4056     if (is_url(sp_repr_css_property(css, "cursor", NULL))) sp_repr_css_set_property(css, "cursor", NULL);
4057     if (is_url(sp_repr_css_property(css, "filter", NULL))) sp_repr_css_set_property(css, "filter", NULL);
4058     if (is_url(sp_repr_css_property(css, "marker", NULL))) sp_repr_css_set_property(css, "marker", NULL);
4059     if (is_url(sp_repr_css_property(css, "marker-start", NULL))) sp_repr_css_set_property(css, "marker-start", NULL);
4060     if (is_url(sp_repr_css_property(css, "marker-mid", NULL))) sp_repr_css_set_property(css, "marker-mid", NULL);
4061     if (is_url(sp_repr_css_property(css, "marker-end", NULL))) sp_repr_css_set_property(css, "marker-end", NULL);
4062     if (is_url(sp_repr_css_property(css, "mask", NULL))) sp_repr_css_set_property(css, "mask", NULL);
4063     if (is_url(sp_repr_css_property(css, "fill", NULL))) sp_repr_css_set_property(css, "fill", NULL);
4064     if (is_url(sp_repr_css_property(css, "stroke", NULL))) sp_repr_css_set_property(css, "stroke", NULL);
4066     return css;
4069 /**
4070  * Scale a single-value property.
4071  */
4072 void
4073 sp_css_attr_scale_property_single(SPCSSAttr *css, gchar const *property,
4074                                   double ex, bool only_with_units = false)
4076     gchar const *w = sp_repr_css_property(css, property, NULL);
4077     if (w) {
4078         gchar *units = NULL;
4079         double wd = g_ascii_strtod(w, &units) * ex;
4080         if (w == units) {// nothing converted, non-numeric value
4081             return;
4082         }
4083         if (only_with_units && (units == NULL || *units == '\0' || *units == '%')) {
4084             // only_with_units, but no units found, so do nothing.
4085             return;
4086         }
4087         Inkscape::CSSOStringStream os;
4088         os << wd << units; // reattach units
4089         sp_repr_css_set_property(css, property, os.str().c_str());
4090     }
4093 /**
4094  * Scale a list-of-values property.
4095  */
4096 void
4097 sp_css_attr_scale_property_list(SPCSSAttr *css, gchar const *property, double ex)
4099     gchar const *string = sp_repr_css_property(css, property, NULL);
4100     if (string) {
4101         Inkscape::CSSOStringStream os;
4102         gchar **a = g_strsplit(string, ",", 10000);
4103         bool first = true;
4104         for (gchar **i = a; i != NULL; i++) {
4105             gchar *w = *i;
4106             if (w == NULL)
4107                 break;
4108             gchar *units = NULL;
4109             double wd = g_ascii_strtod(w, &units) * ex;
4110             if (w == units) {// nothing converted, non-numeric value ("none" or "inherit"); do nothing
4111                 g_strfreev(a);
4112                 return;
4113             }
4114             if (!first) {
4115                 os << ",";
4116             }
4117             os << wd << units; // reattach units
4118             first = false;
4119         }
4120         sp_repr_css_set_property(css, property, os.str().c_str());
4121         g_strfreev(a);
4122     }
4125 /**
4126  * Scale any properties that may hold <length> by ex.
4127  */
4128 SPCSSAttr *
4129 sp_css_attr_scale(SPCSSAttr *css, double ex)
4131     sp_css_attr_scale_property_single(css, "baseline-shift", ex);
4132     sp_css_attr_scale_property_single(css, "stroke-width", ex);
4133     sp_css_attr_scale_property_list   (css, "stroke-dasharray", ex);
4134     sp_css_attr_scale_property_single(css, "stroke-dashoffset", ex);
4135     sp_css_attr_scale_property_single(css, "font-size", ex);
4136     sp_css_attr_scale_property_single(css, "kerning", ex);
4137     sp_css_attr_scale_property_single(css, "letter-spacing", ex);
4138     sp_css_attr_scale_property_single(css, "word-spacing", ex);
4139     sp_css_attr_scale_property_single(css, "line-height", ex, true);
4141     return css;
4145 /**
4146  * Remove quotes and escapes from a string. Returned value must be g_free'd.
4147  * Note: in CSS (in style= and in stylesheets), unquoting and unescaping is done
4148  * by libcroco, our CSS parser, though it adds a new pair of "" quotes for the strings
4149  * it parsed for us. So this function is only used to remove those quotes and for
4150  * presentation attributes, without any unescaping. (XML unescaping
4151  * (&amp; etc) is done by XML parser.)
4152  */
4153 gchar *
4154 attribute_unquote(gchar const *val)
4156     if (val) {
4157         if (*val == '\'' || *val == '"') {
4158             int l = strlen(val);
4159             if (l >= 2) {
4160                 if ( ( val[0] == '"' && val[l - 1] == '"' )  ||
4161                      ( val[0] == '\'' && val[l - 1] == '\'' )  ) {
4162                     return (g_strndup (val+1, l-2));
4163                 }
4164             }
4165         }
4166     }
4168     return (val? g_strdup (val) : NULL);
4171 /**
4172  * Quote and/or escape string for writing to CSS (style=). Returned value must be g_free'd.
4173  */
4174 gchar *
4175 css2_escape_quote(gchar const *val) {
4177     Glib::ustring t;
4178     bool quote = false;
4179     bool last_was_space = false;
4181     for (gchar const *i = val; *i; i++) {
4182         bool is_space = ( *i == ' ' );
4183         if (g_ascii_isalnum(*i) || *i=='-' || *i=='_') {
4184             // ASCII alphanumeric, - and _ don't require quotes
4185             t.push_back(*i);
4186         } else if ( is_space && !last_was_space ) {
4187             // non-consecutive spaces don't require quotes
4188             t.push_back(*i);
4189         } else if (*i=='\'') {
4190             // single quotes require escaping and quotes
4191             t.push_back('\\');
4192             t.push_back(*i);
4193             quote = true;
4194         } else {
4195             // everything else requires quotes
4196             t.push_back(*i);
4197             quote = true;
4198         }
4199         if (i == val && !g_ascii_isalpha(*i)) {
4200             // a non-ASCII/non-alpha initial character requires quotes
4201             quote = true;
4202         }
4203         last_was_space = is_space;
4204     }
4206     if (last_was_space) {
4207         // a trailing space requires quotes
4208         quote = true;
4209     }
4211     if (quote) {
4212         // we use single quotes so the result can be stored in an XML
4213         // attribute without incurring un-aesthetic additional quoting
4214         // (our XML emitter always uses double quotes)
4215         t.insert(t.begin(), '\'');
4216         t.push_back('\'');
4217     }
4219     return (t.empty() ? NULL : g_strdup (t.c_str()));
4222 /*
4223   Local Variables:
4224   mode:c++
4225   c-file-style:"stroustrup"
4226   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
4227   indent-tabs-mode:nil
4228   fill-column:99
4229   End:
4230 */
4231 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :