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/gfx/gfxVars.h"
21 #include "mozilla/PendingAnimationTracker.h"
22 #include "mozilla/PresShell.h"
23 #include "mozilla/RefPtr.h"
24 #include "mozilla/Tuple.h"
25 #include "nsIStreamListener.h"
26 #include "nsMimeTypes.h"
27 #include "nsPresContext.h"
30 #include "nsStubDocumentObserver.h"
31 #include "SVGObserverUtils.h" // for SVGRenderingObserver
32 #include "nsWindowSizes.h"
33 #include "ImageRegion.h"
34 #include "ISurfaceProvider.h"
35 #include "LookupResult.h"
36 #include "Orientation.h"
37 #include "SVGDocumentWrapper.h"
38 #include "SVGDrawingParameters.h"
39 #include "nsIDOMEventListener.h"
40 #include "SurfaceCache.h"
41 #include "mozilla/dom/Document.h"
46 using namespace dom::SVGPreserveAspectRatio_Binding
;
48 using namespace layers
;
52 // Helper-class: SVGRootRenderingObserver
53 class SVGRootRenderingObserver final
: public SVGRenderingObserver
{
57 SVGRootRenderingObserver(SVGDocumentWrapper
* aDocWrapper
,
58 VectorImage
* aVectorImage
)
59 : SVGRenderingObserver(),
60 mDocWrapper(aDocWrapper
),
61 mVectorImage(aVectorImage
),
62 mHonoringInvalidations(true) {
63 MOZ_ASSERT(mDocWrapper
, "Need a non-null SVG document wrapper");
64 MOZ_ASSERT(mVectorImage
, "Need a non-null VectorImage");
67 Element
* elem
= GetReferencedElementWithoutObserving();
68 MOZ_ASSERT(elem
, "no root SVG node for us to observe");
70 SVGObserverUtils::AddRenderingObserver(elem
, this);
71 mInObserverSet
= true;
74 void ResumeHonoringInvalidations() { mHonoringInvalidations
= true; }
77 virtual ~SVGRootRenderingObserver() {
78 // This needs to call our GetReferencedElementWithoutObserving override,
79 // so must be called here rather than in our base class's dtor.
83 Element
* GetReferencedElementWithoutObserving() final
{
84 return mDocWrapper
->GetRootSVGElem();
87 virtual void OnRenderingChange() override
{
88 Element
* elem
= GetReferencedElementWithoutObserving();
89 MOZ_ASSERT(elem
, "missing root SVG node");
91 if (mHonoringInvalidations
&& !mDocWrapper
->ShouldIgnoreInvalidation()) {
92 nsIFrame
* frame
= elem
->GetPrimaryFrame();
93 if (!frame
|| frame
->PresShell()->IsDestroying()) {
94 // We're being destroyed. Bail out.
98 // Ignore further invalidations until we draw.
99 mHonoringInvalidations
= false;
101 mVectorImage
->InvalidateObserversOnNextRefreshDriverTick();
104 // Our caller might've removed us from rendering-observer list.
105 // Add ourselves back!
106 if (!mInObserverSet
) {
107 SVGObserverUtils::AddRenderingObserver(elem
, this);
108 mInObserverSet
= true;
113 const RefPtr
<SVGDocumentWrapper
> mDocWrapper
;
114 VectorImage
* const mVectorImage
; // Raw pointer because it owns me.
115 bool mHonoringInvalidations
;
118 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver
, nsIMutationObserver
)
120 class SVGParseCompleteListener final
: public nsStubDocumentObserver
{
124 SVGParseCompleteListener(SVGDocument
* aDocument
, VectorImage
* aImage
)
125 : mDocument(aDocument
), mImage(aImage
) {
126 MOZ_ASSERT(mDocument
, "Need an SVG document");
127 MOZ_ASSERT(mImage
, "Need an image");
129 mDocument
->AddObserver(this);
133 ~SVGParseCompleteListener() {
135 // The document must have been destroyed before we got our event.
136 // Otherwise this can't happen, since documents hold strong references to
143 void EndLoad(Document
* aDocument
) override
{
144 MOZ_ASSERT(aDocument
== mDocument
, "Got EndLoad for wrong document?");
146 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
147 // we stick around long enough to complete our work.
148 RefPtr
<SVGParseCompleteListener
> kungFuDeathGrip(this);
150 mImage
->OnSVGDocumentParsed();
154 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
156 mDocument
->RemoveObserver(this);
162 RefPtr
<SVGDocument
> mDocument
;
163 VectorImage
* const mImage
; // Raw pointer to owner.
166 NS_IMPL_ISUPPORTS(SVGParseCompleteListener
, nsIDocumentObserver
)
168 class SVGLoadEventListener final
: public nsIDOMEventListener
{
172 SVGLoadEventListener(Document
* aDocument
, VectorImage
* aImage
)
173 : mDocument(aDocument
), mImage(aImage
) {
174 MOZ_ASSERT(mDocument
, "Need an SVG document");
175 MOZ_ASSERT(mImage
, "Need an image");
177 mDocument
->AddEventListener(NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"),
179 mDocument
->AddEventListener(NS_LITERAL_STRING("SVGAbort"), this, true,
181 mDocument
->AddEventListener(NS_LITERAL_STRING("SVGError"), this, true,
186 ~SVGLoadEventListener() {
188 // The document must have been destroyed before we got our event.
189 // Otherwise this can't happen, since documents hold strong references to
196 NS_IMETHOD
HandleEvent(Event
* aEvent
) override
{
197 MOZ_ASSERT(mDocument
, "Need an SVG document. Received multiple events?");
199 // OnSVGDocumentLoaded/OnSVGDocumentError will release our owner's reference
200 // to us, so ensure we stick around long enough to complete our work.
201 RefPtr
<SVGLoadEventListener
> kungFuDeathGrip(this);
203 nsAutoString eventType
;
204 aEvent
->GetType(eventType
);
205 MOZ_ASSERT(eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad") ||
206 eventType
.EqualsLiteral("SVGAbort") ||
207 eventType
.EqualsLiteral("SVGError"),
208 "Received unexpected event");
210 if (eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad")) {
211 mImage
->OnSVGDocumentLoaded();
213 mImage
->OnSVGDocumentError();
220 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
222 mDocument
->RemoveEventListener(
223 NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), this, true);
224 mDocument
->RemoveEventListener(NS_LITERAL_STRING("SVGAbort"), this, true);
225 mDocument
->RemoveEventListener(NS_LITERAL_STRING("SVGError"), this, true);
231 nsCOMPtr
<Document
> mDocument
;
232 VectorImage
* const mImage
; // Raw pointer to owner.
235 NS_IMPL_ISUPPORTS(SVGLoadEventListener
, nsIDOMEventListener
)
237 // Helper-class: SVGDrawingCallback
238 class SVGDrawingCallback
: public gfxDrawingCallback
{
240 SVGDrawingCallback(SVGDocumentWrapper
* aSVGDocumentWrapper
,
241 const IntSize
& aViewportSize
, const IntSize
& aSize
,
242 uint32_t aImageFlags
)
243 : mSVGDocumentWrapper(aSVGDocumentWrapper
),
244 mViewportSize(aViewportSize
),
246 mImageFlags(aImageFlags
) {}
247 virtual bool operator()(gfxContext
* aContext
, const gfxRect
& aFillRect
,
248 const SamplingFilter aSamplingFilter
,
249 const gfxMatrix
& aTransform
) override
;
252 RefPtr
<SVGDocumentWrapper
> mSVGDocumentWrapper
;
253 const IntSize mViewportSize
;
255 uint32_t mImageFlags
;
258 // Based loosely on nsSVGIntegrationUtils' PaintFrameCallback::operator()
259 bool SVGDrawingCallback::operator()(gfxContext
* aContext
,
260 const gfxRect
& aFillRect
,
261 const SamplingFilter aSamplingFilter
,
262 const gfxMatrix
& aTransform
) {
263 MOZ_ASSERT(mSVGDocumentWrapper
, "need an SVGDocumentWrapper");
265 // Get (& sanity-check) the helper-doc's presShell
266 RefPtr
<PresShell
> presShell
= mSVGDocumentWrapper
->GetPresShell();
267 MOZ_ASSERT(presShell
, "GetPresShell returned null for an SVG image?");
269 #ifdef MOZ_GECKO_PROFILER
270 Document
* doc
= presShell
->GetDocument();
271 nsIURI
* uri
= doc
? doc
->GetDocumentURI() : nullptr;
272 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
273 "SVG Image drawing", GRAPHICS
,
274 nsPrintfCString("%dx%d %s", mSize
.width
, mSize
.height
,
275 uri
? uri
->GetSpecOrDefault().get() : "N/A"));
278 gfxContextAutoSaveRestore
contextRestorer(aContext
);
280 // Clip to aFillRect so that we don't paint outside.
282 aContext
->Rectangle(aFillRect
);
285 gfxMatrix matrix
= aTransform
;
286 if (!matrix
.Invert()) {
289 aContext
->SetMatrixDouble(
290 aContext
->CurrentMatrixDouble().PreMultiply(matrix
).PreScale(
291 double(mSize
.width
) / mViewportSize
.width
,
292 double(mSize
.height
) / mViewportSize
.height
));
294 nsPresContext
* presContext
= presShell
->GetPresContext();
295 MOZ_ASSERT(presContext
, "pres shell w/out pres context");
297 nsRect
svgRect(0, 0, presContext
->DevPixelsToAppUnits(mViewportSize
.width
),
298 presContext
->DevPixelsToAppUnits(mViewportSize
.height
));
300 RenderDocumentFlags renderDocFlags
=
301 RenderDocumentFlags::IgnoreViewportScrolling
;
302 if (!(mImageFlags
& imgIContainer::FLAG_SYNC_DECODE
)) {
303 renderDocFlags
|= RenderDocumentFlags::AsyncDecodeImages
;
306 presShell
->RenderDocument(svgRect
, renderDocFlags
,
307 NS_RGBA(0, 0, 0, 0), // transparent
313 class MOZ_STACK_CLASS AutoRestoreSVGState final
{
315 AutoRestoreSVGState(const SVGDrawingParameters
& aParams
,
316 SVGDocumentWrapper
* aSVGDocumentWrapper
, bool& aIsDrawing
,
318 : mIsDrawing(aIsDrawing
)
319 // Apply any 'preserveAspectRatio' override (if specified) to the root
322 mPAR(aParams
.svgContext
, aSVGDocumentWrapper
->GetRootSVGElem())
323 // Set the animation time:
325 mTime(aSVGDocumentWrapper
->GetRootSVGElem(), aParams
.animationTime
) {
326 MOZ_ASSERT(!aIsDrawing
);
327 MOZ_ASSERT(aSVGDocumentWrapper
->GetDocument());
331 // Set context paint (if specified) on the document:
333 MOZ_ASSERT(aParams
.svgContext
->GetContextPaint());
334 mContextPaint
.emplace(*aParams
.svgContext
->GetContextPaint(),
335 *aSVGDocumentWrapper
->GetDocument());
340 AutoRestore
<bool> mIsDrawing
;
341 AutoPreserveAspectRatioOverride mPAR
;
342 AutoSVGTimeSetRestore mTime
;
343 Maybe
<AutoSetRestoreSVGContextPaint
> mContextPaint
;
346 // Implement VectorImage's nsISupports-inherited methods
347 NS_IMPL_ISUPPORTS(VectorImage
, imgIContainer
, nsIStreamListener
,
350 //------------------------------------------------------------------------------
351 // Constructor / Destructor
353 VectorImage::VectorImage(nsIURI
* aURI
/* = nullptr */)
354 : ImageResource(aURI
), // invoke superclass's constructor
356 mIsInitialized(false),
358 mIsFullyLoaded(false),
360 mHaveAnimations(false),
361 mHasPendingInvalidation(false) {}
363 VectorImage::~VectorImage() {
364 CancelAllListeners();
365 SurfaceCache::RemoveImage(ImageKey(this));
368 //------------------------------------------------------------------------------
369 // Methods inherited from Image.h
371 nsresult
VectorImage::Init(const char* aMimeType
, uint32_t aFlags
) {
372 // We don't support re-initialization
373 if (mIsInitialized
) {
374 return NS_ERROR_ILLEGAL_VALUE
;
377 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
&& !mError
,
378 "Flags unexpectedly set before initialization");
379 MOZ_ASSERT(!strcmp(aMimeType
, IMAGE_SVG_XML
), "Unexpected mimetype");
381 mDiscardable
= !!(aFlags
& INIT_FLAG_DISCARDABLE
);
383 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
386 SurfaceCache::LockImage(ImageKey(this));
389 mIsInitialized
= true;
393 size_t VectorImage::SizeOfSourceWithComputedFallback(
394 SizeOfState
& aState
) const {
395 if (!mSVGDocumentWrapper
) {
396 return 0; // No document, so no memory used for the document.
399 SVGDocument
* doc
= mSVGDocumentWrapper
->GetDocument();
401 return 0; // No document, so no memory used for the document.
404 nsWindowSizes
windowSizes(aState
);
405 doc
->DocAddSizeOfIncludingThis(windowSizes
);
407 if (windowSizes
.getTotalSize() == 0) {
408 // MallocSizeOf fails on this platform. Because we also use this method for
409 // determining the size of cache entries, we need to return something
410 // reasonable here. Unfortunately, there's no way to estimate the document's
411 // size accurately, so we just use a constant value of 100KB, which will
412 // generally underestimate the true size.
416 return windowSizes
.getTotalSize();
419 void VectorImage::CollectSizeOfSurfaces(
420 nsTArray
<SurfaceMemoryCounter
>& aCounters
,
421 MallocSizeOf aMallocSizeOf
) const {
422 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters
, aMallocSizeOf
);
425 nsresult
VectorImage::OnImageDataComplete(nsIRequest
* aRequest
,
426 nsISupports
* aContext
,
427 nsresult aStatus
, bool aLastPart
) {
428 // Call our internal OnStopRequest method, which only talks to our embedded
429 // SVG document. This won't have any effect on our ProgressTracker.
430 nsresult finalStatus
= OnStopRequest(aRequest
, aStatus
);
432 // Give precedence to Necko failure codes.
433 if (NS_FAILED(aStatus
)) {
434 finalStatus
= aStatus
;
437 Progress loadProgress
= LoadCompleteProgress(aLastPart
, mError
, finalStatus
);
439 if (mIsFullyLoaded
|| mError
) {
440 // Our document is loaded, so we're ready to notify now.
441 mProgressTracker
->SyncNotifyProgress(loadProgress
);
443 // Record our progress so far; we'll actually send the notifications in
444 // OnSVGDocumentLoaded or OnSVGDocumentError.
445 mLoadProgress
= Some(loadProgress
);
451 nsresult
VectorImage::OnImageDataAvailable(nsIRequest
* aRequest
,
452 nsISupports
* aContext
,
453 nsIInputStream
* aInStr
,
454 uint64_t aSourceOffset
,
456 return OnDataAvailable(aRequest
, aInStr
, aSourceOffset
, aCount
);
459 nsresult
VectorImage::StartAnimation() {
461 return NS_ERROR_FAILURE
;
464 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
466 mSVGDocumentWrapper
->StartAnimation();
470 nsresult
VectorImage::StopAnimation() {
473 rv
= NS_ERROR_FAILURE
;
475 MOZ_ASSERT(mIsFullyLoaded
&& mHaveAnimations
,
476 "Should not have been animating!");
478 mSVGDocumentWrapper
->StopAnimation();
485 bool VectorImage::ShouldAnimate() {
486 return ImageResource::ShouldAnimate() && mIsFullyLoaded
&& mHaveAnimations
;
490 VectorImage::SetAnimationStartTime(const TimeStamp
& aTime
) {
491 // We don't care about animation start time.
494 //------------------------------------------------------------------------------
495 // imgIContainer methods
497 //******************************************************************************
499 VectorImage::GetWidth(int32_t* aWidth
) {
500 if (mError
|| !mIsFullyLoaded
) {
501 // XXXdholbert Technically we should leave outparam untouched when we
502 // fail. But since many callers don't check for failure, we set it to 0 on
503 // failure, for sane/predictable results.
505 return NS_ERROR_FAILURE
;
508 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
510 "Should have a root SVG elem, since we finished "
511 "loading without errors");
512 int32_t rootElemWidth
= rootElem
->GetIntrinsicWidth();
513 if (rootElemWidth
< 0) {
515 return NS_ERROR_FAILURE
;
517 *aWidth
= rootElemWidth
;
521 //******************************************************************************
522 nsresult
VectorImage::GetNativeSizes(nsTArray
<IntSize
>& aNativeSizes
) const {
523 return NS_ERROR_NOT_IMPLEMENTED
;
526 //******************************************************************************
527 size_t VectorImage::GetNativeSizesLength() const { return 0; }
529 //******************************************************************************
531 VectorImage::RequestRefresh(const TimeStamp
& aTime
) {
532 if (HadRecentRefresh(aTime
)) {
536 PendingAnimationTracker
* tracker
=
537 mSVGDocumentWrapper
->GetDocument()->GetPendingAnimationTracker();
538 if (tracker
&& ShouldAnimate()) {
539 tracker
->TriggerPendingAnimationsOnNextTick(aTime
);
544 mSVGDocumentWrapper
->TickRefreshDriver();
546 if (mHasPendingInvalidation
) {
547 SendInvalidationNotifications();
551 void VectorImage::SendInvalidationNotifications() {
552 // Animated images don't send out invalidation notifications as soon as
553 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
554 // records that there are pending invalidations and then returns immediately.
555 // The notifications are actually sent from RequestRefresh(). We send these
556 // notifications there to ensure that there is actually a document observing
557 // us. Otherwise, the notifications are just wasted effort.
559 // Non-animated images post an event to call this method from
560 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
561 // called for them. Ordinarily this isn't needed, since we send out
562 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
563 // SVG document may not be 100% ready to render at that time. In those cases
564 // we would miss the subsequent invalidations if we didn't send out the
565 // notifications indirectly in |InvalidateObservers...|.
567 MOZ_ASSERT(mHasPendingInvalidation
);
568 mHasPendingInvalidation
= false;
569 SurfaceCache::RemoveImage(ImageKey(this));
571 if (UpdateImageContainer(Nothing())) {
572 // If we have image containers, that means we probably won't get a Draw call
573 // from the owner since they are using the container. We must assume all
574 // invalidations need to be handled.
575 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
576 mRenderingObserver
->ResumeHonoringInvalidations();
579 if (mProgressTracker
) {
580 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
581 GetMaxSizedIntRect());
585 NS_IMETHODIMP_(IntRect
)
586 VectorImage::GetImageSpaceInvalidationRect(const IntRect
& aRect
) {
590 //******************************************************************************
592 VectorImage::GetHeight(int32_t* aHeight
) {
593 if (mError
|| !mIsFullyLoaded
) {
594 // XXXdholbert Technically we should leave outparam untouched when we
595 // fail. But since many callers don't check for failure, we set it to 0 on
596 // failure, for sane/predictable results.
598 return NS_ERROR_FAILURE
;
601 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
603 "Should have a root SVG elem, since we finished "
604 "loading without errors");
605 int32_t rootElemHeight
= rootElem
->GetIntrinsicHeight();
606 if (rootElemHeight
< 0) {
608 return NS_ERROR_FAILURE
;
610 *aHeight
= rootElemHeight
;
614 //******************************************************************************
616 VectorImage::GetIntrinsicSize(nsSize
* aSize
) {
617 if (mError
|| !mIsFullyLoaded
) {
618 return NS_ERROR_FAILURE
;
621 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
623 return NS_ERROR_FAILURE
;
626 *aSize
= nsSize(-1, -1);
627 IntrinsicSize rfSize
= rootFrame
->GetIntrinsicSize();
629 aSize
->width
= *rfSize
.width
;
632 aSize
->height
= *rfSize
.height
;
637 //******************************************************************************
638 Maybe
<AspectRatio
> VectorImage::GetIntrinsicRatio() {
639 if (mError
|| !mIsFullyLoaded
) {
643 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
648 return Some(rootFrame
->GetIntrinsicRatio());
651 NS_IMETHODIMP_(Orientation
)
652 VectorImage::GetOrientation() { return Orientation(); }
654 //******************************************************************************
656 VectorImage::GetType(uint16_t* aType
) {
657 NS_ENSURE_ARG_POINTER(aType
);
659 *aType
= imgIContainer::TYPE_VECTOR
;
663 //******************************************************************************
665 VectorImage::GetProducerId(uint32_t* aId
) {
666 NS_ENSURE_ARG_POINTER(aId
);
668 *aId
= ImageResource::GetImageProducerId();
672 //******************************************************************************
674 VectorImage::GetAnimated(bool* aAnimated
) {
675 if (mError
|| !mIsFullyLoaded
) {
676 return NS_ERROR_FAILURE
;
679 *aAnimated
= mSVGDocumentWrapper
->IsAnimated();
683 //******************************************************************************
684 int32_t VectorImage::GetFirstFrameDelay() {
689 if (!mSVGDocumentWrapper
->IsAnimated()) {
693 // We don't really have a frame delay, so just pretend that we constantly
699 VectorImage::WillDrawOpaqueNow() {
700 return false; // In general, SVG content is not opaque.
703 //******************************************************************************
704 NS_IMETHODIMP_(already_AddRefed
<SourceSurface
>)
705 VectorImage::GetFrame(uint32_t aWhichFrame
, uint32_t aFlags
) {
710 // Look up height & width
711 // ----------------------
712 SVGSVGElement
* svgElem
= mSVGDocumentWrapper
->GetRootSVGElem();
714 "Should have a root SVG elem, since we finished "
715 "loading without errors");
716 nsIntSize
imageIntSize(svgElem
->GetIntrinsicWidth(),
717 svgElem
->GetIntrinsicHeight());
719 if (imageIntSize
.IsEmpty()) {
720 // We'll get here if our SVG doc has a percent-valued or negative width or
725 return GetFrameAtSize(imageIntSize
, aWhichFrame
, aFlags
);
728 NS_IMETHODIMP_(already_AddRefed
<SourceSurface
>)
729 VectorImage::GetFrameAtSize(const IntSize
& aSize
, uint32_t aWhichFrame
,
732 NotifyDrawingObservers();
735 auto result
= GetFrameInternal(aSize
, Nothing(), aWhichFrame
, aFlags
);
736 return Get
<2>(result
).forget();
739 Tuple
<ImgDrawResult
, IntSize
, RefPtr
<SourceSurface
>>
740 VectorImage::GetFrameInternal(const IntSize
& aSize
,
741 const Maybe
<SVGImageContext
>& aSVGContext
,
742 uint32_t aWhichFrame
, uint32_t aFlags
) {
743 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
);
745 if (aSize
.IsEmpty() || aWhichFrame
> FRAME_MAX_VALUE
) {
746 return MakeTuple(ImgDrawResult::BAD_ARGS
, aSize
, RefPtr
<SourceSurface
>());
750 return MakeTuple(ImgDrawResult::BAD_IMAGE
, aSize
, RefPtr
<SourceSurface
>());
753 if (!mIsFullyLoaded
) {
754 return MakeTuple(ImgDrawResult::NOT_READY
, aSize
, RefPtr
<SourceSurface
>());
757 RefPtr
<SourceSurface
> sourceSurface
;
759 Tie(sourceSurface
, decodeSize
) =
760 LookupCachedSurface(aSize
, aSVGContext
, aFlags
);
762 return MakeTuple(ImgDrawResult::SUCCESS
, decodeSize
,
763 std::move(sourceSurface
));
767 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
768 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR
, decodeSize
,
769 RefPtr
<SourceSurface
>());
772 // By using a null gfxContext, we ensure that we will always attempt to
773 // create a surface, even if we aren't capable of caching it (e.g. due to our
774 // flags, having an animation, etc). Otherwise CreateSurface will assume that
775 // the caller is capable of drawing directly to its own draw target if we
777 SVGDrawingParameters
params(
778 nullptr, decodeSize
, aSize
, ImageRegion::Create(decodeSize
),
779 SamplingFilter::POINT
, aSVGContext
,
780 mSVGDocumentWrapper
->GetCurrentTimeAsFloat(), aFlags
, 1.0);
782 bool didCache
; // Was the surface put into the cache?
783 bool contextPaint
= aSVGContext
&& aSVGContext
->GetContextPaint();
785 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, mIsDrawing
,
788 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
789 RefPtr
<SourceSurface
> surface
= CreateSurface(params
, svgDrawable
, didCache
);
791 MOZ_ASSERT(!didCache
);
792 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR
, decodeSize
,
793 RefPtr
<SourceSurface
>());
796 SendFrameComplete(didCache
, params
.flags
);
797 return MakeTuple(ImgDrawResult::SUCCESS
, decodeSize
, std::move(surface
));
800 //******************************************************************************
801 Tuple
<ImgDrawResult
, IntSize
> VectorImage::GetImageContainerSize(
802 LayerManager
* aManager
, const IntSize
& aSize
, uint32_t aFlags
) {
804 return MakeTuple(ImgDrawResult::BAD_IMAGE
, IntSize(0, 0));
807 if (!mIsFullyLoaded
) {
808 return MakeTuple(ImgDrawResult::NOT_READY
, IntSize(0, 0));
811 if (mHaveAnimations
||
812 aManager
->GetBackendType() != LayersBackend::LAYERS_WR
) {
813 return MakeTuple(ImgDrawResult::NOT_SUPPORTED
, IntSize(0, 0));
816 // We don't need to check if the size is too big since we only support
817 // WebRender backends.
818 if (aSize
.IsEmpty()) {
819 return MakeTuple(ImgDrawResult::BAD_ARGS
, IntSize(0, 0));
822 return MakeTuple(ImgDrawResult::SUCCESS
, aSize
);
826 VectorImage::IsImageContainerAvailable(LayerManager
* aManager
,
828 if (mError
|| !mIsFullyLoaded
|| mHaveAnimations
||
829 aManager
->GetBackendType() != LayersBackend::LAYERS_WR
) {
836 //******************************************************************************
837 NS_IMETHODIMP_(already_AddRefed
<ImageContainer
>)
838 VectorImage::GetImageContainer(LayerManager
* aManager
, uint32_t aFlags
) {
839 MOZ_ASSERT(aManager
->GetBackendType() != LayersBackend::LAYERS_WR
,
840 "WebRender should always use GetImageContainerAvailableAtSize!");
844 //******************************************************************************
846 VectorImage::IsImageContainerAvailableAtSize(LayerManager
* aManager
,
847 const IntSize
& aSize
,
849 // Since we only support image containers with WebRender, and it can handle
850 // textures larger than the hw max texture size, we don't need to check aSize.
851 return !aSize
.IsEmpty() && IsImageContainerAvailable(aManager
, aFlags
);
854 //******************************************************************************
855 NS_IMETHODIMP_(ImgDrawResult
)
856 VectorImage::GetImageContainerAtSize(layers::LayerManager
* aManager
,
857 const gfx::IntSize
& aSize
,
858 const Maybe
<SVGImageContext
>& aSVGContext
,
860 layers::ImageContainer
** aOutContainer
) {
861 Maybe
<SVGImageContext
> newSVGContext
;
862 MaybeRestrictSVGContext(newSVGContext
, aSVGContext
, aFlags
);
864 // The aspect ratio flag was already handled as part of the SVG context
865 // restriction above.
866 uint32_t flags
= aFlags
& ~(FLAG_FORCE_PRESERVEASPECTRATIO_NONE
);
867 return GetImageContainerImpl(aManager
, aSize
,
868 newSVGContext
? newSVGContext
: aSVGContext
,
869 flags
, aOutContainer
);
872 bool VectorImage::MaybeRestrictSVGContext(
873 Maybe
<SVGImageContext
>& aNewSVGContext
,
874 const Maybe
<SVGImageContext
>& aSVGContext
, uint32_t aFlags
) {
876 (aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
) && aSVGContext
;
878 bool haveContextPaint
= aSVGContext
&& aSVGContext
->GetContextPaint();
879 bool blockContextPaint
= false;
880 if (haveContextPaint
) {
881 blockContextPaint
= !SVGContextPaint::IsAllowedForImageFromURI(mURI
);
884 if (overridePAR
|| blockContextPaint
) {
885 // The key that we create for the image surface cache must match the way
886 // that the image will be painted, so we need to initialize a new matching
887 // SVGImageContext here in order to generate the correct key.
889 aNewSVGContext
= aSVGContext
; // copy
892 // The SVGImageContext must take account of the preserveAspectRatio
894 MOZ_ASSERT(!aSVGContext
->GetPreserveAspectRatio(),
895 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
896 "preserveAspectRatio override is supplied");
897 Maybe
<SVGPreserveAspectRatio
> aspectRatio
= Some(SVGPreserveAspectRatio(
898 SVG_PRESERVEASPECTRATIO_NONE
, SVG_MEETORSLICE_UNKNOWN
));
899 aNewSVGContext
->SetPreserveAspectRatio(aspectRatio
);
902 if (blockContextPaint
) {
903 // The SVGImageContext must not include context paint if the image is
904 // not allowed to use it:
905 aNewSVGContext
->ClearContextPaint();
909 return haveContextPaint
&& !blockContextPaint
;
912 //******************************************************************************
913 NS_IMETHODIMP_(ImgDrawResult
)
914 VectorImage::Draw(gfxContext
* aContext
, const nsIntSize
& aSize
,
915 const ImageRegion
& aRegion
, uint32_t aWhichFrame
,
916 SamplingFilter aSamplingFilter
,
917 const Maybe
<SVGImageContext
>& aSVGContext
, uint32_t aFlags
,
919 if (aWhichFrame
> FRAME_MAX_VALUE
) {
920 return ImgDrawResult::BAD_ARGS
;
924 return ImgDrawResult::BAD_ARGS
;
928 return ImgDrawResult::BAD_IMAGE
;
931 if (!mIsFullyLoaded
) {
932 return ImgDrawResult::NOT_READY
;
935 if (mAnimationConsumers
== 0) {
936 SendOnUnlockedDraw(aFlags
);
939 // We should bypass the cache when:
940 // - We are using a DrawTargetRecording because we prefer the drawing commands
941 // in general to the rasterized surface. This allows blob images to avoid
942 // rasterized SVGs with WebRender.
943 // - The size exceeds what we are willing to cache as a rasterized surface.
944 // We don't do this for WebRender because the performance of the fallback
945 // path is quite bad and upscaling the SVG from the clamped size is better
946 // than bringing the browser to a crawl.
947 if (aContext
->GetDrawTarget()->GetBackendType() == BackendType::RECORDING
||
948 (!gfxVars::UseWebRender() &&
949 aSize
!= SurfaceCache::ClampVectorSize(aSize
))) {
950 aFlags
|= FLAG_BYPASS_SURFACE_CACHE
;
953 MOZ_ASSERT(!(aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
) ||
954 (aSVGContext
&& aSVGContext
->GetViewportSize()),
955 "Viewport size is required when using "
956 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
958 float animTime
= (aWhichFrame
== FRAME_FIRST
)
960 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
962 Maybe
<SVGImageContext
> newSVGContext
;
964 MaybeRestrictSVGContext(newSVGContext
, aSVGContext
, aFlags
);
966 SVGDrawingParameters
params(aContext
, aSize
, aSize
, aRegion
, aSamplingFilter
,
967 newSVGContext
? newSVGContext
: aSVGContext
,
968 animTime
, aFlags
, aOpacity
);
970 // If we have an prerasterized version of this image that matches the
971 // drawing parameters, use that.
972 RefPtr
<SourceSurface
> sourceSurface
;
973 Tie(sourceSurface
, params
.size
) =
974 LookupCachedSurface(aSize
, params
.svgContext
, aFlags
);
976 RefPtr
<gfxDrawable
> drawable
=
977 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
978 Show(drawable
, params
);
979 return ImgDrawResult::SUCCESS
;
982 // else, we need to paint the image:
985 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
986 return ImgDrawResult::TEMPORARY_ERROR
;
989 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, mIsDrawing
,
992 bool didCache
; // Was the surface put into the cache?
993 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
994 sourceSurface
= CreateSurface(params
, svgDrawable
, didCache
);
995 if (!sourceSurface
) {
996 MOZ_ASSERT(!didCache
);
997 Show(svgDrawable
, params
);
998 return ImgDrawResult::SUCCESS
;
1001 RefPtr
<gfxDrawable
> drawable
=
1002 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
1003 Show(drawable
, params
);
1004 SendFrameComplete(didCache
, params
.flags
);
1005 return ImgDrawResult::SUCCESS
;
1008 already_AddRefed
<gfxDrawable
> VectorImage::CreateSVGDrawable(
1009 const SVGDrawingParameters
& aParams
) {
1010 RefPtr
<gfxDrawingCallback
> cb
= new SVGDrawingCallback(
1011 mSVGDocumentWrapper
, aParams
.viewportSize
, aParams
.size
, aParams
.flags
);
1013 RefPtr
<gfxDrawable
> svgDrawable
= new gfxCallbackDrawable(cb
, aParams
.size
);
1014 return svgDrawable
.forget();
1017 Tuple
<RefPtr
<SourceSurface
>, IntSize
> VectorImage::LookupCachedSurface(
1018 const IntSize
& aSize
, const Maybe
<SVGImageContext
>& aSVGContext
,
1020 // If we're not allowed to use a cached surface, don't attempt a lookup.
1021 if (aFlags
& FLAG_BYPASS_SURFACE_CACHE
) {
1022 return MakeTuple(RefPtr
<SourceSurface
>(), aSize
);
1025 // We don't do any caching if we have animation, so don't bother with a lookup
1026 // in this case either.
1027 if (mHaveAnimations
) {
1028 return MakeTuple(RefPtr
<SourceSurface
>(), aSize
);
1031 LookupResult
result(MatchType::NOT_FOUND
);
1032 SurfaceKey surfaceKey
= VectorSurfaceKey(aSize
, aSVGContext
);
1033 if ((aFlags
& FLAG_SYNC_DECODE
) || !(aFlags
& FLAG_HIGH_QUALITY_SCALING
)) {
1034 result
= SurfaceCache::Lookup(ImageKey(this), surfaceKey
,
1035 /* aMarkUsed = */ true);
1037 result
= SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey
,
1038 /* aMarkUsed = */ true);
1041 IntSize rasterSize
=
1042 result
.SuggestedSize().IsEmpty() ? aSize
: result
.SuggestedSize();
1043 MOZ_ASSERT(result
.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING
);
1044 if (!result
|| result
.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND
) {
1045 // No matching surface, or the OS freed the volatile buffer.
1046 return MakeTuple(RefPtr
<SourceSurface
>(), rasterSize
);
1049 RefPtr
<SourceSurface
> sourceSurface
= result
.Surface()->GetSourceSurface();
1050 if (!sourceSurface
) {
1051 // Something went wrong. (Probably a GPU driver crash or device reset.)
1052 // Attempt to recover.
1053 RecoverFromLossOfSurfaces();
1054 return MakeTuple(RefPtr
<SourceSurface
>(), rasterSize
);
1057 return MakeTuple(std::move(sourceSurface
), rasterSize
);
1060 already_AddRefed
<SourceSurface
> VectorImage::CreateSurface(
1061 const SVGDrawingParameters
& aParams
, gfxDrawable
* aSVGDrawable
,
1063 MOZ_ASSERT(mIsDrawing
);
1065 mSVGDocumentWrapper
->UpdateViewportBounds(aParams
.viewportSize
);
1066 mSVGDocumentWrapper
->FlushImageTransformInvalidation();
1068 // Determine whether or not we should put the surface to be created into
1069 // the cache. If we fail, we need to reset this to false to let the caller
1070 // know nothing was put in the cache.
1071 aWillCache
= !(aParams
.flags
& FLAG_BYPASS_SURFACE_CACHE
) &&
1072 // Refuse to cache animated images:
1073 // XXX(seth): We may remove this restriction in bug 922893.
1075 // The image is too big to fit in the cache:
1076 SurfaceCache::CanHold(aParams
.size
);
1078 // If we weren't given a context, then we know we just want the rasterized
1079 // surface. We will create the frame below but only insert it into the cache
1080 // if we actually need to.
1081 if (!aWillCache
&& aParams
.context
) {
1085 // We're about to rerasterize, which may mean that some of the previous
1086 // surfaces we've rasterized aren't useful anymore. We can allow them to
1087 // expire from the cache by unlocking them here, and then sending out an
1088 // invalidation. If this image is locked, any surfaces that are still useful
1089 // will become locked again when Draw touches them, and the remainder will
1090 // eventually expire.
1092 SurfaceCache::UnlockEntries(ImageKey(this));
1095 // If there is no context, the default backend is fine.
1096 BackendType backend
=
1097 aParams
.context
? aParams
.context
->GetDrawTarget()->GetBackendType()
1098 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1100 // Try to create an imgFrame, initializing the surface it contains by drawing
1101 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1102 auto frame
= MakeNotNull
<RefPtr
<imgFrame
>>();
1103 nsresult rv
= frame
->InitWithDrawable(
1104 aSVGDrawable
, aParams
.size
, SurfaceFormat::B8G8R8A8
,
1105 SamplingFilter::POINT
, aParams
.flags
, backend
,
1106 aParams
.context
? aParams
.context
->GetDrawTarget() : nullptr);
1108 // If we couldn't create the frame, it was probably because it would end
1109 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1110 // could be set such that the cache isn't the limiting factor.
1111 if (NS_FAILED(rv
)) {
1116 // Take a strong reference to the frame's surface and make sure it hasn't
1117 // already been purged by the operating system.
1118 RefPtr
<SourceSurface
> surface
= frame
->GetSourceSurface();
1124 // We created the frame, but only because we had no context to draw to
1125 // directly. All the caller wants is the surface in this case.
1127 return surface
.forget();
1130 // Attempt to cache the frame.
1131 SurfaceKey surfaceKey
= VectorSurfaceKey(aParams
.size
, aParams
.svgContext
);
1132 NotNull
<RefPtr
<ISurfaceProvider
>> provider
=
1133 MakeNotNull
<SimpleSurfaceProvider
*>(ImageKey(this), surfaceKey
, frame
);
1135 if (SurfaceCache::Insert(provider
) == InsertOutcome::SUCCESS
&&
1136 aParams
.size
!= aParams
.drawSize
) {
1137 // We created a new surface that wasn't the size we requested, which means
1138 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1139 // need rather than waiting for the cache to expire them.
1140 SurfaceCache::PruneImage(ImageKey(this));
1143 return surface
.forget();
1146 void VectorImage::SendFrameComplete(bool aDidCache
, uint32_t aFlags
) {
1147 // If the cache was not updated, we have nothing to do.
1152 // Send out an invalidation so that surfaces that are still in use get
1153 // re-locked. See the discussion of the UnlockSurfaces call above.
1154 if (!(aFlags
& FLAG_ASYNC_NOTIFY
)) {
1155 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1156 GetMaxSizedIntRect());
1158 NotNull
<RefPtr
<VectorImage
>> image
= WrapNotNull(this);
1159 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1160 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1161 RefPtr
<ProgressTracker
> tracker
= image
->GetProgressTracker();
1163 tracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1164 GetMaxSizedIntRect());
1170 void VectorImage::Show(gfxDrawable
* aDrawable
,
1171 const SVGDrawingParameters
& aParams
) {
1172 // The surface size may differ from the size at which we wish to draw. As
1173 // such, we may need to adjust the context/region to take this into account.
1174 gfxContextMatrixAutoSaveRestore
saveMatrix(aParams
.context
);
1175 ImageRegion
region(aParams
.region
);
1176 if (aParams
.drawSize
!= aParams
.size
) {
1177 gfx::Size
scale(double(aParams
.drawSize
.width
) / aParams
.size
.width
,
1178 double(aParams
.drawSize
.height
) / aParams
.size
.height
);
1179 aParams
.context
->Multiply(gfxMatrix::Scaling(scale
.width
, scale
.height
));
1180 region
.Scale(1.0 / scale
.width
, 1.0 / scale
.height
);
1183 MOZ_ASSERT(aDrawable
, "Should have a gfxDrawable by now");
1184 gfxUtils::DrawPixelSnapped(aParams
.context
, aDrawable
,
1185 SizeDouble(aParams
.size
), region
,
1186 SurfaceFormat::B8G8R8A8
, aParams
.samplingFilter
,
1187 aParams
.flags
, aParams
.opacity
, false);
1190 NotifyDrawingObservers();
1193 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
1194 mRenderingObserver
->ResumeHonoringInvalidations();
1197 void VectorImage::RecoverFromLossOfSurfaces() {
1198 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1200 // Discard all existing frames, since they're probably all now invalid.
1201 SurfaceCache::RemoveImage(ImageKey(this));
1205 VectorImage::StartDecoding(uint32_t aFlags
, uint32_t aWhichFrame
) {
1206 // Nothing to do for SVG images
1210 bool VectorImage::StartDecodingWithResult(uint32_t aFlags
,
1211 uint32_t aWhichFrame
) {
1212 // SVG images are ready to draw when they are loaded
1213 return mIsFullyLoaded
;
1216 bool VectorImage::RequestDecodeWithResult(uint32_t aFlags
,
1217 uint32_t aWhichFrame
) {
1218 // SVG images are ready to draw when they are loaded
1219 return mIsFullyLoaded
;
1223 VectorImage::RequestDecodeForSize(const nsIntSize
& aSize
, uint32_t aFlags
,
1224 uint32_t aWhichFrame
) {
1225 // Nothing to do for SVG images, though in theory we could rasterize to the
1226 // provided size ahead of time if we supported off-main-thread SVG
1231 //******************************************************************************
1234 VectorImage::LockImage() {
1235 MOZ_ASSERT(NS_IsMainThread());
1238 return NS_ERROR_FAILURE
;
1243 if (mLockCount
== 1) {
1244 // Lock this image's surfaces in the SurfaceCache.
1245 SurfaceCache::LockImage(ImageKey(this));
1251 //******************************************************************************
1254 VectorImage::UnlockImage() {
1255 MOZ_ASSERT(NS_IsMainThread());
1258 return NS_ERROR_FAILURE
;
1261 if (mLockCount
== 0) {
1262 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1263 return NS_ERROR_ABORT
;
1268 if (mLockCount
== 0) {
1269 // Unlock this image's surfaces in the SurfaceCache.
1270 SurfaceCache::UnlockImage(ImageKey(this));
1276 //******************************************************************************
1279 VectorImage::RequestDiscard() {
1280 MOZ_ASSERT(NS_IsMainThread());
1282 if (mDiscardable
&& mLockCount
== 0) {
1283 SurfaceCache::RemoveImage(ImageKey(this));
1284 mProgressTracker
->OnDiscard();
1290 void VectorImage::OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) {
1291 MOZ_ASSERT(mProgressTracker
);
1293 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1295 &ProgressTracker::OnDiscard
));
1298 //******************************************************************************
1300 VectorImage::ResetAnimation() {
1302 return NS_ERROR_FAILURE
;
1305 if (!mIsFullyLoaded
|| !mHaveAnimations
) {
1306 return NS_OK
; // There are no animations to be reset.
1309 mSVGDocumentWrapper
->ResetAnimation();
1314 NS_IMETHODIMP_(float)
1315 VectorImage::GetFrameIndex(uint32_t aWhichFrame
) {
1316 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
, "Invalid argument");
1317 return aWhichFrame
== FRAME_FIRST
1319 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1322 //------------------------------------------------------------------------------
1323 // nsIRequestObserver methods
1325 //******************************************************************************
1327 VectorImage::OnStartRequest(nsIRequest
* aRequest
) {
1328 MOZ_ASSERT(!mSVGDocumentWrapper
,
1329 "Repeated call to OnStartRequest -- can this happen?");
1331 mSVGDocumentWrapper
= new SVGDocumentWrapper();
1332 nsresult rv
= mSVGDocumentWrapper
->OnStartRequest(aRequest
);
1333 if (NS_FAILED(rv
)) {
1334 mSVGDocumentWrapper
= nullptr;
1339 // Create a listener to wait until the SVG document is fully loaded, which
1340 // will signal that this image is ready to render. Certain error conditions
1341 // will prevent us from ever getting this notification, so we also create a
1342 // listener that waits for parsing to complete and cancels the
1343 // SVGLoadEventListener if needed. The listeners are automatically attached
1344 // to the document by their constructors.
1345 SVGDocument
* document
= mSVGDocumentWrapper
->GetDocument();
1346 mLoadEventListener
= new SVGLoadEventListener(document
, this);
1347 mParseCompleteListener
= new SVGParseCompleteListener(document
, this);
1352 //******************************************************************************
1354 VectorImage::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
1356 return NS_ERROR_FAILURE
;
1359 return mSVGDocumentWrapper
->OnStopRequest(aRequest
, aStatus
);
1362 void VectorImage::OnSVGDocumentParsed() {
1363 MOZ_ASSERT(mParseCompleteListener
, "Should have the parse complete listener");
1364 MOZ_ASSERT(mLoadEventListener
, "Should have the load event listener");
1366 if (!mSVGDocumentWrapper
->GetRootSVGElem()) {
1367 // This is an invalid SVG document. It may have failed to parse, or it may
1368 // be missing the <svg> root element, or the <svg> root element may not
1369 // declare the correct namespace. In any of these cases, we'll never be
1370 // notified that the SVG finished loading, so we need to treat this as an
1372 OnSVGDocumentError();
1376 void VectorImage::CancelAllListeners() {
1377 if (mParseCompleteListener
) {
1378 mParseCompleteListener
->Cancel();
1379 mParseCompleteListener
= nullptr;
1381 if (mLoadEventListener
) {
1382 mLoadEventListener
->Cancel();
1383 mLoadEventListener
= nullptr;
1387 void VectorImage::OnSVGDocumentLoaded() {
1388 MOZ_ASSERT(mSVGDocumentWrapper
->GetRootSVGElem(),
1389 "Should have parsed successfully");
1390 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
,
1391 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1392 "Duplicate calls to OnSVGDocumentLoaded?");
1394 CancelAllListeners();
1396 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1397 mSVGDocumentWrapper
->FlushLayout();
1399 mIsFullyLoaded
= true;
1400 mHaveAnimations
= mSVGDocumentWrapper
->IsAnimated();
1402 // Start listening to our image for rendering updates.
1403 mRenderingObserver
= new SVGRootRenderingObserver(mSVGDocumentWrapper
, this);
1405 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1406 // stick around long enough to complete our work.
1407 RefPtr
<VectorImage
> kungFuDeathGrip(this);
1409 // Tell *our* observers that we're done loading.
1410 if (mProgressTracker
) {
1411 Progress progress
= FLAG_SIZE_AVAILABLE
| FLAG_HAS_TRANSPARENCY
|
1412 FLAG_FRAME_COMPLETE
| FLAG_DECODE_COMPLETE
;
1414 if (mHaveAnimations
) {
1415 progress
|= FLAG_IS_ANIMATED
;
1418 // Merge in any saved progress from OnImageDataComplete.
1419 if (mLoadProgress
) {
1420 progress
|= *mLoadProgress
;
1421 mLoadProgress
= Nothing();
1424 mProgressTracker
->SyncNotifyProgress(progress
, GetMaxSizedIntRect());
1427 EvaluateAnimation();
1430 void VectorImage::OnSVGDocumentError() {
1431 CancelAllListeners();
1435 if (mProgressTracker
) {
1436 // Notify observers about the error and unblock page load.
1437 Progress progress
= FLAG_HAS_ERROR
;
1439 // Merge in any saved progress from OnImageDataComplete.
1440 if (mLoadProgress
) {
1441 progress
|= *mLoadProgress
;
1442 mLoadProgress
= Nothing();
1445 mProgressTracker
->SyncNotifyProgress(progress
);
1449 //------------------------------------------------------------------------------
1450 // nsIStreamListener method
1452 //******************************************************************************
1454 VectorImage::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
1455 uint64_t aSourceOffset
, uint32_t aCount
) {
1457 return NS_ERROR_FAILURE
;
1460 return mSVGDocumentWrapper
->OnDataAvailable(aRequest
, aInStr
, aSourceOffset
,
1464 // --------------------------
1465 // Invalidation helper method
1467 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1468 if (mHasPendingInvalidation
) {
1472 mHasPendingInvalidation
= true;
1474 // Animated images can wait for the refresh tick.
1475 if (mHaveAnimations
) {
1479 // Non-animated images won't get the refresh tick, so we should just send an
1480 // invalidation outside the current execution context. We need to defer
1481 // because the layout tree is in the middle of invalidation, and the tree
1482 // state needs to be consistent. Specifically only some of the frames have
1483 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1484 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1485 // get cleared when we repaint the SVG into a surface by
1486 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1487 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1488 if (mProgressTracker
) {
1489 eventTarget
= mProgressTracker
->GetEventTarget();
1491 eventTarget
= do_GetMainThread();
1494 RefPtr
<VectorImage
> self(this);
1495 nsCOMPtr
<nsIRunnable
> ev(NS_NewRunnableFunction(
1496 "VectorImage::SendInvalidationNotifications",
1497 [=]() -> void { self
->SendInvalidationNotifications(); }));
1498 eventTarget
->Dispatch(CreateMediumHighRunnable(ev
.forget()),
1499 NS_DISPATCH_NORMAL
);
1502 void VectorImage::PropagateUseCounters(Document
* aParentDocument
) {
1503 Document
* doc
= mSVGDocumentWrapper
->GetDocument();
1505 doc
->PropagateUseCounters(aParentDocument
);
1509 void VectorImage::ReportUseCounters() {
1510 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1511 doc
->ReportUseCounters();
1515 nsIntSize
VectorImage::OptimalImageSizeForDest(const gfxSize
& aDest
,
1516 uint32_t aWhichFrame
,
1517 SamplingFilter aSamplingFilter
,
1519 MOZ_ASSERT(aDest
.width
>= 0 || ceil(aDest
.width
) <= INT32_MAX
||
1520 aDest
.height
>= 0 || ceil(aDest
.height
) <= INT32_MAX
,
1521 "Unexpected destination size");
1523 // We can rescale SVGs freely, so just return the provided destination size.
1524 return nsIntSize::Ceil(aDest
.width
, aDest
.height
);
1527 already_AddRefed
<imgIContainer
> VectorImage::Unwrap() {
1528 nsCOMPtr
<imgIContainer
> self(this);
1529 return self
.forget();
1532 } // namespace image
1533 } // namespace mozilla