Code

Fix for gradient code I committed recently (which accidentally used unsigned ints...
[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-fns.h>
25 #include <libnr/nr-matrix-ops.h>
26 #include <libnr/nr-matrix-scale-ops.h>
27 #include <2geom/transforms.h>
29 #include <sigc++/functors/ptr_fun.h>
30 #include <sigc++/adaptors/bind.h>
32 #include "libnr/nr-gradient.h"
33 #include "libnr/nr-pixops.h"
34 #include "svg/svg.h"
35 #include "svg/svg-color.h"
36 #include "svg/css-ostringstream.h"
37 #include "attributes.h"
38 #include "document-private.h"
39 #include "gradient-chemistry.h"
40 #include "sp-gradient-reference.h"
41 #include "sp-linear-gradient.h"
42 #include "sp-radial-gradient.h"
43 #include "sp-stop.h"
44 #include "streq.h"
45 #include "uri.h"
46 #include "xml/repr.h"
48 #define SP_MACROS_SILENT
49 #include "macros.h"
51 /// Has to be power of 2
52 #define NCOLORS NR_GRADIENT_VECTOR_LENGTH
54 static void sp_stop_class_init(SPStopClass *klass);
55 static void sp_stop_init(SPStop *stop);
57 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
58 static void sp_stop_set(SPObject *object, unsigned key, gchar const *value);
59 static Inkscape::XML::Node *sp_stop_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
61 static SPObjectClass *stop_parent_class;
63 /**
64  * Registers SPStop class and returns its type.
65  */
66 GType
67 sp_stop_get_type()
68 {
69     static GType type = 0;
70     if (!type) {
71         GTypeInfo info = {
72             sizeof(SPStopClass),
73             NULL, NULL,
74             (GClassInitFunc) sp_stop_class_init,
75             NULL, NULL,
76             sizeof(SPStop),
77             16,
78             (GInstanceInitFunc) sp_stop_init,
79             NULL,   /* value_table */
80         };
81         type = g_type_register_static(SP_TYPE_OBJECT, "SPStop", &info, (GTypeFlags)0);
82     }
83     return type;
84 }
86 /**
87  * Callback to initialize SPStop vtable.
88  */
89 static void sp_stop_class_init(SPStopClass *klass)
90 {
91     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
93     stop_parent_class = (SPObjectClass *) g_type_class_ref(SP_TYPE_OBJECT);
95     sp_object_class->build = sp_stop_build;
96     sp_object_class->set = sp_stop_set;
97     sp_object_class->write = sp_stop_write;
98 }
100 /**
101  * Callback to initialize SPStop object.
102  */
103 static void
104 sp_stop_init(SPStop *stop)
106     stop->offset = 0.0;
107     stop->currentColor = false;
108     stop->specified_color.set( 0x000000ff );
109     stop->opacity = 1.0;
112 /**
113  * Virtual build: set stop attributes from its associated XML node.
114  */
115 static void sp_stop_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
117     if (((SPObjectClass *) stop_parent_class)->build)
118         (* ((SPObjectClass *) stop_parent_class)->build)(object, document, repr);
120     sp_object_read_attr(object, "offset");
121     sp_object_read_attr(object, "stop-color");
122     sp_object_read_attr(object, "stop-opacity");
123     sp_object_read_attr(object, "style");
126 /**
127  * Virtual set: set attribute to value.
128  */
129 static void
130 sp_stop_set(SPObject *object, unsigned key, gchar const *value)
132     SPStop *stop = SP_STOP(object);
134     switch (key) {
135         case SP_ATTR_STYLE: {
136         /** \todo
137          * fixme: We are reading simple values 3 times during build (Lauris).
138          * \par
139          * We need presentation attributes etc.
140          * \par
141          * remove the hackish "style reading" from here: see comments in
142          * sp_object_get_style_property about the bugs in our current
143          * approach.  However, note that SPStyle doesn't currently have
144          * stop-color and stop-opacity properties.
145          */
146             {
147                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
148                 if (streq(p, "currentColor")) {
149                     stop->currentColor = true;
150                 } else {
151                     guint32 const color = sp_svg_read_color(p, 0);
152                     stop->specified_color.set( color );
153                 }
154             }
155             {
156                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
157                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
158                 stop->opacity = opacity;
159             }
160             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
161             break;
162         }
163         case SP_PROP_STOP_COLOR: {
164             {
165                 gchar const *p = sp_object_get_style_property(object, "stop-color", "black");
166                 if (streq(p, "currentColor")) {
167                     stop->currentColor = true;
168                 } else {
169                     stop->currentColor = false;
170                     guint32 const color = sp_svg_read_color(p, 0);
171                     stop->specified_color.set( color );
172                 }
173             }
174             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
175             break;
176         }
177         case SP_PROP_STOP_OPACITY: {
178             {
179                 gchar const *p = sp_object_get_style_property(object, "stop-opacity", "1");
180                 gdouble opacity = sp_svg_read_percentage(p, stop->opacity);
181                 stop->opacity = opacity;
182             }
183             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
184             break;
185         }
186         case SP_ATTR_OFFSET: {
187             stop->offset = sp_svg_read_percentage(value, 0.0);
188             object->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
189             break;
190         }
191         default: {
192             if (((SPObjectClass *) stop_parent_class)->set)
193                 (* ((SPObjectClass *) stop_parent_class)->set)(object, key, value);
194             break;
195         }
196     }
199 /**
200  * Virtual write: write object attributes to repr.
201  */
202 static Inkscape::XML::Node *
203 sp_stop_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
205     SPStop *stop = SP_STOP(object);
207     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
208         repr = xml_doc->createElement("svg:stop");
209     }
211     guint32 specifiedcolor = stop->specified_color.toRGBA32( 255 );
212     gfloat opacity = stop->opacity;
214     if (((SPObjectClass *) stop_parent_class)->write)
215         (* ((SPObjectClass *) stop_parent_class)->write)(object, xml_doc, 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, sizeof(c), 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 stop->specified_color.toRGBA32( 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( color );
282         return ret;
283     } else {
284         return stop->specified_color;
285     }
288 /*
289  * Gradient
290  */
292 static void sp_gradient_class_init(SPGradientClass *klass);
293 static void sp_gradient_init(SPGradient *gr);
295 static void sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
296 static void sp_gradient_release(SPObject *object);
297 static void sp_gradient_set(SPObject *object, unsigned key, gchar const *value);
298 static void sp_gradient_child_added(SPObject *object,
299                                     Inkscape::XML::Node *child,
300                                     Inkscape::XML::Node *ref);
301 static void sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child);
302 static void sp_gradient_modified(SPObject *object, guint flags);
303 static Inkscape::XML::Node *sp_gradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
304                                               guint flags);
306 static void gradient_ref_modified(SPObject *href, guint flags, SPGradient *gradient);
308 static bool sp_gradient_invalidate_vector(SPGradient *gr);
309 static void sp_gradient_rebuild_vector(SPGradient *gr);
311 static void gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gradient);
313 SPGradientSpread sp_gradient_get_spread(SPGradient *gradient);
314 SPGradientUnits sp_gradient_get_units(SPGradient *gradient);
316 static SPPaintServerClass *gradient_parent_class;
318 /**
319  * Registers SPGradient class and returns its type.
320  */
321 GType
322 sp_gradient_get_type()
324     static GType gradient_type = 0;
325     if (!gradient_type) {
326         GTypeInfo gradient_info = {
327             sizeof(SPGradientClass),
328             NULL, NULL,
329             (GClassInitFunc) sp_gradient_class_init,
330             NULL, NULL,
331             sizeof(SPGradient),
332             16,
333             (GInstanceInitFunc) sp_gradient_init,
334             NULL,   /* value_table */
335         };
336         gradient_type = g_type_register_static(SP_TYPE_PAINT_SERVER, "SPGradient",
337                                                &gradient_info, (GTypeFlags)0);
338     }
339     return gradient_type;
342 /**
343  * SPGradient vtable initialization.
344  */
345 static void
346 sp_gradient_class_init(SPGradientClass *klass)
348     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
350     gradient_parent_class = (SPPaintServerClass *)g_type_class_ref(SP_TYPE_PAINT_SERVER);
352     sp_object_class->build = sp_gradient_build;
353     sp_object_class->release = sp_gradient_release;
354     sp_object_class->set = sp_gradient_set;
355     sp_object_class->child_added = sp_gradient_child_added;
356     sp_object_class->remove_child = sp_gradient_remove_child;
357     sp_object_class->modified = sp_gradient_modified;
358     sp_object_class->write = sp_gradient_write;
361 /**
362  * Callback for SPGradient object initialization.
363  */
364 static void
365 sp_gradient_init(SPGradient *gr)
367     gr->ref = new SPGradientReference(SP_OBJECT(gr));
368     gr->ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(gradient_ref_changed), gr));
370     /** \todo
371      * Fixme: reprs being rearranged (e.g. via the XML editor)
372      * may require us to clear the state.
373      */
374     gr->state = SP_GRADIENT_STATE_UNKNOWN;
376     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
377     gr->units_set = FALSE;
379     gr->gradientTransform = Geom::identity();
380     gr->gradientTransform_set = FALSE;
382     gr->spread = SP_GRADIENT_SPREAD_PAD;
383     gr->spread_set = FALSE;
385     gr->has_stops = FALSE;
387     gr->vector.built = false;
388     gr->vector.stops.clear();
390     gr->color = NULL;
392     new (&gr->modified_connection) sigc::connection();
395 /**
396  * Virtual build: set gradient attributes from its associated repr.
397  */
398 static void
399 sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
401     SPGradient *gradient = SP_GRADIENT(object);
403     if (((SPObjectClass *) gradient_parent_class)->build)
404         (* ((SPObjectClass *) gradient_parent_class)->build)(object, document, repr);
406     SPObject *ochild;
407     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
408         if (SP_IS_STOP(ochild)) {
409             gradient->has_stops = TRUE;
410             break;
411         }
412     }
414     sp_object_read_attr(object, "gradientUnits");
415     sp_object_read_attr(object, "gradientTransform");
416     sp_object_read_attr(object, "spreadMethod");
417     sp_object_read_attr(object, "xlink:href");
419     /* Register ourselves */
420     sp_document_add_resource(document, "gradient", object);
423 /**
424  * Virtual release of SPGradient members before destruction.
425  */
426 static void
427 sp_gradient_release(SPObject *object)
429     SPGradient *gradient = (SPGradient *) object;
431 #ifdef SP_GRADIENT_VERBOSE
432     g_print("Releasing gradient %s\n", SP_OBJECT_ID(object));
433 #endif
435     if (SP_OBJECT_DOCUMENT(object)) {
436         /* Unregister ourselves */
437         sp_document_remove_resource(SP_OBJECT_DOCUMENT(object), "gradient", SP_OBJECT(object));
438     }
440     if (gradient->ref) {
441         gradient->modified_connection.disconnect();
442         gradient->ref->detach();
443         delete gradient->ref;
444         gradient->ref = NULL;
445     }
447     if (gradient->color) {
448         g_free(gradient->color);
449         gradient->color = NULL;
450     }
452     gradient->modified_connection.~connection();
454     if (((SPObjectClass *) gradient_parent_class)->release)
455         ((SPObjectClass *) gradient_parent_class)->release(object);
458 /**
459  * Set gradient attribute to value.
460  */
461 static void
462 sp_gradient_set(SPObject *object, unsigned key, gchar const *value)
464     SPGradient *gr = SP_GRADIENT(object);
466     switch (key) {
467         case SP_ATTR_GRADIENTUNITS:
468             if (value) {
469                 if (!strcmp(value, "userSpaceOnUse")) {
470                     gr->units = SP_GRADIENT_UNITS_USERSPACEONUSE;
471                 } else {
472                     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
473                 }
474                 gr->units_set = TRUE;
475             } else {
476                 gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
477                 gr->units_set = FALSE;
478             }
479             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
480             break;
481         case SP_ATTR_GRADIENTTRANSFORM: {
482             Geom::Matrix t;
483             if (value && sp_svg_transform_read(value, &t)) {
484                 gr->gradientTransform = t;
485                 gr->gradientTransform_set = TRUE;
486             } else {
487                 gr->gradientTransform = Geom::identity();
488                 gr->gradientTransform_set = FALSE;
489             }
490             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
491             break;
492         }
493         case SP_ATTR_SPREADMETHOD:
494             if (value) {
495                 if (!strcmp(value, "reflect")) {
496                     gr->spread = SP_GRADIENT_SPREAD_REFLECT;
497                 } else if (!strcmp(value, "repeat")) {
498                     gr->spread = SP_GRADIENT_SPREAD_REPEAT;
499                 } else {
500                     gr->spread = SP_GRADIENT_SPREAD_PAD;
501                 }
502                 gr->spread_set = TRUE;
503             } else {
504                 gr->spread_set = FALSE;
505             }
506             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
507             break;
508         case SP_ATTR_XLINK_HREF:
509             if (value) {
510                 try {
511                     gr->ref->attach(Inkscape::URI(value));
512                 } catch (Inkscape::BadURIException &e) {
513                     g_warning("%s", e.what());
514                     gr->ref->detach();
515                 }
516             } else {
517                 gr->ref->detach();
518             }
519             break;
520         default:
521             if (((SPObjectClass *) gradient_parent_class)->set)
522                 ((SPObjectClass *) gradient_parent_class)->set(object, key, value);
523             break;
524     }
527 /**
528  * Gets called when the gradient is (re)attached to another gradient.
529  */
530 static void
531 gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gr)
533     if (old_ref) {
534         gr->modified_connection.disconnect();
535     }
536     if ( SP_IS_GRADIENT(ref)
537          && ref != gr )
538     {
539         gr->modified_connection = ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&gradient_ref_modified), gr));
540     }
542     // Per SVG, all unset attributes must be inherited from linked gradient.
543     // So, as we're now (re)linked, we assign linkee's values to this gradient if they are not yet set -
544     // but without setting the _set flags.
545     // FIXME: do the same for gradientTransform too
546     if (!gr->units_set)
547         gr->units = sp_gradient_get_units (gr);
548     if (!gr->spread_set)
549         gr->spread = sp_gradient_get_spread (gr);
551     /// \todo Fixme: what should the flags (second) argument be? */
552     gradient_ref_modified(ref, 0, gr);
555 /**
556  * Callback for child_added event.
557  */
558 static void
559 sp_gradient_child_added(SPObject *object, Inkscape::XML::Node *child, Inkscape::XML::Node *ref)
561     SPGradient *gr = SP_GRADIENT(object);
563     sp_gradient_invalidate_vector(gr);
565     if (((SPObjectClass *) gradient_parent_class)->child_added)
566         (* ((SPObjectClass *) gradient_parent_class)->child_added)(object, child, ref);
568     SPObject *ochild = sp_object_get_child_by_repr(object, child);
569     if ( ochild && SP_IS_STOP(ochild) ) {
570         gr->has_stops = TRUE;
571     }
573     /// \todo Fixme: should we schedule "modified" here?
574     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
577 /**
578  * Callback for remove_child event.
579  */
580 static void
581 sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child)
583     SPGradient *gr = SP_GRADIENT(object);
585     sp_gradient_invalidate_vector(gr);
587     if (((SPObjectClass *) gradient_parent_class)->remove_child)
588         (* ((SPObjectClass *) gradient_parent_class)->remove_child)(object, child);
590     gr->has_stops = FALSE;
591     SPObject *ochild;
592     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
593         if (SP_IS_STOP(ochild)) {
594             gr->has_stops = TRUE;
595             break;
596         }
597     }
599     /* Fixme: should we schedule "modified" here? */
600     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
603 /**
604  * Callback for modified event.
605  */
606 static void
607 sp_gradient_modified(SPObject *object, guint flags)
609     SPGradient *gr = SP_GRADIENT(object);
611     if (flags & SP_OBJECT_CHILD_MODIFIED_FLAG) {
612         sp_gradient_invalidate_vector(gr);
613     }
615     if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
616         sp_gradient_ensure_colors(gr);
617     }
619     if (flags & SP_OBJECT_MODIFIED_FLAG) flags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
620     flags &= SP_OBJECT_MODIFIED_CASCADE;
622     // FIXME: climb up the ladder of hrefs
623     GSList *l = NULL;
624     for (SPObject *child = sp_object_first_child(object) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
625         g_object_ref(G_OBJECT(child));
626         l = g_slist_prepend(l, child);
627     }
628     l = g_slist_reverse(l);
629     while (l) {
630         SPObject *child = SP_OBJECT(l->data);
631         l = g_slist_remove(l, child);
632         if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
633             child->emitModified(flags);
634         }
635         g_object_unref(G_OBJECT(child));
636     }
639 /**
640  * Write gradient attributes to repr.
641  */
642 static Inkscape::XML::Node *
643 sp_gradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
645     SPGradient *gr = SP_GRADIENT(object);
647     if (((SPObjectClass *) gradient_parent_class)->write)
648         (* ((SPObjectClass *) gradient_parent_class)->write)(object, xml_doc, repr, flags);
650     if (flags & SP_OBJECT_WRITE_BUILD) {
651         GSList *l = NULL;
652         for (SPObject *child = sp_object_first_child(object); child; child = SP_OBJECT_NEXT(child)) {
653             Inkscape::XML::Node *crepr;
654             crepr = child->updateRepr(xml_doc, NULL, flags);
655             if (crepr) l = g_slist_prepend(l, crepr);
656         }
657         while (l) {
658             repr->addChild((Inkscape::XML::Node *) l->data, NULL);
659             Inkscape::GC::release((Inkscape::XML::Node *) l->data);
660             l = g_slist_remove(l, l->data);
661         }
662     }
664     if (gr->ref->getURI()) {
665         gchar *uri_string = gr->ref->getURI()->toString();
666         repr->setAttribute("xlink:href", uri_string);
667         g_free(uri_string);
668     }
670     if ((flags & SP_OBJECT_WRITE_ALL) || gr->units_set) {
671         switch (gr->units) {
672             case SP_GRADIENT_UNITS_USERSPACEONUSE:
673                 repr->setAttribute("gradientUnits", "userSpaceOnUse");
674                 break;
675             default:
676                 repr->setAttribute("gradientUnits", "objectBoundingBox");
677                 break;
678         }
679     }
681     if ((flags & SP_OBJECT_WRITE_ALL) || gr->gradientTransform_set) {
682         gchar *c=sp_svg_transform_write(gr->gradientTransform);
683         repr->setAttribute("gradientTransform", c);
684         g_free(c);
685     }
687     if ((flags & SP_OBJECT_WRITE_ALL) || gr->spread_set) {
688         /* FIXME: Ensure that gr->spread is the inherited value
689          * if !gr->spread_set.  Not currently happening: see sp_gradient_modified.
690          */
691         switch (gr->spread) {
692             case SP_GRADIENT_SPREAD_REFLECT:
693                 repr->setAttribute("spreadMethod", "reflect");
694                 break;
695             case SP_GRADIENT_SPREAD_REPEAT:
696                 repr->setAttribute("spreadMethod", "repeat");
697                 break;
698             default:
699                 repr->setAttribute("spreadMethod", "pad");
700                 break;
701         }
702     }
704     return repr;
707 /**
708  * Forces the vector to be built, if not present (i.e., changed).
709  *
710  * \pre SP_IS_GRADIENT(gradient).
711  */
712 void
713 sp_gradient_ensure_vector(SPGradient *gradient)
715     g_return_if_fail(gradient != NULL);
716     g_return_if_fail(SP_IS_GRADIENT(gradient));
718     if (!gradient->vector.built) {
719         sp_gradient_rebuild_vector(gradient);
720     }
723 /**
724  * Set units property of gradient and emit modified.
725  */
726 void
727 sp_gradient_set_units(SPGradient *gr, SPGradientUnits units)
729     if (units != gr->units) {
730         gr->units = units;
731         gr->units_set = TRUE;
732         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
733     }
736 /**
737  * Set spread property of gradient and emit modified.
738  */
739 void
740 sp_gradient_set_spread(SPGradient *gr, SPGradientSpread spread)
742     if (spread != gr->spread) {
743         gr->spread = spread;
744         gr->spread_set = TRUE;
745         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
746     }
749 /**
750  * Returns the first of {src, src-\>ref-\>getObject(),
751  * src-\>ref-\>getObject()-\>ref-\>getObject(),...}
752  * for which \a match is true, or NULL if none found.
753  *
754  * The raison d'être of this routine is that it correctly handles cycles in the href chain (e.g., if
755  * a gradient gives itself as its href, or if each of two gradients gives the other as its href).
756  *
757  * \pre SP_IS_GRADIENT(src).
758  */
759 static SPGradient *
760 chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *))
762     g_return_val_if_fail(SP_IS_GRADIENT(src), NULL);
764     /* Use a pair of pointers for detecting loops: p1 advances half as fast as p2.  If there is a
765        loop, then once p1 has entered the loop, we'll detect it the next time the distance between
766        p1 and p2 is a multiple of the loop size. */
767     SPGradient *p1 = src, *p2 = src;
768     bool do1 = false;
769     for (;;) {
770         if (match(p2)) {
771             return p2;
772         }
774         p2 = p2->ref->getObject();
775         if (!p2) {
776             return p2;
777         }
778         if (do1) {
779             p1 = p1->ref->getObject();
780         }
781         do1 = !do1;
783         if ( p2 == p1 ) {
784             /* We've been here before, so return NULL to indicate that no matching gradient found
785              * in the chain. */
786             return NULL;
787         }
788     }
791 /**
792  * True if gradient has stops.
793  */
794 static bool
795 has_stops(SPGradient const *gr)
797     return SP_GRADIENT_HAS_STOPS(gr);
800 /**
801  * True if gradient has spread set.
802  */
803 static bool
804 has_spread_set(SPGradient const *gr)
806     return gr->spread_set;
809 /**
810  * True if gradient has units set.
811  */
812 static bool
813 has_units_set(SPGradient const *gr)
815     return gr->units_set;
819 /**
820  * Returns private vector of given gradient (the gradient at the end of the href chain which has
821  * stops), optionally normalizing it.
822  *
823  * \pre SP_IS_GRADIENT(gradient).
824  * \pre There exists a gradient in the chain that has stops.
825  */
826 SPGradient *
827 sp_gradient_get_vector(SPGradient *gradient, bool force_vector)
829     g_return_val_if_fail(gradient != NULL, NULL);
830     g_return_val_if_fail(SP_IS_GRADIENT(gradient), NULL);
832     SPGradient *const src = chase_hrefs(gradient, has_stops);
833     return ( force_vector
834              ? sp_gradient_ensure_vector_normalized(src)
835              : src );
838 /**
839  * Returns the effective spread of given gradient (climbing up the refs chain if needed).
840  *
841  * \pre SP_IS_GRADIENT(gradient).
842  */
843 SPGradientSpread
844 sp_gradient_get_spread(SPGradient *gradient)
846     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_SPREAD_PAD);
848     SPGradient const *src = chase_hrefs(gradient, has_spread_set);
849     return ( src
850              ? src->spread
851              : SP_GRADIENT_SPREAD_PAD ); // pad is the default
854 /**
855  * Returns the effective units of given gradient (climbing up the refs chain if needed).
856  *
857  * \pre SP_IS_GRADIENT(gradient).
858  */
859 SPGradientUnits
860 sp_gradient_get_units(SPGradient *gradient)
862     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX);
864     SPGradient const *src = chase_hrefs(gradient, has_units_set);
865     return ( src
866              ? src->units
867              : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ); // bbox is the default
871 /**
872  * Clears the gradient's svg:stop children from its repr.
873  */
874 void
875 sp_gradient_repr_clear_vector(SPGradient *gr)
877     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
879     /* Collect stops from original repr */
880     GSList *sl = NULL;
881     for (Inkscape::XML::Node *child = repr->firstChild() ; child != NULL; child = child->next() ) {
882         if (!strcmp(child->name(), "svg:stop")) {
883             sl = g_slist_prepend(sl, child);
884         }
885     }
886     /* Remove all stops */
887     while (sl) {
888         /** \todo
889          * fixme: This should work, unless we make gradient
890          * into generic group.
891          */
892         sp_repr_unparent((Inkscape::XML::Node *)sl->data);
893         sl = g_slist_remove(sl, sl->data);
894     }
897 /**
898  * Writes the gradient's internal vector (whether from its own stops, or
899  * inherited from refs) into the gradient repr as svg:stop elements.
900  */
901 void
902 sp_gradient_repr_write_vector(SPGradient *gr)
904     g_return_if_fail(gr != NULL);
905     g_return_if_fail(SP_IS_GRADIENT(gr));
907     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(gr));
908     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
910     /* We have to be careful, as vector may be our own, so construct repr list at first */
911     GSList *cl = NULL;
913     for (guint i = 0; i < gr->vector.stops.size(); i++) {
914         Inkscape::CSSOStringStream os;
915         Inkscape::XML::Node *child = xml_doc->createElement("svg:stop");
916         sp_repr_set_css_double(child, "offset", gr->vector.stops[i].offset);
917         /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no
918          * sense for offset proportions. */
919         gchar c[64];
920         sp_svg_write_color(c, sizeof(c), gr->vector.stops[i].color.toRGBA32( 0x00 ));
921         os << "stop-color:" << c << ";stop-opacity:" << gr->vector.stops[i].opacity;
922         child->setAttribute("style", os.str().c_str());
923         /* Order will be reversed here */
924         cl = g_slist_prepend(cl, child);
925     }
927     sp_gradient_repr_clear_vector(gr);
929     /* And insert new children from list */
930     while (cl) {
931         Inkscape::XML::Node *child = static_cast<Inkscape::XML::Node *>(cl->data);
932         repr->addChild(child, NULL);
933         Inkscape::GC::release(child);
934         cl = g_slist_remove(cl, child);
935     }
939 static void
940 gradient_ref_modified(SPObject */*href*/, guint /*flags*/, SPGradient *gradient)
942     if (sp_gradient_invalidate_vector(gradient)) {
943         SP_OBJECT(gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
944         /* Conditional to avoid causing infinite loop if there's a cycle in the href chain. */
945     }
948 /** Return true iff change made. */
949 static bool
950 sp_gradient_invalidate_vector(SPGradient *gr)
952     bool ret = false;
954     if (gr->color != NULL) {
955         g_free(gr->color);
956         gr->color = NULL;
957         ret = true;
958     }
960     if (gr->vector.built) {
961         gr->vector.built = false;
962         gr->vector.stops.clear();
963         ret = true;
964     }
966     return ret;
969 /** Creates normalized color vector */
970 static void
971 sp_gradient_rebuild_vector(SPGradient *gr)
973     gint len = 0;
974     for ( SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
975           child != NULL ;
976           child = SP_OBJECT_NEXT(child) ) {
977         if (SP_IS_STOP(child)) {
978             len ++;
979         }
980     }
982     gr->has_stops = (len != 0);
984     gr->vector.stops.clear();
986     SPGradient *ref = gr->ref->getObject();
987     if ( !gr->has_stops && ref ) {
988         /* Copy vector from referenced gradient */
989         gr->vector.built = true;   // Prevent infinite recursion.
990         sp_gradient_ensure_vector(ref);
991         if (!ref->vector.stops.empty()) {
992             gr->vector.built = ref->vector.built;
993             gr->vector.stops.assign(ref->vector.stops.begin(), ref->vector.stops.end());
994             return;
995         }
996     }
998     for (SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
999          child != NULL;
1000          child = SP_OBJECT_NEXT(child) ) {
1001         if (SP_IS_STOP(child)) {
1002             SPStop *stop = SP_STOP(child);
1004             SPGradientStop gstop;
1005             if (gr->vector.stops.size() > 0) {
1006                 // "Each gradient offset value is required to be equal to or greater than the
1007                 // previous gradient stop's offset value. If a given gradient stop's offset
1008                 // value is not equal to or greater than all previous offset values, then the
1009                 // offset value is adjusted to be equal to the largest of all previous offset
1010                 // values."
1011                 gstop.offset = MAX(stop->offset, gr->vector.stops.back().offset);
1012             } else {
1013                 gstop.offset = stop->offset;
1014             }
1016             // "Gradient offset values less than 0 (or less than 0%) are rounded up to
1017             // 0%. Gradient offset values greater than 1 (or greater than 100%) are rounded
1018             // down to 100%."
1019             gstop.offset = CLAMP(gstop.offset, 0, 1);
1021             gstop.color = sp_stop_get_color(stop);
1022             gstop.opacity = stop->opacity;
1024             gr->vector.stops.push_back(gstop);
1025         }
1026     }
1028     // Normalize per section 13.2.4 of SVG 1.1.
1029     if (gr->vector.stops.size() == 0) {
1030         /* "If no stops are defined, then painting shall occur as if 'none' were specified as the
1031          * paint style."
1032          */
1033         {
1034             SPGradientStop gstop;
1035             gstop.offset = 0.0;
1036             gstop.color.set( 0x00000000 );
1037             gstop.opacity = 0.0;
1038             gr->vector.stops.push_back(gstop);
1039         }
1040         {
1041             SPGradientStop gstop;
1042             gstop.offset = 1.0;
1043             gstop.color.set( 0x00000000 );
1044             gstop.opacity = 0.0;
1045             gr->vector.stops.push_back(gstop);
1046         }
1047     } else {
1048         /* "If one stop is defined, then paint with the solid color fill using the color defined
1049          * for that gradient stop."
1050          */
1051         if (gr->vector.stops.front().offset > 0.0) {
1052             // If the first one is not at 0, then insert a copy of the first at 0.
1053             SPGradientStop gstop;
1054             gstop.offset = 0.0;
1055             gstop.color = gr->vector.stops.front().color;
1056             gstop.opacity = gr->vector.stops.front().opacity;
1057             gr->vector.stops.insert(gr->vector.stops.begin(), gstop);
1058         }
1059         if (gr->vector.stops.back().offset < 1.0) {
1060             // If the last one is not at 1, then insert a copy of the last at 1.
1061             SPGradientStop gstop;
1062             gstop.offset = 1.0;
1063             gstop.color = gr->vector.stops.back().color;
1064             gstop.opacity = gr->vector.stops.back().opacity;
1065             gr->vector.stops.push_back(gstop);
1066         }
1067     }
1069     gr->vector.built = true;
1072 /**
1073  * The gradient's color array is newly created and set up from vector.
1074  */
1075 void
1076 sp_gradient_ensure_colors(SPGradient *gr)
1078     if (!gr->vector.built) {
1079         sp_gradient_rebuild_vector(gr);
1080     }
1081     g_return_if_fail(!gr->vector.stops.empty());
1083     /// \todo Where is the memory freed?
1084     if (!gr->color) {
1085         gr->color = g_new(guchar, 4 * NCOLORS);
1086     }
1088     for (guint i = 0; i < gr->vector.stops.size() - 1; i++) {
1089         guint32 color = gr->vector.stops[i].color.toRGBA32( gr->vector.stops[i].opacity );
1090         gint r0 = (color >> 24) & 0xff;
1091         gint g0 = (color >> 16) & 0xff;
1092         gint b0 = (color >> 8) & 0xff;
1093         gint a0 = color & 0xff;
1094         color = gr->vector.stops[i + 1].color.toRGBA32( gr->vector.stops[i + 1].opacity );
1095         gint r1 = (color >> 24) & 0xff;
1096         gint g1 = (color >> 16) & 0xff;
1097         gint b1 = (color >> 8) & 0xff;
1098         gint a1 = color & 0xff;
1099         gint o0 = (gint) floor(gr->vector.stops[i].offset * (NCOLORS - 0.001));
1100         gint o1 = (gint) floor(gr->vector.stops[i + 1].offset * (NCOLORS - 0.001));
1101         if (o1 > o0) {
1102             for (int j = o0; j < o1 + 1; j++) {
1103                 gr->color[4 * j + 0] = r0 + ((j-o0)*(r1-r0) + (o1-o0)/2)/(o1-o0);
1104                 gr->color[4 * j + 1] = g0 + ((j-o0)*(g1-g0) + (o1-o0)/2)/(o1-o0);
1105                 gr->color[4 * j + 2] = b0 + ((j-o0)*(b1-b0) + (o1-o0)/2)/(o1-o0);
1106                 gr->color[4 * j + 3] = a0 + ((j-o0)*(a1-a0) + (o1-o0)/2)/(o1-o0);
1107             }
1108         }
1109     }
1112 /**
1113  * Renders gradient vector to buffer as line.
1114  *
1115  * RGB buffer background should be set up beforehand.
1116  *
1117  * @param len,width,height,rowstride Buffer parameters (1 or 2 dimensional).
1118  * @param span Full integer width of requested gradient.
1119  * @param pos Buffer starting position in span.
1120  */
1121 static void
1122 sp_gradient_render_vector_line_rgba(SPGradient *const gradient, guchar *buf,
1123                                     gint const len, gint const pos, gint const span)
1125     g_return_if_fail(gradient != NULL);
1126     g_return_if_fail(SP_IS_GRADIENT(gradient));
1127     g_return_if_fail(buf != NULL);
1128     g_return_if_fail(len > 0);
1129     g_return_if_fail(pos >= 0);
1130     g_return_if_fail(pos + len <= span);
1131     g_return_if_fail(span > 0);
1133     if (!gradient->color) {
1134         sp_gradient_ensure_colors(gradient);
1135     }
1137     gint idx = (pos * 1024 << 8) / span;
1138     gint didx = (1024 << 8) / span;
1140     for (gint x = 0; x < len; x++) {
1141         /// \todo Can this be done with 4 byte copies?
1142         *buf++ = gradient->color[4 * (idx >> 8)];
1143         *buf++ = gradient->color[4 * (idx >> 8) + 1];
1144         *buf++ = gradient->color[4 * (idx >> 8) + 2];
1145         *buf++ = gradient->color[4 * (idx >> 8) + 3];
1146         idx += didx;
1147     }
1150 /**
1151  * Render rectangular RGBA area from gradient vector.
1152  */
1153 void
1154 sp_gradient_render_vector_block_rgba(SPGradient *const gradient, guchar *buf,
1155                                      gint const width, gint const height, gint const rowstride,
1156                                      gint const pos, gint const span, bool const horizontal)
1158     g_return_if_fail(gradient != NULL);
1159     g_return_if_fail(SP_IS_GRADIENT(gradient));
1160     g_return_if_fail(buf != NULL);
1161     g_return_if_fail(width > 0);
1162     g_return_if_fail(height > 0);
1163     g_return_if_fail(pos >= 0);
1164     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1165     g_return_if_fail(span > 0);
1167     if (horizontal) {
1168         sp_gradient_render_vector_line_rgba(gradient, buf, width, pos, span);
1169         for (gint y = 1; y < height; y++) {
1170             memcpy(buf + y * rowstride, buf, 4 * width);
1171         }
1172     } else {
1173         guchar *tmp = (guchar *)alloca(4 * height);
1174         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1175         for (gint y = 0; y < height; y++) {
1176             guchar *b = buf + y * rowstride;
1177             for (gint x = 0; x < width; x++) {
1178                 *b++ = tmp[0];
1179                 *b++ = tmp[1];
1180                 *b++ = tmp[2];
1181                 *b++ = tmp[3];
1182             }
1183             tmp += 4;
1184         }
1185     }
1188 /**
1189  * Render rectangular RGB area from gradient vector.
1190  */
1191 void
1192 sp_gradient_render_vector_block_rgb(SPGradient *gradient, guchar *buf,
1193                                     gint const width, gint const height, gint const /*rowstride*/,
1194                                     gint const pos, gint const span, bool const horizontal)
1196     g_return_if_fail(gradient != NULL);
1197     g_return_if_fail(SP_IS_GRADIENT(gradient));
1198     g_return_if_fail(buf != NULL);
1199     g_return_if_fail(width > 0);
1200     g_return_if_fail(height > 0);
1201     g_return_if_fail(pos >= 0);
1202     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1203     g_return_if_fail(span > 0);
1205     if (horizontal) {
1206         guchar *tmp = (guchar*)alloca(4 * width);
1207         sp_gradient_render_vector_line_rgba(gradient, tmp, width, pos, span);
1208         for (gint y = 0; y < height; y++) {
1209             guchar *t = tmp;
1210             for (gint x = 0; x < width; x++) {
1211                 gint a = t[3];
1212                 gint fc = (t[0] - buf[0]) * a;
1213                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1214                 fc = (t[1] - buf[1]) * a;
1215                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1216                 fc = (t[2] - buf[2]) * a;
1217                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1218                 buf += 3;
1219                 t += 4;
1220             }
1221         }
1222     } else {
1223         guchar *tmp = (guchar*)alloca(4 * height);
1224         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1225         for (gint y = 0; y < height; y++) {
1226             guchar *t = tmp + 4 * y;
1227             for (gint x = 0; x < width; x++) {
1228                 gint a = t[3];
1229                 gint fc = (t[0] - buf[0]) * a;
1230                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1231                 fc = (t[1] - buf[1]) * a;
1232                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1233                 fc = (t[2] - buf[2]) * a;
1234                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1235             }
1236         }
1237     }
1240 Geom::Matrix
1241 sp_gradient_get_g2d_matrix(SPGradient const *gr, Geom::Matrix const &ctm, Geom::Rect const &bbox)
1243     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1244         return ( Geom::Scale(bbox.dimensions())
1245                  * Geom::Translate(bbox.min())
1246                  * Geom::Matrix(ctm) );
1247     } else {
1248         return ctm;
1249     }
1252 Geom::Matrix
1253 sp_gradient_get_gs2d_matrix(SPGradient const *gr, Geom::Matrix const &ctm, Geom::Rect const &bbox)
1255     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1256         return ( gr->gradientTransform
1257                  * Geom::Scale(bbox.dimensions())
1258                  * Geom::Translate(bbox.min())
1259                  * Geom::Matrix(ctm) );
1260     } else {
1261         return gr->gradientTransform * ctm;
1262     }
1265 void
1266 sp_gradient_set_gs2d_matrix(SPGradient *gr, Geom::Matrix const &ctm,
1267                             Geom::Rect const &bbox, Geom::Matrix const &gs2d)
1269     gr->gradientTransform = gs2d * ctm.inverse();
1270     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) {
1271         gr->gradientTransform = ( gr->gradientTransform
1272                                   * Geom::Translate(-bbox.min())
1273                                   * Geom::Scale(bbox.dimensions()).inverse() );
1274     }
1275     gr->gradientTransform_set = TRUE;
1277     SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1280 /*
1281  * Linear Gradient
1282  */
1284 class SPLGPainter;
1286 /// A context with linear gradient, painter, and gradient renderer.
1287 struct SPLGPainter {
1288     SPPainter painter;
1289     SPLinearGradient *lg;
1291     NRLGradientRenderer lgr;
1292 };
1294 static void sp_lineargradient_class_init(SPLinearGradientClass *klass);
1295 static void sp_lineargradient_init(SPLinearGradient *lg);
1297 static void sp_lineargradient_build(SPObject *object,
1298                                     SPDocument *document,
1299                                     Inkscape::XML::Node *repr);
1300 static void sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value);
1301 static Inkscape::XML::Node *sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1302                                                     guint flags);
1304 static SPPainter *sp_lineargradient_painter_new(SPPaintServer *ps,
1305                                                 Geom::Matrix const &full_transform,
1306                                                 Geom::Matrix const &parent_transform,
1307                                                 NRRect const *bbox);
1308 static void sp_lineargradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1310 static void sp_lg_fill(SPPainter *painter, NRPixBlock *pb);
1312 static SPGradientClass *lg_parent_class;
1314 /**
1315  * Register SPLinearGradient class and return its type.
1316  */
1317 GType
1318 sp_lineargradient_get_type()
1320     static GType type = 0;
1321     if (!type) {
1322         GTypeInfo info = {
1323             sizeof(SPLinearGradientClass),
1324             NULL, NULL,
1325             (GClassInitFunc) sp_lineargradient_class_init,
1326             NULL, NULL,
1327             sizeof(SPLinearGradient),
1328             16,
1329             (GInstanceInitFunc) sp_lineargradient_init,
1330             NULL,   /* value_table */
1331         };
1332         type = g_type_register_static(SP_TYPE_GRADIENT, "SPLinearGradient", &info, (GTypeFlags)0);
1333     }
1334     return type;
1337 /**
1338  * SPLinearGradient vtable initialization.
1339  */
1340 static void sp_lineargradient_class_init(SPLinearGradientClass *klass)
1342     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1343     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1345     lg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1347     sp_object_class->build = sp_lineargradient_build;
1348     sp_object_class->set = sp_lineargradient_set;
1349     sp_object_class->write = sp_lineargradient_write;
1351     ps_class->painter_new = sp_lineargradient_painter_new;
1352     ps_class->painter_free = sp_lineargradient_painter_free;
1355 /**
1356  * Callback for SPLinearGradient object initialization.
1357  */
1358 static void sp_lineargradient_init(SPLinearGradient *lg)
1360     lg->x1.unset(SVGLength::PERCENT, 0.0, 0.0);
1361     lg->y1.unset(SVGLength::PERCENT, 0.5, 0.5);
1362     lg->x2.unset(SVGLength::PERCENT, 1.0, 1.0);
1363     lg->y2.unset(SVGLength::PERCENT, 0.5, 0.5);
1366 /**
1367  * Callback: set attributes from associated repr.
1368  */
1369 static void sp_lineargradient_build(SPObject *object,
1370                                     SPDocument *document,
1371                                     Inkscape::XML::Node *repr)
1373     if (((SPObjectClass *) lg_parent_class)->build)
1374         (* ((SPObjectClass *) lg_parent_class)->build)(object, document, repr);
1376     sp_object_read_attr(object, "x1");
1377     sp_object_read_attr(object, "y1");
1378     sp_object_read_attr(object, "x2");
1379     sp_object_read_attr(object, "y2");
1382 /**
1383  * Callback: set attribute.
1384  */
1385 static void
1386 sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value)
1388     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1390     switch (key) {
1391         case SP_ATTR_X1:
1392             lg->x1.readOrUnset(value, SVGLength::PERCENT, 0.0, 0.0);
1393             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1394             break;
1395         case SP_ATTR_Y1:
1396             lg->y1.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1397             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1398             break;
1399         case SP_ATTR_X2:
1400             lg->x2.readOrUnset(value, SVGLength::PERCENT, 1.0, 1.0);
1401             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1402             break;
1403         case SP_ATTR_Y2:
1404             lg->y2.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1405             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1406             break;
1407         default:
1408             if (((SPObjectClass *) lg_parent_class)->set)
1409                 (* ((SPObjectClass *) lg_parent_class)->set)(object, key, value);
1410             break;
1411     }
1414 /**
1415  * Callback: write attributes to associated repr.
1416  */
1417 static Inkscape::XML::Node *
1418 sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1420     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1422     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1423         repr = xml_doc->createElement("svg:linearGradient");
1424     }
1426     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x1._set)
1427         sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
1428     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y1._set)
1429         sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
1430     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x2._set)
1431         sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
1432     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y2._set)
1433         sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
1435     if (((SPObjectClass *) lg_parent_class)->write)
1436         (* ((SPObjectClass *) lg_parent_class)->write)(object, xml_doc, repr, flags);
1438     return repr;
1441 /**
1442  * Create linear gradient context.
1443  *
1444  * Basically we have to deal with transformations
1445  *
1446  * 1) color2norm - maps point in (0,NCOLORS) vector to (0,1) vector
1447  * 2) norm2pos - maps (0,1) vector to x1,y1 - x2,y2
1448  * 2) gradientTransform
1449  * 3) bbox2user
1450  * 4) ctm == userspace to pixel grid
1451  *
1452  * See also (*) in sp-pattern about why we may need parent_transform.
1453  *
1454  * \todo (point 1 above) fixme: I do not know how to deal with start > 0
1455  * and end < 1.
1456  */
1457 static SPPainter *
1458 sp_lineargradient_painter_new(SPPaintServer *ps,
1459                               Geom::Matrix const &full_transform,
1460                               Geom::Matrix const &/*parent_transform*/,
1461                               NRRect const *bbox)
1463     SPLinearGradient *lg = SP_LINEARGRADIENT(ps);
1464     SPGradient *gr = SP_GRADIENT(ps);
1466     if (!gr->color) sp_gradient_ensure_colors(gr);
1468     SPLGPainter *lgp = g_new(SPLGPainter, 1);
1470     lgp->painter.type = SP_PAINTER_IND;
1471     lgp->painter.fill = sp_lg_fill;
1473     lgp->lg = lg;
1475     /** \todo
1476      * Technically speaking, we map NCOLORS on line [start,end] onto line
1477      * [0,1].  I almost think we should fill color array start and end in
1478      * that case. The alternative would be to leave these just empty garbage
1479      * or something similar. Originally I had 1023.9999 here - not sure
1480      * whether we have really to cut out ceil int (Lauris).
1481      */
1482     Geom::Matrix color2norm(Geom::identity());
1483     Geom::Matrix color2px;
1484     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1485         Geom::Matrix norm2pos(Geom::identity());
1487         /* BBox to user coordinate system */
1488         Geom::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1490         Geom::Matrix color2pos = color2norm * norm2pos;
1491         Geom::Matrix color2tpos = color2pos * gr->gradientTransform;
1492         Geom::Matrix color2user = color2tpos * bbox2user;
1493         color2px = color2user * full_transform;
1495     } else {
1496         /* Problem: What to do, if we have mixed lengths and percentages? */
1497         /* Currently we do ignore percentages at all, but that is not good (lauris) */
1499         Geom::Matrix norm2pos(Geom::identity());
1500         Geom::Matrix color2pos = color2norm * norm2pos;
1501         Geom::Matrix color2tpos = color2pos * gr->gradientTransform;
1502         color2px = color2tpos * full_transform;
1504     }
1505     // TODO: remove color2px_nr after converting to 2geom
1506     NR::Matrix color2px_nr = from_2geom(color2px);
1507     nr_lgradient_renderer_setup(&lgp->lgr, gr->color, sp_gradient_get_spread(gr), &color2px_nr,
1508                                 lg->x1.computed, lg->y1.computed,
1509                                 lg->x2.computed, lg->y2.computed);
1511     return (SPPainter *) lgp;
1514 static void
1515 sp_lineargradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1517     g_free(painter);
1520 /**
1521  * Directly set properties of linear gradient and request modified.
1522  */
1523 void
1524 sp_lineargradient_set_position(SPLinearGradient *lg,
1525                                gdouble x1, gdouble y1,
1526                                gdouble x2, gdouble y2)
1528     g_return_if_fail(lg != NULL);
1529     g_return_if_fail(SP_IS_LINEARGRADIENT(lg));
1531     /* fixme: units? (Lauris)  */
1532     lg->x1.set(SVGLength::NONE, x1, x1);
1533     lg->y1.set(SVGLength::NONE, y1, y1);
1534     lg->x2.set(SVGLength::NONE, x2, x2);
1535     lg->y2.set(SVGLength::NONE, y2, y2);
1537     SP_OBJECT(lg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1540 /**
1541  * Callback when linear gradient object is rendered.
1542  */
1543 static void
1544 sp_lg_fill(SPPainter *painter, NRPixBlock *pb)
1546     SPLGPainter *lgp = (SPLGPainter *) painter;
1548     if (lgp->lg->color == NULL) {
1549         sp_gradient_ensure_colors (lgp->lg);
1550         lgp->lgr.vector = lgp->lg->color;
1551     }
1553     nr_render((NRRenderer *) &lgp->lgr, pb, NULL);
1556 /*
1557  * Radial Gradient
1558  */
1560 class SPRGPainter;
1562 /// A context with radial gradient, painter, and gradient renderer.
1563 struct SPRGPainter {
1564     SPPainter painter;
1565     SPRadialGradient *rg;
1566     NRRGradientRenderer rgr;
1567 };
1569 static void sp_radialgradient_class_init(SPRadialGradientClass *klass);
1570 static void sp_radialgradient_init(SPRadialGradient *rg);
1572 static void sp_radialgradient_build(SPObject *object,
1573                                     SPDocument *document,
1574                                     Inkscape::XML::Node *repr);
1575 static void sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value);
1576 static Inkscape::XML::Node *sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1577                                                     guint flags);
1579 static SPPainter *sp_radialgradient_painter_new(SPPaintServer *ps,
1580                                                 Geom::Matrix const &full_transform,
1581                                                 Geom::Matrix const &parent_transform,
1582                                                 NRRect const *bbox);
1583 static void sp_radialgradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1585 static void sp_rg_fill(SPPainter *painter, NRPixBlock *pb);
1587 static SPGradientClass *rg_parent_class;
1589 /**
1590  * Register SPRadialGradient class and return its type.
1591  */
1592 GType
1593 sp_radialgradient_get_type()
1595     static GType type = 0;
1596     if (!type) {
1597         GTypeInfo info = {
1598             sizeof(SPRadialGradientClass),
1599             NULL, NULL,
1600             (GClassInitFunc) sp_radialgradient_class_init,
1601             NULL, NULL,
1602             sizeof(SPRadialGradient),
1603             16,
1604             (GInstanceInitFunc) sp_radialgradient_init,
1605             NULL,   /* value_table */
1606         };
1607         type = g_type_register_static(SP_TYPE_GRADIENT, "SPRadialGradient", &info, (GTypeFlags)0);
1608     }
1609     return type;
1612 /**
1613  * SPRadialGradient vtable initialization.
1614  */
1615 static void sp_radialgradient_class_init(SPRadialGradientClass *klass)
1617     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1618     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1620     rg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1622     sp_object_class->build = sp_radialgradient_build;
1623     sp_object_class->set = sp_radialgradient_set;
1624     sp_object_class->write = sp_radialgradient_write;
1626     ps_class->painter_new = sp_radialgradient_painter_new;
1627     ps_class->painter_free = sp_radialgradient_painter_free;
1630 /**
1631  * Callback for SPRadialGradient object initialization.
1632  */
1633 static void
1634 sp_radialgradient_init(SPRadialGradient *rg)
1636     rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1637     rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1638     rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1639     rg->fx.unset(SVGLength::PERCENT, 0.5, 0.5);
1640     rg->fy.unset(SVGLength::PERCENT, 0.5, 0.5);
1643 /**
1644  * Set radial gradient attributes from associated repr.
1645  */
1646 static void
1647 sp_radialgradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
1649     if (((SPObjectClass *) rg_parent_class)->build)
1650         (* ((SPObjectClass *) rg_parent_class)->build)(object, document, repr);
1652     sp_object_read_attr(object, "cx");
1653     sp_object_read_attr(object, "cy");
1654     sp_object_read_attr(object, "r");
1655     sp_object_read_attr(object, "fx");
1656     sp_object_read_attr(object, "fy");
1659 /**
1660  * Set radial gradient attribute.
1661  */
1662 static void
1663 sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value)
1665     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1667     switch (key) {
1668         case SP_ATTR_CX:
1669             if (!rg->cx.read(value)) {
1670                 rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1671             }
1672             if (!rg->fx._set) {
1673                 rg->fx.value = rg->cx.value;
1674                 rg->fx.computed = rg->cx.computed;
1675             }
1676             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1677             break;
1678         case SP_ATTR_CY:
1679             if (!rg->cy.read(value)) {
1680                 rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1681             }
1682             if (!rg->fy._set) {
1683                 rg->fy.value = rg->cy.value;
1684                 rg->fy.computed = rg->cy.computed;
1685             }
1686             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1687             break;
1688         case SP_ATTR_R:
1689             if (!rg->r.read(value)) {
1690                 rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1691             }
1692             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1693             break;
1694         case SP_ATTR_FX:
1695             if (!rg->fx.read(value)) {
1696                 rg->fx.unset(rg->cx.unit, rg->cx.value, rg->cx.computed);
1697             }
1698             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1699             break;
1700         case SP_ATTR_FY:
1701             if (!rg->fy.read(value)) {
1702                 rg->fy.unset(rg->cy.unit, rg->cy.value, rg->cy.computed);
1703             }
1704             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1705             break;
1706         default:
1707             if (((SPObjectClass *) rg_parent_class)->set)
1708                 ((SPObjectClass *) rg_parent_class)->set(object, key, value);
1709             break;
1710     }
1713 /**
1714  * Write radial gradient attributes to associated repr.
1715  */
1716 static Inkscape::XML::Node *
1717 sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1719     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1721     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1722         repr = xml_doc->createElement("svg:radialGradient");
1723     }
1725     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cx._set) sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
1726     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cy._set) sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
1727     if ((flags & SP_OBJECT_WRITE_ALL) || rg->r._set) sp_repr_set_svg_double(repr, "r", rg->r.computed);
1728     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fx._set) sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
1729     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fy._set) sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
1731     if (((SPObjectClass *) rg_parent_class)->write)
1732         (* ((SPObjectClass *) rg_parent_class)->write)(object, xml_doc, repr, flags);
1734     return repr;
1737 /**
1738  * Create radial gradient context.
1739  */
1740 static SPPainter *
1741 sp_radialgradient_painter_new(SPPaintServer *ps,
1742                               Geom::Matrix const &full_transform,
1743                               Geom::Matrix const &/*parent_transform*/,
1744                               NRRect const *bbox)
1746     SPRadialGradient *rg = SP_RADIALGRADIENT(ps);
1747     SPGradient *gr = SP_GRADIENT(ps);
1749     if (!gr->color) sp_gradient_ensure_colors(gr);
1751     SPRGPainter *rgp = g_new(SPRGPainter, 1);
1753     rgp->painter.type = SP_PAINTER_IND;
1754     rgp->painter.fill = sp_rg_fill;
1756     rgp->rg = rg;
1758     Geom::Matrix gs2px;
1760     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1761         /** \todo
1762          * fixme: We may try to normalize here too, look at
1763          * linearGradient (Lauris)
1764          */
1766         /* BBox to user coordinate system */
1767         Geom::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1769         Geom::Matrix gs2user = gr->gradientTransform * bbox2user;
1771         gs2px = gs2user * full_transform;
1772     } else {
1773         /** \todo
1774          * Problem: What to do, if we have mixed lengths and percentages?
1775          * Currently we do ignore percentages at all, but that is not
1776          * good (lauris)
1777          */
1779         gs2px = gr->gradientTransform * full_transform;
1780     }
1781     // TODO: remove gs2px_nr after converting to 2geom
1782     NR::Matrix gs2px_nr = from_2geom(gs2px);
1783     nr_rgradient_renderer_setup(&rgp->rgr, gr->color, sp_gradient_get_spread(gr),
1784                                 &gs2px_nr,
1785                                 rg->cx.computed, rg->cy.computed,
1786                                 rg->fx.computed, rg->fy.computed,
1787                                 rg->r.computed);
1789     return (SPPainter *) rgp;
1792 static void
1793 sp_radialgradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1795     g_free(painter);
1798 /**
1799  * Directly set properties of radial gradient and request modified.
1800  */
1801 void
1802 sp_radialgradient_set_position(SPRadialGradient *rg,
1803                                gdouble cx, gdouble cy, gdouble fx, gdouble fy, gdouble r)
1805     g_return_if_fail(rg != NULL);
1806     g_return_if_fail(SP_IS_RADIALGRADIENT(rg));
1808     /* fixme: units? (Lauris)  */
1809     rg->cx.set(SVGLength::NONE, cx, cx);
1810     rg->cy.set(SVGLength::NONE, cy, cy);
1811     rg->fx.set(SVGLength::NONE, fx, fx);
1812     rg->fy.set(SVGLength::NONE, fy, fy);
1813     rg->r.set(SVGLength::NONE, r, r);
1815     SP_OBJECT(rg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1818 /**
1819  * Callback when radial gradient object is rendered.
1820  */
1821 static void
1822 sp_rg_fill(SPPainter *painter, NRPixBlock *pb)
1824     SPRGPainter *rgp = (SPRGPainter *) painter;
1826     if (rgp->rg->color == NULL) {
1827         sp_gradient_ensure_colors (rgp->rg);
1828         rgp->rgr.vector = rgp->rg->color;
1829     }
1831     nr_render((NRRenderer *) &rgp->rgr, pb, NULL);
1834 /*
1835   Local Variables:
1836   mode:c++
1837   c-file-style:"stroustrup"
1838   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1839   indent-tabs-mode:nil
1840   fill-column:99
1841   End:
1842 */
1843 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :