no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / layout / svg / SVGOuterSVGFrame.cpp
bloba43e6815cdb69a7987227cd10a625b756d2ea904
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 containAxes.ContainIntrinsicSize(IntrinsicSize(0, 0), *this);
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 containAxes.ContainIntrinsicSize(intrinsicSize, *this);
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 aDesiredSize.Width() =
338 aReflowInput.ComputedWidth() +
339 aReflowInput.ComputedPhysicalBorderPadding().LeftRight();
340 aDesiredSize.Height() =
341 aReflowInput.ComputedHeight() +
342 aReflowInput.ComputedPhysicalBorderPadding().TopBottom();
344 NS_ASSERTION(!GetPrevInFlow(), "SVG can't currently be broken across pages.");
346 SVGSVGElement* svgElem = static_cast<SVGSVGElement*>(GetContent());
348 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
349 PrincipalChildList().FirstChild());
351 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
352 // Initialize
353 svgElem->UpdateHasChildrenOnlyTransform();
356 // If our SVG viewport has changed, update our content and notify.
357 // http://www.w3.org/TR/SVG11/coords.html#ViewportSpace
359 svgFloatSize newViewportSize(
360 nsPresContext::AppUnitsToFloatCSSPixels(aReflowInput.ComputedWidth()),
361 nsPresContext::AppUnitsToFloatCSSPixels(aReflowInput.ComputedHeight()));
363 svgFloatSize oldViewportSize = svgElem->GetViewportSize();
365 uint32_t changeBits = 0;
366 if (newViewportSize != oldViewportSize) {
367 // When our viewport size changes, we may need to update the overflow rects
368 // of our child frames. This is the case if:
370 // * We have a real/synthetic viewBox (a children-only transform), since
371 // the viewBox transform will change as the viewport dimensions change.
373 // * We do not have a real/synthetic viewBox, but the last time we
374 // reflowed (or the last time UpdateOverflow() was called) we did.
376 // We only handle the former case here, in which case we mark all our child
377 // frames as dirty so that we reflow them below and update their overflow
378 // rects.
380 // In the latter case, updating of overflow rects is handled for removal of
381 // real viewBox (the viewBox attribute) in AttributeChanged. Synthetic
382 // viewBox "removal" (e.g. a document references the same SVG via both an
383 // <svg:image> and then as a CSS background image (a synthetic viewBox is
384 // used when painting the former, but not when painting the latter)) is
385 // handled in SVGSVGElement::FlushImageTransformInvalidation.
387 if (svgElem->HasViewBoxOrSyntheticViewBox()) {
388 nsIFrame* anonChild = PrincipalChildList().FirstChild();
389 anonChild->MarkSubtreeDirty();
390 for (nsIFrame* child : anonChild->PrincipalChildList()) {
391 child->MarkSubtreeDirty();
394 changeBits |= COORD_CONTEXT_CHANGED;
395 svgElem->SetViewportSize(newViewportSize);
397 if (mIsRootContent && !mIsInIframe) {
398 const auto oldZoom = mFullZoom;
399 mFullZoom = ComputeFullZoom();
400 if (oldZoom != mFullZoom) {
401 changeBits |= FULL_ZOOM_CHANGED;
404 if (changeBits && !HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
405 NotifyViewportOrTransformChanged(changeBits);
408 // Now that we've marked the necessary children as dirty, call
409 // ReflowSVG() or ReflowSVGNonDisplayText() on them, depending
410 // on whether we are non-display.
411 mCallingReflowSVG = true;
412 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
413 ReflowSVGNonDisplayText(this);
414 } else {
415 // Update the mRects and ink overflow rects of all our descendants,
416 // including our anonymous wrapper kid:
417 anonKid->ReflowSVG();
418 MOZ_ASSERT(!anonKid->GetNextSibling(),
419 "We should have one anonymous child frame wrapping our real "
420 "children");
422 mCallingReflowSVG = false;
424 // Set our anonymous kid's offset from our border box:
425 anonKid->SetPosition(GetContentRectRelativeToSelf().TopLeft());
427 // Including our size in our overflow rects regardless of the value of
428 // 'background', 'border', etc. makes sure that we usually (when we clip to
429 // our content area) don't have to keep changing our overflow rects as our
430 // descendants move about (see perf comment below). Including our size in our
431 // scrollable overflow rect also makes sure that we scroll if we're too big
432 // for our viewport.
434 // <svg> never allows scrolling to anything outside its mRect (only panning),
435 // so we must always keep our scrollable overflow set to our size.
437 // With regards to ink overflow, we always clip root-<svg> (see our
438 // BuildDisplayList method) regardless of the value of the 'overflow'
439 // property since that is per-spec, even for the initial 'visible' value. For
440 // that reason there's no point in adding descendant ink overflow to our
441 // own when this frame is for a root-<svg>. That said, there's also a very
442 // good performance reason for us wanting to avoid doing so. If we did, then
443 // the frame's overflow would often change as descendants that are partially
444 // or fully outside its rect moved (think animation on/off screen), and that
445 // would cause us to do a full NS_FRAME_IS_DIRTY reflow and repaint of the
446 // entire document tree each such move (see bug 875175).
448 // So it's only non-root outer-<svg> that has the ink overflow of its
449 // descendants added to its own. (Note that the default user-agent style
450 // sheet makes 'hidden' the default value for :not(root(svg)), so usually
451 // FinishAndStoreOverflow will still clip this back to the frame's rect.)
453 // WARNING!! Keep UpdateBounds below in sync with whatever we do for our
454 // overflow rects here! (Again, see bug 875175.)
456 aDesiredSize.SetOverflowAreasToDesiredBounds();
458 // An outer SVG will be here as a nondisplay if it fails the conditional
459 // processing test. In that case, we don't maintain its overflow.
460 if (!HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
461 if (!mIsRootContent) {
462 aDesiredSize.mOverflowAreas.InkOverflow().UnionRect(
463 aDesiredSize.mOverflowAreas.InkOverflow(),
464 anonKid->InkOverflowRect() + anonKid->GetPosition());
466 FinishAndStoreOverflow(&aDesiredSize);
469 NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS,
470 ("exit SVGOuterSVGFrame::Reflow: size=%d,%d",
471 aDesiredSize.Width(), aDesiredSize.Height()));
474 void SVGOuterSVGFrame::DidReflow(nsPresContext* aPresContext,
475 const ReflowInput* aReflowInput) {
476 SVGDisplayContainerFrame::DidReflow(aPresContext, aReflowInput);
478 // Make sure elements styled by :hover get updated if script/animation moves
479 // them under or out from under the pointer:
480 PresShell()->SynthesizeMouseMove(false);
483 /* virtual */
484 void SVGOuterSVGFrame::UnionChildOverflow(OverflowAreas& aOverflowAreas) {
485 // See the comments in Reflow above.
487 // WARNING!! Keep this in sync with Reflow above!
489 if (!mIsRootContent) {
490 nsIFrame* anonKid = PrincipalChildList().FirstChild();
491 aOverflowAreas.InkOverflow().UnionRect(
492 aOverflowAreas.InkOverflow(),
493 anonKid->InkOverflowRect() + anonKid->GetPosition());
497 //----------------------------------------------------------------------
498 // container methods
500 nsresult SVGOuterSVGFrame::AttributeChanged(int32_t aNameSpaceID,
501 nsAtom* aAttribute,
502 int32_t aModType) {
503 if (aNameSpaceID == kNameSpaceID_None &&
504 !HasAnyStateBits(NS_FRAME_FIRST_REFLOW | NS_FRAME_IS_NONDISPLAY)) {
505 if (aAttribute == nsGkAtoms::viewBox ||
506 aAttribute == nsGkAtoms::preserveAspectRatio ||
507 aAttribute == nsGkAtoms::transform) {
508 // make sure our cached transform matrix gets (lazily) updated
509 mCanvasTM = nullptr;
511 SVGUtils::NotifyChildrenOfSVGChange(
512 PrincipalChildList().FirstChild(),
513 aAttribute == nsGkAtoms::viewBox
514 ? TRANSFORM_CHANGED | COORD_CONTEXT_CHANGED
515 : TRANSFORM_CHANGED);
517 if (aAttribute != nsGkAtoms::transform) {
518 static_cast<SVGSVGElement*>(GetContent())
519 ->ChildrenOnlyTransformChanged();
522 if (aAttribute == nsGkAtoms::width || aAttribute == nsGkAtoms::height ||
523 aAttribute == nsGkAtoms::viewBox) {
524 // Don't call ChildrenOnlyTransformChanged() here, since we call it
525 // under Reflow if the width/height/viewBox actually changed.
527 MaybeSendIntrinsicSizeAndRatioToEmbedder();
529 if (!mIsInObjectOrEmbed) {
530 // We are not embedded by reference, so our 'width' and 'height'
531 // attributes are not overridden (and viewBox may influence our
532 // intrinsic aspect ratio). We need to reflow.
533 PresShell()->FrameNeedsReflow(
534 this, IntrinsicDirty::FrameAncestorsAndDescendants,
535 NS_FRAME_IS_DIRTY);
540 return NS_OK;
543 bool SVGOuterSVGFrame::IsSVGTransformed(Matrix* aOwnTransform,
544 Matrix* aFromParentTransform) const {
545 // Our anonymous child's HasChildrenOnlyTransform() implementation makes sure
546 // our children-only transforms are applied to our children. We only care
547 // about transforms that transform our own frame here.
549 bool foundTransform = false;
551 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
552 SVGAnimatedTransformList* transformList = content->GetAnimatedTransformList();
553 if ((transformList && transformList->HasTransform()) ||
554 content->GetAnimateMotionTransform()) {
555 if (aOwnTransform) {
556 *aOwnTransform = gfx::ToMatrix(
557 content->PrependLocalTransformsTo(gfxMatrix(), eUserSpaceToParent));
559 foundTransform = true;
562 return foundTransform;
565 //----------------------------------------------------------------------
566 // painting
568 void SVGOuterSVGFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
569 const nsDisplayListSet& aLists) {
570 if (HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
571 return;
574 DisplayBorderBackgroundOutline(aBuilder, aLists);
576 nsRect visibleRect = aBuilder->GetVisibleRect();
577 nsRect dirtyRect = aBuilder->GetDirtyRect();
579 // Per-spec, we always clip root-<svg> even when 'overflow' has its initial
580 // value of 'visible'. See also the "ink overflow" comments in Reflow.
581 DisplayListClipState::AutoSaveRestore autoSR(aBuilder);
582 if (mIsRootContent || StyleDisplay()->IsScrollableOverflow()) {
583 autoSR.ClipContainingBlockDescendantsToContentBox(aBuilder, this);
584 visibleRect = visibleRect.Intersect(GetContentRectRelativeToSelf());
585 dirtyRect = dirtyRect.Intersect(GetContentRectRelativeToSelf());
588 nsDisplayListBuilder::AutoBuildingDisplayList building(
589 aBuilder, this, visibleRect, dirtyRect);
591 nsDisplayList* contentList = aLists.Content();
592 nsDisplayListSet set(contentList, contentList, contentList, contentList,
593 contentList, contentList);
594 BuildDisplayListForNonBlockChildren(aBuilder, set);
597 //----------------------------------------------------------------------
598 // ISVGSVGFrame methods:
600 void SVGOuterSVGFrame::NotifyViewportOrTransformChanged(uint32_t aFlags) {
601 MOZ_ASSERT(aFlags && !(aFlags & ~(COORD_CONTEXT_CHANGED | TRANSFORM_CHANGED |
602 FULL_ZOOM_CHANGED)),
603 "Unexpected aFlags value");
605 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
607 if (aFlags & COORD_CONTEXT_CHANGED) {
608 if (content->HasViewBox()) {
609 // Percentage lengths on children resolve against the viewBox rect so we
610 // don't need to notify them of the viewport change, but the viewBox
611 // transform will have changed, so we need to notify them of that instead.
612 aFlags = TRANSFORM_CHANGED;
613 } else if (content->ShouldSynthesizeViewBox()) {
614 // In the case of a synthesized viewBox, the synthetic viewBox's rect
615 // changes as the viewport changes. As a result we need to maintain the
616 // COORD_CONTEXT_CHANGED flag.
617 aFlags |= TRANSFORM_CHANGED;
618 } else if (mCanvasTM && mCanvasTM->IsSingular()) {
619 // A width/height of zero will result in us having a singular mCanvasTM
620 // even when we don't have a viewBox. So we also want to recompute our
621 // mCanvasTM for this width/height change even though we don't have a
622 // viewBox.
623 aFlags |= TRANSFORM_CHANGED;
627 bool haveNonFulLZoomTransformChange = (aFlags & TRANSFORM_CHANGED);
629 if (aFlags & FULL_ZOOM_CHANGED) {
630 // Convert FULL_ZOOM_CHANGED to TRANSFORM_CHANGED:
631 aFlags = (aFlags & ~FULL_ZOOM_CHANGED) | TRANSFORM_CHANGED;
634 if (aFlags & TRANSFORM_CHANGED) {
635 // Make sure our canvas transform matrix gets (lazily) recalculated:
636 mCanvasTM = nullptr;
638 if (haveNonFulLZoomTransformChange &&
639 !HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
640 uint32_t flags = HasAnyStateBits(NS_FRAME_IN_REFLOW)
641 ? SVGSVGElement::eDuringReflow
642 : 0;
643 content->ChildrenOnlyTransformChanged(flags);
647 SVGUtils::NotifyChildrenOfSVGChange(PrincipalChildList().FirstChild(),
648 aFlags);
651 //----------------------------------------------------------------------
652 // ISVGDisplayableFrame methods:
654 void SVGOuterSVGFrame::PaintSVG(gfxContext& aContext,
655 const gfxMatrix& aTransform,
656 imgDrawingParams& aImgParams) {
657 NS_ASSERTION(
658 PrincipalChildList().FirstChild()->IsSVGOuterSVGAnonChildFrame() &&
659 !PrincipalChildList().FirstChild()->GetNextSibling(),
660 "We should have a single, anonymous, child");
661 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
662 PrincipalChildList().FirstChild());
663 anonKid->PaintSVG(aContext, aTransform, aImgParams);
666 SVGBBox SVGOuterSVGFrame::GetBBoxContribution(
667 const gfx::Matrix& aToBBoxUserspace, uint32_t aFlags) {
668 NS_ASSERTION(
669 PrincipalChildList().FirstChild()->IsSVGOuterSVGAnonChildFrame() &&
670 !PrincipalChildList().FirstChild()->GetNextSibling(),
671 "We should have a single, anonymous, child");
672 // We must defer to our child so that we don't include our
673 // content->PrependLocalTransformsTo() transforms.
674 auto* anonKid = static_cast<SVGOuterSVGAnonChildFrame*>(
675 PrincipalChildList().FirstChild());
676 return anonKid->GetBBoxContribution(aToBBoxUserspace, aFlags);
679 //----------------------------------------------------------------------
680 // SVGContainerFrame methods:
682 gfxMatrix SVGOuterSVGFrame::GetCanvasTM() {
683 if (!mCanvasTM) {
684 SVGSVGElement* content = static_cast<SVGSVGElement*>(GetContent());
686 float devPxPerCSSPx = 1.0f / nsPresContext::AppUnitsToFloatCSSPixels(
687 PresContext()->AppUnitsPerDevPixel());
689 gfxMatrix tm = content->PrependLocalTransformsTo(
690 gfxMatrix::Scaling(devPxPerCSSPx, devPxPerCSSPx));
691 mCanvasTM = MakeUnique<gfxMatrix>(tm);
693 return *mCanvasTM;
696 //----------------------------------------------------------------------
697 // Implementation helpers
699 bool SVGOuterSVGFrame::IsRootOfImage() {
700 if (!mContent->GetParent()) {
701 // Our content is the document element
702 Document* doc = mContent->GetUncomposedDoc();
703 if (doc && doc->IsBeingUsedAsImage()) {
704 // Our document is being used as an image
705 return true;
709 return false;
712 bool SVGOuterSVGFrame::VerticalScrollbarNotNeeded() const {
713 const SVGAnimatedLength& height =
714 static_cast<SVGSVGElement*>(GetContent())
715 ->mLengthAttributes[SVGSVGElement::ATTR_HEIGHT];
716 return height.IsPercentage() && height.GetBaseValInSpecifiedUnits() <= 100;
719 void SVGOuterSVGFrame::AppendDirectlyOwnedAnonBoxes(
720 nsTArray<OwnedAnonBox>& aResult) {
721 nsIFrame* anonKid = PrincipalChildList().FirstChild();
722 MOZ_ASSERT(anonKid->IsSVGOuterSVGAnonChildFrame());
723 aResult.AppendElement(OwnedAnonBox(anonKid));
726 void SVGOuterSVGFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder() {
727 MaybeSendIntrinsicSizeAndRatioToEmbedder(Some(GetIntrinsicSize()),
728 Some(GetAspectRatio()));
731 void SVGOuterSVGFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder(
732 Maybe<IntrinsicSize> aIntrinsicSize, Maybe<AspectRatio> aIntrinsicRatio) {
733 if (!mIsInObjectOrEmbed) {
734 return;
737 nsCOMPtr<nsIDocShell> docShell = PresContext()->GetDocShell();
738 if (!docShell) {
739 return;
742 BrowsingContext* bc = docShell->GetBrowsingContext();
743 MOZ_ASSERT(bc->IsContentSubframe());
745 if (bc->GetParent()->IsInProcess()) {
746 if (Element* embedder = bc->GetEmbedderElement()) {
747 if (nsCOMPtr<nsIObjectLoadingContent> olc = do_QueryInterface(embedder)) {
748 static_cast<nsObjectLoadingContent*>(olc.get())
749 ->SubdocumentIntrinsicSizeOrRatioChanged(aIntrinsicSize,
750 aIntrinsicRatio);
752 return;
756 if (BrowserChild* browserChild = BrowserChild::GetFrom(docShell)) {
757 Unused << browserChild->SendIntrinsicSizeOrRatioChanged(aIntrinsicSize,
758 aIntrinsicRatio);
762 void SVGOuterSVGFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
763 SVGDisplayContainerFrame::DidSetComputedStyle(aOldComputedStyle);
765 if (!aOldComputedStyle) {
766 return;
769 if (aOldComputedStyle->StylePosition()->mAspectRatio !=
770 StylePosition()->mAspectRatio) {
771 // Our aspect-ratio property value changed, and an embedding <object> or
772 // <embed> might care about that.
773 MaybeSendIntrinsicSizeAndRatioToEmbedder();
777 void SVGOuterSVGFrame::Destroy(DestroyContext& aContext) {
778 // This handles both the case when the root <svg> element is made display:none
779 // (and thus loses its intrinsic size and aspect ratio), and when the frame
780 // is navigated elsewhere & we need to reset parent <object>/<embed>'s
781 // recorded intrinsic size/ratio values.
782 MaybeSendIntrinsicSizeAndRatioToEmbedder(Nothing(), Nothing());
784 SVGDisplayContainerFrame::Destroy(aContext);
787 } // namespace mozilla
789 //----------------------------------------------------------------------
790 // Implementation of SVGOuterSVGAnonChildFrame
792 nsContainerFrame* NS_NewSVGOuterSVGAnonChildFrame(
793 mozilla::PresShell* aPresShell, mozilla::ComputedStyle* aStyle) {
794 return new (aPresShell)
795 mozilla::SVGOuterSVGAnonChildFrame(aStyle, aPresShell->GetPresContext());
798 namespace mozilla {
800 NS_IMPL_FRAMEARENA_HELPERS(SVGOuterSVGAnonChildFrame)
802 #ifdef DEBUG
803 void SVGOuterSVGAnonChildFrame::Init(nsIContent* aContent,
804 nsContainerFrame* aParent,
805 nsIFrame* aPrevInFlow) {
806 MOZ_ASSERT(aParent->IsSVGOuterSVGFrame(), "Unexpected parent");
807 SVGDisplayContainerFrame::Init(aContent, aParent, aPrevInFlow);
809 #endif
811 void SVGOuterSVGAnonChildFrame::BuildDisplayList(
812 nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
813 // Wrap our contents into an nsDisplaySVGWrapper.
814 // We wrap this frame instead of the SVGOuterSVGFrame so that the wrapper
815 // doesn't contain the <svg> element's CSS styles, like backgrounds or
816 // borders. Creating the nsDisplaySVGWrapper here also means that it'll be
817 // inside the nsDisplayTransform for our viewbox transform. The
818 // nsDisplaySVGWrapper's reference frame is this frame, because this frame
819 // always returns true from IsSVGTransformed.
820 nsDisplayList newList(aBuilder);
821 nsDisplayListSet set(&newList, &newList, &newList, &newList, &newList,
822 &newList);
823 BuildDisplayListForNonBlockChildren(aBuilder, set);
824 aLists.Content()->AppendNewToTop<nsDisplaySVGWrapper>(aBuilder, this,
825 &newList);
828 static Matrix ComputeOuterSVGAnonChildFrameTransform(
829 const SVGOuterSVGAnonChildFrame* aFrame) {
830 // Our elements 'transform' attribute is applied to our SVGOuterSVGFrame
831 // parent, and the element's children-only transforms are applied to us, the
832 // anonymous child frame. Since we are the child frame, we apply the
833 // children-only transforms as if they are our own transform.
834 SVGSVGElement* content = static_cast<SVGSVGElement*>(aFrame->GetContent());
836 if (!content->HasChildrenOnlyTransform()) {
837 return Matrix();
840 // Outer-<svg> doesn't use x/y, so we can pass eChildToUserSpace here.
841 gfxMatrix ownMatrix =
842 content->PrependLocalTransformsTo(gfxMatrix(), eChildToUserSpace);
844 if (ownMatrix.HasNonTranslation()) {
845 // viewBox, currentScale and currentTranslate should only produce a
846 // rectilinear transform.
847 MOZ_ASSERT(ownMatrix.IsRectilinear(),
848 "Non-rectilinear transform will break the following logic");
850 // The nsDisplayTransform code will apply this transform to our frame,
851 // including to our frame position. We don't want our frame position to
852 // be scaled though, so we need to correct for that in the transform.
853 // XXX Yeah, this is a bit hacky.
854 CSSPoint pos = CSSPixel::FromAppUnits(aFrame->GetPosition());
855 CSSPoint scaledPos = CSSPoint(ownMatrix._11 * pos.x, ownMatrix._22 * pos.y);
856 CSSPoint deltaPos = scaledPos - pos;
857 ownMatrix *= gfxMatrix::Translation(-deltaPos.x, -deltaPos.y);
860 return gfx::ToMatrix(ownMatrix);
863 // We want this frame to be a reference frame. An easy way to achieve that is
864 // to always return true from this method, even for identity transforms.
865 // This frame being a reference frame ensures that the offset between this
866 // <svg> element and the parent reference frame is completely absorbed by the
867 // nsDisplayTransform that's created for this frame, and that this offset does
868 // not affect our descendants' transforms. Consequently, if the <svg> element
869 // moves, e.g. during scrolling, the transform matrices of our contents are
870 // unaffected. This simplifies invalidation.
871 bool SVGOuterSVGAnonChildFrame::IsSVGTransformed(
872 Matrix* aOwnTransform, Matrix* aFromParentTransform) const {
873 if (aOwnTransform) {
874 *aOwnTransform = ComputeOuterSVGAnonChildFrameTransform(this);
877 return true;
880 } // namespace mozilla