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"
10 #include "gfxContext.h"
11 #include "gfxDrawable.h"
12 #include "gfxPlatform.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"
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"
53 using namespace dom::SVGPreserveAspectRatio_Binding
;
55 using namespace layers
;
59 // Helper-class: SVGRootRenderingObserver
60 class SVGRootRenderingObserver final
: public SVGRenderingObserver
{
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");
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; }
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.
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.
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;
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
{
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);
139 ~SVGParseCompleteListener() {
141 // The document must have been destroyed before we got our event.
142 // Otherwise this can't happen, since documents hold strong references to
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();
160 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
162 mDocument
->RemoveObserver(this);
168 RefPtr
<SVGDocument
> mDocument
;
169 VectorImage
* const mImage
; // Raw pointer to owner.
172 NS_IMPL_ISUPPORTS(SVGParseCompleteListener
, nsIDocumentObserver
)
174 class SVGLoadEventListener final
: public nsIDOMEventListener
{
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,
188 ~SVGLoadEventListener() {
190 // The document must have been destroyed before we got our event.
191 // Otherwise this can't happen, since documents hold strong references to
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);
206 nsAutoString eventType
;
207 aEvent
->GetType(eventType
);
208 MOZ_ASSERT(eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad"),
209 "Received unexpected event");
212 mImage
->OnSVGDocumentLoaded();
218 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
220 mDocument
->RemoveEventListener(u
"MozSVGAsImageDocumentLoad"_ns
, this,
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
),
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()) {
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
298 // Implement VectorImage's nsISupports-inherited methods
299 NS_IMPL_ISUPPORTS(VectorImage
, imgIContainer
, nsIStreamListener
,
302 //------------------------------------------------------------------------------
303 // Constructor / Destructor
305 VectorImage::VectorImage(nsIURI
* aURI
/* = nullptr */)
306 : ImageResource(aURI
), // invoke superclass's constructor
308 mIsInitialized(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.
338 SurfaceCache::LockImage(ImageKey(this));
341 mIsInitialized
= true;
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();
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.
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
);
388 // Record our progress so far; we'll actually send the notifications in
389 // OnSVGDocumentLoaded or OnSVGDocumentError.
390 mLoadProgress
= Some(loadProgress
);
396 nsresult
VectorImage::OnImageDataAvailable(nsIRequest
* aRequest
,
397 nsIInputStream
* aInStr
,
398 uint64_t aSourceOffset
,
400 return OnDataAvailable(aRequest
, aInStr
, aSourceOffset
, aCount
);
403 nsresult
VectorImage::StartAnimation() {
405 return NS_ERROR_FAILURE
;
408 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
410 mSVGDocumentWrapper
->StartAnimation();
414 nsresult
VectorImage::StopAnimation() {
417 rv
= NS_ERROR_FAILURE
;
419 MOZ_ASSERT(mIsFullyLoaded
&& mHaveAnimations
,
420 "Should not have been animating!");
422 mSVGDocumentWrapper
->StopAnimation();
429 bool VectorImage::ShouldAnimate() {
430 return ImageResource::ShouldAnimate() && mIsFullyLoaded
&& mHaveAnimations
;
434 VectorImage::SetAnimationStartTime(const TimeStamp
& aTime
) {
435 // We don't care about animation start time.
438 //------------------------------------------------------------------------------
439 // imgIContainer methods
441 //******************************************************************************
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.
449 return NS_ERROR_FAILURE
;
452 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
454 "Should have a root SVG elem, since we finished "
455 "loading without errors");
456 LengthPercentage rootElemWidth
= rootElem
->GetIntrinsicWidth();
458 if (!rootElemWidth
.IsLength()) {
460 return NS_ERROR_FAILURE
;
463 *aWidth
= SVGUtils::ClampToInt(rootElemWidth
.AsLength().ToCSSPixels());
467 //******************************************************************************
468 nsresult
VectorImage::GetNativeSizes(nsTArray
<IntSize
>& aNativeSizes
) {
469 return NS_ERROR_NOT_IMPLEMENTED
;
472 //******************************************************************************
473 size_t VectorImage::GetNativeSizesLength() { return 0; }
475 //******************************************************************************
477 VectorImage::RequestRefresh(const TimeStamp
& aTime
) {
478 if (HadRecentRefresh(aTime
)) {
482 Document
* doc
= mSVGDocumentWrapper
->GetDocument();
484 // We are racing between shutdown and a refresh.
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
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
) {
533 //******************************************************************************
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.
541 return NS_ERROR_FAILURE
;
544 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
546 "Should have a root SVG elem, since we finished "
547 "loading without errors");
548 LengthPercentage rootElemHeight
= rootElem
->GetIntrinsicHeight();
550 if (!rootElemHeight
.IsLength()) {
552 return NS_ERROR_FAILURE
;
555 *aHeight
= SVGUtils::ClampToInt(rootElemHeight
.AsLength().ToCSSPixels());
559 //******************************************************************************
561 VectorImage::GetIntrinsicSize(nsSize
* aSize
) {
562 if (mError
|| !mIsFullyLoaded
) {
563 return NS_ERROR_FAILURE
;
566 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
568 return NS_ERROR_FAILURE
;
571 *aSize
= nsSize(-1, -1);
572 IntrinsicSize rfSize
= rootFrame
->GetIntrinsicSize();
574 aSize
->width
= *rfSize
.width
;
577 aSize
->height
= *rfSize
.height
;
582 //******************************************************************************
583 Maybe
<AspectRatio
> VectorImage::GetIntrinsicRatio() {
584 if (mError
|| !mIsFullyLoaded
) {
588 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
593 return Some(rootFrame
->GetIntrinsicRatio());
596 NS_IMETHODIMP_(Orientation
)
597 VectorImage::GetOrientation() { return Orientation(); }
599 NS_IMETHODIMP_(Resolution
)
600 VectorImage::GetResolution() { return {}; }
602 //******************************************************************************
604 VectorImage::GetType(uint16_t* aType
) {
605 NS_ENSURE_ARG_POINTER(aType
);
607 *aType
= imgIContainer::TYPE_VECTOR
;
611 //******************************************************************************
613 VectorImage::GetProviderId(uint32_t* aId
) {
614 NS_ENSURE_ARG_POINTER(aId
);
616 *aId
= ImageResource::GetImageProviderId();
620 //******************************************************************************
622 VectorImage::GetAnimated(bool* aAnimated
) {
623 if (mError
|| !mIsFullyLoaded
) {
624 return NS_ERROR_FAILURE
;
627 *aAnimated
= mSVGDocumentWrapper
->IsAnimated();
631 //******************************************************************************
632 int32_t VectorImage::GetFirstFrameDelay() {
637 if (!mSVGDocumentWrapper
->IsAnimated()) {
641 // We don't really have a frame delay, so just pretend that we constantly
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
) {
658 // Look up height & width
659 // ----------------------
660 SVGSVGElement
* svgElem
= mSVGDocumentWrapper
->GetRootSVGElem();
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.
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
,
681 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
);
683 AutoProfilerImagePaintMarker
PROFILER_RAII(this);
685 NotifyDrawingObservers();
688 if (aSize
.IsEmpty() || aWhichFrame
> FRAME_MAX_VALUE
|| mError
||
693 uint32_t whichFrame
= mHaveAnimations
? aWhichFrame
: FRAME_FIRST
;
695 auto [sourceSurface
, decodeSize
] =
696 LookupCachedSurface(aSize
, SVGImageContext(), aFlags
);
698 return sourceSurface
.forget();
701 if (mSVGDocumentWrapper
->IsDrawing()) {
702 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
706 float animTime
= (whichFrame
== FRAME_FIRST
)
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
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
);
728 MOZ_ASSERT(!didCache
);
732 SendFrameComplete(didCache
, params
.flags
);
733 return surface
.forget();
737 VectorImage::IsImageContainerAvailable(WindowRenderer
* aRenderer
,
739 if (mError
|| !mIsFullyLoaded
||
740 aRenderer
->GetBackendType() != LayersBackend::LAYERS_WR
) {
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.
753 //******************************************************************************
754 NS_IMETHODIMP_(ImgDrawResult
)
755 VectorImage::GetImageProvider(WindowRenderer
* aRenderer
,
756 const gfx::IntSize
& aSize
,
757 const SVGImageContext
& aSVGContext
,
758 const Maybe
<ImageIntRegion
>& aRegion
,
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
;
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);
787 NotifyDrawingObservers();
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
);
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);
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
);
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
;
844 provider
= MakeRefPtr
<BlobSurfaceProvider
>(ImageKey(this), surfaceKey
,
845 mSVGDocumentWrapper
, aFlags
);
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
862 return ImgDrawResult::NOT_SUPPORTED
;
865 // We aren't using blobs, so we need to rasterize.
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
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
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.
900 return ImgDrawResult::TEMPORARY_ERROR
;
904 MakeRefPtr
<SimpleSurfaceProvider
>(ImageKey(this), surfaceKey
, frame
);
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
,
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
) {
936 // The SVGImageContext must take account of the preserveAspectRatio
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
,
963 if (aWhichFrame
> FRAME_MAX_VALUE
) {
964 return ImgDrawResult::BAD_ARGS
;
968 return ImgDrawResult::BAD_ARGS
;
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
)
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
) ||
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);
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
,
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.
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
) {
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.
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
)) {
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();
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.
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));
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.
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());
1201 NotNull
<RefPtr
<VectorImage
>> image
= WrapNotNull(this);
1202 NS_DispatchToMainThread(CreateRenderBlockingRunnable(NS_NewRunnableFunction(
1203 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1204 RefPtr
<ProgressTracker
> tracker
= image
->GetProgressTracker();
1206 tracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1207 GetMaxSizedIntRect());
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);
1235 NotifyDrawingObservers();
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));
1250 VectorImage::StartDecoding(uint32_t aFlags
, uint32_t aWhichFrame
) {
1251 // Nothing to do for SVG images
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.
1271 return imgIContainer::DECODE_REQUEST_FAILED
;
1274 if (!mIsFullyLoaded
) {
1275 return imgIContainer::DECODE_REQUESTED
;
1278 return imgIContainer::DECODE_SURFACE_AVAILABLE
;
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
1290 //******************************************************************************
1293 VectorImage::LockImage() {
1294 MOZ_ASSERT(NS_IsMainThread());
1297 return NS_ERROR_FAILURE
;
1302 if (mLockCount
== 1) {
1303 // Lock this image's surfaces in the SurfaceCache.
1304 SurfaceCache::LockImage(ImageKey(this));
1310 //******************************************************************************
1313 VectorImage::UnlockImage() {
1314 MOZ_ASSERT(NS_IsMainThread());
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
;
1327 if (mLockCount
== 0) {
1328 // Unlock this image's surfaces in the SurfaceCache.
1329 SurfaceCache::UnlockImage(ImageKey(this));
1335 //******************************************************************************
1338 VectorImage::RequestDiscard() {
1339 MOZ_ASSERT(NS_IsMainThread());
1341 if (mDiscardable
&& mLockCount
== 0) {
1342 SurfaceCache::RemoveImage(ImageKey(this));
1343 mProgressTracker
->OnDiscard();
1349 void VectorImage::OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) {
1350 MOZ_ASSERT(mProgressTracker
);
1352 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1354 &ProgressTracker::OnDiscard
));
1357 //******************************************************************************
1359 VectorImage::ResetAnimation() {
1361 return NS_ERROR_FAILURE
;
1364 if (!mIsFullyLoaded
|| !mHaveAnimations
) {
1365 return NS_OK
; // There are no animations to be reset.
1368 mSVGDocumentWrapper
->ResetAnimation();
1373 NS_IMETHODIMP_(float)
1374 VectorImage::GetFrameIndex(uint32_t aWhichFrame
) {
1375 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
, "Invalid argument");
1376 return aWhichFrame
== FRAME_FIRST
1378 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1381 //------------------------------------------------------------------------------
1382 // nsIRequestObserver methods
1384 //******************************************************************************
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;
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();
1416 //******************************************************************************
1418 VectorImage::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
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
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();
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 //******************************************************************************
1527 VectorImage::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
1528 uint64_t aSourceOffset
, uint32_t aCount
) {
1530 return NS_ERROR_FAILURE
;
1533 return mSVGDocumentWrapper
->OnDataAvailable(aRequest
, aInStr
, aSourceOffset
,
1537 // --------------------------
1538 // Invalidation helper method
1540 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1541 if (mHasPendingInvalidation
) {
1545 mHasPendingInvalidation
= true;
1547 // Animated images can wait for the refresh tick.
1548 if (mHaveAnimations
) {
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
,
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
) {
1599 // Don't bother if the document hasn't loaded yet.
1600 if (!mIsFullyLoaded
) {
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
) {
1633 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1634 doc
->ReportDocumentUseCounters();
1638 } // namespace image
1639 } // namespace mozilla