Bug 1039883 - release Tiled layer's gralloc when an application is background r=nical
[gecko.git] / layout / svg / nsSVGUtils.h
blob4671ac78682489108c6043b9b50653a37a8aae5d
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef NS_SVGUTILS_H
7 #define NS_SVGUTILS_H
9 // include math.h to pick up definition of M_ maths defines e.g. M_PI
10 #define _USE_MATH_DEFINES
11 #include <math.h>
13 #include "DrawMode.h"
14 #include "gfx2DGlue.h"
15 #include "gfxMatrix.h"
16 #include "gfxPoint.h"
17 #include "gfxRect.h"
18 #include "mozilla/gfx/Rect.h"
19 #include "nsAlgorithm.h"
20 #include "nsChangeHint.h"
21 #include "nsColor.h"
22 #include "nsCOMPtr.h"
23 #include "nsID.h"
24 #include "nsISupportsBase.h"
25 #include "nsMathUtils.h"
26 #include "nsStyleStruct.h"
27 #include "mozilla/Constants.h"
28 #include <algorithm>
30 class gfxContext;
31 class gfxPattern;
32 class nsFrameList;
33 class nsIContent;
34 class nsIDocument;
35 class nsIFrame;
36 class nsPresContext;
37 class nsRenderingContext;
38 class nsStyleContext;
39 class nsStyleCoord;
40 class nsSVGClipPathFrame;
41 class nsSVGDisplayContainerFrame;
42 class nsSVGElement;
43 class nsSVGEnum;
44 class nsSVGLength2;
45 class nsSVGOuterSVGFrame;
46 class nsSVGPathGeometryFrame;
47 class nsTextFrame;
48 class gfxTextContextPaint;
50 struct nsStyleSVG;
51 struct nsStyleSVGPaint;
52 struct nsRect;
53 struct nsIntRect;
54 struct nsPoint;
56 namespace mozilla {
57 class SVGAnimatedPreserveAspectRatio;
58 class SVGPreserveAspectRatio;
59 namespace dom {
60 class Element;
61 } // namespace dom
62 namespace gfx {
63 class SourceSurface;
65 } // namespace mozilla
67 // maximum dimension of an offscreen surface - choose so that
68 // the surface size doesn't overflow a 32-bit signed int using
69 // 4 bytes per pixel; in line with gfxASurface::CheckSurfaceSize
70 // In fact Macs can't even manage that
71 #define NS_SVG_OFFSCREEN_MAX_DIMENSION 4096
73 #define SVG_HIT_TEST_FILL 0x01
74 #define SVG_HIT_TEST_STROKE 0x02
75 #define SVG_HIT_TEST_CHECK_MRECT 0x04
78 bool NS_SVGDisplayListHitTestingEnabled();
79 bool NS_SVGDisplayListPaintingEnabled();
80 bool NS_SVGNewGetBBoxEnabled();
82 /**
83 * Sometimes we need to distinguish between an empty box and a box
84 * that contains an element that has no size e.g. a point at the origin.
86 class SVGBBox {
87 typedef mozilla::gfx::Rect Rect;
89 public:
90 SVGBBox()
91 : mIsEmpty(true) {}
93 SVGBBox(const Rect& aRect)
94 : mBBox(aRect), mIsEmpty(false) {}
96 SVGBBox(const gfxRect& aRect)
97 : mBBox(ToRect(aRect)), mIsEmpty(false) {}
99 gfxRect ToThebesRect() const {
100 return ThebesRect(mBBox);
103 bool IsEmpty() const {
104 return mIsEmpty;
107 bool IsFinite() const {
108 return mBBox.IsFinite();
111 void Scale(float aScale) {
112 mBBox.Scale(aScale);
115 void UnionEdges(const SVGBBox& aSVGBBox) {
116 if (aSVGBBox.mIsEmpty) {
117 return;
119 mBBox = mIsEmpty ? aSVGBBox.mBBox : mBBox.UnionEdges(aSVGBBox.mBBox);
120 mIsEmpty = false;
123 void Intersect(const SVGBBox& aSVGBBox) {
124 if (!mIsEmpty && !aSVGBBox.mIsEmpty) {
125 mBBox = mBBox.Intersect(aSVGBBox.mBBox);
126 if (mBBox.IsEmpty()) {
127 mIsEmpty = true;
128 mBBox = Rect(0, 0, 0, 0);
130 } else {
131 mIsEmpty = true;
132 mBBox = Rect(0, 0, 0, 0);
136 private:
137 Rect mBBox;
138 bool mIsEmpty;
141 // GRRR WINDOWS HATE HATE HATE
142 #undef CLIP_MASK
144 class MOZ_STACK_CLASS SVGAutoRenderState
146 public:
147 enum RenderMode {
149 * Used to inform SVG frames that they should paint as normal.
151 NORMAL,
152 /**
153 * Used to inform SVG frames when they are painting as the child of a
154 * simple clipPath. In this case they should only draw their basic geometry
155 * as a path. They should not fill, stroke, or paint anything else.
157 CLIP,
158 /**
159 * Used to inform SVG frames when they are painting as the child of a
160 * complex clipPath that requires the use of a clip mask. In this case they
161 * should only draw their basic geometry as a path and then fill it using
162 * fully opaque white. They should not stroke, or paint anything else.
164 CLIP_MASK
167 SVGAutoRenderState(nsRenderingContext *aContext, RenderMode aMode
168 MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
169 ~SVGAutoRenderState();
171 void SetPaintingToWindow(bool aPaintingToWindow);
173 static RenderMode GetRenderMode(nsRenderingContext *aContext);
174 static bool IsPaintingToWindow(nsRenderingContext *aContext);
176 private:
177 nsRenderingContext *mContext;
178 void *mOriginalRenderState;
179 RenderMode mMode;
180 bool mPaintingToWindow;
181 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
185 #define NS_ISVGFILTERREFERENCE_IID \
186 { 0x9744ee20, 0x1bcf, 0x4c62, \
187 { 0x86, 0x7d, 0xd3, 0x7a, 0x91, 0x60, 0x3e, 0xef } }
189 class nsISVGFilterReference : public nsISupports
191 public:
192 NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISVGFILTERREFERENCE_IID)
193 virtual void Invalidate() = 0;
196 NS_DEFINE_STATIC_IID_ACCESSOR(nsISVGFilterReference, NS_ISVGFILTERREFERENCE_IID)
199 * General functions used by all of SVG layout and possibly content code.
200 * If a method is used by content and depends only on other content methods
201 * it should go in SVGContentUtils instead.
203 class nsSVGUtils
205 public:
206 typedef mozilla::dom::Element Element;
208 static void Init();
211 * Gets the nearest nsSVGInnerSVGFrame or nsSVGOuterSVGFrame frame. aFrame
212 * must be an SVG frame. If aFrame is of type nsGkAtoms::svgOuterSVGFrame,
213 * returns nullptr.
215 static nsSVGDisplayContainerFrame* GetNearestSVGViewport(nsIFrame *aFrame);
218 * Returns the frame's post-filter visual overflow rect when passed the
219 * frame's pre-filter visual overflow rect. If the frame is not currently
220 * being filtered, this function simply returns aUnfilteredRect.
222 static nsRect GetPostFilterVisualOverflowRect(nsIFrame *aFrame,
223 const nsRect &aUnfilteredRect);
226 * Schedules an update of the frame's bounds (which will in turn invalidate
227 * the new area that the frame should paint to).
229 * This does nothing when passed an NS_FRAME_IS_NONDISPLAY frame.
230 * In future we may want to allow ReflowSVG to be called on such frames,
231 * but that would be better implemented as a ForceReflowSVG function to
232 * be called synchronously while painting them without marking or paying
233 * attention to dirty bits like this function.
235 * This is very similar to PresShell::FrameNeedsReflow. The main reason that
236 * we have this function instead of using FrameNeedsReflow is because we need
237 * to be able to call it under nsSVGOuterSVGFrame::NotifyViewportChange when
238 * that function is called by nsSVGOuterSVGFrame::Reflow. FrameNeedsReflow
239 * is not suitable for calling during reflow though, and it asserts as much.
240 * The reason that we want to be callable under NotifyViewportChange is
241 * because we want to synchronously notify and dirty the nsSVGOuterSVGFrame's
242 * children so that when nsSVGOuterSVGFrame::DidReflow is called its children
243 * will be updated for the new size as appropriate. Otherwise we'd have to
244 * post an event to the event loop to mark dirty flags and request an update.
246 * Another reason that we don't currently want to call
247 * PresShell::FrameNeedsReflow is because passing eRestyle to it to get it to
248 * mark descendants dirty would cause it to descend through
249 * nsSVGForeignObjectFrame frames to mark their children dirty, but we want to
250 * handle nsSVGForeignObjectFrame specially. It would also do unnecessary work
251 * descending into NS_FRAME_IS_NONDISPLAY frames.
253 static void ScheduleReflowSVG(nsIFrame *aFrame);
256 * Returns true if the frame or any of its children need ReflowSVG
257 * to be called on them.
259 static bool NeedsReflowSVG(nsIFrame *aFrame);
262 * Update the filter invalidation region for ancestor frames, if relevant.
264 static void NotifyAncestorsOfFilterRegionChange(nsIFrame *aFrame);
266 /* Computes the input length in terms of object space coordinates.
267 Input: rect - bounding box
268 length - length to be converted
270 static float ObjectSpace(const gfxRect &aRect, const nsSVGLength2 *aLength);
272 /* Computes the input length in terms of user space coordinates.
273 Input: content - object to be used for determining user space
274 Input: length - length to be converted
276 static float UserSpace(nsSVGElement *aSVGElement, const nsSVGLength2 *aLength);
278 /* Computes the input length in terms of user space coordinates.
279 Input: aFrame - object to be used for determining user space
280 length - length to be converted
282 static float UserSpace(nsIFrame *aFrame, const nsSVGLength2 *aLength);
284 /* Find the outermost SVG frame of the passed frame */
285 static nsSVGOuterSVGFrame *
286 GetOuterSVGFrame(nsIFrame *aFrame);
289 * Get the covered region for a frame. Return null if it's not an SVG frame.
290 * @param aRect gets a rectangle in app units
291 * @return the outer SVG frame which aRect is relative to
293 static nsIFrame*
294 GetOuterSVGFrameAndCoveredRegion(nsIFrame* aFrame, nsRect* aRect);
296 /* Paint SVG frame with SVG effects - aDirtyRect is the area being
297 * redrawn, in device pixel coordinates relative to the outer svg */
298 static void
299 PaintFrameWithEffects(nsRenderingContext *aContext,
300 const nsIntRect *aDirtyRect,
301 nsIFrame *aFrame,
302 nsIFrame* aTransformRoot = nullptr);
304 /* Hit testing - check if point hits the clipPath of indicated
305 * frame. Returns true if no clipPath set. */
306 static bool
307 HitTestClip(nsIFrame *aFrame, const nsPoint &aPoint);
309 /* Hit testing - check if point hits any children of frame. */
311 static nsIFrame *
312 HitTestChildren(nsIFrame *aFrame, const nsPoint &aPoint);
315 * Returns the CanvasTM of the indicated frame, whether it's a
316 * child SVG frame, container SVG frame, or a regular frame.
317 * For regular frames, we just return an identity matrix.
319 static gfxMatrix GetCanvasTM(nsIFrame* aFrame, uint32_t aFor,
320 nsIFrame* aTransformRoot = nullptr);
323 * Returns the transform from aFrame's user space to canvas space. Only call
324 * with SVG frames. This is like GetCanvasTM, except that it only includes
325 * the transforms from aFrame's user space (i.e. the coordinate context
326 * established by its 'transform' attribute, or else the coordinate context
327 * that its _parent_ establishes for its children) to outer-<svg> device
328 * space. Specifically, it does not include any other transforms introduced
329 * by the frame such as x/y offsets and viewBox attributes.
331 static gfxMatrix GetUserToCanvasTM(nsIFrame* aFrame, uint32_t aFor);
334 * Notify the descendants of aFrame of a change to one of their ancestors
335 * that might affect them.
337 static void
338 NotifyChildrenOfSVGChange(nsIFrame *aFrame, uint32_t aFlags);
341 * Get frame's covered region by walking the children and doing union.
343 static nsRect
344 GetCoveredRegion(const nsFrameList &aFrames);
346 // Converts aPoint from an app unit point in outer-<svg> content rect space
347 // to an app unit point in a frame's SVG userspace.
348 // This is a temporary helper we should no longer need after bug 614732 is
349 // fixed.
350 static nsPoint
351 TransformOuterSVGPointToChildFrame(nsPoint aPoint,
352 const gfxMatrix& aFrameToCanvasTM,
353 nsPresContext* aPresContext);
355 static nsRect
356 TransformFrameRectToOuterSVG(const nsRect& aRect,
357 const gfxMatrix& aMatrix,
358 nsPresContext* aPresContext);
361 * Convert a surface size to an integer for use by thebes
362 * possibly making it smaller in the process so the surface does not
363 * use excessive memory.
365 * @param aSize the desired surface size
366 * @param aResultOverflows true if the desired surface size is too big
367 * @return the surface size to use
369 static gfxIntSize ConvertToSurfaceSize(const gfxSize& aSize,
370 bool *aResultOverflows);
373 * Hit test a given rectangle/matrix.
375 static bool
376 HitTestRect(const mozilla::gfx::Matrix &aMatrix,
377 float aRX, float aRY, float aRWidth, float aRHeight,
378 float aX, float aY);
382 * Get the clip rect for the given frame, taking into account the CSS 'clip'
383 * property. See:
384 * http://www.w3.org/TR/SVG11/masking.html#OverflowAndClipProperties
385 * The arguments for aX, aY, aWidth and aHeight should be the dimensions of
386 * the viewport established by aFrame.
388 static gfxRect
389 GetClipRectForFrame(nsIFrame *aFrame,
390 float aX, float aY, float aWidth, float aHeight);
392 static void SetClipRect(gfxContext *aContext,
393 const gfxMatrix &aCTM,
394 const gfxRect &aRect);
396 /* Using group opacity instead of fill or stroke opacity on a
397 * geometry object seems to be a common authoring mistake. If we're
398 * not applying filters and not both stroking and filling, we can
399 * generate the same result without going through the overhead of a
400 * push/pop group. */
401 static bool
402 CanOptimizeOpacity(nsIFrame *aFrame);
405 * Take the CTM to userspace for an element, and adjust it to a CTM to its
406 * object bounding box space if aUnits is SVG_UNIT_TYPE_OBJECTBOUNDINGBOX.
407 * (I.e. so that [0,0] is at the top left of its bbox, and [1,1] is at the
408 * bottom right of its bbox).
410 * If the bbox is empty, this will return a singular matrix.
412 static gfxMatrix
413 AdjustMatrixForUnits(const gfxMatrix &aMatrix,
414 nsSVGEnum *aUnits,
415 nsIFrame *aFrame);
417 enum BBoxFlags {
418 eBBoxIncludeFill = 1 << 0,
419 eBBoxIncludeFillGeometry = 1 << 1,
420 eBBoxIncludeStroke = 1 << 2,
421 eBBoxIncludeStrokeGeometry = 1 << 3,
422 eBBoxIncludeMarkers = 1 << 4,
423 eBBoxIncludeClipped = 1 << 5
426 * Get the SVG bbox (the SVG spec's simplified idea of bounds) of aFrame in
427 * aFrame's userspace.
429 static gfxRect GetBBox(nsIFrame *aFrame,
430 uint32_t aFlags = eBBoxIncludeFillGeometry);
433 * "User space" is the space that the frame's BBox (as calculated by
434 * nsSVGUtils::GetBBox) is in. "Frame space" is the space that has its origin
435 * at the top left of the union of the frame's border-box rects over all
436 * continuations.
437 * This function returns the offset one needs to add to something in frame
438 * space in order to get its coordinates in user space.
440 static gfxPoint FrameSpaceInCSSPxToUserSpaceOffset(nsIFrame *aFrame);
443 * Convert a userSpaceOnUse/objectBoundingBoxUnits rectangle that's specified
444 * using four nsSVGLength2 values into a user unit rectangle in user space.
446 * @param aXYWH pointer to 4 consecutive nsSVGLength2 objects containing
447 * the x, y, width and height values in that order
448 * @param aBBox the bounding box of the object the rect is relative to;
449 * may be null if aUnits is not SVG_UNIT_TYPE_OBJECTBOUNDINGBOX
450 * @param aFrame the object in which to interpret user-space units;
451 * may be null if aUnits is SVG_UNIT_TYPE_OBJECTBOUNDINGBOX
453 static gfxRect
454 GetRelativeRect(uint16_t aUnits, const nsSVGLength2 *aXYWH,
455 const gfxRect &aBBox, nsIFrame *aFrame);
458 * Find the first frame, starting with aStartFrame and going up its
459 * parent chain, that is not an svgAFrame.
461 static nsIFrame* GetFirstNonAAncestorFrame(nsIFrame* aStartFrame);
463 static bool OuterSVGIsCallingReflowSVG(nsIFrame *aFrame);
464 static bool AnyOuterSVGIsCallingReflowSVG(nsIFrame *aFrame);
467 * Get any additional transforms that apply only to stroking
468 * e.g. non-scaling-stroke
470 static gfxMatrix GetStrokeTransform(nsIFrame *aFrame);
473 * Compute the maximum possible device space stroke extents of a path given
474 * the path's device space path extents, its stroke style and its ctm.
476 * This is a workaround for the lack of suitable cairo API for getting the
477 * tight device space stroke extents of a path. This basically gives us the
478 * tightest extents that we can guarantee fully enclose the inked stroke
479 * without doing the calculations for the actual tight extents. We exploit
480 * the fact that cairo does have an API for getting the tight device space
481 * fill/path extents.
483 * This should die once bug 478152 is fixed.
485 static gfxRect PathExtentsToMaxStrokeExtents(const gfxRect& aPathExtents,
486 nsTextFrame* aFrame,
487 const gfxMatrix& aMatrix);
488 static gfxRect PathExtentsToMaxStrokeExtents(const gfxRect& aPathExtents,
489 nsSVGPathGeometryFrame* aFrame,
490 const gfxMatrix& aMatrix);
493 * Convert a floating-point value to a 32-bit integer value, clamping to
494 * the range of valid integers.
496 static int32_t ClampToInt(double aVal)
498 return NS_lround(std::max(double(INT32_MIN),
499 std::min(double(INT32_MAX), aVal)));
502 static nscolor GetFallbackOrPaintColor(gfxContext *aContext,
503 nsStyleContext *aStyleContext,
504 nsStyleSVGPaint nsStyleSVG::*aFillOrStroke);
507 * Set up cairo context with an object pattern
509 static bool SetupContextPaint(gfxContext *aContext,
510 gfxTextContextPaint *aContextPaint,
511 const nsStyleSVGPaint& aPaint,
512 float aOpacity);
515 * Sets the current paint on the specified gfxContent to be the SVG 'fill'
516 * for the given frame.
518 static bool SetupCairoFillPaint(nsIFrame* aFrame, gfxContext* aContext,
519 gfxTextContextPaint *aContextPaint = nullptr);
522 * Sets the current paint on the specified gfxContent to be the SVG 'stroke'
523 * for the given frame.
525 static bool SetupCairoStrokePaint(nsIFrame* aFrame, gfxContext* aContext,
526 gfxTextContextPaint *aContextPaint = nullptr);
528 static float GetOpacity(nsStyleSVGOpacitySource aOpacityType,
529 const float& aOpacity,
530 gfxTextContextPaint *aOuterContextPaint);
533 * @return false if there is no stroke
535 static bool HasStroke(nsIFrame* aFrame,
536 gfxTextContextPaint *aContextPaint = nullptr);
538 static float GetStrokeWidth(nsIFrame* aFrame,
539 gfxTextContextPaint *aContextPaint = nullptr);
542 * Set up a cairo context for measuring the bounding box of a stroked path.
544 static void SetupCairoStrokeBBoxGeometry(nsIFrame* aFrame,
545 gfxContext *aContext,
546 gfxTextContextPaint *aContextPaint = nullptr);
549 * Set up a cairo context for a stroked path (including any dashing that
550 * applies).
552 static void SetupCairoStrokeGeometry(nsIFrame* aFrame, gfxContext *aContext,
553 gfxTextContextPaint *aContextPaint = nullptr);
556 * Set up a cairo context for stroking, including setting up any stroke-related
557 * properties such as dashing and setting the current paint on the gfxContext.
559 static bool SetupCairoStroke(nsIFrame* aFrame, gfxContext *aContext,
560 gfxTextContextPaint *aContextPaint = nullptr);
563 * This function returns a set of bit flags indicating which parts of the
564 * element (fill, stroke, bounds) should intercept pointer events. It takes
565 * into account the type of element and the value of the 'pointer-events'
566 * property on the element.
568 static uint16_t GetGeometryHitTestFlags(nsIFrame* aFrame);
571 * Render a SVG glyph.
572 * @param aElement the SVG glyph element to render
573 * @param aContext the thebes aContext to draw to
574 * @param aDrawMode fill or stroke or both (see DrawMode)
575 * @return true if rendering succeeded
577 static bool PaintSVGGlyph(Element* aElement, gfxContext* aContext,
578 DrawMode aDrawMode,
579 gfxTextContextPaint* aContextPaint);
581 * Get the extents of a SVG glyph.
582 * @param aElement the SVG glyph element
583 * @param aSVGToAppSpace the matrix mapping the SVG glyph space to the
584 * target context space
585 * @param aResult the result (valid when true is returned)
586 * @return true if calculating the extents succeeded
588 static bool GetSVGGlyphExtents(Element* aElement,
589 const gfxMatrix& aSVGToAppSpace,
590 gfxRect* aResult);
593 * Returns the app unit canvas bounds of a userspace rect.
595 * @param aToCanvas Transform from userspace to canvas device space.
597 static nsRect
598 ToCanvasBounds(const gfxRect &aUserspaceRect,
599 const gfxMatrix &aToCanvas,
600 const nsPresContext *presContext);
603 #endif