summaryrefslogtreecommitdiffstats
path: root/layout/svg/SVGFilterInstance.cpp
blob: 8bc2cd32bbf38d3b969dfa517bee28e8b09ab7cd (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Main header first:
#include "SVGFilterInstance.h"

// Keep others in (case-insensitive) order:
#include "gfxPlatform.h"
#include "gfxUtils.h"
#include "mozilla/ISVGDisplayableFrame.h"
#include "mozilla/SVGContentUtils.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/SVGUtils.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "mozilla/dom/SVGLengthBinding.h"
#include "mozilla/dom/SVGUnitTypesBinding.h"
#include "mozilla/dom/SVGFilterElement.h"
#include "SVGFilterFrame.h"
#include "FilterSupport.h"
#include "gfx2DGlue.h"

using namespace mozilla::dom;
using namespace mozilla::dom::SVGUnitTypes_Binding;
using namespace mozilla::gfx;

namespace mozilla {

SVGFilterInstance::SVGFilterInstance(
    const StyleFilter& aFilter, SVGFilterFrame* aFilterFrame,
    nsIContent* aTargetContent, const UserSpaceMetrics& aMetrics,
    const gfxRect& aTargetBBox,
    const MatrixScalesDouble& aUserSpaceToFilterSpaceScale)
    : mFilter(aFilter),
      mTargetContent(aTargetContent),
      mMetrics(aMetrics),
      mFilterFrame(aFilterFrame),
      mTargetBBox(aTargetBBox),
      mUserSpaceToFilterSpaceScale(aUserSpaceToFilterSpaceScale),
      mSourceAlphaAvailable(false),
      mInitialized(false) {
  // Get the filter element.
  mFilterElement = mFilterFrame->GetFilterContent();
  if (!mFilterElement) {
    MOZ_ASSERT_UNREACHABLE("filter frame should have a related element");
    return;
  }

  mPrimitiveUnits =
      mFilterFrame->GetEnumValue(SVGFilterElement::PRIMITIVEUNITS);

  if (!ComputeBounds()) {
    return;
  }

  mInitialized = true;
}

bool SVGFilterInstance::ComputeBounds() {
  // XXX if filterUnits is set (or has defaulted) to objectBoundingBox, we
  // should send a warning to the error console if the author has used lengths
  // with units. This is a common mistake and can result in the filter region
  // being *massive* below (because we ignore the units and interpret the number
  // as a factor of the bbox width/height). We should also send a warning if the
  // user uses a number without units (a future SVG spec should really
  // deprecate that, since it's too confusing for a bare number to be sometimes
  // interpreted as a fraction of the bounding box and sometimes as user-space
  // units). So really only percentage values should be used in this case.

  // Set the user space bounds (i.e. the filter region in user space).
  SVGAnimatedLength XYWH[4];
  static_assert(sizeof(mFilterElement->mLengthAttributes) == sizeof(XYWH),
                "XYWH size incorrect");
  memcpy(XYWH, mFilterElement->mLengthAttributes,
         sizeof(mFilterElement->mLengthAttributes));
  XYWH[0] = *mFilterFrame->GetLengthValue(SVGFilterElement::ATTR_X);
  XYWH[1] = *mFilterFrame->GetLengthValue(SVGFilterElement::ATTR_Y);
  XYWH[2] = *mFilterFrame->GetLengthValue(SVGFilterElement::ATTR_WIDTH);
  XYWH[3] = *mFilterFrame->GetLengthValue(SVGFilterElement::ATTR_HEIGHT);
  uint16_t filterUnits =
      mFilterFrame->GetEnumValue(SVGFilterElement::FILTERUNITS);
  gfxRect userSpaceBounds =
      SVGUtils::GetRelativeRect(filterUnits, XYWH, mTargetBBox, mMetrics);

  // Transform the user space bounds to filter space, so we
  // can align them with the pixel boundaries of the offscreen surface.
  // The offscreen surface has the same scale as filter space.
  gfxRect filterSpaceBounds = UserSpaceToFilterSpace(userSpaceBounds);
  filterSpaceBounds.RoundOut();
  if (filterSpaceBounds.width <= 0 || filterSpaceBounds.height <= 0) {
    // 0 disables rendering, < 0 is error. dispatch error console warning
    // or error as appropriate.
    return false;
  }

  // Set the filter space bounds.
  if (!gfxUtils::GfxRectToIntRect(filterSpaceBounds, &mFilterSpaceBounds)) {
    // The filter region is way too big if there is float -> int overflow.
    return false;
  }

  return true;
}

float SVGFilterInstance::GetPrimitiveNumber(uint8_t aCtxType,
                                            float aValue) const {
  SVGAnimatedLength val;
  val.Init(aCtxType, 0xff, aValue, SVGLength_Binding::SVG_LENGTHTYPE_NUMBER);

  float value;
  if (mPrimitiveUnits == SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
    value = SVGUtils::ObjectSpace(mTargetBBox, &val);
  } else {
    value = SVGUtils::UserSpace(mMetrics, &val);
  }

  switch (aCtxType) {
    case SVGContentUtils::X:
      return value * static_cast<float>(mUserSpaceToFilterSpaceScale.xScale);
    case SVGContentUtils::Y:
      return value * static_cast<float>(mUserSpaceToFilterSpaceScale.yScale);
    case SVGContentUtils::XY:
    default:
      return value * SVGContentUtils::ComputeNormalizedHypotenuse(
                         mUserSpaceToFilterSpaceScale.xScale,
                         mUserSpaceToFilterSpaceScale.yScale);
  }
}

Point3D SVGFilterInstance::ConvertLocation(const Point3D& aPoint) const {
  SVGAnimatedLength val[4];
  val[0].Init(SVGContentUtils::X, 0xff, aPoint.x,
              SVGLength_Binding::SVG_LENGTHTYPE_NUMBER);
  val[1].Init(SVGContentUtils::Y, 0xff, aPoint.y,
              SVGLength_Binding::SVG_LENGTHTYPE_NUMBER);
  // Dummy width/height values
  val[2].Init(SVGContentUtils::X, 0xff, 0,
              SVGLength_Binding::SVG_LENGTHTYPE_NUMBER);
  val[3].Init(SVGContentUtils::Y, 0xff, 0,
              SVGLength_Binding::SVG_LENGTHTYPE_NUMBER);

  gfxRect feArea =
      SVGUtils::GetRelativeRect(mPrimitiveUnits, val, mTargetBBox, mMetrics);
  gfxRect r = UserSpaceToFilterSpace(feArea);
  return Point3D(r.x, r.y, GetPrimitiveNumber(SVGContentUtils::XY, aPoint.z));
}

gfxRect SVGFilterInstance::UserSpaceToFilterSpace(
    const gfxRect& aUserSpaceRect) const {
  gfxRect filterSpaceRect = aUserSpaceRect;
  filterSpaceRect.Scale(mUserSpaceToFilterSpaceScale);
  return filterSpaceRect;
}

IntRect SVGFilterInstance::ComputeFilterPrimitiveSubregion(
    SVGFilterPrimitiveElement* aFilterElement,
    const nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs,
    const nsTArray<int32_t>& aInputIndices) {
  SVGFilterPrimitiveElement* fE = aFilterElement;

  IntRect defaultFilterSubregion(0, 0, 0, 0);
  if (fE->SubregionIsUnionOfRegions()) {
    for (const auto& inputIndex : aInputIndices) {
      bool isStandardInput =
          inputIndex < 0 || inputIndex == mSourceGraphicIndex;
      IntRect inputSubregion =
          isStandardInput ? mFilterSpaceBounds
                          : aPrimitiveDescrs[inputIndex].PrimitiveSubregion();

      defaultFilterSubregion = defaultFilterSubregion.Union(inputSubregion);
    }
  } else {
    defaultFilterSubregion = mFilterSpaceBounds;
  }

  gfxRect feArea = SVGUtils::GetRelativeRect(
      mPrimitiveUnits,
      &fE->mLengthAttributes[SVGFilterPrimitiveElement::ATTR_X], mTargetBBox,
      mMetrics);
  Rect region = ToRect(UserSpaceToFilterSpace(feArea));

  if (!fE->mLengthAttributes[SVGFilterPrimitiveElement::ATTR_X]
           .IsExplicitlySet())
    region.x = defaultFilterSubregion.X();
  if (!fE->mLengthAttributes[SVGFilterPrimitiveElement::ATTR_Y]
           .IsExplicitlySet())
    region.y = defaultFilterSubregion.Y();
  if (!fE->mLengthAttributes[SVGFilterPrimitiveElement::ATTR_WIDTH]
           .IsExplicitlySet())
    region.width = defaultFilterSubregion.Width();
  if (!fE->mLengthAttributes[SVGFilterPrimitiveElement::ATTR_HEIGHT]
           .IsExplicitlySet())
    region.height = defaultFilterSubregion.Height();

  // We currently require filter primitive subregions to be pixel-aligned.
  // Following the spec, any pixel partially in the region is included
  // in the region.
  region.RoundOut();
  return RoundedToInt(region);
}

void SVGFilterInstance::GetInputsAreTainted(
    const nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs,
    const nsTArray<int32_t>& aInputIndices, bool aFilterInputIsTainted,
    nsTArray<bool>& aOutInputsAreTainted) {
  for (const auto& inputIndex : aInputIndices) {
    if (inputIndex < 0) {
      aOutInputsAreTainted.AppendElement(aFilterInputIsTainted);
    } else {
      aOutInputsAreTainted.AppendElement(
          aPrimitiveDescrs[inputIndex].IsTainted());
    }
  }
}

static int32_t GetLastResultIndex(
    const nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs) {
  uint32_t numPrimitiveDescrs = aPrimitiveDescrs.Length();
  return !numPrimitiveDescrs
             ? FilterPrimitiveDescription::kPrimitiveIndexSourceGraphic
             : numPrimitiveDescrs - 1;
}

int32_t SVGFilterInstance::GetOrCreateSourceAlphaIndex(
    nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs) {
  // If the SourceAlpha index has already been determined or created for this
  // SVG filter, just return it.
  if (mSourceAlphaAvailable) {
    return mSourceAlphaIndex;
  }

  // If this is the first filter in the chain, we can just use the
  // kPrimitiveIndexSourceAlpha keyword to refer to the SourceAlpha of the
  // original image.
  if (mSourceGraphicIndex < 0) {
    mSourceAlphaIndex = FilterPrimitiveDescription::kPrimitiveIndexSourceAlpha;
    mSourceAlphaAvailable = true;
    return mSourceAlphaIndex;
  }

  // Otherwise, create a primitive description to turn the previous filter's
  // output into a SourceAlpha input.
  FilterPrimitiveDescription descr(AsVariant(ToAlphaAttributes()));
  descr.SetInputPrimitive(0, mSourceGraphicIndex);

  const FilterPrimitiveDescription& sourcePrimitiveDescr =
      aPrimitiveDescrs[mSourceGraphicIndex];
  descr.SetPrimitiveSubregion(sourcePrimitiveDescr.PrimitiveSubregion());
  descr.SetIsTainted(sourcePrimitiveDescr.IsTainted());

  ColorSpace colorSpace = sourcePrimitiveDescr.OutputColorSpace();
  descr.SetInputColorSpace(0, colorSpace);
  descr.SetOutputColorSpace(colorSpace);

  aPrimitiveDescrs.AppendElement(std::move(descr));
  mSourceAlphaIndex = aPrimitiveDescrs.Length() - 1;
  mSourceAlphaAvailable = true;
  return mSourceAlphaIndex;
}

nsresult SVGFilterInstance::GetSourceIndices(
    SVGFilterPrimitiveElement* aPrimitiveElement,
    nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs,
    const nsTHashMap<nsStringHashKey, int32_t>& aImageTable,
    nsTArray<int32_t>& aSourceIndices) {
  AutoTArray<SVGStringInfo, 2> sources;
  aPrimitiveElement->GetSourceImageNames(sources);

  for (const auto& source : sources) {
    nsAutoString str;
    source.mString->GetAnimValue(str, source.mElement);

    int32_t sourceIndex = 0;
    if (str.EqualsLiteral("SourceGraphic")) {
      sourceIndex = mSourceGraphicIndex;
    } else if (str.EqualsLiteral("SourceAlpha")) {
      sourceIndex = GetOrCreateSourceAlphaIndex(aPrimitiveDescrs);
    } else if (str.EqualsLiteral("FillPaint")) {
      sourceIndex = FilterPrimitiveDescription::kPrimitiveIndexFillPaint;
    } else if (str.EqualsLiteral("StrokePaint")) {
      sourceIndex = FilterPrimitiveDescription::kPrimitiveIndexStrokePaint;
    } else if (str.EqualsLiteral("BackgroundImage") ||
               str.EqualsLiteral("BackgroundAlpha")) {
      return NS_ERROR_NOT_IMPLEMENTED;
    } else if (str.EqualsLiteral("")) {
      sourceIndex = GetLastResultIndex(aPrimitiveDescrs);
    } else {
      bool inputExists = aImageTable.Get(str, &sourceIndex);
      if (!inputExists) {
        sourceIndex = GetLastResultIndex(aPrimitiveDescrs);
      }
    }

    aSourceIndices.AppendElement(sourceIndex);
  }
  return NS_OK;
}

nsresult SVGFilterInstance::BuildPrimitives(
    nsTArray<FilterPrimitiveDescription>& aPrimitiveDescrs,
    nsTArray<RefPtr<SourceSurface>>& aInputImages, bool aInputIsTainted) {
  mSourceGraphicIndex = GetLastResultIndex(aPrimitiveDescrs);

  // Clip previous filter's output to this filter's filter region.
  if (mSourceGraphicIndex >= 0) {
    FilterPrimitiveDescription& sourceDescr =
        aPrimitiveDescrs[mSourceGraphicIndex];
    sourceDescr.SetPrimitiveSubregion(
        sourceDescr.PrimitiveSubregion().Intersect(mFilterSpaceBounds));
  }

  // Get the filter primitive elements.
  AutoTArray<RefPtr<SVGFilterPrimitiveElement>, 8> primitives;
  for (nsIContent* child = mFilterElement->nsINode::GetFirstChild(); child;
       child = child->GetNextSibling()) {
    if (auto* primitive = SVGFilterPrimitiveElement::FromNode(child)) {
      primitives.AppendElement(primitive);
    }
  }

  // Maps source image name to source index.
  nsTHashMap<nsStringHashKey, int32_t> imageTable(8);

  // The principal that we check principals of any loaded images against.
  nsCOMPtr<nsIPrincipal> principal = mTargetContent->NodePrincipal();

  for (uint32_t primitiveElementIndex = 0;
       primitiveElementIndex < primitives.Length(); ++primitiveElementIndex) {
    SVGFilterPrimitiveElement* filter = primitives[primitiveElementIndex];

    AutoTArray<int32_t, 2> sourceIndices;
    nsresult rv =
        GetSourceIndices(filter, aPrimitiveDescrs, imageTable, sourceIndices);
    if (NS_FAILED(rv)) {
      return rv;
    }

    IntRect primitiveSubregion = ComputeFilterPrimitiveSubregion(
        filter, aPrimitiveDescrs, sourceIndices);

    AutoTArray<bool, 8> sourcesAreTainted;
    GetInputsAreTainted(aPrimitiveDescrs, sourceIndices, aInputIsTainted,
                        sourcesAreTainted);

    FilterPrimitiveDescription descr = filter->GetPrimitiveDescription(
        this, primitiveSubregion, sourcesAreTainted, aInputImages);

    descr.SetIsTainted(filter->OutputIsTainted(sourcesAreTainted, principal));
    descr.SetFilterSpaceBounds(mFilterSpaceBounds);
    descr.SetPrimitiveSubregion(
        primitiveSubregion.Intersect(descr.FilterSpaceBounds()));

    for (uint32_t i = 0; i < sourceIndices.Length(); i++) {
      int32_t inputIndex = sourceIndices[i];
      descr.SetInputPrimitive(i, inputIndex);

      ColorSpace inputColorSpace =
          inputIndex >= 0 ? aPrimitiveDescrs[inputIndex].OutputColorSpace()
                          : ColorSpace(ColorSpace::SRGB);

      ColorSpace desiredInputColorSpace =
          filter->GetInputColorSpace(i, inputColorSpace);
      descr.SetInputColorSpace(i, desiredInputColorSpace);
      if (i == 0) {
        // the output color space is whatever in1 is if there is an in1
        descr.SetOutputColorSpace(desiredInputColorSpace);
      }
    }

    if (sourceIndices.Length() == 0) {
      descr.SetOutputColorSpace(filter->GetOutputColorSpace());
    }

    aPrimitiveDescrs.AppendElement(std::move(descr));
    uint32_t primitiveDescrIndex = aPrimitiveDescrs.Length() - 1;

    nsAutoString str;
    filter->GetResultImageName().GetAnimValue(str, filter);
    imageTable.InsertOrUpdate(str, primitiveDescrIndex);
  }

  return NS_OK;
}

}  // namespace mozilla