Code

Merging from trunk
[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 "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::Document *doc, 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     stop->specified_color.set( 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                     stop->specified_color.set( 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                     stop->specified_color.set( 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::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
204     SPStop *stop = SP_STOP(object);
206     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
207         repr = xml_doc->createElement("svg:stop");
208     }
210     guint32 specifiedcolor = stop->specified_color.toRGBA32( 255 );
211     gfloat opacity = stop->opacity;
213     if (((SPObjectClass *) stop_parent_class)->write)
214         (* ((SPObjectClass *) stop_parent_class)->write)(object, xml_doc, repr, flags);
216     // Since we do a hackish style setting here (because SPStyle does not support stop-color and
217     // stop-opacity), we must do it AFTER calling the parent write method; otherwise
218     // sp_object_write would clear our style= attribute (bug 1695287)
220     Inkscape::CSSOStringStream os;
221     os << "stop-color:";
222     if (stop->currentColor) {
223         os << "currentColor";
224     } else {
225         gchar c[64];
226         sp_svg_write_color(c, sizeof(c), specifiedcolor);
227         os << c;
228     }
229     os << ";stop-opacity:" << opacity;
230     repr->setAttribute("style", os.str().c_str());
231     repr->setAttribute("stop-color", NULL);
232     repr->setAttribute("stop-opacity", NULL);
233     sp_repr_set_css_double(repr, "offset", stop->offset);
234     /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no sense
235      * for offset proportions. */
237     return repr;
240 /**
241  * Return stop's color as 32bit value.
242  */
243 guint32
244 sp_stop_get_rgba32(SPStop const *const stop)
246     guint32 rgb0 = 0;
247     /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
248      * value depends on user agent, and don't give any further restrictions that I can
249      * see.) */
250     if (stop->currentColor) {
251         char const *str = sp_object_get_style_property(stop, "color", NULL);
252         if (str) {
253             rgb0 = sp_svg_read_color(str, rgb0);
254         }
255         unsigned const alpha = static_cast<unsigned>(stop->opacity * 0xff + 0.5);
256         g_return_val_if_fail((alpha & ~0xff) == 0,
257                              rgb0 | 0xff);
258         return rgb0 | alpha;
259     } else {
260         return stop->specified_color.toRGBA32( stop->opacity );
261     }
264 /**
265  * Return stop's color as SPColor.
266  */
267 static SPColor
268 sp_stop_get_color(SPStop const *const stop)
270     if (stop->currentColor) {
271         char const *str = sp_object_get_style_property(stop, "color", NULL);
272         guint32 const dfl = 0;
273         /* Default value: arbitrarily black.  (SVG1.1 and CSS2 both say that the initial
274          * value depends on user agent, and don't give any further restrictions that I can
275          * see.) */
276         guint32 color = dfl;
277         if (str) {
278             color = sp_svg_read_color(str, dfl);
279         }
280         SPColor ret( color );
281         return ret;
282     } else {
283         return stop->specified_color;
284     }
287 /*
288  * Gradient
289  */
291 static void sp_gradient_class_init(SPGradientClass *klass);
292 static void sp_gradient_init(SPGradient *gr);
294 static void sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
295 static void sp_gradient_release(SPObject *object);
296 static void sp_gradient_set(SPObject *object, unsigned key, gchar const *value);
297 static void sp_gradient_child_added(SPObject *object,
298                                     Inkscape::XML::Node *child,
299                                     Inkscape::XML::Node *ref);
300 static void sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child);
301 static void sp_gradient_modified(SPObject *object, guint flags);
302 static Inkscape::XML::Node *sp_gradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
303                                               guint flags);
305 static void gradient_ref_modified(SPObject *href, guint flags, SPGradient *gradient);
307 static bool sp_gradient_invalidate_vector(SPGradient *gr);
308 static void sp_gradient_rebuild_vector(SPGradient *gr);
310 static void gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gradient);
312 SPGradientSpread sp_gradient_get_spread(SPGradient *gradient);
313 SPGradientUnits sp_gradient_get_units(SPGradient *gradient);
315 static SPPaintServerClass *gradient_parent_class;
317 /**
318  * Registers SPGradient class and returns its type.
319  */
320 GType
321 sp_gradient_get_type()
323     static GType gradient_type = 0;
324     if (!gradient_type) {
325         GTypeInfo gradient_info = {
326             sizeof(SPGradientClass),
327             NULL, NULL,
328             (GClassInitFunc) sp_gradient_class_init,
329             NULL, NULL,
330             sizeof(SPGradient),
331             16,
332             (GInstanceInitFunc) sp_gradient_init,
333             NULL,   /* value_table */
334         };
335         gradient_type = g_type_register_static(SP_TYPE_PAINT_SERVER, "SPGradient",
336                                                &gradient_info, (GTypeFlags)0);
337     }
338     return gradient_type;
341 /**
342  * SPGradient vtable initialization.
343  */
344 static void
345 sp_gradient_class_init(SPGradientClass *klass)
347     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
349     gradient_parent_class = (SPPaintServerClass *)g_type_class_ref(SP_TYPE_PAINT_SERVER);
351     sp_object_class->build = sp_gradient_build;
352     sp_object_class->release = sp_gradient_release;
353     sp_object_class->set = sp_gradient_set;
354     sp_object_class->child_added = sp_gradient_child_added;
355     sp_object_class->remove_child = sp_gradient_remove_child;
356     sp_object_class->modified = sp_gradient_modified;
357     sp_object_class->write = sp_gradient_write;
360 /**
361  * Callback for SPGradient object initialization.
362  */
363 static void
364 sp_gradient_init(SPGradient *gr)
366     gr->ref = new SPGradientReference(SP_OBJECT(gr));
367     gr->ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(gradient_ref_changed), gr));
369     /** \todo
370      * Fixme: reprs being rearranged (e.g. via the XML editor)
371      * may require us to clear the state.
372      */
373     gr->state = SP_GRADIENT_STATE_UNKNOWN;
375     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
376     gr->units_set = FALSE;
378     gr->gradientTransform = NR::identity();
379     gr->gradientTransform_set = FALSE;
381     gr->spread = SP_GRADIENT_SPREAD_PAD;
382     gr->spread_set = FALSE;
384     gr->has_stops = FALSE;
386     gr->vector.built = false;
387     gr->vector.stops.clear();
389     gr->color = NULL;
391     new (&gr->modified_connection) sigc::connection();
394 /**
395  * Virtual build: set gradient attributes from its associated repr.
396  */
397 static void
398 sp_gradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
400     SPGradient *gradient = SP_GRADIENT(object);
402     if (((SPObjectClass *) gradient_parent_class)->build)
403         (* ((SPObjectClass *) gradient_parent_class)->build)(object, document, repr);
405     SPObject *ochild;
406     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
407         if (SP_IS_STOP(ochild)) {
408             gradient->has_stops = TRUE;
409             break;
410         }
411     }
413     sp_object_read_attr(object, "gradientUnits");
414     sp_object_read_attr(object, "gradientTransform");
415     sp_object_read_attr(object, "spreadMethod");
416     sp_object_read_attr(object, "xlink:href");
418     /* Register ourselves */
419     sp_document_add_resource(document, "gradient", object);
422 /**
423  * Virtual release of SPGradient members before destruction.
424  */
425 static void
426 sp_gradient_release(SPObject *object)
428     SPGradient *gradient = (SPGradient *) object;
430 #ifdef SP_GRADIENT_VERBOSE
431     g_print("Releasing gradient %s\n", SP_OBJECT_ID(object));
432 #endif
434     if (SP_OBJECT_DOCUMENT(object)) {
435         /* Unregister ourselves */
436         sp_document_remove_resource(SP_OBJECT_DOCUMENT(object), "gradient", SP_OBJECT(object));
437     }
439     if (gradient->ref) {
440         gradient->modified_connection.disconnect();
441         gradient->ref->detach();
442         delete gradient->ref;
443         gradient->ref = NULL;
444     }
446     if (gradient->color) {
447         g_free(gradient->color);
448         gradient->color = NULL;
449     }
451     gradient->modified_connection.~connection();
453     if (((SPObjectClass *) gradient_parent_class)->release)
454         ((SPObjectClass *) gradient_parent_class)->release(object);
457 /**
458  * Set gradient attribute to value.
459  */
460 static void
461 sp_gradient_set(SPObject *object, unsigned key, gchar const *value)
463     SPGradient *gr = SP_GRADIENT(object);
465     switch (key) {
466         case SP_ATTR_GRADIENTUNITS:
467             if (value) {
468                 if (!strcmp(value, "userSpaceOnUse")) {
469                     gr->units = SP_GRADIENT_UNITS_USERSPACEONUSE;
470                 } else {
471                     gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
472                 }
473                 gr->units_set = TRUE;
474             } else {
475                 gr->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
476                 gr->units_set = FALSE;
477             }
478             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
479             break;
480         case SP_ATTR_GRADIENTTRANSFORM: {
481             NR::Matrix t;
482             if (value && sp_svg_transform_read(value, &t)) {
483                 gr->gradientTransform = t;
484                 gr->gradientTransform_set = TRUE;
485             } else {
486                 gr->gradientTransform = NR::identity();
487                 gr->gradientTransform_set = FALSE;
488             }
489             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
490             break;
491         }
492         case SP_ATTR_SPREADMETHOD:
493             if (value) {
494                 if (!strcmp(value, "reflect")) {
495                     gr->spread = SP_GRADIENT_SPREAD_REFLECT;
496                 } else if (!strcmp(value, "repeat")) {
497                     gr->spread = SP_GRADIENT_SPREAD_REPEAT;
498                 } else {
499                     gr->spread = SP_GRADIENT_SPREAD_PAD;
500                 }
501                 gr->spread_set = TRUE;
502             } else {
503                 gr->spread_set = FALSE;
504             }
505             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
506             break;
507         case SP_ATTR_XLINK_HREF:
508             if (value) {
509                 try {
510                     gr->ref->attach(Inkscape::URI(value));
511                 } catch (Inkscape::BadURIException &e) {
512                     g_warning("%s", e.what());
513                     gr->ref->detach();
514                 }
515             } else {
516                 gr->ref->detach();
517             }
518             break;
519         default:
520             if (((SPObjectClass *) gradient_parent_class)->set)
521                 ((SPObjectClass *) gradient_parent_class)->set(object, key, value);
522             break;
523     }
526 /**
527  * Gets called when the gradient is (re)attached to another gradient.
528  */
529 static void
530 gradient_ref_changed(SPObject *old_ref, SPObject *ref, SPGradient *gr)
532     if (old_ref) {
533         gr->modified_connection.disconnect();
534     }
535     if ( SP_IS_GRADIENT(ref)
536          && ref != gr )
537     {
538         gr->modified_connection = ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&gradient_ref_modified), gr));
539     }
541     // Per SVG, all unset attributes must be inherited from linked gradient.
542     // So, as we're now (re)linked, we assign linkee's values to this gradient if they are not yet set -
543     // but without setting the _set flags.
544     // FIXME: do the same for gradientTransform too
545     if (!gr->units_set)
546         gr->units = sp_gradient_get_units (gr);
547     if (!gr->spread_set)
548         gr->spread = sp_gradient_get_spread (gr);
550     /// \todo Fixme: what should the flags (second) argument be? */
551     gradient_ref_modified(ref, 0, gr);
554 /**
555  * Callback for child_added event.
556  */
557 static void
558 sp_gradient_child_added(SPObject *object, Inkscape::XML::Node *child, Inkscape::XML::Node *ref)
560     SPGradient *gr = SP_GRADIENT(object);
562     sp_gradient_invalidate_vector(gr);
564     if (((SPObjectClass *) gradient_parent_class)->child_added)
565         (* ((SPObjectClass *) gradient_parent_class)->child_added)(object, child, ref);
567     SPObject *ochild = sp_object_get_child_by_repr(object, child);
568     if ( ochild && SP_IS_STOP(ochild) ) {
569         gr->has_stops = TRUE;
570     }
572     /// \todo Fixme: should we schedule "modified" here?
573     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
576 /**
577  * Callback for remove_child event.
578  */
579 static void
580 sp_gradient_remove_child(SPObject *object, Inkscape::XML::Node *child)
582     SPGradient *gr = SP_GRADIENT(object);
584     sp_gradient_invalidate_vector(gr);
586     if (((SPObjectClass *) gradient_parent_class)->remove_child)
587         (* ((SPObjectClass *) gradient_parent_class)->remove_child)(object, child);
589     gr->has_stops = FALSE;
590     SPObject *ochild;
591     for ( ochild = sp_object_first_child(object) ; ochild ; ochild = SP_OBJECT_NEXT(ochild) ) {
592         if (SP_IS_STOP(ochild)) {
593             gr->has_stops = TRUE;
594             break;
595         }
596     }
598     /* Fixme: should we schedule "modified" here? */
599     object->requestModified(SP_OBJECT_MODIFIED_FLAG);
602 /**
603  * Callback for modified event.
604  */
605 static void
606 sp_gradient_modified(SPObject *object, guint flags)
608     SPGradient *gr = SP_GRADIENT(object);
610     if (flags & SP_OBJECT_CHILD_MODIFIED_FLAG) {
611         sp_gradient_invalidate_vector(gr);
612     }
614     if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
615         sp_gradient_ensure_colors(gr);
616     }
618     if (flags & SP_OBJECT_MODIFIED_FLAG) flags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
619     flags &= SP_OBJECT_MODIFIED_CASCADE;
621     // FIXME: climb up the ladder of hrefs
622     GSList *l = NULL;
623     for (SPObject *child = sp_object_first_child(object) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
624         g_object_ref(G_OBJECT(child));
625         l = g_slist_prepend(l, child);
626     }
627     l = g_slist_reverse(l);
628     while (l) {
629         SPObject *child = SP_OBJECT(l->data);
630         l = g_slist_remove(l, child);
631         if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
632             child->emitModified(flags);
633         }
634         g_object_unref(G_OBJECT(child));
635     }
638 /**
639  * Write gradient attributes to repr.
640  */
641 static Inkscape::XML::Node *
642 sp_gradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
644     SPGradient *gr = SP_GRADIENT(object);
646     if (((SPObjectClass *) gradient_parent_class)->write)
647         (* ((SPObjectClass *) gradient_parent_class)->write)(object, xml_doc, repr, flags);
649     if (flags & SP_OBJECT_WRITE_BUILD) {
650         GSList *l = NULL;
651         for (SPObject *child = sp_object_first_child(object); child; child = SP_OBJECT_NEXT(child)) {
652             Inkscape::XML::Node *crepr;
653             crepr = child->updateRepr(xml_doc, NULL, flags);
654             if (crepr) l = g_slist_prepend(l, crepr);
655         }
656         while (l) {
657             repr->addChild((Inkscape::XML::Node *) l->data, NULL);
658             Inkscape::GC::release((Inkscape::XML::Node *) l->data);
659             l = g_slist_remove(l, l->data);
660         }
661     }
663     if (gr->ref->getURI()) {
664         gchar *uri_string = gr->ref->getURI()->toString();
665         repr->setAttribute("xlink:href", uri_string);
666         g_free(uri_string);
667     }
669     if ((flags & SP_OBJECT_WRITE_ALL) || gr->units_set) {
670         switch (gr->units) {
671             case SP_GRADIENT_UNITS_USERSPACEONUSE:
672                 repr->setAttribute("gradientUnits", "userSpaceOnUse");
673                 break;
674             default:
675                 repr->setAttribute("gradientUnits", "objectBoundingBox");
676                 break;
677         }
678     }
680     if ((flags & SP_OBJECT_WRITE_ALL) || gr->gradientTransform_set) {
681         gchar *c=sp_svg_transform_write(gr->gradientTransform);
682         repr->setAttribute("gradientTransform", c);
683         g_free(c);
684     }
686     if ((flags & SP_OBJECT_WRITE_ALL) || gr->spread_set) {
687         /* FIXME: Ensure that gr->spread is the inherited value
688          * if !gr->spread_set.  Not currently happening: see sp_gradient_modified.
689          */
690         switch (gr->spread) {
691             case SP_GRADIENT_SPREAD_REFLECT:
692                 repr->setAttribute("spreadMethod", "reflect");
693                 break;
694             case SP_GRADIENT_SPREAD_REPEAT:
695                 repr->setAttribute("spreadMethod", "repeat");
696                 break;
697             default:
698                 repr->setAttribute("spreadMethod", "pad");
699                 break;
700         }
701     }
703     return repr;
706 /**
707  * Forces the vector to be built, if not present (i.e., changed).
708  *
709  * \pre SP_IS_GRADIENT(gradient).
710  */
711 void
712 sp_gradient_ensure_vector(SPGradient *gradient)
714     g_return_if_fail(gradient != NULL);
715     g_return_if_fail(SP_IS_GRADIENT(gradient));
717     if (!gradient->vector.built) {
718         sp_gradient_rebuild_vector(gradient);
719     }
722 /**
723  * Set units property of gradient and emit modified.
724  */
725 void
726 sp_gradient_set_units(SPGradient *gr, SPGradientUnits units)
728     if (units != gr->units) {
729         gr->units = units;
730         gr->units_set = TRUE;
731         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
732     }
735 /**
736  * Set spread property of gradient and emit modified.
737  */
738 void
739 sp_gradient_set_spread(SPGradient *gr, SPGradientSpread spread)
741     if (spread != gr->spread) {
742         gr->spread = spread;
743         gr->spread_set = TRUE;
744         SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
745     }
748 /**
749  * Returns the first of {src, src-\>ref-\>getObject(),
750  * src-\>ref-\>getObject()-\>ref-\>getObject(),...}
751  * for which \a match is true, or NULL if none found.
752  *
753  * The raison d'être of this routine is that it correctly handles cycles in the href chain (e.g., if
754  * a gradient gives itself as its href, or if each of two gradients gives the other as its href).
755  *
756  * \pre SP_IS_GRADIENT(src).
757  */
758 static SPGradient *
759 chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *))
761     g_return_val_if_fail(SP_IS_GRADIENT(src), NULL);
763     /* Use a pair of pointers for detecting loops: p1 advances half as fast as p2.  If there is a
764        loop, then once p1 has entered the loop, we'll detect it the next time the distance between
765        p1 and p2 is a multiple of the loop size. */
766     SPGradient *p1 = src, *p2 = src;
767     bool do1 = false;
768     for (;;) {
769         if (match(p2)) {
770             return p2;
771         }
773         p2 = p2->ref->getObject();
774         if (!p2) {
775             return p2;
776         }
777         if (do1) {
778             p1 = p1->ref->getObject();
779         }
780         do1 = !do1;
782         if ( p2 == p1 ) {
783             /* We've been here before, so return NULL to indicate that no matching gradient found
784              * in the chain. */
785             return NULL;
786         }
787     }
790 /**
791  * True if gradient has stops.
792  */
793 static bool
794 has_stops(SPGradient const *gr)
796     return SP_GRADIENT_HAS_STOPS(gr);
799 /**
800  * True if gradient has spread set.
801  */
802 static bool
803 has_spread_set(SPGradient const *gr)
805     return gr->spread_set;
808 /**
809  * True if gradient has units set.
810  */
811 static bool
812 has_units_set(SPGradient const *gr)
814     return gr->units_set;
818 /**
819  * Returns private vector of given gradient (the gradient at the end of the href chain which has
820  * stops), optionally normalizing it.
821  *
822  * \pre SP_IS_GRADIENT(gradient).
823  * \pre There exists a gradient in the chain that has stops.
824  */
825 SPGradient *
826 sp_gradient_get_vector(SPGradient *gradient, bool force_vector)
828     g_return_val_if_fail(gradient != NULL, NULL);
829     g_return_val_if_fail(SP_IS_GRADIENT(gradient), NULL);
831     SPGradient *const src = chase_hrefs(gradient, has_stops);
832     return ( force_vector
833              ? sp_gradient_ensure_vector_normalized(src)
834              : src );
837 /**
838  * Returns the effective spread of given gradient (climbing up the refs chain if needed).
839  *
840  * \pre SP_IS_GRADIENT(gradient).
841  */
842 SPGradientSpread
843 sp_gradient_get_spread(SPGradient *gradient)
845     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_SPREAD_PAD);
847     SPGradient const *src = chase_hrefs(gradient, has_spread_set);
848     return ( src
849              ? src->spread
850              : SP_GRADIENT_SPREAD_PAD ); // pad is the default
853 /**
854  * Returns the effective units of given gradient (climbing up the refs chain if needed).
855  *
856  * \pre SP_IS_GRADIENT(gradient).
857  */
858 SPGradientUnits
859 sp_gradient_get_units(SPGradient *gradient)
861     g_return_val_if_fail(SP_IS_GRADIENT(gradient), SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX);
863     SPGradient const *src = chase_hrefs(gradient, has_units_set);
864     return ( src
865              ? src->units
866              : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ); // bbox is the default
870 /**
871  * Clears the gradient's svg:stop children from its repr.
872  */
873 void
874 sp_gradient_repr_clear_vector(SPGradient *gr)
876     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
878     /* Collect stops from original repr */
879     GSList *sl = NULL;
880     for (Inkscape::XML::Node *child = repr->firstChild() ; child != NULL; child = child->next() ) {
881         if (!strcmp(child->name(), "svg:stop")) {
882             sl = g_slist_prepend(sl, child);
883         }
884     }
885     /* Remove all stops */
886     while (sl) {
887         /** \todo
888          * fixme: This should work, unless we make gradient
889          * into generic group.
890          */
891         sp_repr_unparent((Inkscape::XML::Node *)sl->data);
892         sl = g_slist_remove(sl, sl->data);
893     }
896 /**
897  * Writes the gradient's internal vector (whether from its own stops, or
898  * inherited from refs) into the gradient repr as svg:stop elements.
899  */
900 void
901 sp_gradient_repr_write_vector(SPGradient *gr)
903     g_return_if_fail(gr != NULL);
904     g_return_if_fail(SP_IS_GRADIENT(gr));
906     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(gr));
907     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
909     /* We have to be careful, as vector may be our own, so construct repr list at first */
910     GSList *cl = NULL;
912     for (guint i = 0; i < gr->vector.stops.size(); i++) {
913         Inkscape::CSSOStringStream os;
914         Inkscape::XML::Node *child = xml_doc->createElement("svg:stop");
915         sp_repr_set_css_double(child, "offset", gr->vector.stops[i].offset);
916         /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no
917          * sense for offset proportions. */
918         gchar c[64];
919         sp_svg_write_color(c, sizeof(c), gr->vector.stops[i].color.toRGBA32( 0x00 ));
920         os << "stop-color:" << c << ";stop-opacity:" << gr->vector.stops[i].opacity;
921         child->setAttribute("style", os.str().c_str());
922         /* Order will be reversed here */
923         cl = g_slist_prepend(cl, child);
924     }
926     sp_gradient_repr_clear_vector(gr);
928     /* And insert new children from list */
929     while (cl) {
930         Inkscape::XML::Node *child = static_cast<Inkscape::XML::Node *>(cl->data);
931         repr->addChild(child, NULL);
932         Inkscape::GC::release(child);
933         cl = g_slist_remove(cl, child);
934     }
938 static void
939 gradient_ref_modified(SPObject */*href*/, guint /*flags*/, SPGradient *gradient)
941     if (sp_gradient_invalidate_vector(gradient)) {
942         SP_OBJECT(gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
943         /* Conditional to avoid causing infinite loop if there's a cycle in the href chain. */
944     }
947 /** Return true iff change made. */
948 static bool
949 sp_gradient_invalidate_vector(SPGradient *gr)
951     bool ret = false;
953     if (gr->color != NULL) {
954         g_free(gr->color);
955         gr->color = NULL;
956         ret = true;
957     }
959     if (gr->vector.built) {
960         gr->vector.built = false;
961         gr->vector.stops.clear();
962         ret = true;
963     }
965     return ret;
968 /** Creates normalized color vector */
969 static void
970 sp_gradient_rebuild_vector(SPGradient *gr)
972     gint len = 0;
973     for ( SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
974           child != NULL ;
975           child = SP_OBJECT_NEXT(child) ) {
976         if (SP_IS_STOP(child)) {
977             len ++;
978         }
979     }
981     gr->has_stops = (len != 0);
983     gr->vector.stops.clear();
985     SPGradient *ref = gr->ref->getObject();
986     if ( !gr->has_stops && ref ) {
987         /* Copy vector from referenced gradient */
988         gr->vector.built = true;   // Prevent infinite recursion.
989         sp_gradient_ensure_vector(ref);
990         if (!ref->vector.stops.empty()) {
991             gr->vector.built = ref->vector.built;
992             gr->vector.stops.assign(ref->vector.stops.begin(), ref->vector.stops.end());
993             return;
994         }
995     }
997     for (SPObject *child = sp_object_first_child(SP_OBJECT(gr)) ;
998          child != NULL;
999          child = SP_OBJECT_NEXT(child) ) {
1000         if (SP_IS_STOP(child)) {
1001             SPStop *stop = SP_STOP(child);
1003             SPGradientStop gstop;
1004             if (gr->vector.stops.size() > 0) {
1005                 // "Each gradient offset value is required to be equal to or greater than the
1006                 // previous gradient stop's offset value. If a given gradient stop's offset
1007                 // value is not equal to or greater than all previous offset values, then the
1008                 // offset value is adjusted to be equal to the largest of all previous offset
1009                 // values."
1010                 gstop.offset = MAX(stop->offset, gr->vector.stops.back().offset);
1011             } else {
1012                 gstop.offset = stop->offset;
1013             }
1015             // "Gradient offset values less than 0 (or less than 0%) are rounded up to
1016             // 0%. Gradient offset values greater than 1 (or greater than 100%) are rounded
1017             // down to 100%."
1018             gstop.offset = CLAMP(gstop.offset, 0, 1);
1020             gstop.color = sp_stop_get_color(stop);
1021             gstop.opacity = stop->opacity;
1023             gr->vector.stops.push_back(gstop);
1024         }
1025     }
1027     // Normalize per section 13.2.4 of SVG 1.1.
1028     if (gr->vector.stops.size() == 0) {
1029         /* "If no stops are defined, then painting shall occur as if 'none' were specified as the
1030          * paint style."
1031          */
1032         {
1033             SPGradientStop gstop;
1034             gstop.offset = 0.0;
1035             gstop.color.set( 0x00000000 );
1036             gstop.opacity = 0.0;
1037             gr->vector.stops.push_back(gstop);
1038         }
1039         {
1040             SPGradientStop gstop;
1041             gstop.offset = 1.0;
1042             gstop.color.set( 0x00000000 );
1043             gstop.opacity = 0.0;
1044             gr->vector.stops.push_back(gstop);
1045         }
1046     } else {
1047         /* "If one stop is defined, then paint with the solid color fill using the color defined
1048          * for that gradient stop."
1049          */
1050         if (gr->vector.stops.front().offset > 0.0) {
1051             // If the first one is not at 0, then insert a copy of the first at 0.
1052             SPGradientStop gstop;
1053             gstop.offset = 0.0;
1054             gstop.color = gr->vector.stops.front().color;
1055             gstop.opacity = gr->vector.stops.front().opacity;
1056             gr->vector.stops.insert(gr->vector.stops.begin(), gstop);
1057         }
1058         if (gr->vector.stops.back().offset < 1.0) {
1059             // If the last one is not at 1, then insert a copy of the last at 1.
1060             SPGradientStop gstop;
1061             gstop.offset = 1.0;
1062             gstop.color = gr->vector.stops.back().color;
1063             gstop.opacity = gr->vector.stops.back().opacity;
1064             gr->vector.stops.push_back(gstop);
1065         }
1066     }
1068     gr->vector.built = true;
1071 /**
1072  * The gradient's color array is newly created and set up from vector.
1073  */
1074 void
1075 sp_gradient_ensure_colors(SPGradient *gr)
1077     if (!gr->vector.built) {
1078         sp_gradient_rebuild_vector(gr);
1079     }
1080     g_return_if_fail(!gr->vector.stops.empty());
1082     /// \todo Where is the memory freed?
1083     if (!gr->color) {
1084         gr->color = g_new(guchar, 4 * NCOLORS);
1085     }
1087     for (guint i = 0; i < gr->vector.stops.size() - 1; i++) {
1088         guint32 color = gr->vector.stops[i].color.toRGBA32( gr->vector.stops[i].opacity );
1089         gint r0 = (color >> 24) & 0xff;
1090         gint g0 = (color >> 16) & 0xff;
1091         gint b0 = (color >> 8) & 0xff;
1092         gint a0 = color & 0xff;
1093         color = gr->vector.stops[i + 1].color.toRGBA32( gr->vector.stops[i + 1].opacity );
1094         gint r1 = (color >> 24) & 0xff;
1095         gint g1 = (color >> 16) & 0xff;
1096         gint b1 = (color >> 8) & 0xff;
1097         gint a1 = color & 0xff;
1098         gint o0 = (gint) floor(gr->vector.stops[i].offset * (NCOLORS - 0.001));
1099         gint o1 = (gint) floor(gr->vector.stops[i + 1].offset * (NCOLORS - 0.001));
1100         if (o1 > o0) {
1101             gint dr = ((r1 - r0) << 16) / (o1 - o0);
1102             gint dg = ((g1 - g0) << 16) / (o1 - o0);
1103             gint db = ((b1 - b0) << 16) / (o1 - o0);
1104             gint da = ((a1 - a0) << 16) / (o1 - o0);
1105             gint r = r0 << 16;
1106             gint g = g0 << 16;
1107             gint b = b0 << 16;
1108             gint a = a0 << 16;
1109             for (int j = o0; j < o1 + 1; j++) {
1110                 gr->color[4 * j] = r >> 16;
1111                 gr->color[4 * j + 1] = g >> 16;
1112                 gr->color[4 * j + 2] = b >> 16;
1113                 gr->color[4 * j + 3] = a >> 16;
1114                 r += dr;
1115                 g += dg;
1116                 b += db;
1117                 a += da;
1118             }
1119         }
1120     }
1123 /**
1124  * Renders gradient vector to buffer as line.
1125  *
1126  * RGB buffer background should be set up beforehand.
1127  *
1128  * @param len,width,height,rowstride Buffer parameters (1 or 2 dimensional).
1129  * @param span Full integer width of requested gradient.
1130  * @param pos Buffer starting position in span.
1131  */
1132 static void
1133 sp_gradient_render_vector_line_rgba(SPGradient *const gradient, guchar *buf,
1134                                     gint const len, gint const pos, gint const span)
1136     g_return_if_fail(gradient != NULL);
1137     g_return_if_fail(SP_IS_GRADIENT(gradient));
1138     g_return_if_fail(buf != NULL);
1139     g_return_if_fail(len > 0);
1140     g_return_if_fail(pos >= 0);
1141     g_return_if_fail(pos + len <= span);
1142     g_return_if_fail(span > 0);
1144     if (!gradient->color) {
1145         sp_gradient_ensure_colors(gradient);
1146     }
1148     gint idx = (pos * 1024 << 8) / span;
1149     gint didx = (1024 << 8) / span;
1151     for (gint x = 0; x < len; x++) {
1152         /// \todo Can this be done with 4 byte copies?
1153         *buf++ = gradient->color[4 * (idx >> 8)];
1154         *buf++ = gradient->color[4 * (idx >> 8) + 1];
1155         *buf++ = gradient->color[4 * (idx >> 8) + 2];
1156         *buf++ = gradient->color[4 * (idx >> 8) + 3];
1157         idx += didx;
1158     }
1161 /**
1162  * Render rectangular RGBA area from gradient vector.
1163  */
1164 void
1165 sp_gradient_render_vector_block_rgba(SPGradient *const gradient, guchar *buf,
1166                                      gint const width, gint const height, gint const rowstride,
1167                                      gint const pos, gint const span, bool const horizontal)
1169     g_return_if_fail(gradient != NULL);
1170     g_return_if_fail(SP_IS_GRADIENT(gradient));
1171     g_return_if_fail(buf != NULL);
1172     g_return_if_fail(width > 0);
1173     g_return_if_fail(height > 0);
1174     g_return_if_fail(pos >= 0);
1175     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1176     g_return_if_fail(span > 0);
1178     if (horizontal) {
1179         sp_gradient_render_vector_line_rgba(gradient, buf, width, pos, span);
1180         for (gint y = 1; y < height; y++) {
1181             memcpy(buf + y * rowstride, buf, 4 * width);
1182         }
1183     } else {
1184         guchar *tmp = (guchar *)alloca(4 * height);
1185         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1186         for (gint y = 0; y < height; y++) {
1187             guchar *b = buf + y * rowstride;
1188             for (gint x = 0; x < width; x++) {
1189                 *b++ = tmp[0];
1190                 *b++ = tmp[1];
1191                 *b++ = tmp[2];
1192                 *b++ = tmp[3];
1193             }
1194             tmp += 4;
1195         }
1196     }
1199 /**
1200  * Render rectangular RGB area from gradient vector.
1201  */
1202 void
1203 sp_gradient_render_vector_block_rgb(SPGradient *gradient, guchar *buf,
1204                                     gint const width, gint const height, gint const /*rowstride*/,
1205                                     gint const pos, gint const span, bool const horizontal)
1207     g_return_if_fail(gradient != NULL);
1208     g_return_if_fail(SP_IS_GRADIENT(gradient));
1209     g_return_if_fail(buf != NULL);
1210     g_return_if_fail(width > 0);
1211     g_return_if_fail(height > 0);
1212     g_return_if_fail(pos >= 0);
1213     g_return_if_fail((horizontal && (pos + width <= span)) || (!horizontal && (pos + height <= span)));
1214     g_return_if_fail(span > 0);
1216     if (horizontal) {
1217         guchar *tmp = (guchar*)alloca(4 * width);
1218         sp_gradient_render_vector_line_rgba(gradient, tmp, width, pos, span);
1219         for (gint y = 0; y < height; y++) {
1220             guchar *t = tmp;
1221             for (gint x = 0; x < width; x++) {
1222                 gint a = t[3];
1223                 gint fc = (t[0] - buf[0]) * a;
1224                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1225                 fc = (t[1] - buf[1]) * a;
1226                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1227                 fc = (t[2] - buf[2]) * a;
1228                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1229                 buf += 3;
1230                 t += 4;
1231             }
1232         }
1233     } else {
1234         guchar *tmp = (guchar*)alloca(4 * height);
1235         sp_gradient_render_vector_line_rgba(gradient, tmp, height, pos, span);
1236         for (gint y = 0; y < height; y++) {
1237             guchar *t = tmp + 4 * y;
1238             for (gint x = 0; x < width; x++) {
1239                 gint a = t[3];
1240                 gint fc = (t[0] - buf[0]) * a;
1241                 buf[0] = buf[0] + ((fc + (fc >> 8) + 0x80) >> 8);
1242                 fc = (t[1] - buf[1]) * a;
1243                 buf[1] = buf[1] + ((fc + (fc >> 8) + 0x80) >> 8);
1244                 fc = (t[2] - buf[2]) * a;
1245                 buf[2] = buf[2] + ((fc + (fc >> 8) + 0x80) >> 8);
1246             }
1247         }
1248     }
1251 NR::Matrix
1252 sp_gradient_get_g2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1254     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1255         return ( Geom::Scale(bbox.dimensions())
1256                  * Geom::Translate(bbox.min())
1257                  * Geom::Matrix(ctm) );
1258     } else {
1259         return ctm;
1260     }
1263 NR::Matrix
1264 sp_gradient_get_gs2d_matrix(SPGradient const *gr, NR::Matrix const &ctm, NR::Rect const &bbox)
1266     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1267         return ( gr->gradientTransform
1268                  * Geom::Scale(bbox.dimensions())
1269                  * Geom::Translate(bbox.min())
1270                  * Geom::Matrix(ctm) );
1271     } else {
1272         return gr->gradientTransform * ctm;
1273     }
1276 void
1277 sp_gradient_set_gs2d_matrix(SPGradient *gr, NR::Matrix const &ctm,
1278                             NR::Rect const &bbox, NR::Matrix const &gs2d)
1280     gr->gradientTransform = gs2d * ctm.inverse();
1281     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) {
1282         gr->gradientTransform = ( gr->gradientTransform
1283                                   * Geom::Translate(-bbox.min())
1284                                   * Geom::Scale(bbox.dimensions()).inverse() );
1285     }
1286     gr->gradientTransform_set = TRUE;
1288     SP_OBJECT(gr)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1291 /*
1292  * Linear Gradient
1293  */
1295 class SPLGPainter;
1297 /// A context with linear gradient, painter, and gradient renderer.
1298 struct SPLGPainter {
1299     SPPainter painter;
1300     SPLinearGradient *lg;
1302     NRLGradientRenderer lgr;
1303 };
1305 static void sp_lineargradient_class_init(SPLinearGradientClass *klass);
1306 static void sp_lineargradient_init(SPLinearGradient *lg);
1308 static void sp_lineargradient_build(SPObject *object,
1309                                     SPDocument *document,
1310                                     Inkscape::XML::Node *repr);
1311 static void sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value);
1312 static Inkscape::XML::Node *sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1313                                                     guint flags);
1315 static SPPainter *sp_lineargradient_painter_new(SPPaintServer *ps,
1316                                                 NR::Matrix const &full_transform,
1317                                                 NR::Matrix const &parent_transform,
1318                                                 NRRect const *bbox);
1319 static void sp_lineargradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1321 static void sp_lg_fill(SPPainter *painter, NRPixBlock *pb);
1323 static SPGradientClass *lg_parent_class;
1325 /**
1326  * Register SPLinearGradient class and return its type.
1327  */
1328 GType
1329 sp_lineargradient_get_type()
1331     static GType type = 0;
1332     if (!type) {
1333         GTypeInfo info = {
1334             sizeof(SPLinearGradientClass),
1335             NULL, NULL,
1336             (GClassInitFunc) sp_lineargradient_class_init,
1337             NULL, NULL,
1338             sizeof(SPLinearGradient),
1339             16,
1340             (GInstanceInitFunc) sp_lineargradient_init,
1341             NULL,   /* value_table */
1342         };
1343         type = g_type_register_static(SP_TYPE_GRADIENT, "SPLinearGradient", &info, (GTypeFlags)0);
1344     }
1345     return type;
1348 /**
1349  * SPLinearGradient vtable initialization.
1350  */
1351 static void sp_lineargradient_class_init(SPLinearGradientClass *klass)
1353     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1354     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1356     lg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1358     sp_object_class->build = sp_lineargradient_build;
1359     sp_object_class->set = sp_lineargradient_set;
1360     sp_object_class->write = sp_lineargradient_write;
1362     ps_class->painter_new = sp_lineargradient_painter_new;
1363     ps_class->painter_free = sp_lineargradient_painter_free;
1366 /**
1367  * Callback for SPLinearGradient object initialization.
1368  */
1369 static void sp_lineargradient_init(SPLinearGradient *lg)
1371     lg->x1.unset(SVGLength::PERCENT, 0.0, 0.0);
1372     lg->y1.unset(SVGLength::PERCENT, 0.5, 0.5);
1373     lg->x2.unset(SVGLength::PERCENT, 1.0, 1.0);
1374     lg->y2.unset(SVGLength::PERCENT, 0.5, 0.5);
1377 /**
1378  * Callback: set attributes from associated repr.
1379  */
1380 static void sp_lineargradient_build(SPObject *object,
1381                                     SPDocument *document,
1382                                     Inkscape::XML::Node *repr)
1384     if (((SPObjectClass *) lg_parent_class)->build)
1385         (* ((SPObjectClass *) lg_parent_class)->build)(object, document, repr);
1387     sp_object_read_attr(object, "x1");
1388     sp_object_read_attr(object, "y1");
1389     sp_object_read_attr(object, "x2");
1390     sp_object_read_attr(object, "y2");
1393 /**
1394  * Callback: set attribute.
1395  */
1396 static void
1397 sp_lineargradient_set(SPObject *object, unsigned key, gchar const *value)
1399     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1401     switch (key) {
1402         case SP_ATTR_X1:
1403             lg->x1.readOrUnset(value, SVGLength::PERCENT, 0.0, 0.0);
1404             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1405             break;
1406         case SP_ATTR_Y1:
1407             lg->y1.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1408             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1409             break;
1410         case SP_ATTR_X2:
1411             lg->x2.readOrUnset(value, SVGLength::PERCENT, 1.0, 1.0);
1412             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1413             break;
1414         case SP_ATTR_Y2:
1415             lg->y2.readOrUnset(value, SVGLength::PERCENT, 0.5, 0.5);
1416             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1417             break;
1418         default:
1419             if (((SPObjectClass *) lg_parent_class)->set)
1420                 (* ((SPObjectClass *) lg_parent_class)->set)(object, key, value);
1421             break;
1422     }
1425 /**
1426  * Callback: write attributes to associated repr.
1427  */
1428 static Inkscape::XML::Node *
1429 sp_lineargradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1431     SPLinearGradient *lg = SP_LINEARGRADIENT(object);
1433     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1434         repr = xml_doc->createElement("svg:linearGradient");
1435     }
1437     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x1._set)
1438         sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
1439     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y1._set)
1440         sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
1441     if ((flags & SP_OBJECT_WRITE_ALL) || lg->x2._set)
1442         sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
1443     if ((flags & SP_OBJECT_WRITE_ALL) || lg->y2._set)
1444         sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
1446     if (((SPObjectClass *) lg_parent_class)->write)
1447         (* ((SPObjectClass *) lg_parent_class)->write)(object, xml_doc, repr, flags);
1449     return repr;
1452 /**
1453  * Create linear gradient context.
1454  *
1455  * Basically we have to deal with transformations
1456  *
1457  * 1) color2norm - maps point in (0,NCOLORS) vector to (0,1) vector
1458  * 2) norm2pos - maps (0,1) vector to x1,y1 - x2,y2
1459  * 2) gradientTransform
1460  * 3) bbox2user
1461  * 4) ctm == userspace to pixel grid
1462  *
1463  * See also (*) in sp-pattern about why we may need parent_transform.
1464  *
1465  * \todo (point 1 above) fixme: I do not know how to deal with start > 0
1466  * and end < 1.
1467  */
1468 static SPPainter *
1469 sp_lineargradient_painter_new(SPPaintServer *ps,
1470                               NR::Matrix const &full_transform,
1471                               NR::Matrix const &/*parent_transform*/,
1472                               NRRect const *bbox)
1474     SPLinearGradient *lg = SP_LINEARGRADIENT(ps);
1475     SPGradient *gr = SP_GRADIENT(ps);
1477     if (!gr->color) sp_gradient_ensure_colors(gr);
1479     SPLGPainter *lgp = g_new(SPLGPainter, 1);
1481     lgp->painter.type = SP_PAINTER_IND;
1482     lgp->painter.fill = sp_lg_fill;
1484     lgp->lg = lg;
1486     /** \todo
1487      * Technically speaking, we map NCOLORS on line [start,end] onto line
1488      * [0,1].  I almost think we should fill color array start and end in
1489      * that case. The alternative would be to leave these just empty garbage
1490      * or something similar. Originally I had 1023.9999 here - not sure
1491      * whether we have really to cut out ceil int (Lauris).
1492      */
1493     NR::Matrix color2norm(NR::identity());
1494     NR::Matrix color2px;
1495     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1496         NR::Matrix norm2pos(NR::identity());
1498         /* BBox to user coordinate system */
1499         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1501         NR::Matrix color2pos = color2norm * norm2pos;
1502         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1503         NR::Matrix color2user = color2tpos * bbox2user;
1504         color2px = color2user * full_transform;
1506     } else {
1507         /* Problem: What to do, if we have mixed lengths and percentages? */
1508         /* Currently we do ignore percentages at all, but that is not good (lauris) */
1510         NR::Matrix norm2pos(NR::identity());
1511         NR::Matrix color2pos = color2norm * norm2pos;
1512         NR::Matrix color2tpos = color2pos * gr->gradientTransform;
1513         color2px = color2tpos * full_transform;
1515     }
1517     nr_lgradient_renderer_setup(&lgp->lgr, gr->color, sp_gradient_get_spread(gr), &color2px,
1518                                 lg->x1.computed, lg->y1.computed,
1519                                 lg->x2.computed, lg->y2.computed);
1521     return (SPPainter *) lgp;
1524 static void
1525 sp_lineargradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1527     g_free(painter);
1530 /**
1531  * Directly set properties of linear gradient and request modified.
1532  */
1533 void
1534 sp_lineargradient_set_position(SPLinearGradient *lg,
1535                                gdouble x1, gdouble y1,
1536                                gdouble x2, gdouble y2)
1538     g_return_if_fail(lg != NULL);
1539     g_return_if_fail(SP_IS_LINEARGRADIENT(lg));
1541     /* fixme: units? (Lauris)  */
1542     lg->x1.set(SVGLength::NONE, x1, x1);
1543     lg->y1.set(SVGLength::NONE, y1, y1);
1544     lg->x2.set(SVGLength::NONE, x2, x2);
1545     lg->y2.set(SVGLength::NONE, y2, y2);
1547     SP_OBJECT(lg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1550 /**
1551  * Callback when linear gradient object is rendered.
1552  */
1553 static void
1554 sp_lg_fill(SPPainter *painter, NRPixBlock *pb)
1556     SPLGPainter *lgp = (SPLGPainter *) painter;
1558     if (lgp->lg->color == NULL) {
1559         sp_gradient_ensure_colors (lgp->lg);
1560         lgp->lgr.vector = lgp->lg->color;
1561     }
1563     nr_render((NRRenderer *) &lgp->lgr, pb, NULL);
1566 /*
1567  * Radial Gradient
1568  */
1570 class SPRGPainter;
1572 /// A context with radial gradient, painter, and gradient renderer.
1573 struct SPRGPainter {
1574     SPPainter painter;
1575     SPRadialGradient *rg;
1576     NRRGradientRenderer rgr;
1577 };
1579 static void sp_radialgradient_class_init(SPRadialGradientClass *klass);
1580 static void sp_radialgradient_init(SPRadialGradient *rg);
1582 static void sp_radialgradient_build(SPObject *object,
1583                                     SPDocument *document,
1584                                     Inkscape::XML::Node *repr);
1585 static void sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value);
1586 static Inkscape::XML::Node *sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr,
1587                                                     guint flags);
1589 static SPPainter *sp_radialgradient_painter_new(SPPaintServer *ps,
1590                                                 NR::Matrix const &full_transform,
1591                                                 NR::Matrix const &parent_transform,
1592                                                 NRRect const *bbox);
1593 static void sp_radialgradient_painter_free(SPPaintServer *ps, SPPainter *painter);
1595 static void sp_rg_fill(SPPainter *painter, NRPixBlock *pb);
1597 static SPGradientClass *rg_parent_class;
1599 /**
1600  * Register SPRadialGradient class and return its type.
1601  */
1602 GType
1603 sp_radialgradient_get_type()
1605     static GType type = 0;
1606     if (!type) {
1607         GTypeInfo info = {
1608             sizeof(SPRadialGradientClass),
1609             NULL, NULL,
1610             (GClassInitFunc) sp_radialgradient_class_init,
1611             NULL, NULL,
1612             sizeof(SPRadialGradient),
1613             16,
1614             (GInstanceInitFunc) sp_radialgradient_init,
1615             NULL,   /* value_table */
1616         };
1617         type = g_type_register_static(SP_TYPE_GRADIENT, "SPRadialGradient", &info, (GTypeFlags)0);
1618     }
1619     return type;
1622 /**
1623  * SPRadialGradient vtable initialization.
1624  */
1625 static void sp_radialgradient_class_init(SPRadialGradientClass *klass)
1627     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
1628     SPPaintServerClass *ps_class = (SPPaintServerClass *) klass;
1630     rg_parent_class = (SPGradientClass*)g_type_class_ref(SP_TYPE_GRADIENT);
1632     sp_object_class->build = sp_radialgradient_build;
1633     sp_object_class->set = sp_radialgradient_set;
1634     sp_object_class->write = sp_radialgradient_write;
1636     ps_class->painter_new = sp_radialgradient_painter_new;
1637     ps_class->painter_free = sp_radialgradient_painter_free;
1640 /**
1641  * Callback for SPRadialGradient object initialization.
1642  */
1643 static void
1644 sp_radialgradient_init(SPRadialGradient *rg)
1646     rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1647     rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1648     rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1649     rg->fx.unset(SVGLength::PERCENT, 0.5, 0.5);
1650     rg->fy.unset(SVGLength::PERCENT, 0.5, 0.5);
1653 /**
1654  * Set radial gradient attributes from associated repr.
1655  */
1656 static void
1657 sp_radialgradient_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
1659     if (((SPObjectClass *) rg_parent_class)->build)
1660         (* ((SPObjectClass *) rg_parent_class)->build)(object, document, repr);
1662     sp_object_read_attr(object, "cx");
1663     sp_object_read_attr(object, "cy");
1664     sp_object_read_attr(object, "r");
1665     sp_object_read_attr(object, "fx");
1666     sp_object_read_attr(object, "fy");
1669 /**
1670  * Set radial gradient attribute.
1671  */
1672 static void
1673 sp_radialgradient_set(SPObject *object, unsigned key, gchar const *value)
1675     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1677     switch (key) {
1678         case SP_ATTR_CX:
1679             if (!rg->cx.read(value)) {
1680                 rg->cx.unset(SVGLength::PERCENT, 0.5, 0.5);
1681             }
1682             if (!rg->fx._set) {
1683                 rg->fx.value = rg->cx.value;
1684                 rg->fx.computed = rg->cx.computed;
1685             }
1686             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1687             break;
1688         case SP_ATTR_CY:
1689             if (!rg->cy.read(value)) {
1690                 rg->cy.unset(SVGLength::PERCENT, 0.5, 0.5);
1691             }
1692             if (!rg->fy._set) {
1693                 rg->fy.value = rg->cy.value;
1694                 rg->fy.computed = rg->cy.computed;
1695             }
1696             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1697             break;
1698         case SP_ATTR_R:
1699             if (!rg->r.read(value)) {
1700                 rg->r.unset(SVGLength::PERCENT, 0.5, 0.5);
1701             }
1702             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1703             break;
1704         case SP_ATTR_FX:
1705             if (!rg->fx.read(value)) {
1706                 rg->fx.unset(rg->cx.unit, rg->cx.value, rg->cx.computed);
1707             }
1708             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1709             break;
1710         case SP_ATTR_FY:
1711             if (!rg->fy.read(value)) {
1712                 rg->fy.unset(rg->cy.unit, rg->cy.value, rg->cy.computed);
1713             }
1714             object->requestModified(SP_OBJECT_MODIFIED_FLAG);
1715             break;
1716         default:
1717             if (((SPObjectClass *) rg_parent_class)->set)
1718                 ((SPObjectClass *) rg_parent_class)->set(object, key, value);
1719             break;
1720     }
1723 /**
1724  * Write radial gradient attributes to associated repr.
1725  */
1726 static Inkscape::XML::Node *
1727 sp_radialgradient_write(SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
1729     SPRadialGradient *rg = SP_RADIALGRADIENT(object);
1731     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
1732         repr = xml_doc->createElement("svg:radialGradient");
1733     }
1735     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cx._set) sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
1736     if ((flags & SP_OBJECT_WRITE_ALL) || rg->cy._set) sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
1737     if ((flags & SP_OBJECT_WRITE_ALL) || rg->r._set) sp_repr_set_svg_double(repr, "r", rg->r.computed);
1738     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fx._set) sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
1739     if ((flags & SP_OBJECT_WRITE_ALL) || rg->fy._set) sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
1741     if (((SPObjectClass *) rg_parent_class)->write)
1742         (* ((SPObjectClass *) rg_parent_class)->write)(object, xml_doc, repr, flags);
1744     return repr;
1747 /**
1748  * Create radial gradient context.
1749  */
1750 static SPPainter *
1751 sp_radialgradient_painter_new(SPPaintServer *ps,
1752                               NR::Matrix const &full_transform,
1753                               NR::Matrix const &/*parent_transform*/,
1754                               NRRect const *bbox)
1756     SPRadialGradient *rg = SP_RADIALGRADIENT(ps);
1757     SPGradient *gr = SP_GRADIENT(ps);
1759     if (!gr->color) sp_gradient_ensure_colors(gr);
1761     SPRGPainter *rgp = g_new(SPRGPainter, 1);
1763     rgp->painter.type = SP_PAINTER_IND;
1764     rgp->painter.fill = sp_rg_fill;
1766     rgp->rg = rg;
1768     NR::Matrix gs2px;
1770     if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
1771         /** \todo
1772          * fixme: We may try to normalize here too, look at
1773          * linearGradient (Lauris)
1774          */
1776         /* BBox to user coordinate system */
1777         NR::Matrix bbox2user(bbox->x1 - bbox->x0, 0, 0, bbox->y1 - bbox->y0, bbox->x0, bbox->y0);
1779         NR::Matrix gs2user = gr->gradientTransform * bbox2user;
1781         gs2px = gs2user * full_transform;
1782     } else {
1783         /** \todo
1784          * Problem: What to do, if we have mixed lengths and percentages?
1785          * Currently we do ignore percentages at all, but that is not
1786          * good (lauris)
1787          */
1789         gs2px = gr->gradientTransform * full_transform;
1790     }
1792     nr_rgradient_renderer_setup(&rgp->rgr, gr->color, sp_gradient_get_spread(gr),
1793                                 &gs2px,
1794                                 rg->cx.computed, rg->cy.computed,
1795                                 rg->fx.computed, rg->fy.computed,
1796                                 rg->r.computed);
1798     return (SPPainter *) rgp;
1801 static void
1802 sp_radialgradient_painter_free(SPPaintServer */*ps*/, SPPainter *painter)
1804     g_free(painter);
1807 /**
1808  * Directly set properties of radial gradient and request modified.
1809  */
1810 void
1811 sp_radialgradient_set_position(SPRadialGradient *rg,
1812                                gdouble cx, gdouble cy, gdouble fx, gdouble fy, gdouble r)
1814     g_return_if_fail(rg != NULL);
1815     g_return_if_fail(SP_IS_RADIALGRADIENT(rg));
1817     /* fixme: units? (Lauris)  */
1818     rg->cx.set(SVGLength::NONE, cx, cx);
1819     rg->cy.set(SVGLength::NONE, cy, cy);
1820     rg->fx.set(SVGLength::NONE, fx, fx);
1821     rg->fy.set(SVGLength::NONE, fy, fy);
1822     rg->r.set(SVGLength::NONE, r, r);
1824     SP_OBJECT(rg)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1827 /**
1828  * Callback when radial gradient object is rendered.
1829  */
1830 static void
1831 sp_rg_fill(SPPainter *painter, NRPixBlock *pb)
1833     SPRGPainter *rgp = (SPRGPainter *) painter;
1835     if (rgp->rg->color == NULL) {
1836         sp_gradient_ensure_colors (rgp->rg);
1837         rgp->rgr.vector = rgp->rg->color;
1838     }
1840     nr_render((NRRenderer *) &rgp->rgr, pb, NULL);
1843 /*
1844   Local Variables:
1845   mode:c++
1846   c-file-style:"stroustrup"
1847   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1848   indent-tabs-mode:nil
1849   fill-column:99
1850   End:
1851 */
1852 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :