summaryrefslogtreecommitdiffstats
path: root/src/filter-chemistry.cpp
blob: e5dc50d6d18c3648713cc27d2614d6610adb5719 (plain)
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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Various utility methods for filters
 *
 * Authors:
 *   Hugo Rodrigues
 *   bulia byak
 *   Niko Kiirala
 *   Jon A. Cruz <jon@joncruz.org>
 *   Abhishek Sharma
 *
 * Copyright (C) 2006-2008 authors
 *
 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
 */

#include "filter-chemistry.h"

#include <cstring>
#include <glibmm.h>

#include "desktop-style.h"
#include "document.h"
#include "filter-enums.h"
#include "style.h"

#include "object/sp-defs.h"
#include "object/sp-item.h"

#include "object/filters/blend.h"
#include "object/filters/gaussian-blur.h"

/**
 * Count how many times the filter is used by the styles of o and its
 * descendants
 */
static guint count_filter_hrefs(SPObject *o, SPFilter *filter)
{
    if (!o)
        return 1;

    guint i = 0;

    SPStyle *style = o->style;
    if (style
        && style->filter.set
        && style->getFilter() == filter)
    {
        i ++;
    }

    for (auto& child: o->children) {
        i += count_filter_hrefs(&child, filter);
    }

    return i;
}

SPFilter *new_filter(SPDocument *document)
{
    g_return_val_if_fail(document != nullptr, NULL);

    SPDefs *defs = document->getDefs();

    Inkscape::XML::Document *xml_doc = document->getReprDoc();

    // create a new filter
    Inkscape::XML::Node *repr;
    repr = xml_doc->createElement("svg:filter");

    // Inkscape now supports both sRGB and linear color-interpolation-filters.
    // But, for the moment, keep sRGB as default value for new filters
    // (historically set to sRGB and doesn't require conversion between
    // filter cairo surfaces and other types of cairo surfaces).
    SPCSSAttr *css = sp_repr_css_attr_new();
    sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB");
    sp_repr_css_change(repr, css, "style");
    sp_repr_css_attr_unref(css);

    // Append the new filter node to defs
    defs->appendChild(repr);
    Inkscape::GC::release(repr);

    // get corresponding object
    SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) );
    
    
    g_assert(f != nullptr);
    g_assert(SP_IS_FILTER(f));

    return f;
}

SPFilterPrimitive *
filter_add_primitive(SPFilter *filter, const Inkscape::Filters::FilterPrimitiveType type)
{
    Inkscape::XML::Document *xml_doc = filter->document->getReprDoc();

    //create filter primitive node
    Inkscape::XML::Node *repr;
    repr = xml_doc->createElement(FPConverter.get_key(type).c_str());

    // set default values
    switch(type) {
        case Inkscape::Filters::NR_FILTER_BLEND:
            repr->setAttribute("mode", "normal");
            break;
        case Inkscape::Filters::NR_FILTER_COLORMATRIX:
            break;
        case Inkscape::Filters::NR_FILTER_COMPONENTTRANSFER:
            break;
        case Inkscape::Filters::NR_FILTER_COMPOSITE:
            break;
        case Inkscape::Filters::NR_FILTER_CONVOLVEMATRIX:
            repr->setAttribute("order", "3 3");
            repr->setAttribute("kernelMatrix", "0 0 0 0 0 0 0 0 0");
            break;
        case Inkscape::Filters::NR_FILTER_DIFFUSELIGHTING:
            break;
        case Inkscape::Filters::NR_FILTER_DISPLACEMENTMAP:
            break;
        case Inkscape::Filters::NR_FILTER_FLOOD:
            break;
        case Inkscape::Filters::NR_FILTER_GAUSSIANBLUR:
            repr->setAttribute("stdDeviation", "1");
            break;
        case Inkscape::Filters::NR_FILTER_IMAGE:
            break;
        case Inkscape::Filters::NR_FILTER_MERGE:
            break;
        case Inkscape::Filters::NR_FILTER_MORPHOLOGY:
            break;
        case Inkscape::Filters::NR_FILTER_OFFSET:
            repr->setAttribute("dx", "0");
            repr->setAttribute("dy", "0");
            break;
        case Inkscape::Filters::NR_FILTER_SPECULARLIGHTING:
            break;
        case Inkscape::Filters::NR_FILTER_TILE:
            break;
        case Inkscape::Filters::NR_FILTER_TURBULENCE:
            break;
        default:
            break;
    }

    //set primitive as child of filter node
    // XML tree being used directly while/where it shouldn't be...
    filter->appendChild(repr);
    Inkscape::GC::release(repr);
    
    // get corresponding object
    SPFilterPrimitive *prim = SP_FILTER_PRIMITIVE( filter->document->getObjectByRepr(repr) );
 
    g_assert(prim != nullptr);
    g_assert(SP_IS_FILTER_PRIMITIVE(prim));

    return prim;
}

/**
 * Creates a filter with blur primitive of specified radius for an item with the given matrix expansion, width and height
 */
SPFilter *
new_filter_gaussian_blur (SPDocument *document, gdouble radius, double expansion)
{
    g_return_val_if_fail(document != nullptr, NULL);

    SPDefs *defs = document->getDefs();

    Inkscape::XML::Document *xml_doc = document->getReprDoc();

    // create a new filter
    Inkscape::XML::Node *repr;
    repr = xml_doc->createElement("svg:filter");
    //repr->setAttribute("inkscape:collect", "always");


    /* Inkscape now supports both sRGB and linear color-interpolation-filters.  
     * But, for the moment, keep sRGB as default value for new filters.
     * historically set to sRGB and doesn't require conversion between
     * filter cairo surfaces and other types of cairo surfaces. lp:1127103 */
    SPCSSAttr *css = sp_repr_css_attr_new();                                    
    sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB");       
    sp_repr_css_change(repr, css, "style");                                     
    sp_repr_css_attr_unref(css);

    //create feGaussianBlur node
    Inkscape::XML::Node *b_repr;
    b_repr = xml_doc->createElement("svg:feGaussianBlur");
    //b_repr->setAttribute("inkscape:collect", "always");
    
    double stdDeviation = radius;
    if (expansion != 0)
        stdDeviation /= expansion;

    //set stdDeviation attribute
    b_repr->setAttributeSvgDouble("stdDeviation", stdDeviation);
    
    //set feGaussianBlur as child of filter node
    repr->appendChild(b_repr);
    Inkscape::GC::release(b_repr);
    
    // Append the new filter node to defs
    defs->appendChild(repr);
    Inkscape::GC::release(repr);

    // get corresponding object
    SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) );
    SPGaussianBlur *b = SP_GAUSSIANBLUR( document->getObjectByRepr(b_repr) );
    
    g_assert(f != nullptr);
    g_assert(SP_IS_FILTER(f));
    g_assert(b != nullptr);
    g_assert(SP_IS_GAUSSIANBLUR(b));

    return f;
}


/**
 * Creates a simple filter with a blend primitive and a blur primitive of specified radius for
 * an item with the given matrix expansion, width and height
 */
static SPFilter *
new_filter_blend_gaussian_blur (SPDocument *document, const char *blendmode, gdouble radius, double expansion)
{
    g_return_val_if_fail(document != nullptr, NULL);

    SPDefs *defs = document->getDefs();

    Inkscape::XML::Document *xml_doc = document->getReprDoc();

    // create a new filter
    Inkscape::XML::Node *repr;
    repr = xml_doc->createElement("svg:filter");
    repr->setAttribute("inkscape:collect", "always");

    /* Inkscape now supports both sRGB and linear color-interpolation-filters.  
     * But, for the moment, keep sRGB as default value for new filters. 
     * historically set to sRGB and doesn't require conversion between
     * filter cairo surfaces and other types of cairo surfaces. lp:1127103 */
    SPCSSAttr *css = sp_repr_css_attr_new();                                    
    sp_repr_css_set_property(css, "color-interpolation-filters", "sRGB");       
    sp_repr_css_change(repr, css, "style");                                     
    sp_repr_css_attr_unref(css);

    // Append the new filter node to defs
    defs->appendChild(repr);
    Inkscape::GC::release(repr);
 
    // get corresponding object
    SPFilter *f = SP_FILTER( document->getObjectByRepr(repr) );
    // Gaussian blur primitive
    if(radius != 0) {
        //create feGaussianBlur node
        Inkscape::XML::Node *b_repr;
        b_repr = xml_doc->createElement("svg:feGaussianBlur");
        b_repr->setAttribute("inkscape:collect", "always");
        
        double stdDeviation = radius;
        if (expansion != 0)
            stdDeviation /= expansion;
        
        //set stdDeviation attribute
        b_repr->setAttributeSvgDouble("stdDeviation", stdDeviation);
     
        //set feGaussianBlur as child of filter node
        repr->appendChild(b_repr);
        Inkscape::GC::release(b_repr);

        SPGaussianBlur *b = SP_GAUSSIANBLUR( document->getObjectByRepr(b_repr) );
        g_assert(b != nullptr);
        g_assert(SP_IS_GAUSSIANBLUR(b));
    }
    // Blend primitive
    if(strcmp(blendmode, "normal")) {
        Inkscape::XML::Node *b_repr;
        b_repr = xml_doc->createElement("svg:feBlend");
        b_repr->setAttribute("inkscape:collect", "always");
        b_repr->setAttribute("mode", blendmode);
        b_repr->setAttribute("in2", "BackgroundImage");

        // set feBlend as child of filter node
        repr->appendChild(b_repr);
        Inkscape::GC::release(b_repr);

        // Enable background image buffer for document
        Inkscape::XML::Node *root = b_repr->root();
        if (!root->attribute("enable-background")) {
            root->setAttribute("enable-background", "new");
        }

        SPFeBlend *b = SP_FEBLEND(document->getObjectByRepr(b_repr));
        g_assert(b != nullptr);
        g_assert(SP_IS_FEBLEND(b));
    }
    
    g_assert(f != nullptr);
    g_assert(SP_IS_FILTER(f));
 
    return f;
}

/**
 * Creates a simple filter for the given item with blend and blur primitives, using the
 * specified mode and radius, respectively
 */
SPFilter *
new_filter_simple_from_item (SPDocument *document, SPItem *item, const char *mode, gdouble radius)
{
    return new_filter_blend_gaussian_blur(document, mode, radius, item->i2dt_affine().descrim());
}

/**
 * Modifies the gaussian blur applied to the item.
 * If no filters are applied to given item, creates a new blur filter.
 * If a filter is applied and it contains a blur, modify that blur.
 * If the filter doesn't contain blur, a blur is added to the filter.
 * Should there be more references to modified filter, that filter is
 * duplicated, so that other elements referring that filter are not modified.
 */
/* TODO: this should be made more generic, not just for blurs */
SPFilter *modify_filter_gaussian_blur_from_item(SPDocument *document, SPItem *item,
                                                gdouble radius)
{
    if (!item->style || !item->style->filter.set) {
        return new_filter_simple_from_item(document, item, "normal", radius);
    }

    SPFilter *filter = item->style->getFilter();
    if (!filter) {
        // We reach here when filter.set is true, but the href is not found in the document
        return new_filter_simple_from_item(document, item, "normal", radius);
    }

    Inkscape::XML::Document *xml_doc = document->getReprDoc();

    // If there are more users for this filter, duplicate it
    if (filter->hrefcount > count_filter_hrefs(item, filter)) {
        Inkscape::XML::Node *repr = item->style->getFilter()->getRepr()->duplicate(xml_doc);
        SPDefs *defs = document->getDefs();
        defs->appendChild(repr);

        filter = SP_FILTER( document->getObjectByRepr(repr) );
        Inkscape::GC::release(repr);
    }

    // Determine the required standard deviation value
    Geom::Affine i2d (item->i2dt_affine ());
    double expansion = i2d.descrim();
    double stdDeviation = radius;
    if (expansion != 0)
        stdDeviation /= expansion;

    // Set the filter effects area
    SPFilter *f = item->style->getFilter();

    Inkscape::XML::Node *repr = f->getRepr();
    // Search for gaussian blur primitives. If found, set the stdDeviation
    // of the first one and return.
    Inkscape::XML::Node *primitive = repr->firstChild();
    while (primitive) {
        if (strcmp("svg:feGaussianBlur", primitive->name()) == 0) {
            primitive->setAttributeSvgDouble("stdDeviation", stdDeviation);
            return filter;
        }
        primitive = primitive->next();
    }

    // If there were no gaussian blur primitives, create a new one

    //create feGaussianBlur node
    Inkscape::XML::Node *b_repr;
    b_repr = xml_doc->createElement("svg:feGaussianBlur");
    //b_repr->setAttribute("inkscape:collect", "always");
    
    //set stdDeviation attribute
    b_repr->setAttributeSvgDouble("stdDeviation", stdDeviation);
    
    //set feGaussianBlur as child of filter node
    filter->getRepr()->appendChild(b_repr);
    Inkscape::GC::release(b_repr);

    return filter;
}

void remove_filter (SPObject *item, bool recursive)
{
    SPCSSAttr *css = sp_repr_css_attr_new();
    sp_repr_css_unset_property(css, "filter");
    if (recursive) {
        sp_repr_css_change_recursive(item->getRepr(), css, "style");
    } else {
        sp_repr_css_change(item->getRepr(), css, "style");
    }
    sp_repr_css_attr_unref(css);
}

void remove_hidder_filter (SPObject *item)
{
    SPFilter *filt = item->style->getFilter();
    if (filt && filt->getId()) {
        Glib::ustring filter = filt->getId();
        if (!filter.rfind("selectable_hidder_filter", 0)) {
            remove_filter(item, false);
        }
    }
}

bool has_hidder_filter(SPObject *item)
{
    SPFilter *filt = item->style->getFilter();
    if (filt && filt->getId()) {
        Glib::ustring filter = filt->getId();
        if (!filter.rfind("selectable_hidder_filter", 0)) {
            return true;
        }
    }
    return false;
}

/**
 * Removes the first feGaussianBlur from the filter attached to given item.
 * Should this leave us with an empty filter, remove that filter.
 */
/* TODO: the removed filter primitive may had had a named result image, so
 * after removing, the filter may be in erroneous state, this situation should
 * be handled gracefully */
void remove_filter_gaussian_blur (SPObject *item)
{
    if (item->style && item->style->filter.set && item->style->getFilter()) {
        // Search for the first blur primitive and remove it. (if found)
        Inkscape::XML::Node *repr = item->style->getFilter()->getRepr();
        Inkscape::XML::Node *primitive = repr->firstChild();
        while (primitive) {
            if (strcmp("svg:feGaussianBlur", primitive->name()) == 0) {
                sp_repr_unparent(primitive);
                break;
            }
            primitive = primitive->next();
        }

        // If there are no more primitives left in this filter, discard it.
        if (repr->childCount() == 0) {
            remove_filter(item, false);
        }
    }
}

/**
 * Removes blend primitive from the filter attached to given item.
 * Get if the filter have a < 1.0 blending filter and if it remove it
 * @params: the item to remove filtered blend
 */
/* TODO: the removed filter primitive may had had a named result image, so
 * after removing, the filter may be in erroneous state, this situation should
 * be handled gracefully */
void remove_filter_legacy_blend(SPObject *item)
{
    if (!item) {
        return;
    }
    if (item->style && item->style->filter.set && item->style->getFilter()) {
        // Search for the first blur primitive and remove it. (if found)
        size_t blurcount = 0;
        size_t blendcount = 0;
        size_t total = 0;
        // determine whether filter is simple (blend and/or blur) or complex
        SPFeBlend *blend = nullptr;
        for (auto &primitive_obj:item->style->getFilter()->children) {
            SPFilterPrimitive *primitive = dynamic_cast<SPFilterPrimitive *>(&primitive_obj);
            if (primitive) {
                if (dynamic_cast<SPFeBlend *>(primitive)) {
                    blend = dynamic_cast<SPFeBlend *>(primitive);
                    ++blendcount;
                }
                SPGaussianBlur *spgausian = dynamic_cast<SPGaussianBlur *>(primitive);
                if (spgausian) {
                    ++blurcount;
                }
                ++total;
            }
        }
        if (blend && total == 2 && blurcount == 1) {
            blend->deleteObject(true);
        } else if (total == 1 && blurcount != 1) {
            remove_filter(item, false);
        }
    }
}

/**
 * Get if the filter have a < 1.0 blending filter 
 * @params: the item to get filtered blend
 */
SPBlendMode filter_get_legacy_blend(SPObject *item)
{
    auto blend = SP_CSS_BLEND_NORMAL;
    if (!item) {
        return blend;
    }
    if (item->style && item->style->filter.set && item->style->getFilter()) {
        // Search for the first blur primitive and remove it. (if found)
        size_t blurcount = 0;
        size_t blendcount = 0;
        size_t total = 0;
        // determine whether filter is simple (blend and/or blur) or complex
        for (auto &primitive_obj:item->style->getFilter()->children) {
            SPFilterPrimitive *primitive = dynamic_cast<SPFilterPrimitive *>(&primitive_obj);
            if (primitive) {
                SPFeBlend *spblend = dynamic_cast<SPFeBlend *>(primitive);
                if (spblend) {
                    ++blendcount;
                    blend = spblend->blend_mode;
                }
                SPGaussianBlur *spgausian = dynamic_cast<SPGaussianBlur *>(primitive);
                if (spgausian) {
                    ++blurcount;
                }
                ++total;
            }
        }
        if (!((blend && total == 2 && blurcount == 1) || total == 1)) {
            blend = SP_CSS_BLEND_NORMAL;
        }
    }
    return blend;
}

bool filter_is_single_gaussian_blur(SPFilter *filter)
{
    return (filter->children.size() == 1 &&
            SP_IS_GAUSSIANBLUR(&filter->children.front()));
}

double get_single_gaussian_blur_radius(SPFilter *filter)
{
    if (filter->children.size() == 1 &&
        SP_IS_GAUSSIANBLUR(&filter->children.front())) {

        SPGaussianBlur *gb = SP_GAUSSIANBLUR(filter->firstChild());
        double x = gb->stdDeviation.getNumber();
        double y = gb->stdDeviation.getOptNumber();
        if (x > 0 && y > 0) {
            return MAX(x, y);
        }
        return x;
    }
    return 0.0;
}



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