no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / image / VectorImage.cpp
blobeccd04e3cfc05e2fbe05468cbcfcf1415768c6c4
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/PresShell.h"
22 #include "mozilla/ProfilerLabels.h"
23 #include "mozilla/RefPtr.h"
24 #include "mozilla/StaticPrefs_image.h"
25 #include "mozilla/SVGObserverUtils.h" // for SVGRenderingObserver
26 #include "mozilla/SVGUtils.h"
28 #include "nsIStreamListener.h"
29 #include "nsMimeTypes.h"
30 #include "nsPresContext.h"
31 #include "nsRect.h"
32 #include "nsString.h"
33 #include "nsStubDocumentObserver.h"
34 #include "nsWindowSizes.h"
35 #include "ImageRegion.h"
36 #include "ISurfaceProvider.h"
37 #include "LookupResult.h"
38 #include "Orientation.h"
39 #include "SVGDocumentWrapper.h"
40 #include "SVGDrawingCallback.h"
41 #include "SVGDrawingParameters.h"
42 #include "nsIDOMEventListener.h"
43 #include "SurfaceCache.h"
44 #include "BlobSurfaceProvider.h"
45 #include "mozilla/dom/Document.h"
46 #include "mozilla/dom/DocumentInlines.h"
47 #include "mozilla/image/Resolution.h"
48 #include "WindowRenderer.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 : mDocWrapper(aDocWrapper),
67 mVectorImage(aVectorImage),
68 mHonoringInvalidations(true) {
69 MOZ_ASSERT(mDocWrapper, "Need a non-null SVG document wrapper");
70 MOZ_ASSERT(mVectorImage, "Need a non-null VectorImage");
72 StartObserving();
73 Element* elem = GetReferencedElementWithoutObserving();
74 MOZ_ASSERT(elem, "no root SVG node for us to observe");
76 SVGObserverUtils::AddRenderingObserver(elem, this);
77 mInObserverSet = true;
80 void ResumeHonoringInvalidations() { mHonoringInvalidations = true; }
82 protected:
83 virtual ~SVGRootRenderingObserver() {
84 // This needs to call our GetReferencedElementWithoutObserving override,
85 // so must be called here rather than in our base class's dtor.
86 StopObserving();
89 Element* GetReferencedElementWithoutObserving() final {
90 return mDocWrapper->GetRootSVGElem();
93 virtual void OnRenderingChange() override {
94 Element* elem = GetReferencedElementWithoutObserving();
95 MOZ_ASSERT(elem, "missing root SVG node");
97 if (mHonoringInvalidations && !mDocWrapper->ShouldIgnoreInvalidation()) {
98 nsIFrame* frame = elem->GetPrimaryFrame();
99 if (!frame || frame->PresShell()->IsDestroying()) {
100 // We're being destroyed. Bail out.
101 return;
104 // Ignore further invalidations until we draw.
105 mHonoringInvalidations = false;
107 mVectorImage->InvalidateObserversOnNextRefreshDriverTick();
110 // Our caller might've removed us from rendering-observer list.
111 // Add ourselves back!
112 if (!mInObserverSet) {
113 SVGObserverUtils::AddRenderingObserver(elem, this);
114 mInObserverSet = true;
118 // Private data
119 const RefPtr<SVGDocumentWrapper> mDocWrapper;
120 VectorImage* const mVectorImage; // Raw pointer because it owns me.
121 bool mHonoringInvalidations;
124 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver, nsIMutationObserver)
126 class SVGParseCompleteListener final : public nsStubDocumentObserver {
127 public:
128 NS_DECL_ISUPPORTS
130 SVGParseCompleteListener(SVGDocument* aDocument, VectorImage* aImage)
131 : mDocument(aDocument), mImage(aImage) {
132 MOZ_ASSERT(mDocument, "Need an SVG document");
133 MOZ_ASSERT(mImage, "Need an image");
135 mDocument->AddObserver(this);
138 private:
139 ~SVGParseCompleteListener() {
140 if (mDocument) {
141 // The document must have been destroyed before we got our event.
142 // Otherwise this can't happen, since documents hold strong references to
143 // their observers.
144 Cancel();
148 public:
149 void EndLoad(Document* aDocument) override {
150 MOZ_ASSERT(aDocument == mDocument, "Got EndLoad for wrong document?");
152 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
153 // we stick around long enough to complete our work.
154 RefPtr<SVGParseCompleteListener> kungFuDeathGrip(this);
156 mImage->OnSVGDocumentParsed();
159 void Cancel() {
160 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
161 if (mDocument) {
162 mDocument->RemoveObserver(this);
163 mDocument = nullptr;
167 private:
168 RefPtr<SVGDocument> mDocument;
169 VectorImage* const mImage; // Raw pointer to owner.
172 NS_IMPL_ISUPPORTS(SVGParseCompleteListener, nsIDocumentObserver)
174 class SVGLoadEventListener final : public nsIDOMEventListener {
175 public:
176 NS_DECL_ISUPPORTS
178 SVGLoadEventListener(Document* aDocument, VectorImage* aImage)
179 : mDocument(aDocument), mImage(aImage) {
180 MOZ_ASSERT(mDocument, "Need an SVG document");
181 MOZ_ASSERT(mImage, "Need an image");
183 mDocument->AddEventListener(u"MozSVGAsImageDocumentLoad"_ns, this, true,
184 false);
187 private:
188 ~SVGLoadEventListener() {
189 if (mDocument) {
190 // The document must have been destroyed before we got our event.
191 // Otherwise this can't happen, since documents hold strong references to
192 // their observers.
193 Cancel();
197 public:
198 NS_IMETHOD HandleEvent(Event* aEvent) override {
199 MOZ_ASSERT(mDocument, "Need an SVG document. Received multiple events?");
201 // OnSVGDocumentLoaded will release our owner's reference
202 // to us, so ensure we stick around long enough to complete our work.
203 RefPtr<SVGLoadEventListener> kungFuDeathGrip(this);
205 #ifdef DEBUG
206 nsAutoString eventType;
207 aEvent->GetType(eventType);
208 MOZ_ASSERT(eventType.EqualsLiteral("MozSVGAsImageDocumentLoad"),
209 "Received unexpected event");
210 #endif
212 mImage->OnSVGDocumentLoaded();
214 return NS_OK;
217 void Cancel() {
218 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
219 if (mDocument) {
220 mDocument->RemoveEventListener(u"MozSVGAsImageDocumentLoad"_ns, this,
221 true);
222 mDocument = nullptr;
226 private:
227 nsCOMPtr<Document> mDocument;
228 VectorImage* const mImage; // Raw pointer to owner.
231 NS_IMPL_ISUPPORTS(SVGLoadEventListener, nsIDOMEventListener)
233 SVGDrawingCallback::SVGDrawingCallback(SVGDocumentWrapper* aSVGDocumentWrapper,
234 const IntSize& aViewportSize,
235 const IntSize& aSize,
236 uint32_t aImageFlags)
237 : mSVGDocumentWrapper(aSVGDocumentWrapper),
238 mViewportSize(aViewportSize),
239 mSize(aSize),
240 mImageFlags(aImageFlags) {}
242 SVGDrawingCallback::~SVGDrawingCallback() = default;
244 // Based loosely on SVGIntegrationUtils' PaintFrameCallback::operator()
245 bool SVGDrawingCallback::operator()(gfxContext* aContext,
246 const gfxRect& aFillRect,
247 const SamplingFilter aSamplingFilter,
248 const gfxMatrix& aTransform) {
249 MOZ_ASSERT(mSVGDocumentWrapper, "need an SVGDocumentWrapper");
251 // Get (& sanity-check) the helper-doc's presShell
252 RefPtr<PresShell> presShell = mSVGDocumentWrapper->GetPresShell();
253 MOZ_ASSERT(presShell, "GetPresShell returned null for an SVG image?");
255 Document* doc = presShell->GetDocument();
256 [[maybe_unused]] nsIURI* uri = doc ? doc->GetDocumentURI() : nullptr;
257 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
258 "SVG Image drawing", GRAPHICS,
259 nsPrintfCString("%dx%d %s", mSize.width, mSize.height,
260 uri ? uri->GetSpecOrDefault().get() : "N/A"));
262 gfxContextAutoSaveRestore contextRestorer(aContext);
264 // Clip to aFillRect so that we don't paint outside.
265 aContext->Clip(aFillRect);
267 gfxMatrix matrix = aTransform;
268 if (!matrix.Invert()) {
269 return false;
271 aContext->SetMatrixDouble(
272 aContext->CurrentMatrixDouble().PreMultiply(matrix).PreScale(
273 double(mSize.width) / mViewportSize.width,
274 double(mSize.height) / mViewportSize.height));
276 nsPresContext* presContext = presShell->GetPresContext();
277 MOZ_ASSERT(presContext, "pres shell w/out pres context");
279 nsRect svgRect(0, 0, presContext->DevPixelsToAppUnits(mViewportSize.width),
280 presContext->DevPixelsToAppUnits(mViewportSize.height));
282 RenderDocumentFlags renderDocFlags =
283 RenderDocumentFlags::IgnoreViewportScrolling;
284 if (!(mImageFlags & imgIContainer::FLAG_SYNC_DECODE)) {
285 renderDocFlags |= RenderDocumentFlags::AsyncDecodeImages;
287 if (mImageFlags & imgIContainer::FLAG_HIGH_QUALITY_SCALING) {
288 renderDocFlags |= RenderDocumentFlags::UseHighQualityScaling;
291 presShell->RenderDocument(svgRect, renderDocFlags,
292 NS_RGBA(0, 0, 0, 0), // transparent
293 aContext);
295 return true;
298 // Implement VectorImage's nsISupports-inherited methods
299 NS_IMPL_ISUPPORTS(VectorImage, imgIContainer, nsIStreamListener,
300 nsIRequestObserver)
302 //------------------------------------------------------------------------------
303 // Constructor / Destructor
305 VectorImage::VectorImage(nsIURI* aURI /* = nullptr */)
306 : ImageResource(aURI), // invoke superclass's constructor
307 mLockCount(0),
308 mIsInitialized(false),
309 mDiscardable(false),
310 mIsFullyLoaded(false),
311 mHaveAnimations(false),
312 mHasPendingInvalidation(false) {}
314 VectorImage::~VectorImage() {
315 ReportDocumentUseCounters();
316 CancelAllListeners();
317 SurfaceCache::RemoveImage(ImageKey(this));
320 //------------------------------------------------------------------------------
321 // Methods inherited from Image.h
323 nsresult VectorImage::Init(const char* aMimeType, uint32_t aFlags) {
324 // We don't support re-initialization
325 if (mIsInitialized) {
326 return NS_ERROR_ILLEGAL_VALUE;
329 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations && !mError,
330 "Flags unexpectedly set before initialization");
331 MOZ_ASSERT(!strcmp(aMimeType, IMAGE_SVG_XML), "Unexpected mimetype");
333 mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE);
335 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
336 if (!mDiscardable) {
337 mLockCount++;
338 SurfaceCache::LockImage(ImageKey(this));
341 mIsInitialized = true;
342 return NS_OK;
345 size_t VectorImage::SizeOfSourceWithComputedFallback(
346 SizeOfState& aState) const {
347 if (!mSVGDocumentWrapper) {
348 return 0; // No document, so no memory used for the document.
351 SVGDocument* doc = mSVGDocumentWrapper->GetDocument();
352 if (!doc) {
353 return 0; // No document, so no memory used for the document.
356 nsWindowSizes windowSizes(aState);
357 doc->DocAddSizeOfIncludingThis(windowSizes);
359 if (windowSizes.getTotalSize() == 0) {
360 // MallocSizeOf fails on this platform. Because we also use this method for
361 // determining the size of cache entries, we need to return something
362 // reasonable here. Unfortunately, there's no way to estimate the document's
363 // size accurately, so we just use a constant value of 100KB, which will
364 // generally underestimate the true size.
365 return 100 * 1024;
368 return windowSizes.getTotalSize();
371 nsresult VectorImage::OnImageDataComplete(nsIRequest* aRequest,
372 nsresult aStatus, bool aLastPart) {
373 // Call our internal OnStopRequest method, which only talks to our embedded
374 // SVG document. This won't have any effect on our ProgressTracker.
375 nsresult finalStatus = OnStopRequest(aRequest, aStatus);
377 // Give precedence to Necko failure codes.
378 if (NS_FAILED(aStatus)) {
379 finalStatus = aStatus;
382 Progress loadProgress = LoadCompleteProgress(aLastPart, mError, finalStatus);
384 if (mIsFullyLoaded || mError) {
385 // Our document is loaded, so we're ready to notify now.
386 mProgressTracker->SyncNotifyProgress(loadProgress);
387 } else {
388 // Record our progress so far; we'll actually send the notifications in
389 // OnSVGDocumentLoaded or OnSVGDocumentError.
390 mLoadProgress = Some(loadProgress);
393 return finalStatus;
396 nsresult VectorImage::OnImageDataAvailable(nsIRequest* aRequest,
397 nsIInputStream* aInStr,
398 uint64_t aSourceOffset,
399 uint32_t aCount) {
400 return OnDataAvailable(aRequest, aInStr, aSourceOffset, aCount);
403 nsresult VectorImage::StartAnimation() {
404 if (mError) {
405 return NS_ERROR_FAILURE;
408 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
410 mSVGDocumentWrapper->StartAnimation();
411 return NS_OK;
414 nsresult VectorImage::StopAnimation() {
415 nsresult rv = NS_OK;
416 if (mError) {
417 rv = NS_ERROR_FAILURE;
418 } else {
419 MOZ_ASSERT(mIsFullyLoaded && mHaveAnimations,
420 "Should not have been animating!");
422 mSVGDocumentWrapper->StopAnimation();
425 mAnimating = false;
426 return rv;
429 bool VectorImage::ShouldAnimate() {
430 return ImageResource::ShouldAnimate() && mIsFullyLoaded && mHaveAnimations;
433 NS_IMETHODIMP_(void)
434 VectorImage::SetAnimationStartTime(const TimeStamp& aTime) {
435 // We don't care about animation start time.
438 //------------------------------------------------------------------------------
439 // imgIContainer methods
441 //******************************************************************************
442 NS_IMETHODIMP
443 VectorImage::GetWidth(int32_t* aWidth) {
444 if (mError || !mIsFullyLoaded) {
445 // XXXdholbert Technically we should leave outparam untouched when we
446 // fail. But since many callers don't check for failure, we set it to 0 on
447 // failure, for sane/predictable results.
448 *aWidth = 0;
449 return NS_ERROR_FAILURE;
452 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
453 MOZ_ASSERT(rootElem,
454 "Should have a root SVG elem, since we finished "
455 "loading without errors");
456 LengthPercentage rootElemWidth = rootElem->GetIntrinsicWidth();
458 if (!rootElemWidth.IsLength()) {
459 *aWidth = 0;
460 return NS_ERROR_FAILURE;
463 *aWidth = SVGUtils::ClampToInt(rootElemWidth.AsLength().ToCSSPixels());
464 return NS_OK;
467 //******************************************************************************
468 nsresult VectorImage::GetNativeSizes(nsTArray<IntSize>& aNativeSizes) {
469 return NS_ERROR_NOT_IMPLEMENTED;
472 //******************************************************************************
473 size_t VectorImage::GetNativeSizesLength() { return 0; }
475 //******************************************************************************
476 NS_IMETHODIMP_(void)
477 VectorImage::RequestRefresh(const TimeStamp& aTime) {
478 if (HadRecentRefresh(aTime)) {
479 return;
482 Document* doc = mSVGDocumentWrapper->GetDocument();
483 if (!doc) {
484 // We are racing between shutdown and a refresh.
485 return;
488 EvaluateAnimation();
490 mSVGDocumentWrapper->TickRefreshDriver();
492 if (mHasPendingInvalidation) {
493 SendInvalidationNotifications();
497 void VectorImage::SendInvalidationNotifications() {
498 // Animated images don't send out invalidation notifications as soon as
499 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
500 // records that there are pending invalidations and then returns immediately.
501 // The notifications are actually sent from RequestRefresh(). We send these
502 // notifications there to ensure that there is actually a document observing
503 // us. Otherwise, the notifications are just wasted effort.
505 // Non-animated images post an event to call this method from
506 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
507 // called for them. Ordinarily this isn't needed, since we send out
508 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
509 // SVG document may not be 100% ready to render at that time. In those cases
510 // we would miss the subsequent invalidations if we didn't send out the
511 // notifications indirectly in |InvalidateObservers...|.
513 mHasPendingInvalidation = false;
515 if (SurfaceCache::InvalidateImage(ImageKey(this))) {
516 // If we still have recordings in the cache, make sure we handle future
517 // invalidations.
518 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
519 mRenderingObserver->ResumeHonoringInvalidations();
522 if (mProgressTracker) {
523 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
524 GetMaxSizedIntRect());
528 NS_IMETHODIMP_(IntRect)
529 VectorImage::GetImageSpaceInvalidationRect(const IntRect& aRect) {
530 return aRect;
533 //******************************************************************************
534 NS_IMETHODIMP
535 VectorImage::GetHeight(int32_t* aHeight) {
536 if (mError || !mIsFullyLoaded) {
537 // XXXdholbert Technically we should leave outparam untouched when we
538 // fail. But since many callers don't check for failure, we set it to 0 on
539 // failure, for sane/predictable results.
540 *aHeight = 0;
541 return NS_ERROR_FAILURE;
544 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
545 MOZ_ASSERT(rootElem,
546 "Should have a root SVG elem, since we finished "
547 "loading without errors");
548 LengthPercentage rootElemHeight = rootElem->GetIntrinsicHeight();
550 if (!rootElemHeight.IsLength()) {
551 *aHeight = 0;
552 return NS_ERROR_FAILURE;
555 *aHeight = SVGUtils::ClampToInt(rootElemHeight.AsLength().ToCSSPixels());
556 return NS_OK;
559 //******************************************************************************
560 NS_IMETHODIMP
561 VectorImage::GetIntrinsicSize(nsSize* aSize) {
562 if (mError || !mIsFullyLoaded) {
563 return NS_ERROR_FAILURE;
566 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
567 if (!rootFrame) {
568 return NS_ERROR_FAILURE;
571 *aSize = nsSize(-1, -1);
572 IntrinsicSize rfSize = rootFrame->GetIntrinsicSize();
573 if (rfSize.width) {
574 aSize->width = *rfSize.width;
576 if (rfSize.height) {
577 aSize->height = *rfSize.height;
579 return NS_OK;
582 //******************************************************************************
583 Maybe<AspectRatio> VectorImage::GetIntrinsicRatio() {
584 if (mError || !mIsFullyLoaded) {
585 return Nothing();
588 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
589 if (!rootFrame) {
590 return Nothing();
593 return Some(rootFrame->GetIntrinsicRatio());
596 NS_IMETHODIMP_(Orientation)
597 VectorImage::GetOrientation() { return Orientation(); }
599 NS_IMETHODIMP_(Resolution)
600 VectorImage::GetResolution() { return {}; }
602 //******************************************************************************
603 NS_IMETHODIMP
604 VectorImage::GetType(uint16_t* aType) {
605 NS_ENSURE_ARG_POINTER(aType);
607 *aType = imgIContainer::TYPE_VECTOR;
608 return NS_OK;
611 //******************************************************************************
612 NS_IMETHODIMP
613 VectorImage::GetProviderId(uint32_t* aId) {
614 NS_ENSURE_ARG_POINTER(aId);
616 *aId = ImageResource::GetImageProviderId();
617 return NS_OK;
620 //******************************************************************************
621 NS_IMETHODIMP
622 VectorImage::GetAnimated(bool* aAnimated) {
623 if (mError || !mIsFullyLoaded) {
624 return NS_ERROR_FAILURE;
627 *aAnimated = mSVGDocumentWrapper->IsAnimated();
628 return NS_OK;
631 //******************************************************************************
632 int32_t VectorImage::GetFirstFrameDelay() {
633 if (mError) {
634 return -1;
637 if (!mSVGDocumentWrapper->IsAnimated()) {
638 return -1;
641 // We don't really have a frame delay, so just pretend that we constantly
642 // need updates.
643 return 0;
646 NS_IMETHODIMP_(bool)
647 VectorImage::WillDrawOpaqueNow() {
648 return false; // In general, SVG content is not opaque.
651 //******************************************************************************
652 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
653 VectorImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags) {
654 if (mError) {
655 return nullptr;
658 // Look up height & width
659 // ----------------------
660 SVGSVGElement* svgElem = mSVGDocumentWrapper->GetRootSVGElem();
661 MOZ_ASSERT(svgElem,
662 "Should have a root SVG elem, since we finished "
663 "loading without errors");
664 LengthPercentage width = svgElem->GetIntrinsicWidth();
665 LengthPercentage height = svgElem->GetIntrinsicHeight();
666 if (!width.IsLength() || !height.IsLength()) {
667 // The SVG is lacking a definite size for its width or height, so we do not
668 // know how big of a surface to generate. Hence, we just bail.
669 return nullptr;
672 nsIntSize imageIntSize(SVGUtils::ClampToInt(width.AsLength().ToCSSPixels()),
673 SVGUtils::ClampToInt(height.AsLength().ToCSSPixels()));
675 return GetFrameAtSize(imageIntSize, aWhichFrame, aFlags);
678 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
679 VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
680 uint32_t aFlags) {
681 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE);
683 AutoProfilerImagePaintMarker PROFILER_RAII(this);
684 #ifdef DEBUG
685 NotifyDrawingObservers();
686 #endif
688 if (aSize.IsEmpty() || aWhichFrame > FRAME_MAX_VALUE || mError ||
689 !mIsFullyLoaded) {
690 return nullptr;
693 uint32_t whichFrame = mHaveAnimations ? aWhichFrame : FRAME_FIRST;
695 auto [sourceSurface, decodeSize] =
696 LookupCachedSurface(aSize, SVGImageContext(), aFlags);
697 if (sourceSurface) {
698 return sourceSurface.forget();
701 if (mSVGDocumentWrapper->IsDrawing()) {
702 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
703 return nullptr;
706 float animTime = (whichFrame == FRAME_FIRST)
707 ? 0.0f
708 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
710 // By using a null gfxContext, we ensure that we will always attempt to
711 // create a surface, even if we aren't capable of caching it (e.g. due to our
712 // flags, having an animation, etc). Otherwise CreateSurface will assume that
713 // the caller is capable of drawing directly to its own draw target if we
714 // cannot cache.
715 SVGImageContext svgContext;
716 SVGDrawingParameters params(
717 nullptr, decodeSize, aSize, ImageRegion::Create(decodeSize),
718 SamplingFilter::POINT, svgContext, animTime, aFlags, 1.0);
720 bool didCache; // Was the surface put into the cache?
722 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper,
723 /* aContextPaint */ false);
725 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
726 RefPtr<SourceSurface> surface = CreateSurface(params, svgDrawable, didCache);
727 if (!surface) {
728 MOZ_ASSERT(!didCache);
729 return nullptr;
732 SendFrameComplete(didCache, params.flags);
733 return surface.forget();
736 NS_IMETHODIMP_(bool)
737 VectorImage::IsImageContainerAvailable(WindowRenderer* aRenderer,
738 uint32_t aFlags) {
739 if (mError || !mIsFullyLoaded ||
740 aRenderer->GetBackendType() != LayersBackend::LAYERS_WR) {
741 return false;
744 if (mHaveAnimations && !StaticPrefs::image_svg_blob_image()) {
745 // We don't support rasterizing animation SVGs. We can put them in a blob
746 // recording however instead of using fallback.
747 return false;
750 return true;
753 //******************************************************************************
754 NS_IMETHODIMP_(ImgDrawResult)
755 VectorImage::GetImageProvider(WindowRenderer* aRenderer,
756 const gfx::IntSize& aSize,
757 const SVGImageContext& aSVGContext,
758 const Maybe<ImageIntRegion>& aRegion,
759 uint32_t aFlags,
760 WebRenderImageProvider** aProvider) {
761 MOZ_ASSERT(NS_IsMainThread());
762 MOZ_ASSERT(aRenderer);
763 MOZ_ASSERT(!(aFlags & FLAG_BYPASS_SURFACE_CACHE), "Unsupported flags");
765 // We don't need to check if the size is too big since we only support
766 // WebRender backends.
767 if (aSize.IsEmpty()) {
768 return ImgDrawResult::BAD_ARGS;
771 if (mError) {
772 return ImgDrawResult::BAD_IMAGE;
775 if (!mIsFullyLoaded) {
776 return ImgDrawResult::NOT_READY;
779 if (mHaveAnimations && !(aFlags & FLAG_RECORD_BLOB)) {
780 // We don't support rasterizing animation SVGs. We can put them in a blob
781 // recording however instead of using fallback.
782 return ImgDrawResult::NOT_SUPPORTED;
785 AutoProfilerImagePaintMarker PROFILER_RAII(this);
786 #ifdef DEBUG
787 NotifyDrawingObservers();
788 #endif
790 // Only blob recordings support a region to restrict drawing.
791 const bool blobRecording = aFlags & FLAG_RECORD_BLOB;
792 MOZ_ASSERT_IF(!blobRecording, aRegion.isNothing());
794 LookupResult result(MatchType::NOT_FOUND);
795 auto playbackType =
796 mHaveAnimations ? PlaybackType::eAnimated : PlaybackType::eStatic;
797 auto surfaceFlags = ToSurfaceFlags(aFlags);
799 SVGImageContext newSVGContext = aSVGContext;
800 bool contextPaint = MaybeRestrictSVGContext(newSVGContext, aFlags);
802 SurfaceKey surfaceKey = VectorSurfaceKey(aSize, aRegion, newSVGContext,
803 surfaceFlags, playbackType);
804 if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
805 result = SurfaceCache::Lookup(ImageKey(this), surfaceKey,
806 /* aMarkUsed = */ true);
807 } else {
808 result = SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey,
809 /* aMarkUsed = */ true);
812 // Unless we get a best match (exact or factor of 2 limited), then we want to
813 // generate a new recording/rerasterize, even if we have a substitute.
814 if (result && (result.Type() == MatchType::EXACT ||
815 result.Type() == MatchType::SUBSTITUTE_BECAUSE_BEST)) {
816 result.Surface().TakeProvider(aProvider);
817 return ImgDrawResult::SUCCESS;
820 // Ensure we store the surface with the correct key if we switched to factor
821 // of 2 sizing or we otherwise got clamped.
822 IntSize rasterSize(aSize);
823 if (!result.SuggestedSize().IsEmpty()) {
824 rasterSize = result.SuggestedSize();
825 surfaceKey = surfaceKey.CloneWithSize(rasterSize);
828 // We're about to rerasterize, which may mean that some of the previous
829 // surfaces we've rasterized aren't useful anymore. We can allow them to
830 // expire from the cache by unlocking them here, and then sending out an
831 // invalidation. If this image is locked, any surfaces that are still useful
832 // will become locked again when Draw touches them, and the remainder will
833 // eventually expire.
834 bool mayCache = SurfaceCache::CanHold(rasterSize);
835 if (mayCache) {
836 SurfaceCache::UnlockEntries(ImageKey(this));
839 // Blob recorded vector images just create a provider responsible for
840 // generating blob keys and recording bindings. The recording won't happen
841 // until the caller requests the key explicitly.
842 RefPtr<ISurfaceProvider> provider;
843 if (blobRecording) {
844 provider = MakeRefPtr<BlobSurfaceProvider>(ImageKey(this), surfaceKey,
845 mSVGDocumentWrapper, aFlags);
846 } else {
847 if (mSVGDocumentWrapper->IsDrawing()) {
848 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
849 return ImgDrawResult::TEMPORARY_ERROR;
852 if (!SurfaceCache::IsLegalSize(rasterSize) ||
853 !Factory::AllowedSurfaceSize(rasterSize)) {
854 // If either of these is true then the InitWithDrawable call below will
855 // fail, so fail early and use this opportunity to return NOT_SUPPORTED
856 // instead of TEMPORARY_ERROR as we do for any InitWithDrawable failure.
857 // This means that we will use fallback which has a path that will draw
858 // directly into the gfxContext without having to allocate a surface. It
859 // means we will have to use fallback and re-rasterize for everytime we
860 // have to draw this image, but it's better than not drawing anything at
861 // all.
862 return ImgDrawResult::NOT_SUPPORTED;
865 // We aren't using blobs, so we need to rasterize.
866 float animTime =
867 mHaveAnimations ? mSVGDocumentWrapper->GetCurrentTimeAsFloat() : 0.0f;
869 // By using a null gfxContext, we ensure that we will always attempt to
870 // create a surface, even if we aren't capable of caching it (e.g. due to
871 // our flags, having an animation, etc). Otherwise CreateSurface will assume
872 // that the caller is capable of drawing directly to its own draw target if
873 // we cannot cache.
874 SVGDrawingParameters params(
875 nullptr, rasterSize, aSize, ImageRegion::Create(rasterSize),
876 SamplingFilter::POINT, newSVGContext, animTime, aFlags, 1.0);
878 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
879 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, contextPaint);
881 mSVGDocumentWrapper->UpdateViewportBounds(params.viewportSize);
882 mSVGDocumentWrapper->FlushImageTransformInvalidation();
884 // Given we have no context, the default backend is fine.
885 BackendType backend =
886 gfxPlatform::GetPlatform()->GetDefaultContentBackend();
888 // Try to create an imgFrame, initializing the surface it contains by
889 // drawing our gfxDrawable into it. (We use FILTER_NEAREST since we never
890 // scale here.)
891 auto frame = MakeNotNull<RefPtr<imgFrame>>();
892 nsresult rv = frame->InitWithDrawable(
893 svgDrawable, params.size, SurfaceFormat::OS_RGBA, SamplingFilter::POINT,
894 params.flags, backend);
896 // If we couldn't create the frame, it was probably because it would end
897 // up way too big. Generally it also wouldn't fit in the cache, but the
898 // prefs could be set such that the cache isn't the limiting factor.
899 if (NS_FAILED(rv)) {
900 return ImgDrawResult::TEMPORARY_ERROR;
903 provider =
904 MakeRefPtr<SimpleSurfaceProvider>(ImageKey(this), surfaceKey, frame);
907 if (mayCache) {
908 // Attempt to cache the frame.
909 if (SurfaceCache::Insert(WrapNotNull(provider)) == InsertOutcome::SUCCESS) {
910 if (rasterSize != aSize) {
911 // We created a new surface that wasn't the size we requested, which
912 // means we entered factor-of-2 mode. We should purge any surfaces we
913 // no longer need rather than waiting for the cache to expire them.
914 SurfaceCache::PruneImage(ImageKey(this));
917 SendFrameComplete(/* aDidCache */ true, aFlags);
921 MOZ_ASSERT(provider);
922 provider.forget(aProvider);
923 return ImgDrawResult::SUCCESS;
926 bool VectorImage::MaybeRestrictSVGContext(SVGImageContext& aSVGContext,
927 uint32_t aFlags) {
928 bool overridePAR = (aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE);
930 bool haveContextPaint = aSVGContext.GetContextPaint();
931 bool blockContextPaint =
932 haveContextPaint && !SVGContextPaint::IsAllowedForImageFromURI(mURI);
934 if (overridePAR || blockContextPaint) {
935 if (overridePAR) {
936 // The SVGImageContext must take account of the preserveAspectRatio
937 // override:
938 MOZ_ASSERT(!aSVGContext.GetPreserveAspectRatio(),
939 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
940 "preserveAspectRatio override is supplied");
941 Maybe<SVGPreserveAspectRatio> aspectRatio = Some(SVGPreserveAspectRatio(
942 SVG_PRESERVEASPECTRATIO_NONE, SVG_MEETORSLICE_UNKNOWN));
943 aSVGContext.SetPreserveAspectRatio(aspectRatio);
946 if (blockContextPaint) {
947 // The SVGImageContext must not include context paint if the image is
948 // not allowed to use it:
949 aSVGContext.ClearContextPaint();
953 return haveContextPaint && !blockContextPaint;
956 //******************************************************************************
957 NS_IMETHODIMP_(ImgDrawResult)
958 VectorImage::Draw(gfxContext* aContext, const nsIntSize& aSize,
959 const ImageRegion& aRegion, uint32_t aWhichFrame,
960 SamplingFilter aSamplingFilter,
961 const SVGImageContext& aSVGContext, uint32_t aFlags,
962 float aOpacity) {
963 if (aWhichFrame > FRAME_MAX_VALUE) {
964 return ImgDrawResult::BAD_ARGS;
967 if (!aContext) {
968 return ImgDrawResult::BAD_ARGS;
971 if (mError) {
972 return ImgDrawResult::BAD_IMAGE;
975 if (!mIsFullyLoaded) {
976 return ImgDrawResult::NOT_READY;
979 if (mAnimationConsumers == 0 && mHaveAnimations) {
980 SendOnUnlockedDraw(aFlags);
983 // We should bypass the cache when:
984 // - We are using a DrawTargetRecording because we prefer the drawing commands
985 // in general to the rasterized surface. This allows blob images to avoid
986 // rasterized SVGs with WebRender.
987 if (aContext->GetDrawTarget()->GetBackendType() == BackendType::RECORDING) {
988 aFlags |= FLAG_BYPASS_SURFACE_CACHE;
991 MOZ_ASSERT(!(aFlags & FLAG_FORCE_PRESERVEASPECTRATIO_NONE) ||
992 aSVGContext.GetViewportSize(),
993 "Viewport size is required when using "
994 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
996 uint32_t whichFrame = mHaveAnimations ? aWhichFrame : FRAME_FIRST;
998 float animTime = (whichFrame == FRAME_FIRST)
999 ? 0.0f
1000 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1002 SVGImageContext newSVGContext = aSVGContext;
1003 bool contextPaint = MaybeRestrictSVGContext(newSVGContext, aFlags);
1005 SVGDrawingParameters params(aContext, aSize, aSize, aRegion, aSamplingFilter,
1006 newSVGContext, animTime, aFlags, aOpacity);
1008 // If we have an prerasterized version of this image that matches the
1009 // drawing parameters, use that.
1010 RefPtr<SourceSurface> sourceSurface;
1011 std::tie(sourceSurface, params.size) =
1012 LookupCachedSurface(aSize, params.svgContext, aFlags);
1013 if (sourceSurface) {
1014 RefPtr<gfxDrawable> drawable =
1015 new gfxSurfaceDrawable(sourceSurface, params.size);
1016 Show(drawable, params);
1017 return ImgDrawResult::SUCCESS;
1020 // else, we need to paint the image:
1022 if (mSVGDocumentWrapper->IsDrawing()) {
1023 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
1024 return ImgDrawResult::TEMPORARY_ERROR;
1027 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, contextPaint);
1029 bool didCache; // Was the surface put into the cache?
1030 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
1031 sourceSurface = CreateSurface(params, svgDrawable, didCache);
1032 if (!sourceSurface) {
1033 MOZ_ASSERT(!didCache);
1034 Show(svgDrawable, params);
1035 return ImgDrawResult::SUCCESS;
1038 RefPtr<gfxDrawable> drawable =
1039 new gfxSurfaceDrawable(sourceSurface, params.size);
1040 Show(drawable, params);
1041 SendFrameComplete(didCache, params.flags);
1042 return ImgDrawResult::SUCCESS;
1045 already_AddRefed<gfxDrawable> VectorImage::CreateSVGDrawable(
1046 const SVGDrawingParameters& aParams) {
1047 RefPtr<gfxDrawingCallback> cb = new SVGDrawingCallback(
1048 mSVGDocumentWrapper, aParams.viewportSize, aParams.size, aParams.flags);
1050 RefPtr<gfxDrawable> svgDrawable = new gfxCallbackDrawable(cb, aParams.size);
1051 return svgDrawable.forget();
1054 std::tuple<RefPtr<SourceSurface>, IntSize> VectorImage::LookupCachedSurface(
1055 const IntSize& aSize, const SVGImageContext& aSVGContext, uint32_t aFlags) {
1056 // We can't use cached surfaces if we:
1057 // - Explicitly disallow it via FLAG_BYPASS_SURFACE_CACHE
1058 // - Want a blob recording which aren't supported by the cache.
1059 // - Have animations which aren't supported by the cache.
1060 if (aFlags & (FLAG_BYPASS_SURFACE_CACHE | FLAG_RECORD_BLOB) ||
1061 mHaveAnimations) {
1062 return std::make_tuple(RefPtr<SourceSurface>(), aSize);
1065 LookupResult result(MatchType::NOT_FOUND);
1066 SurfaceKey surfaceKey = VectorSurfaceKey(aSize, aSVGContext);
1067 if ((aFlags & FLAG_SYNC_DECODE) || !(aFlags & FLAG_HIGH_QUALITY_SCALING)) {
1068 result = SurfaceCache::Lookup(ImageKey(this), surfaceKey,
1069 /* aMarkUsed = */ true);
1070 } else {
1071 result = SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey,
1072 /* aMarkUsed = */ true);
1075 IntSize rasterSize =
1076 result.SuggestedSize().IsEmpty() ? aSize : result.SuggestedSize();
1077 MOZ_ASSERT(result.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING);
1078 if (!result || result.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND) {
1079 // No matching surface, or the OS freed the volatile buffer.
1080 return std::make_tuple(RefPtr<SourceSurface>(), rasterSize);
1083 RefPtr<SourceSurface> sourceSurface = result.Surface()->GetSourceSurface();
1084 if (!sourceSurface) {
1085 // Something went wrong. (Probably a GPU driver crash or device reset.)
1086 // Attempt to recover.
1087 RecoverFromLossOfSurfaces();
1088 return std::make_tuple(RefPtr<SourceSurface>(), rasterSize);
1091 return std::make_tuple(std::move(sourceSurface), rasterSize);
1094 already_AddRefed<SourceSurface> VectorImage::CreateSurface(
1095 const SVGDrawingParameters& aParams, gfxDrawable* aSVGDrawable,
1096 bool& aWillCache) {
1097 MOZ_ASSERT(mSVGDocumentWrapper->IsDrawing());
1098 MOZ_ASSERT(!(aParams.flags & FLAG_RECORD_BLOB));
1100 mSVGDocumentWrapper->UpdateViewportBounds(aParams.viewportSize);
1101 mSVGDocumentWrapper->FlushImageTransformInvalidation();
1103 // Determine whether or not we should put the surface to be created into
1104 // the cache. If we fail, we need to reset this to false to let the caller
1105 // know nothing was put in the cache.
1106 aWillCache = !(aParams.flags & FLAG_BYPASS_SURFACE_CACHE) &&
1107 // Refuse to cache animated images:
1108 // XXX(seth): We may remove this restriction in bug 922893.
1109 !mHaveAnimations &&
1110 // The image is too big to fit in the cache:
1111 SurfaceCache::CanHold(aParams.size);
1113 // If we weren't given a context, then we know we just want the rasterized
1114 // surface. We will create the frame below but only insert it into the cache
1115 // if we actually need to.
1116 if (!aWillCache && aParams.context) {
1117 return nullptr;
1120 // We're about to rerasterize, which may mean that some of the previous
1121 // surfaces we've rasterized aren't useful anymore. We can allow them to
1122 // expire from the cache by unlocking them here, and then sending out an
1123 // invalidation. If this image is locked, any surfaces that are still useful
1124 // will become locked again when Draw touches them, and the remainder will
1125 // eventually expire.
1126 if (aWillCache) {
1127 SurfaceCache::UnlockEntries(ImageKey(this));
1130 // If there is no context, the default backend is fine.
1131 BackendType backend =
1132 aParams.context ? aParams.context->GetDrawTarget()->GetBackendType()
1133 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1135 if (backend == BackendType::DIRECT2D1_1) {
1136 // We don't want to draw arbitrary content with D2D anymore
1137 // because it doesn't support PushLayerWithBlend so switch to skia
1138 backend = BackendType::SKIA;
1141 // Try to create an imgFrame, initializing the surface it contains by drawing
1142 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1143 auto frame = MakeNotNull<RefPtr<imgFrame>>();
1144 nsresult rv = frame->InitWithDrawable(
1145 aSVGDrawable, aParams.size, SurfaceFormat::OS_RGBA, SamplingFilter::POINT,
1146 aParams.flags, backend);
1148 // If we couldn't create the frame, it was probably because it would end
1149 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1150 // could be set such that the cache isn't the limiting factor.
1151 if (NS_FAILED(rv)) {
1152 aWillCache = false;
1153 return nullptr;
1156 // Take a strong reference to the frame's surface and make sure it hasn't
1157 // already been purged by the operating system.
1158 RefPtr<SourceSurface> surface = frame->GetSourceSurface();
1159 if (!surface) {
1160 aWillCache = false;
1161 return nullptr;
1164 // We created the frame, but only because we had no context to draw to
1165 // directly. All the caller wants is the surface in this case.
1166 if (!aWillCache) {
1167 return surface.forget();
1170 // Attempt to cache the frame.
1171 SurfaceKey surfaceKey = VectorSurfaceKey(aParams.size, aParams.svgContext);
1172 NotNull<RefPtr<ISurfaceProvider>> provider =
1173 MakeNotNull<SimpleSurfaceProvider*>(ImageKey(this), surfaceKey, frame);
1175 if (SurfaceCache::Insert(provider) == InsertOutcome::SUCCESS) {
1176 if (aParams.size != aParams.drawSize) {
1177 // We created a new surface that wasn't the size we requested, which means
1178 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1179 // need rather than waiting for the cache to expire them.
1180 SurfaceCache::PruneImage(ImageKey(this));
1182 } else {
1183 aWillCache = false;
1186 return surface.forget();
1189 void VectorImage::SendFrameComplete(bool aDidCache, uint32_t aFlags) {
1190 // If the cache was not updated, we have nothing to do.
1191 if (!aDidCache) {
1192 return;
1195 // Send out an invalidation so that surfaces that are still in use get
1196 // re-locked. See the discussion of the UnlockSurfaces call above.
1197 if (!(aFlags & FLAG_ASYNC_NOTIFY)) {
1198 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1199 GetMaxSizedIntRect());
1200 } else {
1201 NotNull<RefPtr<VectorImage>> image = WrapNotNull(this);
1202 NS_DispatchToMainThread(CreateRenderBlockingRunnable(NS_NewRunnableFunction(
1203 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1204 RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
1205 if (tracker) {
1206 tracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1207 GetMaxSizedIntRect());
1209 })));
1213 void VectorImage::Show(gfxDrawable* aDrawable,
1214 const SVGDrawingParameters& aParams) {
1215 // The surface size may differ from the size at which we wish to draw. As
1216 // such, we may need to adjust the context/region to take this into account.
1217 gfxContextMatrixAutoSaveRestore saveMatrix(aParams.context);
1218 ImageRegion region(aParams.region);
1219 if (aParams.drawSize != aParams.size) {
1220 gfx::MatrixScales scale(
1221 double(aParams.drawSize.width) / aParams.size.width,
1222 double(aParams.drawSize.height) / aParams.size.height);
1223 aParams.context->Multiply(gfx::Matrix::Scaling(scale));
1224 region.Scale(1.0 / scale.xScale, 1.0 / scale.yScale);
1227 MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
1228 gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
1229 SizeDouble(aParams.size), region,
1230 SurfaceFormat::OS_RGBA, aParams.samplingFilter,
1231 aParams.flags, aParams.opacity, false);
1233 AutoProfilerImagePaintMarker PROFILER_RAII(this);
1234 #ifdef DEBUG
1235 NotifyDrawingObservers();
1236 #endif
1238 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
1239 mRenderingObserver->ResumeHonoringInvalidations();
1242 void VectorImage::RecoverFromLossOfSurfaces() {
1243 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1245 // Discard all existing frames, since they're probably all now invalid.
1246 SurfaceCache::RemoveImage(ImageKey(this));
1249 NS_IMETHODIMP
1250 VectorImage::StartDecoding(uint32_t aFlags, uint32_t aWhichFrame) {
1251 // Nothing to do for SVG images
1252 return NS_OK;
1255 bool VectorImage::StartDecodingWithResult(uint32_t aFlags,
1256 uint32_t aWhichFrame) {
1257 // SVG images are ready to draw when they are loaded
1258 return mIsFullyLoaded;
1261 bool VectorImage::HasDecodedPixels() {
1262 MOZ_ASSERT_UNREACHABLE("calling VectorImage::HasDecodedPixels");
1263 return mIsFullyLoaded;
1266 imgIContainer::DecodeResult VectorImage::RequestDecodeWithResult(
1267 uint32_t aFlags, uint32_t aWhichFrame) {
1268 // SVG images are ready to draw when they are loaded and don't have an error.
1270 if (mError) {
1271 return imgIContainer::DECODE_REQUEST_FAILED;
1274 if (!mIsFullyLoaded) {
1275 return imgIContainer::DECODE_REQUESTED;
1278 return imgIContainer::DECODE_SURFACE_AVAILABLE;
1281 NS_IMETHODIMP
1282 VectorImage::RequestDecodeForSize(const nsIntSize& aSize, uint32_t aFlags,
1283 uint32_t aWhichFrame) {
1284 // Nothing to do for SVG images, though in theory we could rasterize to the
1285 // provided size ahead of time if we supported off-main-thread SVG
1286 // rasterization...
1287 return NS_OK;
1290 //******************************************************************************
1292 NS_IMETHODIMP
1293 VectorImage::LockImage() {
1294 MOZ_ASSERT(NS_IsMainThread());
1296 if (mError) {
1297 return NS_ERROR_FAILURE;
1300 mLockCount++;
1302 if (mLockCount == 1) {
1303 // Lock this image's surfaces in the SurfaceCache.
1304 SurfaceCache::LockImage(ImageKey(this));
1307 return NS_OK;
1310 //******************************************************************************
1312 NS_IMETHODIMP
1313 VectorImage::UnlockImage() {
1314 MOZ_ASSERT(NS_IsMainThread());
1316 if (mError) {
1317 return NS_ERROR_FAILURE;
1320 if (mLockCount == 0) {
1321 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1322 return NS_ERROR_ABORT;
1325 mLockCount--;
1327 if (mLockCount == 0) {
1328 // Unlock this image's surfaces in the SurfaceCache.
1329 SurfaceCache::UnlockImage(ImageKey(this));
1332 return NS_OK;
1335 //******************************************************************************
1337 NS_IMETHODIMP
1338 VectorImage::RequestDiscard() {
1339 MOZ_ASSERT(NS_IsMainThread());
1341 if (mDiscardable && mLockCount == 0) {
1342 SurfaceCache::RemoveImage(ImageKey(this));
1343 mProgressTracker->OnDiscard();
1346 return NS_OK;
1349 void VectorImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) {
1350 MOZ_ASSERT(mProgressTracker);
1352 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1353 mProgressTracker,
1354 &ProgressTracker::OnDiscard));
1357 //******************************************************************************
1358 NS_IMETHODIMP
1359 VectorImage::ResetAnimation() {
1360 if (mError) {
1361 return NS_ERROR_FAILURE;
1364 if (!mIsFullyLoaded || !mHaveAnimations) {
1365 return NS_OK; // There are no animations to be reset.
1368 mSVGDocumentWrapper->ResetAnimation();
1370 return NS_OK;
1373 NS_IMETHODIMP_(float)
1374 VectorImage::GetFrameIndex(uint32_t aWhichFrame) {
1375 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
1376 return aWhichFrame == FRAME_FIRST
1377 ? 0.0f
1378 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1381 //------------------------------------------------------------------------------
1382 // nsIRequestObserver methods
1384 //******************************************************************************
1385 NS_IMETHODIMP
1386 VectorImage::OnStartRequest(nsIRequest* aRequest) {
1387 MOZ_ASSERT(!mSVGDocumentWrapper,
1388 "Repeated call to OnStartRequest -- can this happen?");
1390 mSVGDocumentWrapper = new SVGDocumentWrapper();
1391 nsresult rv = mSVGDocumentWrapper->OnStartRequest(aRequest);
1392 if (NS_FAILED(rv)) {
1393 mSVGDocumentWrapper = nullptr;
1394 mError = true;
1395 return rv;
1398 // Create a listener to wait until the SVG document is fully loaded, which
1399 // will signal that this image is ready to render. Certain error conditions
1400 // will prevent us from ever getting this notification, so we also create a
1401 // listener that waits for parsing to complete and cancels the
1402 // SVGLoadEventListener if needed. The listeners are automatically attached
1403 // to the document by their constructors.
1404 SVGDocument* document = mSVGDocumentWrapper->GetDocument();
1405 mLoadEventListener = new SVGLoadEventListener(document, this);
1406 mParseCompleteListener = new SVGParseCompleteListener(document, this);
1408 // Displayed documents will call InitUseCounters under SetScriptGlobalObject,
1409 // but SVG image documents never get a script global object, so we initialize
1410 // use counters here, right after the document has been created.
1411 document->InitUseCounters();
1413 return NS_OK;
1416 //******************************************************************************
1417 NS_IMETHODIMP
1418 VectorImage::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
1419 if (mError) {
1420 return NS_ERROR_FAILURE;
1423 return mSVGDocumentWrapper->OnStopRequest(aRequest, aStatus);
1426 void VectorImage::OnSVGDocumentParsed() {
1427 MOZ_ASSERT(mParseCompleteListener, "Should have the parse complete listener");
1428 MOZ_ASSERT(mLoadEventListener, "Should have the load event listener");
1430 if (!mSVGDocumentWrapper->GetRootSVGElem()) {
1431 // This is an invalid SVG document. It may have failed to parse, or it may
1432 // be missing the <svg> root element, or the <svg> root element may not
1433 // declare the correct namespace. In any of these cases, we'll never be
1434 // notified that the SVG finished loading, so we need to treat this as an
1435 // error.
1436 OnSVGDocumentError();
1440 void VectorImage::CancelAllListeners() {
1441 if (mParseCompleteListener) {
1442 mParseCompleteListener->Cancel();
1443 mParseCompleteListener = nullptr;
1445 if (mLoadEventListener) {
1446 mLoadEventListener->Cancel();
1447 mLoadEventListener = nullptr;
1451 void VectorImage::OnSVGDocumentLoaded() {
1452 MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(),
1453 "Should have parsed successfully");
1454 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations,
1455 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1456 "Duplicate calls to OnSVGDocumentLoaded?");
1458 CancelAllListeners();
1460 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1461 mSVGDocumentWrapper->FlushLayout();
1463 // This is the earliest point that we can get accurate use counter data
1464 // for a valid SVG document. Without the FlushLayout call, we would miss
1465 // any CSS property usage that comes from SVG presentation attributes.
1466 mSVGDocumentWrapper->GetDocument()->ReportDocumentUseCounters();
1468 mIsFullyLoaded = true;
1469 mHaveAnimations = mSVGDocumentWrapper->IsAnimated();
1471 // Start listening to our image for rendering updates.
1472 mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this);
1474 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1475 // stick around long enough to complete our work.
1476 RefPtr<VectorImage> kungFuDeathGrip(this);
1478 // Tell *our* observers that we're done loading.
1479 if (mProgressTracker) {
1480 Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY |
1481 FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE;
1483 if (mHaveAnimations) {
1484 progress |= FLAG_IS_ANIMATED;
1487 // Merge in any saved progress from OnImageDataComplete.
1488 if (mLoadProgress) {
1489 progress |= *mLoadProgress;
1490 mLoadProgress = Nothing();
1493 mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect());
1496 EvaluateAnimation();
1499 void VectorImage::OnSVGDocumentError() {
1500 CancelAllListeners();
1502 mError = true;
1504 // We won't enter OnSVGDocumentLoaded, so report use counters now for this
1505 // invalid document.
1506 ReportDocumentUseCounters();
1508 if (mProgressTracker) {
1509 // Notify observers about the error and unblock page load.
1510 Progress progress = FLAG_HAS_ERROR;
1512 // Merge in any saved progress from OnImageDataComplete.
1513 if (mLoadProgress) {
1514 progress |= *mLoadProgress;
1515 mLoadProgress = Nothing();
1518 mProgressTracker->SyncNotifyProgress(progress);
1522 //------------------------------------------------------------------------------
1523 // nsIStreamListener method
1525 //******************************************************************************
1526 NS_IMETHODIMP
1527 VectorImage::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
1528 uint64_t aSourceOffset, uint32_t aCount) {
1529 if (mError) {
1530 return NS_ERROR_FAILURE;
1533 return mSVGDocumentWrapper->OnDataAvailable(aRequest, aInStr, aSourceOffset,
1534 aCount);
1537 // --------------------------
1538 // Invalidation helper method
1540 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1541 if (mHasPendingInvalidation) {
1542 return;
1545 mHasPendingInvalidation = true;
1547 // Animated images can wait for the refresh tick.
1548 if (mHaveAnimations) {
1549 return;
1552 // Non-animated images won't get the refresh tick, so we should just send an
1553 // invalidation outside the current execution context. We need to defer
1554 // because the layout tree is in the middle of invalidation, and the tree
1555 // state needs to be consistent. Specifically only some of the frames have
1556 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1557 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1558 // get cleared when we repaint the SVG into a surface by
1559 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1560 nsCOMPtr<nsIEventTarget> eventTarget = do_GetMainThread();
1562 RefPtr<VectorImage> self(this);
1563 nsCOMPtr<nsIRunnable> ev(NS_NewRunnableFunction(
1564 "VectorImage::SendInvalidationNotifications",
1565 [=]() -> void { self->SendInvalidationNotifications(); }));
1566 eventTarget->Dispatch(CreateRenderBlockingRunnable(ev.forget()),
1567 NS_DISPATCH_NORMAL);
1570 void VectorImage::PropagateUseCounters(Document* aReferencingDocument) {
1571 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1572 doc->PropagateImageUseCounters(aReferencingDocument);
1576 nsIntSize VectorImage::OptimalImageSizeForDest(const gfxSize& aDest,
1577 uint32_t aWhichFrame,
1578 SamplingFilter aSamplingFilter,
1579 uint32_t aFlags) {
1580 MOZ_ASSERT(aDest.width >= 0 || ceil(aDest.width) <= INT32_MAX ||
1581 aDest.height >= 0 || ceil(aDest.height) <= INT32_MAX,
1582 "Unexpected destination size");
1584 // We can rescale SVGs freely, so just return the provided destination size.
1585 return nsIntSize::Ceil(aDest.width, aDest.height);
1588 already_AddRefed<imgIContainer> VectorImage::Unwrap() {
1589 nsCOMPtr<imgIContainer> self(this);
1590 return self.forget();
1593 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1594 const MediaFeatureChange& aChange) {
1595 if (!mSVGDocumentWrapper) {
1596 return;
1599 // Don't bother if the document hasn't loaded yet.
1600 if (!mIsFullyLoaded) {
1601 return;
1604 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1605 if (RefPtr<nsPresContext> presContext = doc->GetPresContext()) {
1606 presContext->MediaFeatureValuesChanged(
1607 aChange, MediaFeatureChangePropagation::All);
1608 // Media feature value changes don't happen in the middle of layout,
1609 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1610 // to invalidate asynchronously.
1611 if (presContext->FlushPendingMediaFeatureValuesChanged()) {
1612 // NOTE(emilio): SendInvalidationNotifications flushes layout via
1613 // VectorImage::CreateSurface -> FlushImageTransformInvalidation.
1614 SendInvalidationNotifications();
1620 nsresult VectorImage::GetHotspotX(int32_t* aX) {
1621 return Image::GetHotspotX(aX);
1624 nsresult VectorImage::GetHotspotY(int32_t* aY) {
1625 return Image::GetHotspotY(aY);
1628 void VectorImage::ReportDocumentUseCounters() {
1629 if (!mSVGDocumentWrapper) {
1630 return;
1633 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1634 doc->ReportDocumentUseCounters();
1638 } // namespace image
1639 } // namespace mozilla