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