Bug 1682766 [wpt PR 26921] - Fix nullptr dereference accessing PolicyContainer in...
[gecko.git] / image / VectorImage.cpp
blob68a2b2287816dde80e8a9e3ff5761e8040cbaed3
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 #include "VectorImage.h"
8 #include "gfx2DGlue.h"
9 #include "gfxContext.h"
10 #include "gfxDrawable.h"
11 #include "gfxPlatform.h"
12 #include "gfxUtils.h"
13 #include "imgFrame.h"
14 #include "mozilla/AutoRestore.h"
15 #include "mozilla/MemoryReporting.h"
16 #include "mozilla/MediaFeatureChange.h"
17 #include "mozilla/dom/Event.h"
18 #include "mozilla/dom/SVGSVGElement.h"
19 #include "mozilla/dom/SVGDocument.h"
20 #include "mozilla/gfx/2D.h"
21 #include "mozilla/gfx/gfxVars.h"
22 #include "mozilla/PendingAnimationTracker.h"
23 #include "mozilla/PresShell.h"
24 #include "mozilla/RefPtr.h"
25 #include "mozilla/SVGObserverUtils.h" // for SVGRenderingObserver
26 #include "mozilla/Tuple.h"
27 #include "nsIStreamListener.h"
28 #include "nsMimeTypes.h"
29 #include "nsPresContext.h"
30 #include "nsRect.h"
31 #include "nsString.h"
32 #include "nsStubDocumentObserver.h"
33 #include "nsWindowSizes.h"
34 #include "ImageRegion.h"
35 #include "ISurfaceProvider.h"
36 #include "LookupResult.h"
37 #include "Orientation.h"
38 #include "SVGDocumentWrapper.h"
39 #include "SVGDrawingParameters.h"
40 #include "nsIDOMEventListener.h"
41 #include "SurfaceCache.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/DocumentInlines.h"
45 namespace mozilla {
47 using namespace dom;
48 using namespace dom::SVGPreserveAspectRatio_Binding;
49 using namespace gfx;
50 using namespace layers;
52 namespace image {
54 // Helper-class: SVGRootRenderingObserver
55 class SVGRootRenderingObserver final : public SVGRenderingObserver {
56 public:
57 NS_DECL_ISUPPORTS
59 SVGRootRenderingObserver(SVGDocumentWrapper* aDocWrapper,
60 VectorImage* aVectorImage)
61 : SVGRenderingObserver(),
62 mDocWrapper(aDocWrapper),
63 mVectorImage(aVectorImage),
64 mHonoringInvalidations(true) {
65 MOZ_ASSERT(mDocWrapper, "Need a non-null SVG document wrapper");
66 MOZ_ASSERT(mVectorImage, "Need a non-null VectorImage");
68 StartObserving();
69 Element* elem = GetReferencedElementWithoutObserving();
70 MOZ_ASSERT(elem, "no root SVG node for us to observe");
72 SVGObserverUtils::AddRenderingObserver(elem, this);
73 mInObserverSet = true;
76 void ResumeHonoringInvalidations() { mHonoringInvalidations = true; }
78 protected:
79 virtual ~SVGRootRenderingObserver() {
80 // This needs to call our GetReferencedElementWithoutObserving override,
81 // so must be called here rather than in our base class's dtor.
82 StopObserving();
85 Element* GetReferencedElementWithoutObserving() final {
86 return mDocWrapper->GetRootSVGElem();
89 virtual void OnRenderingChange() override {
90 Element* elem = GetReferencedElementWithoutObserving();
91 MOZ_ASSERT(elem, "missing root SVG node");
93 if (mHonoringInvalidations && !mDocWrapper->ShouldIgnoreInvalidation()) {
94 nsIFrame* frame = elem->GetPrimaryFrame();
95 if (!frame || frame->PresShell()->IsDestroying()) {
96 // We're being destroyed. Bail out.
97 return;
100 // Ignore further invalidations until we draw.
101 mHonoringInvalidations = false;
103 mVectorImage->InvalidateObserversOnNextRefreshDriverTick();
106 // Our caller might've removed us from rendering-observer list.
107 // Add ourselves back!
108 if (!mInObserverSet) {
109 SVGObserverUtils::AddRenderingObserver(elem, this);
110 mInObserverSet = true;
114 // Private data
115 const RefPtr<SVGDocumentWrapper> mDocWrapper;
116 VectorImage* const mVectorImage; // Raw pointer because it owns me.
117 bool mHonoringInvalidations;
120 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver, nsIMutationObserver)
122 class SVGParseCompleteListener final : public nsStubDocumentObserver {
123 public:
124 NS_DECL_ISUPPORTS
126 SVGParseCompleteListener(SVGDocument* aDocument, VectorImage* aImage)
127 : mDocument(aDocument), mImage(aImage) {
128 MOZ_ASSERT(mDocument, "Need an SVG document");
129 MOZ_ASSERT(mImage, "Need an image");
131 mDocument->AddObserver(this);
134 private:
135 ~SVGParseCompleteListener() {
136 if (mDocument) {
137 // The document must have been destroyed before we got our event.
138 // Otherwise this can't happen, since documents hold strong references to
139 // their observers.
140 Cancel();
144 public:
145 void EndLoad(Document* aDocument) override {
146 MOZ_ASSERT(aDocument == mDocument, "Got EndLoad for wrong document?");
148 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
149 // we stick around long enough to complete our work.
150 RefPtr<SVGParseCompleteListener> kungFuDeathGrip(this);
152 mImage->OnSVGDocumentParsed();
155 void Cancel() {
156 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
157 if (mDocument) {
158 mDocument->RemoveObserver(this);
159 mDocument = nullptr;
163 private:
164 RefPtr<SVGDocument> mDocument;
165 VectorImage* const mImage; // Raw pointer to owner.
168 NS_IMPL_ISUPPORTS(SVGParseCompleteListener, nsIDocumentObserver)
170 class SVGLoadEventListener final : public nsIDOMEventListener {
171 public:
172 NS_DECL_ISUPPORTS
174 SVGLoadEventListener(Document* aDocument, VectorImage* aImage)
175 : mDocument(aDocument), mImage(aImage) {
176 MOZ_ASSERT(mDocument, "Need an SVG document");
177 MOZ_ASSERT(mImage, "Need an image");
179 mDocument->AddEventListener(u"MozSVGAsImageDocumentLoad"_ns, this, true,
180 false);
183 private:
184 ~SVGLoadEventListener() {
185 if (mDocument) {
186 // The document must have been destroyed before we got our event.
187 // Otherwise this can't happen, since documents hold strong references to
188 // their observers.
189 Cancel();
193 public:
194 NS_IMETHOD HandleEvent(Event* aEvent) override {
195 MOZ_ASSERT(mDocument, "Need an SVG document. Received multiple events?");
197 // OnSVGDocumentLoaded will release our owner's reference
198 // to us, so ensure we stick around long enough to complete our work.
199 RefPtr<SVGLoadEventListener> kungFuDeathGrip(this);
201 #ifdef DEBUG
202 nsAutoString eventType;
203 aEvent->GetType(eventType);
204 MOZ_ASSERT(eventType.EqualsLiteral("MozSVGAsImageDocumentLoad"),
205 "Received unexpected event");
206 #endif
208 mImage->OnSVGDocumentLoaded();
210 return NS_OK;
213 void Cancel() {
214 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
215 if (mDocument) {
216 mDocument->RemoveEventListener(u"MozSVGAsImageDocumentLoad"_ns, this,
217 true);
218 mDocument = nullptr;
222 private:
223 nsCOMPtr<Document> mDocument;
224 VectorImage* const mImage; // Raw pointer to owner.
227 NS_IMPL_ISUPPORTS(SVGLoadEventListener, nsIDOMEventListener)
229 // Helper-class: SVGDrawingCallback
230 class SVGDrawingCallback : public gfxDrawingCallback {
231 public:
232 SVGDrawingCallback(SVGDocumentWrapper* aSVGDocumentWrapper,
233 const IntSize& aViewportSize, const IntSize& aSize,
234 uint32_t aImageFlags)
235 : mSVGDocumentWrapper(aSVGDocumentWrapper),
236 mViewportSize(aViewportSize),
237 mSize(aSize),
238 mImageFlags(aImageFlags) {}
239 virtual bool operator()(gfxContext* aContext, const gfxRect& aFillRect,
240 const SamplingFilter aSamplingFilter,
241 const gfxMatrix& aTransform) override;
243 private:
244 RefPtr<SVGDocumentWrapper> mSVGDocumentWrapper;
245 const IntSize mViewportSize;
246 const IntSize mSize;
247 uint32_t mImageFlags;
250 // Based loosely on SVGIntegrationUtils' PaintFrameCallback::operator()
251 bool SVGDrawingCallback::operator()(gfxContext* aContext,
252 const gfxRect& aFillRect,
253 const SamplingFilter aSamplingFilter,
254 const gfxMatrix& aTransform) {
255 MOZ_ASSERT(mSVGDocumentWrapper, "need an SVGDocumentWrapper");
257 // Get (& sanity-check) the helper-doc's presShell
258 RefPtr<PresShell> presShell = mSVGDocumentWrapper->GetPresShell();
259 MOZ_ASSERT(presShell, "GetPresShell returned null for an SVG image?");
261 #ifdef MOZ_GECKO_PROFILER
262 Document* doc = presShell->GetDocument();
263 nsIURI* uri = doc ? doc->GetDocumentURI() : nullptr;
264 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
265 "SVG Image drawing", GRAPHICS,
266 nsPrintfCString("%dx%d %s", mSize.width, mSize.height,
267 uri ? uri->GetSpecOrDefault().get() : "N/A"));
268 #endif
270 gfxContextAutoSaveRestore contextRestorer(aContext);
272 // Clip to aFillRect so that we don't paint outside.
273 aContext->NewPath();
274 aContext->Rectangle(aFillRect);
275 aContext->Clip();
277 gfxMatrix matrix = aTransform;
278 if (!matrix.Invert()) {
279 return false;
281 aContext->SetMatrixDouble(
282 aContext->CurrentMatrixDouble().PreMultiply(matrix).PreScale(
283 double(mSize.width) / mViewportSize.width,
284 double(mSize.height) / mViewportSize.height));
286 nsPresContext* presContext = presShell->GetPresContext();
287 MOZ_ASSERT(presContext, "pres shell w/out pres context");
289 nsRect svgRect(0, 0, presContext->DevPixelsToAppUnits(mViewportSize.width),
290 presContext->DevPixelsToAppUnits(mViewportSize.height));
292 RenderDocumentFlags renderDocFlags =
293 RenderDocumentFlags::IgnoreViewportScrolling;
294 if (!(mImageFlags & imgIContainer::FLAG_SYNC_DECODE)) {
295 renderDocFlags |= RenderDocumentFlags::AsyncDecodeImages;
297 if (mImageFlags & imgIContainer::FLAG_HIGH_QUALITY_SCALING) {
298 renderDocFlags |= RenderDocumentFlags::UseHighQualityScaling;
301 presShell->RenderDocument(svgRect, renderDocFlags,
302 NS_RGBA(0, 0, 0, 0), // transparent
303 aContext);
305 return true;
308 class MOZ_STACK_CLASS AutoRestoreSVGState final {
309 public:
310 AutoRestoreSVGState(const SVGDrawingParameters& aParams,
311 SVGDocumentWrapper* aSVGDocumentWrapper, bool& aIsDrawing,
312 bool aContextPaint)
313 : mIsDrawing(aIsDrawing)
314 // Apply any 'preserveAspectRatio' override (if specified) to the root
315 // element:
317 mPAR(aParams.svgContext, aSVGDocumentWrapper->GetRootSVGElem())
318 // Set the animation time:
320 mTime(aSVGDocumentWrapper->GetRootSVGElem(), aParams.animationTime) {
321 MOZ_ASSERT(!aIsDrawing);
322 MOZ_ASSERT(aSVGDocumentWrapper->GetDocument());
324 aIsDrawing = true;
326 // Set context paint (if specified) on the document:
327 if (aContextPaint) {
328 MOZ_ASSERT(aParams.svgContext->GetContextPaint());
329 mContextPaint.emplace(*aParams.svgContext->GetContextPaint(),
330 *aSVGDocumentWrapper->GetDocument());
334 private:
335 AutoRestore<bool> mIsDrawing;
336 AutoPreserveAspectRatioOverride mPAR;
337 AutoSVGTimeSetRestore mTime;
338 Maybe<AutoSetRestoreSVGContextPaint> mContextPaint;
341 // Implement VectorImage's nsISupports-inherited methods
342 NS_IMPL_ISUPPORTS(VectorImage, imgIContainer, nsIStreamListener,
343 nsIRequestObserver)
345 //------------------------------------------------------------------------------
346 // Constructor / Destructor
348 VectorImage::VectorImage(nsIURI* aURI /* = nullptr */)
349 : ImageResource(aURI), // invoke superclass's constructor
350 mLockCount(0),
351 mIsInitialized(false),
352 mDiscardable(false),
353 mIsFullyLoaded(false),
354 mIsDrawing(false),
355 mHaveAnimations(false),
356 mHasPendingInvalidation(false) {}
358 VectorImage::~VectorImage() {
359 ReportDocumentUseCounters();
360 CancelAllListeners();
361 SurfaceCache::RemoveImage(ImageKey(this));
364 //------------------------------------------------------------------------------
365 // Methods inherited from Image.h
367 nsresult VectorImage::Init(const char* aMimeType, uint32_t aFlags) {
368 // We don't support re-initialization
369 if (mIsInitialized) {
370 return NS_ERROR_ILLEGAL_VALUE;
373 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations && !mError,
374 "Flags unexpectedly set before initialization");
375 MOZ_ASSERT(!strcmp(aMimeType, IMAGE_SVG_XML), "Unexpected mimetype");
377 mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE);
379 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
380 if (!mDiscardable) {
381 mLockCount++;
382 SurfaceCache::LockImage(ImageKey(this));
385 mIsInitialized = true;
386 return NS_OK;
389 size_t VectorImage::SizeOfSourceWithComputedFallback(
390 SizeOfState& aState) const {
391 if (!mSVGDocumentWrapper) {
392 return 0; // No document, so no memory used for the document.
395 SVGDocument* doc = mSVGDocumentWrapper->GetDocument();
396 if (!doc) {
397 return 0; // No document, so no memory used for the document.
400 nsWindowSizes windowSizes(aState);
401 doc->DocAddSizeOfIncludingThis(windowSizes);
403 if (windowSizes.getTotalSize() == 0) {
404 // MallocSizeOf fails on this platform. Because we also use this method for
405 // determining the size of cache entries, we need to return something
406 // reasonable here. Unfortunately, there's no way to estimate the document's
407 // size accurately, so we just use a constant value of 100KB, which will
408 // generally underestimate the true size.
409 return 100 * 1024;
412 return windowSizes.getTotalSize();
415 void VectorImage::CollectSizeOfSurfaces(
416 nsTArray<SurfaceMemoryCounter>& aCounters,
417 MallocSizeOf aMallocSizeOf) const {
418 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters, aMallocSizeOf);
421 nsresult VectorImage::OnImageDataComplete(nsIRequest* aRequest,
422 nsISupports* aContext,
423 nsresult aStatus, bool aLastPart) {
424 // Call our internal OnStopRequest method, which only talks to our embedded
425 // SVG document. This won't have any effect on our ProgressTracker.
426 nsresult finalStatus = OnStopRequest(aRequest, aStatus);
428 // Give precedence to Necko failure codes.
429 if (NS_FAILED(aStatus)) {
430 finalStatus = aStatus;
433 Progress loadProgress = LoadCompleteProgress(aLastPart, mError, finalStatus);
435 if (mIsFullyLoaded || mError) {
436 // Our document is loaded, so we're ready to notify now.
437 mProgressTracker->SyncNotifyProgress(loadProgress);
438 } else {
439 // Record our progress so far; we'll actually send the notifications in
440 // OnSVGDocumentLoaded or OnSVGDocumentError.
441 mLoadProgress = Some(loadProgress);
444 return finalStatus;
447 nsresult VectorImage::OnImageDataAvailable(nsIRequest* aRequest,
448 nsISupports* aContext,
449 nsIInputStream* aInStr,
450 uint64_t aSourceOffset,
451 uint32_t aCount) {
452 return OnDataAvailable(aRequest, aInStr, aSourceOffset, aCount);
455 nsresult VectorImage::StartAnimation() {
456 if (mError) {
457 return NS_ERROR_FAILURE;
460 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
462 mSVGDocumentWrapper->StartAnimation();
463 return NS_OK;
466 nsresult VectorImage::StopAnimation() {
467 nsresult rv = NS_OK;
468 if (mError) {
469 rv = NS_ERROR_FAILURE;
470 } else {
471 MOZ_ASSERT(mIsFullyLoaded && mHaveAnimations,
472 "Should not have been animating!");
474 mSVGDocumentWrapper->StopAnimation();
477 mAnimating = false;
478 return rv;
481 bool VectorImage::ShouldAnimate() {
482 return ImageResource::ShouldAnimate() && mIsFullyLoaded && mHaveAnimations;
485 NS_IMETHODIMP_(void)
486 VectorImage::SetAnimationStartTime(const TimeStamp& aTime) {
487 // We don't care about animation start time.
490 //------------------------------------------------------------------------------
491 // imgIContainer methods
493 //******************************************************************************
494 NS_IMETHODIMP
495 VectorImage::GetWidth(int32_t* aWidth) {
496 if (mError || !mIsFullyLoaded) {
497 // XXXdholbert Technically we should leave outparam untouched when we
498 // fail. But since many callers don't check for failure, we set it to 0 on
499 // failure, for sane/predictable results.
500 *aWidth = 0;
501 return NS_ERROR_FAILURE;
504 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
505 MOZ_ASSERT(rootElem,
506 "Should have a root SVG elem, since we finished "
507 "loading without errors");
508 int32_t rootElemWidth = rootElem->GetIntrinsicWidth();
509 if (rootElemWidth < 0) {
510 *aWidth = 0;
511 return NS_ERROR_FAILURE;
513 *aWidth = rootElemWidth;
514 return NS_OK;
517 //******************************************************************************
518 nsresult VectorImage::GetNativeSizes(nsTArray<IntSize>& aNativeSizes) const {
519 return NS_ERROR_NOT_IMPLEMENTED;
522 //******************************************************************************
523 size_t VectorImage::GetNativeSizesLength() const { return 0; }
525 //******************************************************************************
526 NS_IMETHODIMP_(void)
527 VectorImage::RequestRefresh(const TimeStamp& aTime) {
528 if (HadRecentRefresh(aTime)) {
529 return;
532 PendingAnimationTracker* tracker =
533 mSVGDocumentWrapper->GetDocument()->GetPendingAnimationTracker();
534 if (tracker && ShouldAnimate()) {
535 tracker->TriggerPendingAnimationsOnNextTick(aTime);
538 EvaluateAnimation();
540 mSVGDocumentWrapper->TickRefreshDriver();
542 if (mHasPendingInvalidation) {
543 SendInvalidationNotifications();
547 void VectorImage::SendInvalidationNotifications() {
548 // Animated images don't send out invalidation notifications as soon as
549 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
550 // records that there are pending invalidations and then returns immediately.
551 // The notifications are actually sent from RequestRefresh(). We send these
552 // notifications there to ensure that there is actually a document observing
553 // us. Otherwise, the notifications are just wasted effort.
555 // Non-animated images post an event to call this method from
556 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
557 // called for them. Ordinarily this isn't needed, since we send out
558 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
559 // SVG document may not be 100% ready to render at that time. In those cases
560 // we would miss the subsequent invalidations if we didn't send out the
561 // notifications indirectly in |InvalidateObservers...|.
563 mHasPendingInvalidation = false;
564 SurfaceCache::RemoveImage(ImageKey(this));
566 if (UpdateImageContainer(Nothing())) {
567 // If we have image containers, that means we probably won't get a Draw call
568 // from the owner since they are using the container. We must assume all
569 // invalidations need to be handled.
570 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
571 mRenderingObserver->ResumeHonoringInvalidations();
574 if (mProgressTracker) {
575 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
576 GetMaxSizedIntRect());
580 NS_IMETHODIMP_(IntRect)
581 VectorImage::GetImageSpaceInvalidationRect(const IntRect& aRect) {
582 return aRect;
585 //******************************************************************************
586 NS_IMETHODIMP
587 VectorImage::GetHeight(int32_t* aHeight) {
588 if (mError || !mIsFullyLoaded) {
589 // XXXdholbert Technically we should leave outparam untouched when we
590 // fail. But since many callers don't check for failure, we set it to 0 on
591 // failure, for sane/predictable results.
592 *aHeight = 0;
593 return NS_ERROR_FAILURE;
596 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
597 MOZ_ASSERT(rootElem,
598 "Should have a root SVG elem, since we finished "
599 "loading without errors");
600 int32_t rootElemHeight = rootElem->GetIntrinsicHeight();
601 if (rootElemHeight < 0) {
602 *aHeight = 0;
603 return NS_ERROR_FAILURE;
605 *aHeight = rootElemHeight;
606 return NS_OK;
609 //******************************************************************************
610 NS_IMETHODIMP
611 VectorImage::GetIntrinsicSize(nsSize* aSize) {
612 if (mError || !mIsFullyLoaded) {
613 return NS_ERROR_FAILURE;
616 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
617 if (!rootFrame) {
618 return NS_ERROR_FAILURE;
621 *aSize = nsSize(-1, -1);
622 IntrinsicSize rfSize = rootFrame->GetIntrinsicSize();
623 if (rfSize.width) {
624 aSize->width = *rfSize.width;
626 if (rfSize.height) {
627 aSize->height = *rfSize.height;
629 return NS_OK;
632 //******************************************************************************
633 Maybe<AspectRatio> VectorImage::GetIntrinsicRatio() {
634 if (mError || !mIsFullyLoaded) {
635 return Nothing();
638 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
639 if (!rootFrame) {
640 return Nothing();
643 return Some(rootFrame->GetIntrinsicRatio());
646 NS_IMETHODIMP_(Orientation)
647 VectorImage::GetOrientation() { return Orientation(); }
649 NS_IMETHODIMP_(bool)
650 VectorImage::HandledOrientation() { return false; }
652 //******************************************************************************
653 NS_IMETHODIMP
654 VectorImage::GetType(uint16_t* aType) {
655 NS_ENSURE_ARG_POINTER(aType);
657 *aType = imgIContainer::TYPE_VECTOR;
658 return NS_OK;
661 //******************************************************************************
662 NS_IMETHODIMP
663 VectorImage::GetProducerId(uint32_t* aId) {
664 NS_ENSURE_ARG_POINTER(aId);
666 *aId = ImageResource::GetImageProducerId();
667 return NS_OK;
670 //******************************************************************************
671 NS_IMETHODIMP
672 VectorImage::GetAnimated(bool* aAnimated) {
673 if (mError || !mIsFullyLoaded) {
674 return NS_ERROR_FAILURE;
677 *aAnimated = mSVGDocumentWrapper->IsAnimated();
678 return NS_OK;
681 //******************************************************************************
682 int32_t VectorImage::GetFirstFrameDelay() {
683 if (mError) {
684 return -1;
687 if (!mSVGDocumentWrapper->IsAnimated()) {
688 return -1;
691 // We don't really have a frame delay, so just pretend that we constantly
692 // need updates.
693 return 0;
696 NS_IMETHODIMP_(bool)
697 VectorImage::WillDrawOpaqueNow() {
698 return false; // In general, SVG content is not opaque.
701 //******************************************************************************
702 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
703 VectorImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
704 if (mError) {
705 return nullptr;
708 // Look up height & width
709 // ----------------------
710 SVGSVGElement* svgElem = mSVGDocumentWrapper->GetRootSVGElem();
711 MOZ_ASSERT(svgElem,
712 "Should have a root SVG elem, since we finished "
713 "loading without errors");
714 nsIntSize imageIntSize(svgElem->GetIntrinsicWidth(),
715 svgElem->GetIntrinsicHeight());
717 if (imageIntSize.IsEmpty()) {
718 // We'll get here if our SVG doc has a percent-valued or negative width or
719 // height.
720 return nullptr;
723 return GetFrameAtSize(imageIntSize, aWhichFrame, aFlags);
726 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
727 VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
728 uint32_t aFlags) {
729 #ifdef DEBUG
730 NotifyDrawingObservers();
731 #endif
733 auto result = GetFrameInternal(aSize, Nothing(), aWhichFrame, aFlags);
734 return Get<2>(result).forget();
737 Tuple<ImgDrawResult, IntSize, RefPtr<SourceSurface>>
738 VectorImage::GetFrameInternal(const IntSize& aSize,
739 const Maybe<SVGImageContext>& aSVGContext,
740 uint32_t aWhichFrame, uint32_t aFlags) {
741 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE);
743 if (aSize.IsEmpty() || aWhichFrame > FRAME_MAX_VALUE) {
744 return MakeTuple(ImgDrawResult::BAD_ARGS, aSize, RefPtr<SourceSurface>());
747 if (mError) {
748 return MakeTuple(ImgDrawResult::BAD_IMAGE, aSize, RefPtr<SourceSurface>());
751 if (!mIsFullyLoaded) {
752 return MakeTuple(ImgDrawResult::NOT_READY, aSize, RefPtr<SourceSurface>());
755 RefPtr<SourceSurface> sourceSurface;
756 IntSize decodeSize;
757 Tie(sourceSurface, decodeSize) =
758 LookupCachedSurface(aSize, aSVGContext, aFlags);
759 if (sourceSurface) {
760 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize,
761 std::move(sourceSurface));
764 if (mIsDrawing) {
765 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
766 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
767 RefPtr<SourceSurface>());
770 // By using a null gfxContext, we ensure that we will always attempt to
771 // create a surface, even if we aren't capable of caching it (e.g. due to our
772 // flags, having an animation, etc). Otherwise CreateSurface will assume that
773 // the caller is capable of drawing directly to its own draw target if we
774 // cannot cache.
775 SVGDrawingParameters params(
776 nullptr, decodeSize, aSize, ImageRegion::Create(decodeSize),
777 SamplingFilter::POINT, aSVGContext,
778 mSVGDocumentWrapper->GetCurrentTimeAsFloat(), aFlags, 1.0);
780 bool didCache; // Was the surface put into the cache?
781 bool contextPaint = aSVGContext && aSVGContext->GetContextPaint();
783 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, mIsDrawing,
784 contextPaint);
786 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
787 RefPtr<SourceSurface> surface = CreateSurface(params, svgDrawable, didCache);
788 if (!surface) {
789 MOZ_ASSERT(!didCache);
790 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
791 RefPtr<SourceSurface>());
794 SendFrameComplete(didCache, params.flags);
795 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize, std::move(surface));
798 //******************************************************************************
799 Tuple<ImgDrawResult, IntSize> VectorImage::GetImageContainerSize(
800 LayerManager* aManager, const IntSize& aSize, uint32_t aFlags) {
801 if (mError) {
802 return MakeTuple(ImgDrawResult::BAD_IMAGE, IntSize(0, 0));
805 if (!mIsFullyLoaded) {
806 return MakeTuple(ImgDrawResult::NOT_READY, IntSize(0, 0));
809 if (mHaveAnimations ||
810 aManager->GetBackendType() != LayersBackend::LAYERS_WR) {
811 return MakeTuple(ImgDrawResult::NOT_SUPPORTED, IntSize(0, 0));
814 // We don't need to check if the size is too big since we only support
815 // WebRender backends.
816 if (aSize.IsEmpty()) {
817 return MakeTuple(ImgDrawResult::BAD_ARGS, IntSize(0, 0));
820 return MakeTuple(ImgDrawResult::SUCCESS, aSize);
823 NS_IMETHODIMP_(bool)
824 VectorImage::IsImageContainerAvailable(LayerManager* aManager,
825 uint32_t aFlags) {
826 if (mError || !mIsFullyLoaded || mHaveAnimations ||
827 aManager->GetBackendType() != LayersBackend::LAYERS_WR) {
828 return false;
831 return true;
834 //******************************************************************************
835 NS_IMETHODIMP_(already_AddRefed<ImageContainer>)
836 VectorImage::GetImageContainer(LayerManager* aManager, uint32_t aFlags) {
837 MOZ_ASSERT(aManager->GetBackendType() != LayersBackend::LAYERS_WR,
838 "WebRender should always use GetImageContainerAvailableAtSize!");
839 return nullptr;
842 //******************************************************************************
843 NS_IMETHODIMP_(bool)
844 VectorImage::IsImageContainerAvailableAtSize(LayerManager* aManager,
845 const IntSize& aSize,
846 uint32_t aFlags) {
847 // Since we only support image containers with WebRender, and it can handle
848 // textures larger than the hw max texture size, we don't need to check aSize.
849 return !aSize.IsEmpty() && IsImageContainerAvailable(aManager, aFlags);
852 //******************************************************************************
853 NS_IMETHODIMP_(ImgDrawResult)
854 VectorImage::GetImageContainerAtSize(layers::LayerManager* aManager,
855 const gfx::IntSize& aSize,
856 const Maybe<SVGImageContext>& aSVGContext,
857 uint32_t aFlags,
858 layers::ImageContainer** aOutContainer) {
859 Maybe<SVGImageContext> newSVGContext;
860 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
862 // The aspect ratio flag was already handled as part of the SVG context
863 // restriction above.
864 uint32_t flags = aFlags & ~(FLAG_FORCE_PRESERVEASPECTRATIO_NONE);
865 return GetImageContainerImpl(aManager, aSize,
866 newSVGContext ? newSVGContext : aSVGContext,
867 flags, aOutContainer);
870 bool VectorImage::MaybeRestrictSVGContext(
871 Maybe<SVGImageContext>& aNewSVGContext,
872 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags) {
873 bool overridePAR =
874 (aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) && aSVGContext;
876 bool haveContextPaint = aSVGContext && aSVGContext->GetContextPaint();
877 bool blockContextPaint = false;
878 if (haveContextPaint) {
879 blockContextPaint = !SVGContextPaint::IsAllowedForImageFromURI(mURI);
882 if (overridePAR || blockContextPaint) {
883 // The key that we create for the image surface cache must match the way
884 // that the image will be painted, so we need to initialize a new matching
885 // SVGImageContext here in order to generate the correct key.
887 aNewSVGContext = aSVGContext; // copy
889 if (overridePAR) {
890 // The SVGImageContext must take account of the preserveAspectRatio
891 // override:
892 MOZ_ASSERT(!aSVGContext->GetPreserveAspectRatio(),
893 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
894 "preserveAspectRatio override is supplied");
895 Maybe<SVGPreserveAspectRatio> aspectRatio = Some(SVGPreserveAspectRatio(
896 SVG_PRESERVEASPECTRATIO_NONE, SVG_MEETORSLICE_UNKNOWN));
897 aNewSVGContext->SetPreserveAspectRatio(aspectRatio);
900 if (blockContextPaint) {
901 // The SVGImageContext must not include context paint if the image is
902 // not allowed to use it:
903 aNewSVGContext->ClearContextPaint();
907 return haveContextPaint && !blockContextPaint;
910 //******************************************************************************
911 NS_IMETHODIMP_(ImgDrawResult)
912 VectorImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
913 const ImageRegion& aRegion, uint32_t aWhichFrame,
914 SamplingFilter aSamplingFilter,
915 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags,
916 float aOpacity) {
917 if (aWhichFrame > FRAME_MAX_VALUE) {
918 return ImgDrawResult::BAD_ARGS;
921 if (!aContext) {
922 return ImgDrawResult::BAD_ARGS;
925 if (mError) {
926 return ImgDrawResult::BAD_IMAGE;
929 if (!mIsFullyLoaded) {
930 return ImgDrawResult::NOT_READY;
933 if (mAnimationConsumers == 0) {
934 SendOnUnlockedDraw(aFlags);
937 // We should bypass the cache when:
938 // - We are using a DrawTargetRecording because we prefer the drawing commands
939 // in general to the rasterized surface. This allows blob images to avoid
940 // rasterized SVGs with WebRender.
941 // - The size exceeds what we are willing to cache as a rasterized surface.
942 // We don't do this for WebRender because the performance of the fallback
943 // path is quite bad and upscaling the SVG from the clamped size is better
944 // than bringing the browser to a crawl.
945 if (aContext->GetDrawTarget()->GetBackendType() == BackendType::RECORDING ||
946 (!gfxVars::UseWebRender() &&
947 aSize != SurfaceCache::ClampVectorSize(aSize))) {
948 aFlags |= FLAG_BYPASS_SURFACE_CACHE;
951 MOZ_ASSERT(!(aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) ||
952 (aSVGContext && aSVGContext->GetViewportSize()),
953 "Viewport size is required when using "
954 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
956 float animTime = (aWhichFrame == FRAME_FIRST)
957 ? 0.0f
958 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
960 Maybe<SVGImageContext> newSVGContext;
961 bool contextPaint =
962 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
964 SVGDrawingParameters params(aContext, aSize, aSize, aRegion, aSamplingFilter,
965 newSVGContext ? newSVGContext : aSVGContext,
966 animTime, aFlags, aOpacity);
968 // If we have an prerasterized version of this image that matches the
969 // drawing parameters, use that.
970 RefPtr<SourceSurface> sourceSurface;
971 Tie(sourceSurface, params.size) =
972 LookupCachedSurface(aSize, params.svgContext, aFlags);
973 if (sourceSurface) {
974 RefPtr<gfxDrawable> drawable =
975 new gfxSurfaceDrawable(sourceSurface, params.size);
976 Show(drawable, params);
977 return ImgDrawResult::SUCCESS;
980 // else, we need to paint the image:
982 if (mIsDrawing) {
983 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
984 return ImgDrawResult::TEMPORARY_ERROR;
987 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, mIsDrawing,
988 contextPaint);
990 bool didCache; // Was the surface put into the cache?
991 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
992 sourceSurface = CreateSurface(params, svgDrawable, didCache);
993 if (!sourceSurface) {
994 MOZ_ASSERT(!didCache);
995 Show(svgDrawable, params);
996 return ImgDrawResult::SUCCESS;
999 RefPtr<gfxDrawable> drawable =
1000 new gfxSurfaceDrawable(sourceSurface, params.size);
1001 Show(drawable, params);
1002 SendFrameComplete(didCache, params.flags);
1003 return ImgDrawResult::SUCCESS;
1006 already_AddRefed<gfxDrawable> VectorImage::CreateSVGDrawable(
1007 const SVGDrawingParameters& aParams) {
1008 RefPtr<gfxDrawingCallback> cb = new SVGDrawingCallback(
1009 mSVGDocumentWrapper, aParams.viewportSize, aParams.size, aParams.flags);
1011 RefPtr<gfxDrawable> svgDrawable = new gfxCallbackDrawable(cb, aParams.size);
1012 return svgDrawable.forget();
1015 Tuple<RefPtr<SourceSurface>, IntSize> VectorImage::LookupCachedSurface(
1016 const IntSize& aSize, const Maybe<SVGImageContext>& aSVGContext,
1017 uint32_t aFlags) {
1018 // If we're not allowed to use a cached surface, don't attempt a lookup.
1019 if (aFlags & FLAG_BYPASS_SURFACE_CACHE) {
1020 return MakeTuple(RefPtr<SourceSurface>(), aSize);
1023 // We don't do any caching if we have animation, so don't bother with a lookup
1024 // in this case either.
1025 if (mHaveAnimations) {
1026 return MakeTuple(RefPtr<SourceSurface>(), aSize);
1029 LookupResult result(MatchType::NOT_FOUND);
1030 SurfaceKey surfaceKey = VectorSurfaceKey(aSize, aSVGContext);
1031 if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
1032 result = SurfaceCache::Lookup(ImageKey(this), surfaceKey,
1033 /* aMarkUsed = */ true);
1034 } else {
1035 result = SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey,
1036 /* aMarkUsed = */ true);
1039 IntSize rasterSize =
1040 result.SuggestedSize().IsEmpty() ? aSize : result.SuggestedSize();
1041 MOZ_ASSERT(result.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING);
1042 if (!result || result.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND) {
1043 // No matching surface, or the OS freed the volatile buffer.
1044 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1047 RefPtr<SourceSurface> sourceSurface = result.Surface()->GetSourceSurface();
1048 if (!sourceSurface) {
1049 // Something went wrong. (Probably a GPU driver crash or device reset.)
1050 // Attempt to recover.
1051 RecoverFromLossOfSurfaces();
1052 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1055 return MakeTuple(std::move(sourceSurface), rasterSize);
1058 already_AddRefed<SourceSurface> VectorImage::CreateSurface(
1059 const SVGDrawingParameters& aParams, gfxDrawable* aSVGDrawable,
1060 bool& aWillCache) {
1061 MOZ_ASSERT(mIsDrawing);
1063 mSVGDocumentWrapper->UpdateViewportBounds(aParams.viewportSize);
1064 mSVGDocumentWrapper->FlushImageTransformInvalidation();
1066 // Determine whether or not we should put the surface to be created into
1067 // the cache. If we fail, we need to reset this to false to let the caller
1068 // know nothing was put in the cache.
1069 aWillCache = !(aParams.flags & FLAG_BYPASS_SURFACE_CACHE) &&
1070 // Refuse to cache animated images:
1071 // XXX(seth): We may remove this restriction in bug 922893.
1072 !mHaveAnimations &&
1073 // The image is too big to fit in the cache:
1074 SurfaceCache::CanHold(aParams.size);
1076 // If we weren't given a context, then we know we just want the rasterized
1077 // surface. We will create the frame below but only insert it into the cache
1078 // if we actually need to.
1079 if (!aWillCache && aParams.context) {
1080 return nullptr;
1083 // We're about to rerasterize, which may mean that some of the previous
1084 // surfaces we've rasterized aren't useful anymore. We can allow them to
1085 // expire from the cache by unlocking them here, and then sending out an
1086 // invalidation. If this image is locked, any surfaces that are still useful
1087 // will become locked again when Draw touches them, and the remainder will
1088 // eventually expire.
1089 if (aWillCache) {
1090 SurfaceCache::UnlockEntries(ImageKey(this));
1093 // If there is no context, the default backend is fine.
1094 BackendType backend =
1095 aParams.context ? aParams.context->GetDrawTarget()->GetBackendType()
1096 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1098 // Try to create an imgFrame, initializing the surface it contains by drawing
1099 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1100 auto frame = MakeNotNull<RefPtr<imgFrame>>();
1101 nsresult rv = frame->InitWithDrawable(
1102 aSVGDrawable, aParams.size, SurfaceFormat::OS_RGBA, SamplingFilter::POINT,
1103 aParams.flags, backend);
1105 // If we couldn't create the frame, it was probably because it would end
1106 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1107 // could be set such that the cache isn't the limiting factor.
1108 if (NS_FAILED(rv)) {
1109 aWillCache = false;
1110 return nullptr;
1113 // Take a strong reference to the frame's surface and make sure it hasn't
1114 // already been purged by the operating system.
1115 RefPtr<SourceSurface> surface = frame->GetSourceSurface();
1116 if (!surface) {
1117 aWillCache = false;
1118 return nullptr;
1121 // We created the frame, but only because we had no context to draw to
1122 // directly. All the caller wants is the surface in this case.
1123 if (!aWillCache) {
1124 return surface.forget();
1127 // Attempt to cache the frame.
1128 SurfaceKey surfaceKey = VectorSurfaceKey(aParams.size, aParams.svgContext);
1129 NotNull<RefPtr<ISurfaceProvider>> provider =
1130 MakeNotNull<SimpleSurfaceProvider*>(ImageKey(this), surfaceKey, frame);
1132 if (SurfaceCache::Insert(provider) == InsertOutcome::SUCCESS) {
1133 if (aParams.size != aParams.drawSize) {
1134 // We created a new surface that wasn't the size we requested, which means
1135 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1136 // need rather than waiting for the cache to expire them.
1137 SurfaceCache::PruneImage(ImageKey(this));
1139 } else {
1140 aWillCache = false;
1143 return surface.forget();
1146 void VectorImage::SendFrameComplete(bool aDidCache, uint32_t aFlags) {
1147 // If the cache was not updated, we have nothing to do.
1148 if (!aDidCache) {
1149 return;
1152 // Send out an invalidation so that surfaces that are still in use get
1153 // re-locked. See the discussion of the UnlockSurfaces call above.
1154 if (!(aFlags & FLAG_ASYNC_NOTIFY)) {
1155 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1156 GetMaxSizedIntRect());
1157 } else {
1158 NotNull<RefPtr<VectorImage>> image = WrapNotNull(this);
1159 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1160 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1161 RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
1162 if (tracker) {
1163 tracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1164 GetMaxSizedIntRect());
1166 })));
1170 void VectorImage::Show(gfxDrawable* aDrawable,
1171 const SVGDrawingParameters& aParams) {
1172 // The surface size may differ from the size at which we wish to draw. As
1173 // such, we may need to adjust the context/region to take this into account.
1174 gfxContextMatrixAutoSaveRestore saveMatrix(aParams.context);
1175 ImageRegion region(aParams.region);
1176 if (aParams.drawSize != aParams.size) {
1177 gfx::Size scale(double(aParams.drawSize.width) / aParams.size.width,
1178 double(aParams.drawSize.height) / aParams.size.height);
1179 aParams.context->Multiply(gfxMatrix::Scaling(scale.width, scale.height));
1180 region.Scale(1.0 / scale.width, 1.0 / scale.height);
1183 MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
1184 gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
1185 SizeDouble(aParams.size), region,
1186 SurfaceFormat::OS_RGBA, aParams.samplingFilter,
1187 aParams.flags, aParams.opacity, false);
1189 #ifdef DEBUG
1190 NotifyDrawingObservers();
1191 #endif
1193 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
1194 mRenderingObserver->ResumeHonoringInvalidations();
1197 void VectorImage::RecoverFromLossOfSurfaces() {
1198 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1200 // Discard all existing frames, since they're probably all now invalid.
1201 SurfaceCache::RemoveImage(ImageKey(this));
1204 NS_IMETHODIMP
1205 VectorImage::StartDecoding(uint32_t aFlags, uint32_t aWhichFrame) {
1206 // Nothing to do for SVG images
1207 return NS_OK;
1210 bool VectorImage::StartDecodingWithResult(uint32_t aFlags,
1211 uint32_t aWhichFrame) {
1212 // SVG images are ready to draw when they are loaded
1213 return mIsFullyLoaded;
1216 imgIContainer::DecodeResult VectorImage::RequestDecodeWithResult(
1217 uint32_t aFlags, uint32_t aWhichFrame) {
1218 // SVG images are ready to draw when they are loaded and don't have an error.
1220 if (mError) {
1221 return imgIContainer::DECODE_REQUEST_FAILED;
1224 if (!mIsFullyLoaded) {
1225 return imgIContainer::DECODE_REQUESTED;
1228 return imgIContainer::DECODE_SURFACE_AVAILABLE;
1231 NS_IMETHODIMP
1232 VectorImage::RequestDecodeForSize(const nsIntSize& aSize, uint32_t aFlags,
1233 uint32_t aWhichFrame) {
1234 // Nothing to do for SVG images, though in theory we could rasterize to the
1235 // provided size ahead of time if we supported off-main-thread SVG
1236 // rasterization...
1237 return NS_OK;
1240 //******************************************************************************
1242 NS_IMETHODIMP
1243 VectorImage::LockImage() {
1244 MOZ_ASSERT(NS_IsMainThread());
1246 if (mError) {
1247 return NS_ERROR_FAILURE;
1250 mLockCount++;
1252 if (mLockCount == 1) {
1253 // Lock this image's surfaces in the SurfaceCache.
1254 SurfaceCache::LockImage(ImageKey(this));
1257 return NS_OK;
1260 //******************************************************************************
1262 NS_IMETHODIMP
1263 VectorImage::UnlockImage() {
1264 MOZ_ASSERT(NS_IsMainThread());
1266 if (mError) {
1267 return NS_ERROR_FAILURE;
1270 if (mLockCount == 0) {
1271 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1272 return NS_ERROR_ABORT;
1275 mLockCount--;
1277 if (mLockCount == 0) {
1278 // Unlock this image's surfaces in the SurfaceCache.
1279 SurfaceCache::UnlockImage(ImageKey(this));
1282 return NS_OK;
1285 //******************************************************************************
1287 NS_IMETHODIMP
1288 VectorImage::RequestDiscard() {
1289 MOZ_ASSERT(NS_IsMainThread());
1291 if (mDiscardable && mLockCount == 0) {
1292 SurfaceCache::RemoveImage(ImageKey(this));
1293 mProgressTracker->OnDiscard();
1296 return NS_OK;
1299 void VectorImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) {
1300 MOZ_ASSERT(mProgressTracker);
1302 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1303 mProgressTracker,
1304 &ProgressTracker::OnDiscard));
1307 //******************************************************************************
1308 NS_IMETHODIMP
1309 VectorImage::ResetAnimation() {
1310 if (mError) {
1311 return NS_ERROR_FAILURE;
1314 if (!mIsFullyLoaded || !mHaveAnimations) {
1315 return NS_OK; // There are no animations to be reset.
1318 mSVGDocumentWrapper->ResetAnimation();
1320 return NS_OK;
1323 NS_IMETHODIMP_(float)
1324 VectorImage::GetFrameIndex(uint32_t aWhichFrame) {
1325 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
1326 return aWhichFrame == FRAME_FIRST
1327 ? 0.0f
1328 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1331 //------------------------------------------------------------------------------
1332 // nsIRequestObserver methods
1334 //******************************************************************************
1335 NS_IMETHODIMP
1336 VectorImage::OnStartRequest(nsIRequest* aRequest) {
1337 MOZ_ASSERT(!mSVGDocumentWrapper,
1338 "Repeated call to OnStartRequest -- can this happen?");
1340 mSVGDocumentWrapper = new SVGDocumentWrapper();
1341 nsresult rv = mSVGDocumentWrapper->OnStartRequest(aRequest);
1342 if (NS_FAILED(rv)) {
1343 mSVGDocumentWrapper = nullptr;
1344 mError = true;
1345 return rv;
1348 // Create a listener to wait until the SVG document is fully loaded, which
1349 // will signal that this image is ready to render. Certain error conditions
1350 // will prevent us from ever getting this notification, so we also create a
1351 // listener that waits for parsing to complete and cancels the
1352 // SVGLoadEventListener if needed. The listeners are automatically attached
1353 // to the document by their constructors.
1354 SVGDocument* document = mSVGDocumentWrapper->GetDocument();
1355 mLoadEventListener = new SVGLoadEventListener(document, this);
1356 mParseCompleteListener = new SVGParseCompleteListener(document, this);
1358 // Displayed documents will call InitUseCounters under SetScriptGlobalObject,
1359 // but SVG image documents never get a script global object, so we initialize
1360 // use counters here, right after the document has been created.
1361 document->InitUseCounters();
1363 return NS_OK;
1366 //******************************************************************************
1367 NS_IMETHODIMP
1368 VectorImage::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
1369 if (mError) {
1370 return NS_ERROR_FAILURE;
1373 return mSVGDocumentWrapper->OnStopRequest(aRequest, aStatus);
1376 void VectorImage::OnSVGDocumentParsed() {
1377 MOZ_ASSERT(mParseCompleteListener, "Should have the parse complete listener");
1378 MOZ_ASSERT(mLoadEventListener, "Should have the load event listener");
1380 if (!mSVGDocumentWrapper->GetRootSVGElem()) {
1381 // This is an invalid SVG document. It may have failed to parse, or it may
1382 // be missing the <svg> root element, or the <svg> root element may not
1383 // declare the correct namespace. In any of these cases, we'll never be
1384 // notified that the SVG finished loading, so we need to treat this as an
1385 // error.
1386 OnSVGDocumentError();
1390 void VectorImage::CancelAllListeners() {
1391 if (mParseCompleteListener) {
1392 mParseCompleteListener->Cancel();
1393 mParseCompleteListener = nullptr;
1395 if (mLoadEventListener) {
1396 mLoadEventListener->Cancel();
1397 mLoadEventListener = nullptr;
1401 void VectorImage::OnSVGDocumentLoaded() {
1402 MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(),
1403 "Should have parsed successfully");
1404 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations,
1405 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1406 "Duplicate calls to OnSVGDocumentLoaded?");
1408 CancelAllListeners();
1410 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1411 mSVGDocumentWrapper->FlushLayout();
1413 // This is the earliest point that we can get accurate use counter data
1414 // for a valid SVG document. Without the FlushLayout call, we would miss
1415 // any CSS property usage that comes from SVG presentation attributes.
1416 mSVGDocumentWrapper->GetDocument()->ReportDocumentUseCounters();
1418 mIsFullyLoaded = true;
1419 mHaveAnimations = mSVGDocumentWrapper->IsAnimated();
1421 // Start listening to our image for rendering updates.
1422 mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this);
1424 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1425 // stick around long enough to complete our work.
1426 RefPtr<VectorImage> kungFuDeathGrip(this);
1428 // Tell *our* observers that we're done loading.
1429 if (mProgressTracker) {
1430 Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY |
1431 FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE;
1433 if (mHaveAnimations) {
1434 progress |= FLAG_IS_ANIMATED;
1437 // Merge in any saved progress from OnImageDataComplete.
1438 if (mLoadProgress) {
1439 progress |= *mLoadProgress;
1440 mLoadProgress = Nothing();
1443 mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect());
1446 EvaluateAnimation();
1449 void VectorImage::OnSVGDocumentError() {
1450 CancelAllListeners();
1452 mError = true;
1454 // We won't enter OnSVGDocumentLoaded, so report use counters now for this
1455 // invalid document.
1456 ReportDocumentUseCounters();
1458 if (mProgressTracker) {
1459 // Notify observers about the error and unblock page load.
1460 Progress progress = FLAG_HAS_ERROR;
1462 // Merge in any saved progress from OnImageDataComplete.
1463 if (mLoadProgress) {
1464 progress |= *mLoadProgress;
1465 mLoadProgress = Nothing();
1468 mProgressTracker->SyncNotifyProgress(progress);
1472 //------------------------------------------------------------------------------
1473 // nsIStreamListener method
1475 //******************************************************************************
1476 NS_IMETHODIMP
1477 VectorImage::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
1478 uint64_t aSourceOffset, uint32_t aCount) {
1479 if (mError) {
1480 return NS_ERROR_FAILURE;
1483 return mSVGDocumentWrapper->OnDataAvailable(aRequest, aInStr, aSourceOffset,
1484 aCount);
1487 // --------------------------
1488 // Invalidation helper method
1490 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1491 if (mHasPendingInvalidation) {
1492 return;
1495 mHasPendingInvalidation = true;
1497 // Animated images can wait for the refresh tick.
1498 if (mHaveAnimations) {
1499 return;
1502 // Non-animated images won't get the refresh tick, so we should just send an
1503 // invalidation outside the current execution context. We need to defer
1504 // because the layout tree is in the middle of invalidation, and the tree
1505 // state needs to be consistent. Specifically only some of the frames have
1506 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1507 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1508 // get cleared when we repaint the SVG into a surface by
1509 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1510 nsCOMPtr<nsIEventTarget> eventTarget;
1511 if (mProgressTracker) {
1512 eventTarget = mProgressTracker->GetEventTarget();
1513 } else {
1514 eventTarget = do_GetMainThread();
1517 RefPtr<VectorImage> self(this);
1518 nsCOMPtr<nsIRunnable> ev(NS_NewRunnableFunction(
1519 "VectorImage::SendInvalidationNotifications",
1520 [=]() -> void { self->SendInvalidationNotifications(); }));
1521 eventTarget->Dispatch(CreateMediumHighRunnable(ev.forget()),
1522 NS_DISPATCH_NORMAL);
1525 void VectorImage::PropagateUseCounters(Document* aReferencingDocument) {
1526 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1527 doc->PropagateImageUseCounters(aReferencingDocument);
1531 nsIntSize VectorImage::OptimalImageSizeForDest(const gfxSize& aDest,
1532 uint32_t aWhichFrame,
1533 SamplingFilter aSamplingFilter,
1534 uint32_t aFlags) {
1535 MOZ_ASSERT(aDest.width >= 0 || ceil(aDest.width) <= INT32_MAX ||
1536 aDest.height >= 0 || ceil(aDest.height) <= INT32_MAX,
1537 "Unexpected destination size");
1539 // We can rescale SVGs freely, so just return the provided destination size.
1540 return nsIntSize::Ceil(aDest.width, aDest.height);
1543 already_AddRefed<imgIContainer> VectorImage::Unwrap() {
1544 nsCOMPtr<imgIContainer> self(this);
1545 return self.forget();
1548 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1549 const MediaFeatureChange& aChange) {
1550 if (!mSVGDocumentWrapper) {
1551 return;
1554 // Don't bother if the document hasn't loaded yet.
1555 if (!mIsFullyLoaded) {
1556 return;
1559 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1560 if (RefPtr<nsPresContext> presContext = doc->GetPresContext()) {
1561 presContext->MediaFeatureValuesChanged(
1562 aChange, MediaFeatureChangePropagation::All);
1563 // Media feature value changes don't happen in the middle of layout,
1564 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1565 // to invalidate asynchronously.
1566 if (presContext->FlushPendingMediaFeatureValuesChanged()) {
1567 // NOTE(emilio): SendInvalidationNotifications flushes layout via
1568 // VectorImage::CreateSurface -> FlushImageTransformInvalidation.
1569 SendInvalidationNotifications();
1575 nsresult VectorImage::GetHotspotX(int32_t* aX) {
1576 return Image::GetHotspotX(aX);
1579 nsresult VectorImage::GetHotspotY(int32_t* aY) {
1580 return Image::GetHotspotY(aY);
1583 void VectorImage::ReportDocumentUseCounters() {
1584 if (!mSVGDocumentWrapper) {
1585 return;
1588 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1589 doc->ReportDocumentUseCounters();
1593 } // namespace image
1594 } // namespace mozilla