Backed out changeset 2960ea3e50ca (bug 1881157) for causing crashtest assertion failu...
[gecko.git] / layout / svg / SVGOuterSVGFrame.cpp
blobea0879c0c292e10f9a6c10370c60dd10358a3ac2
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 // Main header first:
8 #include "SVGOuterSVGFrame.h"
10 // Keep others in (case-insensitive) order:
11 #include "gfxContext.h"
12 #include "nsDisplayList.h"
13 #include "nsIInterfaceRequestorUtils.h"
14 #include "nsLayoutUtils.h"
15 #include "nsObjectLoadingContent.h"
16 #include "nsSubDocumentFrame.h"
17 #include "mozilla/PresShell.h"
18 #include "mozilla/SVGUtils.h"
19 #include "mozilla/dom/BrowserChild.h"
20 #include "mozilla/dom/Document.h"
21 #include "mozilla/dom/Element.h"
22 #include "mozilla/dom/SVGSVGElement.h"
24 using namespace mozilla::dom;
25 using namespace mozilla::gfx;
26 using namespace mozilla::image;
28 //----------------------------------------------------------------------
29 // Implementation
31 nsContainerFrame* NS_NewSVGOuterSVGFrame(mozilla::PresShell* aPresShell,
32 mozilla::ComputedStyle* aStyle) {
33 return new (aPresShell)
34 mozilla::SVGOuterSVGFrame(aStyle, aPresShell->GetPresContext());
37 namespace mozilla {
39 NS_IMPL_FRAMEARENA_HELPERS(SVGOuterSVGFrame)
41 SVGOuterSVGFrame::SVGOuterSVGFrame(ComputedStyle* aStyle,
42 nsPresContext* aPresContext)
43 : SVGDisplayContainerFrame(aStyle, aPresContext, kClassID) {
44 // Outer-<svg> has CSS layout, so remove this bit:
45 RemoveStateBits(NS_FRAME_SVG_LAYOUT);
46 AddStateBits(NS_FRAME_REFLOW_ROOT | NS_FRAME_FONT_INFLATION_CONTAINER |
47 NS_FRAME_FONT_INFLATION_FLOW_ROOT | NS_FRAME_MAY_BE_TRANSFORMED);
50 // The CSS Containment spec says that size-contained replaced elements must be
51 // treated as having an intrinsic width and height of 0. That's applicable to
52 // outer SVG frames, unless they're the outermost element (in which case
53 // they're not really "replaced", and there's no outer context to contain sizes
54 // from leaking into). Hence, we check for a parent element before we bother
55 // testing for 'contain:size'.
56 static inline ContainSizeAxes ContainSizeAxesIfApplicable(
57 const SVGOuterSVGFrame* aFrame) {
58 if (!aFrame->GetContent()->GetParent()) {
59 return ContainSizeAxes(false, false);
61 return aFrame->GetContainSizeAxes();
64 // This should match ImageDocument::GetZoomLevel.
65 float SVGOuterSVGFrame::ComputeFullZoom() const {
66 MOZ_ASSERT(mIsRootContent);
67 MOZ_ASSERT(!mIsInIframe);
68 if (BrowsingContext* bc = PresContext()->Document()->GetBrowsingContext()) {
69 return bc->FullZoom();
71 return 1.0f;
74 void SVGOuterSVGFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
75 nsIFrame* aPrevInFlow) {
76 NS_ASSERTION(aContent->IsSVGElement(nsGkAtoms::svg),
77 "Content is not an SVG 'svg' element!");
79 // Check for conditional processing attributes here rather than in
80 // nsCSSFrameConstructor::FindSVGData because we want to avoid
81 // simply giving failing outer <svg> elements an SVGContainerFrame.
82 // We don't create other SVG frames if PassesConditionalProcessingTests
83 // returns false, but since we do create SVGOuterSVGFrame frames we
84 // prevent them from painting by [ab]use NS_FRAME_IS_NONDISPLAY. The
85 // frame will be recreated via an nsChangeHint_ReconstructFrame restyle if
86 // the value returned by PassesConditionalProcessingTests changes.
87 auto* svg = static_cast<SVGSVGElement*>(aContent);
88 if (!svg->PassesConditionalProcessingTests()) {
89 AddStateBits(NS_FRAME_IS_NONDISPLAY);
92 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
94 Document* doc = mContent->GetUncomposedDoc();
95 mIsRootContent = doc && doc->GetRootElement() == mContent;
97 if (mIsRootContent) {
98 if (nsCOMPtr<nsIDocShell> docShell = PresContext()->GetDocShell()) {
99 RefPtr<BrowsingContext> bc = docShell->GetBrowsingContext();
100 if (const Maybe<nsString>& type = bc->GetEmbedderElementType()) {
101 mIsInObjectOrEmbed =
102 nsGkAtoms::object->Equals(*type) || nsGkAtoms::embed->Equals(*type);
103 mIsInIframe = nsGkAtoms::iframe->Equals(*type);
106 if (!mIsInIframe) {
107 mFullZoom = ComputeFullZoom();
111 MaybeSendIntrinsicSizeAndRatioToEmbedder();
114 //----------------------------------------------------------------------
115 // nsQueryFrame methods
117 NS_QUERYFRAME_HEAD(SVGOuterSVGFrame)
118 NS_QUERYFRAME_ENTRY(SVGOuterSVGFrame)
119 NS_QUERYFRAME_ENTRY(ISVGSVGFrame)
120 NS_QUERYFRAME_TAIL_INHERITING(SVGDisplayContainerFrame)
122 //----------------------------------------------------------------------
123 // nsIFrame methods
124 //----------------------------------------------------------------------
125 // reflowing
127 /* virtual */
128 nscoord SVGOuterSVGFrame::GetMinISize(gfxContext* aRenderingContext) {
129 nscoord result;
130 DISPLAY_MIN_INLINE_SIZE(this, result);
132 // If this ever changes to return something other than zero, then
133 // nsSubDocumentFrame::GetMinISize will also need to change.
134 result = nscoord(0);
136 return result;
139 /* virtual */
140 nscoord SVGOuterSVGFrame::GetPrefISize(gfxContext* aRenderingContext) {
141 nscoord result;
142 DISPLAY_PREF_INLINE_SIZE(this, result);
144 SVGSVGElement* svg = static_cast<SVGSVGElement*>(GetContent());
145 WritingMode wm = GetWritingMode();
146 const SVGAnimatedLength& isize =
147 wm.IsVertical() ? svg->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT]
148 : svg->mLengthAttributes[SVGSVGElement::ATTR_WIDTH];
150 if (Maybe<nscoord> containISize =
151 ContainSizeAxesIfApplicable(this).ContainIntrinsicISize(*this)) {
152 result = *containISize;
153 } else if (isize.IsPercentage()) {
154 // If we are here, our inline size attribute is a percentage either
155 // explicitly (via an attribute value) or implicitly (by being unset, which
156 // is treated as 100%). The following if-condition, deciding to return
157 // either the fallback intrinsic size or zero, is made to match blink and
158 // webkit's behavior for webcompat.
159 if (isize.IsExplicitlySet() || StylePosition()->ISize(wm).HasPercent() ||
160 !GetAspectRatio()) {
161 result = wm.IsVertical() ? kFallbackIntrinsicSize.height
162 : kFallbackIntrinsicSize.width;
163 } else {
164 result = nscoord(0);
166 } else {
167 result = nsPresContext::CSSPixelsToAppUnits(isize.GetAnimValue(svg));
168 if (result < 0) {
169 result = nscoord(0);
173 return result;
176 /* virtual */
177 IntrinsicSize SVGOuterSVGFrame::GetIntrinsicSize() {
178 // XXXjwatt Note that here we want to return the CSS width/height if they're
179 // specified and we're embedded inside an nsIObjectLoadingContent.
181 const auto containAxes = ContainSizeAxesIfApplicable(this);
182 if (containAxes.IsBoth()) {
183 // Intrinsic size of 'contain:size' replaced elements is determined by
184 // contain-intrinsic-size, defaulting to 0x0.
185 return FinishIntrinsicSize(containAxes, IntrinsicSize(0, 0));
188 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
189 const SVGAnimatedLength& width =
190 content->mLengthAttributes[SVGSVGElement::ATTR_WIDTH];
191 const SVGAnimatedLength& height =
192 content->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
194 IntrinsicSize intrinsicSize;
196 if (!width.IsPercentage()) {
197 nscoord val =
198 nsPresContext::CSSPixelsToAppUnits(width.GetAnimValue(content));
199 intrinsicSize.width.emplace(std::max(val, 0));
202 if (!height.IsPercentage()) {
203 nscoord val =
204 nsPresContext::CSSPixelsToAppUnits(height.GetAnimValue(content));
205 intrinsicSize.height.emplace(std::max(val, 0));
208 return FinishIntrinsicSize(containAxes, intrinsicSize);
211 /* virtual */
212 AspectRatio SVGOuterSVGFrame::GetIntrinsicRatio() const {
213 if (ContainSizeAxesIfApplicable(this).IsAny()) {
214 return AspectRatio();
217 // We only have an intrinsic size/ratio if our width and height attributes
218 // are both specified and set to non-percentage values, or we have a viewBox
219 // rect: https://svgwg.org/svg2-draft/coords.html#SizingSVGInCSS
221 auto* content = static_cast<SVGSVGElement*>(GetContent());
222 const SVGAnimatedLength& width =
223 content->mLengthAttributes[SVGSVGElement::ATTR_WIDTH];
224 const SVGAnimatedLength& height =
225 content->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
226 if (!width.IsPercentage() && !height.IsPercentage()) {
227 // Use width/height ratio only if
228 // 1. it's not a degenerate ratio, and
229 // 2. width and height are non-negative numbers.
230 // Otherwise, we use the viewbox rect.
231 // https://github.com/w3c/csswg-drafts/issues/6286
232 const float w = width.GetAnimValue(content);
233 const float h = height.GetAnimValue(content);
234 if (w > 0.0f && h > 0.0f) {
235 return AspectRatio::FromSize(w, h);
239 const auto& viewBox = content->GetViewBoxInternal();
240 if (viewBox.HasRect()) {
241 const auto& anim = viewBox.GetAnimValue();
242 return AspectRatio::FromSize(anim.width, anim.height);
245 return SVGDisplayContainerFrame::GetIntrinsicRatio();
248 /* virtual */
249 nsIFrame::SizeComputationResult SVGOuterSVGFrame::ComputeSize(
250 gfxContext* aRenderingContext, WritingMode aWritingMode,
251 const LogicalSize& aCBSize, nscoord aAvailableISize,
252 const LogicalSize& aMargin, const LogicalSize& aBorderPadding,
253 const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) {
254 if (IsRootOfImage() || mIsInObjectOrEmbed) {
255 // The embedding element has sized itself using the CSS replaced element
256 // sizing rules, using our intrinsic dimensions as necessary. The SVG spec
257 // says that the width and height of embedded SVG is overridden by the
258 // width and height of the embedding element, so we just need to size to
259 // the viewport that the embedding element has established for us.
260 return {aCBSize, AspectRatioUsage::None};
263 LogicalSize cbSize = aCBSize;
264 IntrinsicSize intrinsicSize = GetIntrinsicSize();
266 if (mIsRootContent) {
267 // We're the root of the outermost browsing context, so we need to scale
268 // cbSize by the full-zoom so that SVGs with percentage width/height zoom:
270 NS_ASSERTION(aCBSize.ISize(aWritingMode) != NS_UNCONSTRAINEDSIZE &&
271 aCBSize.BSize(aWritingMode) != NS_UNCONSTRAINEDSIZE,
272 "root should not have auto-width/height containing block");
274 if (!mIsInIframe) {
275 // NOTE: We can't just use mFullZoom because this can run before Reflow()
276 // updates it.
277 const float zoom = ComputeFullZoom();
278 cbSize.ISize(aWritingMode) *= zoom;
279 cbSize.BSize(aWritingMode) *= zoom;
282 // We also need to honour the width and height attributes' default values
283 // of 100% when we're the root of a browsing context. (GetIntrinsicSize()
284 // doesn't report these since there's no such thing as a percentage
285 // intrinsic size. Also note that explicit percentage values are mapped
286 // into style, so the following isn't for them.)
288 auto* content = static_cast<SVGSVGElement*>(GetContent());
290 const SVGAnimatedLength& width =
291 content->mLengthAttributes[SVGSVGElement::ATTR_WIDTH];
292 if (width.IsPercentage()) {
293 MOZ_ASSERT(!intrinsicSize.width,
294 "GetIntrinsicSize should have reported no intrinsic width");
295 float val = width.GetAnimValInSpecifiedUnits() / 100.0f;
296 intrinsicSize.width.emplace(std::max(val, 0.0f) *
297 cbSize.Width(aWritingMode));
300 const SVGAnimatedLength& height =
301 content->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
302 NS_ASSERTION(aCBSize.BSize(aWritingMode) != NS_UNCONSTRAINEDSIZE,
303 "root should not have auto-height containing block");
304 if (height.IsPercentage()) {
305 MOZ_ASSERT(!intrinsicSize.height,
306 "GetIntrinsicSize should have reported no intrinsic height");
307 float val = height.GetAnimValInSpecifiedUnits() / 100.0f;
308 intrinsicSize.height.emplace(std::max(val, 0.0f) *
309 cbSize.Height(aWritingMode));
311 MOZ_ASSERT(intrinsicSize.height && intrinsicSize.width,
312 "We should have just handled the only situation where"
313 "we lack an intrinsic height or width.");
316 return {ComputeSizeWithIntrinsicDimensions(
317 aRenderingContext, aWritingMode, intrinsicSize, GetAspectRatio(),
318 cbSize, aMargin, aBorderPadding, aSizeOverrides, aFlags),
319 AspectRatioUsage::None};
322 void SVGOuterSVGFrame::Reflow(nsPresContext* aPresContext,
323 ReflowOutput& aDesiredSize,
324 const ReflowInput& aReflowInput,
325 nsReflowStatus& aStatus) {
326 MarkInReflow();
327 DO_GLOBAL_REFLOW_COUNT("SVGOuterSVGFrame");
328 DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
329 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
330 NS_FRAME_TRACE(
331 NS_FRAME_TRACE_CALLS,
332 ("enter SVGOuterSVGFrame::Reflow: availSize=%d,%d",
333 aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight()));
335 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IN_REFLOW), "frame is not in reflow");
337 const auto wm = GetWritingMode();
338 aDesiredSize.SetSize(wm, aReflowInput.ComputedSizeWithBorderPadding(wm));
340 NS_ASSERTION(!GetPrevInFlow(), "SVG can't currently be broken across pages.");
342 SVGSVGElement* svgElem = static_cast<SVGSVGElement*>(GetContent());
344 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
345 PrincipalChildList().FirstChild());
347 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
348 // Initialize
349 svgElem->UpdateHasChildrenOnlyTransform();
352 // If our SVG viewport has changed, update our content and notify.
353 // http://www.w3.org/TR/SVG11/coords.html#ViewportSpace
355 gfx::Size newViewportSize(
356 nsPresContext::AppUnitsToFloatCSSPixels(aReflowInput.ComputedWidth()),
357 nsPresContext::AppUnitsToFloatCSSPixels(aReflowInput.ComputedHeight()));
359 uint32_t changeBits = 0;
360 if (newViewportSize != svgElem->GetViewportSize()) {
361 // When our viewport size changes, we may need to update the overflow rects
362 // of our child frames. This is the case if:
364 // * We have a real/synthetic viewBox (a children-only transform), since
365 // the viewBox transform will change as the viewport dimensions change.
367 // * We do not have a real/synthetic viewBox, but the last time we
368 // reflowed (or the last time UpdateOverflow() was called) we did.
370 // We only handle the former case here, in which case we mark all our child
371 // frames as dirty so that we reflow them below and update their overflow
372 // rects.
374 // In the latter case, updating of overflow rects is handled for removal of
375 // real viewBox (the viewBox attribute) in AttributeChanged. Synthetic
376 // viewBox "removal" (e.g. a document references the same SVG via both an
377 // <svg:image> and then as a CSS background image (a synthetic viewBox is
378 // used when painting the former, but not when painting the latter)) is
379 // handled in SVGSVGElement::FlushImageTransformInvalidation.
381 if (svgElem->HasViewBoxOrSyntheticViewBox()) {
382 nsIFrame* anonChild = PrincipalChildList().FirstChild();
383 anonChild->MarkSubtreeDirty();
384 for (nsIFrame* child : anonChild->PrincipalChildList()) {
385 child->MarkSubtreeDirty();
388 changeBits |= COORD_CONTEXT_CHANGED;
389 svgElem->SetViewportSize(newViewportSize);
391 if (mIsRootContent && !mIsInIframe) {
392 const auto oldZoom = mFullZoom;
393 mFullZoom = ComputeFullZoom();
394 if (oldZoom != mFullZoom) {
395 changeBits |= FULL_ZOOM_CHANGED;
398 if (changeBits && !HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
399 NotifyViewportOrTransformChanged(changeBits);
402 // Now that we've marked the necessary children as dirty, call
403 // ReflowSVG() or ReflowSVGNonDisplayText() on them, depending
404 // on whether we are non-display.
405 mCallingReflowSVG = true;
406 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
407 ReflowSVGNonDisplayText(this);
408 } else {
409 // Update the mRects and ink overflow rects of all our descendants,
410 // including our anonymous wrapper kid:
411 anonKid->ReflowSVG();
412 MOZ_ASSERT(!anonKid->GetNextSibling(),
413 "We should have one anonymous child frame wrapping our real "
414 "children");
416 mCallingReflowSVG = false;
418 // Set our anonymous kid's offset from our border box:
419 anonKid->SetPosition(GetContentRectRelativeToSelf().TopLeft());
421 // Including our size in our overflow rects regardless of the value of
422 // 'background', 'border', etc. makes sure that we usually (when we clip to
423 // our content area) don't have to keep changing our overflow rects as our
424 // descendants move about (see perf comment below). Including our size in our
425 // scrollable overflow rect also makes sure that we scroll if we're too big
426 // for our viewport.
428 // <svg> never allows scrolling to anything outside its mRect (only panning),
429 // so we must always keep our scrollable overflow set to our size.
431 // With regards to ink overflow, we always clip root-<svg> (see our
432 // BuildDisplayList method) regardless of the value of the 'overflow'
433 // property since that is per-spec, even for the initial 'visible' value. For
434 // that reason there's no point in adding descendant ink overflow to our
435 // own when this frame is for a root-<svg>. That said, there's also a very
436 // good performance reason for us wanting to avoid doing so. If we did, then
437 // the frame's overflow would often change as descendants that are partially
438 // or fully outside its rect moved (think animation on/off screen), and that
439 // would cause us to do a full NS_FRAME_IS_DIRTY reflow and repaint of the
440 // entire document tree each such move (see bug 875175).
442 // So it's only non-root outer-<svg> that has the ink overflow of its
443 // descendants added to its own. (Note that the default user-agent style
444 // sheet makes 'hidden' the default value for :not(root(svg)), so usually
445 // FinishAndStoreOverflow will still clip this back to the frame's rect.)
447 // WARNING!! Keep UpdateBounds below in sync with whatever we do for our
448 // overflow rects here! (Again, see bug 875175.)
450 aDesiredSize.SetOverflowAreasToDesiredBounds();
452 // An outer SVG will be here as a nondisplay if it fails the conditional
453 // processing test. In that case, we don't maintain its overflow.
454 if (!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
455 if (!mIsRootContent) {
456 aDesiredSize.mOverflowAreas.InkOverflow().UnionRect(
457 aDesiredSize.mOverflowAreas.InkOverflow(),
458 anonKid->InkOverflowRect() + anonKid->GetPosition());
460 FinishAndStoreOverflow(&aDesiredSize);
463 NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS,
464 ("exit SVGOuterSVGFrame::Reflow: size=%d,%d",
465 aDesiredSize.Width(), aDesiredSize.Height()));
468 void SVGOuterSVGFrame::DidReflow(nsPresContext* aPresContext,
469 const ReflowInput* aReflowInput) {
470 SVGDisplayContainerFrame::DidReflow(aPresContext, aReflowInput);
472 // Make sure elements styled by :hover get updated if script/animation moves
473 // them under or out from under the pointer:
474 PresShell()->SynthesizeMouseMove(false);
477 /* virtual */
478 void SVGOuterSVGFrame::UnionChildOverflow(OverflowAreas& aOverflowAreas) {
479 // See the comments in Reflow above.
481 // WARNING!! Keep this in sync with Reflow above!
483 if (!mIsRootContent) {
484 nsIFrame* anonKid = PrincipalChildList().FirstChild();
485 aOverflowAreas.InkOverflow().UnionRect(
486 aOverflowAreas.InkOverflow(),
487 anonKid->InkOverflowRect() + anonKid->GetPosition());
491 //----------------------------------------------------------------------
492 // container methods
494 nsresult SVGOuterSVGFrame::AttributeChanged(int32_t aNameSpaceID,
495 nsAtom* aAttribute,
496 int32_t aModType) {
497 if (aNameSpaceID == kNameSpaceID_None &&
498 !HasAnyStateBits(NS_FRAME_FIRST_REFLOW | NS_FRAME_IS_NONDISPLAY)) {
499 if (aAttribute == nsGkAtoms::viewBox ||
500 aAttribute == nsGkAtoms::preserveAspectRatio ||
501 aAttribute == nsGkAtoms::transform) {
502 // make sure our cached transform matrix gets (lazily) updated
503 mCanvasTM = nullptr;
505 SVGUtils::NotifyChildrenOfSVGChange(
506 PrincipalChildList().FirstChild(),
507 aAttribute == nsGkAtoms::viewBox
508 ? TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
509 : TRANSFORM_CHANGED);
511 if (aAttribute != nsGkAtoms::transform) {
512 static_cast<SVGSVGElement*>(GetContent())
513 ->ChildrenOnlyTransformChanged();
516 if (aAttribute == nsGkAtoms::width || aAttribute == nsGkAtoms::height ||
517 aAttribute == nsGkAtoms::viewBox) {
518 // Don't call ChildrenOnlyTransformChanged() here, since we call it
519 // under Reflow if the width/height/viewBox actually changed.
521 MaybeSendIntrinsicSizeAndRatioToEmbedder();
523 if (!mIsInObjectOrEmbed) {
524 // We are not embedded by reference, so our 'width' and 'height'
525 // attributes are not overridden (and viewBox may influence our
526 // intrinsic aspect ratio). We need to reflow.
527 PresShell()->FrameNeedsReflow(
528 this, IntrinsicDirty::FrameAncestorsAndDescendants,
529 NS_FRAME_IS_DIRTY);
534 return NS_OK;
537 bool SVGOuterSVGFrame::IsSVGTransformed(Matrix* aOwnTransform,
538 Matrix* aFromParentTransform) const {
539 // Our anonymous child's HasChildrenOnlyTransform() implementation makes sure
540 // our children-only transforms are applied to our children. We only care
541 // about transforms that transform our own frame here.
543 bool foundTransform = false;
545 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
546 SVGAnimatedTransformList* transformList = content->GetAnimatedTransformList();
547 if ((transformList && transformList->HasTransform()) ||
548 content->GetAnimateMotionTransform()) {
549 if (aOwnTransform) {
550 *aOwnTransform = gfx::ToMatrix(
551 content->PrependLocalTransformsTo(gfxMatrix(), eUserSpaceToParent));
553 foundTransform = true;
556 return foundTransform;
559 //----------------------------------------------------------------------
560 // painting
562 void SVGOuterSVGFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
563 const nsDisplayListSet& aLists) {
564 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
565 return;
568 DisplayBorderBackgroundOutline(aBuilder, aLists);
570 nsRect visibleRect = aBuilder->GetVisibleRect();
571 nsRect dirtyRect = aBuilder->GetDirtyRect();
573 // Per-spec, we always clip root-<svg> even when 'overflow' has its initial
574 // value of 'visible'. See also the "ink overflow" comments in Reflow.
575 DisplayListClipState::AutoSaveRestore autoSR(aBuilder);
576 if (mIsRootContent || StyleDisplay()->IsScrollableOverflow()) {
577 autoSR.ClipContainingBlockDescendantsToContentBox(aBuilder, this);
578 visibleRect = visibleRect.Intersect(GetContentRectRelativeToSelf());
579 dirtyRect = dirtyRect.Intersect(GetContentRectRelativeToSelf());
582 nsDisplayListBuilder::AutoBuildingDisplayList building(
583 aBuilder, this, visibleRect, dirtyRect);
585 nsDisplayList* contentList = aLists.Content();
586 nsDisplayListSet set(contentList, contentList, contentList, contentList,
587 contentList, contentList);
588 BuildDisplayListForNonBlockChildren(aBuilder, set);
591 //----------------------------------------------------------------------
592 // ISVGSVGFrame methods:
594 void SVGOuterSVGFrame::NotifyViewportOrTransformChanged(uint32_t aFlags) {
595 MOZ_ASSERT(aFlags && !(aFlags & ~(COORD_CONTEXT_CHANGED | TRANSFORM_CHANGED |
596 FULL_ZOOM_CHANGED)),
597 "Unexpected aFlags value");
599 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
601 if (aFlags & COORD_CONTEXT_CHANGED) {
602 if (content->HasViewBox()) {
603 // Percentage lengths on children resolve against the viewBox rect so we
604 // don't need to notify them of the viewport change, but the viewBox
605 // transform will have changed, so we need to notify them of that instead.
606 aFlags = TRANSFORM_CHANGED;
607 } else if (content->ShouldSynthesizeViewBox()) {
608 // In the case of a synthesized viewBox, the synthetic viewBox's rect
609 // changes as the viewport changes. As a result we need to maintain the
610 // COORD_CONTEXT_CHANGED flag.
611 aFlags |= TRANSFORM_CHANGED;
612 } else if (mCanvasTM && mCanvasTM->IsSingular()) {
613 // A width/height of zero will result in us having a singular mCanvasTM
614 // even when we don't have a viewBox. So we also want to recompute our
615 // mCanvasTM for this width/height change even though we don't have a
616 // viewBox.
617 aFlags |= TRANSFORM_CHANGED;
621 bool haveNonFulLZoomTransformChange = (aFlags & TRANSFORM_CHANGED);
623 if (aFlags & FULL_ZOOM_CHANGED) {
624 // Convert FULL_ZOOM_CHANGED to TRANSFORM_CHANGED:
625 aFlags = (aFlags & ~FULL_ZOOM_CHANGED) | TRANSFORM_CHANGED;
628 if (aFlags & TRANSFORM_CHANGED) {
629 // Make sure our canvas transform matrix gets (lazily) recalculated:
630 mCanvasTM = nullptr;
632 if (haveNonFulLZoomTransformChange &&
633 !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
634 uint32_t flags = HasAnyStateBits(NS_FRAME_IN_REFLOW)
635 ? SVGSVGElement::eDuringReflow
636 : 0;
637 content->ChildrenOnlyTransformChanged(flags);
641 SVGUtils::NotifyChildrenOfSVGChange(PrincipalChildList().FirstChild(),
642 aFlags);
645 //----------------------------------------------------------------------
646 // ISVGDisplayableFrame methods:
648 void SVGOuterSVGFrame::PaintSVG(gfxContext& aContext,
649 const gfxMatrix& aTransform,
650 imgDrawingParams& aImgParams) {
651 NS_ASSERTION(
652 PrincipalChildList().FirstChild()->IsSVGOuterSVGAnonChildFrame() &&
653 !PrincipalChildList().FirstChild()->GetNextSibling(),
654 "We should have a single, anonymous, child");
655 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
656 PrincipalChildList().FirstChild());
657 anonKid->PaintSVG(aContext, aTransform, aImgParams);
660 SVGBBox SVGOuterSVGFrame::GetBBoxContribution(
661 const gfx::Matrix& aToBBoxUserspace, uint32_t aFlags) {
662 NS_ASSERTION(
663 PrincipalChildList().FirstChild()->IsSVGOuterSVGAnonChildFrame() &&
664 !PrincipalChildList().FirstChild()->GetNextSibling(),
665 "We should have a single, anonymous, child");
666 // We must defer to our child so that we don't include our
667 // content->PrependLocalTransformsTo() transforms.
668 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
669 PrincipalChildList().FirstChild());
670 return anonKid->GetBBoxContribution(aToBBoxUserspace, aFlags);
673 //----------------------------------------------------------------------
674 // SVGContainerFrame methods:
676 gfxMatrix SVGOuterSVGFrame::GetCanvasTM() {
677 if (!mCanvasTM) {
678 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
680 float devPxPerCSSPx = 1.0f / nsPresContext::AppUnitsToFloatCSSPixels(
681 PresContext()->AppUnitsPerDevPixel());
683 gfxMatrix tm = content->PrependLocalTransformsTo(
684 gfxMatrix::Scaling(devPxPerCSSPx, devPxPerCSSPx));
685 mCanvasTM = MakeUnique<gfxMatrix>(tm);
687 return *mCanvasTM;
690 //----------------------------------------------------------------------
691 // Implementation helpers
693 bool SVGOuterSVGFrame::IsRootOfImage() {
694 if (!mContent->GetParent()) {
695 // Our content is the document element
696 Document* doc = mContent->GetUncomposedDoc();
697 if (doc && doc->IsBeingUsedAsImage()) {
698 // Our document is being used as an image
699 return true;
703 return false;
706 bool SVGOuterSVGFrame::VerticalScrollbarNotNeeded() const {
707 const SVGAnimatedLength& height =
708 static_cast<SVGSVGElement*>(GetContent())
709 ->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
710 return height.IsPercentage() && height.GetBaseValInSpecifiedUnits() <= 100;
713 void SVGOuterSVGFrame::AppendDirectlyOwnedAnonBoxes(
714 nsTArray<OwnedAnonBox>& aResult) {
715 nsIFrame* anonKid = PrincipalChildList().FirstChild();
716 MOZ_ASSERT(anonKid->IsSVGOuterSVGAnonChildFrame());
717 aResult.AppendElement(OwnedAnonBox(anonKid));
720 void SVGOuterSVGFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder() {
721 MaybeSendIntrinsicSizeAndRatioToEmbedder(Some(GetIntrinsicSize()),
722 Some(GetAspectRatio()));
725 void SVGOuterSVGFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder(
726 Maybe<IntrinsicSize> aIntrinsicSize, Maybe<AspectRatio> aIntrinsicRatio) {
727 if (!mIsInObjectOrEmbed) {
728 return;
731 nsCOMPtr<nsIDocShell> docShell = PresContext()->GetDocShell();
732 if (!docShell) {
733 return;
736 BrowsingContext* bc = docShell->GetBrowsingContext();
737 MOZ_ASSERT(bc->IsContentSubframe());
739 if (bc->GetParent()->IsInProcess()) {
740 if (Element* embedder = bc->GetEmbedderElement()) {
741 if (nsCOMPtr<nsIObjectLoadingContent> olc = do_QueryInterface(embedder)) {
742 static_cast<nsObjectLoadingContent*>(olc.get())
743 ->SubdocumentIntrinsicSizeOrRatioChanged(aIntrinsicSize,
744 aIntrinsicRatio);
746 return;
750 if (BrowserChild* browserChild = BrowserChild::GetFrom(docShell)) {
751 Unused << browserChild->SendIntrinsicSizeOrRatioChanged(aIntrinsicSize,
752 aIntrinsicRatio);
756 void SVGOuterSVGFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
757 SVGDisplayContainerFrame::DidSetComputedStyle(aOldComputedStyle);
759 if (!aOldComputedStyle) {
760 return;
763 if (aOldComputedStyle->StylePosition()->mAspectRatio !=
764 StylePosition()->mAspectRatio) {
765 // Our aspect-ratio property value changed, and an embedding <object> or
766 // <embed> might care about that.
767 MaybeSendIntrinsicSizeAndRatioToEmbedder();
771 void SVGOuterSVGFrame::Destroy(DestroyContext& aContext) {
772 // This handles both the case when the root <svg> element is made display:none
773 // (and thus loses its intrinsic size and aspect ratio), and when the frame
774 // is navigated elsewhere & we need to reset parent <object>/<embed>'s
775 // recorded intrinsic size/ratio values.
776 MaybeSendIntrinsicSizeAndRatioToEmbedder(Nothing(), Nothing());
778 SVGDisplayContainerFrame::Destroy(aContext);
781 } // namespace mozilla
783 //----------------------------------------------------------------------
784 // Implementation of SVGOuterSVGAnonChildFrame
786 nsContainerFrame* NS_NewSVGOuterSVGAnonChildFrame(
787 mozilla::PresShell* aPresShell, mozilla::ComputedStyle* aStyle) {
788 return new (aPresShell)
789 mozilla::SVGOuterSVGAnonChildFrame(aStyle, aPresShell->GetPresContext());
792 namespace mozilla {
794 NS_IMPL_FRAMEARENA_HELPERS(SVGOuterSVGAnonChildFrame)
796 #ifdef DEBUG
797 void SVGOuterSVGAnonChildFrame::Init(nsIContent* aContent,
798 nsContainerFrame* aParent,
799 nsIFrame* aPrevInFlow) {
800 MOZ_ASSERT(aParent->IsSVGOuterSVGFrame(), "Unexpected parent");
801 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
803 #endif
805 void SVGOuterSVGAnonChildFrame::BuildDisplayList(
806 nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
807 // Wrap our contents into an nsDisplaySVGWrapper.
808 // We wrap this frame instead of the SVGOuterSVGFrame so that the wrapper
809 // doesn't contain the <svg> element's CSS styles, like backgrounds or
810 // borders. Creating the nsDisplaySVGWrapper here also means that it'll be
811 // inside the nsDisplayTransform for our viewbox transform. The
812 // nsDisplaySVGWrapper's reference frame is this frame, because this frame
813 // always returns true from IsSVGTransformed.
814 nsDisplayList newList(aBuilder);
815 nsDisplayListSet set(&newList, &newList, &newList, &newList, &newList,
816 &newList);
817 BuildDisplayListForNonBlockChildren(aBuilder, set);
818 aLists.Content()->AppendNewToTop<nsDisplaySVGWrapper>(aBuilder, this,
819 &newList);
822 static Matrix ComputeOuterSVGAnonChildFrameTransform(
823 const SVGOuterSVGAnonChildFrame* aFrame) {
824 // Our elements 'transform' attribute is applied to our SVGOuterSVGFrame
825 // parent, and the element's children-only transforms are applied to us, the
826 // anonymous child frame. Since we are the child frame, we apply the
827 // children-only transforms as if they are our own transform.
828 SVGSVGElement* content = static_cast<SVGSVGElement*>(aFrame->GetContent());
830 if (!content->HasChildrenOnlyTransform()) {
831 return Matrix();
834 // Outer-<svg> doesn't use x/y, so we can pass eChildToUserSpace here.
835 gfxMatrix ownMatrix =
836 content->PrependLocalTransformsTo(gfxMatrix(), eChildToUserSpace);
838 if (ownMatrix.HasNonTranslation()) {
839 // viewBox, currentScale and currentTranslate should only produce a
840 // rectilinear transform.
841 MOZ_ASSERT(ownMatrix.IsRectilinear(),
842 "Non-rectilinear transform will break the following logic");
844 // The nsDisplayTransform code will apply this transform to our frame,
845 // including to our frame position. We don't want our frame position to
846 // be scaled though, so we need to correct for that in the transform.
847 // XXX Yeah, this is a bit hacky.
848 CSSPoint pos = CSSPixel::FromAppUnits(aFrame->GetPosition());
849 CSSPoint scaledPos = CSSPoint(ownMatrix._11 * pos.x, ownMatrix._22 * pos.y);
850 CSSPoint deltaPos = scaledPos - pos;
851 ownMatrix *= gfxMatrix::Translation(-deltaPos.x, -deltaPos.y);
854 return gfx::ToMatrix(ownMatrix);
857 // We want this frame to be a reference frame. An easy way to achieve that is
858 // to always return true from this method, even for identity transforms.
859 // This frame being a reference frame ensures that the offset between this
860 // <svg> element and the parent reference frame is completely absorbed by the
861 // nsDisplayTransform that's created for this frame, and that this offset does
862 // not affect our descendants' transforms. Consequently, if the <svg> element
863 // moves, e.g. during scrolling, the transform matrices of our contents are
864 // unaffected. This simplifies invalidation.
865 bool SVGOuterSVGAnonChildFrame::IsSVGTransformed(
866 Matrix* aOwnTransform, Matrix* aFromParentTransform) const {
867 if (aOwnTransform) {
868 *aOwnTransform = ComputeOuterSVGAnonChildFrameTransform(this);
871 return true;
874 } // namespace mozilla