Code

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