Bug 1858915 [wpt PR 42525] - Use taskcluster-run in infra tests, a=testonly
[gecko.git] / layout / svg / SVGUtils.h
blobf28879b796fa9709f6c5d0026b9b983d3a81c65d
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef LAYOUT_SVG_SVGUTILS_H_
8 #define LAYOUT_SVG_SVGUTILS_H_
10 // include math.h to pick up definition of M_ maths defines e.g. M_PI
11 #include <math.h>
13 #include "DrawMode.h"
14 #include "ImgDrawResult.h"
15 #include "gfx2DGlue.h"
16 #include "gfxMatrix.h"
17 #include "gfxPoint.h"
18 #include "gfxRect.h"
19 #include "mozilla/gfx/Rect.h"
20 #include "nsAlgorithm.h"
21 #include "nsChangeHint.h"
22 #include "nsColor.h"
23 #include "nsCOMPtr.h"
24 #include "nsID.h"
25 #include "nsIFrame.h"
26 #include "nsISupports.h"
27 #include "nsMathUtils.h"
28 #include "nsStyleStruct.h"
29 #include <algorithm>
31 class gfxContext;
32 class nsFrameList;
33 class nsIContent;
35 class nsPresContext;
36 class nsTextFrame;
38 struct nsStyleSVG;
39 struct nsRect;
41 namespace mozilla {
42 class SVGAnimatedEnumeration;
43 class SVGAnimatedLength;
44 class SVGContextPaint;
45 struct SVGContextPaintImpl;
46 class SVGDisplayContainerFrame;
47 class SVGGeometryFrame;
48 class SVGOuterSVGFrame;
49 namespace dom {
50 class Element;
51 class SVGElement;
52 class UserSpaceMetrics;
53 } // namespace dom
54 namespace gfx {
55 class DrawTarget;
56 class GeneralPattern;
57 } // namespace gfx
58 } // namespace mozilla
60 // maximum dimension of an offscreen surface - choose so that
61 // the surface size doesn't overflow a 32-bit signed int using
62 // 4 bytes per pixel; in line with Factory::CheckSurfaceSize
63 // In fact Macs can't even manage that
64 #define NS_SVG_OFFSCREEN_MAX_DIMENSION 4096
66 #define SVG_HIT_TEST_FILL 0x01
67 #define SVG_HIT_TEST_STROKE 0x02
69 bool NS_SVGNewGetBBoxEnabled();
71 namespace mozilla {
73 /**
74 * Sometimes we need to distinguish between an empty box and a box
75 * that contains an element that has no size e.g. a point at the origin.
77 class SVGBBox final {
78 using Rect = gfx::Rect;
80 public:
81 SVGBBox() : mIsEmpty(true) {}
83 MOZ_IMPLICIT SVGBBox(const Rect& aRect) : mBBox(aRect), mIsEmpty(false) {}
85 MOZ_IMPLICIT SVGBBox(const gfxRect& aRect)
86 : mBBox(ToRect(aRect)), mIsEmpty(false) {}
88 operator const Rect&() { return mBBox; }
90 gfxRect ToThebesRect() const { return ThebesRect(mBBox); }
92 bool IsEmpty() const { return mIsEmpty; }
94 bool IsFinite() const { return mBBox.IsFinite(); }
96 void Scale(float aScale) { mBBox.Scale(aScale); }
98 void UnionEdges(const SVGBBox& aSVGBBox) {
99 if (aSVGBBox.mIsEmpty) {
100 return;
102 mBBox = mIsEmpty ? aSVGBBox.mBBox : mBBox.UnionEdges(aSVGBBox.mBBox);
103 mIsEmpty = false;
106 void Intersect(const SVGBBox& aSVGBBox) {
107 if (!mIsEmpty && !aSVGBBox.mIsEmpty) {
108 mBBox = mBBox.Intersect(aSVGBBox.mBBox);
109 if (mBBox.IsEmpty()) {
110 mIsEmpty = true;
111 mBBox = Rect(0, 0, 0, 0);
113 } else {
114 mIsEmpty = true;
115 mBBox = Rect(0, 0, 0, 0);
119 private:
120 Rect mBBox;
121 bool mIsEmpty;
124 // GRRR WINDOWS HATE HATE HATE
125 #undef CLIP_MASK
127 class MOZ_RAII SVGAutoRenderState final {
128 using DrawTarget = gfx::DrawTarget;
130 public:
131 explicit SVGAutoRenderState(DrawTarget* aDrawTarget);
132 ~SVGAutoRenderState();
134 void SetPaintingToWindow(bool aPaintingToWindow);
136 static bool IsPaintingToWindow(DrawTarget* aDrawTarget);
138 private:
139 DrawTarget* mDrawTarget;
140 void* mOriginalRenderState;
141 bool mPaintingToWindow;
145 * General functions used by all of SVG layout and possibly content code.
146 * If a method is used by content and depends only on other content methods
147 * it should go in SVGContentUtils instead.
149 class SVGUtils final {
150 public:
151 using Element = dom::Element;
152 using SVGElement = dom::SVGElement;
153 using AntialiasMode = gfx::AntialiasMode;
154 using DrawTarget = gfx::DrawTarget;
155 using FillRule = gfx::FillRule;
156 using GeneralPattern = gfx::GeneralPattern;
157 using Size = gfx::Size;
158 using imgDrawingParams = image::imgDrawingParams;
160 NS_DECLARE_FRAME_PROPERTY_DELETABLE(ObjectBoundingBoxProperty, gfxRect)
163 * Returns the frame's post-filter ink overflow rect when passed the
164 * frame's pre-filter ink overflow rect. If the frame is not currently
165 * being filtered, this function simply returns aUnfilteredRect.
167 static nsRect GetPostFilterInkOverflowRect(nsIFrame* aFrame,
168 const nsRect& aPreFilterRect);
171 * Schedules an update of the frame's bounds (which will in turn invalidate
172 * the new area that the frame should paint to).
174 * This does nothing when passed an NS_FRAME_IS_NONDISPLAY frame.
175 * In future we may want to allow ReflowSVG to be called on such frames,
176 * but that would be better implemented as a ForceReflowSVG function to
177 * be called synchronously while painting them without marking or paying
178 * attention to dirty bits like this function.
180 * This is very similar to PresShell::FrameNeedsReflow. The main reason that
181 * we have this function instead of using FrameNeedsReflow is because we need
182 * to be able to call it under SVGOuterSVGFrame::NotifyViewportChange when
183 * that function is called by SVGOuterSVGFrame::Reflow. FrameNeedsReflow
184 * is not suitable for calling during reflow though, and it asserts as much.
185 * The reason that we want to be callable under NotifyViewportChange is
186 * because we want to synchronously notify and dirty the SVGOuterSVGFrame's
187 * children so that when SVGOuterSVGFrame::DidReflow is called its children
188 * will be updated for the new size as appropriate. Otherwise we'd have to
189 * post an event to the event loop to mark dirty flags and request an update.
191 * Another reason that we don't currently want to call
192 * PresShell::FrameNeedsReflow is because passing eRestyle to it to get it to
193 * mark descendants dirty would cause it to descend through
194 * SVGForeignObjectFrame frames to mark their children dirty, but we want to
195 * handle SVGForeignObjectFrame specially. It would also do unnecessary work
196 * descending into NS_FRAME_IS_NONDISPLAY frames.
198 static void ScheduleReflowSVG(nsIFrame* aFrame);
201 * Returns true if the frame or any of its children need ReflowSVG
202 * to be called on them.
204 static bool NeedsReflowSVG(const nsIFrame* aFrame);
207 * Percentage lengths in SVG are resolved against the width/height of the
208 * nearest viewport (or its viewBox, if set). This helper returns the size
209 * of this "context" for the given frame so that percentage values can be
210 * resolved.
212 static Size GetContextSize(const nsIFrame* aFrame);
214 /* Computes the input length in terms of object space coordinates.
215 Input: rect - bounding box
216 length - length to be converted
218 static float ObjectSpace(const gfxRect& aRect,
219 const SVGAnimatedLength* aLength);
221 /* Computes the input length in terms of user space coordinates.
222 Input: content - object to be used for determining user space
223 Input: length - length to be converted
225 static float UserSpace(nsIFrame* aNonSVGContext,
226 const SVGAnimatedLength* aLength);
227 static float UserSpace(const dom::UserSpaceMetrics& aMetrics,
228 const SVGAnimatedLength* aLength);
230 /* Find the outermost SVG frame of the passed frame */
231 static SVGOuterSVGFrame* GetOuterSVGFrame(nsIFrame* aFrame);
234 * Get the covered region for a frame. Return null if it's not an SVG frame.
235 * @param aRect gets a rectangle in app units
236 * @return the outer SVG frame which aRect is relative to
238 static nsIFrame* GetOuterSVGFrameAndCoveredRegion(nsIFrame* aFrame,
239 nsRect* aRect);
241 /* Paint SVG frame with SVG effects
243 static void PaintFrameWithEffects(nsIFrame* aFrame, gfxContext& aContext,
244 const gfxMatrix& aTransform,
245 imgDrawingParams& aImgParams);
247 /* Hit testing - check if point hits the clipPath of indicated
248 * frame. Returns true if no clipPath set. */
249 static bool HitTestClip(nsIFrame* aFrame, const gfxPoint& aPoint);
252 * Returns the CanvasTM of the indicated frame, whether it's a
253 * child SVG frame, container SVG frame, or a regular frame.
254 * For regular frames, we just return an identity matrix.
256 static gfxMatrix GetCanvasTM(nsIFrame* aFrame);
259 * Returns whether the frame is transformed and what those transforms are.
261 static bool IsSVGTransformed(const nsIFrame* aFrame,
262 gfx::Matrix* aOwnTransform,
263 gfx::Matrix* aFromParentTransform);
266 * Notify the descendants of aFrame of a change to one of their ancestors
267 * that might affect them.
269 static void NotifyChildrenOfSVGChange(nsIFrame* aFrame, uint32_t aFlags);
272 * Convert a surface size to an integer for use by thebes
273 * possibly making it smaller in the process so the surface does not
274 * use excessive memory.
276 * @param aSize the desired surface size
277 * @param aResultOverflows true if the desired surface size is too big
278 * @return the surface size to use
280 static gfx::IntSize ConvertToSurfaceSize(const gfxSize& aSize,
281 bool* aResultOverflows);
284 * Hit test a given rectangle/matrix.
286 static bool HitTestRect(const gfx::Matrix& aMatrix, float aRX, float aRY,
287 float aRWidth, float aRHeight, float aX, float aY);
290 * Get the clip rect for the given frame, taking into account the CSS 'clip'
291 * property. See:
292 * http://www.w3.org/TR/SVG11/masking.html#OverflowAndClipProperties
293 * The arguments for aX, aY, aWidth and aHeight should be the dimensions of
294 * the viewport established by aFrame.
296 static gfxRect GetClipRectForFrame(const nsIFrame* aFrame, float aX, float aY,
297 float aWidth, float aHeight);
299 /* Using group opacity instead of fill or stroke opacity on a
300 * geometry object seems to be a common authoring mistake. If we're
301 * not applying filters and not both stroking and filling, we can
302 * generate the same result without going through the overhead of a
303 * push/pop group. */
304 static bool CanOptimizeOpacity(const nsIFrame* aFrame);
307 * Take the CTM to userspace for an element, and adjust it to a CTM to its
308 * object bounding box space if aUnits is SVG_UNIT_TYPE_OBJECTBOUNDINGBOX.
309 * (I.e. so that [0,0] is at the top left of its bbox, and [1,1] is at the
310 * bottom right of its bbox).
312 * If the bbox is empty, this will return a singular matrix.
314 * @param aFlags One or more of the BBoxFlags values defined below.
316 static gfxMatrix AdjustMatrixForUnits(const gfxMatrix& aMatrix,
317 const SVGAnimatedEnumeration* aUnits,
318 nsIFrame* aFrame, uint32_t aFlags);
320 enum BBoxFlags {
321 eBBoxIncludeFill = 1 << 0,
322 // Include the geometry of the fill even when the fill does not
323 // actually render (e.g. when fill="none" or fill-opacity="0")
324 eBBoxIncludeFillGeometry = 1 << 1,
325 eBBoxIncludeStroke = 1 << 2,
326 // Include the geometry of the stroke even when the stroke does not
327 // actually render (e.g. when stroke="none" or stroke-opacity="0")
328 eBBoxIncludeStrokeGeometry = 1 << 3,
329 eBBoxIncludeMarkers = 1 << 4,
330 eBBoxIncludeClipped = 1 << 5,
331 // Normally a getBBox call on outer-<svg> should only return the
332 // bounds of the elements children. This flag will cause the
333 // element's bounds to be returned instead.
334 eUseFrameBoundsForOuterSVG = 1 << 6,
335 // https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
336 eForGetClientRects = 1 << 7,
337 // If the given frame is an HTML element, only include the region of the
338 // given frame, instead of all continuations of it, while computing bbox if
339 // this flag is set.
340 eIncludeOnlyCurrentFrameForNonSVGElement = 1 << 8,
341 // This flag is only has an effect when the target is a <use> element.
342 // getBBox returns the bounds of the elements children in user space if
343 // this flag is set; Otherwise, getBBox returns the union bounds in
344 // the coordinate system formed by the <use> element.
345 eUseUserSpaceOfUseElement = 1 << 9,
346 // For a frame with a clip-path, if this flag is set then the result
347 // will not be clipped to the bbox of the content inside the clip-path.
348 eDoNotClipToBBoxOfContentInsideClipPath = 1 << 10,
351 * This function in primarily for implementing the SVG DOM function getBBox()
352 * and the SVG attribute value 'objectBoundingBox'. However, it has been
353 * extended with various extra parameters in order to become more of a
354 * general purpose getter of all sorts of bounds that we might need to obtain
355 * for SVG elements, or even for other elements that have SVG effects applied
356 * to them.
358 * @param aFrame The frame of the element for which the bounds are to be
359 * obtained.
360 * @param aFlags One or more of the BBoxFlags values defined above.
361 * @param aToBoundsSpace If not specified the returned rect is in aFrame's
362 * element's "user space". A matrix can optionally be pass to specify a
363 * transform from aFrame's user space to the bounds space of interest
364 * (typically this will be the ancestor SVGOuterSVGFrame, but it could be
365 * to any other coordinate space).
367 static gfxRect GetBBox(nsIFrame* aFrame,
368 // If the default arg changes, update the handling for
369 // ObjectBoundingBoxProperty() in the implementation.
370 uint32_t aFlags = eBBoxIncludeFillGeometry,
371 const gfxMatrix* aToBoundsSpace = nullptr);
374 * "User space" is the space that the frame's BBox (as calculated by
375 * SVGUtils::GetBBox) is in. "Frame space" is the space that has its origin
376 * at the top left of the union of the frame's border-box rects over all
377 * continuations.
378 * This function returns the offset one needs to add to something in frame
379 * space in order to get its coordinates in user space.
381 static gfxPoint FrameSpaceInCSSPxToUserSpaceOffset(const nsIFrame* aFrame);
384 * Convert a userSpaceOnUse/objectBoundingBoxUnits rectangle that's specified
385 * using four SVGAnimatedLength values into a user unit rectangle in user
386 * space.
388 * @param aXYWH pointer to 4 consecutive SVGAnimatedLength objects containing
389 * the x, y, width and height values in that order
390 * @param aBBox the bounding box of the object the rect is relative to;
391 * may be null if aUnits is not SVG_UNIT_TYPE_OBJECTBOUNDINGBOX
392 * @param aFrame the object in which to interpret user-space units;
393 * may be null if aUnits is SVG_UNIT_TYPE_OBJECTBOUNDINGBOX
395 static gfxRect GetRelativeRect(uint16_t aUnits,
396 const SVGAnimatedLength* aXYWH,
397 const gfxRect& aBBox, nsIFrame* aFrame);
399 static gfxRect GetRelativeRect(uint16_t aUnits,
400 const SVGAnimatedLength* aXYWH,
401 const gfxRect& aBBox,
402 const dom::UserSpaceMetrics& aMetrics);
404 static bool OuterSVGIsCallingReflowSVG(nsIFrame* aFrame);
405 static bool AnyOuterSVGIsCallingReflowSVG(nsIFrame* aFrame);
408 * See https://svgwg.org/svg2-draft/painting.html#NonScalingStroke
410 * If the computed value of the 'vector-effect' property on aFrame is
411 * 'non-scaling-stroke', then this function will set aUserToOuterSVG to the
412 * transform from aFrame's SVG user space to the initial coordinate system
413 * established by the viewport of aFrame's outer-<svg>'s (the coordinate
414 * system in which the stroke is fixed). If aUserToOuterSVG is set to a
415 * non-identity matrix this function returns true, else it returns false.
417 static bool GetNonScalingStrokeTransform(const nsIFrame* aFrame,
418 gfxMatrix* aUserToOuterSVG);
421 * Compute the maximum possible device space stroke extents of a path given
422 * the path's device space path extents, its stroke style and its ctm.
424 * This is a workaround for the lack of suitable cairo API for getting the
425 * tight device space stroke extents of a path. This basically gives us the
426 * tightest extents that we can guarantee fully enclose the inked stroke
427 * without doing the calculations for the actual tight extents. We exploit
428 * the fact that cairo does have an API for getting the tight device space
429 * fill/path extents.
431 * This should die once bug 478152 is fixed.
433 static gfxRect PathExtentsToMaxStrokeExtents(const gfxRect& aPathExtents,
434 const nsTextFrame* aFrame,
435 const gfxMatrix& aMatrix);
436 static gfxRect PathExtentsToMaxStrokeExtents(const gfxRect& aPathExtents,
437 const SVGGeometryFrame* aFrame,
438 const gfxMatrix& aMatrix);
441 * Convert a floating-point value to a 32-bit integer value, clamping to
442 * the range of valid integers.
444 static int32_t ClampToInt(double aVal) {
445 return NS_lround(
446 std::max(double(INT32_MIN), std::min(double(INT32_MAX), aVal)));
450 * Convert a floating-point value to a 64-bit integer value, clamping to
451 * the lowest and highest integers that can be safely compared to a double.
453 static int64_t ClampToInt64(double aVal) {
454 return static_cast<int64_t>(
455 std::clamp<double>(aVal, INT64_MIN, std::nexttoward(INT64_MAX, 0)));
458 static nscolor GetFallbackOrPaintColor(
459 const ComputedStyle&, StyleSVGPaint nsStyleSVG::*aFillOrStroke,
460 nscolor aDefaultContextFallbackColor);
462 static void MakeFillPatternFor(nsIFrame* aFrame, gfxContext* aContext,
463 GeneralPattern* aOutPattern,
464 imgDrawingParams& aImgParams,
465 SVGContextPaint* aContextPaint = nullptr);
467 static void MakeStrokePatternFor(nsIFrame* aFrame, gfxContext* aContext,
468 GeneralPattern* aOutPattern,
469 imgDrawingParams& aImgParams,
470 SVGContextPaint* aContextPaint = nullptr);
472 static float GetOpacity(const StyleSVGOpacity&, const SVGContextPaint*);
475 * @return false if there is no stroke
477 static bool HasStroke(const nsIFrame* aFrame,
478 const SVGContextPaint* aContextPaint = nullptr);
480 static float GetStrokeWidth(const nsIFrame* aFrame,
481 const SVGContextPaint* aContextPaint = nullptr);
484 * Set up a context for a stroked path (including any dashing that applies).
486 static void SetupStrokeGeometry(nsIFrame* aFrame, gfxContext* aContext,
487 SVGContextPaint* aContextPaint = nullptr);
490 * This function returns a set of bit flags indicating which parts of the
491 * element (fill, stroke, bounds) should intercept pointer events. It takes
492 * into account the type of element and the value of the 'pointer-events'
493 * property on the element.
495 static uint16_t GetGeometryHitTestFlags(const nsIFrame* aFrame);
497 static FillRule ToFillRule(StyleFillRule aFillRule) {
498 return aFillRule == StyleFillRule::Evenodd ? FillRule::FILL_EVEN_ODD
499 : FillRule::FILL_WINDING;
502 static AntialiasMode ToAntialiasMode(StyleTextRendering aTextRendering) {
503 return aTextRendering == StyleTextRendering::Optimizespeed
504 ? AntialiasMode::NONE
505 : AntialiasMode::SUBPIXEL;
509 * Render a SVG glyph.
510 * @param aElement the SVG glyph element to render
511 * @param aContext the thebes aContext to draw to
512 * @return true if rendering succeeded
514 static void PaintSVGGlyph(Element* aElement, gfxContext* aContext);
517 * Get the extents of a SVG glyph.
518 * @param aElement the SVG glyph element
519 * @param aSVGToAppSpace the matrix mapping the SVG glyph space to the
520 * target context space
521 * @param aResult the result (valid when true is returned)
522 * @return true if calculating the extents succeeded
524 static bool GetSVGGlyphExtents(const Element* aElement,
525 const gfxMatrix& aSVGToAppSpace,
526 gfxRect* aResult);
529 * Returns the app unit canvas bounds of a userspace rect.
531 * @param aToCanvas Transform from userspace to canvas device space.
533 static nsRect ToCanvasBounds(const gfxRect& aUserspaceRect,
534 const gfxMatrix& aToCanvas,
535 const nsPresContext* presContext);
537 struct MaskUsage;
538 static MaskUsage DetermineMaskUsage(const nsIFrame* aFrame,
539 bool aHandleOpacity);
541 struct MOZ_STACK_CLASS MaskUsage {
542 friend MaskUsage SVGUtils::DetermineMaskUsage(const nsIFrame* aFrame,
543 bool aHandleOpacity);
545 bool ShouldGenerateMaskLayer() const { return mShouldGenerateMaskLayer; }
547 bool ShouldGenerateClipMaskLayer() const {
548 return mShouldGenerateClipMaskLayer;
551 bool ShouldGenerateLayer() const {
552 return mShouldGenerateMaskLayer || mShouldGenerateClipMaskLayer;
555 bool ShouldGenerateMask() const {
556 return mShouldGenerateMaskLayer || mShouldGenerateClipMaskLayer ||
557 !IsOpaque();
560 bool ShouldApplyClipPath() const { return mShouldApplyClipPath; }
562 bool HasSVGClip() const {
563 return mShouldGenerateClipMaskLayer || mShouldApplyClipPath;
566 bool ShouldApplyBasicShapeOrPath() const {
567 return mShouldApplyBasicShapeOrPath;
570 bool IsSimpleClipShape() const { return mIsSimpleClipShape; }
572 bool IsOpaque() const { return mOpacity == 1.0f; }
574 bool IsTransparent() const { return mOpacity == 0.0f; }
576 float Opacity() const { return mOpacity; }
578 bool UsingMaskOrClipPath() const {
579 return mShouldGenerateMaskLayer || mShouldGenerateClipMaskLayer ||
580 mShouldApplyClipPath || mShouldApplyBasicShapeOrPath;
583 bool ShouldDoSomething() const {
584 return mShouldGenerateMaskLayer || mShouldGenerateClipMaskLayer ||
585 mShouldApplyClipPath || mShouldApplyBasicShapeOrPath ||
586 mOpacity != 1.0f;
589 private:
590 MaskUsage() = default;
592 float mOpacity = 0.0f;
593 bool mShouldGenerateMaskLayer = false;
594 bool mShouldGenerateClipMaskLayer = false;
595 bool mShouldApplyClipPath = false;
596 bool mShouldApplyBasicShapeOrPath = false;
597 bool mIsSimpleClipShape = false;
600 static float ComputeOpacity(const nsIFrame* aFrame, bool aHandleOpacity);
603 * SVG frames expect to paint in SVG user units, which are equal to CSS px
604 * units. This method provides a transform matrix to multiply onto a
605 * gfxContext's current transform to convert the context's current units from
606 * its usual dev pixels to SVG user units/CSS px to keep the SVG code happy.
608 static gfxMatrix GetCSSPxToDevPxMatrix(const nsIFrame* aNonSVGFrame);
611 * It is a replacement of
612 * SVGElement::PrependLocalTransformsTo(eUserSpaceToParent).
613 * If no CSS transform is involved, they should behave exactly the same;
614 * if there are CSS transforms, this one will take them into account
615 * while SVGElement::PrependLocalTransformsTo won't.
617 static gfxMatrix GetTransformMatrixInUserSpace(const nsIFrame* aFrame);
620 } // namespace mozilla
622 #endif // LAYOUT_SVG_SVGUTILS_H_