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"
42 #include "mozilla/dom/DocumentInlines.h"
47 using namespace dom::SVGPreserveAspectRatio_Binding
;
49 using namespace layers
;
53 // Helper-class: SVGRootRenderingObserver
54 class SVGRootRenderingObserver final
: public SVGRenderingObserver
{
58 SVGRootRenderingObserver(SVGDocumentWrapper
* aDocWrapper
,
59 VectorImage
* aVectorImage
)
60 : SVGRenderingObserver(),
61 mDocWrapper(aDocWrapper
),
62 mVectorImage(aVectorImage
),
63 mHonoringInvalidations(true) {
64 MOZ_ASSERT(mDocWrapper
, "Need a non-null SVG document wrapper");
65 MOZ_ASSERT(mVectorImage
, "Need a non-null VectorImage");
68 Element
* elem
= GetReferencedElementWithoutObserving();
69 MOZ_ASSERT(elem
, "no root SVG node for us to observe");
71 SVGObserverUtils::AddRenderingObserver(elem
, this);
72 mInObserverSet
= true;
75 void ResumeHonoringInvalidations() { mHonoringInvalidations
= true; }
78 virtual ~SVGRootRenderingObserver() {
79 // This needs to call our GetReferencedElementWithoutObserving override,
80 // so must be called here rather than in our base class's dtor.
84 Element
* GetReferencedElementWithoutObserving() final
{
85 return mDocWrapper
->GetRootSVGElem();
88 virtual void OnRenderingChange() override
{
89 Element
* elem
= GetReferencedElementWithoutObserving();
90 MOZ_ASSERT(elem
, "missing root SVG node");
92 if (mHonoringInvalidations
&& !mDocWrapper
->ShouldIgnoreInvalidation()) {
93 nsIFrame
* frame
= elem
->GetPrimaryFrame();
94 if (!frame
|| frame
->PresShell()->IsDestroying()) {
95 // We're being destroyed. Bail out.
99 // Ignore further invalidations until we draw.
100 mHonoringInvalidations
= false;
102 mVectorImage
->InvalidateObserversOnNextRefreshDriverTick();
105 // Our caller might've removed us from rendering-observer list.
106 // Add ourselves back!
107 if (!mInObserverSet
) {
108 SVGObserverUtils::AddRenderingObserver(elem
, this);
109 mInObserverSet
= true;
114 const RefPtr
<SVGDocumentWrapper
> mDocWrapper
;
115 VectorImage
* const mVectorImage
; // Raw pointer because it owns me.
116 bool mHonoringInvalidations
;
119 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver
, nsIMutationObserver
)
121 class SVGParseCompleteListener final
: public nsStubDocumentObserver
{
125 SVGParseCompleteListener(SVGDocument
* aDocument
, VectorImage
* aImage
)
126 : mDocument(aDocument
), mImage(aImage
) {
127 MOZ_ASSERT(mDocument
, "Need an SVG document");
128 MOZ_ASSERT(mImage
, "Need an image");
130 mDocument
->AddObserver(this);
134 ~SVGParseCompleteListener() {
136 // The document must have been destroyed before we got our event.
137 // Otherwise this can't happen, since documents hold strong references to
144 void EndLoad(Document
* aDocument
) override
{
145 MOZ_ASSERT(aDocument
== mDocument
, "Got EndLoad for wrong document?");
147 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
148 // we stick around long enough to complete our work.
149 RefPtr
<SVGParseCompleteListener
> kungFuDeathGrip(this);
151 mImage
->OnSVGDocumentParsed();
155 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
157 mDocument
->RemoveObserver(this);
163 RefPtr
<SVGDocument
> mDocument
;
164 VectorImage
* const mImage
; // Raw pointer to owner.
167 NS_IMPL_ISUPPORTS(SVGParseCompleteListener
, nsIDocumentObserver
)
169 class SVGLoadEventListener final
: public nsIDOMEventListener
{
173 SVGLoadEventListener(Document
* aDocument
, VectorImage
* aImage
)
174 : mDocument(aDocument
), mImage(aImage
) {
175 MOZ_ASSERT(mDocument
, "Need an SVG document");
176 MOZ_ASSERT(mImage
, "Need an image");
178 mDocument
->AddEventListener(NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"),
180 mDocument
->AddEventListener(NS_LITERAL_STRING("SVGAbort"), this, true,
182 mDocument
->AddEventListener(NS_LITERAL_STRING("SVGError"), this, true,
187 ~SVGLoadEventListener() {
189 // The document must have been destroyed before we got our event.
190 // Otherwise this can't happen, since documents hold strong references to
197 NS_IMETHOD
HandleEvent(Event
* aEvent
) override
{
198 MOZ_ASSERT(mDocument
, "Need an SVG document. Received multiple events?");
200 // OnSVGDocumentLoaded/OnSVGDocumentError will release our owner's reference
201 // to us, so ensure we stick around long enough to complete our work.
202 RefPtr
<SVGLoadEventListener
> kungFuDeathGrip(this);
204 nsAutoString eventType
;
205 aEvent
->GetType(eventType
);
206 MOZ_ASSERT(eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad") ||
207 eventType
.EqualsLiteral("SVGAbort") ||
208 eventType
.EqualsLiteral("SVGError"),
209 "Received unexpected event");
211 if (eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad")) {
212 mImage
->OnSVGDocumentLoaded();
214 mImage
->OnSVGDocumentError();
221 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
223 mDocument
->RemoveEventListener(
224 NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), this, true);
225 mDocument
->RemoveEventListener(NS_LITERAL_STRING("SVGAbort"), this, true);
226 mDocument
->RemoveEventListener(NS_LITERAL_STRING("SVGError"), this, true);
232 nsCOMPtr
<Document
> mDocument
;
233 VectorImage
* const mImage
; // Raw pointer to owner.
236 NS_IMPL_ISUPPORTS(SVGLoadEventListener
, nsIDOMEventListener
)
238 // Helper-class: SVGDrawingCallback
239 class SVGDrawingCallback
: public gfxDrawingCallback
{
241 SVGDrawingCallback(SVGDocumentWrapper
* aSVGDocumentWrapper
,
242 const IntSize
& aViewportSize
, const IntSize
& aSize
,
243 uint32_t aImageFlags
)
244 : mSVGDocumentWrapper(aSVGDocumentWrapper
),
245 mViewportSize(aViewportSize
),
247 mImageFlags(aImageFlags
) {}
248 virtual bool operator()(gfxContext
* aContext
, const gfxRect
& aFillRect
,
249 const SamplingFilter aSamplingFilter
,
250 const gfxMatrix
& aTransform
) override
;
253 RefPtr
<SVGDocumentWrapper
> mSVGDocumentWrapper
;
254 const IntSize mViewportSize
;
256 uint32_t mImageFlags
;
259 // Based loosely on nsSVGIntegrationUtils' PaintFrameCallback::operator()
260 bool SVGDrawingCallback::operator()(gfxContext
* aContext
,
261 const gfxRect
& aFillRect
,
262 const SamplingFilter aSamplingFilter
,
263 const gfxMatrix
& aTransform
) {
264 MOZ_ASSERT(mSVGDocumentWrapper
, "need an SVGDocumentWrapper");
266 // Get (& sanity-check) the helper-doc's presShell
267 RefPtr
<PresShell
> presShell
= mSVGDocumentWrapper
->GetPresShell();
268 MOZ_ASSERT(presShell
, "GetPresShell returned null for an SVG image?");
270 #ifdef MOZ_GECKO_PROFILER
271 Document
* doc
= presShell
->GetDocument();
272 nsIURI
* uri
= doc
? doc
->GetDocumentURI() : nullptr;
273 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
274 "SVG Image drawing", GRAPHICS
,
275 nsPrintfCString("%dx%d %s", mSize
.width
, mSize
.height
,
276 uri
? uri
->GetSpecOrDefault().get() : "N/A"));
279 gfxContextAutoSaveRestore
contextRestorer(aContext
);
281 // Clip to aFillRect so that we don't paint outside.
283 aContext
->Rectangle(aFillRect
);
286 gfxMatrix matrix
= aTransform
;
287 if (!matrix
.Invert()) {
290 aContext
->SetMatrixDouble(
291 aContext
->CurrentMatrixDouble().PreMultiply(matrix
).PreScale(
292 double(mSize
.width
) / mViewportSize
.width
,
293 double(mSize
.height
) / mViewportSize
.height
));
295 nsPresContext
* presContext
= presShell
->GetPresContext();
296 MOZ_ASSERT(presContext
, "pres shell w/out pres context");
298 nsRect
svgRect(0, 0, presContext
->DevPixelsToAppUnits(mViewportSize
.width
),
299 presContext
->DevPixelsToAppUnits(mViewportSize
.height
));
301 RenderDocumentFlags renderDocFlags
=
302 RenderDocumentFlags::IgnoreViewportScrolling
;
303 if (!(mImageFlags
& imgIContainer::FLAG_SYNC_DECODE
)) {
304 renderDocFlags
|= RenderDocumentFlags::AsyncDecodeImages
;
307 presShell
->RenderDocument(svgRect
, renderDocFlags
,
308 NS_RGBA(0, 0, 0, 0), // transparent
314 class MOZ_STACK_CLASS AutoRestoreSVGState final
{
316 AutoRestoreSVGState(const SVGDrawingParameters
& aParams
,
317 SVGDocumentWrapper
* aSVGDocumentWrapper
, bool& aIsDrawing
,
319 : mIsDrawing(aIsDrawing
)
320 // Apply any 'preserveAspectRatio' override (if specified) to the root
323 mPAR(aParams
.svgContext
, aSVGDocumentWrapper
->GetRootSVGElem())
324 // Set the animation time:
326 mTime(aSVGDocumentWrapper
->GetRootSVGElem(), aParams
.animationTime
) {
327 MOZ_ASSERT(!aIsDrawing
);
328 MOZ_ASSERT(aSVGDocumentWrapper
->GetDocument());
332 // Set context paint (if specified) on the document:
334 MOZ_ASSERT(aParams
.svgContext
->GetContextPaint());
335 mContextPaint
.emplace(*aParams
.svgContext
->GetContextPaint(),
336 *aSVGDocumentWrapper
->GetDocument());
341 AutoRestore
<bool> mIsDrawing
;
342 AutoPreserveAspectRatioOverride mPAR
;
343 AutoSVGTimeSetRestore mTime
;
344 Maybe
<AutoSetRestoreSVGContextPaint
> mContextPaint
;
347 // Implement VectorImage's nsISupports-inherited methods
348 NS_IMPL_ISUPPORTS(VectorImage
, imgIContainer
, nsIStreamListener
,
351 //------------------------------------------------------------------------------
352 // Constructor / Destructor
354 VectorImage::VectorImage(nsIURI
* aURI
/* = nullptr */)
355 : ImageResource(aURI
), // invoke superclass's constructor
357 mIsInitialized(false),
359 mIsFullyLoaded(false),
361 mHaveAnimations(false),
362 mHasPendingInvalidation(false) {}
364 VectorImage::~VectorImage() {
365 CancelAllListeners();
366 SurfaceCache::RemoveImage(ImageKey(this));
369 //------------------------------------------------------------------------------
370 // Methods inherited from Image.h
372 nsresult
VectorImage::Init(const char* aMimeType
, uint32_t aFlags
) {
373 // We don't support re-initialization
374 if (mIsInitialized
) {
375 return NS_ERROR_ILLEGAL_VALUE
;
378 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
&& !mError
,
379 "Flags unexpectedly set before initialization");
380 MOZ_ASSERT(!strcmp(aMimeType
, IMAGE_SVG_XML
), "Unexpected mimetype");
382 mDiscardable
= !!(aFlags
& INIT_FLAG_DISCARDABLE
);
384 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
387 SurfaceCache::LockImage(ImageKey(this));
390 mIsInitialized
= true;
394 size_t VectorImage::SizeOfSourceWithComputedFallback(
395 SizeOfState
& aState
) const {
396 if (!mSVGDocumentWrapper
) {
397 return 0; // No document, so no memory used for the document.
400 SVGDocument
* doc
= mSVGDocumentWrapper
->GetDocument();
402 return 0; // No document, so no memory used for the document.
405 nsWindowSizes
windowSizes(aState
);
406 doc
->DocAddSizeOfIncludingThis(windowSizes
);
408 if (windowSizes
.getTotalSize() == 0) {
409 // MallocSizeOf fails on this platform. Because we also use this method for
410 // determining the size of cache entries, we need to return something
411 // reasonable here. Unfortunately, there's no way to estimate the document's
412 // size accurately, so we just use a constant value of 100KB, which will
413 // generally underestimate the true size.
417 return windowSizes
.getTotalSize();
420 void VectorImage::CollectSizeOfSurfaces(
421 nsTArray
<SurfaceMemoryCounter
>& aCounters
,
422 MallocSizeOf aMallocSizeOf
) const {
423 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters
, aMallocSizeOf
);
426 nsresult
VectorImage::OnImageDataComplete(nsIRequest
* aRequest
,
427 nsISupports
* aContext
,
428 nsresult aStatus
, bool aLastPart
) {
429 // Call our internal OnStopRequest method, which only talks to our embedded
430 // SVG document. This won't have any effect on our ProgressTracker.
431 nsresult finalStatus
= OnStopRequest(aRequest
, aStatus
);
433 // Give precedence to Necko failure codes.
434 if (NS_FAILED(aStatus
)) {
435 finalStatus
= aStatus
;
438 Progress loadProgress
= LoadCompleteProgress(aLastPart
, mError
, finalStatus
);
440 if (mIsFullyLoaded
|| mError
) {
441 // Our document is loaded, so we're ready to notify now.
442 mProgressTracker
->SyncNotifyProgress(loadProgress
);
444 // Record our progress so far; we'll actually send the notifications in
445 // OnSVGDocumentLoaded or OnSVGDocumentError.
446 mLoadProgress
= Some(loadProgress
);
452 nsresult
VectorImage::OnImageDataAvailable(nsIRequest
* aRequest
,
453 nsISupports
* aContext
,
454 nsIInputStream
* aInStr
,
455 uint64_t aSourceOffset
,
457 return OnDataAvailable(aRequest
, aInStr
, aSourceOffset
, aCount
);
460 nsresult
VectorImage::StartAnimation() {
462 return NS_ERROR_FAILURE
;
465 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
467 mSVGDocumentWrapper
->StartAnimation();
471 nsresult
VectorImage::StopAnimation() {
474 rv
= NS_ERROR_FAILURE
;
476 MOZ_ASSERT(mIsFullyLoaded
&& mHaveAnimations
,
477 "Should not have been animating!");
479 mSVGDocumentWrapper
->StopAnimation();
486 bool VectorImage::ShouldAnimate() {
487 return ImageResource::ShouldAnimate() && mIsFullyLoaded
&& mHaveAnimations
;
491 VectorImage::SetAnimationStartTime(const TimeStamp
& aTime
) {
492 // We don't care about animation start time.
495 //------------------------------------------------------------------------------
496 // imgIContainer methods
498 //******************************************************************************
500 VectorImage::GetWidth(int32_t* aWidth
) {
501 if (mError
|| !mIsFullyLoaded
) {
502 // XXXdholbert Technically we should leave outparam untouched when we
503 // fail. But since many callers don't check for failure, we set it to 0 on
504 // failure, for sane/predictable results.
506 return NS_ERROR_FAILURE
;
509 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
511 "Should have a root SVG elem, since we finished "
512 "loading without errors");
513 int32_t rootElemWidth
= rootElem
->GetIntrinsicWidth();
514 if (rootElemWidth
< 0) {
516 return NS_ERROR_FAILURE
;
518 *aWidth
= rootElemWidth
;
522 //******************************************************************************
523 nsresult
VectorImage::GetNativeSizes(nsTArray
<IntSize
>& aNativeSizes
) const {
524 return NS_ERROR_NOT_IMPLEMENTED
;
527 //******************************************************************************
528 size_t VectorImage::GetNativeSizesLength() const { return 0; }
530 //******************************************************************************
532 VectorImage::RequestRefresh(const TimeStamp
& aTime
) {
533 if (HadRecentRefresh(aTime
)) {
537 PendingAnimationTracker
* tracker
=
538 mSVGDocumentWrapper
->GetDocument()->GetPendingAnimationTracker();
539 if (tracker
&& ShouldAnimate()) {
540 tracker
->TriggerPendingAnimationsOnNextTick(aTime
);
545 mSVGDocumentWrapper
->TickRefreshDriver();
547 if (mHasPendingInvalidation
) {
548 SendInvalidationNotifications();
552 void VectorImage::SendInvalidationNotifications() {
553 // Animated images don't send out invalidation notifications as soon as
554 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
555 // records that there are pending invalidations and then returns immediately.
556 // The notifications are actually sent from RequestRefresh(). We send these
557 // notifications there to ensure that there is actually a document observing
558 // us. Otherwise, the notifications are just wasted effort.
560 // Non-animated images post an event to call this method from
561 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
562 // called for them. Ordinarily this isn't needed, since we send out
563 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
564 // SVG document may not be 100% ready to render at that time. In those cases
565 // we would miss the subsequent invalidations if we didn't send out the
566 // notifications indirectly in |InvalidateObservers...|.
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::OS_RGBA
, SamplingFilter::POINT
,
1105 aParams
.flags
, backend
);
1107 // If we couldn't create the frame, it was probably because it would end
1108 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1109 // could be set such that the cache isn't the limiting factor.
1110 if (NS_FAILED(rv
)) {
1115 // Take a strong reference to the frame's surface and make sure it hasn't
1116 // already been purged by the operating system.
1117 RefPtr
<SourceSurface
> surface
= frame
->GetSourceSurface();
1123 // We created the frame, but only because we had no context to draw to
1124 // directly. All the caller wants is the surface in this case.
1126 return surface
.forget();
1129 // Attempt to cache the frame.
1130 SurfaceKey surfaceKey
= VectorSurfaceKey(aParams
.size
, aParams
.svgContext
);
1131 NotNull
<RefPtr
<ISurfaceProvider
>> provider
=
1132 MakeNotNull
<SimpleSurfaceProvider
*>(ImageKey(this), surfaceKey
, frame
);
1134 if (SurfaceCache::Insert(provider
) == InsertOutcome::SUCCESS
&&
1135 aParams
.size
!= aParams
.drawSize
) {
1136 // We created a new surface that wasn't the size we requested, which means
1137 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1138 // need rather than waiting for the cache to expire them.
1139 SurfaceCache::PruneImage(ImageKey(this));
1142 return surface
.forget();
1145 void VectorImage::SendFrameComplete(bool aDidCache
, uint32_t aFlags
) {
1146 // If the cache was not updated, we have nothing to do.
1151 // Send out an invalidation so that surfaces that are still in use get
1152 // re-locked. See the discussion of the UnlockSurfaces call above.
1153 if (!(aFlags
& FLAG_ASYNC_NOTIFY
)) {
1154 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1155 GetMaxSizedIntRect());
1157 NotNull
<RefPtr
<VectorImage
>> image
= WrapNotNull(this);
1158 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1159 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1160 RefPtr
<ProgressTracker
> tracker
= image
->GetProgressTracker();
1162 tracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1163 GetMaxSizedIntRect());
1169 void VectorImage::Show(gfxDrawable
* aDrawable
,
1170 const SVGDrawingParameters
& aParams
) {
1171 // The surface size may differ from the size at which we wish to draw. As
1172 // such, we may need to adjust the context/region to take this into account.
1173 gfxContextMatrixAutoSaveRestore
saveMatrix(aParams
.context
);
1174 ImageRegion
region(aParams
.region
);
1175 if (aParams
.drawSize
!= aParams
.size
) {
1176 gfx::Size
scale(double(aParams
.drawSize
.width
) / aParams
.size
.width
,
1177 double(aParams
.drawSize
.height
) / aParams
.size
.height
);
1178 aParams
.context
->Multiply(gfxMatrix::Scaling(scale
.width
, scale
.height
));
1179 region
.Scale(1.0 / scale
.width
, 1.0 / scale
.height
);
1182 MOZ_ASSERT(aDrawable
, "Should have a gfxDrawable by now");
1183 gfxUtils::DrawPixelSnapped(aParams
.context
, aDrawable
,
1184 SizeDouble(aParams
.size
), region
,
1185 SurfaceFormat::OS_RGBA
, aParams
.samplingFilter
,
1186 aParams
.flags
, aParams
.opacity
, false);
1189 NotifyDrawingObservers();
1192 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
1193 mRenderingObserver
->ResumeHonoringInvalidations();
1196 void VectorImage::RecoverFromLossOfSurfaces() {
1197 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1199 // Discard all existing frames, since they're probably all now invalid.
1200 SurfaceCache::RemoveImage(ImageKey(this));
1204 VectorImage::StartDecoding(uint32_t aFlags
, uint32_t aWhichFrame
) {
1205 // Nothing to do for SVG images
1209 bool VectorImage::StartDecodingWithResult(uint32_t aFlags
,
1210 uint32_t aWhichFrame
) {
1211 // SVG images are ready to draw when they are loaded
1212 return mIsFullyLoaded
;
1215 bool VectorImage::RequestDecodeWithResult(uint32_t aFlags
,
1216 uint32_t aWhichFrame
) {
1217 // SVG images are ready to draw when they are loaded
1218 return mIsFullyLoaded
;
1222 VectorImage::RequestDecodeForSize(const nsIntSize
& aSize
, uint32_t aFlags
,
1223 uint32_t aWhichFrame
) {
1224 // Nothing to do for SVG images, though in theory we could rasterize to the
1225 // provided size ahead of time if we supported off-main-thread SVG
1230 //******************************************************************************
1233 VectorImage::LockImage() {
1234 MOZ_ASSERT(NS_IsMainThread());
1237 return NS_ERROR_FAILURE
;
1242 if (mLockCount
== 1) {
1243 // Lock this image's surfaces in the SurfaceCache.
1244 SurfaceCache::LockImage(ImageKey(this));
1250 //******************************************************************************
1253 VectorImage::UnlockImage() {
1254 MOZ_ASSERT(NS_IsMainThread());
1257 return NS_ERROR_FAILURE
;
1260 if (mLockCount
== 0) {
1261 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1262 return NS_ERROR_ABORT
;
1267 if (mLockCount
== 0) {
1268 // Unlock this image's surfaces in the SurfaceCache.
1269 SurfaceCache::UnlockImage(ImageKey(this));
1275 //******************************************************************************
1278 VectorImage::RequestDiscard() {
1279 MOZ_ASSERT(NS_IsMainThread());
1281 if (mDiscardable
&& mLockCount
== 0) {
1282 SurfaceCache::RemoveImage(ImageKey(this));
1283 mProgressTracker
->OnDiscard();
1287 mSVGDocumentWrapper
? mSVGDocumentWrapper
->GetDocument() : nullptr) {
1288 doc
->ReportUseCounters();
1294 void VectorImage::OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) {
1295 MOZ_ASSERT(mProgressTracker
);
1297 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1299 &ProgressTracker::OnDiscard
));
1302 //******************************************************************************
1304 VectorImage::ResetAnimation() {
1306 return NS_ERROR_FAILURE
;
1309 if (!mIsFullyLoaded
|| !mHaveAnimations
) {
1310 return NS_OK
; // There are no animations to be reset.
1313 mSVGDocumentWrapper
->ResetAnimation();
1318 NS_IMETHODIMP_(float)
1319 VectorImage::GetFrameIndex(uint32_t aWhichFrame
) {
1320 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
, "Invalid argument");
1321 return aWhichFrame
== FRAME_FIRST
1323 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1326 //------------------------------------------------------------------------------
1327 // nsIRequestObserver methods
1329 //******************************************************************************
1331 VectorImage::OnStartRequest(nsIRequest
* aRequest
) {
1332 MOZ_ASSERT(!mSVGDocumentWrapper
,
1333 "Repeated call to OnStartRequest -- can this happen?");
1335 mSVGDocumentWrapper
= new SVGDocumentWrapper();
1336 nsresult rv
= mSVGDocumentWrapper
->OnStartRequest(aRequest
);
1337 if (NS_FAILED(rv
)) {
1338 mSVGDocumentWrapper
= nullptr;
1343 // Create a listener to wait until the SVG document is fully loaded, which
1344 // will signal that this image is ready to render. Certain error conditions
1345 // will prevent us from ever getting this notification, so we also create a
1346 // listener that waits for parsing to complete and cancels the
1347 // SVGLoadEventListener if needed. The listeners are automatically attached
1348 // to the document by their constructors.
1349 SVGDocument
* document
= mSVGDocumentWrapper
->GetDocument();
1350 mLoadEventListener
= new SVGLoadEventListener(document
, this);
1351 mParseCompleteListener
= new SVGParseCompleteListener(document
, this);
1356 //******************************************************************************
1358 VectorImage::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
1360 return NS_ERROR_FAILURE
;
1363 return mSVGDocumentWrapper
->OnStopRequest(aRequest
, aStatus
);
1366 void VectorImage::OnSVGDocumentParsed() {
1367 MOZ_ASSERT(mParseCompleteListener
, "Should have the parse complete listener");
1368 MOZ_ASSERT(mLoadEventListener
, "Should have the load event listener");
1370 if (!mSVGDocumentWrapper
->GetRootSVGElem()) {
1371 // This is an invalid SVG document. It may have failed to parse, or it may
1372 // be missing the <svg> root element, or the <svg> root element may not
1373 // declare the correct namespace. In any of these cases, we'll never be
1374 // notified that the SVG finished loading, so we need to treat this as an
1376 OnSVGDocumentError();
1380 void VectorImage::CancelAllListeners() {
1381 if (mParseCompleteListener
) {
1382 mParseCompleteListener
->Cancel();
1383 mParseCompleteListener
= nullptr;
1385 if (mLoadEventListener
) {
1386 mLoadEventListener
->Cancel();
1387 mLoadEventListener
= nullptr;
1391 void VectorImage::OnSVGDocumentLoaded() {
1392 MOZ_ASSERT(mSVGDocumentWrapper
->GetRootSVGElem(),
1393 "Should have parsed successfully");
1394 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
,
1395 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1396 "Duplicate calls to OnSVGDocumentLoaded?");
1398 CancelAllListeners();
1400 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1401 mSVGDocumentWrapper
->FlushLayout();
1403 mIsFullyLoaded
= true;
1404 mHaveAnimations
= mSVGDocumentWrapper
->IsAnimated();
1406 // Start listening to our image for rendering updates.
1407 mRenderingObserver
= new SVGRootRenderingObserver(mSVGDocumentWrapper
, this);
1409 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1410 // stick around long enough to complete our work.
1411 RefPtr
<VectorImage
> kungFuDeathGrip(this);
1413 // Tell *our* observers that we're done loading.
1414 if (mProgressTracker
) {
1415 Progress progress
= FLAG_SIZE_AVAILABLE
| FLAG_HAS_TRANSPARENCY
|
1416 FLAG_FRAME_COMPLETE
| FLAG_DECODE_COMPLETE
;
1418 if (mHaveAnimations
) {
1419 progress
|= FLAG_IS_ANIMATED
;
1422 // Merge in any saved progress from OnImageDataComplete.
1423 if (mLoadProgress
) {
1424 progress
|= *mLoadProgress
;
1425 mLoadProgress
= Nothing();
1428 mProgressTracker
->SyncNotifyProgress(progress
, GetMaxSizedIntRect());
1431 EvaluateAnimation();
1434 void VectorImage::OnSVGDocumentError() {
1435 CancelAllListeners();
1439 if (mProgressTracker
) {
1440 // Notify observers about the error and unblock page load.
1441 Progress progress
= FLAG_HAS_ERROR
;
1443 // Merge in any saved progress from OnImageDataComplete.
1444 if (mLoadProgress
) {
1445 progress
|= *mLoadProgress
;
1446 mLoadProgress
= Nothing();
1449 mProgressTracker
->SyncNotifyProgress(progress
);
1453 //------------------------------------------------------------------------------
1454 // nsIStreamListener method
1456 //******************************************************************************
1458 VectorImage::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
1459 uint64_t aSourceOffset
, uint32_t aCount
) {
1461 return NS_ERROR_FAILURE
;
1464 return mSVGDocumentWrapper
->OnDataAvailable(aRequest
, aInStr
, aSourceOffset
,
1468 // --------------------------
1469 // Invalidation helper method
1471 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1472 if (mHasPendingInvalidation
) {
1476 mHasPendingInvalidation
= true;
1478 // Animated images can wait for the refresh tick.
1479 if (mHaveAnimations
) {
1483 // Non-animated images won't get the refresh tick, so we should just send an
1484 // invalidation outside the current execution context. We need to defer
1485 // because the layout tree is in the middle of invalidation, and the tree
1486 // state needs to be consistent. Specifically only some of the frames have
1487 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1488 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1489 // get cleared when we repaint the SVG into a surface by
1490 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1491 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1492 if (mProgressTracker
) {
1493 eventTarget
= mProgressTracker
->GetEventTarget();
1495 eventTarget
= do_GetMainThread();
1498 RefPtr
<VectorImage
> self(this);
1499 nsCOMPtr
<nsIRunnable
> ev(NS_NewRunnableFunction(
1500 "VectorImage::SendInvalidationNotifications",
1501 [=]() -> void { self
->SendInvalidationNotifications(); }));
1502 eventTarget
->Dispatch(CreateMediumHighRunnable(ev
.forget()),
1503 NS_DISPATCH_NORMAL
);
1506 void VectorImage::PropagateUseCounters(Document
* aParentDocument
) {
1507 Document
* doc
= mSVGDocumentWrapper
->GetDocument();
1509 doc
->PropagateUseCounters(aParentDocument
);
1513 nsIntSize
VectorImage::OptimalImageSizeForDest(const gfxSize
& aDest
,
1514 uint32_t aWhichFrame
,
1515 SamplingFilter aSamplingFilter
,
1517 MOZ_ASSERT(aDest
.width
>= 0 || ceil(aDest
.width
) <= INT32_MAX
||
1518 aDest
.height
>= 0 || ceil(aDest
.height
) <= INT32_MAX
,
1519 "Unexpected destination size");
1521 // We can rescale SVGs freely, so just return the provided destination size.
1522 return nsIntSize::Ceil(aDest
.width
, aDest
.height
);
1525 already_AddRefed
<imgIContainer
> VectorImage::Unwrap() {
1526 nsCOMPtr
<imgIContainer
> self(this);
1527 return self
.forget();
1530 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1531 const MediaFeatureChange
& aChange
) {
1532 if (!mSVGDocumentWrapper
) {
1536 // Don't bother if the document hasn't loaded yet.
1537 if (!mIsFullyLoaded
) {
1541 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1542 if (nsPresContext
* presContext
= doc
->GetPresContext()) {
1543 presContext
->MediaFeatureValuesChangedAllDocuments(aChange
);
1544 // Media feature value changes don't happen in the middle of layout,
1545 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1546 // to invalidate asynchronously.
1548 // Ideally we would not invalidate images if the media feature value
1549 // change did not cause any updates to the document, but since non-
1550 // animated SVG images do not have their refresh driver ticked, it
1551 // is the invalidation (and then the painting) which is what causes
1552 // the document to be flushed. Theme and system metrics changes are
1553 // rare, though, so it's not a big deal to invalidate even if it
1554 // doesn't cause any change.
1555 SendInvalidationNotifications();
1560 } // namespace image
1561 } // namespace mozilla