~inkscape.dev/inkscape/trunk

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
/** \file
 * SPGradient, SPStop, SPLinearGradient, SPRadialGradient,
 * SPMeshGradient, SPMeshRow, SPMeshPatch
 */
/*
 * Authors:
 *   Lauris Kaplinski <lauris@kaplinski.com>
 *   bulia byak <buliabyak@users.sf.net>
 *   Jasper van de Gronde <th.v.d.gronde@hccnet.nl>
 *   Jon A. Cruz <jon@joncruz.org>
 *   Abhishek Sharma
 *   Tavmjong Bah <tavmjong@free.fr>
 *
 * Copyright (C) 1999-2002 Lauris Kaplinski
 * Copyright (C) 2000-2001 Ximian, Inc.
 * Copyright (C) 2004 David Turner
 * Copyright (C) 2009 Jasper van de Gronde
 * Copyright (C) 2011 Tavmjong Bah
 *
 * Released under GNU GPL, read the file 'COPYING' for more information
 *
 */

#define noSP_GRADIENT_VERBOSE
//#define OBJECT_TRACE

#include "sp-gradient.h"

#include <cstring>
#include <string>

#include <2geom/transforms.h>

#include <cairo.h>

#include <sigc++/functors/ptr_fun.h>
#include <sigc++/adaptors/bind.h>

#include "bad-uri-exception.h"
#include "display/cairo-utils.h"
#include "svg/svg.h"
#include "svg/css-ostringstream.h"
#include "attributes.h"
#include "document-private.h"
#include "gradient-chemistry.h"
#include "sp-gradient-reference.h"
#include "sp-linear-gradient.h"
#include "sp-radial-gradient.h"
#include "sp-mesh-gradient.h"
#include "sp-mesh-row.h"
#include "sp-mesh-patch.h"
#include "sp-stop.h"

/// Has to be power of 2   Seems to be unused.
//#define NCOLORS NR_GRADIENT_VECTOR_LENGTH

bool SPGradient::hasStops() const
{
    return has_stops;
}

bool SPGradient::hasPatches() const
{
    return has_patches;
}

bool SPGradient::isUnitsSet() const
{
    return units_set;
}

SPGradientUnits SPGradient::getUnits() const
{
    return units;
}

bool SPGradient::isSpreadSet() const
{
    return spread_set;
}

SPGradientSpread SPGradient::getSpread() const
{
    return spread;
}

void SPGradient::setSwatch( bool swatch )
{
    if ( swatch != isSwatch() ) {
        this->swatch = swatch; // to make isSolid() work, this happens first
        gchar const* paintVal = swatch ? (isSolid() ? "solid" : "gradient") : 0;
        setAttribute( "osb:paint", paintVal, 0 );

        requestModified( SP_OBJECT_MODIFIED_FLAG );
    }
}


/**
 * return true if this gradient is "equivalent" to that gradient.
 * Equivalent meaning they have the same stop count, same stop colors and same stop opacity
 * @param that - A gradient to compare this to
 */
bool SPGradient::isEquivalent(SPGradient *that)
{
    //TODO Make this work for mesh gradients

    bool status = false;
    
    while(1){ // not really a loop, used to avoid deep nesting or multiple exit points from function
        if (this->getStopCount() != that->getStopCount()) { break; }
        if (this->hasStops() != that->hasStops()) { break; }
        if (!this->getVector() || !that->getVector()) { break; }
        if (this->isSwatch() != that->isSwatch()) {  break; }
        if ( this->isSwatch() ){
           // drop down to check stops.
        }
        else if (
            (SP_IS_LINEARGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) ||
            (SP_IS_RADIALGRADIENT(this) && SP_IS_RADIALGRADIENT(that)) ||
            (SP_IS_MESHGRADIENT(this)   && SP_IS_MESHGRADIENT(that))) {
            if(!this->isAligned(that))break;
        }
        else { break; }  // this should never happen, some unhandled type of gradient

        SPStop *as = this->getVector()->getFirstStop();
        SPStop *bs = that->getVector()->getFirstStop();

        bool effective = true;
        while (effective && (as && bs)) {
            if (!as->getEffectiveColor().isClose(bs->getEffectiveColor(), 0.001) ||
                    as->offset != bs->offset || as->opacity != bs->opacity ) {
                effective = false;
                break;
            } 
            else {
                as = as->getNextStop();
                bs = bs->getNextStop();
            }
        }
        if (!effective) break;

        status = true;
        break;
    }
    return status;
}

/**
 * return true if this gradient is "aligned" to that gradient.
 * Aligned means that they have exactly the same coordinates and transform.
 * @param that - A gradient to compare this to
 */
bool SPGradient::isAligned(SPGradient *that)
{
    bool status = false;
    
   /*  Some gradients have coordinates/other values specified, some don't.  
           yes/yes check the coordinates/other values
           no/no   aligned (because both have all default values)
           yes/no  not aligned
           no/yes  not aligned
       It is NOT safe to just compare the computed values because if that field has
       not been set the computed value could be full of garbage.
       
       In theory the yes/no and no/yes cases could be aligned if the specified value
       matches the default value.
    */

    while(1){ // not really a loop, used to avoid deep nesting or multiple exit points from function
        if(this->gradientTransform_set != that->gradientTransform_set) { break; }
        if(this->gradientTransform_set && 
            (this->gradientTransform != that->gradientTransform)) { break; }
        if (SP_IS_LINEARGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) {
            SPLinearGradient *sg=SP_LINEARGRADIENT(this);
            SPLinearGradient *tg=SP_LINEARGRADIENT(that);
 
            if( sg->x1._set != tg->x1._set) { break; }
            if( sg->y1._set != tg->y1._set) { break; }
            if( sg->x2._set != tg->x2._set) { break; }
            if( sg->y2._set != tg->y2._set) { break; }
            if( sg->x1._set && sg->y1._set && sg->x2._set && sg->y2._set) {
                if( (sg->x1.computed != tg->x1.computed) ||
                    (sg->y1.computed != tg->y1.computed) ||
                    (sg->x2.computed != tg->x2.computed) ||
                    (sg->y2.computed != tg->y2.computed) )  { break; }
            } else if( sg->x1._set || sg->y1._set || sg->x2._set || sg->y2._set) { break; } // some mix of set and not set
            // none set? assume aligned and fall through
        } else if (SP_IS_RADIALGRADIENT(this) && SP_IS_LINEARGRADIENT(that)) {
            SPRadialGradient *sg=SP_RADIALGRADIENT(this);
            SPRadialGradient *tg=SP_RADIALGRADIENT(that);

            if( sg->cx._set != tg->cx._set) { break; }
            if( sg->cy._set != tg->cy._set) { break; }
            if( sg->r._set  != tg->r._set)  { break; }
            if( sg->fx._set != tg->fx._set) { break; }
            if( sg->fy._set != tg->fy._set) { break; }
            if( sg->cx._set && sg->cy._set && sg->fx._set && sg->fy._set && sg->r._set) {
                if( (sg->cx.computed != tg->cx.computed) ||
                    (sg->cy.computed != tg->cy.computed) ||
                    (sg->r.computed  != tg->r.computed ) ||
                    (sg->fx.computed != tg->fx.computed) ||
                    (sg->fy.computed != tg->fy.computed)  ) { break; }
            } else if(  sg->cx._set || sg->cy._set || sg->fx._set || sg->fy._set || sg->r._set ) { break; } // some mix of set and not set
            // none set? assume aligned and fall through
        } else if (SP_IS_MESHGRADIENT(this) && SP_IS_MESHGRADIENT(that)) {
            SPMeshGradient *sg=SP_MESHGRADIENT(this);
            SPMeshGradient *tg=SP_MESHGRADIENT(that);
 
            if( sg->x._set  !=  !tg->x._set) { break; }
            if( sg->y._set  !=  !tg->y._set) { break; }
            if( sg->x._set  &&  sg->y._set) { 
                if( (sg->x.computed != tg->x.computed) ||
                    (sg->y.computed != tg->y.computed) ) { break; }
            } else if( sg->x._set || sg->y._set) { break; } // some mix of set and not set
            // none set? assume aligned and fall through
         } else {
            break;
        }
        status = true;
        break;
    }
    return status;
}

/*
 * Gradient
 */
SPGradient::SPGradient() : SPPaintServer(), units(),
        spread(),
        ref(NULL),
        state(2),
        vector() {

    this->ref = new SPGradientReference(this);
    this->ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(SPGradient::gradientRefChanged), this));

    /** \todo
     * Fixme: reprs being rearranged (e.g. via the XML editor)
     * may require us to clear the state.
     */
    this->state = SP_GRADIENT_STATE_UNKNOWN;

    this->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
    this->units_set = FALSE;

    this->gradientTransform = Geom::identity();
    this->gradientTransform_set = FALSE;

    this->spread = SP_GRADIENT_SPREAD_PAD;
    this->spread_set = FALSE;

    this->has_stops = FALSE;
    this->has_patches = FALSE;

    this->vector.built = false;
    this->vector.stops.clear();
}

SPGradient::~SPGradient() {
}

/**
 * Virtual build: set gradient attributes from its associated repr.
 */
void SPGradient::build(SPDocument *document, Inkscape::XML::Node *repr)
{
    // Work-around in case a swatch had been marked for immediate collection:
    if ( repr->attribute("osb:paint") && repr->attribute("inkscape:collect") ) {
        repr->setAttribute("inkscape:collect", 0);
    }

    SPPaintServer::build(document, repr);

    for (auto& ochild: children) {
        if (SP_IS_STOP(&ochild)) {
            this->has_stops = TRUE;
            break;
        }
        if (SP_IS_MESHROW(&ochild)) {
            for (auto& ochild2: ochild.children) {
                if (SP_IS_MESHPATCH(&ochild2)) {
                    this->has_patches = TRUE;
                    break;
                }
            }
            if (this->has_patches == TRUE) {
                break;
            }
        }
    }

    this->readAttr( "gradientUnits" );
    this->readAttr( "gradientTransform" );
    this->readAttr( "spreadMethod" );
    this->readAttr( "xlink:href" );
    this->readAttr( "osb:paint" );

    // Register ourselves
    document->addResource("gradient", this);
}

/**
 * Virtual release of SPGradient members before destruction.
 */
void SPGradient::release()
{

#ifdef SP_GRADIENT_VERBOSE
    g_print("Releasing this %s\n", this->getId());
#endif

    if (this->document) {
        // Unregister ourselves
        this->document->removeResource("gradient", this);
    }

    if (this->ref) {
        this->modified_connection.disconnect();
        this->ref->detach();
        delete this->ref;
        this->ref = NULL;
    }

    //this->modified_connection.~connection();

    SPPaintServer::release();
}

/**
 * Set gradient attribute to value.
 */
void SPGradient::set(unsigned key, gchar const *value)
{
#ifdef OBJECT_TRACE
    std::stringstream temp;
    temp << "SPGradient::set: " << key  << " " << (value?value:"null");
    objectTrace( temp.str() );
#endif

    switch (key) {
        case SP_ATTR_GRADIENTUNITS:
            if (value) {
                if (!strcmp(value, "userSpaceOnUse")) {
                    this->units = SP_GRADIENT_UNITS_USERSPACEONUSE;
                } else {
                    this->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
                }

                this->units_set = TRUE;
            } else {
                this->units = SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX;
                this->units_set = FALSE;
            }

            this->requestModified(SP_OBJECT_MODIFIED_FLAG);
            break;

        case SP_ATTR_GRADIENTTRANSFORM: {
            Geom::Affine t;
            if (value && sp_svg_transform_read(value, &t)) {
                this->gradientTransform = t;
                this->gradientTransform_set = TRUE;
            } else {
                this->gradientTransform = Geom::identity();
                this->gradientTransform_set = FALSE;
            }

            this->requestModified(SP_OBJECT_MODIFIED_FLAG);
            break;
        }
        case SP_ATTR_SPREADMETHOD:
            if (value) {
                if (!strcmp(value, "reflect")) {
                    this->spread = SP_GRADIENT_SPREAD_REFLECT;
                } else if (!strcmp(value, "repeat")) {
                    this->spread = SP_GRADIENT_SPREAD_REPEAT;
                } else {
                    this->spread = SP_GRADIENT_SPREAD_PAD;
                }

                this->spread_set = TRUE;
            } else {
                this->spread_set = FALSE;
            }

            this->requestModified(SP_OBJECT_MODIFIED_FLAG);
            break;

        case SP_ATTR_XLINK_HREF:
            if (value) {
                try {
                    this->ref->attach(Inkscape::URI(value));
                } catch (Inkscape::BadURIException &e) {
                    g_warning("%s", e.what());
                    this->ref->detach();
                }
            } else {
                this->ref->detach();
            }
            break;

        case SP_ATTR_OSB_SWATCH:
        {
            bool newVal = (value != 0);
            bool modified = false;

            if (newVal != this->swatch) {
                this->swatch = newVal;
                modified = true;
            }

            if (newVal) {
                // Might need to flip solid/gradient
                Glib::ustring paintVal = ( this->hasStops() && (this->getStopCount() == 0) ) ? "solid" : "gradient";

                if ( paintVal != value ) {
                    this->setAttribute( "osb:paint", paintVal.c_str(), 0 );
                    modified = true;
                }
            }

            if (modified) {
                this->requestModified(SP_OBJECT_MODIFIED_FLAG);
            }
        }
            break;
        default:
            SPPaintServer::set(key, value);
            break;
    }

#ifdef OBJECT_TRACE
    objectTrace( "SPGradient::set", false );
#endif
}

/**
 * Gets called when the gradient is (re)attached to another gradient.
 */
void SPGradient::gradientRefChanged(SPObject *old_ref, SPObject *ref, SPGradient *gr)
{
    if (old_ref) {
        gr->modified_connection.disconnect();
    }
    if ( SP_IS_GRADIENT(ref)
         && ref != gr )
    {
        gr->modified_connection = ref->connectModified(sigc::bind<2>(sigc::ptr_fun(&SPGradient::gradientRefModified), gr));
    }

    // Per SVG, all unset attributes must be inherited from linked gradient.
    // So, as we're now (re)linked, we assign linkee's values to this gradient if they are not yet set -
    // but without setting the _set flags.
    // FIXME: do the same for gradientTransform too
    if (!gr->units_set) {
        gr->units = gr->fetchUnits();
    }
    if (!gr->spread_set) {
        gr->spread = gr->fetchSpread();
    }

    /// \todo Fixme: what should the flags (second) argument be? */
    gradientRefModified(ref, 0, gr);
}

/**
 * Callback for child_added event.
 */
void SPGradient::child_added(Inkscape::XML::Node *child, Inkscape::XML::Node *ref)
{
    this->invalidateVector();

    SPPaintServer::child_added(child, ref);

    SPObject *ochild = this->get_child_by_repr(child);
    if ( ochild && SP_IS_STOP(ochild) ) {
        this->has_stops = TRUE;
        if ( this->getStopCount() > 0 ) {
            gchar const * attr = this->getAttribute("osb:paint");
            if ( attr && strcmp(attr, "gradient") ) {
            	this->setAttribute( "osb:paint", "gradient", 0 );
            }
        }
    }
    if ( ochild && SP_IS_MESHROW(ochild) ) {
        this->has_patches = TRUE;
    }

    /// \todo Fixme: should we schedule "modified" here?
    this->requestModified(SP_OBJECT_MODIFIED_FLAG);
}

/**
 * Callback for remove_child event.
 */
void SPGradient::remove_child(Inkscape::XML::Node *child)
{
    this->invalidateVector();

    SPPaintServer::remove_child(child);

    this->has_stops = FALSE;
    this->has_patches = FALSE;
    for (auto& ochild: children) {
        if (SP_IS_STOP(&ochild)) {
            this->has_stops = TRUE;
            break;
        }
        if (SP_IS_MESHROW(&ochild)) {
            for (auto& ochild2: ochild.children) {
                if (SP_IS_MESHPATCH(&ochild2)) {
                    this->has_patches = TRUE;
                    break;
                }
            }
            if (this->has_patches == TRUE) {
                break;
            }
        }
    }

    if ( this->getStopCount() == 0 ) {
        gchar const * attr = this->getAttribute("osb:paint");

        if ( attr && strcmp(attr, "solid") ) {
            this->setAttribute( "osb:paint", "solid", 0 );
        }
    }

    /* Fixme: should we schedule "modified" here? */
    this->requestModified(SP_OBJECT_MODIFIED_FLAG);
}

/**
 * Callback for modified event.
 */
void SPGradient::modified(guint flags)
{
#ifdef OBJECT_TRACE
    objectTrace( "SPGradient::modified" );
#endif

    if (flags & SP_OBJECT_CHILD_MODIFIED_FLAG) {
        if (SP_IS_MESHGRADIENT(this)) {
            this->invalidateArray();
        } else {
            this->invalidateVector();
        }
    }

    if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) {
        if (SP_IS_MESHGRADIENT(this)) {
            this->ensureArray();
        } else {
            this->ensureVector();
        }
    }

    if (flags & SP_OBJECT_MODIFIED_FLAG) flags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
    flags &= SP_OBJECT_MODIFIED_CASCADE;

    // FIXME: climb up the ladder of hrefs
    GSList *l = NULL;

    for (auto& child: children) {
        sp_object_ref(&child);
        l = g_slist_prepend(l, &child);
    }

    l = g_slist_reverse(l);

    while (l) {
        SPObject *child = SP_OBJECT(l->data);
        l = g_slist_remove(l, child);

        if (flags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
            child->emitModified(flags);
        }

        sp_object_unref(child);
    }

#ifdef OBJECT_TRACE
    objectTrace( "SPGradient::modified", false );
#endif
}

SPStop* SPGradient::getFirstStop()
{
    SPStop* first = nullptr;
    for (auto& ochild: children) {
        if (SP_IS_STOP(&ochild)) {
            first = SP_STOP(&ochild);
            break;
        }
    }
    return first;
}

int SPGradient::getStopCount() const
{
    int count = 0;

    for (SPStop *stop = const_cast<SPGradient*>(this)->getFirstStop(); stop && stop->getNextStop(); stop = stop->getNextStop()) {
        count++;
    }

    return count;
}

/**
 * Write gradient attributes to repr.
 */
Inkscape::XML::Node *SPGradient::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
{
#ifdef OBJECT_TRACE
    objectTrace( "SPGradient::write" );
#endif

    SPPaintServer::write(xml_doc, repr, flags);

    if (flags & SP_OBJECT_WRITE_BUILD) {
        GSList *l = NULL;

        for (auto& child: children) {
            Inkscape::XML::Node *crepr = child.updateRepr(xml_doc, NULL, flags);

            if (crepr) {
                l = g_slist_prepend(l, crepr);
            }
        }

        while (l) {
            repr->addChild((Inkscape::XML::Node *) l->data, NULL);
            Inkscape::GC::release((Inkscape::XML::Node *) l->data);
            l = g_slist_remove(l, l->data);
        }
    }

    if (this->ref->getURI()) {
        gchar *uri_string = this->ref->getURI()->toString();
        repr->setAttribute("xlink:href", uri_string);
        g_free(uri_string);
    }

    if ((flags & SP_OBJECT_WRITE_ALL) || this->units_set) {
        switch (this->units) {
            case SP_GRADIENT_UNITS_USERSPACEONUSE:
                repr->setAttribute("gradientUnits", "userSpaceOnUse");
                break;
            default:
                repr->setAttribute("gradientUnits", "objectBoundingBox");
                break;
        }
    }

    if ((flags & SP_OBJECT_WRITE_ALL) || this->gradientTransform_set) {
        gchar *c=sp_svg_transform_write(this->gradientTransform);
        repr->setAttribute("gradientTransform", c);
        g_free(c);
    }

    if ((flags & SP_OBJECT_WRITE_ALL) || this->spread_set) {
        /* FIXME: Ensure that this->spread is the inherited value
         * if !this->spread_set.  Not currently happening: see SPGradient::modified.
         */
        switch (this->spread) {
            case SP_GRADIENT_SPREAD_REFLECT:
                repr->setAttribute("spreadMethod", "reflect");
                break;
            case SP_GRADIENT_SPREAD_REPEAT:
                repr->setAttribute("spreadMethod", "repeat");
                break;
            default:
                repr->setAttribute("spreadMethod", "pad");
                break;
        }
    }

    if ( (flags & SP_OBJECT_WRITE_EXT) && this->isSwatch() ) {
        if ( this->isSolid() ) {
            repr->setAttribute( "osb:paint", "solid" );
        } else {
            repr->setAttribute( "osb:paint", "gradient" );
        }
    } else {
        repr->setAttribute( "osb:paint", 0 );
    }

#ifdef OBJECT_TRACE
    objectTrace( "SPGradient::write", false );
#endif
    return repr;
}

/**
 * Forces the vector to be built, if not present (i.e., changed).
 *
 * \pre SP_IS_GRADIENT(gradient).
 */
void SPGradient::ensureVector()
{
    if ( !vector.built ) {
        rebuildVector();
    }
}

/**
 * Forces the array to be built, if not present (i.e., changed).
 *
 * \pre SP_IS_GRADIENT(gradient).
 */
void SPGradient::ensureArray()
{
    //std::cout << "SPGradient::ensureArray()" << std::endl;
    if ( !array.built ) {
        rebuildArray();
    }
}

/**
 * Set units property of gradient and emit modified.
 */
void SPGradient::setUnits(SPGradientUnits units)
{
    if (units != this->units) {
        this->units = units;
        units_set = TRUE;
        requestModified(SP_OBJECT_MODIFIED_FLAG);
    }
}

/**
 * Set spread property of gradient and emit modified.
 */
void SPGradient::setSpread(SPGradientSpread spread)
{
    if (spread != this->spread) {
        this->spread = spread;
        spread_set = TRUE;
        requestModified(SP_OBJECT_MODIFIED_FLAG);
    }
}

/**
 * Returns the first of {src, src-\>ref-\>getObject(),
 * src-\>ref-\>getObject()-\>ref-\>getObject(),...}
 * for which \a match is true, or NULL if none found.
 *
 * The raison d'être of this routine is that it correctly handles cycles in the href chain (e.g., if
 * a gradient gives itself as its href, or if each of two gradients gives the other as its href).
 *
 * \pre SP_IS_GRADIENT(src).
 */
static SPGradient *
chase_hrefs(SPGradient *const src, bool (*match)(SPGradient const *))
{
    g_return_val_if_fail(SP_IS_GRADIENT(src), NULL);

    /* Use a pair of pointers for detecting loops: p1 advances half as fast as p2.  If there is a
       loop, then once p1 has entered the loop, we'll detect it the next time the distance between
       p1 and p2 is a multiple of the loop size. */
    SPGradient *p1 = src, *p2 = src;
    bool do1 = false;
    for (;;) {
        if (match(p2)) {
            return p2;
        }

        p2 = p2->ref->getObject();
        if (!p2) {
            return p2;
        }
        if (do1) {
            p1 = p1->ref->getObject();
        }
        do1 = !do1;

        if ( p2 == p1 ) {
            /* We've been here before, so return NULL to indicate that no matching gradient found
             * in the chain. */
            return NULL;
        }
    }
}

/**
 * True if gradient has stops.
 */
static bool has_stopsFN(SPGradient const *gr)
{
    return gr->hasStops();
}

/**
 * True if gradient has patches (i.e. a mesh).
 */
static bool has_patchesFN(SPGradient const *gr)
{
    return gr->hasPatches();
}

/**
 * True if gradient has spread set.
 */
static bool has_spread_set(SPGradient const *gr)
{
    return gr->isSpreadSet();
}

/**
 * True if gradient has units set.
 */
static bool
has_units_set(SPGradient const *gr)
{
    return gr->isUnitsSet();
}


SPGradient *SPGradient::getVector(bool force_vector)
{
    SPGradient * src = chase_hrefs(this, has_stopsFN);
    if (src == NULL) {
        src = this;
    }

    if (force_vector) {
        src = sp_gradient_ensure_vector_normalized(src);
    }
    return src;
}

SPGradient *SPGradient::getArray(bool force_vector)
{
    SPGradient * src = chase_hrefs(this, has_patchesFN);
    if (src == NULL) {
        src = this;
    }
    return src;
}

/**
 * Returns the effective spread of given gradient (climbing up the refs chain if needed).
 *
 * \pre SP_IS_GRADIENT(gradient).
 */
SPGradientSpread SPGradient::fetchSpread()
{
    SPGradient const *src = chase_hrefs(this, has_spread_set);
    return ( src
             ? src->spread
             : SP_GRADIENT_SPREAD_PAD ); // pad is the default
}

/**
 * Returns the effective units of given gradient (climbing up the refs chain if needed).
 *
 * \pre SP_IS_GRADIENT(gradient).
 */
SPGradientUnits SPGradient::fetchUnits()
{
    SPGradient const *src = chase_hrefs(this, has_units_set);
    return ( src
             ? src->units
             : SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ); // bbox is the default
}


/**
 * Clears the gradient's svg:stop children from its repr.
 */
void
sp_gradient_repr_clear_vector(SPGradient *gr)
{
    Inkscape::XML::Node *repr = gr->getRepr();

    /* Collect stops from original repr */
    GSList *sl = NULL;
    for (Inkscape::XML::Node *child = repr->firstChild() ; child != NULL; child = child->next() ) {
        if (!strcmp(child->name(), "svg:stop")) {
            sl = g_slist_prepend(sl, child);
        }
    }
    /* Remove all stops */
    while (sl) {
        /** \todo
         * fixme: This should work, unless we make gradient
         * into generic group.
         */
        sp_repr_unparent((Inkscape::XML::Node *)sl->data);
        sl = g_slist_remove(sl, sl->data);
    }
}

/**
 * Writes the gradient's internal vector (whether from its own stops, or
 * inherited from refs) into the gradient repr as svg:stop elements.
 */
void
sp_gradient_repr_write_vector(SPGradient *gr)
{
    g_return_if_fail(gr != NULL);
    g_return_if_fail(SP_IS_GRADIENT(gr));

    Inkscape::XML::Document *xml_doc = gr->document->getReprDoc();
    Inkscape::XML::Node *repr = gr->getRepr();

    /* We have to be careful, as vector may be our own, so construct repr list at first */
    GSList *cl = NULL;

    for (guint i = 0; i < gr->vector.stops.size(); i++) {
        Inkscape::CSSOStringStream os;
        Inkscape::XML::Node *child = xml_doc->createElement("svg:stop");
        sp_repr_set_css_double(child, "offset", gr->vector.stops[i].offset);
        /* strictly speaking, offset an SVG <number> rather than a CSS one, but exponents make no
         * sense for offset proportions. */
        os << "stop-color:" << gr->vector.stops[i].color.toString() << ";stop-opacity:" << gr->vector.stops[i].opacity;
        child->setAttribute("style", os.str().c_str());
        /* Order will be reversed here */
        cl = g_slist_prepend(cl, child);
    }

    sp_gradient_repr_clear_vector(gr);

    /* And insert new children from list */
    while (cl) {
        Inkscape::XML::Node *child = static_cast<Inkscape::XML::Node *>(cl->data);
        repr->addChild(child, NULL);
        Inkscape::GC::release(child);
        cl = g_slist_remove(cl, child);
    }
}


void SPGradient::gradientRefModified(SPObject */*href*/, guint /*flags*/, SPGradient *gradient)
{
    if ( gradient->invalidateVector() ) {
        gradient->requestModified(SP_OBJECT_MODIFIED_FLAG);
        // Conditional to avoid causing infinite loop if there's a cycle in the href chain.
    }
}

/** Return true if change made. */
bool SPGradient::invalidateVector()
{
    bool ret = false;

    if (vector.built) {
        vector.built = false;
        vector.stops.clear();
        ret = true;
    }

    return ret;
}

/** Return true if change made. */
bool SPGradient::invalidateArray()
{
    bool ret = false;

    if (array.built) {
        array.built = false;
        // array.clear();
        ret = true;
    }

    return ret;
}

/** Creates normalized color vector */
void SPGradient::rebuildVector()
{
    gint len = 0;
    for (auto& child: children) {
        if (SP_IS_STOP(&child)) {
            len ++;
        }
    }

    has_stops = (len != 0);

    vector.stops.clear();

    SPGradient *reffed = ref ? ref->getObject() : NULL;
    if ( !hasStops() && reffed ) {
        /* Copy vector from referenced gradient */
        vector.built = true;   // Prevent infinite recursion.
        reffed->ensureVector();
        if (!reffed->vector.stops.empty()) {
            vector.built = reffed->vector.built;
            vector.stops.assign(reffed->vector.stops.begin(), reffed->vector.stops.end());
            return;
        }
    }

    for (auto& child: children) {
        if (SP_IS_STOP(&child)) {
            SPStop *stop = SP_STOP(&child);

            SPGradientStop gstop;
            if (!vector.stops.empty()) {
                // "Each gradient offset value is required to be equal to or greater than the
                // previous gradient stop's offset value. If a given gradient stop's offset
                // value is not equal to or greater than all previous offset values, then the
                // offset value is adjusted to be equal to the largest of all previous offset
                // values."
                gstop.offset = MAX(stop->offset, vector.stops.back().offset);
            } else {
                gstop.offset = stop->offset;
            }

            // "Gradient offset values less than 0 (or less than 0%) are rounded up to
            // 0%. Gradient offset values greater than 1 (or greater than 100%) are rounded
            // down to 100%."
            gstop.offset = CLAMP(gstop.offset, 0, 1);

            gstop.color = stop->getEffectiveColor();
            gstop.opacity = stop->opacity;

            vector.stops.push_back(gstop);
        }
    }

    // Normalize per section 13.2.4 of SVG 1.1.
    if (vector.stops.empty()) {
        /* "If no stops are defined, then painting shall occur as if 'none' were specified as the
         * paint style."
         */
        {
            SPGradientStop gstop;
            gstop.offset = 0.0;
            gstop.color.set( 0x00000000 );
            gstop.opacity = 0.0;
            vector.stops.push_back(gstop);
        }
        {
            SPGradientStop gstop;
            gstop.offset = 1.0;
            gstop.color.set( 0x00000000 );
            gstop.opacity = 0.0;
            vector.stops.push_back(gstop);
        }
    } else {
        /* "If one stop is defined, then paint with the solid color fill using the color defined
         * for that gradient stop."
         */
        if (vector.stops.front().offset > 0.0) {
            // If the first one is not at 0, then insert a copy of the first at 0.
            SPGradientStop gstop;
            gstop.offset = 0.0;
            gstop.color = vector.stops.front().color;
            gstop.opacity = vector.stops.front().opacity;
            vector.stops.insert(vector.stops.begin(), gstop);
        }
        if (vector.stops.back().offset < 1.0) {
            // If the last one is not at 1, then insert a copy of the last at 1.
            SPGradientStop gstop;
            gstop.offset = 1.0;
            gstop.color = vector.stops.back().color;
            gstop.opacity = vector.stops.back().opacity;
            vector.stops.push_back(gstop);
        }
    }

    vector.built = true;
}

/** Creates normalized color mesh patch array */
void SPGradient::rebuildArray()
{
    // std::cout << "SPGradient::rebuildArray()" << std::endl;

    if( !SP_IS_MESHGRADIENT(this) ) {
        g_warning( "SPGradient::rebuildArray() called for non-mesh gradient" );
        return;
    }

    array.read( SP_MESHGRADIENT( this ) );
    has_patches = array.patch_columns() > 0;
}

Geom::Affine
sp_gradient_get_g2d_matrix(SPGradient const *gr, Geom::Affine const &ctm, Geom::Rect const &bbox)
{
    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
        return ( Geom::Scale(bbox.dimensions())
                 * Geom::Translate(bbox.min())
                 * Geom::Affine(ctm) );
    } else {
        return ctm;
    }
}

Geom::Affine
sp_gradient_get_gs2d_matrix(SPGradient const *gr, Geom::Affine const &ctm, Geom::Rect const &bbox)
{
    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
        return ( gr->gradientTransform
                 * Geom::Scale(bbox.dimensions())
                 * Geom::Translate(bbox.min())
                 * Geom::Affine(ctm) );
    } else {
        return gr->gradientTransform * ctm;
    }
}

void
sp_gradient_set_gs2d_matrix(SPGradient *gr, Geom::Affine const &ctm,
                            Geom::Rect const &bbox, Geom::Affine const &gs2d)
{
    gr->gradientTransform = gs2d * ctm.inverse();
    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX ) {
        gr->gradientTransform = ( gr->gradientTransform
                                  * Geom::Translate(-bbox.min())
                                  * Geom::Scale(bbox.dimensions()).inverse() );
    }
    gr->gradientTransform_set = TRUE;

    gr->requestModified(SP_OBJECT_MODIFIED_FLAG);
}




/* CAIRO RENDERING STUFF */

void
sp_gradient_pattern_common_setup(cairo_pattern_t *cp,
                                 SPGradient *gr,
                                 Geom::OptRect const &bbox,
                                 double opacity)
{
    // set spread type
    switch (gr->getSpread()) {
    case SP_GRADIENT_SPREAD_REFLECT:
        cairo_pattern_set_extend(cp, CAIRO_EXTEND_REFLECT);
        break;
    case SP_GRADIENT_SPREAD_REPEAT:
        cairo_pattern_set_extend(cp, CAIRO_EXTEND_REPEAT);
        break;
    case SP_GRADIENT_SPREAD_PAD:
    default:
        cairo_pattern_set_extend(cp, CAIRO_EXTEND_PAD);
        break;
    }

    // add stops
    if (!SP_IS_MESHGRADIENT(gr)) {
        for (std::vector<SPGradientStop>::iterator i = gr->vector.stops.begin();
             i != gr->vector.stops.end(); ++i)
        {
            // multiply stop opacity by paint opacity
            cairo_pattern_add_color_stop_rgba(cp, i->offset,
                                              i->color.v.c[0], i->color.v.c[1], i->color.v.c[2], i->opacity * opacity);
        }
    }

    // set pattern transform matrix
    Geom::Affine gs2user = gr->gradientTransform;
    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX && bbox) {
        Geom::Affine bbox2user(bbox->width(), 0, 0, bbox->height(), bbox->left(), bbox->top());
        gs2user *= bbox2user;
    }
    ink_cairo_pattern_set_matrix(cp, gs2user.inverse());
}

cairo_pattern_t *
sp_gradient_create_preview_pattern(SPGradient *gr, double width)
{
    cairo_pattern_t *pat = NULL;

    if (!SP_IS_MESHGRADIENT(gr)) {
        gr->ensureVector();

        pat = cairo_pattern_create_linear(0, 0, width, 0);

        for (std::vector<SPGradientStop>::iterator i = gr->vector.stops.begin();
             i != gr->vector.stops.end(); ++i)
        {
            cairo_pattern_add_color_stop_rgba(pat, i->offset,
              i->color.v.c[0], i->color.v.c[1], i->color.v.c[2], i->opacity);
        }
    } else {

        // For the moment, use the top row of nodes for preview.
        unsigned columns = gr->array.patch_columns();

        double offset = 1.0/double(columns);

        pat = cairo_pattern_create_linear(0, 0, width, 0);

        for (unsigned i = 0; i < columns+1; ++i) {
            SPMeshNode* node = gr->array.node( 0, i*3 );
            cairo_pattern_add_color_stop_rgba(pat, i*offset,
              node->color.v.c[0], node->color.v.c[1], node->color.v.c[2], node->opacity);
        }
    }

    return pat;
}

/*
  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 :