~centralelyon2010/inkscape/imagelinks2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
/*
 * Various utility methods for gradients
 *
 * Authors:
 *   Lauris Kaplinski <lauris@kaplinski.com>
 *   bulia byak
 *   Johan Engelen <j.b.c.engelen@ewi.utwente.nl>
 *   Jon A. Cruz <jon@joncruz.org>
 *   Abhishek Sharma
 *
 * Copyright (C) 2010 Authors
 * Copyright (C) 2007 Johan Engelen
 * Copyright (C) 2001-2005 authors
 * Copyright (C) 2001 Ximian, Inc.
 *
 * Released under GNU GPL, read the file 'COPYING' for more information
 */

#include <2geom/transforms.h>
#include <2geom/bezier-curve.h>

#include "style.h"
#include "document-private.h"
#include "desktop-style.h"

#include "sp-gradient-reference.h"
#include "sp-gradient-vector.h"
#include "sp-linear-gradient.h"
#include "sp-radial-gradient.h"
#include "sp-stop.h"
#include "widgets/gradient-vector.h"

#include "sp-text.h"
#include "sp-tspan.h"
#include "xml/repr.h"
#include "svg/svg.h"
#include "svg/svg-color.h"
#include "svg/css-ostringstream.h"
#include "preferences.h"

#define noSP_GR_VERBOSE

// Terminology:
//
// "vector" is a gradient that has stops but not position coords. It can be referenced by one or
// more privates. Objects should not refer to it directly. It has no radial/linear distinction.
//
// "private" is a gradient that has no stops but has position coords (e.g. center, radius etc for a
// radial). It references a vector for the actual colors. Each private is only used by one
// object. It is either linear or radial.

static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *gr);

SPGradient *sp_gradient_ensure_vector_normalized(SPGradient *gr)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_ensure_vector_normalized(%p)", gr);
#endif
    g_return_val_if_fail(gr != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);

    /* If we are already normalized vector, just return */
    if (gr->state == SP_GRADIENT_STATE_VECTOR) return gr;
    /* Fail, if we have wrong state set */
    if (gr->state != SP_GRADIENT_STATE_UNKNOWN) {
        g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, gr->getId());
        return NULL;
    }

    /* First make sure we have vector directly defined (i.e. gr has its own stops) */
    if ( !gr->hasStops() ) {
        /* We do not have stops ourselves, so flatten stops as well */
        gr->ensureVector();
        g_assert(gr->vector.built);
        // this adds stops from gr->vector as children to gr
        sp_gradient_repr_write_vector (gr);
    }

    /* If gr hrefs some other gradient, remove the href */
    if (gr->ref->getObject()) {
        // We are hrefing someone, so require flattening
        gr->updateRepr(SP_OBJECT_WRITE_EXT | SP_OBJECT_WRITE_ALL);
        sp_gradient_repr_set_link(gr->getRepr(), NULL);
    }

    /* Everything is OK, set state flag */
    gr->state = SP_GRADIENT_STATE_VECTOR;
    return gr;
}

/**
 * Creates new private gradient for the given vector
 */

static SPGradient *sp_gradient_get_private_normalized(SPDocument *document, SPGradient *vector, SPGradientType type)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_get_private_normalized(%p, %p, %d)", document, vector, type);
#endif

    g_return_val_if_fail(document != NULL, NULL);
    g_return_val_if_fail(vector != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(vector), NULL);
    g_return_val_if_fail(vector->hasStops(), NULL);

    SPDefs *defs = document->getDefs();

    Inkscape::XML::Document *xml_doc = document->getReprDoc();
    // create a new private gradient of the requested type
    Inkscape::XML::Node *repr;
    if (type == SP_GRADIENT_TYPE_LINEAR) {
        repr = xml_doc->createElement("svg:linearGradient");
    } else {
        repr = xml_doc->createElement("svg:radialGradient");
    }

    // privates are garbage-collectable
    repr->setAttribute("inkscape:collect", "always");

    // link to vector
    sp_gradient_repr_set_link(repr, vector);

    /* Append the new private gradient to defs */
    defs->getRepr()->appendChild(repr);
    Inkscape::GC::release(repr);

    // get corresponding object
    SPGradient *gr = (SPGradient *) document->getObjectByRepr(repr);
    g_assert(gr != NULL);
    g_assert(SP_IS_GRADIENT(gr));

    return gr;
}

/**
Count how many times gr is used by the styles of o and its descendants
*/
guint count_gradient_hrefs(SPObject *o, SPGradient *gr)
{
    if (!o)
        return 1;

    guint i = 0;

    SPStyle *style = o->style;
    if (style
        && style->fill.isPaintserver()
        && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style))
        && SP_GRADIENT(SP_STYLE_FILL_SERVER(style)) == gr)
    {
        i ++;
    }
    if (style
        && style->stroke.isPaintserver()
        && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style))
        && SP_GRADIENT(SP_STYLE_STROKE_SERVER(style)) == gr)
    {
        i ++;
    }

    for ( SPObject *child = o->firstChild(); child; child = child->getNext() ) {
        i += count_gradient_hrefs(child, gr);
    }

    return i;
}


/**
 * If gr has other users, create a new private; also check if gr links to vector, relink if not
 */
SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
                                                  SPGradientType type, SPObject *o)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_fork_private_if_necessary(%p, %p, %d, %p)", gr, vector, type, o);
#endif
    g_return_val_if_fail(gr != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);

    // Orphaned gradient, no vector with stops at the end of the line; this used to be an assert
    // but i think we should not abort on this - maybe just write a validity warning into some sort
    // of log
    if ( !vector || !vector->hasStops() ) {
        return (gr);
    }

    // user is the object that uses this gradient; normally it's item but for tspans, we
    // check its ancestor text so that tspans don't get different gradients from their
    // texts.
    SPObject *user = o;
    while (SP_IS_TSPAN(user)) {
        user = user->parent;
    }

    // Check the number of uses of the gradient within this object;
    // if we are private and there are no other users,
    if (!vector->isSwatch() && (gr->hrefcount <= count_gradient_hrefs(user, gr))) {
        // check vector
        if ( gr != vector && gr->ref->getObject() != vector ) {
            /* our href is not the vector, and vector is different from gr; relink */
            sp_gradient_repr_set_link(gr->getRepr(), vector);
        }
        return gr;
    }

    SPDocument *doc = gr->document;
    SPObject *defs = doc->getDefs();

    if ((gr->hasStops()) ||
        (gr->state != SP_GRADIENT_STATE_UNKNOWN) ||
        (gr->parent != SP_OBJECT(defs)) ||
        (gr->hrefcount > 1)) {
        // we have to clone a fresh new private gradient for the given vector

        // create an empty one
        SPGradient *gr_new = sp_gradient_get_private_normalized(doc, vector, type);

        // copy all the attributes to it
        Inkscape::XML::Node *repr_new = gr_new->getRepr();
        Inkscape::XML::Node *repr = gr->getRepr();
        repr_new->setAttribute("gradientUnits", repr->attribute("gradientUnits"));
        repr_new->setAttribute("gradientTransform", repr->attribute("gradientTransform"));
        repr_new->setAttribute("spreadMethod", repr->attribute("spreadMethod"));
        if (SP_IS_RADIALGRADIENT(gr)) {
            repr_new->setAttribute("cx", repr->attribute("cx"));
            repr_new->setAttribute("cy", repr->attribute("cy"));
            repr_new->setAttribute("fx", repr->attribute("fx"));
            repr_new->setAttribute("fy", repr->attribute("fy"));
            repr_new->setAttribute("r", repr->attribute("r"));
        } else {
            repr_new->setAttribute("x1", repr->attribute("x1"));
            repr_new->setAttribute("y1", repr->attribute("y1"));
            repr_new->setAttribute("x2", repr->attribute("x2"));
            repr_new->setAttribute("y2", repr->attribute("y2"));
        }

        return gr_new;
    } else {
        return gr;
    }
}

SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_fork_vector_if_necessary(%p)", gr);
#endif
    // Some people actually prefer their gradient vectors to be shared...
    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
    if (!prefs->getBool("/options/forkgradientvectors/value", true))
        return gr;

    if (gr->hrefcount > 1) {
        SPDocument *doc = gr->document;
        Inkscape::XML::Document *xml_doc = doc->getReprDoc();

        Inkscape::XML::Node *repr = gr->getRepr()->duplicate(xml_doc);
        doc->getDefs()->getRepr()->addChild(repr, NULL);
        SPGradient *gr_new = (SPGradient *) doc->getObjectByRepr(repr);
        gr_new = sp_gradient_ensure_vector_normalized (gr_new);
        Inkscape::GC::release(repr);
        return gr_new;
    }
    return gr;
}

/**
 *  Obtain the vector from the gradient. A forked vector will be created and linked to this gradient if another gradient uses it.
 */
SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_get_forked_vector_if_necessary(%p, %d)", gradient, force_vector);
#endif
    SPGradient *vector = gradient->getVector(force_vector);
    vector = sp_gradient_fork_vector_if_necessary (vector);
    if ( gradient != vector && gradient->ref->getObject() != vector ) {
        sp_gradient_repr_set_link(gradient->getRepr(), vector);
    }
    return vector;
}


/**
 * Convert an item's gradient to userspace _without_ preserving coords, setting them to defaults
 * instead. No forking or reapplying is done because this is only called for newly created privates.
 * @return The new gradient.
 */
SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_reset_to_userspace(%p, %p)", gr, item);
#endif
    Inkscape::XML::Node *repr = gr->getRepr();

    // calculate the bbox of the item
    item->document->ensureUpToDate();
    Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine

    if (!bbox)
        return gr;

    Geom::Coord const width = bbox->dimensions()[Geom::X];
    Geom::Coord const height = bbox->dimensions()[Geom::Y];

    Geom::Point const center = bbox->midpoint();

    if (SP_IS_RADIALGRADIENT(gr)) {
        sp_repr_set_svg_double(repr, "cx", center[Geom::X]);
        sp_repr_set_svg_double(repr, "cy", center[Geom::Y]);
        sp_repr_set_svg_double(repr, "fx", center[Geom::X]);
        sp_repr_set_svg_double(repr, "fy", center[Geom::Y]);
        sp_repr_set_svg_double(repr, "r", width/2);

        // we want it to be elliptic, not circular
        Geom::Affine squeeze = Geom::Translate (-center) *
            Geom::Scale(1, height/width) *
            Geom::Translate (center);

        gr->gradientTransform = squeeze;
        {
            gchar *c=sp_svg_transform_write(gr->gradientTransform);
            gr->getRepr()->setAttribute("gradientTransform", c);
            g_free(c);
        }
    } else {
        sp_repr_set_svg_double(repr, "x1", (center - Geom::Point(width/2, 0))[Geom::X]);
        sp_repr_set_svg_double(repr, "y1", (center - Geom::Point(width/2, 0))[Geom::Y]);
        sp_repr_set_svg_double(repr, "x2", (center + Geom::Point(width/2, 0))[Geom::X]);
        sp_repr_set_svg_double(repr, "y2", (center + Geom::Point(width/2, 0))[Geom::Y]);
    }

    // set the gradientUnits
    repr->setAttribute("gradientUnits", "userSpaceOnUse");

    return gr;
}

/**
 * Convert an item's gradient to userspace if necessary, also fork it if necessary.
 * @return The new gradient.
 */
SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *property)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_convert_to_userspace(%p, %p, \"%s\")", gr, item, property);
#endif
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);

    if ( gr && gr->isSolid() ) {
        return gr;
    }

    // First, fork it if it is shared
    gr = sp_gradient_fork_private_if_necessary(gr, gr->getVector(),
                                               SP_IS_RADIALGRADIENT(gr) ? SP_GRADIENT_TYPE_RADIAL : SP_GRADIENT_TYPE_LINEAR, item);

    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {

        Inkscape::XML::Node *repr = gr->getRepr();

        // calculate the bbox of the item
        item->document->ensureUpToDate();
        Geom::Affine bbox2user;
        Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine
        if ( bbox ) {
            bbox2user = Geom::Affine(bbox->dimensions()[Geom::X], 0,
                                   0, bbox->dimensions()[Geom::Y],
                                   bbox->min()[Geom::X], bbox->min()[Geom::Y]);
        } else {
            // would be degenerate otherwise
            bbox2user = Geom::identity();
        }

        /* skew is the additional transform, defined by the proportions of the item, that we need
         * to apply to the gradient in order to work around this weird bit from SVG 1.1
         * (http://www.w3.org/TR/SVG11/pservers.html#LinearGradients):
         *
         *   When gradientUnits="objectBoundingBox" and gradientTransform is the identity
         *   matrix, the stripes of the linear gradient are perpendicular to the gradient
         *   vector in object bounding box space (i.e., the abstract coordinate system where
         *   (0,0) is at the top/left of the object bounding box and (1,1) is at the
         *   bottom/right of the object bounding box). When the object's bounding box is not
         *   square, the stripes that are conceptually perpendicular to the gradient vector
         *   within object bounding box space will render non-perpendicular relative to the
         *   gradient vector in user space due to application of the non-uniform scaling
         *   transformation from bounding box space to user space.
         */
        Geom::Affine skew = bbox2user;
        double exp = skew.descrim();
        skew[0] /= exp;
        skew[1] /= exp;
        skew[2] /= exp;
        skew[3] /= exp;
        skew[4] = 0;
        skew[5] = 0;

        // apply skew to the gradient
        gr->gradientTransform = skew;
        {
            gchar *c=sp_svg_transform_write(gr->gradientTransform);
            gr->getRepr()->setAttribute("gradientTransform", c);
            g_free(c);
        }

        // Matrix to convert points to userspace coords; postmultiply by inverse of skew so
        // as to cancel it out when it's applied to the gradient during rendering
        Geom::Affine point_convert = bbox2user * skew.inverse();

        if (SP_IS_RADIALGRADIENT(gr)) {
            SPRadialGradient *rg = SP_RADIALGRADIENT(gr);

            // original points in the bbox coords
            Geom::Point c_b = Geom::Point(rg->cx.computed, rg->cy.computed);
            Geom::Point f_b = Geom::Point(rg->fx.computed, rg->fy.computed);
            double r_b = rg->r.computed;

            // converted points in userspace coords
            Geom::Point c_u = c_b * point_convert;
            Geom::Point f_u = f_b * point_convert;
            double r_u = r_b * point_convert.descrim();

            sp_repr_set_svg_double(repr, "cx", c_u[Geom::X]);
            sp_repr_set_svg_double(repr, "cy", c_u[Geom::Y]);
            sp_repr_set_svg_double(repr, "fx", f_u[Geom::X]);
            sp_repr_set_svg_double(repr, "fy", f_u[Geom::Y]);
            sp_repr_set_svg_double(repr, "r", r_u);

        } else {
            SPLinearGradient *lg = SP_LINEARGRADIENT(gr);

            Geom::Point p1_b = Geom::Point(lg->x1.computed, lg->y1.computed);
            Geom::Point p2_b = Geom::Point(lg->x2.computed, lg->y2.computed);

            Geom::Point p1_u = p1_b * point_convert;
            Geom::Point p2_u = p2_b * point_convert;

            sp_repr_set_svg_double(repr, "x1", p1_u[Geom::X]);
            sp_repr_set_svg_double(repr, "y1", p1_u[Geom::Y]);
            sp_repr_set_svg_double(repr, "x2", p2_u[Geom::X]);
            sp_repr_set_svg_double(repr, "y2", p2_u[Geom::Y]);
        }

        // set the gradientUnits
        repr->setAttribute("gradientUnits", "userSpaceOnUse");
    }

    // apply the gradient to the item (may be necessary if we forked it); not recursive
    // generally because grouped items will be taken care of later (we're being called
    // from sp_item_adjust_paint_recursive); however text and all its children should all
    // refer to one gradient, hence the recursive call for text (because we can't/don't
    // want to access tspans and set gradients on them separately)
    if (SP_IS_TEXT(item)) {
        sp_style_set_property_url(item, property, gr, true);
    } else {
        sp_style_set_property_url(item, property, gr, false);
    }

    return gr;
}

void sp_gradient_transform_multiply(SPGradient *gradient, Geom::Affine postmul, bool set)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_transform_multiply(%p, , %d)", gradient, set);
#endif
    if (set) {
        gradient->gradientTransform = postmul;
    } else {
        gradient->gradientTransform *= postmul; // fixme: get gradient transform by climbing to hrefs?
    }
    gradient->gradientTransform_set = TRUE;

    gchar *c=sp_svg_transform_write(gradient->gradientTransform);
    gradient->getRepr()->setAttribute("gradientTransform", c);
    g_free(c);
}

SPGradient *sp_item_gradient(SPItem *item, bool fill_or_stroke)
{
    SPStyle *style = item->style;
    SPGradient *gradient = 0;

    if (fill_or_stroke) {
        if (style && (style->fill.isPaintserver())) {
            SPPaintServer *server = item->style->getFillPaintServer();
            if ( SP_IS_GRADIENT(server) ) {
                gradient = SP_GRADIENT(server);
            }
        }
    } else {
        if (style && (style->stroke.isPaintserver())) {
            SPPaintServer *server = item->style->getStrokePaintServer();
            if ( SP_IS_GRADIENT(server) ) {
                gradient = SP_GRADIENT(server);
            }
        }
    }

   return gradient;
}

SPStop *sp_last_stop(SPGradient *gradient)
{
    for (SPStop *stop = gradient->getFirstStop(); stop != NULL; stop = stop->getNextStop()) {
        if (stop->getNextStop() == NULL)
            return stop;
    }
    return NULL;
}

SPStop *sp_get_stop_i(SPGradient *gradient, guint stop_i)
{
    SPStop *stop = gradient->getFirstStop();

    // if this is valid but weird gradient without an offset-zero stop element,
    // inkscape has created a handle for the start of gradient anyway,
    // so when it asks for stop N that corresponds to stop element N-1
    if (stop->offset != 0)
        stop_i --;

    for (guint i = 0; i < stop_i; i++) {
        if (!stop) {
            return NULL;
        }
        stop = stop->getNextStop();
    }

    return stop;
}

guint32 average_color(guint32 c1, guint32 c2, gdouble p)
{
    guint32 r = (guint32) (SP_RGBA32_R_U (c1) * (1 - p) + SP_RGBA32_R_U (c2) * p);
    guint32 g = (guint32) (SP_RGBA32_G_U (c1) * (1 - p) + SP_RGBA32_G_U (c2) * p);
    guint32 b = (guint32) (SP_RGBA32_B_U (c1) * (1 - p) + SP_RGBA32_B_U (c2) * p);
    guint32 a = (guint32) (SP_RGBA32_A_U (c1) * (1 - p) + SP_RGBA32_A_U (c2) * p);

    return SP_RGBA32_U_COMPOSE(r, g, b, a);
}

SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_stop, gfloat offset)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_vector_add_stop(%p, %p, %p, %f)", vector, prev_stop, next_stop, offset);
#endif

    Inkscape::XML::Node *new_stop_repr = NULL;
    new_stop_repr = prev_stop->getRepr()->duplicate(vector->getRepr()->document());
    vector->getRepr()->addChild(new_stop_repr, prev_stop->getRepr());

    SPStop *newstop = reinterpret_cast<SPStop *>(vector->document->getObjectByRepr(new_stop_repr));
    newstop->offset = offset;
    sp_repr_set_css_double( newstop->getRepr(), "offset", (double)offset);
    guint32 const c1 = sp_stop_get_rgba32(prev_stop);
    guint32 const c2 = sp_stop_get_rgba32(next_stop);
    guint32 cnew = average_color (c1, c2, (offset - prev_stop->offset) / (next_stop->offset - prev_stop->offset));
    Inkscape::CSSOStringStream os;
    gchar c[64];
    sp_svg_write_color (c, sizeof(c), cnew);
    gdouble opacity = (gdouble) SP_RGBA32_A_F (cnew);
    os << "stop-color:" << c << ";stop-opacity:" << opacity <<";";
    newstop->getRepr()->setAttribute("style", os.str().c_str());
    Inkscape::GC::release(new_stop_repr);

    return newstop;
}

void sp_item_gradient_edit_stop(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
{
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (!gradient || !SP_IS_GRADIENT(gradient))
        return;

    SPGradient *vector = gradient->getVector();
    switch (point_type) {
        case POINT_LG_BEGIN:
        case POINT_RG_CENTER:
        case POINT_RG_FOCUS:
        {
            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, vector->getFirstStop());
            gtk_widget_show (dialog);
        }
        break;

        case POINT_LG_END:
        case POINT_RG_R1:
        case POINT_RG_R2:
        {
            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, sp_last_stop (vector));
            gtk_widget_show (dialog);
        }
        break;

        case POINT_LG_MID:
        case POINT_RG_MID1:
        case POINT_RG_MID2:
        {
            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, sp_get_stop_i (vector, point_i));
            gtk_widget_show (dialog);
        }
        break;
        default:
            break;
    }
}

guint32 sp_item_gradient_stop_query_style(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
{
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (!gradient || !SP_IS_GRADIENT(gradient))
        return 0;

    SPGradient *vector = gradient->getVector();

    if (!vector) // orphan!
        return 0; // what else to do?

    switch (point_type) {
        case POINT_LG_BEGIN:
        case POINT_RG_CENTER:
        case POINT_RG_FOCUS:
        {
            SPStop *first = vector->getFirstStop();
            if (first) {
                return sp_stop_get_rgba32(first);
            }
        }
        break;

        case POINT_LG_END:
        case POINT_RG_R1:
        case POINT_RG_R2:
        {
            SPStop *last = sp_last_stop (vector);
            if (last) {
                return sp_stop_get_rgba32(last);
            }
        }
        break;

        case POINT_LG_MID:
        case POINT_RG_MID1:
        case POINT_RG_MID2:
        {
            SPStop *stopi = sp_get_stop_i (vector, point_i);
            if (stopi) {
                return sp_stop_get_rgba32(stopi);
            }
        }
        break;

        default:
            break;
    }
    return 0;
}

void sp_item_gradient_stop_set_style(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke, SPCSSAttr *stop)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_item_gradient_stop_set_style(%p, %d, %d, %d, %p)", item, point_type, point_i, fill_or_stroke, stop);
#endif
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (!gradient || !SP_IS_GRADIENT(gradient))
        return;

    SPGradient *vector = gradient->getVector();

    if (!vector) // orphan!
        return;

    vector = sp_gradient_fork_vector_if_necessary (vector);
    if ( gradient != vector && gradient->ref->getObject() != vector ) {
        sp_gradient_repr_set_link(gradient->getRepr(), vector);
    }

    switch (point_type) {
        case POINT_LG_BEGIN:
        case POINT_RG_CENTER:
        case POINT_RG_FOCUS:
        {
            SPStop *first = vector->getFirstStop();
            if (first) {
                sp_repr_css_change(first->getRepr(), stop, "style");
            }
        }
        break;

        case POINT_LG_END:
        case POINT_RG_R1:
        case POINT_RG_R2:
        {
            SPStop *last = sp_last_stop (vector);
            if (last) {
                sp_repr_css_change(last->getRepr(), stop, "style");
            }
        }
        break;

        case POINT_LG_MID:
        case POINT_RG_MID1:
        case POINT_RG_MID2:
        {
            SPStop *stopi = sp_get_stop_i (vector, point_i);
            if (stopi) {
                sp_repr_css_change(stopi->getRepr(), stop, "style");
            }
        }
        break;

        default:
            break;
    }
}

void sp_item_gradient_reverse_vector(SPItem *item, bool fill_or_stroke)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_item_gradient_reverse_vector(%p, %d)", item, fill_or_stroke);
#endif
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
    if (!gradient || !SP_IS_GRADIENT(gradient))
        return;

    SPGradient *vector = gradient->getVector();
    if (!vector) // orphan!
        return;

    vector = sp_gradient_fork_vector_if_necessary (vector);
    if ( gradient != vector && gradient->ref->getObject() != vector ) {
        sp_gradient_repr_set_link(gradient->getRepr(), vector);
    }

    GSList *child_reprs = NULL;
    GSList *child_objects = NULL;
    std::vector<double> offsets;
    for ( SPObject *child = vector->firstChild(); child; child = child->getNext()) {
        child_reprs = g_slist_prepend (child_reprs, child->getRepr());
        child_objects = g_slist_prepend (child_objects, child);
        offsets.push_back(sp_repr_get_double_attribute(child->getRepr(), "offset", 0));
    }

    GSList *child_copies = NULL;
    for (GSList *i = child_reprs; i != NULL; i = i->next) {
        Inkscape::XML::Node *repr = (Inkscape::XML::Node *) i->data;
        Inkscape::XML::Document *xml_doc = vector->getRepr()->document();
        child_copies = g_slist_append (child_copies, repr->duplicate(xml_doc));
    }


    for (GSList *i = child_objects; i != NULL; i = i->next) {
        SPObject *child = SP_OBJECT (i->data);
        child->deleteObject();
    }

    std::vector<double>::iterator iter = offsets.end() - 1;
    for (GSList *i = child_copies; i != NULL; i = i->next) {
        Inkscape::XML::Node *copy = (Inkscape::XML::Node *) i->data;
        vector->appendChildRepr(copy);
        sp_repr_set_svg_double (copy, "offset", 1 - *iter);
        iter --;
        Inkscape::GC::release(copy);
    }

    g_slist_free (child_reprs);
    g_slist_free (child_copies);
    g_slist_free (child_objects);
}


/**
Set the position of point point_type of the gradient applied to item (either fill_or_stroke) to
p_w (in desktop coordinates). Write_repr if you want the change to become permanent.
*/
void sp_item_gradient_set_coords(SPItem *item, guint point_type, guint point_i, Geom::Point p_w, bool fill_or_stroke, bool write_repr, bool scale)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_item_gradient_set_coords(%p, %d, %d, ...)", item, point_type, point_i );
#endif
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (!gradient || !SP_IS_GRADIENT(gradient))
        return;

    gradient = sp_gradient_convert_to_userspace (gradient, item, fill_or_stroke? "fill" : "stroke");

    Geom::Affine i2d (item->i2dt_affine ());
    Geom::Point p = p_w * i2d.inverse();
    p *= (gradient->gradientTransform).inverse();
    // now p is in gradient's original coordinates

    Inkscape::XML::Node *repr = gradient->getRepr();

    if (SP_IS_LINEARGRADIENT(gradient)) {
        SPLinearGradient *lg = SP_LINEARGRADIENT(gradient);
        switch (point_type) {
            case POINT_LG_BEGIN:
                if (scale) {
                    lg->x2.computed += (lg->x1.computed - p[Geom::X]);
                    lg->y2.computed += (lg->y1.computed - p[Geom::Y]);
                }
                lg->x1.computed = p[Geom::X];
                lg->y1.computed = p[Geom::Y];
                if (write_repr) {
                    if (scale) {
                        sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
                        sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
                    }
                    sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
                    sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
                } else {
                    gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
                }
                break;
            case POINT_LG_END:
                if (scale) {
                    lg->x1.computed += (lg->x2.computed - p[Geom::X]);
                    lg->y1.computed += (lg->y2.computed - p[Geom::Y]);
                }
                lg->x2.computed = p[Geom::X];
                lg->y2.computed = p[Geom::Y];
                if (write_repr) {
                    if (scale) {
                        sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
                        sp_repr_set_svg_double(repr, "y1", lg->y1.computed);
                    }
                    sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
                    sp_repr_set_svg_double(repr, "y2", lg->y2.computed);
                } else {
                    gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
                }
                break;
            case POINT_LG_MID:
            {
                // using X-coordinates only to determine the offset, assuming p has been snapped to the vector from begin to end.
                Geom::Point begin(lg->x1.computed, lg->y1.computed);
                Geom::Point end(lg->x2.computed, lg->y2.computed);
                double offset = Geom::LineSegment(begin, end).nearestPoint(p);
                SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (lg, false);
                lg->ensureVector();
                lg->vector.stops.at(point_i).offset = offset;
                SPStop* stopi = sp_get_stop_i(vector, point_i);
                stopi->offset = offset;
                if (write_repr) {
                    sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset);
                } else {
                    stopi->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
                }
            }
            break;
            default:
                break;
        }
    } else if (SP_IS_RADIALGRADIENT(gradient)) {
        SPRadialGradient *rg = SP_RADIALGRADIENT(gradient);
        Geom::Point c (rg->cx.computed, rg->cy.computed);
        Geom::Point c_w = c * gradient->gradientTransform * i2d; // now in desktop coords
        if ((point_type == POINT_RG_R1 || point_type == POINT_RG_R2) && Geom::L2 (p_w - c_w) < 1e-3) {
            // prevent setting a radius too close to the center
            return;
        }
        Geom::Affine new_transform;
        bool transform_set = false;

        switch (point_type) {
            case POINT_RG_CENTER:
                rg->fx.computed = p[Geom::X] + (rg->fx.computed - rg->cx.computed);
                rg->fy.computed = p[Geom::Y] + (rg->fy.computed - rg->cy.computed);
                rg->cx.computed = p[Geom::X];
                rg->cy.computed = p[Geom::Y];
                if (write_repr) {
                    sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
                    sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
                    sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
                    sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
                } else {
                    gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
                }
                break;
            case POINT_RG_FOCUS:
                rg->fx.computed = p[Geom::X];
                rg->fy.computed = p[Geom::Y];
                if (write_repr) {
                    sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
                    sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
                } else {
                    gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
                }
                break;
            case POINT_RG_R1:
            {
                Geom::Point r1_w = (c + Geom::Point(rg->r.computed, 0)) * gradient->gradientTransform * i2d;
                double r1_angle = Geom::atan2(r1_w - c_w);
                double move_angle = Geom::atan2(p_w - c_w) - r1_angle;
                double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r1_w - c_w);

                Geom::Affine move = Geom::Affine (Geom::Translate (-c_w)) *
                    Geom::Affine (Geom::Rotate(-r1_angle)) *
                    Geom::Affine (Geom::Scale(move_stretch, scale? move_stretch : 1)) *
                    Geom::Affine (Geom::Rotate(r1_angle)) *
                    Geom::Affine (Geom::Rotate(move_angle)) *
                    Geom::Affine (Geom::Translate (c_w));

                new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
                transform_set = true;

                break;
            }
            case POINT_RG_R2:
            {
                Geom::Point r2_w = (c + Geom::Point(0, -rg->r.computed)) * gradient->gradientTransform * i2d;
                double r2_angle = Geom::atan2(r2_w - c_w);
                double move_angle = Geom::atan2(p_w - c_w) - r2_angle;
                double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r2_w - c_w);

                Geom::Affine move = Geom::Affine (Geom::Translate (-c_w)) *
                    Geom::Affine (Geom::Rotate(-r2_angle)) *
                    Geom::Affine (Geom::Scale(move_stretch, scale? move_stretch : 1)) *
                    Geom::Affine (Geom::Rotate(r2_angle)) *
                    Geom::Affine (Geom::Rotate(move_angle)) *
                    Geom::Affine (Geom::Translate (c_w));

                new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
                transform_set = true;

                break;
            }
        case POINT_RG_MID1:
            {
                Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed);
                Geom::Point end   = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
                double offset = Geom::LineSegment(start, end).nearestPoint(p);
                SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (rg, false);
                rg->ensureVector();
                rg->vector.stops.at(point_i).offset = offset;
                SPStop* stopi = sp_get_stop_i(vector, point_i);
                stopi->offset = offset;
                if (write_repr) {
                    sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset);
                } else {
                    stopi->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
                }
                break;
            }
        case POINT_RG_MID2:
                Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed);
                Geom::Point end   = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
                double offset = Geom::LineSegment(start, end).nearestPoint(p);
                SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(rg, false);
                rg->ensureVector();
                rg->vector.stops.at(point_i).offset = offset;
                SPStop* stopi = sp_get_stop_i(vector, point_i);
                stopi->offset = offset;
                if (write_repr) {
                    sp_repr_set_css_double(stopi->getRepr(), "offset", stopi->offset);
                } else {
                    stopi->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
                }
                break;
        }

        if (transform_set) {
            gradient->gradientTransform = new_transform;
            gradient->gradientTransform_set = TRUE;
            if (write_repr) {
                gchar *s=sp_svg_transform_write(gradient->gradientTransform);
                gradient->getRepr()->setAttribute("gradientTransform", s);
                g_free(s);
            } else {
                gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
            }
        }
    }
}

SPGradient *sp_item_gradient_get_vector(SPItem *item, bool fill_or_stroke)
{
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (gradient) {
        return gradient->getVector();
    }
    return NULL;
}

SPGradientSpread sp_item_gradient_get_spread(SPItem *item, bool fill_or_stroke)
{
    SPGradientSpread spread = SP_GRADIENT_SPREAD_PAD;
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    if (gradient) {
        spread = gradient->fetchSpread();
    }
    return spread;
}


/**
Returns the position of point point_type of the gradient applied to item (either fill_or_stroke),
in desktop coordinates.
*/

Geom::Point sp_item_gradient_get_coords(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_item_gradient_get_coords(%p, %d, %d, %d)", item, point_type, point_i, fill_or_stroke);
#endif
    SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);

    Geom::Point p (0, 0);

    if (!gradient)
        return p;

    if (SP_IS_LINEARGRADIENT(gradient)) {
        SPLinearGradient *lg = SP_LINEARGRADIENT(gradient);
        switch (point_type) {
            case POINT_LG_BEGIN:
                p = Geom::Point (lg->x1.computed, lg->y1.computed);
                break;
            case POINT_LG_END:
                p = Geom::Point (lg->x2.computed, lg->y2.computed);
                break;
            case POINT_LG_MID:
                {
                    gdouble offset = lg->vector.stops.at(point_i).offset;
                    p = (1-offset) * Geom::Point(lg->x1.computed, lg->y1.computed) + offset * Geom::Point(lg->x2.computed, lg->y2.computed);
                }
                break;
        }
    } else     if (SP_IS_RADIALGRADIENT(gradient)) {
        SPRadialGradient *rg = SP_RADIALGRADIENT(gradient);
        switch (point_type) {
            case POINT_RG_CENTER:
                p = Geom::Point (rg->cx.computed, rg->cy.computed);
                break;
            case POINT_RG_FOCUS:
                p = Geom::Point (rg->fx.computed, rg->fy.computed);
                break;
            case POINT_RG_R1:
                p = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
                break;
            case POINT_RG_R2:
                p = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
                break;
            case POINT_RG_MID1:
                {
                    gdouble offset = rg->vector.stops.at(point_i).offset;
                    p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed);
                }
                break;
            case POINT_RG_MID2:
                {
                    gdouble offset = rg->vector.stops.at(point_i).offset;
                    p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed);
                }
                break;
        }
    }

    if (SP_GRADIENT(gradient)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
        item->document->ensureUpToDate();
        Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine
        if (bbox) {
            p *= Geom::Affine(bbox->dimensions()[Geom::X], 0,
                            0, bbox->dimensions()[Geom::Y],
                            bbox->min()[Geom::X], bbox->min()[Geom::Y]);
        }
    }
    p *= Geom::Affine(gradient->gradientTransform) * (Geom::Affine)item->i2dt_affine();
    return p;
}


/**
 * Sets item fill or stroke to the gradient of the specified type with given vector, creating
 * new private gradient, if needed.
 * gr has to be a normalized vector.
 */

SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, bool is_fill)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_item_set_gradient(%p, %p, %d, %d)", item, gr, type, is_fill);
#endif
    g_return_val_if_fail(item != NULL, NULL);
    g_return_val_if_fail(SP_IS_ITEM(item), NULL);
    g_return_val_if_fail(gr != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
    g_return_val_if_fail(gr->state == SP_GRADIENT_STATE_VECTOR, NULL);

    SPStyle *style = item->style;
    g_assert(style != NULL);

    SPPaintServer *ps = NULL;
    if (is_fill? style->fill.isPaintserver() : style->stroke.isPaintserver())
        ps = is_fill? SP_STYLE_FILL_SERVER(style) : SP_STYLE_STROKE_SERVER(style);

    if (ps
        && ( (type == SP_GRADIENT_TYPE_LINEAR && SP_IS_LINEARGRADIENT(ps)) ||
             (type == SP_GRADIENT_TYPE_RADIAL && SP_IS_RADIALGRADIENT(ps))   ) )
    {

        /* Current fill style is the gradient of the required type */
        SPGradient *current = SP_GRADIENT(ps);

        //g_message("hrefcount %d   count %d\n", current->hrefcount, count_gradient_hrefs(item, current));

        if (!current->isSwatch()
            && (current->hrefcount == 1 ||
            current->hrefcount == count_gradient_hrefs(item, current))) {

            // current is private and it's either used once, or all its uses are by children of item;
            // so just change its href to vector

            if ( current != gr && current->getVector() != gr ) {
                // href is not the vector
                sp_gradient_repr_set_link(current->getRepr(), gr);
            }
            item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
            return current;

        } else {

            // the gradient is not private, or it is shared with someone else;
            // normalize it (this includes creating new private if necessary)
            SPGradient *normalized = sp_gradient_fork_private_if_necessary(current, gr, type, item);

            g_return_val_if_fail(normalized != NULL, NULL);

            if (normalized != current) {

                /* We have to change object style here; recursive because this is used from
                 * fill&stroke and must work for groups etc. */
                sp_style_set_property_url(item, is_fill? "fill" : "stroke", normalized, true);
            }
            item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
            return normalized;
        }

    } else {
        /* Current fill style is not a gradient or wrong type, so construct everything */
        SPGradient *constructed = sp_gradient_get_private_normalized(item->document, gr, type);
        constructed = sp_gradient_reset_to_userspace(constructed, item);
        sp_style_set_property_url(item, ( is_fill ? "fill" : "stroke" ), constructed, true);
        item->requestDisplayUpdate(( SP_OBJECT_MODIFIED_FLAG |
                                     SP_OBJECT_STYLE_MODIFIED_FLAG ));
        return constructed;
    }
}

static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *link)
{
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_repr_set_link(%p, %p)", repr, link);
#endif
    g_return_if_fail(repr != NULL);
    if (link) {
        g_return_if_fail(SP_IS_GRADIENT(link));
    }

    if (link) {
        Glib::ustring ref("#");
        ref += link->getId();
        repr->setAttribute("xlink:href", ref.c_str());
    } else {
        repr->setAttribute("xlink:href", 0);
    }
}


static void addStop( Inkscape::XML::Node *parent, Glib::ustring const &color, gint opacity, gchar const *offset )
{
#ifdef SP_GR_VERBOSE
    g_message("addStop(%p, %s, %d, %s)", parent, color.c_str(), opacity, offset);
#endif
    Inkscape::XML::Node *stop = parent->document()->createElement("svg:stop");
    {
        gchar *tmp = g_strdup_printf( "stop-color:%s;stop-opacity:%d;", color.c_str(), opacity );
        stop->setAttribute( "style", tmp );
        g_free(tmp);
    }

    stop->setAttribute( "offset", offset );

    parent->appendChild(stop);
    Inkscape::GC::release(stop);
}

/*
 * Get default normalized gradient vector of document, create if there is none
 */
SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor const &color, bool singleStop )
{
    SPDefs *defs = document->getDefs();
    Inkscape::XML::Document *xml_doc = document->rdoc;

    Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient");

    if ( !singleStop ) {
        repr->setAttribute("inkscape:collect", "always");
        // set here, but removed when it's edited in the gradient editor
        // to further reduce clutter, we could
        // (1) here, search gradients by color and return what is found without duplication
        // (2) in fill & stroke, show only one copy of each gradient in list
    }

    Glib::ustring colorStr = color.toString();
    addStop( repr, colorStr, 1, "0" );
    if ( !singleStop ) {
        addStop( repr, colorStr, 0, "1" );
    }

    defs->getRepr()->addChild(repr, NULL);
    Inkscape::GC::release(repr);

    /* fixme: This does not look like nice */
    SPGradient *gr = static_cast<SPGradient *>(document->getObjectByRepr(repr));
    g_assert(gr != NULL);
    g_assert(SP_IS_GRADIENT(gr));
    /* fixme: Maybe add extra sanity check here */
    gr->state = SP_GRADIENT_STATE_VECTOR;

    return gr;
}

/**
Return the preferred vector for \a o, made from (in order of preference) its current vector,
current fill or stroke color, or from desktop style if \a o is NULL or doesn't have style.
*/
SPGradient *sp_gradient_vector_for_object( SPDocument *const doc, SPDesktop *const desktop,
                                           SPObject *const o, bool const is_fill, bool singleStop )
{
    SPColor color;
    if ( (o == NULL) || (o->style == NULL) ) {
        color = sp_desktop_get_color(desktop, is_fill);
    } else {
        // take the color of the object
        SPStyle const &style = *(o->style);
        SPIPaint const &paint = ( is_fill
                                  ? style.fill
                                  : style.stroke );
        if (paint.isPaintserver()) {
            SPObject *server = is_fill? o->style->getFillPaintServer() : o->style->getStrokePaintServer();
            if ( SP_IS_GRADIENT(server) ) {
                return SP_GRADIENT(server)->getVector(true);
            } else {
                color = sp_desktop_get_color(desktop, is_fill);
            }
        } else if (paint.isColor()) {
            color = paint.value.color;
        } else {
            // if o doesn't use flat color, then take current color of the desktop.
            color = sp_desktop_get_color(desktop, is_fill);
        }
    }

    return sp_document_default_gradient_vector( doc, color, singleStop );
}


/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :