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/PendingAnimationTracker.h"
22 #include "mozilla/PresShell.h"
23 #include "mozilla/ProfilerLabels.h"
24 #include "mozilla/RefPtr.h"
25 #include "mozilla/StaticPrefs_image.h"
26 #include "mozilla/SVGObserverUtils.h" // for SVGRenderingObserver
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 : SVGRenderingObserver(),
67 mDocWrapper(aDocWrapper
),
68 mVectorImage(aVectorImage
),
69 mHonoringInvalidations(true) {
70 MOZ_ASSERT(mDocWrapper
, "Need a non-null SVG document wrapper");
71 MOZ_ASSERT(mVectorImage
, "Need a non-null VectorImage");
74 Element
* elem
= GetReferencedElementWithoutObserving();
75 MOZ_ASSERT(elem
, "no root SVG node for us to observe");
77 SVGObserverUtils::AddRenderingObserver(elem
, this);
78 mInObserverSet
= true;
81 void ResumeHonoringInvalidations() { mHonoringInvalidations
= true; }
84 virtual ~SVGRootRenderingObserver() {
85 // This needs to call our GetReferencedElementWithoutObserving override,
86 // so must be called here rather than in our base class's dtor.
90 Element
* GetReferencedElementWithoutObserving() final
{
91 return mDocWrapper
->GetRootSVGElem();
94 virtual void OnRenderingChange() override
{
95 Element
* elem
= GetReferencedElementWithoutObserving();
96 MOZ_ASSERT(elem
, "missing root SVG node");
98 if (mHonoringInvalidations
&& !mDocWrapper
->ShouldIgnoreInvalidation()) {
99 nsIFrame
* frame
= elem
->GetPrimaryFrame();
100 if (!frame
|| frame
->PresShell()->IsDestroying()) {
101 // We're being destroyed. Bail out.
105 // Ignore further invalidations until we draw.
106 mHonoringInvalidations
= false;
108 mVectorImage
->InvalidateObserversOnNextRefreshDriverTick();
111 // Our caller might've removed us from rendering-observer list.
112 // Add ourselves back!
113 if (!mInObserverSet
) {
114 SVGObserverUtils::AddRenderingObserver(elem
, this);
115 mInObserverSet
= true;
120 const RefPtr
<SVGDocumentWrapper
> mDocWrapper
;
121 VectorImage
* const mVectorImage
; // Raw pointer because it owns me.
122 bool mHonoringInvalidations
;
125 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver
, nsIMutationObserver
)
127 class SVGParseCompleteListener final
: public nsStubDocumentObserver
{
131 SVGParseCompleteListener(SVGDocument
* aDocument
, VectorImage
* aImage
)
132 : mDocument(aDocument
), mImage(aImage
) {
133 MOZ_ASSERT(mDocument
, "Need an SVG document");
134 MOZ_ASSERT(mImage
, "Need an image");
136 mDocument
->AddObserver(this);
140 ~SVGParseCompleteListener() {
142 // The document must have been destroyed before we got our event.
143 // Otherwise this can't happen, since documents hold strong references to
150 void EndLoad(Document
* aDocument
) override
{
151 MOZ_ASSERT(aDocument
== mDocument
, "Got EndLoad for wrong document?");
153 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
154 // we stick around long enough to complete our work.
155 RefPtr
<SVGParseCompleteListener
> kungFuDeathGrip(this);
157 mImage
->OnSVGDocumentParsed();
161 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
163 mDocument
->RemoveObserver(this);
169 RefPtr
<SVGDocument
> mDocument
;
170 VectorImage
* const mImage
; // Raw pointer to owner.
173 NS_IMPL_ISUPPORTS(SVGParseCompleteListener
, nsIDocumentObserver
)
175 class SVGLoadEventListener final
: public nsIDOMEventListener
{
179 SVGLoadEventListener(Document
* aDocument
, VectorImage
* aImage
)
180 : mDocument(aDocument
), mImage(aImage
) {
181 MOZ_ASSERT(mDocument
, "Need an SVG document");
182 MOZ_ASSERT(mImage
, "Need an image");
184 mDocument
->AddEventListener(u
"MozSVGAsImageDocumentLoad"_ns
, this, true,
189 ~SVGLoadEventListener() {
191 // The document must have been destroyed before we got our event.
192 // Otherwise this can't happen, since documents hold strong references to
199 NS_IMETHOD
HandleEvent(Event
* aEvent
) override
{
200 MOZ_ASSERT(mDocument
, "Need an SVG document. Received multiple events?");
202 // OnSVGDocumentLoaded will release our owner's reference
203 // to us, so ensure we stick around long enough to complete our work.
204 RefPtr
<SVGLoadEventListener
> kungFuDeathGrip(this);
207 nsAutoString eventType
;
208 aEvent
->GetType(eventType
);
209 MOZ_ASSERT(eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad"),
210 "Received unexpected event");
213 mImage
->OnSVGDocumentLoaded();
219 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
221 mDocument
->RemoveEventListener(u
"MozSVGAsImageDocumentLoad"_ns
, this,
228 nsCOMPtr
<Document
> mDocument
;
229 VectorImage
* const mImage
; // Raw pointer to owner.
232 NS_IMPL_ISUPPORTS(SVGLoadEventListener
, nsIDOMEventListener
)
234 SVGDrawingCallback::SVGDrawingCallback(SVGDocumentWrapper
* aSVGDocumentWrapper
,
235 const IntSize
& aViewportSize
,
236 const IntSize
& aSize
,
237 uint32_t aImageFlags
)
238 : mSVGDocumentWrapper(aSVGDocumentWrapper
),
239 mViewportSize(aViewportSize
),
241 mImageFlags(aImageFlags
) {}
243 SVGDrawingCallback::~SVGDrawingCallback() = default;
245 // Based loosely on SVGIntegrationUtils' PaintFrameCallback::operator()
246 bool SVGDrawingCallback::operator()(gfxContext
* aContext
,
247 const gfxRect
& aFillRect
,
248 const SamplingFilter aSamplingFilter
,
249 const gfxMatrix
& aTransform
) {
250 MOZ_ASSERT(mSVGDocumentWrapper
, "need an SVGDocumentWrapper");
252 // Get (& sanity-check) the helper-doc's presShell
253 RefPtr
<PresShell
> presShell
= mSVGDocumentWrapper
->GetPresShell();
254 MOZ_ASSERT(presShell
, "GetPresShell returned null for an SVG image?");
256 Document
* doc
= presShell
->GetDocument();
257 [[maybe_unused
]] nsIURI
* uri
= doc
? doc
->GetDocumentURI() : nullptr;
258 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
259 "SVG Image drawing", GRAPHICS
,
260 nsPrintfCString("%dx%d %s", mSize
.width
, mSize
.height
,
261 uri
? uri
->GetSpecOrDefault().get() : "N/A"));
263 gfxContextAutoSaveRestore
contextRestorer(aContext
);
265 // Clip to aFillRect so that we don't paint outside.
266 aContext
->Clip(aFillRect
);
268 gfxMatrix matrix
= aTransform
;
269 if (!matrix
.Invert()) {
272 aContext
->SetMatrixDouble(
273 aContext
->CurrentMatrixDouble().PreMultiply(matrix
).PreScale(
274 double(mSize
.width
) / mViewportSize
.width
,
275 double(mSize
.height
) / mViewportSize
.height
));
277 nsPresContext
* presContext
= presShell
->GetPresContext();
278 MOZ_ASSERT(presContext
, "pres shell w/out pres context");
280 nsRect
svgRect(0, 0, presContext
->DevPixelsToAppUnits(mViewportSize
.width
),
281 presContext
->DevPixelsToAppUnits(mViewportSize
.height
));
283 RenderDocumentFlags renderDocFlags
=
284 RenderDocumentFlags::IgnoreViewportScrolling
;
285 if (!(mImageFlags
& imgIContainer::FLAG_SYNC_DECODE
)) {
286 renderDocFlags
|= RenderDocumentFlags::AsyncDecodeImages
;
288 if (mImageFlags
& imgIContainer::FLAG_HIGH_QUALITY_SCALING
) {
289 renderDocFlags
|= RenderDocumentFlags::UseHighQualityScaling
;
292 presShell
->RenderDocument(svgRect
, renderDocFlags
,
293 NS_RGBA(0, 0, 0, 0), // transparent
299 // Implement VectorImage's nsISupports-inherited methods
300 NS_IMPL_ISUPPORTS(VectorImage
, imgIContainer
, nsIStreamListener
,
303 //------------------------------------------------------------------------------
304 // Constructor / Destructor
306 VectorImage::VectorImage(nsIURI
* aURI
/* = nullptr */)
307 : ImageResource(aURI
), // invoke superclass's constructor
309 mIsInitialized(false),
311 mIsFullyLoaded(false),
312 mHaveAnimations(false),
313 mHasPendingInvalidation(false) {}
315 VectorImage::~VectorImage() {
316 ReportDocumentUseCounters();
317 CancelAllListeners();
318 SurfaceCache::RemoveImage(ImageKey(this));
321 //------------------------------------------------------------------------------
322 // Methods inherited from Image.h
324 nsresult
VectorImage::Init(const char* aMimeType
, uint32_t aFlags
) {
325 // We don't support re-initialization
326 if (mIsInitialized
) {
327 return NS_ERROR_ILLEGAL_VALUE
;
330 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
&& !mError
,
331 "Flags unexpectedly set before initialization");
332 MOZ_ASSERT(!strcmp(aMimeType
, IMAGE_SVG_XML
), "Unexpected mimetype");
334 mDiscardable
= !!(aFlags
& INIT_FLAG_DISCARDABLE
);
336 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
339 SurfaceCache::LockImage(ImageKey(this));
342 mIsInitialized
= true;
346 size_t VectorImage::SizeOfSourceWithComputedFallback(
347 SizeOfState
& aState
) const {
348 if (!mSVGDocumentWrapper
) {
349 return 0; // No document, so no memory used for the document.
352 SVGDocument
* doc
= mSVGDocumentWrapper
->GetDocument();
354 return 0; // No document, so no memory used for the document.
357 nsWindowSizes
windowSizes(aState
);
358 doc
->DocAddSizeOfIncludingThis(windowSizes
);
360 if (windowSizes
.getTotalSize() == 0) {
361 // MallocSizeOf fails on this platform. Because we also use this method for
362 // determining the size of cache entries, we need to return something
363 // reasonable here. Unfortunately, there's no way to estimate the document's
364 // size accurately, so we just use a constant value of 100KB, which will
365 // generally underestimate the true size.
369 return windowSizes
.getTotalSize();
372 nsresult
VectorImage::OnImageDataComplete(nsIRequest
* aRequest
,
373 nsresult aStatus
, bool aLastPart
) {
374 // Call our internal OnStopRequest method, which only talks to our embedded
375 // SVG document. This won't have any effect on our ProgressTracker.
376 nsresult finalStatus
= OnStopRequest(aRequest
, aStatus
);
378 // Give precedence to Necko failure codes.
379 if (NS_FAILED(aStatus
)) {
380 finalStatus
= aStatus
;
383 Progress loadProgress
= LoadCompleteProgress(aLastPart
, mError
, finalStatus
);
385 if (mIsFullyLoaded
|| mError
) {
386 // Our document is loaded, so we're ready to notify now.
387 mProgressTracker
->SyncNotifyProgress(loadProgress
);
389 // Record our progress so far; we'll actually send the notifications in
390 // OnSVGDocumentLoaded or OnSVGDocumentError.
391 mLoadProgress
= Some(loadProgress
);
397 nsresult
VectorImage::OnImageDataAvailable(nsIRequest
* aRequest
,
398 nsIInputStream
* aInStr
,
399 uint64_t aSourceOffset
,
401 return OnDataAvailable(aRequest
, aInStr
, aSourceOffset
, aCount
);
404 nsresult
VectorImage::StartAnimation() {
406 return NS_ERROR_FAILURE
;
409 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
411 mSVGDocumentWrapper
->StartAnimation();
415 nsresult
VectorImage::StopAnimation() {
418 rv
= NS_ERROR_FAILURE
;
420 MOZ_ASSERT(mIsFullyLoaded
&& mHaveAnimations
,
421 "Should not have been animating!");
423 mSVGDocumentWrapper
->StopAnimation();
430 bool VectorImage::ShouldAnimate() {
431 return ImageResource::ShouldAnimate() && mIsFullyLoaded
&& mHaveAnimations
;
435 VectorImage::SetAnimationStartTime(const TimeStamp
& aTime
) {
436 // We don't care about animation start time.
439 //------------------------------------------------------------------------------
440 // imgIContainer methods
442 //******************************************************************************
444 VectorImage::GetWidth(int32_t* aWidth
) {
445 if (mError
|| !mIsFullyLoaded
) {
446 // XXXdholbert Technically we should leave outparam untouched when we
447 // fail. But since many callers don't check for failure, we set it to 0 on
448 // failure, for sane/predictable results.
450 return NS_ERROR_FAILURE
;
453 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
455 "Should have a root SVG elem, since we finished "
456 "loading without errors");
457 int32_t rootElemWidth
= rootElem
->GetIntrinsicWidth();
458 if (rootElemWidth
< 0) {
460 return NS_ERROR_FAILURE
;
462 *aWidth
= rootElemWidth
;
466 //******************************************************************************
467 nsresult
VectorImage::GetNativeSizes(nsTArray
<IntSize
>& aNativeSizes
) {
468 return NS_ERROR_NOT_IMPLEMENTED
;
471 //******************************************************************************
472 size_t VectorImage::GetNativeSizesLength() { return 0; }
474 //******************************************************************************
476 VectorImage::RequestRefresh(const TimeStamp
& aTime
) {
477 if (HadRecentRefresh(aTime
)) {
481 Document
* doc
= mSVGDocumentWrapper
->GetDocument();
483 // We are racing between shutdown and a refresh.
487 PendingAnimationTracker
* tracker
= doc
->GetPendingAnimationTracker();
488 if (tracker
&& ShouldAnimate()) {
489 tracker
->TriggerPendingAnimationsOnNextTick(aTime
);
494 mSVGDocumentWrapper
->TickRefreshDriver();
496 if (mHasPendingInvalidation
) {
497 SendInvalidationNotifications();
501 void VectorImage::SendInvalidationNotifications() {
502 // Animated images don't send out invalidation notifications as soon as
503 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
504 // records that there are pending invalidations and then returns immediately.
505 // The notifications are actually sent from RequestRefresh(). We send these
506 // notifications there to ensure that there is actually a document observing
507 // us. Otherwise, the notifications are just wasted effort.
509 // Non-animated images post an event to call this method from
510 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
511 // called for them. Ordinarily this isn't needed, since we send out
512 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
513 // SVG document may not be 100% ready to render at that time. In those cases
514 // we would miss the subsequent invalidations if we didn't send out the
515 // notifications indirectly in |InvalidateObservers...|.
517 mHasPendingInvalidation
= false;
519 if (SurfaceCache::InvalidateImage(ImageKey(this))) {
520 // If we still have recordings in the cache, make sure we handle future
522 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
523 mRenderingObserver
->ResumeHonoringInvalidations();
526 if (mProgressTracker
) {
527 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
528 GetMaxSizedIntRect());
532 NS_IMETHODIMP_(IntRect
)
533 VectorImage::GetImageSpaceInvalidationRect(const IntRect
& aRect
) {
537 //******************************************************************************
539 VectorImage::GetHeight(int32_t* aHeight
) {
540 if (mError
|| !mIsFullyLoaded
) {
541 // XXXdholbert Technically we should leave outparam untouched when we
542 // fail. But since many callers don't check for failure, we set it to 0 on
543 // failure, for sane/predictable results.
545 return NS_ERROR_FAILURE
;
548 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
550 "Should have a root SVG elem, since we finished "
551 "loading without errors");
552 int32_t rootElemHeight
= rootElem
->GetIntrinsicHeight();
553 if (rootElemHeight
< 0) {
555 return NS_ERROR_FAILURE
;
557 *aHeight
= rootElemHeight
;
561 //******************************************************************************
563 VectorImage::GetIntrinsicSize(nsSize
* aSize
) {
564 if (mError
|| !mIsFullyLoaded
) {
565 return NS_ERROR_FAILURE
;
568 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
570 return NS_ERROR_FAILURE
;
573 *aSize
= nsSize(-1, -1);
574 IntrinsicSize rfSize
= rootFrame
->GetIntrinsicSize();
576 aSize
->width
= *rfSize
.width
;
579 aSize
->height
= *rfSize
.height
;
584 //******************************************************************************
585 Maybe
<AspectRatio
> VectorImage::GetIntrinsicRatio() {
586 if (mError
|| !mIsFullyLoaded
) {
590 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
595 return Some(rootFrame
->GetIntrinsicRatio());
598 NS_IMETHODIMP_(Orientation
)
599 VectorImage::GetOrientation() { return Orientation(); }
601 NS_IMETHODIMP_(Resolution
)
602 VectorImage::GetResolution() { return {}; }
604 //******************************************************************************
606 VectorImage::GetType(uint16_t* aType
) {
607 NS_ENSURE_ARG_POINTER(aType
);
609 *aType
= imgIContainer::TYPE_VECTOR
;
613 //******************************************************************************
615 VectorImage::GetProviderId(uint32_t* aId
) {
616 NS_ENSURE_ARG_POINTER(aId
);
618 *aId
= ImageResource::GetImageProviderId();
622 //******************************************************************************
624 VectorImage::GetAnimated(bool* aAnimated
) {
625 if (mError
|| !mIsFullyLoaded
) {
626 return NS_ERROR_FAILURE
;
629 *aAnimated
= mSVGDocumentWrapper
->IsAnimated();
633 //******************************************************************************
634 int32_t VectorImage::GetFirstFrameDelay() {
639 if (!mSVGDocumentWrapper
->IsAnimated()) {
643 // We don't really have a frame delay, so just pretend that we constantly
649 VectorImage::WillDrawOpaqueNow() {
650 return false; // In general, SVG content is not opaque.
653 //******************************************************************************
654 NS_IMETHODIMP_(already_AddRefed
<SourceSurface
>)
655 VectorImage::GetFrame(uint32_t aWhichFrame
, uint32_t aFlags
) {
660 // Look up height & width
661 // ----------------------
662 SVGSVGElement
* svgElem
= mSVGDocumentWrapper
->GetRootSVGElem();
664 "Should have a root SVG elem, since we finished "
665 "loading without errors");
666 nsIntSize
imageIntSize(svgElem
->GetIntrinsicWidth(),
667 svgElem
->GetIntrinsicHeight());
669 if (imageIntSize
.IsEmpty()) {
670 // We'll get here if our SVG doc has a percent-valued or negative width or
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 SurfaceKey surfaceKey
=
800 VectorSurfaceKey(aSize
, aRegion
, aSVGContext
, surfaceFlags
, playbackType
);
801 if ((aFlags
& FLAG_SYNC_DECODE
) || !(aFlags
& FLAG_HIGH_QUALITY_SCALING
)) {
802 result
= SurfaceCache::Lookup(ImageKey(this), surfaceKey
,
803 /* aMarkUsed = */ true);
805 result
= SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey
,
806 /* aMarkUsed = */ true);
809 // Unless we get a best match (exact or factor of 2 limited), then we want to
810 // generate a new recording/rerasterize, even if we have a substitute.
811 if (result
&& (result
.Type() == MatchType::EXACT
||
812 result
.Type() == MatchType::SUBSTITUTE_BECAUSE_BEST
)) {
813 result
.Surface().TakeProvider(aProvider
);
814 return ImgDrawResult::SUCCESS
;
817 // Ensure we store the surface with the correct key if we switched to factor
818 // of 2 sizing or we otherwise got clamped.
819 IntSize
rasterSize(aSize
);
820 if (!result
.SuggestedSize().IsEmpty()) {
821 rasterSize
= result
.SuggestedSize();
822 surfaceKey
= surfaceKey
.CloneWithSize(rasterSize
);
825 // We're about to rerasterize, which may mean that some of the previous
826 // surfaces we've rasterized aren't useful anymore. We can allow them to
827 // expire from the cache by unlocking them here, and then sending out an
828 // invalidation. If this image is locked, any surfaces that are still useful
829 // will become locked again when Draw touches them, and the remainder will
830 // eventually expire.
831 bool mayCache
= SurfaceCache::CanHold(rasterSize
);
833 SurfaceCache::UnlockEntries(ImageKey(this));
836 // Blob recorded vector images just create a provider responsible for
837 // generating blob keys and recording bindings. The recording won't happen
838 // until the caller requests the key explicitly.
839 RefPtr
<ISurfaceProvider
> provider
;
841 provider
= MakeRefPtr
<BlobSurfaceProvider
>(ImageKey(this), surfaceKey
,
842 mSVGDocumentWrapper
, aFlags
);
844 if (mSVGDocumentWrapper
->IsDrawing()) {
845 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
846 return ImgDrawResult::TEMPORARY_ERROR
;
849 if (!SurfaceCache::IsLegalSize(rasterSize
) ||
850 !Factory::AllowedSurfaceSize(rasterSize
)) {
851 // If either of these is true then the InitWithDrawable call below will
852 // fail, so fail early and use this opportunity to return NOT_SUPPORTED
853 // instead of TEMPORARY_ERROR as we do for any InitWithDrawable failure.
854 // This means that we will use fallback which has a path that will draw
855 // directly into the gfxContext without having to allocate a surface. It
856 // means we will have to use fallback and re-rasterize for everytime we
857 // have to draw this image, but it's better than not drawing anything at
859 return ImgDrawResult::NOT_SUPPORTED
;
862 // We aren't using blobs, so we need to rasterize.
864 mHaveAnimations
? mSVGDocumentWrapper
->GetCurrentTimeAsFloat() : 0.0f
;
866 // By using a null gfxContext, we ensure that we will always attempt to
867 // create a surface, even if we aren't capable of caching it (e.g. due to
868 // our flags, having an animation, etc). Otherwise CreateSurface will assume
869 // that the caller is capable of drawing directly to its own draw target if
871 SVGDrawingParameters
params(
872 nullptr, rasterSize
, aSize
, ImageRegion::Create(rasterSize
),
873 SamplingFilter::POINT
, aSVGContext
, animTime
, aFlags
, 1.0);
875 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
876 bool contextPaint
= aSVGContext
.GetContextPaint();
877 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, contextPaint
);
879 mSVGDocumentWrapper
->UpdateViewportBounds(params
.viewportSize
);
880 mSVGDocumentWrapper
->FlushImageTransformInvalidation();
882 // Given we have no context, the default backend is fine.
883 BackendType backend
=
884 gfxPlatform::GetPlatform()->GetDefaultContentBackend();
886 // Try to create an imgFrame, initializing the surface it contains by
887 // drawing our gfxDrawable into it. (We use FILTER_NEAREST since we never
889 auto frame
= MakeNotNull
<RefPtr
<imgFrame
>>();
890 nsresult rv
= frame
->InitWithDrawable(
891 svgDrawable
, params
.size
, SurfaceFormat::OS_RGBA
, SamplingFilter::POINT
,
892 params
.flags
, backend
);
894 // If we couldn't create the frame, it was probably because it would end
895 // up way too big. Generally it also wouldn't fit in the cache, but the
896 // prefs could be set such that the cache isn't the limiting factor.
898 return ImgDrawResult::TEMPORARY_ERROR
;
902 MakeRefPtr
<SimpleSurfaceProvider
>(ImageKey(this), surfaceKey
, frame
);
906 // Attempt to cache the frame.
907 if (SurfaceCache::Insert(WrapNotNull(provider
)) == InsertOutcome::SUCCESS
) {
908 if (rasterSize
!= aSize
) {
909 // We created a new surface that wasn't the size we requested, which
910 // means we entered factor-of-2 mode. We should purge any surfaces we
911 // no longer need rather than waiting for the cache to expire them.
912 SurfaceCache::PruneImage(ImageKey(this));
915 SendFrameComplete(/* aDidCache */ true, aFlags
);
919 MOZ_ASSERT(provider
);
920 provider
.forget(aProvider
);
921 return ImgDrawResult::SUCCESS
;
924 bool VectorImage::MaybeRestrictSVGContext(SVGImageContext
& aSVGContext
,
926 bool overridePAR
= (aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
);
928 bool haveContextPaint
= aSVGContext
.GetContextPaint();
929 bool blockContextPaint
=
930 haveContextPaint
&& !SVGContextPaint::IsAllowedForImageFromURI(mURI
);
932 if (overridePAR
|| blockContextPaint
) {
934 // The SVGImageContext must take account of the preserveAspectRatio
936 MOZ_ASSERT(!aSVGContext
.GetPreserveAspectRatio(),
937 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
938 "preserveAspectRatio override is supplied");
939 Maybe
<SVGPreserveAspectRatio
> aspectRatio
= Some(SVGPreserveAspectRatio(
940 SVG_PRESERVEASPECTRATIO_NONE
, SVG_MEETORSLICE_UNKNOWN
));
941 aSVGContext
.SetPreserveAspectRatio(aspectRatio
);
944 if (blockContextPaint
) {
945 // The SVGImageContext must not include context paint if the image is
946 // not allowed to use it:
947 aSVGContext
.ClearContextPaint();
951 return haveContextPaint
&& !blockContextPaint
;
954 //******************************************************************************
955 NS_IMETHODIMP_(ImgDrawResult
)
956 VectorImage::Draw(gfxContext
* aContext
, const nsIntSize
& aSize
,
957 const ImageRegion
& aRegion
, uint32_t aWhichFrame
,
958 SamplingFilter aSamplingFilter
,
959 const SVGImageContext
& aSVGContext
, uint32_t aFlags
,
961 if (aWhichFrame
> FRAME_MAX_VALUE
) {
962 return ImgDrawResult::BAD_ARGS
;
966 return ImgDrawResult::BAD_ARGS
;
970 return ImgDrawResult::BAD_IMAGE
;
973 if (!mIsFullyLoaded
) {
974 return ImgDrawResult::NOT_READY
;
977 if (mAnimationConsumers
== 0 && mHaveAnimations
) {
978 SendOnUnlockedDraw(aFlags
);
981 // We should bypass the cache when:
982 // - We are using a DrawTargetRecording because we prefer the drawing commands
983 // in general to the rasterized surface. This allows blob images to avoid
984 // rasterized SVGs with WebRender.
985 if (aContext
->GetDrawTarget()->GetBackendType() == BackendType::RECORDING
) {
986 aFlags
|= FLAG_BYPASS_SURFACE_CACHE
;
989 MOZ_ASSERT(!(aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
) ||
990 aSVGContext
.GetViewportSize(),
991 "Viewport size is required when using "
992 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
994 uint32_t whichFrame
= mHaveAnimations
? aWhichFrame
: FRAME_FIRST
;
996 float animTime
= (whichFrame
== FRAME_FIRST
)
998 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1000 SVGImageContext newSVGContext
= aSVGContext
;
1001 bool contextPaint
= MaybeRestrictSVGContext(newSVGContext
, aFlags
);
1003 SVGDrawingParameters
params(aContext
, aSize
, aSize
, aRegion
, aSamplingFilter
,
1004 newSVGContext
, animTime
, aFlags
, aOpacity
);
1006 // If we have an prerasterized version of this image that matches the
1007 // drawing parameters, use that.
1008 RefPtr
<SourceSurface
> sourceSurface
;
1009 std::tie(sourceSurface
, params
.size
) =
1010 LookupCachedSurface(aSize
, params
.svgContext
, aFlags
);
1011 if (sourceSurface
) {
1012 RefPtr
<gfxDrawable
> drawable
=
1013 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
1014 Show(drawable
, params
);
1015 return ImgDrawResult::SUCCESS
;
1018 // else, we need to paint the image:
1020 if (mSVGDocumentWrapper
->IsDrawing()) {
1021 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
1022 return ImgDrawResult::TEMPORARY_ERROR
;
1025 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, contextPaint
);
1027 bool didCache
; // Was the surface put into the cache?
1028 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
1029 sourceSurface
= CreateSurface(params
, svgDrawable
, didCache
);
1030 if (!sourceSurface
) {
1031 MOZ_ASSERT(!didCache
);
1032 Show(svgDrawable
, params
);
1033 return ImgDrawResult::SUCCESS
;
1036 RefPtr
<gfxDrawable
> drawable
=
1037 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
1038 Show(drawable
, params
);
1039 SendFrameComplete(didCache
, params
.flags
);
1040 return ImgDrawResult::SUCCESS
;
1043 already_AddRefed
<gfxDrawable
> VectorImage::CreateSVGDrawable(
1044 const SVGDrawingParameters
& aParams
) {
1045 RefPtr
<gfxDrawingCallback
> cb
= new SVGDrawingCallback(
1046 mSVGDocumentWrapper
, aParams
.viewportSize
, aParams
.size
, aParams
.flags
);
1048 RefPtr
<gfxDrawable
> svgDrawable
= new gfxCallbackDrawable(cb
, aParams
.size
);
1049 return svgDrawable
.forget();
1052 std::tuple
<RefPtr
<SourceSurface
>, IntSize
> VectorImage::LookupCachedSurface(
1053 const IntSize
& aSize
, const SVGImageContext
& aSVGContext
, uint32_t aFlags
) {
1054 // We can't use cached surfaces if we:
1055 // - Explicitly disallow it via FLAG_BYPASS_SURFACE_CACHE
1056 // - Want a blob recording which aren't supported by the cache.
1057 // - Have animations which aren't supported by the cache.
1058 if (aFlags
& (FLAG_BYPASS_SURFACE_CACHE
| FLAG_RECORD_BLOB
) ||
1060 return std::make_tuple(RefPtr
<SourceSurface
>(), aSize
);
1063 LookupResult
result(MatchType::NOT_FOUND
);
1064 SurfaceKey surfaceKey
= VectorSurfaceKey(aSize
, aSVGContext
);
1065 if ((aFlags
& FLAG_SYNC_DECODE
) || !(aFlags
& FLAG_HIGH_QUALITY_SCALING
)) {
1066 result
= SurfaceCache::Lookup(ImageKey(this), surfaceKey
,
1067 /* aMarkUsed = */ true);
1069 result
= SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey
,
1070 /* aMarkUsed = */ true);
1073 IntSize rasterSize
=
1074 result
.SuggestedSize().IsEmpty() ? aSize
: result
.SuggestedSize();
1075 MOZ_ASSERT(result
.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING
);
1076 if (!result
|| result
.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND
) {
1077 // No matching surface, or the OS freed the volatile buffer.
1078 return std::make_tuple(RefPtr
<SourceSurface
>(), rasterSize
);
1081 RefPtr
<SourceSurface
> sourceSurface
= result
.Surface()->GetSourceSurface();
1082 if (!sourceSurface
) {
1083 // Something went wrong. (Probably a GPU driver crash or device reset.)
1084 // Attempt to recover.
1085 RecoverFromLossOfSurfaces();
1086 return std::make_tuple(RefPtr
<SourceSurface
>(), rasterSize
);
1089 return std::make_tuple(std::move(sourceSurface
), rasterSize
);
1092 already_AddRefed
<SourceSurface
> VectorImage::CreateSurface(
1093 const SVGDrawingParameters
& aParams
, gfxDrawable
* aSVGDrawable
,
1095 MOZ_ASSERT(mSVGDocumentWrapper
->IsDrawing());
1096 MOZ_ASSERT(!(aParams
.flags
& FLAG_RECORD_BLOB
));
1098 mSVGDocumentWrapper
->UpdateViewportBounds(aParams
.viewportSize
);
1099 mSVGDocumentWrapper
->FlushImageTransformInvalidation();
1101 // Determine whether or not we should put the surface to be created into
1102 // the cache. If we fail, we need to reset this to false to let the caller
1103 // know nothing was put in the cache.
1104 aWillCache
= !(aParams
.flags
& FLAG_BYPASS_SURFACE_CACHE
) &&
1105 // Refuse to cache animated images:
1106 // XXX(seth): We may remove this restriction in bug 922893.
1108 // The image is too big to fit in the cache:
1109 SurfaceCache::CanHold(aParams
.size
);
1111 // If we weren't given a context, then we know we just want the rasterized
1112 // surface. We will create the frame below but only insert it into the cache
1113 // if we actually need to.
1114 if (!aWillCache
&& aParams
.context
) {
1118 // We're about to rerasterize, which may mean that some of the previous
1119 // surfaces we've rasterized aren't useful anymore. We can allow them to
1120 // expire from the cache by unlocking them here, and then sending out an
1121 // invalidation. If this image is locked, any surfaces that are still useful
1122 // will become locked again when Draw touches them, and the remainder will
1123 // eventually expire.
1125 SurfaceCache::UnlockEntries(ImageKey(this));
1128 // If there is no context, the default backend is fine.
1129 BackendType backend
=
1130 aParams
.context
? aParams
.context
->GetDrawTarget()->GetBackendType()
1131 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1133 if (backend
== BackendType::DIRECT2D1_1
) {
1134 // We don't want to draw arbitrary content with D2D anymore
1135 // because it doesn't support PushLayerWithBlend so switch to skia
1136 backend
= BackendType::SKIA
;
1139 // Try to create an imgFrame, initializing the surface it contains by drawing
1140 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1141 auto frame
= MakeNotNull
<RefPtr
<imgFrame
>>();
1142 nsresult rv
= frame
->InitWithDrawable(
1143 aSVGDrawable
, aParams
.size
, SurfaceFormat::OS_RGBA
, SamplingFilter::POINT
,
1144 aParams
.flags
, backend
);
1146 // If we couldn't create the frame, it was probably because it would end
1147 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1148 // could be set such that the cache isn't the limiting factor.
1149 if (NS_FAILED(rv
)) {
1154 // Take a strong reference to the frame's surface and make sure it hasn't
1155 // already been purged by the operating system.
1156 RefPtr
<SourceSurface
> surface
= frame
->GetSourceSurface();
1162 // We created the frame, but only because we had no context to draw to
1163 // directly. All the caller wants is the surface in this case.
1165 return surface
.forget();
1168 // Attempt to cache the frame.
1169 SurfaceKey surfaceKey
= VectorSurfaceKey(aParams
.size
, aParams
.svgContext
);
1170 NotNull
<RefPtr
<ISurfaceProvider
>> provider
=
1171 MakeNotNull
<SimpleSurfaceProvider
*>(ImageKey(this), surfaceKey
, frame
);
1173 if (SurfaceCache::Insert(provider
) == InsertOutcome::SUCCESS
) {
1174 if (aParams
.size
!= aParams
.drawSize
) {
1175 // We created a new surface that wasn't the size we requested, which means
1176 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1177 // need rather than waiting for the cache to expire them.
1178 SurfaceCache::PruneImage(ImageKey(this));
1184 return surface
.forget();
1187 void VectorImage::SendFrameComplete(bool aDidCache
, uint32_t aFlags
) {
1188 // If the cache was not updated, we have nothing to do.
1193 // Send out an invalidation so that surfaces that are still in use get
1194 // re-locked. See the discussion of the UnlockSurfaces call above.
1195 if (!(aFlags
& FLAG_ASYNC_NOTIFY
)) {
1196 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1197 GetMaxSizedIntRect());
1199 NotNull
<RefPtr
<VectorImage
>> image
= WrapNotNull(this);
1200 NS_DispatchToMainThread(CreateRenderBlockingRunnable(NS_NewRunnableFunction(
1201 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1202 RefPtr
<ProgressTracker
> tracker
= image
->GetProgressTracker();
1204 tracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1205 GetMaxSizedIntRect());
1211 void VectorImage::Show(gfxDrawable
* aDrawable
,
1212 const SVGDrawingParameters
& aParams
) {
1213 // The surface size may differ from the size at which we wish to draw. As
1214 // such, we may need to adjust the context/region to take this into account.
1215 gfxContextMatrixAutoSaveRestore
saveMatrix(aParams
.context
);
1216 ImageRegion
region(aParams
.region
);
1217 if (aParams
.drawSize
!= aParams
.size
) {
1218 gfx::MatrixScales
scale(
1219 double(aParams
.drawSize
.width
) / aParams
.size
.width
,
1220 double(aParams
.drawSize
.height
) / aParams
.size
.height
);
1221 aParams
.context
->Multiply(gfx::Matrix::Scaling(scale
));
1222 region
.Scale(1.0 / scale
.xScale
, 1.0 / scale
.yScale
);
1225 MOZ_ASSERT(aDrawable
, "Should have a gfxDrawable by now");
1226 gfxUtils::DrawPixelSnapped(aParams
.context
, aDrawable
,
1227 SizeDouble(aParams
.size
), region
,
1228 SurfaceFormat::OS_RGBA
, aParams
.samplingFilter
,
1229 aParams
.flags
, aParams
.opacity
, false);
1231 AutoProfilerImagePaintMarker
PROFILER_RAII(this);
1233 NotifyDrawingObservers();
1236 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
1237 mRenderingObserver
->ResumeHonoringInvalidations();
1240 void VectorImage::RecoverFromLossOfSurfaces() {
1241 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1243 // Discard all existing frames, since they're probably all now invalid.
1244 SurfaceCache::RemoveImage(ImageKey(this));
1248 VectorImage::StartDecoding(uint32_t aFlags
, uint32_t aWhichFrame
) {
1249 // Nothing to do for SVG images
1253 bool VectorImage::StartDecodingWithResult(uint32_t aFlags
,
1254 uint32_t aWhichFrame
) {
1255 // SVG images are ready to draw when they are loaded
1256 return mIsFullyLoaded
;
1259 bool VectorImage::HasDecodedPixels() {
1260 MOZ_ASSERT_UNREACHABLE("calling VectorImage::HasDecodedPixels");
1261 return mIsFullyLoaded
;
1264 imgIContainer::DecodeResult
VectorImage::RequestDecodeWithResult(
1265 uint32_t aFlags
, uint32_t aWhichFrame
) {
1266 // SVG images are ready to draw when they are loaded and don't have an error.
1269 return imgIContainer::DECODE_REQUEST_FAILED
;
1272 if (!mIsFullyLoaded
) {
1273 return imgIContainer::DECODE_REQUESTED
;
1276 return imgIContainer::DECODE_SURFACE_AVAILABLE
;
1280 VectorImage::RequestDecodeForSize(const nsIntSize
& aSize
, uint32_t aFlags
,
1281 uint32_t aWhichFrame
) {
1282 // Nothing to do for SVG images, though in theory we could rasterize to the
1283 // provided size ahead of time if we supported off-main-thread SVG
1288 //******************************************************************************
1291 VectorImage::LockImage() {
1292 MOZ_ASSERT(NS_IsMainThread());
1295 return NS_ERROR_FAILURE
;
1300 if (mLockCount
== 1) {
1301 // Lock this image's surfaces in the SurfaceCache.
1302 SurfaceCache::LockImage(ImageKey(this));
1308 //******************************************************************************
1311 VectorImage::UnlockImage() {
1312 MOZ_ASSERT(NS_IsMainThread());
1315 return NS_ERROR_FAILURE
;
1318 if (mLockCount
== 0) {
1319 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1320 return NS_ERROR_ABORT
;
1325 if (mLockCount
== 0) {
1326 // Unlock this image's surfaces in the SurfaceCache.
1327 SurfaceCache::UnlockImage(ImageKey(this));
1333 //******************************************************************************
1336 VectorImage::RequestDiscard() {
1337 MOZ_ASSERT(NS_IsMainThread());
1339 if (mDiscardable
&& mLockCount
== 0) {
1340 SurfaceCache::RemoveImage(ImageKey(this));
1341 mProgressTracker
->OnDiscard();
1347 void VectorImage::OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) {
1348 MOZ_ASSERT(mProgressTracker
);
1350 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1352 &ProgressTracker::OnDiscard
));
1355 //******************************************************************************
1357 VectorImage::ResetAnimation() {
1359 return NS_ERROR_FAILURE
;
1362 if (!mIsFullyLoaded
|| !mHaveAnimations
) {
1363 return NS_OK
; // There are no animations to be reset.
1366 mSVGDocumentWrapper
->ResetAnimation();
1371 NS_IMETHODIMP_(float)
1372 VectorImage::GetFrameIndex(uint32_t aWhichFrame
) {
1373 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
, "Invalid argument");
1374 return aWhichFrame
== FRAME_FIRST
1376 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1379 //------------------------------------------------------------------------------
1380 // nsIRequestObserver methods
1382 //******************************************************************************
1384 VectorImage::OnStartRequest(nsIRequest
* aRequest
) {
1385 MOZ_ASSERT(!mSVGDocumentWrapper
,
1386 "Repeated call to OnStartRequest -- can this happen?");
1388 mSVGDocumentWrapper
= new SVGDocumentWrapper();
1389 nsresult rv
= mSVGDocumentWrapper
->OnStartRequest(aRequest
);
1390 if (NS_FAILED(rv
)) {
1391 mSVGDocumentWrapper
= nullptr;
1396 // Create a listener to wait until the SVG document is fully loaded, which
1397 // will signal that this image is ready to render. Certain error conditions
1398 // will prevent us from ever getting this notification, so we also create a
1399 // listener that waits for parsing to complete and cancels the
1400 // SVGLoadEventListener if needed. The listeners are automatically attached
1401 // to the document by their constructors.
1402 SVGDocument
* document
= mSVGDocumentWrapper
->GetDocument();
1403 mLoadEventListener
= new SVGLoadEventListener(document
, this);
1404 mParseCompleteListener
= new SVGParseCompleteListener(document
, this);
1406 // Displayed documents will call InitUseCounters under SetScriptGlobalObject,
1407 // but SVG image documents never get a script global object, so we initialize
1408 // use counters here, right after the document has been created.
1409 document
->InitUseCounters();
1414 //******************************************************************************
1416 VectorImage::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
1418 return NS_ERROR_FAILURE
;
1421 return mSVGDocumentWrapper
->OnStopRequest(aRequest
, aStatus
);
1424 void VectorImage::OnSVGDocumentParsed() {
1425 MOZ_ASSERT(mParseCompleteListener
, "Should have the parse complete listener");
1426 MOZ_ASSERT(mLoadEventListener
, "Should have the load event listener");
1428 if (!mSVGDocumentWrapper
->GetRootSVGElem()) {
1429 // This is an invalid SVG document. It may have failed to parse, or it may
1430 // be missing the <svg> root element, or the <svg> root element may not
1431 // declare the correct namespace. In any of these cases, we'll never be
1432 // notified that the SVG finished loading, so we need to treat this as an
1434 OnSVGDocumentError();
1438 void VectorImage::CancelAllListeners() {
1439 if (mParseCompleteListener
) {
1440 mParseCompleteListener
->Cancel();
1441 mParseCompleteListener
= nullptr;
1443 if (mLoadEventListener
) {
1444 mLoadEventListener
->Cancel();
1445 mLoadEventListener
= nullptr;
1449 void VectorImage::OnSVGDocumentLoaded() {
1450 MOZ_ASSERT(mSVGDocumentWrapper
->GetRootSVGElem(),
1451 "Should have parsed successfully");
1452 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
,
1453 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1454 "Duplicate calls to OnSVGDocumentLoaded?");
1456 CancelAllListeners();
1458 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1459 mSVGDocumentWrapper
->FlushLayout();
1461 // This is the earliest point that we can get accurate use counter data
1462 // for a valid SVG document. Without the FlushLayout call, we would miss
1463 // any CSS property usage that comes from SVG presentation attributes.
1464 mSVGDocumentWrapper
->GetDocument()->ReportDocumentUseCounters();
1466 mIsFullyLoaded
= true;
1467 mHaveAnimations
= mSVGDocumentWrapper
->IsAnimated();
1469 // Start listening to our image for rendering updates.
1470 mRenderingObserver
= new SVGRootRenderingObserver(mSVGDocumentWrapper
, this);
1472 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1473 // stick around long enough to complete our work.
1474 RefPtr
<VectorImage
> kungFuDeathGrip(this);
1476 // Tell *our* observers that we're done loading.
1477 if (mProgressTracker
) {
1478 Progress progress
= FLAG_SIZE_AVAILABLE
| FLAG_HAS_TRANSPARENCY
|
1479 FLAG_FRAME_COMPLETE
| FLAG_DECODE_COMPLETE
;
1481 if (mHaveAnimations
) {
1482 progress
|= FLAG_IS_ANIMATED
;
1485 // Merge in any saved progress from OnImageDataComplete.
1486 if (mLoadProgress
) {
1487 progress
|= *mLoadProgress
;
1488 mLoadProgress
= Nothing();
1491 mProgressTracker
->SyncNotifyProgress(progress
, GetMaxSizedIntRect());
1494 EvaluateAnimation();
1497 void VectorImage::OnSVGDocumentError() {
1498 CancelAllListeners();
1502 // We won't enter OnSVGDocumentLoaded, so report use counters now for this
1503 // invalid document.
1504 ReportDocumentUseCounters();
1506 if (mProgressTracker
) {
1507 // Notify observers about the error and unblock page load.
1508 Progress progress
= FLAG_HAS_ERROR
;
1510 // Merge in any saved progress from OnImageDataComplete.
1511 if (mLoadProgress
) {
1512 progress
|= *mLoadProgress
;
1513 mLoadProgress
= Nothing();
1516 mProgressTracker
->SyncNotifyProgress(progress
);
1520 //------------------------------------------------------------------------------
1521 // nsIStreamListener method
1523 //******************************************************************************
1525 VectorImage::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
1526 uint64_t aSourceOffset
, uint32_t aCount
) {
1528 return NS_ERROR_FAILURE
;
1531 return mSVGDocumentWrapper
->OnDataAvailable(aRequest
, aInStr
, aSourceOffset
,
1535 // --------------------------
1536 // Invalidation helper method
1538 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1539 if (mHasPendingInvalidation
) {
1543 mHasPendingInvalidation
= true;
1545 // Animated images can wait for the refresh tick.
1546 if (mHaveAnimations
) {
1550 // Non-animated images won't get the refresh tick, so we should just send an
1551 // invalidation outside the current execution context. We need to defer
1552 // because the layout tree is in the middle of invalidation, and the tree
1553 // state needs to be consistent. Specifically only some of the frames have
1554 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1555 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1556 // get cleared when we repaint the SVG into a surface by
1557 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1558 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1559 if (mProgressTracker
) {
1560 eventTarget
= mProgressTracker
->GetEventTarget();
1562 eventTarget
= do_GetMainThread();
1565 RefPtr
<VectorImage
> self(this);
1566 nsCOMPtr
<nsIRunnable
> ev(NS_NewRunnableFunction(
1567 "VectorImage::SendInvalidationNotifications",
1568 [=]() -> void { self
->SendInvalidationNotifications(); }));
1569 eventTarget
->Dispatch(CreateRenderBlockingRunnable(ev
.forget()),
1570 NS_DISPATCH_NORMAL
);
1573 void VectorImage::PropagateUseCounters(Document
* aReferencingDocument
) {
1574 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1575 doc
->PropagateImageUseCounters(aReferencingDocument
);
1579 nsIntSize
VectorImage::OptimalImageSizeForDest(const gfxSize
& aDest
,
1580 uint32_t aWhichFrame
,
1581 SamplingFilter aSamplingFilter
,
1583 MOZ_ASSERT(aDest
.width
>= 0 || ceil(aDest
.width
) <= INT32_MAX
||
1584 aDest
.height
>= 0 || ceil(aDest
.height
) <= INT32_MAX
,
1585 "Unexpected destination size");
1587 // We can rescale SVGs freely, so just return the provided destination size.
1588 return nsIntSize::Ceil(aDest
.width
, aDest
.height
);
1591 already_AddRefed
<imgIContainer
> VectorImage::Unwrap() {
1592 nsCOMPtr
<imgIContainer
> self(this);
1593 return self
.forget();
1596 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1597 const MediaFeatureChange
& aChange
) {
1598 if (!mSVGDocumentWrapper
) {
1602 // Don't bother if the document hasn't loaded yet.
1603 if (!mIsFullyLoaded
) {
1607 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1608 if (RefPtr
<nsPresContext
> presContext
= doc
->GetPresContext()) {
1609 presContext
->MediaFeatureValuesChanged(
1610 aChange
, MediaFeatureChangePropagation::All
);
1611 // Media feature value changes don't happen in the middle of layout,
1612 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1613 // to invalidate asynchronously.
1614 if (presContext
->FlushPendingMediaFeatureValuesChanged()) {
1615 // NOTE(emilio): SendInvalidationNotifications flushes layout via
1616 // VectorImage::CreateSurface -> FlushImageTransformInvalidation.
1617 SendInvalidationNotifications();
1623 nsresult
VectorImage::GetHotspotX(int32_t* aX
) {
1624 return Image::GetHotspotX(aX
);
1627 nsresult
VectorImage::GetHotspotY(int32_t* aY
) {
1628 return Image::GetHotspotY(aY
);
1631 void VectorImage::ReportDocumentUseCounters() {
1632 if (!mSVGDocumentWrapper
) {
1636 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1637 doc
->ReportDocumentUseCounters();
1641 } // namespace image
1642 } // namespace mozilla