gradient-chemistry.cpp 60.7 KB
Newer Older
MenTaLguY's avatar
MenTaLguY committed
1 2 3
/*
 * Various utility methods for gradients
 *
4
 * Authors:
MenTaLguY's avatar
MenTaLguY committed
5
 *   Lauris Kaplinski <[email protected]>
6
 *   bulia byak
7
 *   Johan Engelen <[email protected]>
8
 *   Jon A. Cruz <[email protected]>
9
 *   Abhishek Sharma
10
 *   Tavmjong Bah <[email protected]>
MenTaLguY's avatar
MenTaLguY committed
11
 *
12
 * Copyright (C) 2012 Tavmjong Bah
13
 * Copyright (C) 2010 Authors
14
 * Copyright (C) 2007 Johan Engelen
15
 * Copyright (C) 2001-2005 authors
MenTaLguY's avatar
MenTaLguY committed
16 17 18 19 20
 * Copyright (C) 2001 Ximian, Inc.
 *
 * Released under GNU GPL, read the file 'COPYING' for more information
 */

21 22
#include "widgets/gradient-vector.h"

Krzysztof Kosiński's avatar
Krzysztof Kosiński committed
23 24
#include <2geom/transforms.h>
#include <2geom/bezier-curve.h>
25 26
#include <2geom/crossing.h>
#include <2geom/line.h>
MenTaLguY's avatar
MenTaLguY committed
27 28 29

#include "style.h"
#include "document-private.h"
30
#include "document-undo.h"
31
#include "desktop.h"
32
#include "desktop-style.h"
33

34
#include "ui/tools/tool-base.h"
35 36 37
#include "selection.h"
#include "verbs.h"
#include <glibmm/i18n.h>
38

39 40 41
#include "sp-gradient-reference.h"
#include "sp-linear-gradient.h"
#include "sp-radial-gradient.h"
42
#include "sp-mesh-gradient.h"
43
#include "sp-stop.h"
44
#include "gradient-drag.h"
45
#include "gradient-chemistry.h"
46

47
#include "sp-text.h"
48
#include "sp-tspan.h"
49
#include "svg/svg.h"
50
#include "svg/svg-color.h"
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
51
#include "svg/css-ostringstream.h"
52

53
#define noSP_GR_VERBOSE
MenTaLguY's avatar
MenTaLguY committed
54

55
using Inkscape::DocumentUndo;
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

namespace {

Inkscape::PaintTarget paintTargetItems[] = {Inkscape::FOR_FILL, Inkscape::FOR_STROKE};

std::vector<Inkscape::PaintTarget> vectorOfPaintTargets(paintTargetItems, paintTargetItems + (sizeof(paintTargetItems) / sizeof(paintTargetItems[0])));

} // namespace

namespace Inkscape {

std::vector<PaintTarget> const &allPaintTargets()
{
    return vectorOfPaintTargets;
}

} // namespace Inkscape

74
// Terminology:
Peter Moulder's avatar
Peter Moulder committed
75 76 77 78
//
// "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.
//
79 80 81 82 83 84 85 86
// "array" is a gradient that has mesh rows and patches. It may or may not have "x" and "y" attributes.
// An array does have spacial information so it cannot be normalized like a "vector".
//
// "shared" is either a "vector" or "array" that is shared between multiple objects.
//
// "private" is a gradient that is not shared. A private linear or radial gradient has no stops but
// has position coords (e.g. center, radius etc for a radial); it references a "vector" for the
// actual colors. A mesh may or may not reference an array. Each private is only used by one object.
Peter Moulder's avatar
Peter Moulder committed
87

88
static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *gr);
MenTaLguY's avatar
MenTaLguY committed
89

90
SPGradient *sp_gradient_ensure_vector_normalized(SPGradient *gr)
MenTaLguY's avatar
MenTaLguY committed
91
{
92 93 94
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_ensure_vector_normalized(%p)", gr);
#endif
Peter Moulder's avatar
Peter Moulder committed
95 96
    g_return_val_if_fail(gr != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
97
    g_return_val_if_fail(!SP_IS_MESHGRADIENT(gr), NULL);
Peter Moulder's avatar
Peter Moulder committed
98 99 100 101 102

    /* 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) {
Jon A. Cruz's avatar
Jon A. Cruz committed
103
        g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, gr->getId());
Peter Moulder's avatar
Peter Moulder committed
104 105 106
        return NULL;
    }

107
    /* First make sure we have vector directly defined (i.e. gr has its own stops) */
108
    if ( !gr->hasStops() ) {
109
        /* We do not have stops ourselves, so flatten stops as well */
110
        gr->ensureVector();
111
        g_assert(gr->vector.built);
112 113 114
        // this adds stops from gr->vector as children to gr
        sp_gradient_repr_write_vector (gr);
    }
Peter Moulder's avatar
Peter Moulder committed
115

116
    /* If gr hrefs some other gradient, remove the href */
117 118 119 120 121 122
    if (gr->ref){
        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);
        }
Peter Moulder's avatar
Peter Moulder committed
123
    }
124 125 126 127

    /* Everything is OK, set state flag */
    gr->state = SP_GRADIENT_STATE_VECTOR;
    return gr;
MenTaLguY's avatar
MenTaLguY committed
128 129
}

130
/**
131
 * Creates new private gradient for the given shared gradient.
MenTaLguY's avatar
MenTaLguY committed
132 133
 */

134
static SPGradient *sp_gradient_get_private_normalized(SPDocument *document, SPGradient *shared, SPGradientType type)
MenTaLguY's avatar
MenTaLguY committed
135
{
136
#ifdef SP_GR_VERBOSE
137
    g_message("sp_gradient_get_private_normalized(%p, %p, %d)", document, shared, type);
138 139
#endif

Peter Moulder's avatar
Peter Moulder committed
140
    g_return_val_if_fail(document != NULL, NULL);
141 142 143
    g_return_val_if_fail(shared != NULL, NULL);
    g_return_val_if_fail(SP_IS_GRADIENT(shared), NULL);
    g_return_val_if_fail(shared->hasStops() || shared->hasPatches(), NULL);
Peter Moulder's avatar
Peter Moulder committed
144

145
    SPDefs *defs = document->getDefs();
Peter Moulder's avatar
Peter Moulder committed
146

147
    Inkscape::XML::Document *xml_doc = document->getReprDoc();
Peter Moulder's avatar
Peter Moulder committed
148
    // create a new private gradient of the requested type
149
    Inkscape::XML::Node *repr;
Peter Moulder's avatar
Peter Moulder committed
150
    if (type == SP_GRADIENT_TYPE_LINEAR) {
151
        repr = xml_doc->createElement("svg:linearGradient");
152
    } else if(type == SP_GRADIENT_TYPE_RADIAL) {
153
        repr = xml_doc->createElement("svg:radialGradient");
154
    } else {
155
        repr = xml_doc->createElement("svg:meshgradient");
Peter Moulder's avatar
Peter Moulder committed
156 157 158
    }

    // privates are garbage-collectable
159
    repr->setAttribute("inkscape:collect", "always");
Peter Moulder's avatar
Peter Moulder committed
160

161 162
    // link to shared
    sp_gradient_repr_set_link(repr, shared);
Peter Moulder's avatar
Peter Moulder committed
163 164

    /* Append the new private gradient to defs */
165
    defs->getRepr()->appendChild(repr);
166
    Inkscape::GC::release(repr);
Peter Moulder's avatar
Peter Moulder committed
167 168

    // get corresponding object
Kris De Gussem's avatar
Kris De Gussem committed
169
    SPGradient *gr = static_cast<SPGradient *>(document->getObjectByRepr(repr));
Peter Moulder's avatar
Peter Moulder committed
170 171 172 173
    g_assert(gr != NULL);
    g_assert(SP_IS_GRADIENT(gr));

    return gr;
MenTaLguY's avatar
MenTaLguY committed
174 175
}

176
/**
177 178
Count how many times gr is used by the styles of o and its descendants
*/
179
static guint count_gradient_hrefs(SPObject *o, SPGradient *gr)
180
{
Peter Moulder's avatar
Peter Moulder committed
181 182 183 184 185
    if (!o)
        return 1;

    guint i = 0;

186
    SPStyle *style = o->style;
Peter Moulder's avatar
Peter Moulder committed
187
    if (style
Jon A. Cruz's avatar
Jon A. Cruz committed
188
        && style->fill.isPaintserver()
Peter Moulder's avatar
Peter Moulder committed
189 190 191 192 193 194
        && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style))
        && SP_GRADIENT(SP_STYLE_FILL_SERVER(style)) == gr)
    {
        i ++;
    }
    if (style
Jon A. Cruz's avatar
Jon A. Cruz committed
195
        && style->stroke.isPaintserver()
Peter Moulder's avatar
Peter Moulder committed
196 197 198 199 200 201
        && SP_IS_GRADIENT(SP_STYLE_STROKE_SERVER(style))
        && SP_GRADIENT(SP_STYLE_STROKE_SERVER(style)) == gr)
    {
        i ++;
    }

202
    for (auto& child: o->children) {
203
        i += count_gradient_hrefs(&child, gr);
Peter Moulder's avatar
Peter Moulder committed
204 205 206
    }

    return i;
207
}
208

209 210

/**
211
 * If gr has other users, create a new shared; also check if gr links to shared, relink if not
212
 */
213
static SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *shared,
214
                                                         SPGradientType type, SPObject *o)
MenTaLguY's avatar
MenTaLguY committed
215
{
216
#ifdef SP_GR_VERBOSE
217
    g_message("sp_gradient_fork_private_if_necessary(%p, %p, %d, %p)", gr, shared, type, o);
218
#endif
Peter Moulder's avatar
Peter Moulder committed
219
    g_return_val_if_fail(gr != NULL, NULL);
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
220
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
221

222 223 224 225
    // Orphaned gradient, no shared with stops or patches at the end of the line; this used to be
    // an assert
    if ( !shared || !(shared->hasStops() || shared->hasPatches()) ) {
        std::cerr << "sp_gradient_fork_private_if_necessary: Orphaned gradient" << std::endl;
226
        return (gr);
227
    }
Peter Moulder's avatar
Peter Moulder committed
228 229 230 231 232 233

    // 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)) {
234
        user = user->parent;
Peter Moulder's avatar
Peter Moulder committed
235 236 237 238
    }

    // Check the number of uses of the gradient within this object;
    // if we are private and there are no other users,
239 240 241 242 243
    if (!shared->isSwatch() && (gr->hrefcount <= count_gradient_hrefs(user, gr))) {
        // check shared
        if ( gr != shared && gr->ref->getObject() != shared ) {
            /* our href is not the shared, and shared is different from gr; relink */
            sp_gradient_repr_set_link(gr->getRepr(), shared);
Peter Moulder's avatar
Peter Moulder committed
244 245 246 247
        }
        return gr;
    }

248
    SPDocument *doc = gr->document;
249
    SPObject *defs = doc->getDefs();
Peter Moulder's avatar
Peter Moulder committed
250

251
    if ((gr->hasStops()) ||
252
        (gr->hasPatches()) ||
Peter Moulder's avatar
Peter Moulder committed
253
        (gr->state != SP_GRADIENT_STATE_UNKNOWN) ||
254
        (gr->parent != SP_OBJECT(defs)) ||
255
        (gr->hrefcount > 1)) {
256 257

        // we have to clone a fresh new private gradient for the given shared
Peter Moulder's avatar
Peter Moulder committed
258 259

        // create an empty one
260
        SPGradient *gr_new = sp_gradient_get_private_normalized(doc, shared, type);
Peter Moulder's avatar
Peter Moulder committed
261 262

        // copy all the attributes to it
263 264
        Inkscape::XML::Node *repr_new = gr_new->getRepr();
        Inkscape::XML::Node *repr = gr->getRepr();
265 266
        repr_new->setAttribute("gradientUnits", repr->attribute("gradientUnits"));
        repr_new->setAttribute("gradientTransform", repr->attribute("gradientTransform"));
Peter Moulder's avatar
Peter Moulder committed
267
        if (SP_IS_RADIALGRADIENT(gr)) {
268 269 270 271
            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"));
272 273 274
            repr_new->setAttribute("r",  repr->attribute("r" ));
            repr_new->setAttribute("fr", repr->attribute("fr"));
            repr_new->setAttribute("spreadMethod", repr->attribute("spreadMethod"));
275
        } else if (SP_IS_LINEARGRADIENT(gr)) {
276 277 278 279
            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"));
280 281 282 283 284 285 286 287 288 289 290 291 292 293
            repr_new->setAttribute("spreadMethod", repr->attribute("spreadMethod"));
        } else { // Mesh
            repr_new->setAttribute("x", repr->attribute("x"));
            repr_new->setAttribute("y", repr->attribute("y"));
            repr_new->setAttribute("type", repr->attribute("type"));

            // We probably want a completely separate mesh gradient so
            // copy the children and unset the link to the shared.
            for ( Inkscape::XML::Node *child = repr->firstChild() ; child ; child = child->next() ) {
                Inkscape::XML::Node *copy = child->duplicate(doc->getReprDoc());
                repr_new->appendChild( copy );
                Inkscape::GC::release( copy );
            }
            sp_gradient_repr_set_link(repr_new, NULL);
Peter Moulder's avatar
Peter Moulder committed
294 295 296 297 298
        }
        return gr_new;
    } else {
        return gr;
    }
MenTaLguY's avatar
MenTaLguY committed
299 300
}

301
SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr)
302
{
303 304 305
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_fork_vector_if_necessary(%p)", gr);
#endif
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
306
    // Some people actually prefer their gradient vectors to be shared...
Ted Gould's avatar
Ted Gould committed
307 308
    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
    if (!prefs->getBool("/options/forkgradientvectors/value", true))
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
309 310
        return gr;

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

315
        Inkscape::XML::Node *repr = gr->getRepr()->duplicate(xml_doc);
316
        doc->getDefs()->getRepr()->addChild(repr, NULL);
Kris De Gussem's avatar
Kris De Gussem committed
317
        SPGradient *gr_new = static_cast<SPGradient *>(doc->getObjectByRepr(repr));
318
        gr_new = sp_gradient_ensure_vector_normalized (gr_new);
319
        Inkscape::GC::release(repr);
320 321 322 323 324
        return gr_new;
    }
    return gr;
}

325 326 327
/**
 *  Obtain the vector from the gradient. A forked vector will be created and linked to this gradient if another gradient uses it.
 */
328
SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector)
329
{
330 331 332
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_get_forked_vector_if_necessary(%p, %d)", gradient, force_vector);
#endif
333
    SPGradient *vector = gradient->getVector(force_vector);
334 335
    vector = sp_gradient_fork_vector_if_necessary (vector);
    if ( gradient != vector && gradient->ref->getObject() != vector ) {
336
        sp_gradient_repr_set_link(gradient->getRepr(), vector);
337 338 339 340 341
    }
    return vector;
}


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

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

Ted Gould's avatar
Ted Gould committed
358
    if (!bbox)
359 360
        return gr;

Ted Gould's avatar
Ted Gould committed
361 362
    Geom::Coord const width = bbox->dimensions()[Geom::X];
    Geom::Coord const height = bbox->dimensions()[Geom::Y];
363

Ted Gould's avatar
Ted Gould committed
364
    Geom::Point const center = bbox->midpoint();
365 366

    if (SP_IS_RADIALGRADIENT(gr)) {
Ted Gould's avatar
Ted Gould committed
367 368 369 370
        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]);
371
        sp_repr_set_svg_double(repr, "r", width/2);
372 373

        // we want it to be elliptic, not circular
Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
374
        Geom::Affine squeeze = Geom::Translate (-center) *
375 376
            Geom::Scale(1, height/width) *
            Geom::Translate (center);
377 378 379

        gr->gradientTransform = squeeze;
        {
MenTaLguY's avatar
MenTaLguY committed
380
            gchar *c=sp_svg_transform_write(gr->gradientTransform);
381
            gr->getRepr()->setAttribute("gradientTransform", c);
MenTaLguY's avatar
MenTaLguY committed
382
            g_free(c);
383
        }
384
    } else if (SP_IS_LINEARGRADIENT(gr)) {
385 386 387 388 389 390 391 392 393 394 395

        // Assume horizontal gradient by default (as per SVG 1.1)
        Geom::Point pStart = center - Geom::Point(width/2, 0);
        Geom::Point pEnd = center + Geom::Point(width/2, 0);

        // Get the preferred gradient angle from prefs
        Inkscape::Preferences *prefs = Inkscape::Preferences::get();
        double angle = prefs->getDouble("/dialogs/gradienteditor/angle", 0.0);

        if (angle != 0.0) {

396
            Geom::Line grl(center, Geom::rad_from_deg(angle));
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
            Geom::LineSegment bbl1(bbox->corner(0), bbox->corner(1));
            Geom::LineSegment bbl2(bbox->corner(1), bbox->corner(2));
            Geom::LineSegment bbl3(bbox->corner(2), bbox->corner(3));
            Geom::LineSegment bbl4(bbox->corner(3), bbox->corner(0));

            // Find where our gradient line intersects the bounding box.
            if (intersection(bbl1, grl)) {
                pStart = bbl1.pointAt((*intersection(bbl1, grl)).ta);
                pEnd = bbl3.pointAt((*intersection(bbl3, grl)).ta);
                if (intersection(bbl1, grl.ray(grl.angle()))) {
                    std::swap(pStart, pEnd);
                }
            } else if (intersection(bbl2, grl)) {
                pStart = bbl2.pointAt((*intersection(bbl2, grl)).ta);
                pEnd = bbl4.pointAt((*intersection(bbl4, grl)).ta);
                if (intersection(bbl2, grl.ray(grl.angle()))) {
                    std::swap(pStart, pEnd);
                }
            }

        }

        sp_repr_set_svg_double(repr, "x1", pStart[Geom::X]);
        sp_repr_set_svg_double(repr, "y1", pStart[Geom::Y]);
        sp_repr_set_svg_double(repr, "x2", pEnd[Geom::X]);
        sp_repr_set_svg_double(repr, "y2", pEnd[Geom::Y]);

424 425 426 427 428 429
    } else {
        // Mesh
        // THIS IS BEING CALLED TWICE WHENEVER A NEW GRADIENT IS CREATED, WRITING HERE CAUSES PROBLEMS
        // IN SPMeshNodeArray::create()
        //sp_repr_set_svg_double(repr, "x", bbox->min()[Geom::X]);
        //sp_repr_set_svg_double(repr, "y", bbox->min()[Geom::Y]);
430 431

        // We don't create a shared array gradient.
432
        SPMeshGradient* mg = SP_MESHGRADIENT( gr );
433
        mg->array.create( mg, item, bbox );
434 435 436
    }

    // set the gradientUnits
437
    repr->setAttribute("gradientUnits", "userSpaceOnUse");
438 439 440 441

    return gr;
}

Dmitry Kirsanov's avatar
comment  
Dmitry Kirsanov committed
442
/**
Peter Moulder's avatar
Peter Moulder committed
443 444
 * Convert an item's gradient to userspace if necessary, also fork it if necessary.
 * @return The new gradient.
Dmitry Kirsanov's avatar
comment  
Dmitry Kirsanov committed
445
 */
446
SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *property)
447
{
448 449 450
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_convert_to_userspace(%p, %p, \"%s\")", gr, item, property);
#endif
Peter Moulder's avatar
Peter Moulder committed
451 452
    g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);

453 454 455 456
    if ( gr && gr->isSolid() ) {
        return gr;
    }

Peter Moulder's avatar
Peter Moulder committed
457
    // First, fork it if it is shared
458 459 460 461 462 463 464
    if (SP_IS_LINEARGRADIENT(gr)) {
        gr = sp_gradient_fork_private_if_necessary(gr, gr->getVector(), SP_GRADIENT_TYPE_LINEAR, item);
    } else if (SP_IS_RADIALGRADIENT(gr)) {
        gr = sp_gradient_fork_private_if_necessary(gr, gr->getVector(), SP_GRADIENT_TYPE_RADIAL, item);
    } else {
        gr = sp_gradient_fork_private_if_necessary(gr, gr->getArray(),  SP_GRADIENT_TYPE_MESH,   item);
    }
Peter Moulder's avatar
Peter Moulder committed
465

466
    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
Peter Moulder's avatar
Peter Moulder committed
467

468
        Inkscape::XML::Node *repr = gr->getRepr();
Peter Moulder's avatar
Peter Moulder committed
469 470

        // calculate the bbox of the item
471
        item->document->ensureUpToDate();
Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
472
        Geom::Affine bbox2user;
473
        Geom::OptRect bbox = item->visualBounds(); // we need "true" bbox without item_i2d_affine
Ted Gould's avatar
Ted Gould committed
474
        if ( bbox ) {
Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
475
            bbox2user = Geom::Affine(bbox->dimensions()[Geom::X], 0,
Ted Gould's avatar
Ted Gould committed
476 477
                                   0, bbox->dimensions()[Geom::Y],
                                   bbox->min()[Geom::X], bbox->min()[Geom::Y]);
MenTaLguY's avatar
MenTaLguY committed
478 479
        } else {
            // would be degenerate otherwise
Ted Gould's avatar
Ted Gould committed
480
            bbox2user = Geom::identity();
MenTaLguY's avatar
MenTaLguY committed
481
        }
Peter Moulder's avatar
Peter Moulder committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

        /* 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.
         */
Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
497
        Geom::Affine skew = bbox2user;
Ted Gould's avatar
Ted Gould committed
498
        double exp = skew.descrim();
Peter Moulder's avatar
Peter Moulder committed
499 500 501 502 503 504 505 506 507 508
        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;
        {
MenTaLguY's avatar
MenTaLguY committed
509
            gchar *c=sp_svg_transform_write(gr->gradientTransform);
510
            gr->getRepr()->setAttribute("gradientTransform", c);
MenTaLguY's avatar
MenTaLguY committed
511
            g_free(c);
Peter Moulder's avatar
Peter Moulder committed
512 513 514 515
        }

        // 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
Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
516
        Geom::Affine point_convert = bbox2user * skew.inverse();
Peter Moulder's avatar
Peter Moulder committed
517

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        if (SP_IS_LINEARGRADIENT(gr)) {
            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");

        } else if (SP_IS_RADIALGRADIENT(gr)) {
Peter Moulder's avatar
Peter Moulder committed
536 537 538
            SPRadialGradient *rg = SP_RADIALGRADIENT(gr);

            // original points in the bbox coords
Ted Gould's avatar
Ted Gould committed
539 540
            Geom::Point c_b = Geom::Point(rg->cx.computed, rg->cy.computed);
            Geom::Point f_b = Geom::Point(rg->fx.computed, rg->fy.computed);
Peter Moulder's avatar
Peter Moulder committed
541 542 543
            double r_b = rg->r.computed;

            // converted points in userspace coords
Ted Gould's avatar
Ted Gould committed
544 545 546 547 548 549 550 551
            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]);
552
            sp_repr_set_svg_double(repr, "r", r_u);
Peter Moulder's avatar
Peter Moulder committed
553

554 555
            // set the gradientUnits
            repr->setAttribute("gradientUnits", "userSpaceOnUse");
Peter Moulder's avatar
Peter Moulder committed
556

557 558
        } else {
            std::cerr << "sp_gradient_convert_to_userspace: Conversion of mesh to userspace not implemented" << std::endl;
Peter Moulder's avatar
Peter Moulder committed
559 560 561 562 563 564 565 566
        }
    }

    // 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)
567 568 569 570 571
    if (SP_IS_TEXT(item)) {
        sp_style_set_property_url(item, property, gr, true);
    } else {
        sp_style_set_property_url(item, property, gr, false);
    }
Peter Moulder's avatar
Peter Moulder committed
572 573

    return gr;
MenTaLguY's avatar
MenTaLguY committed
574 575
}

Johan B. C. Engelen's avatar
Johan B. C. Engelen committed
576
void sp_gradient_transform_multiply(SPGradient *gradient, Geom::Affine postmul, bool set)
577
{
578 579 580
#ifdef SP_GR_VERBOSE
    g_message("sp_gradient_transform_multiply(%p, , %d)", gradient, set);
#endif
Peter Moulder's avatar
Peter Moulder committed
581 582 583 584 585 586 587
    if (set) {
        gradient->gradientTransform = postmul;
    } else {
        gradient->gradientTransform *= postmul; // fixme: get gradient transform by climbing to hrefs?
    }
    gradient->gradientTransform_set = TRUE;

MenTaLguY's avatar
MenTaLguY committed
588
    gchar *c=sp_svg_transform_write(gradient->gradientTransform);
589
    gradient->getRepr()->setAttribute("gradientTransform", c);
MenTaLguY's avatar
MenTaLguY committed
590
    g_free(c);
591 592
}

593
SPGradient *getGradient(SPItem *item, Inkscape::PaintTarget fill_or_stroke)
594
{
595 596
    SPStyle *style = item->style;
    SPGradient *gradient = 0;
597

598 599 600 601 602 603 604 605
    switch (fill_or_stroke)
    {
        case Inkscape::FOR_FILL:
            if (style && (style->fill.isPaintserver())) {
                SPPaintServer *server = item->style->getFillPaintServer();
                if ( SP_IS_GRADIENT(server) ) {
                    gradient = SP_GRADIENT(server);
                }
606
            }
607 608 609 610 611 612 613
            break;
        case Inkscape::FOR_STROKE:
            if (style && (style->stroke.isPaintserver())) {
                SPPaintServer *server = item->style->getStrokePaintServer();
                if ( SP_IS_GRADIENT(server) ) {
                    gradient = SP_GRADIENT(server);
                }
614
            }
615
            break;
616
    }
617

Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
618 619 620
   return gradient;
}

621
SPStop *sp_last_stop(SPGradient *gradient)
622
{
Jon A. Cruz's avatar
Jon A. Cruz committed
623 624
    for (SPStop *stop = gradient->getFirstStop(); stop != NULL; stop = stop->getNextStop()) {
        if (stop->getNextStop() == NULL)
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
625 626 627
            return stop;
    }
    return NULL;
628
}
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
629

630
SPStop *sp_get_stop_i(SPGradient *gradient, guint stop_i)
631
{
632
    SPStop *stop = gradient->getFirstStop();
633 634 635
    if (!stop) {
        return NULL;
    }
636

637
    // if this is valid but weird gradient without an offset-zero stop element,
638 639 640
    // 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)
Kris De Gussem's avatar
Kris De Gussem committed
641
    {
642
        stop_i--;
Kris De Gussem's avatar
Kris De Gussem committed
643 644
    }
    
Jon A. Cruz's avatar
Jon A. Cruz committed
645 646 647 648 649
    for (guint i = 0; i < stop_i; i++) {
        if (!stop) {
            return NULL;
        }
        stop = stop->getNextStop();
650 651
    }

Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
652
    return stop;
653 654
}

655
guint32 average_color(guint32 c1, guint32 c2, gdouble p)
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
656
{
657 658 659 660
    guint32 r = static_cast<guint32>(SP_RGBA32_R_U (c1) * (1 - p) + SP_RGBA32_R_U (c2) * p);
    guint32 g = static_cast<guint32>(SP_RGBA32_G_U (c1) * (1 - p) + SP_RGBA32_G_U (c2) * p);
    guint32 b = static_cast<guint32>(SP_RGBA32_B_U (c1) * (1 - p) + SP_RGBA32_B_U (c2) * p);
    guint32 a = static_cast<guint32>(SP_RGBA32_A_U (c1) * (1 - p) + SP_RGBA32_A_U (c2) * p);
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
661

662
    return SP_RGBA32_U_COMPOSE(r, g, b, a);
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
663 664
}

665
SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_stop, gfloat offset)
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
666
{
667 668 669 670
#ifdef SP_GR_VERBOSE
    g_message("sp_vector_add_stop(%p, %p, %p, %f)", vector, prev_stop, next_stop, offset);
#endif

Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
671
    Inkscape::XML::Node *new_stop_repr = NULL;
672 673
    new_stop_repr = prev_stop->getRepr()->duplicate(vector->getRepr()->document());
    vector->getRepr()->addChild(new_stop_repr, prev_stop->getRepr());
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
674

675
    SPStop *newstop = reinterpret_cast<SPStop *>(vector->document->getObjectByRepr(new_stop_repr));
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
676
    newstop->offset = offset;
677
    sp_repr_set_css_double( newstop->getRepr(), "offset", (double)offset);
Markus Engel's avatar
Markus Engel committed
678 679
    guint32 const c1 = prev_stop->get_rgba32();
    guint32 const c2 = next_stop->get_rgba32();
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
680 681 682 683 684 685
    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 <<";";
686
    newstop->getRepr()->setAttribute("style", os.str().c_str());
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
687 688 689 690
    Inkscape::GC::release(new_stop_repr);

    return newstop;
}
691

692
void sp_item_gradient_edit_stop(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke)
693
{
694
    SPGradient *gradient = getGradient(item, fill_or_stroke);
695

696
    if (!gradient || !SP_IS_GRADIENT(gradient)) {
697
        return;
698
    }
699

700
    SPGradient *vector = gradient->getVector();
701 702
    switch (point_type) {
        case POINT_LG_BEGIN:
703 704 705
        case POINT_RG_CENTER:
        case POINT_RG_FOCUS:
        {
706
            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, vector->getFirstStop());
707 708 709 710
            gtk_widget_show (dialog);
        }
        break;

711
        case POINT_LG_END:
712 713 714 715 716 717 718
        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;
719

720 721 722 723 724 725 726 727
        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;
728
        default:
729
            g_warning( "Unhandled gradient handle" );
730 731 732 733
            break;
    }
}

734
guint32 sp_item_gradient_stop_query_style(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke)
735
{
736
    SPGradient *gradient = getGradient(item, fill_or_stroke);
737

738
    if (!gradient || !SP_IS_GRADIENT(gradient)) {
739
        return 0;
740
    }
741

742
    if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient) ) {
743

744
        SPGradient *vector = gradient->getVector();
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
745

746 747 748 749 750 751 752 753 754 755
        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) {
Markus Engel's avatar
Markus Engel committed
756
                    return first->get_rgba32();
757
                }
758
            }
759
            break;
760

761 762 763 764 765 766
            case POINT_LG_END:
            case POINT_RG_R1:
            case POINT_RG_R2:
            {
                SPStop *last = sp_last_stop (vector);
                if (last) {
Markus Engel's avatar
Markus Engel committed
767
                    return last->get_rgba32();
768
                }
769
            }
770
            break;
771

772 773 774 775 776 777
            case POINT_LG_MID:
            case POINT_RG_MID1:
            case POINT_RG_MID2:
            {
                SPStop *stopi = sp_get_stop_i (vector, point_i);
                if (stopi) {
Markus Engel's avatar
Markus Engel committed
778
                    return stopi->get_rgba32();
779
                }
780
            }
781 782 783 784 785
            break;

            default:
                g_warning( "Bad linear/radial gradient handle type" );
                break;
786
        }
787
        return 0;
788
    } else if (SP_IS_MESHGRADIENT(gradient)) {
789

790
        // Mesh gradient
791
        SPMeshGradient *mg = SP_MESHGRADIENT(gradient);
792 793 794

        switch (point_type) {
            case POINT_MG_CORNER: {
795 796 797
                if (point_i >= mg->array.corners.size()) {
                    return 0;
                }
798 799 800 801 802 803 804 805 806
                SPMeshNode const* cornerpoint = mg->array.corners[ point_i ];

                if (cornerpoint) {
                    SPColor color  = cornerpoint->color;
                    double opacity = cornerpoint->opacity;
                    return  color.toRGBA32( opacity );
                } else {
                    return 0;
                }
807 808 809 810 811 812 813 814 815 816 817 818 819 820
                break;
            }

            case POINT_MG_HANDLE:
            case POINT_MG_TENSOR:
            {
                // Do nothing. Handles and tensors don't have color
                break;
            }

            default:
                g_warning( "Bad mesh handle type" );
        }
        return 0;
821
    }
822 823

    return 0;
824 825
}

826
void sp_item_gradient_stop_set_style(SPItem *item, GrPointType point_type, guint point_i, Inkscape::PaintTarget fill_or_stroke, SPCSSAttr *stop)
827
{
828 829 830
#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
831
    SPGradient *gradient = getGradient(item, fill_or_stroke);
832 833 834 835

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

836
    if (SP_IS_LINEARGRADIENT(gradient) || SP_IS_RADIALGRADIENT(gradient) ) {
Dmitry Kirsanov's avatar
Dmitry Kirsanov committed
837

838
        SPGradient *vector = gradient->getVector();
839

840 841
        if (!vector) // orphan!
            return;
842

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