Bug 1728955: part 8) Refactor `DisplayErrCode` in Windows' `nsClipboard`. r=masayuki
[gecko.git] / image / VectorImage.cpp
blob129bd85ed014a76d6e0472f238ffec8e03a77e28
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 "AutoRestoreSVGState.h"
9 #include "gfx2DGlue.h"
10 #include "gfxContext.h"
11 #include "gfxDrawable.h"
12 #include "gfxPlatform.h"
13 #include "gfxUtils.h"
14 #include "imgFrame.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/ProfilerLabels.h"
25 #include "mozilla/RefPtr.h"
26 #include "mozilla/StaticPrefs_image.h"
27 #include "mozilla/SVGObserverUtils.h" // for SVGRenderingObserver
28 #include "mozilla/Tuple.h"
29 #include "nsIStreamListener.h"
30 #include "nsMimeTypes.h"
31 #include "nsPresContext.h"
32 #include "nsRect.h"
33 #include "nsString.h"
34 #include "nsStubDocumentObserver.h"
35 #include "nsWindowSizes.h"
36 #include "ImageRegion.h"
37 #include "ISurfaceProvider.h"
38 #include "LookupResult.h"
39 #include "Orientation.h"
40 #include "SourceSurfaceBlobImage.h"
41 #include "SVGDocumentWrapper.h"
42 #include "SVGDrawingCallback.h"
43 #include "SVGDrawingParameters.h"
44 #include "nsIDOMEventListener.h"
45 #include "SurfaceCache.h"
46 #include "mozilla/dom/Document.h"
47 #include "mozilla/dom/DocumentInlines.h"
48 #include "mozilla/image/Resolution.h"
50 namespace mozilla {
52 using namespace dom;
53 using namespace dom::SVGPreserveAspectRatio_Binding;
54 using namespace gfx;
55 using namespace layers;
57 namespace image {
59 // Helper-class: SVGRootRenderingObserver
60 class SVGRootRenderingObserver final : public SVGRenderingObserver {
61 public:
62 NS_DECL_ISUPPORTS
64 SVGRootRenderingObserver(SVGDocumentWrapper* aDocWrapper,
65 VectorImage* aVectorImage)
66 : SVGRenderingObserver(),
67 mDocWrapper(aDocWrapper),
68 mVectorImage(aVectorImage),
69 mHonoringInvalidations(true) {
70 MOZ_ASSERT(mDocWrapper, "Need a non-null SVG document wrapper");
71 MOZ_ASSERT(mVectorImage, "Need a non-null VectorImage");
73 StartObserving();
74 Element* elem = GetReferencedElementWithoutObserving();
75 MOZ_ASSERT(elem, "no root SVG node for us to observe");
77 SVGObserverUtils::AddRenderingObserver(elem, this);
78 mInObserverSet = true;
81 void ResumeHonoringInvalidations() { mHonoringInvalidations = true; }
83 protected:
84 virtual ~SVGRootRenderingObserver() {
85 // This needs to call our GetReferencedElementWithoutObserving override,
86 // so must be called here rather than in our base class's dtor.
87 StopObserving();
90 Element* GetReferencedElementWithoutObserving() final {
91 return mDocWrapper->GetRootSVGElem();
94 virtual void OnRenderingChange() override {
95 Element* elem = GetReferencedElementWithoutObserving();
96 MOZ_ASSERT(elem, "missing root SVG node");
98 if (mHonoringInvalidations && !mDocWrapper->ShouldIgnoreInvalidation()) {
99 nsIFrame* frame = elem->GetPrimaryFrame();
100 if (!frame || frame->PresShell()->IsDestroying()) {
101 // We're being destroyed. Bail out.
102 return;
105 // Ignore further invalidations until we draw.
106 mHonoringInvalidations = false;
108 mVectorImage->InvalidateObserversOnNextRefreshDriverTick();
111 // Our caller might've removed us from rendering-observer list.
112 // Add ourselves back!
113 if (!mInObserverSet) {
114 SVGObserverUtils::AddRenderingObserver(elem, this);
115 mInObserverSet = true;
119 // Private data
120 const RefPtr<SVGDocumentWrapper> mDocWrapper;
121 VectorImage* const mVectorImage; // Raw pointer because it owns me.
122 bool mHonoringInvalidations;
125 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver, nsIMutationObserver)
127 class SVGParseCompleteListener final : public nsStubDocumentObserver {
128 public:
129 NS_DECL_ISUPPORTS
131 SVGParseCompleteListener(SVGDocument* aDocument, VectorImage* aImage)
132 : mDocument(aDocument), mImage(aImage) {
133 MOZ_ASSERT(mDocument, "Need an SVG document");
134 MOZ_ASSERT(mImage, "Need an image");
136 mDocument->AddObserver(this);
139 private:
140 ~SVGParseCompleteListener() {
141 if (mDocument) {
142 // The document must have been destroyed before we got our event.
143 // Otherwise this can't happen, since documents hold strong references to
144 // their observers.
145 Cancel();
149 public:
150 void EndLoad(Document* aDocument) override {
151 MOZ_ASSERT(aDocument == mDocument, "Got EndLoad for wrong document?");
153 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
154 // we stick around long enough to complete our work.
155 RefPtr<SVGParseCompleteListener> kungFuDeathGrip(this);
157 mImage->OnSVGDocumentParsed();
160 void Cancel() {
161 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
162 if (mDocument) {
163 mDocument->RemoveObserver(this);
164 mDocument = nullptr;
168 private:
169 RefPtr<SVGDocument> mDocument;
170 VectorImage* const mImage; // Raw pointer to owner.
173 NS_IMPL_ISUPPORTS(SVGParseCompleteListener, nsIDocumentObserver)
175 class SVGLoadEventListener final : public nsIDOMEventListener {
176 public:
177 NS_DECL_ISUPPORTS
179 SVGLoadEventListener(Document* aDocument, VectorImage* aImage)
180 : mDocument(aDocument), mImage(aImage) {
181 MOZ_ASSERT(mDocument, "Need an SVG document");
182 MOZ_ASSERT(mImage, "Need an image");
184 mDocument->AddEventListener(u"MozSVGAsImageDocumentLoad"_ns, this, true,
185 false);
188 private:
189 ~SVGLoadEventListener() {
190 if (mDocument) {
191 // The document must have been destroyed before we got our event.
192 // Otherwise this can't happen, since documents hold strong references to
193 // their observers.
194 Cancel();
198 public:
199 NS_IMETHOD HandleEvent(Event* aEvent) override {
200 MOZ_ASSERT(mDocument, "Need an SVG document. Received multiple events?");
202 // OnSVGDocumentLoaded will release our owner's reference
203 // to us, so ensure we stick around long enough to complete our work.
204 RefPtr<SVGLoadEventListener> kungFuDeathGrip(this);
206 #ifdef DEBUG
207 nsAutoString eventType;
208 aEvent->GetType(eventType);
209 MOZ_ASSERT(eventType.EqualsLiteral("MozSVGAsImageDocumentLoad"),
210 "Received unexpected event");
211 #endif
213 mImage->OnSVGDocumentLoaded();
215 return NS_OK;
218 void Cancel() {
219 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
220 if (mDocument) {
221 mDocument->RemoveEventListener(u"MozSVGAsImageDocumentLoad"_ns, this,
222 true);
223 mDocument = nullptr;
227 private:
228 nsCOMPtr<Document> mDocument;
229 VectorImage* const mImage; // Raw pointer to owner.
232 NS_IMPL_ISUPPORTS(SVGLoadEventListener, nsIDOMEventListener)
234 SVGDrawingCallback::SVGDrawingCallback(SVGDocumentWrapper* aSVGDocumentWrapper,
235 const IntSize& aViewportSize,
236 const IntSize& aSize,
237 uint32_t aImageFlags)
238 : mSVGDocumentWrapper(aSVGDocumentWrapper),
239 mViewportSize(aViewportSize),
240 mSize(aSize),
241 mImageFlags(aImageFlags) {}
243 SVGDrawingCallback::~SVGDrawingCallback() = default;
245 // Based loosely on SVGIntegrationUtils' PaintFrameCallback::operator()
246 bool SVGDrawingCallback::operator()(gfxContext* aContext,
247 const gfxRect& aFillRect,
248 const SamplingFilter aSamplingFilter,
249 const gfxMatrix& aTransform) {
250 MOZ_ASSERT(mSVGDocumentWrapper, "need an SVGDocumentWrapper");
252 // Get (& sanity-check) the helper-doc's presShell
253 RefPtr<PresShell> presShell = mSVGDocumentWrapper->GetPresShell();
254 MOZ_ASSERT(presShell, "GetPresShell returned null for an SVG image?");
256 Document* doc = presShell->GetDocument();
257 [[maybe_unused]] nsIURI* uri = doc ? doc->GetDocumentURI() : nullptr;
258 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
259 "SVG Image drawing", GRAPHICS,
260 nsPrintfCString("%dx%d %s", mSize.width, mSize.height,
261 uri ? uri->GetSpecOrDefault().get() : "N/A"));
263 gfxContextAutoSaveRestore contextRestorer(aContext);
265 // Clip to aFillRect so that we don't paint outside.
266 aContext->NewPath();
267 aContext->Rectangle(aFillRect);
268 aContext->Clip();
270 gfxMatrix matrix = aTransform;
271 if (!matrix.Invert()) {
272 return false;
274 aContext->SetMatrixDouble(
275 aContext->CurrentMatrixDouble().PreMultiply(matrix).PreScale(
276 double(mSize.width) / mViewportSize.width,
277 double(mSize.height) / mViewportSize.height));
279 nsPresContext* presContext = presShell->GetPresContext();
280 MOZ_ASSERT(presContext, "pres shell w/out pres context");
282 nsRect svgRect(0, 0, presContext->DevPixelsToAppUnits(mViewportSize.width),
283 presContext->DevPixelsToAppUnits(mViewportSize.height));
285 RenderDocumentFlags renderDocFlags =
286 RenderDocumentFlags::IgnoreViewportScrolling;
287 if (!(mImageFlags & imgIContainer::FLAG_SYNC_DECODE)) {
288 renderDocFlags |= RenderDocumentFlags::AsyncDecodeImages;
290 if (mImageFlags & imgIContainer::FLAG_HIGH_QUALITY_SCALING) {
291 renderDocFlags |= RenderDocumentFlags::UseHighQualityScaling;
294 presShell->RenderDocument(svgRect, renderDocFlags,
295 NS_RGBA(0, 0, 0, 0), // transparent
296 aContext);
298 return true;
301 // Implement VectorImage's nsISupports-inherited methods
302 NS_IMPL_ISUPPORTS(VectorImage, imgIContainer, nsIStreamListener,
303 nsIRequestObserver)
305 //------------------------------------------------------------------------------
306 // Constructor / Destructor
308 VectorImage::VectorImage(nsIURI* aURI /* = nullptr */)
309 : ImageResource(aURI), // invoke superclass's constructor
310 mLockCount(0),
311 mIsInitialized(false),
312 mDiscardable(false),
313 mIsFullyLoaded(false),
314 mHaveAnimations(false),
315 mHasPendingInvalidation(false) {}
317 VectorImage::~VectorImage() {
318 ReportDocumentUseCounters();
319 CancelAllListeners();
320 SurfaceCache::RemoveImage(ImageKey(this));
323 //------------------------------------------------------------------------------
324 // Methods inherited from Image.h
326 nsresult VectorImage::Init(const char* aMimeType, uint32_t aFlags) {
327 // We don't support re-initialization
328 if (mIsInitialized) {
329 return NS_ERROR_ILLEGAL_VALUE;
332 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations && !mError,
333 "Flags unexpectedly set before initialization");
334 MOZ_ASSERT(!strcmp(aMimeType, IMAGE_SVG_XML), "Unexpected mimetype");
336 mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE);
338 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
339 if (!mDiscardable) {
340 mLockCount++;
341 SurfaceCache::LockImage(ImageKey(this));
344 mIsInitialized = true;
345 return NS_OK;
348 size_t VectorImage::SizeOfSourceWithComputedFallback(
349 SizeOfState& aState) const {
350 if (!mSVGDocumentWrapper) {
351 return 0; // No document, so no memory used for the document.
354 SVGDocument* doc = mSVGDocumentWrapper->GetDocument();
355 if (!doc) {
356 return 0; // No document, so no memory used for the document.
359 nsWindowSizes windowSizes(aState);
360 doc->DocAddSizeOfIncludingThis(windowSizes);
362 if (windowSizes.getTotalSize() == 0) {
363 // MallocSizeOf fails on this platform. Because we also use this method for
364 // determining the size of cache entries, we need to return something
365 // reasonable here. Unfortunately, there's no way to estimate the document's
366 // size accurately, so we just use a constant value of 100KB, which will
367 // generally underestimate the true size.
368 return 100 * 1024;
371 return windowSizes.getTotalSize();
374 void VectorImage::CollectSizeOfSurfaces(
375 nsTArray<SurfaceMemoryCounter>& aCounters,
376 MallocSizeOf aMallocSizeOf) const {
377 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters, aMallocSizeOf);
378 ImageResource::CollectSizeOfSurfaces(aCounters, aMallocSizeOf);
381 nsresult VectorImage::OnImageDataComplete(nsIRequest* aRequest,
382 nsISupports* aContext,
383 nsresult aStatus, bool aLastPart) {
384 // Call our internal OnStopRequest method, which only talks to our embedded
385 // SVG document. This won't have any effect on our ProgressTracker.
386 nsresult finalStatus = OnStopRequest(aRequest, aStatus);
388 // Give precedence to Necko failure codes.
389 if (NS_FAILED(aStatus)) {
390 finalStatus = aStatus;
393 Progress loadProgress = LoadCompleteProgress(aLastPart, mError, finalStatus);
395 if (mIsFullyLoaded || mError) {
396 // Our document is loaded, so we're ready to notify now.
397 mProgressTracker->SyncNotifyProgress(loadProgress);
398 } else {
399 // Record our progress so far; we'll actually send the notifications in
400 // OnSVGDocumentLoaded or OnSVGDocumentError.
401 mLoadProgress = Some(loadProgress);
404 return finalStatus;
407 nsresult VectorImage::OnImageDataAvailable(nsIRequest* aRequest,
408 nsISupports* aContext,
409 nsIInputStream* aInStr,
410 uint64_t aSourceOffset,
411 uint32_t aCount) {
412 return OnDataAvailable(aRequest, aInStr, aSourceOffset, aCount);
415 nsresult VectorImage::StartAnimation() {
416 if (mError) {
417 return NS_ERROR_FAILURE;
420 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
422 mSVGDocumentWrapper->StartAnimation();
423 return NS_OK;
426 nsresult VectorImage::StopAnimation() {
427 nsresult rv = NS_OK;
428 if (mError) {
429 rv = NS_ERROR_FAILURE;
430 } else {
431 MOZ_ASSERT(mIsFullyLoaded && mHaveAnimations,
432 "Should not have been animating!");
434 mSVGDocumentWrapper->StopAnimation();
437 mAnimating = false;
438 return rv;
441 bool VectorImage::ShouldAnimate() {
442 return ImageResource::ShouldAnimate() && mIsFullyLoaded && mHaveAnimations;
445 NS_IMETHODIMP_(void)
446 VectorImage::SetAnimationStartTime(const TimeStamp& aTime) {
447 // We don't care about animation start time.
450 //------------------------------------------------------------------------------
451 // imgIContainer methods
453 //******************************************************************************
454 NS_IMETHODIMP
455 VectorImage::GetWidth(int32_t* aWidth) {
456 if (mError || !mIsFullyLoaded) {
457 // XXXdholbert Technically we should leave outparam untouched when we
458 // fail. But since many callers don't check for failure, we set it to 0 on
459 // failure, for sane/predictable results.
460 *aWidth = 0;
461 return NS_ERROR_FAILURE;
464 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
465 MOZ_ASSERT(rootElem,
466 "Should have a root SVG elem, since we finished "
467 "loading without errors");
468 int32_t rootElemWidth = rootElem->GetIntrinsicWidth();
469 if (rootElemWidth < 0) {
470 *aWidth = 0;
471 return NS_ERROR_FAILURE;
473 *aWidth = rootElemWidth;
474 return NS_OK;
477 //******************************************************************************
478 nsresult VectorImage::GetNativeSizes(nsTArray<IntSize>& aNativeSizes) const {
479 return NS_ERROR_NOT_IMPLEMENTED;
482 //******************************************************************************
483 size_t VectorImage::GetNativeSizesLength() const { return 0; }
485 //******************************************************************************
486 NS_IMETHODIMP_(void)
487 VectorImage::RequestRefresh(const TimeStamp& aTime) {
488 if (HadRecentRefresh(aTime)) {
489 return;
492 PendingAnimationTracker* tracker =
493 mSVGDocumentWrapper->GetDocument()->GetPendingAnimationTracker();
494 if (tracker && ShouldAnimate()) {
495 tracker->TriggerPendingAnimationsOnNextTick(aTime);
498 EvaluateAnimation();
500 mSVGDocumentWrapper->TickRefreshDriver();
502 if (mHasPendingInvalidation) {
503 SendInvalidationNotifications();
507 void VectorImage::SendInvalidationNotifications() {
508 // Animated images don't send out invalidation notifications as soon as
509 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
510 // records that there are pending invalidations and then returns immediately.
511 // The notifications are actually sent from RequestRefresh(). We send these
512 // notifications there to ensure that there is actually a document observing
513 // us. Otherwise, the notifications are just wasted effort.
515 // Non-animated images post an event to call this method from
516 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
517 // called for them. Ordinarily this isn't needed, since we send out
518 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
519 // SVG document may not be 100% ready to render at that time. In those cases
520 // we would miss the subsequent invalidations if we didn't send out the
521 // notifications indirectly in |InvalidateObservers...|.
523 mHasPendingInvalidation = false;
524 SurfaceCache::RemoveImage(ImageKey(this));
526 if (UpdateImageContainer(Nothing())) {
527 // If we have image containers, that means we probably won't get a Draw call
528 // from the owner since they are using the container. We must assume all
529 // invalidations need to be handled.
530 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
531 mRenderingObserver->ResumeHonoringInvalidations();
534 if (mProgressTracker) {
535 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
536 GetMaxSizedIntRect());
540 NS_IMETHODIMP_(IntRect)
541 VectorImage::GetImageSpaceInvalidationRect(const IntRect& aRect) {
542 return aRect;
545 //******************************************************************************
546 NS_IMETHODIMP
547 VectorImage::GetHeight(int32_t* aHeight) {
548 if (mError || !mIsFullyLoaded) {
549 // XXXdholbert Technically we should leave outparam untouched when we
550 // fail. But since many callers don't check for failure, we set it to 0 on
551 // failure, for sane/predictable results.
552 *aHeight = 0;
553 return NS_ERROR_FAILURE;
556 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
557 MOZ_ASSERT(rootElem,
558 "Should have a root SVG elem, since we finished "
559 "loading without errors");
560 int32_t rootElemHeight = rootElem->GetIntrinsicHeight();
561 if (rootElemHeight < 0) {
562 *aHeight = 0;
563 return NS_ERROR_FAILURE;
565 *aHeight = rootElemHeight;
566 return NS_OK;
569 //******************************************************************************
570 NS_IMETHODIMP
571 VectorImage::GetIntrinsicSize(nsSize* aSize) {
572 if (mError || !mIsFullyLoaded) {
573 return NS_ERROR_FAILURE;
576 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
577 if (!rootFrame) {
578 return NS_ERROR_FAILURE;
581 *aSize = nsSize(-1, -1);
582 IntrinsicSize rfSize = rootFrame->GetIntrinsicSize();
583 if (rfSize.width) {
584 aSize->width = *rfSize.width;
586 if (rfSize.height) {
587 aSize->height = *rfSize.height;
589 return NS_OK;
592 //******************************************************************************
593 Maybe<AspectRatio> VectorImage::GetIntrinsicRatio() {
594 if (mError || !mIsFullyLoaded) {
595 return Nothing();
598 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
599 if (!rootFrame) {
600 return Nothing();
603 return Some(rootFrame->GetIntrinsicRatio());
606 NS_IMETHODIMP_(Orientation)
607 VectorImage::GetOrientation() { return Orientation(); }
609 NS_IMETHODIMP_(Resolution)
610 VectorImage::GetResolution() { return {}; }
612 //******************************************************************************
613 NS_IMETHODIMP
614 VectorImage::GetType(uint16_t* aType) {
615 NS_ENSURE_ARG_POINTER(aType);
617 *aType = imgIContainer::TYPE_VECTOR;
618 return NS_OK;
621 //******************************************************************************
622 NS_IMETHODIMP
623 VectorImage::GetProducerId(uint32_t* aId) {
624 NS_ENSURE_ARG_POINTER(aId);
626 *aId = ImageResource::GetImageProducerId();
627 return NS_OK;
630 //******************************************************************************
631 NS_IMETHODIMP
632 VectorImage::GetAnimated(bool* aAnimated) {
633 if (mError || !mIsFullyLoaded) {
634 return NS_ERROR_FAILURE;
637 *aAnimated = mSVGDocumentWrapper->IsAnimated();
638 return NS_OK;
641 //******************************************************************************
642 int32_t VectorImage::GetFirstFrameDelay() {
643 if (mError) {
644 return -1;
647 if (!mSVGDocumentWrapper->IsAnimated()) {
648 return -1;
651 // We don't really have a frame delay, so just pretend that we constantly
652 // need updates.
653 return 0;
656 NS_IMETHODIMP_(bool)
657 VectorImage::WillDrawOpaqueNow() {
658 return false; // In general, SVG content is not opaque.
661 //******************************************************************************
662 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
663 VectorImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
664 if (mError) {
665 return nullptr;
668 // Look up height & width
669 // ----------------------
670 SVGSVGElement* svgElem = mSVGDocumentWrapper->GetRootSVGElem();
671 MOZ_ASSERT(svgElem,
672 "Should have a root SVG elem, since we finished "
673 "loading without errors");
674 nsIntSize imageIntSize(svgElem->GetIntrinsicWidth(),
675 svgElem->GetIntrinsicHeight());
677 if (imageIntSize.IsEmpty()) {
678 // We'll get here if our SVG doc has a percent-valued or negative width or
679 // height.
680 return nullptr;
683 return GetFrameAtSize(imageIntSize, aWhichFrame, aFlags);
686 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
687 VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
688 uint32_t aFlags) {
689 AutoProfilerImagePaintMarker PROFILER_RAII(this);
690 #ifdef DEBUG
691 NotifyDrawingObservers();
692 #endif
694 auto result =
695 GetFrameInternal(aSize, Nothing(), Nothing(), aWhichFrame, aFlags);
696 return Get<2>(result).forget();
699 Tuple<ImgDrawResult, IntSize, RefPtr<SourceSurface>>
700 VectorImage::GetFrameInternal(const IntSize& aSize,
701 const Maybe<SVGImageContext>& aSVGContext,
702 const Maybe<ImageIntRegion>& aRegion,
703 uint32_t aWhichFrame, uint32_t aFlags) {
704 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE);
706 if (aSize.IsEmpty() || aWhichFrame > FRAME_MAX_VALUE) {
707 return MakeTuple(ImgDrawResult::BAD_ARGS, aSize, RefPtr<SourceSurface>());
710 if (mError) {
711 return MakeTuple(ImgDrawResult::BAD_IMAGE, aSize, RefPtr<SourceSurface>());
714 if (!mIsFullyLoaded) {
715 return MakeTuple(ImgDrawResult::NOT_READY, aSize, RefPtr<SourceSurface>());
718 uint32_t whichFrame = mHaveAnimations ? aWhichFrame : FRAME_FIRST;
720 RefPtr<SourceSurface> sourceSurface;
721 IntSize decodeSize;
722 Tie(sourceSurface, decodeSize) =
723 LookupCachedSurface(aSize, aSVGContext, aFlags);
724 if (sourceSurface) {
725 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize,
726 std::move(sourceSurface));
729 if (mSVGDocumentWrapper->IsDrawing()) {
730 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
731 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
732 RefPtr<SourceSurface>());
735 float animTime = (whichFrame == FRAME_FIRST)
736 ? 0.0f
737 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
739 // If we aren't given a region, create one that covers the whole SVG image.
740 ImageRegion region =
741 aRegion ? aRegion->ToImageRegion() : ImageRegion::Create(decodeSize);
743 // By using a null gfxContext, we ensure that we will always attempt to
744 // create a surface, even if we aren't capable of caching it (e.g. due to our
745 // flags, having an animation, etc). Otherwise CreateSurface will assume that
746 // the caller is capable of drawing directly to its own draw target if we
747 // cannot cache.
748 SVGDrawingParameters params(nullptr, decodeSize, aSize, region,
749 SamplingFilter::POINT, aSVGContext, animTime,
750 aFlags, 1.0);
752 // Blob recorded vector images just create a simple surface responsible for
753 // generating blob keys and recording bindings. The recording won't happen
754 // until the caller requests the key after GetImageContainerAtSize.
755 if (aFlags & FLAG_RECORD_BLOB) {
756 RefPtr<SourceSurface> surface =
757 new SourceSurfaceBlobImage(mSVGDocumentWrapper, aSVGContext, aRegion,
758 decodeSize, whichFrame, aFlags);
760 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize, std::move(surface));
763 bool didCache; // Was the surface put into the cache?
764 bool contextPaint = aSVGContext && aSVGContext->GetContextPaint();
766 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, contextPaint);
768 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
769 RefPtr<SourceSurface> surface = CreateSurface(params, svgDrawable, didCache);
770 if (!surface) {
771 MOZ_ASSERT(!didCache);
772 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR, decodeSize,
773 RefPtr<SourceSurface>());
776 SendFrameComplete(didCache, params.flags);
777 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize, std::move(surface));
780 //******************************************************************************
781 Tuple<ImgDrawResult, IntSize> VectorImage::GetImageContainerSize(
782 WindowRenderer* aRenderer, const IntSize& aSize, uint32_t aFlags) {
783 if (mError) {
784 return MakeTuple(ImgDrawResult::BAD_IMAGE, IntSize(0, 0));
787 if (!mIsFullyLoaded) {
788 return MakeTuple(ImgDrawResult::NOT_READY, IntSize(0, 0));
791 if (mHaveAnimations && !StaticPrefs::image_svg_blob_image()) {
792 // We don't support rasterizing animation SVGs. We can put them in a blob
793 // recording however instead of using fallback.
794 return MakeTuple(ImgDrawResult::NOT_SUPPORTED, IntSize(0, 0));
797 if (aRenderer->GetBackendType() != LayersBackend::LAYERS_WR) {
798 return MakeTuple(ImgDrawResult::NOT_SUPPORTED, IntSize(0, 0));
801 // We don't need to check if the size is too big since we only support
802 // WebRender backends.
803 if (aSize.IsEmpty()) {
804 return MakeTuple(ImgDrawResult::BAD_ARGS, IntSize(0, 0));
807 return MakeTuple(ImgDrawResult::SUCCESS, aSize);
810 NS_IMETHODIMP_(bool)
811 VectorImage::IsImageContainerAvailable(WindowRenderer* aRenderer,
812 uint32_t aFlags) {
813 if (mError || !mIsFullyLoaded ||
814 aRenderer->GetBackendType() != LayersBackend::LAYERS_WR) {
815 return false;
818 if (mHaveAnimations && !StaticPrefs::image_svg_blob_image()) {
819 // We don't support rasterizing animation SVGs. We can put them in a blob
820 // recording however instead of using fallback.
821 return false;
824 return true;
827 //******************************************************************************
828 NS_IMETHODIMP_(ImgDrawResult)
829 VectorImage::GetImageContainerAtSize(WindowRenderer* aRenderer,
830 const gfx::IntSize& aSize,
831 const Maybe<SVGImageContext>& aSVGContext,
832 const Maybe<ImageIntRegion>& aRegion,
833 uint32_t aFlags,
834 layers::ImageContainer** aOutContainer) {
835 Maybe<SVGImageContext> newSVGContext;
836 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
838 // The aspect ratio flag was already handled as part of the SVG context
839 // restriction above.
840 uint32_t flags = aFlags & ~(FLAG_FORCE_PRESERVEASPECTRATIO_NONE);
841 auto rv = GetImageContainerImpl(aRenderer, aSize,
842 newSVGContext ? newSVGContext : aSVGContext,
843 aRegion, flags, aOutContainer);
845 // Invalidations may still be suspended if we had a refresh tick and there
846 // were no image containers remaining. If we created a new container, we
847 // should resume invalidations to allow animations to progress.
848 if (*aOutContainer && mRenderingObserver) {
849 mRenderingObserver->ResumeHonoringInvalidations();
852 return rv;
855 bool VectorImage::MaybeRestrictSVGContext(
856 Maybe<SVGImageContext>& aNewSVGContext,
857 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags) {
858 bool overridePAR =
859 (aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) && aSVGContext;
861 bool haveContextPaint = aSVGContext && aSVGContext->GetContextPaint();
862 bool blockContextPaint = false;
863 if (haveContextPaint) {
864 blockContextPaint = !SVGContextPaint::IsAllowedForImageFromURI(mURI);
867 if (overridePAR || blockContextPaint) {
868 // The key that we create for the image surface cache must match the way
869 // that the image will be painted, so we need to initialize a new matching
870 // SVGImageContext here in order to generate the correct key.
872 aNewSVGContext = aSVGContext; // copy
874 if (overridePAR) {
875 // The SVGImageContext must take account of the preserveAspectRatio
876 // override:
877 MOZ_ASSERT(!aSVGContext->GetPreserveAspectRatio(),
878 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
879 "preserveAspectRatio override is supplied");
880 Maybe<SVGPreserveAspectRatio> aspectRatio = Some(SVGPreserveAspectRatio(
881 SVG_PRESERVEASPECTRATIO_NONE, SVG_MEETORSLICE_UNKNOWN));
882 aNewSVGContext->SetPreserveAspectRatio(aspectRatio);
885 if (blockContextPaint) {
886 // The SVGImageContext must not include context paint if the image is
887 // not allowed to use it:
888 aNewSVGContext->ClearContextPaint();
892 return haveContextPaint && !blockContextPaint;
895 //******************************************************************************
896 NS_IMETHODIMP_(ImgDrawResult)
897 VectorImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
898 const ImageRegion& aRegion, uint32_t aWhichFrame,
899 SamplingFilter aSamplingFilter,
900 const Maybe<SVGImageContext>& aSVGContext, uint32_t aFlags,
901 float aOpacity) {
902 if (aWhichFrame > FRAME_MAX_VALUE) {
903 return ImgDrawResult::BAD_ARGS;
906 if (!aContext) {
907 return ImgDrawResult::BAD_ARGS;
910 if (mError) {
911 return ImgDrawResult::BAD_IMAGE;
914 if (!mIsFullyLoaded) {
915 return ImgDrawResult::NOT_READY;
918 if (mAnimationConsumers == 0) {
919 SendOnUnlockedDraw(aFlags);
922 // We should bypass the cache when:
923 // - We are using a DrawTargetRecording because we prefer the drawing commands
924 // in general to the rasterized surface. This allows blob images to avoid
925 // rasterized SVGs with WebRender.
926 // - The size exceeds what we are willing to cache as a rasterized surface.
927 // We don't do this for WebRender because the performance of the fallback
928 // path is quite bad and upscaling the SVG from the clamped size is better
929 // than bringing the browser to a crawl.
930 if (aContext->GetDrawTarget()->GetBackendType() == BackendType::RECORDING ||
931 (!gfxVars::UseWebRender() &&
932 aSize != SurfaceCache::ClampVectorSize(aSize))) {
933 aFlags |= FLAG_BYPASS_SURFACE_CACHE;
936 MOZ_ASSERT(!(aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) ||
937 (aSVGContext && aSVGContext->GetViewportSize()),
938 "Viewport size is required when using "
939 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
941 uint32_t whichFrame = mHaveAnimations ? aWhichFrame : FRAME_FIRST;
943 float animTime = (whichFrame == FRAME_FIRST)
944 ? 0.0f
945 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
947 Maybe<SVGImageContext> newSVGContext;
948 bool contextPaint =
949 MaybeRestrictSVGContext(newSVGContext, aSVGContext, aFlags);
951 SVGDrawingParameters params(aContext, aSize, aSize, aRegion, aSamplingFilter,
952 newSVGContext ? newSVGContext : aSVGContext,
953 animTime, aFlags, aOpacity);
955 // If we have an prerasterized version of this image that matches the
956 // drawing parameters, use that.
957 RefPtr<SourceSurface> sourceSurface;
958 Tie(sourceSurface, params.size) =
959 LookupCachedSurface(aSize, params.svgContext, aFlags);
960 if (sourceSurface) {
961 RefPtr<gfxDrawable> drawable =
962 new gfxSurfaceDrawable(sourceSurface, params.size);
963 Show(drawable, params);
964 return ImgDrawResult::SUCCESS;
967 // else, we need to paint the image:
969 if (mSVGDocumentWrapper->IsDrawing()) {
970 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
971 return ImgDrawResult::TEMPORARY_ERROR;
974 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, contextPaint);
976 bool didCache; // Was the surface put into the cache?
977 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
978 sourceSurface = CreateSurface(params, svgDrawable, didCache);
979 if (!sourceSurface) {
980 MOZ_ASSERT(!didCache);
981 Show(svgDrawable, params);
982 return ImgDrawResult::SUCCESS;
985 RefPtr<gfxDrawable> drawable =
986 new gfxSurfaceDrawable(sourceSurface, params.size);
987 Show(drawable, params);
988 SendFrameComplete(didCache, params.flags);
989 return ImgDrawResult::SUCCESS;
992 already_AddRefed<gfxDrawable> VectorImage::CreateSVGDrawable(
993 const SVGDrawingParameters& aParams) {
994 RefPtr<gfxDrawingCallback> cb = new SVGDrawingCallback(
995 mSVGDocumentWrapper, aParams.viewportSize, aParams.size, aParams.flags);
997 RefPtr<gfxDrawable> svgDrawable = new gfxCallbackDrawable(cb, aParams.size);
998 return svgDrawable.forget();
1001 Tuple<RefPtr<SourceSurface>, IntSize> VectorImage::LookupCachedSurface(
1002 const IntSize& aSize, const Maybe<SVGImageContext>& aSVGContext,
1003 uint32_t aFlags) {
1004 // We can't use cached surfaces if we:
1005 // - Explicitly disallow it via FLAG_BYPASS_SURFACE_CACHE
1006 // - Want a blob recording which aren't supported by the cache.
1007 // - Have animations which aren't supported by the cache.
1008 if (aFlags & (FLAG_BYPASS_SURFACE_CACHE | FLAG_RECORD_BLOB) ||
1009 mHaveAnimations) {
1010 return MakeTuple(RefPtr<SourceSurface>(), aSize);
1013 LookupResult result(MatchType::NOT_FOUND);
1014 SurfaceKey surfaceKey = VectorSurfaceKey(aSize, aSVGContext);
1015 if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
1016 result = SurfaceCache::Lookup(ImageKey(this), surfaceKey,
1017 /* aMarkUsed = */ true);
1018 } else {
1019 result = SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey,
1020 /* aMarkUsed = */ true);
1023 IntSize rasterSize =
1024 result.SuggestedSize().IsEmpty() ? aSize : result.SuggestedSize();
1025 MOZ_ASSERT(result.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING);
1026 if (!result || result.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND) {
1027 // No matching surface, or the OS freed the volatile buffer.
1028 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1031 RefPtr<SourceSurface> sourceSurface = result.Surface()->GetSourceSurface();
1032 if (!sourceSurface) {
1033 // Something went wrong. (Probably a GPU driver crash or device reset.)
1034 // Attempt to recover.
1035 RecoverFromLossOfSurfaces();
1036 return MakeTuple(RefPtr<SourceSurface>(), rasterSize);
1039 return MakeTuple(std::move(sourceSurface), rasterSize);
1042 already_AddRefed<SourceSurface> VectorImage::CreateSurface(
1043 const SVGDrawingParameters& aParams, gfxDrawable* aSVGDrawable,
1044 bool& aWillCache) {
1045 MOZ_ASSERT(mSVGDocumentWrapper->IsDrawing());
1046 MOZ_ASSERT(!(aParams.flags & FLAG_RECORD_BLOB));
1048 mSVGDocumentWrapper->UpdateViewportBounds(aParams.viewportSize);
1049 mSVGDocumentWrapper->FlushImageTransformInvalidation();
1051 // Determine whether or not we should put the surface to be created into
1052 // the cache. If we fail, we need to reset this to false to let the caller
1053 // know nothing was put in the cache.
1054 aWillCache = !(aParams.flags & FLAG_BYPASS_SURFACE_CACHE) &&
1055 // Refuse to cache animated images:
1056 // XXX(seth): We may remove this restriction in bug 922893.
1057 !mHaveAnimations &&
1058 // The image is too big to fit in the cache:
1059 SurfaceCache::CanHold(aParams.size);
1061 // If we weren't given a context, then we know we just want the rasterized
1062 // surface. We will create the frame below but only insert it into the cache
1063 // if we actually need to.
1064 if (!aWillCache && aParams.context) {
1065 return nullptr;
1068 // We're about to rerasterize, which may mean that some of the previous
1069 // surfaces we've rasterized aren't useful anymore. We can allow them to
1070 // expire from the cache by unlocking them here, and then sending out an
1071 // invalidation. If this image is locked, any surfaces that are still useful
1072 // will become locked again when Draw touches them, and the remainder will
1073 // eventually expire.
1074 if (aWillCache) {
1075 SurfaceCache::UnlockEntries(ImageKey(this));
1078 // If there is no context, the default backend is fine.
1079 BackendType backend =
1080 aParams.context ? aParams.context->GetDrawTarget()->GetBackendType()
1081 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1083 // Try to create an imgFrame, initializing the surface it contains by drawing
1084 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1085 auto frame = MakeNotNull<RefPtr<imgFrame>>();
1086 nsresult rv = frame->InitWithDrawable(
1087 aSVGDrawable, aParams.size, SurfaceFormat::OS_RGBA, SamplingFilter::POINT,
1088 aParams.flags, backend);
1090 // If we couldn't create the frame, it was probably because it would end
1091 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1092 // could be set such that the cache isn't the limiting factor.
1093 if (NS_FAILED(rv)) {
1094 aWillCache = false;
1095 return nullptr;
1098 // Take a strong reference to the frame's surface and make sure it hasn't
1099 // already been purged by the operating system.
1100 RefPtr<SourceSurface> surface = frame->GetSourceSurface();
1101 if (!surface) {
1102 aWillCache = false;
1103 return nullptr;
1106 // We created the frame, but only because we had no context to draw to
1107 // directly. All the caller wants is the surface in this case.
1108 if (!aWillCache) {
1109 return surface.forget();
1112 // Attempt to cache the frame.
1113 SurfaceKey surfaceKey = VectorSurfaceKey(aParams.size, aParams.svgContext);
1114 NotNull<RefPtr<ISurfaceProvider>> provider =
1115 MakeNotNull<SimpleSurfaceProvider*>(ImageKey(this), surfaceKey, frame);
1117 if (SurfaceCache::Insert(provider) == InsertOutcome::SUCCESS) {
1118 if (aParams.size != aParams.drawSize) {
1119 // We created a new surface that wasn't the size we requested, which means
1120 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1121 // need rather than waiting for the cache to expire them.
1122 SurfaceCache::PruneImage(ImageKey(this));
1124 } else {
1125 aWillCache = false;
1128 return surface.forget();
1131 void VectorImage::SendFrameComplete(bool aDidCache, uint32_t aFlags) {
1132 // If the cache was not updated, we have nothing to do.
1133 if (!aDidCache) {
1134 return;
1137 // Send out an invalidation so that surfaces that are still in use get
1138 // re-locked. See the discussion of the UnlockSurfaces call above.
1139 if (!(aFlags & FLAG_ASYNC_NOTIFY)) {
1140 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1141 GetMaxSizedIntRect());
1142 } else {
1143 NotNull<RefPtr<VectorImage>> image = WrapNotNull(this);
1144 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1145 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1146 RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
1147 if (tracker) {
1148 tracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1149 GetMaxSizedIntRect());
1151 })));
1155 void VectorImage::Show(gfxDrawable* aDrawable,
1156 const SVGDrawingParameters& aParams) {
1157 // The surface size may differ from the size at which we wish to draw. As
1158 // such, we may need to adjust the context/region to take this into account.
1159 gfxContextMatrixAutoSaveRestore saveMatrix(aParams.context);
1160 ImageRegion region(aParams.region);
1161 if (aParams.drawSize != aParams.size) {
1162 gfx::Size scale(double(aParams.drawSize.width) / aParams.size.width,
1163 double(aParams.drawSize.height) / aParams.size.height);
1164 aParams.context->Multiply(gfxMatrix::Scaling(scale.width, scale.height));
1165 region.Scale(1.0 / scale.width, 1.0 / scale.height);
1168 MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
1169 gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
1170 SizeDouble(aParams.size), region,
1171 SurfaceFormat::OS_RGBA, aParams.samplingFilter,
1172 aParams.flags, aParams.opacity, false);
1174 AutoProfilerImagePaintMarker PROFILER_RAII(this);
1175 #ifdef DEBUG
1176 NotifyDrawingObservers();
1177 #endif
1179 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
1180 mRenderingObserver->ResumeHonoringInvalidations();
1183 void VectorImage::RecoverFromLossOfSurfaces() {
1184 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1186 // Discard all existing frames, since they're probably all now invalid.
1187 SurfaceCache::RemoveImage(ImageKey(this));
1190 NS_IMETHODIMP
1191 VectorImage::StartDecoding(uint32_t aFlags, uint32_t aWhichFrame) {
1192 // Nothing to do for SVG images
1193 return NS_OK;
1196 bool VectorImage::StartDecodingWithResult(uint32_t aFlags,
1197 uint32_t aWhichFrame) {
1198 // SVG images are ready to draw when they are loaded
1199 return mIsFullyLoaded;
1202 imgIContainer::DecodeResult VectorImage::RequestDecodeWithResult(
1203 uint32_t aFlags, uint32_t aWhichFrame) {
1204 // SVG images are ready to draw when they are loaded and don't have an error.
1206 if (mError) {
1207 return imgIContainer::DECODE_REQUEST_FAILED;
1210 if (!mIsFullyLoaded) {
1211 return imgIContainer::DECODE_REQUESTED;
1214 return imgIContainer::DECODE_SURFACE_AVAILABLE;
1217 NS_IMETHODIMP
1218 VectorImage::RequestDecodeForSize(const nsIntSize& aSize, uint32_t aFlags,
1219 uint32_t aWhichFrame) {
1220 // Nothing to do for SVG images, though in theory we could rasterize to the
1221 // provided size ahead of time if we supported off-main-thread SVG
1222 // rasterization...
1223 return NS_OK;
1226 //******************************************************************************
1228 NS_IMETHODIMP
1229 VectorImage::LockImage() {
1230 MOZ_ASSERT(NS_IsMainThread());
1232 if (mError) {
1233 return NS_ERROR_FAILURE;
1236 mLockCount++;
1238 if (mLockCount == 1) {
1239 // Lock this image's surfaces in the SurfaceCache.
1240 SurfaceCache::LockImage(ImageKey(this));
1243 return NS_OK;
1246 //******************************************************************************
1248 NS_IMETHODIMP
1249 VectorImage::UnlockImage() {
1250 MOZ_ASSERT(NS_IsMainThread());
1252 if (mError) {
1253 return NS_ERROR_FAILURE;
1256 if (mLockCount == 0) {
1257 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1258 return NS_ERROR_ABORT;
1261 mLockCount--;
1263 if (mLockCount == 0) {
1264 // Unlock this image's surfaces in the SurfaceCache.
1265 SurfaceCache::UnlockImage(ImageKey(this));
1268 return NS_OK;
1271 //******************************************************************************
1273 NS_IMETHODIMP
1274 VectorImage::RequestDiscard() {
1275 MOZ_ASSERT(NS_IsMainThread());
1277 if (mDiscardable && mLockCount == 0) {
1278 SurfaceCache::RemoveImage(ImageKey(this));
1279 mProgressTracker->OnDiscard();
1282 return NS_OK;
1285 void VectorImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) {
1286 MOZ_ASSERT(mProgressTracker);
1288 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1289 mProgressTracker,
1290 &ProgressTracker::OnDiscard));
1293 //******************************************************************************
1294 NS_IMETHODIMP
1295 VectorImage::ResetAnimation() {
1296 if (mError) {
1297 return NS_ERROR_FAILURE;
1300 if (!mIsFullyLoaded || !mHaveAnimations) {
1301 return NS_OK; // There are no animations to be reset.
1304 mSVGDocumentWrapper->ResetAnimation();
1306 return NS_OK;
1309 NS_IMETHODIMP_(float)
1310 VectorImage::GetFrameIndex(uint32_t aWhichFrame) {
1311 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
1312 return aWhichFrame == FRAME_FIRST
1313 ? 0.0f
1314 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1317 //------------------------------------------------------------------------------
1318 // nsIRequestObserver methods
1320 //******************************************************************************
1321 NS_IMETHODIMP
1322 VectorImage::OnStartRequest(nsIRequest* aRequest) {
1323 MOZ_ASSERT(!mSVGDocumentWrapper,
1324 "Repeated call to OnStartRequest -- can this happen?");
1326 mSVGDocumentWrapper = new SVGDocumentWrapper();
1327 nsresult rv = mSVGDocumentWrapper->OnStartRequest(aRequest);
1328 if (NS_FAILED(rv)) {
1329 mSVGDocumentWrapper = nullptr;
1330 mError = true;
1331 return rv;
1334 // Create a listener to wait until the SVG document is fully loaded, which
1335 // will signal that this image is ready to render. Certain error conditions
1336 // will prevent us from ever getting this notification, so we also create a
1337 // listener that waits for parsing to complete and cancels the
1338 // SVGLoadEventListener if needed. The listeners are automatically attached
1339 // to the document by their constructors.
1340 SVGDocument* document = mSVGDocumentWrapper->GetDocument();
1341 mLoadEventListener = new SVGLoadEventListener(document, this);
1342 mParseCompleteListener = new SVGParseCompleteListener(document, this);
1344 // Displayed documents will call InitUseCounters under SetScriptGlobalObject,
1345 // but SVG image documents never get a script global object, so we initialize
1346 // use counters here, right after the document has been created.
1347 document->InitUseCounters();
1349 return NS_OK;
1352 //******************************************************************************
1353 NS_IMETHODIMP
1354 VectorImage::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
1355 if (mError) {
1356 return NS_ERROR_FAILURE;
1359 return mSVGDocumentWrapper->OnStopRequest(aRequest, aStatus);
1362 void VectorImage::OnSVGDocumentParsed() {
1363 MOZ_ASSERT(mParseCompleteListener, "Should have the parse complete listener");
1364 MOZ_ASSERT(mLoadEventListener, "Should have the load event listener");
1366 if (!mSVGDocumentWrapper->GetRootSVGElem()) {
1367 // This is an invalid SVG document. It may have failed to parse, or it may
1368 // be missing the <svg> root element, or the <svg> root element may not
1369 // declare the correct namespace. In any of these cases, we'll never be
1370 // notified that the SVG finished loading, so we need to treat this as an
1371 // error.
1372 OnSVGDocumentError();
1376 void VectorImage::CancelAllListeners() {
1377 if (mParseCompleteListener) {
1378 mParseCompleteListener->Cancel();
1379 mParseCompleteListener = nullptr;
1381 if (mLoadEventListener) {
1382 mLoadEventListener->Cancel();
1383 mLoadEventListener = nullptr;
1387 void VectorImage::OnSVGDocumentLoaded() {
1388 MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(),
1389 "Should have parsed successfully");
1390 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations,
1391 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1392 "Duplicate calls to OnSVGDocumentLoaded?");
1394 CancelAllListeners();
1396 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1397 mSVGDocumentWrapper->FlushLayout();
1399 // This is the earliest point that we can get accurate use counter data
1400 // for a valid SVG document. Without the FlushLayout call, we would miss
1401 // any CSS property usage that comes from SVG presentation attributes.
1402 mSVGDocumentWrapper->GetDocument()->ReportDocumentUseCounters();
1404 mIsFullyLoaded = true;
1405 mHaveAnimations = mSVGDocumentWrapper->IsAnimated();
1407 // Start listening to our image for rendering updates.
1408 mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this);
1410 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1411 // stick around long enough to complete our work.
1412 RefPtr<VectorImage> kungFuDeathGrip(this);
1414 // Tell *our* observers that we're done loading.
1415 if (mProgressTracker) {
1416 Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY |
1417 FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE;
1419 if (mHaveAnimations) {
1420 progress |= FLAG_IS_ANIMATED;
1423 // Merge in any saved progress from OnImageDataComplete.
1424 if (mLoadProgress) {
1425 progress |= *mLoadProgress;
1426 mLoadProgress = Nothing();
1429 mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect());
1432 EvaluateAnimation();
1435 void VectorImage::OnSVGDocumentError() {
1436 CancelAllListeners();
1438 mError = true;
1440 // We won't enter OnSVGDocumentLoaded, so report use counters now for this
1441 // invalid document.
1442 ReportDocumentUseCounters();
1444 if (mProgressTracker) {
1445 // Notify observers about the error and unblock page load.
1446 Progress progress = FLAG_HAS_ERROR;
1448 // Merge in any saved progress from OnImageDataComplete.
1449 if (mLoadProgress) {
1450 progress |= *mLoadProgress;
1451 mLoadProgress = Nothing();
1454 mProgressTracker->SyncNotifyProgress(progress);
1458 //------------------------------------------------------------------------------
1459 // nsIStreamListener method
1461 //******************************************************************************
1462 NS_IMETHODIMP
1463 VectorImage::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
1464 uint64_t aSourceOffset, uint32_t aCount) {
1465 if (mError) {
1466 return NS_ERROR_FAILURE;
1469 return mSVGDocumentWrapper->OnDataAvailable(aRequest, aInStr, aSourceOffset,
1470 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(CreateMediumHighRunnable(ev.forget()),
1508 NS_DISPATCH_NORMAL);
1511 void VectorImage::PropagateUseCounters(Document* aReferencingDocument) {
1512 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1513 doc->PropagateImageUseCounters(aReferencingDocument);
1517 nsIntSize VectorImage::OptimalImageSizeForDest(const gfxSize& aDest,
1518 uint32_t aWhichFrame,
1519 SamplingFilter aSamplingFilter,
1520 uint32_t aFlags) {
1521 MOZ_ASSERT(aDest.width >= 0 || ceil(aDest.width) <= INT32_MAX ||
1522 aDest.height >= 0 || ceil(aDest.height) <= INT32_MAX,
1523 "Unexpected destination size");
1525 // We can rescale SVGs freely, so just return the provided destination size.
1526 return nsIntSize::Ceil(aDest.width, aDest.height);
1529 already_AddRefed<imgIContainer> VectorImage::Unwrap() {
1530 nsCOMPtr<imgIContainer> self(this);
1531 return self.forget();
1534 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1535 const MediaFeatureChange& aChange) {
1536 if (!mSVGDocumentWrapper) {
1537 return;
1540 // Don't bother if the document hasn't loaded yet.
1541 if (!mIsFullyLoaded) {
1542 return;
1545 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1546 if (RefPtr<nsPresContext> presContext = doc->GetPresContext()) {
1547 presContext->MediaFeatureValuesChanged(
1548 aChange, MediaFeatureChangePropagation::All);
1549 // Media feature value changes don't happen in the middle of layout,
1550 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1551 // to invalidate asynchronously.
1552 if (presContext->FlushPendingMediaFeatureValuesChanged()) {
1553 // NOTE(emilio): SendInvalidationNotifications flushes layout via
1554 // VectorImage::CreateSurface -> FlushImageTransformInvalidation.
1555 SendInvalidationNotifications();
1561 nsresult VectorImage::GetHotspotX(int32_t* aX) {
1562 return Image::GetHotspotX(aX);
1565 nsresult VectorImage::GetHotspotY(int32_t* aY) {
1566 return Image::GetHotspotY(aY);
1569 void VectorImage::ReportDocumentUseCounters() {
1570 if (!mSVGDocumentWrapper) {
1571 return;
1574 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1575 doc->ReportDocumentUseCounters();
1579 } // namespace image
1580 } // namespace mozilla