Code

do the same remembering for stop opacity
[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
22 #include <libnr/nr-matrix-div.h>
23 #include <libnr/nr-matrix-fns.h>
24 #include <libnr/nr-matrix-ops.h>
25 #include <libnr/nr-matrix-scale-ops.h>
26 #include <libnr/nr-matrix-translate-ops.h>
27 #include "libnr/nr-scale-translate-ops.h"
29 #include <sigc++/functors/ptr_fun.h>
30 #include <sigc++/adaptors/bind.h>
32 #include "libnr/nr-gradient.h"
33 #include "svg/svg.h"
34 #include "svg/svg-color.h"
35 #include "svg/css-ostringstream.h"
36 #include "attributes.h"
37 #include "document-private.h"
38 #include "gradient-chemistry.h"
39 #include "sp-gradient-reference.h"
40 #include "sp-linear-gradient.h"
41 #include "sp-radial-gradient.h"
42 #include "sp-stop.h"
43 #include "streq.h"
44 #include "uri.h"
45 #include "xml/repr.h"
47 #define SP_MACROS_SILENT
48 #include "macros.h"
50 /// Has to be power of 2
51 #define NCOLORS NR_GRADIENT_VECTOR_LENGTH
53 static void sp_stop_class_init(SPStopClass *klass);
54 static void sp_stop_init(SPStop *stop);
56 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
57 static void sp_stop_set(SPObject *object, unsigned key, gchar const *value);
58 static Inkscape::XML::Node *sp_stop_write(SPObject *object, Inkscape::XML::Node *repr, guint flags);
60 static SPObjectClass *stop_parent_class;
62 /**
63  * Registers SPStop class and returns its type.
64  */
65 GType
66 sp_stop_get_type()
67 {
68     static GType type = 0;
69     if (!type) {
70         GTypeInfo info = {
71             sizeof(SPStopClass),
72             NULL, NULL,
73             (GClassInitFunc) sp_stop_class_init,
74             NULL, NULL,
75             sizeof(SPStop),
76             16,
77             (GInstanceInitFunc) sp_stop_init,
78             NULL,   /* value_table */
79         };
80         type = g_type_register_static(SP_TYPE_OBJECT, "SPStop", &info, (GTypeFlags)0);
81     }
82     return type;
83 }
85 /**
86  * Callback to initialize SPStop vtable.
87  */
88 static void sp_stop_class_init(SPStopClass *klass)
89 {
90     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
92     stop_parent_class = (SPObjectClass *) g_type_class_ref(SP_TYPE_OBJECT);
94     sp_object_class->build = sp_stop_build;
95     sp_object_class->set = sp_stop_set;
96     sp_object_class->write = sp_stop_write;
97 }
99 /**
100  * Callback to initialize SPStop object.
101  */
102 static void
103 sp_stop_init(SPStop *stop)
105     stop->offset = 0.0;
106     stop->currentColor = false;
107     sp_color_set_rgb_rgba32(&stop->specified_color, 0x000000ff);
108     stop->opacity = 1.0;
111 /**
112  * Virtual build: set stop attributes from its associated XML node.
113  */
114 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
116     if (((SPObjectClass *) stop_parent_class)->build)
117         (* ((SPObjectClass *) stop_parent_class)->build)(object, document, repr);
119     sp_object_read_attr(object, "offset");
120     sp_object_read_attr(object, "stop-color");
121     sp_object_read_attr(object, "stop-opacity");
122     sp_object_read_attr(object, "style");
125 /**
126  * Virtual set: set attribute to value.
127  */
128 static void
129 sp_stop_set(SPObject *object, unsigned key, gchar const *value)
131     SPStop *stop = SP_STOP(object);
133     switch (key) {
134         case SP_ATTR_STYLE: {
135         /** \todo
136          * fixme: We are reading simple values 3 times during build (Lauris).
137          * \par
138          * We need presentation attributes etc.
139          * \par
140          * remove the hackish "style reading" from here: see comments in
141          * sp_object_get_style_property about the bugs in our current
142          * approach.  However, note that SPStyle doesn't currently have
143          * stop-color and stop-opacity properties.
144          */
145             {
146                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
147                 if (streq(p, "currentColor")) {
148                     stop->currentColor = true;
149                 } else {
150                     guint32 const color = sp_svg_read_color(p, 0);
151                     sp_color_set_rgb_rgba32(&stop->specified_color, color);
152                 }
153             }
154             {
155                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
156                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
157                 stop->opacity = opacity;
158             }
159             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
160             break;
161         }
162         case SP_PROP_STOP_COLOR: {
163             {
164                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
165                 if (streq(p, "currentColor")) {
166                     stop->currentColor = true;
167                 } else {
168                     stop->currentColor = false;
169                     guint32 const color = sp_svg_read_color(p, 0);
170                     sp_color_set_rgb_rgba32(&stop->specified_color, color);
171                 }
172             }
173             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
174             break;
175         }
176         case SP_PROP_STOP_OPACITY: {
177             {
178                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
179                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
180                 stop->opacity = opacity;
181             }
182             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
183             break;
184         }
185         case SP_ATTR_OFFSET: {
186             stop->offset = sp_svg_read_percentage(value, 0.0);
187             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
188             break;
189         }
190         default: {
191             if (((SPObjectClass *) stop_parent_class)->set)
192                 (* ((SPObjectClass *) stop_parent_class)->set)(object, key, value);
193             break;
194         }
195     }
198 /**
199  * Virtual write: write object attributes to repr.
200  */
201 static Inkscape::XML::Node *
202 sp_stop_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
204     SPStop *stop = SP_STOP(object);
206     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
207         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
208         repr = xml_doc->createElement("svg:stop");
209     }
211     guint32 specifiedcolor = sp_color_get_rgba32_ualpha(&stop->specified_color, 255);
212     gfloat opacity = stop->opacity;
214     if (((SPObjectClass *) stop_parent_class)->write)
215         (* ((SPObjectClass *) stop_parent_class)->write)(object, repr, flags);
217     // Since we do a hackish style setting here (because SPStyle does not support stop-color and
218     // stop-opacity), we must do it AFTER calling the parent write method; otherwise
219     // sp_object_write would clear our style= attribute (bug 1695287)
221     Inkscape::CSSOStringStream os;
222     os << "stop-color:";
223     if (stop->currentColor) {
224         os << "currentColor";
225     } else {
226         gchar c[64];
227         sp_svg_write_color(c, 64, specifiedcolor);
228         os << c;
229     }
230     os << ";stop-opacity:" << opacity;
231     repr->setAttribute("style", os.str().c_str());
232     repr->setAttribute("stop-color", NULL);
233     repr->setAttribute("stop-opacity", NULL);
234     sp_repr_set_css_double(repr, "offset", stop->offset);
235     /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no sense
236      * for offset proportions. */
238     return repr;
241 /**
242  * Return stop's color as 32bit value.
243  */
244 guint32
245 sp_stop_get_rgba32(SPStop const *const stop)
247     guint32 rgb0 = 0;
248     /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
249      * value depends on user agent, and don't give any further restrictions that I can
250      * see.) */
251     if (stop->currentColor) {
252         char const *str = sp_object_get_style_property(stop, "color", NULL);
253         if (str) {
254             rgb0 = sp_svg_read_color(str, rgb0);
255         }
256         unsigned const alpha = static_cast<unsigned>(stop->opacity * 0xff + 0.5);
257         g_return_val_if_fail((alpha & ~0xff) == 0,
258                              rgb0 | 0xff);
259         return rgb0 | alpha;
260     } else {
261         return sp_color_get_rgba32_falpha(&stop->specified_color, stop->opacity);
262     }
265 /**
266  * Return stop's color as SPColor.
267  */
268 static SPColor
269 sp_stop_get_color(SPStop const *const stop)
271     if (stop->currentColor) {
272         char const *str = sp_object_get_style_property(stop, "color", NULL);
273         guint32 const dfl = 0;
274         /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
275          * value depends on user agent, and don't give any further restrictions that I can
276          * see.) */
277         guint32 color = dfl;
278         if (str) {
279             color = sp_svg_read_color(str, dfl);
280         }
281         SPColor ret;
282         sp_color_set_rgb_rgba32(&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::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     }
619     
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::Node *repr, guint flags)
646     SPGradient *gr = SP_GRADIENT(object);
648     if (((SPObjectClass *) gradient_parent_class)->write)
649         (* ((SPObjectClass *) gradient_parent_class)->write)(object, 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(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, 64, sp_color_get_rgba32_ualpha(&gr->vector.stops[i].color, 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             sp_color_set_rgb_rgba32(&gstop.color, 0x00000000);
1038             gstop.opacity = 0.0;
1039             gr->vector.stops.push_back(gstop);
1040         }
1041         {
1042             SPGradientStop gstop;
1043             gstop.offset = 1.0;
1044             sp_color_set_rgb_rgba32(&gstop.color, 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             sp_color_copy(&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             sp_color_copy(&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 = sp_color_get_rgba32_falpha(&gr->vector.stops[i].color,
1091                                                    gr->vector.stops[i].opacity);
1092         gint r0 = (color >> 24) & 0xff;
1093         gint g0 = (color >> 16) & 0xff;
1094         gint b0 = (color >> 8) & 0xff;
1095         gint a0 = color & 0xff;
1096         color = sp_color_get_rgba32_falpha(&gr->vector.stops[i + 1].color,
1097                                            gr->vector.stops[i + 1].opacity);
1098         gint r1 = (color >> 24) & 0xff;
1099         gint g1 = (color >> 16) & 0xff;
1100         gint b1 = (color >> 8) & 0xff;
1101         gint a1 = color & 0xff;
1102         gint o0 = (gint) floor(gr->vector.stops[i].offset * (NCOLORS - 0.001));
1103         gint o1 = (gint) floor(gr->vector.stops[i + 1].offset * (NCOLORS - 0.001));
1104         if (o1 > o0) {
1105             gint dr = ((r1 - r0) << 16) / (o1 - o0);
1106             gint dg = ((g1 - g0) << 16) / (o1 - o0);
1107             gint db = ((b1 - b0) << 16) / (o1 - o0);
1108             gint da = ((a1 - a0) << 16) / (o1 - o0);
1109             gint r = r0 << 16;
1110             gint g = g0 << 16;
1111             gint b = b0 << 16;
1112             gint a = a0 << 16;
1113             for (int j = o0; j < o1 + 1; j++) {
1114                 gr->color[4 * j] = r >> 16;
1115                 gr->color[4 * j + 1] = g >> 16;
1116                 gr->color[4 * j + 2] = b >> 16;
1117                 gr->color[4 * j + 3] = a >> 16;
1118                 r += dr;
1119                 g += dg;
1120                 b += db;
1121                 a += da;
1122             }
1123         }
1124     }
1127 /**
1128  * Renders gradient vector to buffer as line.
1129  *
1130  * RGB buffer background should be set up beforehand.
1131  *
1132  * @param len,width,height,rowstride Buffer parameters (1 or 2 dimensional).
1133  * @param span Full integer width of requested gradient.
1134  * @param pos Buffer starting position in span.
1135  */
1136 static void
1137 sp_gradient_render_vector_line_rgba(SPGradient *const gradient, guchar *buf,
1138                                     gint const len, gint const pos, gint const span)
1140     g_return_if_fail(gradient != NULL);
1141     g_return_if_fail(SP_IS_GRADIENT(gradient));
1142     g_return_if_fail(buf != NULL);
1143     g_return_if_fail(len > 0);
1144     g_return_if_fail(pos >= 0);
1145     g_return_if_fail(pos + len <= span);
1146     g_return_if_fail(span > 0);
1148     if (!gradient->color) {
1149         sp_gradient_ensure_colors(gradient);
1150     }
1152     gint idx = (pos * 1024 << 8) / span;
1153     gint didx = (1024 << 8) / span;
1155     for (gint x = 0; x < len; x++) {
1156         /// \todo Can this be done with 4 byte copies?
1157         *buf++ = gradient->color[4 * (idx >> 8)];
1158         *buf++ = gradient->color[4 * (idx >> 8) + 1];
1159         *buf++ = gradient->color[4 * (idx >> 8) + 2];
1160         *buf++ = gradient->color[4 * (idx >> 8) + 3];
1161         idx += didx;
1162     }
1165 /**
1166  * Render rectangular RGBA area from gradient vector.
1167  */
1168 void
1169 sp_gradient_render_vector_block_rgba(SPGradient *const gradient, guchar *buf,
1170                                      gint const width, gint const height, gint const rowstride,
1171                                      gint const pos, gint const span, bool const horizontal)
1173     g_return_if_fail(gradient != NULL);
1174     g_return_if_fail(SP_IS_GRADIENT(gradient));
1175     g_return_if_fail(buf != NULL);
1176     g_return_if_fail(width > 0);
1177     g_return_if_fail(height > 0);
1178     g_return_if_fail(pos >= 0);
1179     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1180     g_return_if_fail(span > 0);
1182     if (horizontal) {
1183         sp_gradient_render_vector_line_rgba(gradient, buf, width, pos, span);
1184         for (gint y = 1; y < height; y++) {
1185             memcpy(buf + y * rowstride, buf, 4 * width);
1186         }
1187     } else {
1188         guchar *tmp = (guchar *)alloca(4 * height);
1189         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1190         for (gint y = 0; y < height; y++) {
1191             guchar *b = buf + y * rowstride;
1192             for (gint x = 0; x < width; x++) {
1193                 *b++ = tmp[0];
1194                 *b++ = tmp[1];
1195                 *b++ = tmp[2];
1196                 *b++ = tmp[3];
1197             }
1198             tmp += 4;
1199         }
1200     }
1203 /**
1204  * Render rectangular RGB area from gradient vector.
1205  */
1206 void
1207 sp_gradient_render_vector_block_rgb(SPGradient *gradient, guchar *buf,
1208                                     gint const width, gint const height, gint const rowstride,
1209                                     gint const pos, gint const span, bool const horizontal)
1211     g_return_if_fail(gradient != NULL);
1212     g_return_if_fail(SP_IS_GRADIENT(gradient));
1213     g_return_if_fail(buf != NULL);
1214     g_return_if_fail(width > 0);
1215     g_return_if_fail(height > 0);
1216     g_return_if_fail(pos >= 0);
1217     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1218     g_return_if_fail(span > 0);
1220     if (horizontal) {
1221         guchar *tmp = (guchar*)alloca(4 * width);
1222         sp_gradient_render_vector_line_rgba(gradient, tmp, width, pos, span);
1223         for (gint y = 0; y < height; y++) {
1224             guchar *t = tmp;
1225             for (gint x = 0; x < width; x++) {
1226                 gint a = t[3];
1227                 gint fc = (t[0] - buf[0]) * a;
1228                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1229                 fc = (t[1] - buf[1]) * a;
1230                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1231                 fc = (t[2] - buf[2]) * a;
1232                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1233                 buf += 3;
1234                 t += 4;
1235             }
1236         }
1237     } else {
1238         guchar *tmp = (guchar*)alloca(4 * height);
1239         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1240         for (gint y = 0; y < height; y++) {
1241             guchar *t = tmp + 4 * y;
1242             for (gint x = 0; x < width; x++) {
1243                 gint a = t[3];
1244                 gint fc = (t[0] - buf[0]) * a;
1245                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1246                 fc = (t[1] - buf[1]) * a;
1247                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1248                 fc = (t[2] - buf[2]) * a;
1249                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1250             }
1251         }
1252     }
1255 NR::Matrix
1256 sp_gradient_get_g2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1258     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1259         return ( NR::scale(bbox.dimensions())
1260                  * NR::translate(bbox.min())
1261                  * ctm );
1262     } else {
1263         return ctm;
1264     }
1267 NR::Matrix
1268 sp_gradient_get_gs2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1270     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1271         return ( gr->gradientTransform
1272                  * NR::scale(bbox.dimensions())
1273                  * NR::translate(bbox.min())
1274                  * ctm );
1275     } else {
1276         return gr->gradientTransform * ctm;
1277     }
1280 void
1281 sp_gradient_set_gs2d_matrix(SPGradient *gr, NR::Matrix const &ctm,
1282                             NR::Rect const &bbox, NR::Matrix const &gs2d)
1284     gr->gradientTransform = gs2d / ctm;
1285     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) {
1286         gr->gradientTransform = ( gr->gradientTransform
1287                                   / NR::translate(bbox.min())
1288                                   / NR::scale(bbox.dimensions()) );
1289     }
1290     gr->gradientTransform_set = TRUE;
1292     SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1295 /*
1296  * Linear Gradient
1297  */
1299 class SPLGPainter;
1301 /// A context with linear gradient, painter, and gradient renderer.
1302 struct SPLGPainter {
1303     SPPainter painter;
1304     SPLinearGradient *lg;
1306     NRLGradientRenderer lgr;
1307 };
1309 static void sp_lineargradient_class_init(SPLinearGradientClass *klass);
1310 static void sp_lineargradient_init(SPLinearGradient *lg);
1312 static void sp_lineargradient_build(SPObject *object,
1313                                     SPDocument *document,
1314                                     Inkscape::XML::Node *repr);
1315 static void sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value);
1316 static Inkscape::XML::Node *sp_lineargradient_write(SPObject *object, Inkscape::XML::Node *repr,
1317                                                     guint flags);
1319 static SPPainter *sp_lineargradient_painter_new(SPPaintServer *ps,
1320                                                 NR::Matrix const &full_transform,
1321                                                 NR::Matrix const &parent_transform,
1322                                                 NRRect const *bbox);
1323 static void sp_lineargradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1325 static void sp_lg_fill(SPPainter *painter, NRPixBlock *pb);
1327 static SPGradientClass *lg_parent_class;
1329 /**
1330  * Register SPLinearGradient class and return its type.
1331  */
1332 GType
1333 sp_lineargradient_get_type()
1335     static GType type = 0;
1336     if (!type) {
1337         GTypeInfo info = {
1338             sizeof(SPLinearGradientClass),
1339             NULL, NULL,
1340             (GClassInitFunc) sp_lineargradient_class_init,
1341             NULL, NULL,
1342             sizeof(SPLinearGradient),
1343             16,
1344             (GInstanceInitFunc) sp_lineargradient_init,
1345             NULL,   /* value_table */
1346         };
1347         type = g_type_register_static(SP_TYPE_GRADIENT, "SPLinearGradient", &info, (GTypeFlags)0);
1348     }
1349     return type;
1352 /**
1353  * SPLinearGradient vtable initialization.
1354  */
1355 static void sp_lineargradient_class_init(SPLinearGradientClass *klass)
1357     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1358     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1360     lg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1362     sp_object_class->build = sp_lineargradient_build;
1363     sp_object_class->set = sp_lineargradient_set;
1364     sp_object_class->write = sp_lineargradient_write;
1366     ps_class->painter_new = sp_lineargradient_painter_new;
1367     ps_class->painter_free = sp_lineargradient_painter_free;
1370 /**
1371  * Callback for SPLinearGradient object initialization.
1372  */
1373 static void sp_lineargradient_init(SPLinearGradient *lg)
1375     lg->x1.unset(SVGLength::PERCENT, 0.0, 0.0);
1376     lg->y1.unset(SVGLength::PERCENT, 0.5, 0.5);
1377     lg->x2.unset(SVGLength::PERCENT, 1.0, 1.0);
1378     lg->y2.unset(SVGLength::PERCENT, 0.5, 0.5);
1381 /**
1382  * Callback: set attributes from associated repr.
1383  */
1384 static void sp_lineargradient_build(SPObject *object,
1385                                     SPDocument *document,
1386                                     Inkscape::XML::Node *repr)
1388     if (((SPObjectClass *) lg_parent_class)->build)
1389         (* ((SPObjectClass *) lg_parent_class)->build)(object, document, repr);
1391     sp_object_read_attr(object, "x1");
1392     sp_object_read_attr(object, "y1");
1393     sp_object_read_attr(object, "x2");
1394     sp_object_read_attr(object, "y2");
1397 /**
1398  * Callback: set attribute.
1399  */
1400 static void
1401 sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value)
1403     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1405     switch (key) {
1406         case SP_ATTR_X1:
1407             lg->x1.readOrUnset(value, SVGLength::PERCENT, 0.0, 0.0);
1408             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1409             break;
1410         case SP_ATTR_Y1:
1411             lg->y1.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1412             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1413             break;
1414         case SP_ATTR_X2:
1415             lg->x2.readOrUnset(value, SVGLength::PERCENT, 1.0, 1.0);
1416             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1417             break;
1418         case SP_ATTR_Y2:
1419             lg->y2.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1420             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1421             break;
1422         default:
1423             if (((SPObjectClass *) lg_parent_class)->set)
1424                 (* ((SPObjectClass *) lg_parent_class)->set)(object, key, value);
1425             break;
1426     }
1429 /**
1430  * Callback: write attributes to associated repr.
1431  */
1432 static Inkscape::XML::Node *
1433 sp_lineargradient_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
1435     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1437     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1438         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
1439         repr = xml_doc->createElement("svg:linearGradient");
1440     }
1442     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x1._set)
1443         sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
1444     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y1._set)
1445         sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
1446     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x2._set)
1447         sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
1448     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y2._set)
1449         sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
1451     if (((SPObjectClass *) lg_parent_class)->write)
1452         (* ((SPObjectClass *) lg_parent_class)->write)(object, repr, flags);
1454     return repr;
1457 /**
1458  * Create linear gradient context.
1459  *
1460  * Basically we have to deal with transformations
1461  *
1462  * 1) color2norm - maps point in (0,NCOLORS) vector to (0,1) vector
1463  * 2) norm2pos - maps (0,1) vector to x1,y1 - x2,y2
1464  * 2) gradientTransform
1465  * 3) bbox2user
1466  * 4) ctm == userspace to pixel grid
1467  *
1468  * See also (*) in sp-pattern about why we may need parent_transform.
1469  *
1470  * \todo (point 1 above) fixme: I do not know how to deal with start > 0
1471  * and end < 1.
1472  */
1473 static SPPainter *
1474 sp_lineargradient_painter_new(SPPaintServer *ps,
1475                               NR::Matrix const &full_transform,
1476                               NR::Matrix const &parent_transform,
1477                               NRRect const *bbox)
1479     SPLinearGradient *lg = SP_LINEARGRADIENT(ps);
1480     SPGradient *gr = SP_GRADIENT(ps);
1482     if (!gr->color) sp_gradient_ensure_colors(gr);
1484     SPLGPainter *lgp = g_new(SPLGPainter, 1);
1486     lgp->painter.type = SP_PAINTER_IND;
1487     lgp->painter.fill = sp_lg_fill;
1489     lgp->lg = lg;
1491     /** \todo
1492      * Technically speaking, we map NCOLORS on line [start,end] onto line
1493      * [0,1].  I almost think we should fill color array start and end in
1494      * that case. The alternative would be to leave these just empty garbage
1495      * or something similar. Originally I had 1023.9999 here - not sure
1496      * whether we have really to cut out ceil int (Lauris).
1497      */
1498     NR::Matrix color2norm(NR::identity());
1499     NR::Matrix color2px;
1500     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1501         NR::Matrix norm2pos(NR::identity());
1503         /* BBox to user coordinate system */
1504         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1506         NR::Matrix color2pos = color2norm * norm2pos;
1507         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1508         NR::Matrix color2user = color2tpos * bbox2user;
1509         color2px = color2user * full_transform;
1511     } else {
1512         /* Problem: What to do, if we have mixed lengths and percentages? */
1513         /* Currently we do ignore percentages at all, but that is not good (lauris) */
1515         NR::Matrix norm2pos(NR::identity());
1516         NR::Matrix color2pos = color2norm * norm2pos;
1517         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1518         color2px = color2tpos * full_transform;
1520     }
1522     NRMatrix v2px;
1523     color2px.copyto(&v2px);
1525     nr_lgradient_renderer_setup(&lgp->lgr, gr->color, sp_gradient_get_spread(gr), &v2px,
1526                                 lg->x1.computed, lg->y1.computed,
1527                                 lg->x2.computed, lg->y2.computed);
1529     return (SPPainter *) lgp;
1532 static void
1533 sp_lineargradient_painter_free(SPPaintServer *ps, SPPainter *painter)
1535     g_free(painter);
1538 /**
1539  * Directly set properties of linear gradient and request modified.
1540  */
1541 void
1542 sp_lineargradient_set_position(SPLinearGradient *lg,
1543                                gdouble x1, gdouble y1,
1544                                gdouble x2, gdouble y2)
1546     g_return_if_fail(lg != NULL);
1547     g_return_if_fail(SP_IS_LINEARGRADIENT(lg));
1549     /* fixme: units? (Lauris)  */
1550     lg->x1.set(SVGLength::NONE, x1, x1);
1551     lg->y1.set(SVGLength::NONE, y1, y1);
1552     lg->x2.set(SVGLength::NONE, x2, x2);
1553     lg->y2.set(SVGLength::NONE, y2, y2);
1555     SP_OBJECT(lg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1558 /**
1559  * Callback when linear gradient object is rendered.
1560  */
1561 static void
1562 sp_lg_fill(SPPainter *painter, NRPixBlock *pb)
1564     SPLGPainter *lgp = (SPLGPainter *) painter;
1566     if (lgp->lg->color == NULL) {
1567         sp_gradient_ensure_colors (lgp->lg);
1568         lgp->lgr.vector = lgp->lg->color;
1569     }
1571     nr_render((NRRenderer *) &lgp->lgr, pb, NULL);
1574 /*
1575  * Radial Gradient
1576  */
1578 class SPRGPainter;
1580 /// A context with radial gradient, painter, and gradient renderer.
1581 struct SPRGPainter {
1582     SPPainter painter;
1583     SPRadialGradient *rg;
1584     NRRGradientRenderer rgr;
1585 };
1587 static void sp_radialgradient_class_init(SPRadialGradientClass *klass);
1588 static void sp_radialgradient_init(SPRadialGradient *rg);
1590 static void sp_radialgradient_build(SPObject *object,
1591                                     SPDocument *document,
1592                                     Inkscape::XML::Node *repr);
1593 static void sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value);
1594 static Inkscape::XML::Node *sp_radialgradient_write(SPObject *object, Inkscape::XML::Node *repr,
1595                                                     guint flags);
1597 static SPPainter *sp_radialgradient_painter_new(SPPaintServer *ps,
1598                                                 NR::Matrix const &full_transform,
1599                                                 NR::Matrix const &parent_transform,
1600                                                 NRRect const *bbox);
1601 static void sp_radialgradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1603 static void sp_rg_fill(SPPainter *painter, NRPixBlock *pb);
1605 static SPGradientClass *rg_parent_class;
1607 /**
1608  * Register SPRadialGradient class and return its type.
1609  */
1610 GType
1611 sp_radialgradient_get_type()
1613     static GType type = 0;
1614     if (!type) {
1615         GTypeInfo info = {
1616             sizeof(SPRadialGradientClass),
1617             NULL, NULL,
1618             (GClassInitFunc) sp_radialgradient_class_init,
1619             NULL, NULL,
1620             sizeof(SPRadialGradient),
1621             16,
1622             (GInstanceInitFunc) sp_radialgradient_init,
1623             NULL,   /* value_table */
1624         };
1625         type = g_type_register_static(SP_TYPE_GRADIENT, "SPRadialGradient", &info, (GTypeFlags)0);
1626     }
1627     return type;
1630 /**
1631  * SPRadialGradient vtable initialization.
1632  */
1633 static void sp_radialgradient_class_init(SPRadialGradientClass *klass)
1635     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1636     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1638     rg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1640     sp_object_class->build = sp_radialgradient_build;
1641     sp_object_class->set = sp_radialgradient_set;
1642     sp_object_class->write = sp_radialgradient_write;
1644     ps_class->painter_new = sp_radialgradient_painter_new;
1645     ps_class->painter_free = sp_radialgradient_painter_free;
1648 /**
1649  * Callback for SPRadialGradient object initialization.
1650  */
1651 static void
1652 sp_radialgradient_init(SPRadialGradient *rg)
1654     rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1655     rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1656     rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1657     rg->fx.unset(SVGLength::PERCENT, 0.5, 0.5);
1658     rg->fy.unset(SVGLength::PERCENT, 0.5, 0.5);
1661 /**
1662  * Set radial gradient attributes from associated repr.
1663  */
1664 static void
1665 sp_radialgradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
1667     if (((SPObjectClass *) rg_parent_class)->build)
1668         (* ((SPObjectClass *) rg_parent_class)->build)(object, document, repr);
1670     sp_object_read_attr(object, "cx");
1671     sp_object_read_attr(object, "cy");
1672     sp_object_read_attr(object, "r");
1673     sp_object_read_attr(object, "fx");
1674     sp_object_read_attr(object, "fy");
1677 /**
1678  * Set radial gradient attribute.
1679  */
1680 static void
1681 sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value)
1683     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1685     switch (key) {
1686         case SP_ATTR_CX:
1687             if (!rg->cx.read(value)) {
1688                 rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1689             }
1690             if (!rg->fx._set) {
1691                 rg->fx.value = rg->cx.value;
1692                 rg->fx.computed = rg->cx.computed;
1693             }
1694             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1695             break;
1696         case SP_ATTR_CY:
1697             if (!rg->cy.read(value)) {
1698                 rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1699             }
1700             if (!rg->fy._set) {
1701                 rg->fy.value = rg->cy.value;
1702                 rg->fy.computed = rg->cy.computed;
1703             }
1704             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1705             break;
1706         case SP_ATTR_R:
1707             if (!rg->r.read(value)) {
1708                 rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1709             }
1710             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1711             break;
1712         case SP_ATTR_FX:
1713             if (!rg->fx.read(value)) {
1714                 rg->fx.unset(rg->cx.unit, rg->cx.value, rg->cx.computed);
1715             }
1716             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1717             break;
1718         case SP_ATTR_FY:
1719             if (!rg->fy.read(value)) {
1720                 rg->fy.unset(rg->cy.unit, rg->cy.value, rg->cy.computed);
1721             }
1722             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1723             break;
1724         default:
1725             if (((SPObjectClass *) rg_parent_class)->set)
1726                 ((SPObjectClass *) rg_parent_class)->set(object, key, value);
1727             break;
1728     }
1731 /**
1732  * Write radial gradient attributes to associated repr.
1733  */
1734 static Inkscape::XML::Node *
1735 sp_radialgradient_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
1737     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1739     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1740         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
1741         repr = xml_doc->createElement("svg:radialGradient");
1742     }
1744     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cx._set) sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
1745     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cy._set) sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
1746     if ((flags & SP_OBJECT_WRITE_ALL) || rg->r._set) sp_repr_set_svg_double(repr, "r", rg->r.computed);
1747     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fx._set) sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
1748     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fy._set) sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
1750     if (((SPObjectClass *) rg_parent_class)->write)
1751         (* ((SPObjectClass *) rg_parent_class)->write)(object, repr, flags);
1753     return repr;
1756 /**
1757  * Create radial gradient context.
1758  */
1759 static SPPainter *
1760 sp_radialgradient_painter_new(SPPaintServer *ps,
1761                               NR::Matrix const &full_transform,
1762                               NR::Matrix const &parent_transform,
1763                               NRRect const *bbox)
1765     SPRadialGradient *rg = SP_RADIALGRADIENT(ps);
1766     SPGradient *gr = SP_GRADIENT(ps);
1768     if (!gr->color) sp_gradient_ensure_colors(gr);
1770     SPRGPainter *rgp = g_new(SPRGPainter, 1);
1772     rgp->painter.type = SP_PAINTER_IND;
1773     rgp->painter.fill = sp_rg_fill;
1775     rgp->rg = rg;
1777     NR::Matrix gs2px;
1779     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1780         /** \todo
1781          * fixme: We may try to normalize here too, look at
1782          * linearGradient (Lauris)
1783          */
1785         /* BBox to user coordinate system */
1786         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1788         NR::Matrix gs2user = gr->gradientTransform * bbox2user;
1790         gs2px = gs2user * full_transform;
1791     } else {
1792         /** \todo
1793          * Problem: What to do, if we have mixed lengths and percentages?
1794          * Currently we do ignore percentages at all, but that is not
1795          * good (lauris)
1796          */
1798         gs2px = gr->gradientTransform * full_transform;
1799     }
1801     NRMatrix gs2px_nr;
1802     gs2px.copyto(&gs2px_nr);
1804     nr_rgradient_renderer_setup(&rgp->rgr, gr->color, sp_gradient_get_spread(gr),
1805                                 &gs2px_nr,
1806                                 rg->cx.computed, rg->cy.computed,
1807                                 rg->fx.computed, rg->fy.computed,
1808                                 rg->r.computed);
1810     return (SPPainter *) rgp;
1813 static void
1814 sp_radialgradient_painter_free(SPPaintServer *ps, SPPainter *painter)
1816     g_free(painter);
1819 /**
1820  * Directly set properties of radial gradient and request modified.
1821  */
1822 void
1823 sp_radialgradient_set_position(SPRadialGradient *rg,
1824                                gdouble cx, gdouble cy, gdouble fx, gdouble fy, gdouble r)
1826     g_return_if_fail(rg != NULL);
1827     g_return_if_fail(SP_IS_RADIALGRADIENT(rg));
1829     /* fixme: units? (Lauris)  */
1830     rg->cx.set(SVGLength::NONE, cx, cx);
1831     rg->cy.set(SVGLength::NONE, cy, cy);
1832     rg->fx.set(SVGLength::NONE, fx, fx);
1833     rg->fy.set(SVGLength::NONE, fy, fy);
1834     rg->r.set(SVGLength::NONE, r, r);
1836     SP_OBJECT(rg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1839 /**
1840  * Callback when radial gradient object is rendered.
1841  */
1842 static void
1843 sp_rg_fill(SPPainter *painter, NRPixBlock *pb)
1845     SPRGPainter *rgp = (SPRGPainter *) painter;
1847     if (rgp->rg->color == NULL) {
1848         sp_gradient_ensure_colors (rgp->rg);
1849         rgp->rgr.vector = rgp->rg->color;
1850     }
1852     nr_render((NRRenderer *) &rgp->rgr, pb, NULL);
1855 /*
1856   Local Variables:
1857   mode:c++
1858   c-file-style:"stroustrup"
1859   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1860   indent-tabs-mode:nil
1861   fill-column:99
1862   End:
1863 */
1864 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :