Code

plumb XML::Documents in everywhere
[inkscape.git] / src / sp-gradient.cpp
1 #define __SP_GRADIENT_C__
3 /** \file
4  * SPGradient, SPStop, SPLinearGradient, SPRadialGradient.
5  */
6 /*
7  * Authors:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 1999-2002 Lauris Kaplinski
12  * Copyright (C) 2000-2001 Ximian, Inc.
13  * Copyright (C) 2004 David Turner
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  *
17  */
19 #define noSP_GRADIENT_VERBOSE
21 #include <cstring>
22 #include <string>
24 #include <libnr/nr-matrix-div.h>
25 #include <libnr/nr-matrix-fns.h>
26 #include <libnr/nr-matrix-ops.h>
27 #include <libnr/nr-matrix-scale-ops.h>
28 #include <libnr/nr-matrix-translate-ops.h>
29 #include "libnr/nr-scale-translate-ops.h"
31 #include <sigc++/functors/ptr_fun.h>
32 #include <sigc++/adaptors/bind.h>
34 #include "libnr/nr-gradient.h"
35 #include "svg/svg.h"
36 #include "svg/svg-color.h"
37 #include "svg/css-ostringstream.h"
38 #include "attributes.h"
39 #include "document-private.h"
40 #include "gradient-chemistry.h"
41 #include "sp-gradient-reference.h"
42 #include "sp-linear-gradient.h"
43 #include "sp-radial-gradient.h"
44 #include "sp-stop.h"
45 #include "streq.h"
46 #include "uri.h"
47 #include "xml/repr.h"
49 #define SP_MACROS_SILENT
50 #include "macros.h"
52 /// Has to be power of 2
53 #define NCOLORS NR_GRADIENT_VECTOR_LENGTH
55 static void sp_stop_class_init(SPStopClass *klass);
56 static void sp_stop_init(SPStop *stop);
58 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
59 static void sp_stop_set(SPObject *object, unsigned key, gchar const *value);
60 static Inkscape::XML::Node *sp_stop_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
62 static SPObjectClass *stop_parent_class;
64 /**
65  * Registers SPStop class and returns its type.
66  */
67 GType
68 sp_stop_get_type()
69 {
70     static GType type = 0;
71     if (!type) {
72         GTypeInfo info = {
73             sizeof(SPStopClass),
74             NULL, NULL,
75             (GClassInitFunc) sp_stop_class_init,
76             NULL, NULL,
77             sizeof(SPStop),
78             16,
79             (GInstanceInitFunc) sp_stop_init,
80             NULL,   /* value_table */
81         };
82         type = g_type_register_static(SP_TYPE_OBJECT, "SPStop", &info, (GTypeFlags)0);
83     }
84     return type;
85 }
87 /**
88  * Callback to initialize SPStop vtable.
89  */
90 static void sp_stop_class_init(SPStopClass *klass)
91 {
92     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
94     stop_parent_class = (SPObjectClass *) g_type_class_ref(SP_TYPE_OBJECT);
96     sp_object_class->build = sp_stop_build;
97     sp_object_class->set = sp_stop_set;
98     sp_object_class->write = sp_stop_write;
99 }
101 /**
102  * Callback to initialize SPStop object.
103  */
104 static void
105 sp_stop_init(SPStop *stop)
107     stop->offset = 0.0;
108     stop->currentColor = false;
109     stop->specified_color.set( 0x000000ff );
110     stop->opacity = 1.0;
113 /**
114  * Virtual build: set stop attributes from its associated XML node.
115  */
116 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
118     if (((SPObjectClass *) stop_parent_class)->build)
119         (* ((SPObjectClass *) stop_parent_class)->build)(object, document, repr);
121     sp_object_read_attr(object, "offset");
122     sp_object_read_attr(object, "stop-color");
123     sp_object_read_attr(object, "stop-opacity");
124     sp_object_read_attr(object, "style");
127 /**
128  * Virtual set: set attribute to value.
129  */
130 static void
131 sp_stop_set(SPObject *object, unsigned key, gchar const *value)
133     SPStop *stop = SP_STOP(object);
135     switch (key) {
136         case SP_ATTR_STYLE: {
137         /** \todo
138          * fixme: We are reading simple values 3 times during build (Lauris).
139          * \par
140          * We need presentation attributes etc.
141          * \par
142          * remove the hackish "style reading" from here: see comments in
143          * sp_object_get_style_property about the bugs in our current
144          * approach.  However, note that SPStyle doesn't currently have
145          * stop-color and stop-opacity properties.
146          */
147             {
148                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
149                 if (streq(p, "currentColor")) {
150                     stop->currentColor = true;
151                 } else {
152                     guint32 const color = sp_svg_read_color(p, 0);
153                     stop->specified_color.set( color );
154                 }
155             }
156             {
157                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
158                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
159                 stop->opacity = opacity;
160             }
161             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
162             break;
163         }
164         case SP_PROP_STOP_COLOR: {
165             {
166                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
167                 if (streq(p, "currentColor")) {
168                     stop->currentColor = true;
169                 } else {
170                     stop->currentColor = false;
171                     guint32 const color = sp_svg_read_color(p, 0);
172                     stop->specified_color.set( color );
173                 }
174             }
175             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
176             break;
177         }
178         case SP_PROP_STOP_OPACITY: {
179             {
180                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
181                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
182                 stop->opacity = opacity;
183             }
184             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
185             break;
186         }
187         case SP_ATTR_OFFSET: {
188             stop->offset = sp_svg_read_percentage(value, 0.0);
189             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
190             break;
191         }
192         default: {
193             if (((SPObjectClass *) stop_parent_class)->set)
194                 (* ((SPObjectClass *) stop_parent_class)->set)(object, key, value);
195             break;
196         }
197     }
200 /**
201  * Virtual write: write object attributes to repr.
202  */
203 static Inkscape::XML::Node *
204 sp_stop_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
206     SPStop *stop = SP_STOP(object);
208     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
209         repr = xml_doc->createElement("svg:stop");
210     }
212     guint32 specifiedcolor = stop->specified_color.toRGBA32( 255 );
213     gfloat opacity = stop->opacity;
215     if (((SPObjectClass *) stop_parent_class)->write)
216         (* ((SPObjectClass *) stop_parent_class)->write)(object, xml_doc, repr, flags);
218     // Since we do a hackish style setting here (because SPStyle does not support stop-color and
219     // stop-opacity), we must do it AFTER calling the parent write method; otherwise
220     // sp_object_write would clear our style= attribute (bug 1695287)
222     Inkscape::CSSOStringStream os;
223     os << "stop-color:";
224     if (stop->currentColor) {
225         os << "currentColor";
226     } else {
227         gchar c[64];
228         sp_svg_write_color(c, sizeof(c), specifiedcolor);
229         os << c;
230     }
231     os << ";stop-opacity:" << opacity;
232     repr->setAttribute("style", os.str().c_str());
233     repr->setAttribute("stop-color", NULL);
234     repr->setAttribute("stop-opacity", NULL);
235     sp_repr_set_css_double(repr, "offset", stop->offset);
236     /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no sense
237      * for offset proportions. */
239     return repr;
242 /**
243  * Return stop's color as 32bit value.
244  */
245 guint32
246 sp_stop_get_rgba32(SPStop const *const stop)
248     guint32 rgb0 = 0;
249     /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
250      * value depends on user agent, and don't give any further restrictions that I can
251      * see.) */
252     if (stop->currentColor) {
253         char const *str = sp_object_get_style_property(stop, "color", NULL);
254         if (str) {
255             rgb0 = sp_svg_read_color(str, rgb0);
256         }
257         unsigned const alpha = static_cast<unsigned>(stop->opacity * 0xff + 0.5);
258         g_return_val_if_fail((alpha & ~0xff) == 0,
259                              rgb0 | 0xff);
260         return rgb0 | alpha;
261     } else {
262         return stop->specified_color.toRGBA32( stop->opacity );
263     }
266 /**
267  * Return stop's color as SPColor.
268  */
269 static SPColor
270 sp_stop_get_color(SPStop const *const stop)
272     if (stop->currentColor) {
273         char const *str = sp_object_get_style_property(stop, "color", NULL);
274         guint32 const dfl = 0;
275         /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
276          * value depends on user agent, and don't give any further restrictions that I can
277          * see.) */
278         guint32 color = dfl;
279         if (str) {
280             color = sp_svg_read_color(str, dfl);
281         }
282         SPColor ret( color );
283         return ret;
284     } else {
285         return stop->specified_color;
286     }
289 /*
290  * Gradient
291  */
293 static void sp_gradient_class_init(SPGradientClass *klass);
294 static void sp_gradient_init(SPGradient *gr);
296 static void sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
297 static void sp_gradient_release(SPObject *object);
298 static void sp_gradient_set(SPObject *object, unsigned key, gchar const *value);
299 static void sp_gradient_child_added(SPObject *object,
300                                     Inkscape::XML::Node *child,
301                                     Inkscape::XML::Node *ref);
302 static void sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child);
303 static void sp_gradient_modified(SPObject *object, guint flags);
304 static Inkscape::XML::Node *sp_gradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
305                                               guint flags);
307 static void gradient_ref_modified(SPObject *href, guint flags, SPGradient *gradient);
309 static bool sp_gradient_invalidate_vector(SPGradient *gr);
310 static void sp_gradient_rebuild_vector(SPGradient *gr);
312 static void gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gradient);
314 SPGradientSpread sp_gradient_get_spread(SPGradient *gradient);
315 SPGradientUnits sp_gradient_get_units(SPGradient *gradient);
317 static SPPaintServerClass *gradient_parent_class;
319 /**
320  * Registers SPGradient class and returns its type.
321  */
322 GType
323 sp_gradient_get_type()
325     static GType gradient_type = 0;
326     if (!gradient_type) {
327         GTypeInfo gradient_info = {
328             sizeof(SPGradientClass),
329             NULL, NULL,
330             (GClassInitFunc) sp_gradient_class_init,
331             NULL, NULL,
332             sizeof(SPGradient),
333             16,
334             (GInstanceInitFunc) sp_gradient_init,
335             NULL,   /* value_table */
336         };
337         gradient_type = g_type_register_static(SP_TYPE_PAINT_SERVER, "SPGradient",
338                                                &gradient_info, (GTypeFlags)0);
339     }
340     return gradient_type;
343 /**
344  * SPGradient vtable initialization.
345  */
346 static void
347 sp_gradient_class_init(SPGradientClass *klass)
349     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
351     gradient_parent_class = (SPPaintServerClass *)g_type_class_ref(SP_TYPE_PAINT_SERVER);
353     sp_object_class->build = sp_gradient_build;
354     sp_object_class->release = sp_gradient_release;
355     sp_object_class->set = sp_gradient_set;
356     sp_object_class->child_added = sp_gradient_child_added;
357     sp_object_class->remove_child = sp_gradient_remove_child;
358     sp_object_class->modified = sp_gradient_modified;
359     sp_object_class->write = sp_gradient_write;
362 /**
363  * Callback for SPGradient object initialization.
364  */
365 static void
366 sp_gradient_init(SPGradient *gr)
368     gr->ref = new SPGradientReference(SP_OBJECT(gr));
369     gr->ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(gradient_ref_changed), gr));
371     /** \todo
372      * Fixme: reprs being rearranged (e.g. via the XML editor)
373      * may require us to clear the state.
374      */
375     gr->state = SP_GRADIENT_STATE_UNKNOWN;
377     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
378     gr->units_set = FALSE;
380     gr->gradientTransform = NR::identity();
381     gr->gradientTransform_set = FALSE;
383     gr->spread = SP_GRADIENT_SPREAD_PAD;
384     gr->spread_set = FALSE;
386     gr->has_stops = FALSE;
388     gr->vector.built = false;
389     gr->vector.stops.clear();
391     gr->color = NULL;
393     new (&gr->modified_connection) sigc::connection();
396 /**
397  * Virtual build: set gradient attributes from its associated repr.
398  */
399 static void
400 sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
402     SPGradient *gradient = SP_GRADIENT(object);
404     if (((SPObjectClass *) gradient_parent_class)->build)
405         (* ((SPObjectClass *) gradient_parent_class)->build)(object, document, repr);
407     SPObject *ochild;
408     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
409         if (SP_IS_STOP(ochild)) {
410             gradient->has_stops = TRUE;
411             break;
412         }
413     }
415     sp_object_read_attr(object, "gradientUnits");
416     sp_object_read_attr(object, "gradientTransform");
417     sp_object_read_attr(object, "spreadMethod");
418     sp_object_read_attr(object, "xlink:href");
420     /* Register ourselves */
421     sp_document_add_resource(document, "gradient", object);
424 /**
425  * Virtual release of SPGradient members before destruction.
426  */
427 static void
428 sp_gradient_release(SPObject *object)
430     SPGradient *gradient = (SPGradient *) object;
432 #ifdef SP_GRADIENT_VERBOSE
433     g_print("Releasing gradient %s\n", SP_OBJECT_ID(object));
434 #endif
436     if (SP_OBJECT_DOCUMENT(object)) {
437         /* Unregister ourselves */
438         sp_document_remove_resource(SP_OBJECT_DOCUMENT(object), "gradient", SP_OBJECT(object));
439     }
441     if (gradient->ref) {
442         gradient->modified_connection.disconnect();
443         gradient->ref->detach();
444         delete gradient->ref;
445         gradient->ref = NULL;
446     }
448     if (gradient->color) {
449         g_free(gradient->color);
450         gradient->color = NULL;
451     }
453     gradient->modified_connection.~connection();
455     if (((SPObjectClass *) gradient_parent_class)->release)
456         ((SPObjectClass *) gradient_parent_class)->release(object);
459 /**
460  * Set gradient attribute to value.
461  */
462 static void
463 sp_gradient_set(SPObject *object, unsigned key, gchar const *value)
465     SPGradient *gr = SP_GRADIENT(object);
467     switch (key) {
468         case SP_ATTR_GRADIENTUNITS:
469             if (value) {
470                 if (!strcmp(value, "userSpaceOnUse")) {
471                     gr->units = SP_GRADIENT_UNITS_USERSPACEONUSE;
472                 } else {
473                     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
474                 }
475                 gr->units_set = TRUE;
476             } else {
477                 gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
478                 gr->units_set = FALSE;
479             }
480             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
481             break;
482         case SP_ATTR_GRADIENTTRANSFORM: {
483             NR::Matrix t;
484             if (value && sp_svg_transform_read(value, &t)) {
485                 gr->gradientTransform = t;
486                 gr->gradientTransform_set = TRUE;
487             } else {
488                 gr->gradientTransform = NR::identity();
489                 gr->gradientTransform_set = FALSE;
490             }
491             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
492             break;
493         }
494         case SP_ATTR_SPREADMETHOD:
495             if (value) {
496                 if (!strcmp(value, "reflect")) {
497                     gr->spread = SP_GRADIENT_SPREAD_REFLECT;
498                 } else if (!strcmp(value, "repeat")) {
499                     gr->spread = SP_GRADIENT_SPREAD_REPEAT;
500                 } else {
501                     gr->spread = SP_GRADIENT_SPREAD_PAD;
502                 }
503                 gr->spread_set = TRUE;
504             } else {
505                 gr->spread_set = FALSE;
506             }
507             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
508             break;
509         case SP_ATTR_XLINK_HREF:
510             if (value) {
511                 try {
512                     gr->ref->attach(Inkscape::URI(value));
513                 } catch (Inkscape::BadURIException &e) {
514                     g_warning("%s", e.what());
515                     gr->ref->detach();
516                 }
517             } else {
518                 gr->ref->detach();
519             }
520             break;
521         default:
522             if (((SPObjectClass *) gradient_parent_class)->set)
523                 ((SPObjectClass *) gradient_parent_class)->set(object, key, value);
524             break;
525     }
528 /**
529  * Gets called when the gradient is (re)attached to another gradient.
530  */
531 static void
532 gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gr)
534     if (old_ref) {
535         gr->modified_connection.disconnect();
536     }
537     if ( SP_IS_GRADIENT(ref)
538          && ref != gr )
539     {
540         gr->modified_connection = ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&gradient_ref_modified), gr));
541     }
543     // Per SVG, all unset attributes must be inherited from linked gradient.
544     // So, as we're now (re)linked, we assign linkee's values to this gradient if they are not yet set -
545     // but without setting the _set flags.
546     // FIXME: do the same for gradientTransform too
547     if (!gr->units_set)
548         gr->units = sp_gradient_get_units (gr);
549     if (!gr->spread_set)
550         gr->spread = sp_gradient_get_spread (gr);
552     /// \todo Fixme: what should the flags (second) argument be? */
553     gradient_ref_modified(ref, 0, gr);
556 /**
557  * Callback for child_added event.
558  */
559 static void
560 sp_gradient_child_added(SPObject *object, Inkscape::XML::Node *child, Inkscape::XML::Node *ref)
562     SPGradient *gr = SP_GRADIENT(object);
564     sp_gradient_invalidate_vector(gr);
566     if (((SPObjectClass *) gradient_parent_class)->child_added)
567         (* ((SPObjectClass *) gradient_parent_class)->child_added)(object, child, ref);
569     SPObject *ochild = sp_object_get_child_by_repr(object, child);
570     if ( ochild && SP_IS_STOP(ochild) ) {
571         gr->has_stops = TRUE;
572     }
574     /// \todo Fixme: should we schedule "modified" here?
575     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
578 /**
579  * Callback for remove_child event.
580  */
581 static void
582 sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child)
584     SPGradient *gr = SP_GRADIENT(object);
586     sp_gradient_invalidate_vector(gr);
588     if (((SPObjectClass *) gradient_parent_class)->remove_child)
589         (* ((SPObjectClass *) gradient_parent_class)->remove_child)(object, child);
591     gr->has_stops = FALSE;
592     SPObject *ochild;
593     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
594         if (SP_IS_STOP(ochild)) {
595             gr->has_stops = TRUE;
596             break;
597         }
598     }
600     /* Fixme: should we schedule "modified" here? */
601     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
604 /**
605  * Callback for modified event.
606  */
607 static void
608 sp_gradient_modified(SPObject *object, guint flags)
610     SPGradient *gr = SP_GRADIENT(object);
612     if (flags & SP_OBJECT_CHILD_MODIFIED_FLAG) {
613         sp_gradient_invalidate_vector(gr);
614     }
616     if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
617         sp_gradient_ensure_colors(gr);
618     }
620     if (flags & SP_OBJECT_MODIFIED_FLAG) flags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
621     flags &= SP_OBJECT_MODIFIED_CASCADE;
623     // FIXME: climb up the ladder of hrefs
624     GSList *l = NULL;
625     for (SPObject *child = sp_object_first_child(object) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
626         g_object_ref(G_OBJECT(child));
627         l = g_slist_prepend(l, child);
628     }
629     l = g_slist_reverse(l);
630     while (l) {
631         SPObject *child = SP_OBJECT(l->data);
632         l = g_slist_remove(l, child);
633         if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
634             child->emitModified(flags);
635         }
636         g_object_unref(G_OBJECT(child));
637     }
640 /**
641  * Write gradient attributes to repr.
642  */
643 static Inkscape::XML::Node *
644 sp_gradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
646     SPGradient *gr = SP_GRADIENT(object);
648     if (((SPObjectClass *) gradient_parent_class)->write)
649         (* ((SPObjectClass *) gradient_parent_class)->write)(object, xml_doc, repr, flags);
651     if (flags & SP_OBJECT_WRITE_BUILD) {
652         GSList *l = NULL;
653         for (SPObject *child = sp_object_first_child(object); child; child = SP_OBJECT_NEXT(child)) {
654             Inkscape::XML::Node *crepr;
655             crepr = child->updateRepr(xml_doc, NULL, flags);
656             if (crepr) l = g_slist_prepend(l, crepr);
657         }
658         while (l) {
659             repr->addChild((Inkscape::XML::Node *) l->data, NULL);
660             Inkscape::GC::release((Inkscape::XML::Node *) l->data);
661             l = g_slist_remove(l, l->data);
662         }
663     }
665     if (gr->ref->getURI()) {
666         gchar *uri_string = gr->ref->getURI()->toString();
667         repr->setAttribute("xlink:href", uri_string);
668         g_free(uri_string);
669     }
671     if ((flags & SP_OBJECT_WRITE_ALL) || gr->units_set) {
672         switch (gr->units) {
673             case SP_GRADIENT_UNITS_USERSPACEONUSE:
674                 repr->setAttribute("gradientUnits", "userSpaceOnUse");
675                 break;
676             default:
677                 repr->setAttribute("gradientUnits", "objectBoundingBox");
678                 break;
679         }
680     }
682     if ((flags & SP_OBJECT_WRITE_ALL) || gr->gradientTransform_set) {
683         gchar *c=sp_svg_transform_write(gr->gradientTransform);
684         repr->setAttribute("gradientTransform", c);
685         g_free(c);
686     }
688     if ((flags & SP_OBJECT_WRITE_ALL) || gr->spread_set) {
689         /* FIXME: Ensure that gr->spread is the inherited value
690          * if !gr->spread_set.  Not currently happening: see sp_gradient_modified.
691          */
692         switch (gr->spread) {
693             case SP_GRADIENT_SPREAD_REFLECT:
694                 repr->setAttribute("spreadMethod", "reflect");
695                 break;
696             case SP_GRADIENT_SPREAD_REPEAT:
697                 repr->setAttribute("spreadMethod", "repeat");
698                 break;
699             default:
700                 repr->setAttribute("spreadMethod", "pad");
701                 break;
702         }
703     }
705     return repr;
708 /**
709  * Forces the vector to be built, if not present (i.e., changed).
710  *
711  * \pre SP_IS_GRADIENT(gradient).
712  */
713 void
714 sp_gradient_ensure_vector(SPGradient *gradient)
716     g_return_if_fail(gradient != NULL);
717     g_return_if_fail(SP_IS_GRADIENT(gradient));
719     if (!gradient->vector.built) {
720         sp_gradient_rebuild_vector(gradient);
721     }
724 /**
725  * Set units property of gradient and emit modified.
726  */
727 void
728 sp_gradient_set_units(SPGradient *gr, SPGradientUnits units)
730     if (units != gr->units) {
731         gr->units = units;
732         gr->units_set = TRUE;
733         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
734     }
737 /**
738  * Set spread property of gradient and emit modified.
739  */
740 void
741 sp_gradient_set_spread(SPGradient *gr, SPGradientSpread spread)
743     if (spread != gr->spread) {
744         gr->spread = spread;
745         gr->spread_set = TRUE;
746         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
747     }
750 /**
751  * Returns the first of {src, src-\>ref-\>getObject(),
752  * src-\>ref-\>getObject()-\>ref-\>getObject(),...}
753  * for which \a match is true, or NULL if none found.
754  *
755  * The raison d'être of this routine is that it correctly handles cycles in the href chain (e.g., if
756  * a gradient gives itself as its href, or if each of two gradients gives the other as its href).
757  *
758  * \pre SP_IS_GRADIENT(src).
759  */
760 static SPGradient *
761 chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *))
763     g_return_val_if_fail(SP_IS_GRADIENT(src), NULL);
765     /* Use a pair of pointers for detecting loops: p1 advances half as fast as p2.  If there is a
766        loop, then once p1 has entered the loop, we'll detect it the next time the distance between
767        p1 and p2 is a multiple of the loop size. */
768     SPGradient *p1 = src, *p2 = src;
769     bool do1 = false;
770     for (;;) {
771         if (match(p2)) {
772             return p2;
773         }
775         p2 = p2->ref->getObject();
776         if (!p2) {
777             return p2;
778         }
779         if (do1) {
780             p1 = p1->ref->getObject();
781         }
782         do1 = !do1;
784         if ( p2 == p1 ) {
785             /* We've been here before, so return NULL to indicate that no matching gradient found
786              * in the chain. */
787             return NULL;
788         }
789     }
792 /**
793  * True if gradient has stops.
794  */
795 static bool
796 has_stops(SPGradient const *gr)
798     return SP_GRADIENT_HAS_STOPS(gr);
801 /**
802  * True if gradient has spread set.
803  */
804 static bool
805 has_spread_set(SPGradient const *gr)
807     return gr->spread_set;
810 /**
811  * True if gradient has units set.
812  */
813 static bool
814 has_units_set(SPGradient const *gr)
816     return gr->units_set;
820 /**
821  * Returns private vector of given gradient (the gradient at the end of the href chain which has
822  * stops), optionally normalizing it.
823  *
824  * \pre SP_IS_GRADIENT(gradient).
825  * \pre There exists a gradient in the chain that has stops.
826  */
827 SPGradient *
828 sp_gradient_get_vector(SPGradient *gradient, bool force_vector)
830     g_return_val_if_fail(gradient != NULL, NULL);
831     g_return_val_if_fail(SP_IS_GRADIENT(gradient), NULL);
833     SPGradient *const src = chase_hrefs(gradient, has_stops);
834     return ( force_vector
835              ? sp_gradient_ensure_vector_normalized(src)
836              : src );
839 /**
840  * Returns the effective spread of given gradient (climbing up the refs chain if needed).
841  *
842  * \pre SP_IS_GRADIENT(gradient).
843  */
844 SPGradientSpread
845 sp_gradient_get_spread(SPGradient *gradient)
847     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_SPREAD_PAD);
849     SPGradient const *src = chase_hrefs(gradient, has_spread_set);
850     return ( src
851              ? src->spread
852              : SP_GRADIENT_SPREAD_PAD ); // pad is the default
855 /**
856  * Returns the effective units of given gradient (climbing up the refs chain if needed).
857  *
858  * \pre SP_IS_GRADIENT(gradient).
859  */
860 SPGradientUnits
861 sp_gradient_get_units(SPGradient *gradient)
863     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX);
865     SPGradient const *src = chase_hrefs(gradient, has_units_set);
866     return ( src
867              ? src->units
868              : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ); // bbox is the default
872 /**
873  * Clears the gradient's svg:stop children from its repr.
874  */
875 void
876 sp_gradient_repr_clear_vector(SPGradient *gr)
878     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
880     /* Collect stops from original repr */
881     GSList *sl = NULL;
882     for (Inkscape::XML::Node *child = repr->firstChild() ; child != NULL; child = child->next() ) {
883         if (!strcmp(child->name(), "svg:stop")) {
884             sl = g_slist_prepend(sl, child);
885         }
886     }
887     /* Remove all stops */
888     while (sl) {
889         /** \todo
890          * fixme: This should work, unless we make gradient
891          * into generic group.
892          */
893         sp_repr_unparent((Inkscape::XML::Node *)sl->data);
894         sl = g_slist_remove(sl, sl->data);
895     }
898 /**
899  * Writes the gradient's internal vector (whether from its own stops, or
900  * inherited from refs) into the gradient repr as svg:stop elements.
901  */
902 void
903 sp_gradient_repr_write_vector(SPGradient *gr)
905     g_return_if_fail(gr != NULL);
906     g_return_if_fail(SP_IS_GRADIENT(gr));
908     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(gr));
909     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
911     /* We have to be careful, as vector may be our own, so construct repr list at first */
912     GSList *cl = NULL;
914     for (guint i = 0; i < gr->vector.stops.size(); i++) {
915         Inkscape::CSSOStringStream os;
916         Inkscape::XML::Node *child = xml_doc->createElement("svg:stop");
917         sp_repr_set_css_double(child, "offset", gr->vector.stops[i].offset);
918         /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no
919          * sense for offset proportions. */
920         gchar c[64];
921         sp_svg_write_color(c, sizeof(c), gr->vector.stops[i].color.toRGBA32( 0x00 ));
922         os << "stop-color:" << c << ";stop-opacity:" << gr->vector.stops[i].opacity;
923         child->setAttribute("style", os.str().c_str());
924         /* Order will be reversed here */
925         cl = g_slist_prepend(cl, child);
926     }
928     sp_gradient_repr_clear_vector(gr);
930     /* And insert new children from list */
931     while (cl) {
932         Inkscape::XML::Node *child = static_cast<Inkscape::XML::Node *>(cl->data);
933         repr->addChild(child, NULL);
934         Inkscape::GC::release(child);
935         cl = g_slist_remove(cl, child);
936     }
940 static void
941 gradient_ref_modified(SPObject */*href*/, guint /*flags*/, SPGradient *gradient)
943     if (sp_gradient_invalidate_vector(gradient)) {
944         SP_OBJECT(gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
945         /* Conditional to avoid causing infinite loop if there's a cycle in the href chain. */
946     }
949 /** Return true iff change made. */
950 static bool
951 sp_gradient_invalidate_vector(SPGradient *gr)
953     bool ret = false;
955     if (gr->color != NULL) {
956         g_free(gr->color);
957         gr->color = NULL;
958         ret = true;
959     }
961     if (gr->vector.built) {
962         gr->vector.built = false;
963         gr->vector.stops.clear();
964         ret = true;
965     }
967     return ret;
970 /** Creates normalized color vector */
971 static void
972 sp_gradient_rebuild_vector(SPGradient *gr)
974     gint len = 0;
975     for ( SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
976           child != NULL ;
977           child = SP_OBJECT_NEXT(child) ) {
978         if (SP_IS_STOP(child)) {
979             len ++;
980         }
981     }
983     gr->has_stops = (len != 0);
985     gr->vector.stops.clear();
987     SPGradient *ref = gr->ref->getObject();
988     if ( !gr->has_stops && ref ) {
989         /* Copy vector from referenced gradient */
990         gr->vector.built = true;   // Prevent infinite recursion.
991         sp_gradient_ensure_vector(ref);
992         if (!ref->vector.stops.empty()) {
993             gr->vector.built = ref->vector.built;
994             gr->vector.stops.assign(ref->vector.stops.begin(), ref->vector.stops.end());
995             return;
996         }
997     }
999     for (SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
1000          child != NULL;
1001          child = SP_OBJECT_NEXT(child) ) {
1002         if (SP_IS_STOP(child)) {
1003             SPStop *stop = SP_STOP(child);
1005             SPGradientStop gstop;
1006             if (gr->vector.stops.size() > 0) {
1007                 // "Each gradient offset value is required to be equal to or greater than the
1008                 // previous gradient stop's offset value. If a given gradient stop's offset
1009                 // value is not equal to or greater than all previous offset values, then the
1010                 // offset value is adjusted to be equal to the largest of all previous offset
1011                 // values."
1012                 gstop.offset = MAX(stop->offset, gr->vector.stops.back().offset);
1013             } else {
1014                 gstop.offset = stop->offset;
1015             }
1017             // "Gradient offset values less than 0 (or less than 0%) are rounded up to
1018             // 0%. Gradient offset values greater than 1 (or greater than 100%) are rounded
1019             // down to 100%."
1020             gstop.offset = CLAMP(gstop.offset, 0, 1);
1022             gstop.color = sp_stop_get_color(stop);
1023             gstop.opacity = stop->opacity;
1025             gr->vector.stops.push_back(gstop);
1026         }
1027     }
1029     // Normalize per section 13.2.4 of SVG 1.1.
1030     if (gr->vector.stops.size() == 0) {
1031         /* "If no stops are defined, then painting shall occur as if 'none' were specified as the
1032          * paint style."
1033          */
1034         {
1035             SPGradientStop gstop;
1036             gstop.offset = 0.0;
1037             gstop.color.set( 0x00000000 );
1038             gstop.opacity = 0.0;
1039             gr->vector.stops.push_back(gstop);
1040         }
1041         {
1042             SPGradientStop gstop;
1043             gstop.offset = 1.0;
1044             gstop.color.set( 0x00000000 );
1045             gstop.opacity = 0.0;
1046             gr->vector.stops.push_back(gstop);
1047         }
1048     } else {
1049         /* "If one stop is defined, then paint with the solid color fill using the color defined
1050          * for that gradient stop."
1051          */
1052         if (gr->vector.stops.front().offset > 0.0) {
1053             // If the first one is not at 0, then insert a copy of the first at 0.
1054             SPGradientStop gstop;
1055             gstop.offset = 0.0;
1056             gstop.color = gr->vector.stops.front().color;
1057             gstop.opacity = gr->vector.stops.front().opacity;
1058             gr->vector.stops.insert(gr->vector.stops.begin(), gstop);
1059         }
1060         if (gr->vector.stops.back().offset < 1.0) {
1061             // If the last one is not at 1, then insert a copy of the last at 1.
1062             SPGradientStop gstop;
1063             gstop.offset = 1.0;
1064             gstop.color = gr->vector.stops.back().color;
1065             gstop.opacity = gr->vector.stops.back().opacity;
1066             gr->vector.stops.push_back(gstop);
1067         }
1068     }
1070     gr->vector.built = true;
1073 /**
1074  * The gradient's color array is newly created and set up from vector.
1075  */
1076 void
1077 sp_gradient_ensure_colors(SPGradient *gr)
1079     if (!gr->vector.built) {
1080         sp_gradient_rebuild_vector(gr);
1081     }
1082     g_return_if_fail(!gr->vector.stops.empty());
1084     /// \todo Where is the memory freed?
1085     if (!gr->color) {
1086         gr->color = g_new(guchar, 4 * NCOLORS);
1087     }
1089     for (guint i = 0; i < gr->vector.stops.size() - 1; i++) {
1090         guint32 color = gr->vector.stops[i].color.toRGBA32( gr->vector.stops[i].opacity );
1091         gint r0 = (color >> 24) & 0xff;
1092         gint g0 = (color >> 16) & 0xff;
1093         gint b0 = (color >> 8) & 0xff;
1094         gint a0 = color & 0xff;
1095         color = gr->vector.stops[i + 1].color.toRGBA32( gr->vector.stops[i + 1].opacity );
1096         gint r1 = (color >> 24) & 0xff;
1097         gint g1 = (color >> 16) & 0xff;
1098         gint b1 = (color >> 8) & 0xff;
1099         gint a1 = color & 0xff;
1100         gint o0 = (gint) floor(gr->vector.stops[i].offset * (NCOLORS - 0.001));
1101         gint o1 = (gint) floor(gr->vector.stops[i + 1].offset * (NCOLORS - 0.001));
1102         if (o1 > o0) {
1103             gint dr = ((r1 - r0) << 16) / (o1 - o0);
1104             gint dg = ((g1 - g0) << 16) / (o1 - o0);
1105             gint db = ((b1 - b0) << 16) / (o1 - o0);
1106             gint da = ((a1 - a0) << 16) / (o1 - o0);
1107             gint r = r0 << 16;
1108             gint g = g0 << 16;
1109             gint b = b0 << 16;
1110             gint a = a0 << 16;
1111             for (int j = o0; j < o1 + 1; j++) {
1112                 gr->color[4 * j] = r >> 16;
1113                 gr->color[4 * j + 1] = g >> 16;
1114                 gr->color[4 * j + 2] = b >> 16;
1115                 gr->color[4 * j + 3] = a >> 16;
1116                 r += dr;
1117                 g += dg;
1118                 b += db;
1119                 a += da;
1120             }
1121         }
1122     }
1125 /**
1126  * Renders gradient vector to buffer as line.
1127  *
1128  * RGB buffer background should be set up beforehand.
1129  *
1130  * @param len,width,height,rowstride Buffer parameters (1 or 2 dimensional).
1131  * @param span Full integer width of requested gradient.
1132  * @param pos Buffer starting position in span.
1133  */
1134 static void
1135 sp_gradient_render_vector_line_rgba(SPGradient *const gradient, guchar *buf,
1136                                     gint const len, gint const pos, gint const span)
1138     g_return_if_fail(gradient != NULL);
1139     g_return_if_fail(SP_IS_GRADIENT(gradient));
1140     g_return_if_fail(buf != NULL);
1141     g_return_if_fail(len > 0);
1142     g_return_if_fail(pos >= 0);
1143     g_return_if_fail(pos + len <= span);
1144     g_return_if_fail(span > 0);
1146     if (!gradient->color) {
1147         sp_gradient_ensure_colors(gradient);
1148     }
1150     gint idx = (pos * 1024 << 8) / span;
1151     gint didx = (1024 << 8) / span;
1153     for (gint x = 0; x < len; x++) {
1154         /// \todo Can this be done with 4 byte copies?
1155         *buf++ = gradient->color[4 * (idx >> 8)];
1156         *buf++ = gradient->color[4 * (idx >> 8) + 1];
1157         *buf++ = gradient->color[4 * (idx >> 8) + 2];
1158         *buf++ = gradient->color[4 * (idx >> 8) + 3];
1159         idx += didx;
1160     }
1163 /**
1164  * Render rectangular RGBA area from gradient vector.
1165  */
1166 void
1167 sp_gradient_render_vector_block_rgba(SPGradient *const gradient, guchar *buf,
1168                                      gint const width, gint const height, gint const rowstride,
1169                                      gint const pos, gint const span, bool const horizontal)
1171     g_return_if_fail(gradient != NULL);
1172     g_return_if_fail(SP_IS_GRADIENT(gradient));
1173     g_return_if_fail(buf != NULL);
1174     g_return_if_fail(width > 0);
1175     g_return_if_fail(height > 0);
1176     g_return_if_fail(pos >= 0);
1177     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1178     g_return_if_fail(span > 0);
1180     if (horizontal) {
1181         sp_gradient_render_vector_line_rgba(gradient, buf, width, pos, span);
1182         for (gint y = 1; y < height; y++) {
1183             memcpy(buf + y * rowstride, buf, 4 * width);
1184         }
1185     } else {
1186         guchar *tmp = (guchar *)alloca(4 * height);
1187         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1188         for (gint y = 0; y < height; y++) {
1189             guchar *b = buf + y * rowstride;
1190             for (gint x = 0; x < width; x++) {
1191                 *b++ = tmp[0];
1192                 *b++ = tmp[1];
1193                 *b++ = tmp[2];
1194                 *b++ = tmp[3];
1195             }
1196             tmp += 4;
1197         }
1198     }
1201 /**
1202  * Render rectangular RGB area from gradient vector.
1203  */
1204 void
1205 sp_gradient_render_vector_block_rgb(SPGradient *gradient, guchar *buf,
1206                                     gint const width, gint const height, gint const /*rowstride*/,
1207                                     gint const pos, gint const span, bool const horizontal)
1209     g_return_if_fail(gradient != NULL);
1210     g_return_if_fail(SP_IS_GRADIENT(gradient));
1211     g_return_if_fail(buf != NULL);
1212     g_return_if_fail(width > 0);
1213     g_return_if_fail(height > 0);
1214     g_return_if_fail(pos >= 0);
1215     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1216     g_return_if_fail(span > 0);
1218     if (horizontal) {
1219         guchar *tmp = (guchar*)alloca(4 * width);
1220         sp_gradient_render_vector_line_rgba(gradient, tmp, width, pos, span);
1221         for (gint y = 0; y < height; y++) {
1222             guchar *t = tmp;
1223             for (gint x = 0; x < width; x++) {
1224                 gint a = t[3];
1225                 gint fc = (t[0] - buf[0]) * a;
1226                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1227                 fc = (t[1] - buf[1]) * a;
1228                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1229                 fc = (t[2] - buf[2]) * a;
1230                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1231                 buf += 3;
1232                 t += 4;
1233             }
1234         }
1235     } else {
1236         guchar *tmp = (guchar*)alloca(4 * height);
1237         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1238         for (gint y = 0; y < height; y++) {
1239             guchar *t = tmp + 4 * y;
1240             for (gint x = 0; x < width; x++) {
1241                 gint a = t[3];
1242                 gint fc = (t[0] - buf[0]) * a;
1243                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1244                 fc = (t[1] - buf[1]) * a;
1245                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1246                 fc = (t[2] - buf[2]) * a;
1247                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1248             }
1249         }
1250     }
1253 NR::Matrix
1254 sp_gradient_get_g2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1256     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1257         return ( NR::scale(bbox.dimensions())
1258                  * NR::translate(bbox.min())
1259                  * ctm );
1260     } else {
1261         return ctm;
1262     }
1265 NR::Matrix
1266 sp_gradient_get_gs2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1268     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1269         return ( gr->gradientTransform
1270                  * NR::scale(bbox.dimensions())
1271                  * NR::translate(bbox.min())
1272                  * ctm );
1273     } else {
1274         return gr->gradientTransform * ctm;
1275     }
1278 void
1279 sp_gradient_set_gs2d_matrix(SPGradient *gr, NR::Matrix const &ctm,
1280                             NR::Rect const &bbox, NR::Matrix const &gs2d)
1282     gr->gradientTransform = gs2d / ctm;
1283     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) {
1284         gr->gradientTransform = ( gr->gradientTransform
1285                                   / NR::translate(bbox.min())
1286                                   / NR::scale(bbox.dimensions()) );
1287     }
1288     gr->gradientTransform_set = TRUE;
1290     SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1293 /*
1294  * Linear Gradient
1295  */
1297 class SPLGPainter;
1299 /// A context with linear gradient, painter, and gradient renderer.
1300 struct SPLGPainter {
1301     SPPainter painter;
1302     SPLinearGradient *lg;
1304     NRLGradientRenderer lgr;
1305 };
1307 static void sp_lineargradient_class_init(SPLinearGradientClass *klass);
1308 static void sp_lineargradient_init(SPLinearGradient *lg);
1310 static void sp_lineargradient_build(SPObject *object,
1311                                     SPDocument *document,
1312                                     Inkscape::XML::Node *repr);
1313 static void sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value);
1314 static Inkscape::XML::Node *sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1315                                                     guint flags);
1317 static SPPainter *sp_lineargradient_painter_new(SPPaintServer *ps,
1318                                                 NR::Matrix const &full_transform,
1319                                                 NR::Matrix const &parent_transform,
1320                                                 NRRect const *bbox);
1321 static void sp_lineargradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1323 static void sp_lg_fill(SPPainter *painter, NRPixBlock *pb);
1325 static SPGradientClass *lg_parent_class;
1327 /**
1328  * Register SPLinearGradient class and return its type.
1329  */
1330 GType
1331 sp_lineargradient_get_type()
1333     static GType type = 0;
1334     if (!type) {
1335         GTypeInfo info = {
1336             sizeof(SPLinearGradientClass),
1337             NULL, NULL,
1338             (GClassInitFunc) sp_lineargradient_class_init,
1339             NULL, NULL,
1340             sizeof(SPLinearGradient),
1341             16,
1342             (GInstanceInitFunc) sp_lineargradient_init,
1343             NULL,   /* value_table */
1344         };
1345         type = g_type_register_static(SP_TYPE_GRADIENT, "SPLinearGradient", &info, (GTypeFlags)0);
1346     }
1347     return type;
1350 /**
1351  * SPLinearGradient vtable initialization.
1352  */
1353 static void sp_lineargradient_class_init(SPLinearGradientClass *klass)
1355     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1356     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1358     lg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1360     sp_object_class->build = sp_lineargradient_build;
1361     sp_object_class->set = sp_lineargradient_set;
1362     sp_object_class->write = sp_lineargradient_write;
1364     ps_class->painter_new = sp_lineargradient_painter_new;
1365     ps_class->painter_free = sp_lineargradient_painter_free;
1368 /**
1369  * Callback for SPLinearGradient object initialization.
1370  */
1371 static void sp_lineargradient_init(SPLinearGradient *lg)
1373     lg->x1.unset(SVGLength::PERCENT, 0.0, 0.0);
1374     lg->y1.unset(SVGLength::PERCENT, 0.5, 0.5);
1375     lg->x2.unset(SVGLength::PERCENT, 1.0, 1.0);
1376     lg->y2.unset(SVGLength::PERCENT, 0.5, 0.5);
1379 /**
1380  * Callback: set attributes from associated repr.
1381  */
1382 static void sp_lineargradient_build(SPObject *object,
1383                                     SPDocument *document,
1384                                     Inkscape::XML::Node *repr)
1386     if (((SPObjectClass *) lg_parent_class)->build)
1387         (* ((SPObjectClass *) lg_parent_class)->build)(object, document, repr);
1389     sp_object_read_attr(object, "x1");
1390     sp_object_read_attr(object, "y1");
1391     sp_object_read_attr(object, "x2");
1392     sp_object_read_attr(object, "y2");
1395 /**
1396  * Callback: set attribute.
1397  */
1398 static void
1399 sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value)
1401     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1403     switch (key) {
1404         case SP_ATTR_X1:
1405             lg->x1.readOrUnset(value, SVGLength::PERCENT, 0.0, 0.0);
1406             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1407             break;
1408         case SP_ATTR_Y1:
1409             lg->y1.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1410             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1411             break;
1412         case SP_ATTR_X2:
1413             lg->x2.readOrUnset(value, SVGLength::PERCENT, 1.0, 1.0);
1414             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1415             break;
1416         case SP_ATTR_Y2:
1417             lg->y2.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1418             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1419             break;
1420         default:
1421             if (((SPObjectClass *) lg_parent_class)->set)
1422                 (* ((SPObjectClass *) lg_parent_class)->set)(object, key, value);
1423             break;
1424     }
1427 /**
1428  * Callback: write attributes to associated repr.
1429  */
1430 static Inkscape::XML::Node *
1431 sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1433     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1435     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1436         repr = xml_doc->createElement("svg:linearGradient");
1437     }
1439     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x1._set)
1440         sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
1441     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y1._set)
1442         sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
1443     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x2._set)
1444         sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
1445     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y2._set)
1446         sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
1448     if (((SPObjectClass *) lg_parent_class)->write)
1449         (* ((SPObjectClass *) lg_parent_class)->write)(object, xml_doc, repr, flags);
1451     return repr;
1454 /**
1455  * Create linear gradient context.
1456  *
1457  * Basically we have to deal with transformations
1458  *
1459  * 1) color2norm - maps point in (0,NCOLORS) vector to (0,1) vector
1460  * 2) norm2pos - maps (0,1) vector to x1,y1 - x2,y2
1461  * 2) gradientTransform
1462  * 3) bbox2user
1463  * 4) ctm == userspace to pixel grid
1464  *
1465  * See also (*) in sp-pattern about why we may need parent_transform.
1466  *
1467  * \todo (point 1 above) fixme: I do not know how to deal with start > 0
1468  * and end < 1.
1469  */
1470 static SPPainter *
1471 sp_lineargradient_painter_new(SPPaintServer *ps,
1472                               NR::Matrix const &full_transform,
1473                               NR::Matrix const &/*parent_transform*/,
1474                               NRRect const *bbox)
1476     SPLinearGradient *lg = SP_LINEARGRADIENT(ps);
1477     SPGradient *gr = SP_GRADIENT(ps);
1479     if (!gr->color) sp_gradient_ensure_colors(gr);
1481     SPLGPainter *lgp = g_new(SPLGPainter, 1);
1483     lgp->painter.type = SP_PAINTER_IND;
1484     lgp->painter.fill = sp_lg_fill;
1486     lgp->lg = lg;
1488     /** \todo
1489      * Technically speaking, we map NCOLORS on line [start,end] onto line
1490      * [0,1].  I almost think we should fill color array start and end in
1491      * that case. The alternative would be to leave these just empty garbage
1492      * or something similar. Originally I had 1023.9999 here - not sure
1493      * whether we have really to cut out ceil int (Lauris).
1494      */
1495     NR::Matrix color2norm(NR::identity());
1496     NR::Matrix color2px;
1497     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1498         NR::Matrix norm2pos(NR::identity());
1500         /* BBox to user coordinate system */
1501         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1503         NR::Matrix color2pos = color2norm * norm2pos;
1504         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1505         NR::Matrix color2user = color2tpos * bbox2user;
1506         color2px = color2user * full_transform;
1508     } else {
1509         /* Problem: What to do, if we have mixed lengths and percentages? */
1510         /* Currently we do ignore percentages at all, but that is not good (lauris) */
1512         NR::Matrix norm2pos(NR::identity());
1513         NR::Matrix color2pos = color2norm * norm2pos;
1514         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1515         color2px = color2tpos * full_transform;
1517     }
1519     nr_lgradient_renderer_setup(&lgp->lgr, gr->color, sp_gradient_get_spread(gr), &color2px,
1520                                 lg->x1.computed, lg->y1.computed,
1521                                 lg->x2.computed, lg->y2.computed);
1523     return (SPPainter *) lgp;
1526 static void
1527 sp_lineargradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1529     g_free(painter);
1532 /**
1533  * Directly set properties of linear gradient and request modified.
1534  */
1535 void
1536 sp_lineargradient_set_position(SPLinearGradient *lg,
1537                                gdouble x1, gdouble y1,
1538                                gdouble x2, gdouble y2)
1540     g_return_if_fail(lg != NULL);
1541     g_return_if_fail(SP_IS_LINEARGRADIENT(lg));
1543     /* fixme: units? (Lauris)  */
1544     lg->x1.set(SVGLength::NONE, x1, x1);
1545     lg->y1.set(SVGLength::NONE, y1, y1);
1546     lg->x2.set(SVGLength::NONE, x2, x2);
1547     lg->y2.set(SVGLength::NONE, y2, y2);
1549     SP_OBJECT(lg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1552 /**
1553  * Callback when linear gradient object is rendered.
1554  */
1555 static void
1556 sp_lg_fill(SPPainter *painter, NRPixBlock *pb)
1558     SPLGPainter *lgp = (SPLGPainter *) painter;
1560     if (lgp->lg->color == NULL) {
1561         sp_gradient_ensure_colors (lgp->lg);
1562         lgp->lgr.vector = lgp->lg->color;
1563     }
1565     nr_render((NRRenderer *) &lgp->lgr, pb, NULL);
1568 /*
1569  * Radial Gradient
1570  */
1572 class SPRGPainter;
1574 /// A context with radial gradient, painter, and gradient renderer.
1575 struct SPRGPainter {
1576     SPPainter painter;
1577     SPRadialGradient *rg;
1578     NRRGradientRenderer rgr;
1579 };
1581 static void sp_radialgradient_class_init(SPRadialGradientClass *klass);
1582 static void sp_radialgradient_init(SPRadialGradient *rg);
1584 static void sp_radialgradient_build(SPObject *object,
1585                                     SPDocument *document,
1586                                     Inkscape::XML::Node *repr);
1587 static void sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value);
1588 static Inkscape::XML::Node *sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1589                                                     guint flags);
1591 static SPPainter *sp_radialgradient_painter_new(SPPaintServer *ps,
1592                                                 NR::Matrix const &full_transform,
1593                                                 NR::Matrix const &parent_transform,
1594                                                 NRRect const *bbox);
1595 static void sp_radialgradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1597 static void sp_rg_fill(SPPainter *painter, NRPixBlock *pb);
1599 static SPGradientClass *rg_parent_class;
1601 /**
1602  * Register SPRadialGradient class and return its type.
1603  */
1604 GType
1605 sp_radialgradient_get_type()
1607     static GType type = 0;
1608     if (!type) {
1609         GTypeInfo info = {
1610             sizeof(SPRadialGradientClass),
1611             NULL, NULL,
1612             (GClassInitFunc) sp_radialgradient_class_init,
1613             NULL, NULL,
1614             sizeof(SPRadialGradient),
1615             16,
1616             (GInstanceInitFunc) sp_radialgradient_init,
1617             NULL,   /* value_table */
1618         };
1619         type = g_type_register_static(SP_TYPE_GRADIENT, "SPRadialGradient", &info, (GTypeFlags)0);
1620     }
1621     return type;
1624 /**
1625  * SPRadialGradient vtable initialization.
1626  */
1627 static void sp_radialgradient_class_init(SPRadialGradientClass *klass)
1629     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1630     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1632     rg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1634     sp_object_class->build = sp_radialgradient_build;
1635     sp_object_class->set = sp_radialgradient_set;
1636     sp_object_class->write = sp_radialgradient_write;
1638     ps_class->painter_new = sp_radialgradient_painter_new;
1639     ps_class->painter_free = sp_radialgradient_painter_free;
1642 /**
1643  * Callback for SPRadialGradient object initialization.
1644  */
1645 static void
1646 sp_radialgradient_init(SPRadialGradient *rg)
1648     rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1649     rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1650     rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1651     rg->fx.unset(SVGLength::PERCENT, 0.5, 0.5);
1652     rg->fy.unset(SVGLength::PERCENT, 0.5, 0.5);
1655 /**
1656  * Set radial gradient attributes from associated repr.
1657  */
1658 static void
1659 sp_radialgradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
1661     if (((SPObjectClass *) rg_parent_class)->build)
1662         (* ((SPObjectClass *) rg_parent_class)->build)(object, document, repr);
1664     sp_object_read_attr(object, "cx");
1665     sp_object_read_attr(object, "cy");
1666     sp_object_read_attr(object, "r");
1667     sp_object_read_attr(object, "fx");
1668     sp_object_read_attr(object, "fy");
1671 /**
1672  * Set radial gradient attribute.
1673  */
1674 static void
1675 sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value)
1677     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1679     switch (key) {
1680         case SP_ATTR_CX:
1681             if (!rg->cx.read(value)) {
1682                 rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1683             }
1684             if (!rg->fx._set) {
1685                 rg->fx.value = rg->cx.value;
1686                 rg->fx.computed = rg->cx.computed;
1687             }
1688             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1689             break;
1690         case SP_ATTR_CY:
1691             if (!rg->cy.read(value)) {
1692                 rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1693             }
1694             if (!rg->fy._set) {
1695                 rg->fy.value = rg->cy.value;
1696                 rg->fy.computed = rg->cy.computed;
1697             }
1698             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1699             break;
1700         case SP_ATTR_R:
1701             if (!rg->r.read(value)) {
1702                 rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1703             }
1704             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1705             break;
1706         case SP_ATTR_FX:
1707             if (!rg->fx.read(value)) {
1708                 rg->fx.unset(rg->cx.unit, rg->cx.value, rg->cx.computed);
1709             }
1710             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1711             break;
1712         case SP_ATTR_FY:
1713             if (!rg->fy.read(value)) {
1714                 rg->fy.unset(rg->cy.unit, rg->cy.value, rg->cy.computed);
1715             }
1716             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1717             break;
1718         default:
1719             if (((SPObjectClass *) rg_parent_class)->set)
1720                 ((SPObjectClass *) rg_parent_class)->set(object, key, value);
1721             break;
1722     }
1725 /**
1726  * Write radial gradient attributes to associated repr.
1727  */
1728 static Inkscape::XML::Node *
1729 sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1731     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1733     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1734         repr = xml_doc->createElement("svg:radialGradient");
1735     }
1737     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cx._set) sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
1738     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cy._set) sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
1739     if ((flags & SP_OBJECT_WRITE_ALL) || rg->r._set) sp_repr_set_svg_double(repr, "r", rg->r.computed);
1740     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fx._set) sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
1741     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fy._set) sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
1743     if (((SPObjectClass *) rg_parent_class)->write)
1744         (* ((SPObjectClass *) rg_parent_class)->write)(object, xml_doc, repr, flags);
1746     return repr;
1749 /**
1750  * Create radial gradient context.
1751  */
1752 static SPPainter *
1753 sp_radialgradient_painter_new(SPPaintServer *ps,
1754                               NR::Matrix const &full_transform,
1755                               NR::Matrix const &/*parent_transform*/,
1756                               NRRect const *bbox)
1758     SPRadialGradient *rg = SP_RADIALGRADIENT(ps);
1759     SPGradient *gr = SP_GRADIENT(ps);
1761     if (!gr->color) sp_gradient_ensure_colors(gr);
1763     SPRGPainter *rgp = g_new(SPRGPainter, 1);
1765     rgp->painter.type = SP_PAINTER_IND;
1766     rgp->painter.fill = sp_rg_fill;
1768     rgp->rg = rg;
1770     NR::Matrix gs2px;
1772     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1773         /** \todo
1774          * fixme: We may try to normalize here too, look at
1775          * linearGradient (Lauris)
1776          */
1778         /* BBox to user coordinate system */
1779         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1781         NR::Matrix gs2user = gr->gradientTransform * bbox2user;
1783         gs2px = gs2user * full_transform;
1784     } else {
1785         /** \todo
1786          * Problem: What to do, if we have mixed lengths and percentages?
1787          * Currently we do ignore percentages at all, but that is not
1788          * good (lauris)
1789          */
1791         gs2px = gr->gradientTransform * full_transform;
1792     }
1794     nr_rgradient_renderer_setup(&rgp->rgr, gr->color, sp_gradient_get_spread(gr),
1795                                 &gs2px,
1796                                 rg->cx.computed, rg->cy.computed,
1797                                 rg->fx.computed, rg->fy.computed,
1798                                 rg->r.computed);
1800     return (SPPainter *) rgp;
1803 static void
1804 sp_radialgradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1806     g_free(painter);
1809 /**
1810  * Directly set properties of radial gradient and request modified.
1811  */
1812 void
1813 sp_radialgradient_set_position(SPRadialGradient *rg,
1814                                gdouble cx, gdouble cy, gdouble fx, gdouble fy, gdouble r)
1816     g_return_if_fail(rg != NULL);
1817     g_return_if_fail(SP_IS_RADIALGRADIENT(rg));
1819     /* fixme: units? (Lauris)  */
1820     rg->cx.set(SVGLength::NONE, cx, cx);
1821     rg->cy.set(SVGLength::NONE, cy, cy);
1822     rg->fx.set(SVGLength::NONE, fx, fx);
1823     rg->fy.set(SVGLength::NONE, fy, fy);
1824     rg->r.set(SVGLength::NONE, r, r);
1826     SP_OBJECT(rg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1829 /**
1830  * Callback when radial gradient object is rendered.
1831  */
1832 static void
1833 sp_rg_fill(SPPainter *painter, NRPixBlock *pb)
1835     SPRGPainter *rgp = (SPRGPainter *) painter;
1837     if (rgp->rg->color == NULL) {
1838         sp_gradient_ensure_colors (rgp->rg);
1839         rgp->rgr.vector = rgp->rg->color;
1840     }
1842     nr_render((NRRenderer *) &rgp->rgr, pb, NULL);
1845 /*
1846   Local Variables:
1847   mode:c++
1848   c-file-style:"stroustrup"
1849   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1850   indent-tabs-mode:nil
1851   fill-column:99
1852   End:
1853 */
1854 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :