Bug 1523562 [wpt PR 14847] - Make named constructors' |prototype|s have the right...
[gecko.git] / image / VectorImage.cpp
blob0f22effbac5c1becbaf5f354495d3f9e0fc61884
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/dom/Event.h"
17 #include "mozilla/dom/SVGSVGElement.h"
18 #include "mozilla/dom/SVGDocument.h"
19 #include "mozilla/gfx/2D.h"
20 #include "mozilla/PendingAnimationTracker.h"
21 #include "mozilla/RefPtr.h"
22 #include "mozilla/Tuple.h"
23 #include "nsIPresShell.h"
24 #include "nsIStreamListener.h"
25 #include "nsMimeTypes.h"
26 #include "nsPresContext.h"
27 #include "nsRect.h"
28 #include "nsString.h"
29 #include "nsStubDocumentObserver.h"
30 #include "SVGObserverUtils.h" // for SVGRenderingObserver
31 #include "nsWindowSizes.h"
32 #include "ImageRegion.h"
33 #include "ISurfaceProvider.h"
34 #include "LookupResult.h"
35 #include "Orientation.h"
36 #include "SVGDocumentWrapper.h"
37 #include "SVGDrawingParameters.h"
38 #include "nsIDOMEventListener.h"
39 #include "SurfaceCache.h"
40 #include "mozilla/dom/Document.h"
42 namespace mozilla {
44 using namespace dom;
45 using namespace dom::SVGPreserveAspectRatio_Binding;
46 using namespace gfx;
47 using namespace layers;
49 namespace image {
51 // Helper-class: SVGRootRenderingObserver
52 class SVGRootRenderingObserver final : public SVGRenderingObserver {
53 public:
54 NS_DECL_ISUPPORTS
56 SVGRootRenderingObserver(SVGDocumentWrapper* aDocWrapper,
57 VectorImage* aVectorImage)
58 : SVGRenderingObserver(),
59 mDocWrapper(aDocWrapper),
60 mVectorImage(aVectorImage),
61 mHonoringInvalidations(true) {
62 MOZ_ASSERT(mDocWrapper, "Need a non-null SVG document wrapper");
63 MOZ_ASSERT(mVectorImage, "Need a non-null VectorImage");
65 StartObserving();
66 Element* elem = GetReferencedElementWithoutObserving();
67 MOZ_ASSERT(elem, "no root SVG node for us to observe");
69 SVGObserverUtils::AddRenderingObserver(elem, this);
70 mInObserverList = true;
73 void ResumeHonoringInvalidations() { mHonoringInvalidations = true; }
75 protected:
76 virtual ~SVGRootRenderingObserver() {
77 // This needs to call our GetReferencedElementWithoutObserving override,
78 // so must be called here rather than in our base class's dtor.
79 StopObserving();
82 Element* GetReferencedElementWithoutObserving() final {
83 return mDocWrapper->GetRootSVGElem();
86 virtual void OnRenderingChange() override {
87 Element* elem = GetReferencedElementWithoutObserving();
88 MOZ_ASSERT(elem, "missing root SVG node");
90 if (mHonoringInvalidations && !mDocWrapper->ShouldIgnoreInvalidation()) {
91 nsIFrame* frame = elem->GetPrimaryFrame();
92 if (!frame || frame->PresShell()->IsDestroying()) {
93 // We're being destroyed. Bail out.
94 return;
97 // Ignore further invalidations until we draw.
98 mHonoringInvalidations = false;
100 mVectorImage->InvalidateObserversOnNextRefreshDriverTick();
103 // Our caller might've removed us from rendering-observer list.
104 // Add ourselves back!
105 if (!mInObserverList) {
106 SVGObserverUtils::AddRenderingObserver(elem, this);
107 mInObserverList = true;
111 // Private data
112 const RefPtr<SVGDocumentWrapper> mDocWrapper;
113 VectorImage* const mVectorImage; // Raw pointer because it owns me.
114 bool mHonoringInvalidations;
117 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver, nsIMutationObserver)
119 class SVGParseCompleteListener final : public nsStubDocumentObserver {
120 public:
121 NS_DECL_ISUPPORTS
123 SVGParseCompleteListener(SVGDocument* aDocument, VectorImage* aImage)
124 : mDocument(aDocument), mImage(aImage) {
125 MOZ_ASSERT(mDocument, "Need an SVG document");
126 MOZ_ASSERT(mImage, "Need an image");
128 mDocument->AddObserver(this);
131 private:
132 ~SVGParseCompleteListener() {
133 if (mDocument) {
134 // The document must have been destroyed before we got our event.
135 // Otherwise this can't happen, since documents hold strong references to
136 // their observers.
137 Cancel();
141 public:
142 void EndLoad(Document* aDocument) override {
143 MOZ_ASSERT(aDocument == mDocument, "Got EndLoad for wrong document?");
145 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
146 // we stick around long enough to complete our work.
147 RefPtr<SVGParseCompleteListener> kungFuDeathGrip(this);
149 mImage->OnSVGDocumentParsed();
152 void Cancel() {
153 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
154 if (mDocument) {
155 mDocument->RemoveObserver(this);
156 mDocument = nullptr;
160 private:
161 RefPtr<SVGDocument> mDocument;
162 VectorImage* const mImage; // Raw pointer to owner.
165 NS_IMPL_ISUPPORTS(SVGParseCompleteListener, nsIDocumentObserver)
167 class SVGLoadEventListener final : public nsIDOMEventListener {
168 public:
169 NS_DECL_ISUPPORTS
171 SVGLoadEventListener(Document* aDocument, VectorImage* aImage)
172 : mDocument(aDocument), mImage(aImage) {
173 MOZ_ASSERT(mDocument, "Need an SVG document");
174 MOZ_ASSERT(mImage, "Need an image");
176 mDocument->AddEventListener(NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"),
177 this, true, false);
178 mDocument->AddEventListener(NS_LITERAL_STRING("SVGAbort"), this, true,
179 false);
180 mDocument->AddEventListener(NS_LITERAL_STRING("SVGError"), this, true,
181 false);
184 private:
185 ~SVGLoadEventListener() {
186 if (mDocument) {
187 // The document must have been destroyed before we got our event.
188 // Otherwise this can't happen, since documents hold strong references to
189 // their observers.
190 Cancel();
194 public:
195 NS_IMETHOD HandleEvent(Event* aEvent) override {
196 MOZ_ASSERT(mDocument, "Need an SVG document. Received multiple events?");
198 // OnSVGDocumentLoaded/OnSVGDocumentError will release our owner's reference
199 // to us, so ensure we stick around long enough to complete our work.
200 RefPtr<SVGLoadEventListener> kungFuDeathGrip(this);
202 nsAutoString eventType;
203 aEvent->GetType(eventType);
204 MOZ_ASSERT(eventType.EqualsLiteral("MozSVGAsImageDocumentLoad") ||
205 eventType.EqualsLiteral("SVGAbort") ||
206 eventType.EqualsLiteral("SVGError"),
207 "Received unexpected event");
209 if (eventType.EqualsLiteral("MozSVGAsImageDocumentLoad")) {
210 mImage->OnSVGDocumentLoaded();
211 } else {
212 mImage->OnSVGDocumentError();
215 return NS_OK;
218 void Cancel() {
219 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
220 if (mDocument) {
221 mDocument->RemoveEventListener(
222 NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), this, true);
223 mDocument->RemoveEventListener(NS_LITERAL_STRING("SVGAbort"), this, true);
224 mDocument->RemoveEventListener(NS_LITERAL_STRING("SVGError"), this, true);
225 mDocument = nullptr;
229 private:
230 nsCOMPtr<Document> mDocument;
231 VectorImage* const mImage; // Raw pointer to owner.
234 NS_IMPL_ISUPPORTS(SVGLoadEventListener, nsIDOMEventListener)
236 // Helper-class: SVGDrawingCallback
237 class SVGDrawingCallback : public gfxDrawingCallback {
238 public:
239 SVGDrawingCallback(SVGDocumentWrapper* aSVGDocumentWrapper,
240 const IntSize& aViewportSize, const IntSize& aSize,
241 uint32_t aImageFlags)
242 : mSVGDocumentWrapper(aSVGDocumentWrapper),
243 mViewportSize(aViewportSize),
244 mSize(aSize),
245 mImageFlags(aImageFlags) {}
246 virtual bool operator()(gfxContext* aContext, const gfxRect& aFillRect,
247 const SamplingFilter aSamplingFilter,
248 const gfxMatrix& aTransform) override;
250 private:
251 RefPtr<SVGDocumentWrapper> mSVGDocumentWrapper;
252 const IntSize mViewportSize;
253 const IntSize mSize;
254 uint32_t mImageFlags;
257 // Based loosely on nsSVGIntegrationUtils' PaintFrameCallback::operator()
258 bool SVGDrawingCallback::operator()(gfxContext* aContext,
259 const gfxRect& aFillRect,
260 const SamplingFilter aSamplingFilter,
261 const gfxMatrix& aTransform) {
262 MOZ_ASSERT(mSVGDocumentWrapper, "need an SVGDocumentWrapper");
264 // Get (& sanity-check) the helper-doc's presShell
265 nsCOMPtr<nsIPresShell> presShell = mSVGDocumentWrapper->GetPresShell();
266 MOZ_ASSERT(presShell, "GetPresShell returned null for an SVG image?");
268 #ifdef MOZ_GECKO_PROFILER
269 Document* doc = presShell->GetDocument();
270 nsIURI* uri = doc ? doc->GetDocumentURI() : nullptr;
271 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
272 "SVG Image drawing", GRAPHICS,
273 nsPrintfCString("%dx%d %s", mSize.width, mSize.height,
274 uri ? uri->GetSpecOrDefault().get() : "N/A"));
275 #endif
277 gfxContextAutoSaveRestore contextRestorer(aContext);
279 // Clip to aFillRect so that we don't paint outside.
280 aContext->NewPath();
281 aContext->Rectangle(aFillRect);
282 aContext->Clip();
284 gfxMatrix matrix = aTransform;
285 if (!matrix.Invert()) {
286 return false;
288 aContext->SetMatrixDouble(
289 aContext->CurrentMatrixDouble().PreMultiply(matrix).PreScale(
290 double(mSize.width) / mViewportSize.width,
291 double(mSize.height) / mViewportSize.height));
293 nsPresContext* presContext = presShell->GetPresContext();
294 MOZ_ASSERT(presContext, "pres shell w/out pres context");
296 nsRect svgRect(0, 0, presContext->DevPixelsToAppUnits(mViewportSize.width),
297 presContext->DevPixelsToAppUnits(mViewportSize.height));
299 uint32_t renderDocFlags = nsIPresShell::RENDER_IGNORE_VIEWPORT_SCROLLING;
300 if (!(mImageFlags & imgIContainer::FLAG_SYNC_DECODE)) {
301 renderDocFlags |= nsIPresShell::RENDER_ASYNC_DECODE_IMAGES;
304 presShell->RenderDocument(svgRect, renderDocFlags,
305 NS_RGBA(0, 0, 0, 0), // transparent
306 aContext);
308 return true;
311 class MOZ_STACK_CLASS AutoRestoreSVGState final {
312 public:
313 AutoRestoreSVGState(const SVGDrawingParameters& aParams,
314 SVGDocumentWrapper* aSVGDocumentWrapper, bool& aIsDrawing,
315 bool aContextPaint)
316 : mIsDrawing(aIsDrawing)
317 // Apply any 'preserveAspectRatio' override (if specified) to the root
318 // element:
320 mPAR(aParams.svgContext, aSVGDocumentWrapper->GetRootSVGElem())
321 // Set the animation time:
323 mTime(aSVGDocumentWrapper->GetRootSVGElem(), aParams.animationTime) {
324 MOZ_ASSERT(!aIsDrawing);
325 MOZ_ASSERT(aSVGDocumentWrapper->GetDocument());
327 aIsDrawing = true;
329 // Set context paint (if specified) on the document:
330 if (aContextPaint) {
331 MOZ_ASSERT(aParams.svgContext->GetContextPaint());
332 mContextPaint.emplace(*aParams.svgContext->GetContextPaint(),
333 *aSVGDocumentWrapper->GetDocument());
337 private:
338 AutoRestore<bool> mIsDrawing;
339 AutoPreserveAspectRatioOverride mPAR;
340 AutoSVGTimeSetRestore mTime;
341 Maybe<AutoSetRestoreSVGContextPaint> mContextPaint;
344 // Implement VectorImage's nsISupports-inherited methods
345 NS_IMPL_ISUPPORTS(VectorImage, imgIContainer, nsIStreamListener,
346 nsIRequestObserver)
348 //------------------------------------------------------------------------------
349 // Constructor / Destructor
351 VectorImage::VectorImage(nsIURI* aURI /* = nullptr */)
352 : ImageResource(aURI), // invoke superclass's constructor
353 mLockCount(0),
354 mIsInitialized(false),
355 mDiscardable(false),
356 mIsFullyLoaded(false),
357 mIsDrawing(false),
358 mHaveAnimations(false),
359 mHasPendingInvalidation(false) {}
361 VectorImage::~VectorImage() {
362 CancelAllListeners();
363 SurfaceCache::RemoveImage(ImageKey(this));
366 //------------------------------------------------------------------------------
367 // Methods inherited from Image.h
369 nsresult VectorImage::Init(const char* aMimeType, uint32_t aFlags) {
370 // We don't support re-initialization
371 if (mIsInitialized) {
372 return NS_ERROR_ILLEGAL_VALUE;
375 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations && !mError,
376 "Flags unexpectedly set before initialization");
377 MOZ_ASSERT(!strcmp(aMimeType, IMAGE_SVG_XML), "Unexpected mimetype");
379 mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE);
381 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
382 if (!mDiscardable) {
383 mLockCount++;
384 SurfaceCache::LockImage(ImageKey(this));
387 mIsInitialized = true;
388 return NS_OK;
391 size_t VectorImage::SizeOfSourceWithComputedFallback(
392 SizeOfState& aState) const {
393 if (!mSVGDocumentWrapper) {
394 return 0; // No document, so no memory used for the document.
397 SVGDocument* doc = mSVGDocumentWrapper->GetDocument();
398 if (!doc) {
399 return 0; // No document, so no memory used for the document.
402 nsWindowSizes windowSizes(aState);
403 doc->DocAddSizeOfIncludingThis(windowSizes);
405 if (windowSizes.getTotalSize() == 0) {
406 // MallocSizeOf fails on this platform. Because we also use this method for
407 // determining the size of cache entries, we need to return something
408 // reasonable here. Unfortunately, there's no way to estimate the document's
409 // size accurately, so we just use a constant value of 100KB, which will
410 // generally underestimate the true size.
411 return 100 * 1024;
414 return windowSizes.getTotalSize();
417 void VectorImage::CollectSizeOfSurfaces(
418 nsTArray<SurfaceMemoryCounter>& aCounters,
419 MallocSizeOf aMallocSizeOf) const {
420 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters, aMallocSizeOf);
423 nsresult VectorImage::OnImageDataComplete(nsIRequest* aRequest,
424 nsISupports* aContext,
425 nsresult aStatus, bool aLastPart) {
426 // Call our internal OnStopRequest method, which only talks to our embedded
427 // SVG document. This won't have any effect on our ProgressTracker.
428 nsresult finalStatus = OnStopRequest(aRequest, aContext, aStatus);
430 // Give precedence to Necko failure codes.
431 if (NS_FAILED(aStatus)) {
432 finalStatus = aStatus;
435 Progress loadProgress = LoadCompleteProgress(aLastPart, mError, finalStatus);
437 if (mIsFullyLoaded || mError) {
438 // Our document is loaded, so we're ready to notify now.
439 mProgressTracker->SyncNotifyProgress(loadProgress);
440 } else {
441 // Record our progress so far; we'll actually send the notifications in
442 // OnSVGDocumentLoaded or OnSVGDocumentError.
443 mLoadProgress = Some(loadProgress);
446 return finalStatus;
449 nsresult VectorImage::OnImageDataAvailable(nsIRequest* aRequest,
450 nsISupports* aContext,
451 nsIInputStream* aInStr,
452 uint64_t aSourceOffset,
453 uint32_t aCount) {
454 return OnDataAvailable(aRequest, aContext, aInStr, aSourceOffset, aCount);
457 nsresult VectorImage::StartAnimation() {
458 if (mError) {
459 return NS_ERROR_FAILURE;
462 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
464 mSVGDocumentWrapper->StartAnimation();
465 return NS_OK;
468 nsresult VectorImage::StopAnimation() {
469 nsresult rv = NS_OK;
470 if (mError) {
471 rv = NS_ERROR_FAILURE;
472 } else {
473 MOZ_ASSERT(mIsFullyLoaded && mHaveAnimations,
474 "Should not have been animating!");
476 mSVGDocumentWrapper->StopAnimation();
479 mAnimating = false;
480 return rv;
483 bool VectorImage::ShouldAnimate() {
484 return ImageResource::ShouldAnimate() && mIsFullyLoaded && mHaveAnimations;
487 NS_IMETHODIMP_(void)
488 VectorImage::SetAnimationStartTime(const TimeStamp& aTime) {
489 // We don't care about animation start time.
492 //------------------------------------------------------------------------------
493 // imgIContainer methods
495 //******************************************************************************
496 NS_IMETHODIMP
497 VectorImage::GetWidth(int32_t* aWidth) {
498 if (mError || !mIsFullyLoaded) {
499 // XXXdholbert Technically we should leave outparam untouched when we
500 // fail. But since many callers don't check for failure, we set it to 0 on
501 // failure, for sane/predictable results.
502 *aWidth = 0;
503 return NS_ERROR_FAILURE;
506 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
507 MOZ_ASSERT(rootElem,
508 "Should have a root SVG elem, since we finished "
509 "loading without errors");
510 int32_t rootElemWidth = rootElem->GetIntrinsicWidth();
511 if (rootElemWidth < 0) {
512 *aWidth = 0;
513 return NS_ERROR_FAILURE;
515 *aWidth = rootElemWidth;
516 return NS_OK;
519 //******************************************************************************
520 nsresult VectorImage::GetNativeSizes(nsTArray<IntSize>& aNativeSizes) const {
521 return NS_ERROR_NOT_IMPLEMENTED;
524 //******************************************************************************
525 size_t VectorImage::GetNativeSizesLength() const { return 0; }
527 //******************************************************************************
528 NS_IMETHODIMP_(void)
529 VectorImage::RequestRefresh(const TimeStamp& aTime) {
530 if (HadRecentRefresh(aTime)) {
531 return;
534 PendingAnimationTracker* tracker =
535 mSVGDocumentWrapper->GetDocument()->GetPendingAnimationTracker();
536 if (tracker && ShouldAnimate()) {
537 tracker->TriggerPendingAnimationsOnNextTick(aTime);
540 EvaluateAnimation();
542 mSVGDocumentWrapper->TickRefreshDriver();
544 if (mHasPendingInvalidation) {
545 SendInvalidationNotifications();
549 void VectorImage::SendInvalidationNotifications() {
550 // Animated images don't send out invalidation notifications as soon as
551 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
552 // records that there are pending invalidations and then returns immediately.
553 // The notifications are actually sent from RequestRefresh(). We send these
554 // notifications there to ensure that there is actually a document observing
555 // us. Otherwise, the notifications are just wasted effort.
557 // Non-animated images post an event to call this method from
558 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
559 // called for them. Ordinarily this isn't needed, since we send out
560 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
561 // SVG document may not be 100% ready to render at that time. In those cases
562 // we would miss the subsequent invalidations if we didn't send out the
563 // notifications indirectly in |InvalidateObservers...|.
565 MOZ_ASSERT(mHasPendingInvalidation);
566 mHasPendingInvalidation = false;
567 SurfaceCache::RemoveImage(ImageKey(this));
569 if (UpdateImageContainer(Nothing())) {
570 // If we have image containers, that means we probably won't get a Draw call
571 // from the owner since they are using the container. We must assume all
572 // invalidations need to be handled.
573 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
574 mRenderingObserver->ResumeHonoringInvalidations();
577 if (mProgressTracker) {
578 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
579 GetMaxSizedIntRect());
583 NS_IMETHODIMP_(IntRect)
584 VectorImage::GetImageSpaceInvalidationRect(const IntRect& aRect) {
585 return aRect;
588 //******************************************************************************
589 NS_IMETHODIMP
590 VectorImage::GetHeight(int32_t* aHeight) {
591 if (mError || !mIsFullyLoaded) {
592 // XXXdholbert Technically we should leave outparam untouched when we
593 // fail. But since many callers don't check for failure, we set it to 0 on
594 // failure, for sane/predictable results.
595 *aHeight = 0;
596 return NS_ERROR_FAILURE;
599 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
600 MOZ_ASSERT(rootElem,
601 "Should have a root SVG elem, since we finished "
602 "loading without errors");
603 int32_t rootElemHeight = rootElem->GetIntrinsicHeight();
604 if (rootElemHeight < 0) {
605 *aHeight = 0;
606 return NS_ERROR_FAILURE;
608 *aHeight = rootElemHeight;
609 return NS_OK;
612 //******************************************************************************
613 NS_IMETHODIMP
614 VectorImage::GetIntrinsicSize(nsSize* aSize) {
615 if (mError || !mIsFullyLoaded) {
616 return NS_ERROR_FAILURE;
619 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
620 if (!rootFrame) {
621 return NS_ERROR_FAILURE;
624 *aSize = nsSize(-1, -1);
625 IntrinsicSize rfSize = rootFrame->GetIntrinsicSize();
626 if (rfSize.width.GetUnit() == eStyleUnit_Coord) {
627 aSize->width = rfSize.width.GetCoordValue();
629 if (rfSize.height.GetUnit() == eStyleUnit_Coord) {
630 aSize->height = rfSize.height.GetCoordValue();
633 return NS_OK;
636 //******************************************************************************
637 NS_IMETHODIMP
638 VectorImage::GetIntrinsicRatio(nsSize* aRatio) {
639 if (mError || !mIsFullyLoaded) {
640 return NS_ERROR_FAILURE;
643 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
644 if (!rootFrame) {
645 return NS_ERROR_FAILURE;
648 *aRatio = rootFrame->GetIntrinsicRatio();
649 return NS_OK;
652 NS_IMETHODIMP_(Orientation)
653 VectorImage::GetOrientation() { return Orientation(); }
655 //******************************************************************************
656 NS_IMETHODIMP
657 VectorImage::GetType(uint16_t* aType) {
658 NS_ENSURE_ARG_POINTER(aType);
660 *aType = imgIContainer::TYPE_VECTOR;
661 return NS_OK;
664 //******************************************************************************
665 NS_IMETHODIMP
666 VectorImage::GetAnimated(bool* aAnimated) {
667 if (mError || !mIsFullyLoaded) {
668 return NS_ERROR_FAILURE;
671 *aAnimated = mSVGDocumentWrapper->IsAnimated();
672 return NS_OK;
675 //******************************************************************************
676 int32_t VectorImage::GetFirstFrameDelay() {
677 if (mError) {
678 return -1;
681 if (!mSVGDocumentWrapper->IsAnimated()) {
682 return -1;
685 // We don't really have a frame delay, so just pretend that we constantly
686 // need updates.
687 return 0;
690 NS_IMETHODIMP_(bool)
691 VectorImage::WillDrawOpaqueNow() {
692 return false; // In general, SVG content is not opaque.
695 //******************************************************************************
696 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
697 VectorImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
698 if (mError) {
699 return nullptr;
702 // Look up height & width
703 // ----------------------
704 SVGSVGElement* svgElem = mSVGDocumentWrapper->GetRootSVGElem();
705 MOZ_ASSERT(svgElem,
706 "Should have a root SVG elem, since we finished "
707 "loading without errors");
708 nsIntSize imageIntSize(svgElem->GetIntrinsicWidth(),
709 svgElem->GetIntrinsicHeight());
711 if (imageIntSize.IsEmpty()) {
712 // We'll get here if our SVG doc has a percent-valued or negative width or
713 // height.
714 return nullptr;
717 return GetFrameAtSize(imageIntSize, aWhichFrame, aFlags);
720 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
721 VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
722 uint32_t aFlags) {
723 #ifdef DEBUG
724 NotifyDrawingObservers();
725 #endif
727 auto result = GetFrameInternal(aSize, Nothing(), aWhichFrame, aFlags);
728 return Get<2>(result).forget();
731 Tuple<ImgDrawResult, IntSize, RefPtr<SourceSurface>>
732 VectorImage::GetFrameInternal(const IntSize& aSize,
733 const Maybe<SVGImageContext>& aSVGContext,
734 uint32_t aWhichFrame, uint32_t aFlags) {
735 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE);
737 if (aSize.IsEmpty() || aWhichFrame > FRAME_MAX_VALUE) {
738 return MakeTuple(ImgDrawResult::BAD_ARGS, aSize, RefPtr<SourceSurface>());
741 if (mError) {
742 return MakeTuple(ImgDrawResult::BAD_IMAGE, aSize, RefPtr<SourceSurface>());
745 if (!mIsFullyLoaded) {
746 return MakeTuple(ImgDrawResult::NOT_READY, aSize, RefPtr<SourceSurface>());
749 // We don't allow large surfaces to be rasterized on the Draw and
750 // GetImageContainerAtSize paths, because those have alternatives. If we get
751 // here however, then we know it came from GetFrame(AtSize) and that path does
752 // not have any fallback method, so we don't check UseSurfaceCacheForSize.
753 RefPtr<SourceSurface> sourceSurface;
754 IntSize decodeSize;
755 Tie(sourceSurface, decodeSize) =
756 LookupCachedSurface(aSize, aSVGContext, aFlags);
757 if (sourceSurface) {
758 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize,
759 std::move(sourceSurface));
762 if (mIsDrawing) {
763 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
764 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
765 RefPtr<SourceSurface>());
768 // By using a null gfxContext, we ensure that we will always attempt to
769 // create a surface, even if we aren't capable of caching it (e.g. due to our
770 // flags, having an animation, etc). Otherwise CreateSurface will assume that
771 // the caller is capable of drawing directly to its own draw target if we
772 // cannot cache.
773 SVGDrawingParameters params(
774 nullptr, decodeSize, aSize, ImageRegion::Create(decodeSize),
775 SamplingFilter::POINT, aSVGContext,
776 mSVGDocumentWrapper->GetCurrentTimeAsFloat(), aFlags, 1.0);
778 bool didCache; // Was the surface put into the cache?
779 bool contextPaint = aSVGContext && aSVGContext->GetContextPaint();
781 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, mIsDrawing,
782 contextPaint);
784 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
785 RefPtr<SourceSurface> surface = CreateSurface(params, svgDrawable, didCache);
786 if (!surface) {
787 MOZ_ASSERT(!didCache);
788 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
789 RefPtr<SourceSurface>());
792 SendFrameComplete(didCache, params.flags);
793 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize, std::move(surface));
796 //******************************************************************************
797 Tuple<ImgDrawResult, IntSize> VectorImage::GetImageContainerSize(
798 LayerManager* aManager, const IntSize& aSize, uint32_t aFlags) {
799 if (mError) {
800 return MakeTuple(ImgDrawResult::BAD_IMAGE, IntSize(0, 0));
803 if (!mIsFullyLoaded) {
804 return MakeTuple(ImgDrawResult::NOT_READY, IntSize(0, 0));
807 if (mHaveAnimations ||
808 aManager->GetBackendType() != LayersBackend::LAYERS_WR) {
809 return MakeTuple(ImgDrawResult::NOT_SUPPORTED, IntSize(0, 0));
812 // We don't need to check if the size is too big since we only support
813 // WebRender backends.
814 if (aSize.IsEmpty()) {
815 return MakeTuple(ImgDrawResult::BAD_ARGS, IntSize(0, 0));
818 return MakeTuple(ImgDrawResult::SUCCESS, aSize);
821 NS_IMETHODIMP_(bool)
822 VectorImage::IsImageContainerAvailable(LayerManager* aManager,
823 uint32_t aFlags) {
824 if (mError || !mIsFullyLoaded || mHaveAnimations ||
825 aManager->GetBackendType() != LayersBackend::LAYERS_WR) {
826 return false;
829 return true;
832 //******************************************************************************
833 NS_IMETHODIMP_(already_AddRefed<ImageContainer>)
834 VectorImage::GetImageContainer(LayerManager* aManager, uint32_t aFlags) {
835 MOZ_ASSERT(aManager->GetBackendType() != LayersBackend::LAYERS_WR,
836 "WebRender should always use GetImageContainerAvailableAtSize!");
837 return nullptr;
840 //******************************************************************************
841 NS_IMETHODIMP_(bool)
842 VectorImage::IsImageContainerAvailableAtSize(LayerManager* aManager,
843 const IntSize& aSize,
844 uint32_t aFlags) {
845 // Since we only support image containers with WebRender, and it can handle
846 // textures larger than the hw max texture size, we don't need to check aSize.
847 return !aSize.IsEmpty() && UseSurfaceCacheForSize(aSize) &&
848 IsImageContainerAvailable(aManager, aFlags);
851 //******************************************************************************
852 NS_IMETHODIMP_(ImgDrawResult)
853 VectorImage::GetImageContainerAtSize(layers::LayerManager* aManager,
854 const gfx::IntSize& aSize,
855 const Maybe<SVGImageContext>& aSVGContext,
856 uint32_t aFlags,
857 layers::ImageContainer** aOutContainer) {
858 if (!UseSurfaceCacheForSize(aSize)) {
859 return ImgDrawResult::NOT_SUPPORTED;
862 Maybe<SVGImageContext> newSVGContext;
863 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
865 // The aspect ratio flag was already handled as part of the SVG context
866 // restriction above.
867 uint32_t flags = aFlags & ~(FLAG_FORCE_PRESERVEASPECTRATIO_NONE);
868 return GetImageContainerImpl(aManager, aSize,
869 newSVGContext ? newSVGContext : aSVGContext,
870 flags, aOutContainer);
873 bool VectorImage::MaybeRestrictSVGContext(
874 Maybe<SVGImageContext>& aNewSVGContext,
875 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags) {
876 bool overridePAR =
877 (aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) && aSVGContext;
879 bool haveContextPaint = aSVGContext && aSVGContext->GetContextPaint();
880 bool blockContextPaint = false;
881 if (haveContextPaint) {
882 blockContextPaint = !SVGContextPaint::IsAllowedForImageFromURI(mURI);
885 if (overridePAR || blockContextPaint) {
886 // The key that we create for the image surface cache must match the way
887 // that the image will be painted, so we need to initialize a new matching
888 // SVGImageContext here in order to generate the correct key.
890 aNewSVGContext = aSVGContext; // copy
892 if (overridePAR) {
893 // The SVGImageContext must take account of the preserveAspectRatio
894 // overide:
895 MOZ_ASSERT(!aSVGContext->GetPreserveAspectRatio(),
896 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
897 "preserveAspectRatio override is supplied");
898 Maybe<SVGPreserveAspectRatio> aspectRatio = Some(SVGPreserveAspectRatio(
899 SVG_PRESERVEASPECTRATIO_NONE, SVG_MEETORSLICE_UNKNOWN));
900 aNewSVGContext->SetPreserveAspectRatio(aspectRatio);
903 if (blockContextPaint) {
904 // The SVGImageContext must not include context paint if the image is
905 // not allowed to use it:
906 aNewSVGContext->ClearContextPaint();
910 return haveContextPaint && !blockContextPaint;
913 //******************************************************************************
914 NS_IMETHODIMP_(ImgDrawResult)
915 VectorImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
916 const ImageRegion& aRegion, uint32_t aWhichFrame,
917 SamplingFilter aSamplingFilter,
918 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags,
919 float aOpacity) {
920 if (aWhichFrame > FRAME_MAX_VALUE) {
921 return ImgDrawResult::BAD_ARGS;
924 if (!aContext) {
925 return ImgDrawResult::BAD_ARGS;
928 if (mError) {
929 return ImgDrawResult::BAD_IMAGE;
932 if (!mIsFullyLoaded) {
933 return ImgDrawResult::NOT_READY;
936 if (mAnimationConsumers == 0) {
937 SendOnUnlockedDraw(aFlags);
940 // We should bypass the cache when:
941 // - We are using a DrawTargetRecording because we prefer the drawing commands
942 // in general to the rasterized surface. This allows blob images to avoid
943 // rasterized SVGs with WebRender.
944 // - The size exceeds what we are will to cache as a rasterized surface.
945 if (aContext->GetDrawTarget()->GetBackendType() == BackendType::RECORDING ||
946 !UseSurfaceCacheForSize(aSize)) {
947 aFlags |= FLAG_BYPASS_SURFACE_CACHE;
950 MOZ_ASSERT(!(aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) ||
951 (aSVGContext && aSVGContext->GetViewportSize()),
952 "Viewport size is required when using "
953 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
955 float animTime = (aWhichFrame == FRAME_FIRST)
956 ? 0.0f
957 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
959 Maybe<SVGImageContext> newSVGContext;
960 bool contextPaint =
961 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
963 SVGDrawingParameters params(aContext, aSize, aSize, aRegion, aSamplingFilter,
964 newSVGContext ? newSVGContext : aSVGContext,
965 animTime, aFlags, aOpacity);
967 // If we have an prerasterized version of this image that matches the
968 // drawing parameters, use that.
969 RefPtr<SourceSurface> sourceSurface;
970 Tie(sourceSurface, params.size) =
971 LookupCachedSurface(aSize, params.svgContext, aFlags);
972 if (sourceSurface) {
973 RefPtr<gfxDrawable> drawable =
974 new gfxSurfaceDrawable(sourceSurface, params.size);
975 Show(drawable, params);
976 return ImgDrawResult::SUCCESS;
979 // else, we need to paint the image:
981 if (mIsDrawing) {
982 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
983 return ImgDrawResult::TEMPORARY_ERROR;
986 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, mIsDrawing,
987 contextPaint);
989 bool didCache; // Was the surface put into the cache?
990 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
991 sourceSurface = CreateSurface(params, svgDrawable, didCache);
992 if (!sourceSurface) {
993 MOZ_ASSERT(!didCache);
994 Show(svgDrawable, params);
995 return ImgDrawResult::SUCCESS;
998 RefPtr<gfxDrawable> drawable =
999 new gfxSurfaceDrawable(sourceSurface, params.size);
1000 Show(drawable, params);
1001 SendFrameComplete(didCache, params.flags);
1002 return ImgDrawResult::SUCCESS;
1005 already_AddRefed<gfxDrawable> VectorImage::CreateSVGDrawable(
1006 const SVGDrawingParameters& aParams) {
1007 RefPtr<gfxDrawingCallback> cb = new SVGDrawingCallback(
1008 mSVGDocumentWrapper, aParams.viewportSize, aParams.size, aParams.flags);
1010 RefPtr<gfxDrawable> svgDrawable = new gfxCallbackDrawable(cb, aParams.size);
1011 return svgDrawable.forget();
1014 bool VectorImage::UseSurfaceCacheForSize(const IntSize& aSize) const {
1015 int32_t maxSizeKB = gfxPrefs::ImageCacheMaxRasterizedSVGThresholdKB();
1016 if (maxSizeKB <= 0) {
1017 return true;
1020 if (!SurfaceCache::IsLegalSize(aSize)) {
1021 return false;
1024 // With factor of 2 mode, we should be willing to use a surface which is up
1025 // to twice the width, and twice the height, of the maximum sized surface
1026 // before switching to drawing to the target directly. That means the size in
1027 // KB works out to be:
1028 // width * height * 4 [bytes/pixel] * / 1024 [bytes/KB] <= 2 * 2 * maxSizeKB
1029 return aSize.width * aSize.height / 1024 <= maxSizeKB;
1032 Tuple<RefPtr<SourceSurface>, IntSize> VectorImage::LookupCachedSurface(
1033 const IntSize& aSize, const Maybe<SVGImageContext>& aSVGContext,
1034 uint32_t aFlags) {
1035 // If we're not allowed to use a cached surface, don't attempt a lookup.
1036 if (aFlags & FLAG_BYPASS_SURFACE_CACHE) {
1037 return MakeTuple(RefPtr<SourceSurface>(), aSize);
1040 // We don't do any caching if we have animation, so don't bother with a lookup
1041 // in this case either.
1042 if (mHaveAnimations) {
1043 return MakeTuple(RefPtr<SourceSurface>(), aSize);
1046 LookupResult result(MatchType::NOT_FOUND);
1047 SurfaceKey surfaceKey = VectorSurfaceKey(aSize, aSVGContext);
1048 if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
1049 result = SurfaceCache::Lookup(ImageKey(this), surfaceKey,
1050 /* aMarkUsed = */ true);
1051 } else {
1052 result = SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey,
1053 /* aMarkUsed = */ true);
1056 IntSize rasterSize =
1057 result.SuggestedSize().IsEmpty() ? aSize : result.SuggestedSize();
1058 MOZ_ASSERT(result.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING);
1059 if (!result || result.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND) {
1060 // No matching surface, or the OS freed the volatile buffer.
1061 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1064 RefPtr<SourceSurface> sourceSurface = result.Surface()->GetSourceSurface();
1065 if (!sourceSurface) {
1066 // Something went wrong. (Probably a GPU driver crash or device reset.)
1067 // Attempt to recover.
1068 RecoverFromLossOfSurfaces();
1069 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1072 return MakeTuple(std::move(sourceSurface), rasterSize);
1075 already_AddRefed<SourceSurface> VectorImage::CreateSurface(
1076 const SVGDrawingParameters& aParams, gfxDrawable* aSVGDrawable,
1077 bool& aWillCache) {
1078 MOZ_ASSERT(mIsDrawing);
1080 mSVGDocumentWrapper->UpdateViewportBounds(aParams.viewportSize);
1081 mSVGDocumentWrapper->FlushImageTransformInvalidation();
1083 // Determine whether or not we should put the surface to be created into
1084 // the cache. If we fail, we need to reset this to false to let the caller
1085 // know nothing was put in the cache.
1086 aWillCache = !(aParams.flags & FLAG_BYPASS_SURFACE_CACHE) &&
1087 // Refuse to cache animated images:
1088 // XXX(seth): We may remove this restriction in bug 922893.
1089 !mHaveAnimations &&
1090 // The image is too big to fit in the cache:
1091 SurfaceCache::CanHold(aParams.size);
1093 // If we weren't given a context, then we know we just want the rasterized
1094 // surface. We will create the frame below but only insert it into the cache
1095 // if we actually need to.
1096 if (!aWillCache && aParams.context) {
1097 return nullptr;
1100 // We're about to rerasterize, which may mean that some of the previous
1101 // surfaces we've rasterized aren't useful anymore. We can allow them to
1102 // expire from the cache by unlocking them here, and then sending out an
1103 // invalidation. If this image is locked, any surfaces that are still useful
1104 // will become locked again when Draw touches them, and the remainder will
1105 // eventually expire.
1106 if (aWillCache) {
1107 SurfaceCache::UnlockEntries(ImageKey(this));
1110 // If there is no context, the default backend is fine.
1111 BackendType backend =
1112 aParams.context ? aParams.context->GetDrawTarget()->GetBackendType()
1113 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1115 // Try to create an imgFrame, initializing the surface it contains by drawing
1116 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1117 auto frame = MakeNotNull<RefPtr<imgFrame>>();
1118 nsresult rv = frame->InitWithDrawable(
1119 aSVGDrawable, aParams.size, SurfaceFormat::B8G8R8A8,
1120 SamplingFilter::POINT, aParams.flags, backend,
1121 aParams.context ? aParams.context->GetDrawTarget() : nullptr);
1123 // If we couldn't create the frame, it was probably because it would end
1124 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1125 // could be set such that the cache isn't the limiting factor.
1126 if (NS_FAILED(rv)) {
1127 aWillCache = false;
1128 return nullptr;
1131 // Take a strong reference to the frame's surface and make sure it hasn't
1132 // already been purged by the operating system.
1133 RefPtr<SourceSurface> surface = frame->GetSourceSurface();
1134 if (!surface) {
1135 aWillCache = false;
1136 return nullptr;
1139 // We created the frame, but only because we had no context to draw to
1140 // directly. All the caller wants is the surface in this case.
1141 if (!aWillCache) {
1142 return surface.forget();
1145 // Attempt to cache the frame.
1146 SurfaceKey surfaceKey = VectorSurfaceKey(aParams.size, aParams.svgContext);
1147 NotNull<RefPtr<ISurfaceProvider>> provider =
1148 MakeNotNull<SimpleSurfaceProvider*>(ImageKey(this), surfaceKey, frame);
1150 if (SurfaceCache::Insert(provider) == InsertOutcome::SUCCESS &&
1151 aParams.size != aParams.drawSize) {
1152 // We created a new surface that wasn't the size we requested, which means
1153 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1154 // need rather than waiting for the cache to expire them.
1155 SurfaceCache::PruneImage(ImageKey(this));
1158 return surface.forget();
1161 void VectorImage::SendFrameComplete(bool aDidCache, uint32_t aFlags) {
1162 // If the cache was not updated, we have nothing to do.
1163 if (!aDidCache) {
1164 return;
1167 // Send out an invalidation so that surfaces that are still in use get
1168 // re-locked. See the discussion of the UnlockSurfaces call above.
1169 if (!(aFlags & FLAG_ASYNC_NOTIFY)) {
1170 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1171 GetMaxSizedIntRect());
1172 } else {
1173 NotNull<RefPtr<VectorImage>> image = WrapNotNull(this);
1174 NS_DispatchToMainThread(NS_NewRunnableFunction(
1175 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1176 RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
1177 if (tracker) {
1178 tracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1179 GetMaxSizedIntRect());
1181 }));
1185 void VectorImage::Show(gfxDrawable* aDrawable,
1186 const SVGDrawingParameters& aParams) {
1187 // The surface size may differ from the size at which we wish to draw. As
1188 // such, we may need to adjust the context/region to take this into account.
1189 gfxContextMatrixAutoSaveRestore saveMatrix(aParams.context);
1190 ImageRegion region(aParams.region);
1191 if (aParams.drawSize != aParams.size) {
1192 gfx::Size scale(double(aParams.drawSize.width) / aParams.size.width,
1193 double(aParams.drawSize.height) / aParams.size.height);
1194 aParams.context->Multiply(gfxMatrix::Scaling(scale.width, scale.height));
1195 region.Scale(1.0 / scale.width, 1.0 / scale.height);
1198 MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
1199 gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
1200 SizeDouble(aParams.size), region,
1201 SurfaceFormat::B8G8R8A8, aParams.samplingFilter,
1202 aParams.flags, aParams.opacity, false);
1204 #ifdef DEBUG
1205 NotifyDrawingObservers();
1206 #endif
1208 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
1209 mRenderingObserver->ResumeHonoringInvalidations();
1212 void VectorImage::RecoverFromLossOfSurfaces() {
1213 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1215 // Discard all existing frames, since they're probably all now invalid.
1216 SurfaceCache::RemoveImage(ImageKey(this));
1219 NS_IMETHODIMP
1220 VectorImage::StartDecoding(uint32_t aFlags) {
1221 // Nothing to do for SVG images
1222 return NS_OK;
1225 bool VectorImage::StartDecodingWithResult(uint32_t aFlags) {
1226 // SVG images are ready to draw when they are loaded
1227 return mIsFullyLoaded;
1230 NS_IMETHODIMP
1231 VectorImage::RequestDecodeForSize(const nsIntSize& aSize, uint32_t aFlags) {
1232 // Nothing to do for SVG images, though in theory we could rasterize to the
1233 // provided size ahead of time if we supported off-main-thread SVG
1234 // rasterization...
1235 return NS_OK;
1238 //******************************************************************************
1240 NS_IMETHODIMP
1241 VectorImage::LockImage() {
1242 MOZ_ASSERT(NS_IsMainThread());
1244 if (mError) {
1245 return NS_ERROR_FAILURE;
1248 mLockCount++;
1250 if (mLockCount == 1) {
1251 // Lock this image's surfaces in the SurfaceCache.
1252 SurfaceCache::LockImage(ImageKey(this));
1255 return NS_OK;
1258 //******************************************************************************
1260 NS_IMETHODIMP
1261 VectorImage::UnlockImage() {
1262 MOZ_ASSERT(NS_IsMainThread());
1264 if (mError) {
1265 return NS_ERROR_FAILURE;
1268 if (mLockCount == 0) {
1269 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1270 return NS_ERROR_ABORT;
1273 mLockCount--;
1275 if (mLockCount == 0) {
1276 // Unlock this image's surfaces in the SurfaceCache.
1277 SurfaceCache::UnlockImage(ImageKey(this));
1280 return NS_OK;
1283 //******************************************************************************
1285 NS_IMETHODIMP
1286 VectorImage::RequestDiscard() {
1287 MOZ_ASSERT(NS_IsMainThread());
1289 if (mDiscardable && mLockCount == 0) {
1290 SurfaceCache::RemoveImage(ImageKey(this));
1291 mProgressTracker->OnDiscard();
1294 return NS_OK;
1297 void VectorImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) {
1298 MOZ_ASSERT(mProgressTracker);
1300 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1301 mProgressTracker,
1302 &ProgressTracker::OnDiscard));
1305 //******************************************************************************
1306 NS_IMETHODIMP
1307 VectorImage::ResetAnimation() {
1308 if (mError) {
1309 return NS_ERROR_FAILURE;
1312 if (!mIsFullyLoaded || !mHaveAnimations) {
1313 return NS_OK; // There are no animations to be reset.
1316 mSVGDocumentWrapper->ResetAnimation();
1318 return NS_OK;
1321 NS_IMETHODIMP_(float)
1322 VectorImage::GetFrameIndex(uint32_t aWhichFrame) {
1323 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
1324 return aWhichFrame == FRAME_FIRST
1325 ? 0.0f
1326 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1329 //------------------------------------------------------------------------------
1330 // nsIRequestObserver methods
1332 //******************************************************************************
1333 NS_IMETHODIMP
1334 VectorImage::OnStartRequest(nsIRequest* aRequest, nsISupports* aCtxt) {
1335 MOZ_ASSERT(!mSVGDocumentWrapper,
1336 "Repeated call to OnStartRequest -- can this happen?");
1338 mSVGDocumentWrapper = new SVGDocumentWrapper();
1339 nsresult rv = mSVGDocumentWrapper->OnStartRequest(aRequest, aCtxt);
1340 if (NS_FAILED(rv)) {
1341 mSVGDocumentWrapper = nullptr;
1342 mError = true;
1343 return rv;
1346 // Create a listener to wait until the SVG document is fully loaded, which
1347 // will signal that this image is ready to render. Certain error conditions
1348 // will prevent us from ever getting this notification, so we also create a
1349 // listener that waits for parsing to complete and cancels the
1350 // SVGLoadEventListener if needed. The listeners are automatically attached
1351 // to the document by their constructors.
1352 SVGDocument* document = mSVGDocumentWrapper->GetDocument();
1353 mLoadEventListener = new SVGLoadEventListener(document, this);
1354 mParseCompleteListener = new SVGParseCompleteListener(document, this);
1356 return NS_OK;
1359 //******************************************************************************
1360 NS_IMETHODIMP
1361 VectorImage::OnStopRequest(nsIRequest* aRequest, nsISupports* aCtxt,
1362 nsresult aStatus) {
1363 if (mError) {
1364 return NS_ERROR_FAILURE;
1367 return mSVGDocumentWrapper->OnStopRequest(aRequest, aCtxt, aStatus);
1370 void VectorImage::OnSVGDocumentParsed() {
1371 MOZ_ASSERT(mParseCompleteListener, "Should have the parse complete listener");
1372 MOZ_ASSERT(mLoadEventListener, "Should have the load event listener");
1374 if (!mSVGDocumentWrapper->GetRootSVGElem()) {
1375 // This is an invalid SVG document. It may have failed to parse, or it may
1376 // be missing the <svg> root element, or the <svg> root element may not
1377 // declare the correct namespace. In any of these cases, we'll never be
1378 // notified that the SVG finished loading, so we need to treat this as an
1379 // error.
1380 OnSVGDocumentError();
1384 void VectorImage::CancelAllListeners() {
1385 if (mParseCompleteListener) {
1386 mParseCompleteListener->Cancel();
1387 mParseCompleteListener = nullptr;
1389 if (mLoadEventListener) {
1390 mLoadEventListener->Cancel();
1391 mLoadEventListener = nullptr;
1395 void VectorImage::OnSVGDocumentLoaded() {
1396 MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(),
1397 "Should have parsed successfully");
1398 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations,
1399 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1400 "Duplicate calls to OnSVGDocumentLoaded?");
1402 CancelAllListeners();
1404 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1405 mSVGDocumentWrapper->FlushLayout();
1407 mIsFullyLoaded = true;
1408 mHaveAnimations = mSVGDocumentWrapper->IsAnimated();
1410 // Start listening to our image for rendering updates.
1411 mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this);
1413 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1414 // stick around long enough to complete our work.
1415 RefPtr<VectorImage> kungFuDeathGrip(this);
1417 // Tell *our* observers that we're done loading.
1418 if (mProgressTracker) {
1419 Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY |
1420 FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE;
1422 if (mHaveAnimations) {
1423 progress |= FLAG_IS_ANIMATED;
1426 // Merge in any saved progress from OnImageDataComplete.
1427 if (mLoadProgress) {
1428 progress |= *mLoadProgress;
1429 mLoadProgress = Nothing();
1432 mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect());
1435 EvaluateAnimation();
1438 void VectorImage::OnSVGDocumentError() {
1439 CancelAllListeners();
1441 mError = true;
1443 if (mProgressTracker) {
1444 // Notify observers about the error and unblock page load.
1445 Progress progress = FLAG_HAS_ERROR;
1447 // Merge in any saved progress from OnImageDataComplete.
1448 if (mLoadProgress) {
1449 progress |= *mLoadProgress;
1450 mLoadProgress = Nothing();
1453 mProgressTracker->SyncNotifyProgress(progress);
1457 //------------------------------------------------------------------------------
1458 // nsIStreamListener method
1460 //******************************************************************************
1461 NS_IMETHODIMP
1462 VectorImage::OnDataAvailable(nsIRequest* aRequest, nsISupports* aCtxt,
1463 nsIInputStream* aInStr, uint64_t aSourceOffset,
1464 uint32_t aCount) {
1465 if (mError) {
1466 return NS_ERROR_FAILURE;
1469 return mSVGDocumentWrapper->OnDataAvailable(aRequest, aCtxt, aInStr,
1470 aSourceOffset, aCount);
1473 // --------------------------
1474 // Invalidation helper method
1476 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1477 if (mHasPendingInvalidation) {
1478 return;
1481 mHasPendingInvalidation = true;
1483 // Animated images can wait for the refresh tick.
1484 if (mHaveAnimations) {
1485 return;
1488 // Non-animated images won't get the refresh tick, so we should just send an
1489 // invalidation outside the current execution context. We need to defer
1490 // because the layout tree is in the middle of invalidation, and the tree
1491 // state needs to be consistent. Specifically only some of the frames have
1492 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1493 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1494 // get cleared when we repaint the SVG into a surface by
1495 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1496 nsCOMPtr<nsIEventTarget> eventTarget;
1497 if (mProgressTracker) {
1498 eventTarget = mProgressTracker->GetEventTarget();
1499 } else {
1500 eventTarget = do_GetMainThread();
1503 RefPtr<VectorImage> self(this);
1504 nsCOMPtr<nsIRunnable> ev(NS_NewRunnableFunction(
1505 "VectorImage::SendInvalidationNotifications",
1506 [=]() -> void { self->SendInvalidationNotifications(); }));
1507 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
1510 void VectorImage::PropagateUseCounters(Document* aParentDocument) {
1511 Document* doc = mSVGDocumentWrapper->GetDocument();
1512 if (doc) {
1513 doc->PropagateUseCounters(aParentDocument);
1517 void VectorImage::ReportUseCounters() {
1518 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1519 doc->ReportUseCounters();
1523 nsIntSize VectorImage::OptimalImageSizeForDest(const gfxSize& aDest,
1524 uint32_t aWhichFrame,
1525 SamplingFilter aSamplingFilter,
1526 uint32_t aFlags) {
1527 MOZ_ASSERT(aDest.width >= 0 || ceil(aDest.width) <= INT32_MAX ||
1528 aDest.height >= 0 || ceil(aDest.height) <= INT32_MAX,
1529 "Unexpected destination size");
1531 // We can rescale SVGs freely, so just return the provided destination size.
1532 return nsIntSize::Ceil(aDest.width, aDest.height);
1535 already_AddRefed<imgIContainer> VectorImage::Unwrap() {
1536 nsCOMPtr<imgIContainer> self(this);
1537 return self.forget();
1540 } // namespace image
1541 } // namespace mozilla