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/MediaFeatureChange.h"
17 #include "mozilla/dom/Event.h"
18 #include "mozilla/dom/SVGSVGElement.h"
19 #include "mozilla/dom/SVGDocument.h"
20 #include "mozilla/gfx/2D.h"
21 #include "mozilla/gfx/gfxVars.h"
22 #include "mozilla/layers/LayerManager.h"
23 #include "mozilla/PendingAnimationTracker.h"
24 #include "mozilla/PresShell.h"
25 #include "mozilla/ProfilerLabels.h"
26 #include "mozilla/RefPtr.h"
27 #include "mozilla/SVGObserverUtils.h" // for SVGRenderingObserver
28 #include "mozilla/Tuple.h"
29 #include "nsIStreamListener.h"
30 #include "nsMimeTypes.h"
31 #include "nsPresContext.h"
34 #include "nsStubDocumentObserver.h"
35 #include "nsWindowSizes.h"
36 #include "ImageRegion.h"
37 #include "ISurfaceProvider.h"
38 #include "LookupResult.h"
39 #include "Orientation.h"
40 #include "SVGDocumentWrapper.h"
41 #include "SVGDrawingParameters.h"
42 #include "nsIDOMEventListener.h"
43 #include "SurfaceCache.h"
44 #include "mozilla/dom/Document.h"
45 #include "mozilla/dom/DocumentInlines.h"
50 using namespace dom::SVGPreserveAspectRatio_Binding
;
52 using namespace layers
;
56 // Helper-class: SVGRootRenderingObserver
57 class SVGRootRenderingObserver final
: public SVGRenderingObserver
{
61 SVGRootRenderingObserver(SVGDocumentWrapper
* aDocWrapper
,
62 VectorImage
* aVectorImage
)
63 : SVGRenderingObserver(),
64 mDocWrapper(aDocWrapper
),
65 mVectorImage(aVectorImage
),
66 mHonoringInvalidations(true) {
67 MOZ_ASSERT(mDocWrapper
, "Need a non-null SVG document wrapper");
68 MOZ_ASSERT(mVectorImage
, "Need a non-null VectorImage");
71 Element
* elem
= GetReferencedElementWithoutObserving();
72 MOZ_ASSERT(elem
, "no root SVG node for us to observe");
74 SVGObserverUtils::AddRenderingObserver(elem
, this);
75 mInObserverSet
= true;
78 void ResumeHonoringInvalidations() { mHonoringInvalidations
= true; }
81 virtual ~SVGRootRenderingObserver() {
82 // This needs to call our GetReferencedElementWithoutObserving override,
83 // so must be called here rather than in our base class's dtor.
87 Element
* GetReferencedElementWithoutObserving() final
{
88 return mDocWrapper
->GetRootSVGElem();
91 virtual void OnRenderingChange() override
{
92 Element
* elem
= GetReferencedElementWithoutObserving();
93 MOZ_ASSERT(elem
, "missing root SVG node");
95 if (mHonoringInvalidations
&& !mDocWrapper
->ShouldIgnoreInvalidation()) {
96 nsIFrame
* frame
= elem
->GetPrimaryFrame();
97 if (!frame
|| frame
->PresShell()->IsDestroying()) {
98 // We're being destroyed. Bail out.
102 // Ignore further invalidations until we draw.
103 mHonoringInvalidations
= false;
105 mVectorImage
->InvalidateObserversOnNextRefreshDriverTick();
108 // Our caller might've removed us from rendering-observer list.
109 // Add ourselves back!
110 if (!mInObserverSet
) {
111 SVGObserverUtils::AddRenderingObserver(elem
, this);
112 mInObserverSet
= true;
117 const RefPtr
<SVGDocumentWrapper
> mDocWrapper
;
118 VectorImage
* const mVectorImage
; // Raw pointer because it owns me.
119 bool mHonoringInvalidations
;
122 NS_IMPL_ISUPPORTS(SVGRootRenderingObserver
, nsIMutationObserver
)
124 class SVGParseCompleteListener final
: public nsStubDocumentObserver
{
128 SVGParseCompleteListener(SVGDocument
* aDocument
, VectorImage
* aImage
)
129 : mDocument(aDocument
), mImage(aImage
) {
130 MOZ_ASSERT(mDocument
, "Need an SVG document");
131 MOZ_ASSERT(mImage
, "Need an image");
133 mDocument
->AddObserver(this);
137 ~SVGParseCompleteListener() {
139 // The document must have been destroyed before we got our event.
140 // Otherwise this can't happen, since documents hold strong references to
147 void EndLoad(Document
* aDocument
) override
{
148 MOZ_ASSERT(aDocument
== mDocument
, "Got EndLoad for wrong document?");
150 // OnSVGDocumentParsed will release our owner's reference to us, so ensure
151 // we stick around long enough to complete our work.
152 RefPtr
<SVGParseCompleteListener
> kungFuDeathGrip(this);
154 mImage
->OnSVGDocumentParsed();
158 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
160 mDocument
->RemoveObserver(this);
166 RefPtr
<SVGDocument
> mDocument
;
167 VectorImage
* const mImage
; // Raw pointer to owner.
170 NS_IMPL_ISUPPORTS(SVGParseCompleteListener
, nsIDocumentObserver
)
172 class SVGLoadEventListener final
: public nsIDOMEventListener
{
176 SVGLoadEventListener(Document
* aDocument
, VectorImage
* aImage
)
177 : mDocument(aDocument
), mImage(aImage
) {
178 MOZ_ASSERT(mDocument
, "Need an SVG document");
179 MOZ_ASSERT(mImage
, "Need an image");
181 mDocument
->AddEventListener(u
"MozSVGAsImageDocumentLoad"_ns
, 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 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);
204 nsAutoString eventType
;
205 aEvent
->GetType(eventType
);
206 MOZ_ASSERT(eventType
.EqualsLiteral("MozSVGAsImageDocumentLoad"),
207 "Received unexpected event");
210 mImage
->OnSVGDocumentLoaded();
216 MOZ_ASSERT(mDocument
, "Duplicate call to Cancel");
218 mDocument
->RemoveEventListener(u
"MozSVGAsImageDocumentLoad"_ns
, this,
225 nsCOMPtr
<Document
> mDocument
;
226 VectorImage
* const mImage
; // Raw pointer to owner.
229 NS_IMPL_ISUPPORTS(SVGLoadEventListener
, nsIDOMEventListener
)
231 // Helper-class: SVGDrawingCallback
232 class SVGDrawingCallback
: public gfxDrawingCallback
{
234 SVGDrawingCallback(SVGDocumentWrapper
* aSVGDocumentWrapper
,
235 const IntSize
& aViewportSize
, const IntSize
& aSize
,
236 uint32_t aImageFlags
)
237 : mSVGDocumentWrapper(aSVGDocumentWrapper
),
238 mViewportSize(aViewportSize
),
240 mImageFlags(aImageFlags
) {}
241 virtual bool operator()(gfxContext
* aContext
, const gfxRect
& aFillRect
,
242 const SamplingFilter aSamplingFilter
,
243 const gfxMatrix
& aTransform
) override
;
246 RefPtr
<SVGDocumentWrapper
> mSVGDocumentWrapper
;
247 const IntSize mViewportSize
;
249 uint32_t mImageFlags
;
252 // Based loosely on SVGIntegrationUtils' PaintFrameCallback::operator()
253 bool SVGDrawingCallback::operator()(gfxContext
* aContext
,
254 const gfxRect
& aFillRect
,
255 const SamplingFilter aSamplingFilter
,
256 const gfxMatrix
& aTransform
) {
257 MOZ_ASSERT(mSVGDocumentWrapper
, "need an SVGDocumentWrapper");
259 // Get (& sanity-check) the helper-doc's presShell
260 RefPtr
<PresShell
> presShell
= mSVGDocumentWrapper
->GetPresShell();
261 MOZ_ASSERT(presShell
, "GetPresShell returned null for an SVG image?");
263 Document
* doc
= presShell
->GetDocument();
264 [[maybe_unused
]] nsIURI
* uri
= doc
? doc
->GetDocumentURI() : nullptr;
265 AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING(
266 "SVG Image drawing", GRAPHICS
,
267 nsPrintfCString("%dx%d %s", mSize
.width
, mSize
.height
,
268 uri
? uri
->GetSpecOrDefault().get() : "N/A"));
270 gfxContextAutoSaveRestore
contextRestorer(aContext
);
272 // Clip to aFillRect so that we don't paint outside.
274 aContext
->Rectangle(aFillRect
);
277 gfxMatrix matrix
= aTransform
;
278 if (!matrix
.Invert()) {
281 aContext
->SetMatrixDouble(
282 aContext
->CurrentMatrixDouble().PreMultiply(matrix
).PreScale(
283 double(mSize
.width
) / mViewportSize
.width
,
284 double(mSize
.height
) / mViewportSize
.height
));
286 nsPresContext
* presContext
= presShell
->GetPresContext();
287 MOZ_ASSERT(presContext
, "pres shell w/out pres context");
289 nsRect
svgRect(0, 0, presContext
->DevPixelsToAppUnits(mViewportSize
.width
),
290 presContext
->DevPixelsToAppUnits(mViewportSize
.height
));
292 RenderDocumentFlags renderDocFlags
=
293 RenderDocumentFlags::IgnoreViewportScrolling
;
294 if (!(mImageFlags
& imgIContainer::FLAG_SYNC_DECODE
)) {
295 renderDocFlags
|= RenderDocumentFlags::AsyncDecodeImages
;
297 if (mImageFlags
& imgIContainer::FLAG_HIGH_QUALITY_SCALING
) {
298 renderDocFlags
|= RenderDocumentFlags::UseHighQualityScaling
;
301 presShell
->RenderDocument(svgRect
, renderDocFlags
,
302 NS_RGBA(0, 0, 0, 0), // transparent
308 class MOZ_STACK_CLASS AutoRestoreSVGState final
{
310 AutoRestoreSVGState(const SVGDrawingParameters
& aParams
,
311 SVGDocumentWrapper
* aSVGDocumentWrapper
, bool& aIsDrawing
,
313 : mIsDrawing(aIsDrawing
)
314 // Apply any 'preserveAspectRatio' override (if specified) to the root
317 mPAR(aParams
.svgContext
, aSVGDocumentWrapper
->GetRootSVGElem())
318 // Set the animation time:
320 mTime(aSVGDocumentWrapper
->GetRootSVGElem(), aParams
.animationTime
) {
321 MOZ_ASSERT(!aIsDrawing
);
322 MOZ_ASSERT(aSVGDocumentWrapper
->GetDocument());
326 // Set context paint (if specified) on the document:
328 MOZ_ASSERT(aParams
.svgContext
->GetContextPaint());
329 mContextPaint
.emplace(*aParams
.svgContext
->GetContextPaint(),
330 *aSVGDocumentWrapper
->GetDocument());
335 AutoRestore
<bool> mIsDrawing
;
336 AutoPreserveAspectRatioOverride mPAR
;
337 AutoSVGTimeSetRestore mTime
;
338 Maybe
<AutoSetRestoreSVGContextPaint
> mContextPaint
;
341 // Implement VectorImage's nsISupports-inherited methods
342 NS_IMPL_ISUPPORTS(VectorImage
, imgIContainer
, nsIStreamListener
,
345 //------------------------------------------------------------------------------
346 // Constructor / Destructor
348 VectorImage::VectorImage(nsIURI
* aURI
/* = nullptr */)
349 : ImageResource(aURI
), // invoke superclass's constructor
351 mIsInitialized(false),
353 mIsFullyLoaded(false),
355 mHaveAnimations(false),
356 mHasPendingInvalidation(false) {}
358 VectorImage::~VectorImage() {
359 ReportDocumentUseCounters();
360 CancelAllListeners();
361 SurfaceCache::RemoveImage(ImageKey(this));
364 //------------------------------------------------------------------------------
365 // Methods inherited from Image.h
367 nsresult
VectorImage::Init(const char* aMimeType
, uint32_t aFlags
) {
368 // We don't support re-initialization
369 if (mIsInitialized
) {
370 return NS_ERROR_ILLEGAL_VALUE
;
373 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
&& !mError
,
374 "Flags unexpectedly set before initialization");
375 MOZ_ASSERT(!strcmp(aMimeType
, IMAGE_SVG_XML
), "Unexpected mimetype");
377 mDiscardable
= !!(aFlags
& INIT_FLAG_DISCARDABLE
);
379 // Lock this image's surfaces in the SurfaceCache if we're not discardable.
382 SurfaceCache::LockImage(ImageKey(this));
385 mIsInitialized
= true;
389 size_t VectorImage::SizeOfSourceWithComputedFallback(
390 SizeOfState
& aState
) const {
391 if (!mSVGDocumentWrapper
) {
392 return 0; // No document, so no memory used for the document.
395 SVGDocument
* doc
= mSVGDocumentWrapper
->GetDocument();
397 return 0; // No document, so no memory used for the document.
400 nsWindowSizes
windowSizes(aState
);
401 doc
->DocAddSizeOfIncludingThis(windowSizes
);
403 if (windowSizes
.getTotalSize() == 0) {
404 // MallocSizeOf fails on this platform. Because we also use this method for
405 // determining the size of cache entries, we need to return something
406 // reasonable here. Unfortunately, there's no way to estimate the document's
407 // size accurately, so we just use a constant value of 100KB, which will
408 // generally underestimate the true size.
412 return windowSizes
.getTotalSize();
415 void VectorImage::CollectSizeOfSurfaces(
416 nsTArray
<SurfaceMemoryCounter
>& aCounters
,
417 MallocSizeOf aMallocSizeOf
) const {
418 SurfaceCache::CollectSizeOfSurfaces(ImageKey(this), aCounters
, aMallocSizeOf
);
421 nsresult
VectorImage::OnImageDataComplete(nsIRequest
* aRequest
,
422 nsISupports
* aContext
,
423 nsresult aStatus
, bool aLastPart
) {
424 // Call our internal OnStopRequest method, which only talks to our embedded
425 // SVG document. This won't have any effect on our ProgressTracker.
426 nsresult finalStatus
= OnStopRequest(aRequest
, aStatus
);
428 // Give precedence to Necko failure codes.
429 if (NS_FAILED(aStatus
)) {
430 finalStatus
= aStatus
;
433 Progress loadProgress
= LoadCompleteProgress(aLastPart
, mError
, finalStatus
);
435 if (mIsFullyLoaded
|| mError
) {
436 // Our document is loaded, so we're ready to notify now.
437 mProgressTracker
->SyncNotifyProgress(loadProgress
);
439 // Record our progress so far; we'll actually send the notifications in
440 // OnSVGDocumentLoaded or OnSVGDocumentError.
441 mLoadProgress
= Some(loadProgress
);
447 nsresult
VectorImage::OnImageDataAvailable(nsIRequest
* aRequest
,
448 nsISupports
* aContext
,
449 nsIInputStream
* aInStr
,
450 uint64_t aSourceOffset
,
452 return OnDataAvailable(aRequest
, aInStr
, aSourceOffset
, aCount
);
455 nsresult
VectorImage::StartAnimation() {
457 return NS_ERROR_FAILURE
;
460 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
462 mSVGDocumentWrapper
->StartAnimation();
466 nsresult
VectorImage::StopAnimation() {
469 rv
= NS_ERROR_FAILURE
;
471 MOZ_ASSERT(mIsFullyLoaded
&& mHaveAnimations
,
472 "Should not have been animating!");
474 mSVGDocumentWrapper
->StopAnimation();
481 bool VectorImage::ShouldAnimate() {
482 return ImageResource::ShouldAnimate() && mIsFullyLoaded
&& mHaveAnimations
;
486 VectorImage::SetAnimationStartTime(const TimeStamp
& aTime
) {
487 // We don't care about animation start time.
490 //------------------------------------------------------------------------------
491 // imgIContainer methods
493 //******************************************************************************
495 VectorImage::GetWidth(int32_t* aWidth
) {
496 if (mError
|| !mIsFullyLoaded
) {
497 // XXXdholbert Technically we should leave outparam untouched when we
498 // fail. But since many callers don't check for failure, we set it to 0 on
499 // failure, for sane/predictable results.
501 return NS_ERROR_FAILURE
;
504 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
506 "Should have a root SVG elem, since we finished "
507 "loading without errors");
508 int32_t rootElemWidth
= rootElem
->GetIntrinsicWidth();
509 if (rootElemWidth
< 0) {
511 return NS_ERROR_FAILURE
;
513 *aWidth
= rootElemWidth
;
517 //******************************************************************************
518 nsresult
VectorImage::GetNativeSizes(nsTArray
<IntSize
>& aNativeSizes
) const {
519 return NS_ERROR_NOT_IMPLEMENTED
;
522 //******************************************************************************
523 size_t VectorImage::GetNativeSizesLength() const { return 0; }
525 //******************************************************************************
527 VectorImage::RequestRefresh(const TimeStamp
& aTime
) {
528 if (HadRecentRefresh(aTime
)) {
532 PendingAnimationTracker
* tracker
=
533 mSVGDocumentWrapper
->GetDocument()->GetPendingAnimationTracker();
534 if (tracker
&& ShouldAnimate()) {
535 tracker
->TriggerPendingAnimationsOnNextTick(aTime
);
540 mSVGDocumentWrapper
->TickRefreshDriver();
542 if (mHasPendingInvalidation
) {
543 SendInvalidationNotifications();
547 void VectorImage::SendInvalidationNotifications() {
548 // Animated images don't send out invalidation notifications as soon as
549 // they're generated. Instead, InvalidateObserversOnNextRefreshDriverTick
550 // records that there are pending invalidations and then returns immediately.
551 // The notifications are actually sent from RequestRefresh(). We send these
552 // notifications there to ensure that there is actually a document observing
553 // us. Otherwise, the notifications are just wasted effort.
555 // Non-animated images post an event to call this method from
556 // InvalidateObserversOnNextRefreshDriverTick, because RequestRefresh is never
557 // called for them. Ordinarily this isn't needed, since we send out
558 // invalidation notifications in OnSVGDocumentLoaded, but in rare cases the
559 // SVG document may not be 100% ready to render at that time. In those cases
560 // we would miss the subsequent invalidations if we didn't send out the
561 // notifications indirectly in |InvalidateObservers...|.
563 mHasPendingInvalidation
= false;
564 SurfaceCache::RemoveImage(ImageKey(this));
566 if (UpdateImageContainer(Nothing())) {
567 // If we have image containers, that means we probably won't get a Draw call
568 // from the owner since they are using the container. We must assume all
569 // invalidations need to be handled.
570 MOZ_ASSERT(mRenderingObserver
, "Should have a rendering observer by now");
571 mRenderingObserver
->ResumeHonoringInvalidations();
574 if (mProgressTracker
) {
575 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
576 GetMaxSizedIntRect());
580 NS_IMETHODIMP_(IntRect
)
581 VectorImage::GetImageSpaceInvalidationRect(const IntRect
& aRect
) {
585 //******************************************************************************
587 VectorImage::GetHeight(int32_t* aHeight
) {
588 if (mError
|| !mIsFullyLoaded
) {
589 // XXXdholbert Technically we should leave outparam untouched when we
590 // fail. But since many callers don't check for failure, we set it to 0 on
591 // failure, for sane/predictable results.
593 return NS_ERROR_FAILURE
;
596 SVGSVGElement
* rootElem
= mSVGDocumentWrapper
->GetRootSVGElem();
598 "Should have a root SVG elem, since we finished "
599 "loading without errors");
600 int32_t rootElemHeight
= rootElem
->GetIntrinsicHeight();
601 if (rootElemHeight
< 0) {
603 return NS_ERROR_FAILURE
;
605 *aHeight
= rootElemHeight
;
609 //******************************************************************************
611 VectorImage::GetIntrinsicSize(nsSize
* aSize
) {
612 if (mError
|| !mIsFullyLoaded
) {
613 return NS_ERROR_FAILURE
;
616 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
618 return NS_ERROR_FAILURE
;
621 *aSize
= nsSize(-1, -1);
622 IntrinsicSize rfSize
= rootFrame
->GetIntrinsicSize();
624 aSize
->width
= *rfSize
.width
;
627 aSize
->height
= *rfSize
.height
;
632 //******************************************************************************
633 Maybe
<AspectRatio
> VectorImage::GetIntrinsicRatio() {
634 if (mError
|| !mIsFullyLoaded
) {
638 nsIFrame
* rootFrame
= mSVGDocumentWrapper
->GetRootLayoutFrame();
643 return Some(rootFrame
->GetIntrinsicRatio());
646 NS_IMETHODIMP_(Orientation
)
647 VectorImage::GetOrientation() { return Orientation(); }
649 //******************************************************************************
651 VectorImage::GetType(uint16_t* aType
) {
652 NS_ENSURE_ARG_POINTER(aType
);
654 *aType
= imgIContainer::TYPE_VECTOR
;
658 //******************************************************************************
660 VectorImage::GetProducerId(uint32_t* aId
) {
661 NS_ENSURE_ARG_POINTER(aId
);
663 *aId
= ImageResource::GetImageProducerId();
667 //******************************************************************************
669 VectorImage::GetAnimated(bool* aAnimated
) {
670 if (mError
|| !mIsFullyLoaded
) {
671 return NS_ERROR_FAILURE
;
674 *aAnimated
= mSVGDocumentWrapper
->IsAnimated();
678 //******************************************************************************
679 int32_t VectorImage::GetFirstFrameDelay() {
684 if (!mSVGDocumentWrapper
->IsAnimated()) {
688 // We don't really have a frame delay, so just pretend that we constantly
694 VectorImage::WillDrawOpaqueNow() {
695 return false; // In general, SVG content is not opaque.
698 //******************************************************************************
699 NS_IMETHODIMP_(already_AddRefed
<SourceSurface
>)
700 VectorImage::GetFrame(uint32_t aWhichFrame
, uint32_t aFlags
) {
705 // Look up height & width
706 // ----------------------
707 SVGSVGElement
* svgElem
= mSVGDocumentWrapper
->GetRootSVGElem();
709 "Should have a root SVG elem, since we finished "
710 "loading without errors");
711 nsIntSize
imageIntSize(svgElem
->GetIntrinsicWidth(),
712 svgElem
->GetIntrinsicHeight());
714 if (imageIntSize
.IsEmpty()) {
715 // We'll get here if our SVG doc has a percent-valued or negative width or
720 return GetFrameAtSize(imageIntSize
, aWhichFrame
, aFlags
);
723 NS_IMETHODIMP_(already_AddRefed
<SourceSurface
>)
724 VectorImage::GetFrameAtSize(const IntSize
& aSize
, uint32_t aWhichFrame
,
726 AutoProfilerImagePaintMarker
PROFILER_RAII(this);
728 NotifyDrawingObservers();
731 auto result
= GetFrameInternal(aSize
, Nothing(), aWhichFrame
, aFlags
);
732 return Get
<2>(result
).forget();
735 Tuple
<ImgDrawResult
, IntSize
, RefPtr
<SourceSurface
>>
736 VectorImage::GetFrameInternal(const IntSize
& aSize
,
737 const Maybe
<SVGImageContext
>& aSVGContext
,
738 uint32_t aWhichFrame
, uint32_t aFlags
) {
739 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
);
741 if (aSize
.IsEmpty() || aWhichFrame
> FRAME_MAX_VALUE
) {
742 return MakeTuple(ImgDrawResult::BAD_ARGS
, aSize
, RefPtr
<SourceSurface
>());
746 return MakeTuple(ImgDrawResult::BAD_IMAGE
, aSize
, RefPtr
<SourceSurface
>());
749 if (!mIsFullyLoaded
) {
750 return MakeTuple(ImgDrawResult::NOT_READY
, aSize
, RefPtr
<SourceSurface
>());
753 RefPtr
<SourceSurface
> sourceSurface
;
755 Tie(sourceSurface
, decodeSize
) =
756 LookupCachedSurface(aSize
, aSVGContext
, aFlags
);
758 return MakeTuple(ImgDrawResult::SUCCESS
, decodeSize
,
759 std::move(sourceSurface
));
763 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
764 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR
, decodeSize
,
765 RefPtr
<SourceSurface
>());
768 // By using a null gfxContext, we ensure that we will always attempt to
769 // create a surface, even if we aren't capable of caching it (e.g. due to our
770 // flags, having an animation, etc). Otherwise CreateSurface will assume that
771 // the caller is capable of drawing directly to its own draw target if we
773 SVGDrawingParameters
params(
774 nullptr, decodeSize
, aSize
, ImageRegion::Create(decodeSize
),
775 SamplingFilter::POINT
, aSVGContext
,
776 mSVGDocumentWrapper
->GetCurrentTimeAsFloat(), aFlags
, 1.0);
778 bool didCache
; // Was the surface put into the cache?
779 bool contextPaint
= aSVGContext
&& aSVGContext
->GetContextPaint();
781 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, mIsDrawing
,
784 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
785 RefPtr
<SourceSurface
> surface
= CreateSurface(params
, svgDrawable
, didCache
);
787 MOZ_ASSERT(!didCache
);
788 return MakeTuple(ImgDrawResult::TEMPORARY_ERROR
, decodeSize
,
789 RefPtr
<SourceSurface
>());
792 SendFrameComplete(didCache
, params
.flags
);
793 return MakeTuple(ImgDrawResult::SUCCESS
, decodeSize
, std::move(surface
));
796 //******************************************************************************
797 Tuple
<ImgDrawResult
, IntSize
> VectorImage::GetImageContainerSize(
798 LayerManager
* aManager
, const IntSize
& aSize
, uint32_t aFlags
) {
800 return MakeTuple(ImgDrawResult::BAD_IMAGE
, IntSize(0, 0));
803 if (!mIsFullyLoaded
) {
804 return MakeTuple(ImgDrawResult::NOT_READY
, IntSize(0, 0));
807 if (mHaveAnimations
||
808 aManager
->GetBackendType() != LayersBackend::LAYERS_WR
) {
809 return MakeTuple(ImgDrawResult::NOT_SUPPORTED
, IntSize(0, 0));
812 // We don't need to check if the size is too big since we only support
813 // WebRender backends.
814 if (aSize
.IsEmpty()) {
815 return MakeTuple(ImgDrawResult::BAD_ARGS
, IntSize(0, 0));
818 return MakeTuple(ImgDrawResult::SUCCESS
, aSize
);
822 VectorImage::IsImageContainerAvailable(LayerManager
* aManager
,
824 if (mError
|| !mIsFullyLoaded
|| mHaveAnimations
||
825 aManager
->GetBackendType() != LayersBackend::LAYERS_WR
) {
832 //******************************************************************************
833 NS_IMETHODIMP_(already_AddRefed
<ImageContainer
>)
834 VectorImage::GetImageContainer(LayerManager
* aManager
, uint32_t aFlags
) {
835 MOZ_ASSERT(aManager
->GetBackendType() != LayersBackend::LAYERS_WR
,
836 "WebRender should always use GetImageContainerAvailableAtSize!");
840 //******************************************************************************
842 VectorImage::IsImageContainerAvailableAtSize(LayerManager
* aManager
,
843 const IntSize
& aSize
,
845 // Since we only support image containers with WebRender, and it can handle
846 // textures larger than the hw max texture size, we don't need to check aSize.
847 return !aSize
.IsEmpty() && IsImageContainerAvailable(aManager
, aFlags
);
850 //******************************************************************************
851 NS_IMETHODIMP_(ImgDrawResult
)
852 VectorImage::GetImageContainerAtSize(layers::LayerManager
* aManager
,
853 const gfx::IntSize
& aSize
,
854 const Maybe
<SVGImageContext
>& aSVGContext
,
856 layers::ImageContainer
** aOutContainer
) {
857 Maybe
<SVGImageContext
> newSVGContext
;
858 MaybeRestrictSVGContext(newSVGContext
, aSVGContext
, aFlags
);
860 // The aspect ratio flag was already handled as part of the SVG context
861 // restriction above.
862 uint32_t flags
= aFlags
& ~(FLAG_FORCE_PRESERVEASPECTRATIO_NONE
);
863 return GetImageContainerImpl(aManager
, aSize
,
864 newSVGContext
? newSVGContext
: aSVGContext
,
865 flags
, aOutContainer
);
868 bool VectorImage::MaybeRestrictSVGContext(
869 Maybe
<SVGImageContext
>& aNewSVGContext
,
870 const Maybe
<SVGImageContext
>& aSVGContext
, uint32_t aFlags
) {
872 (aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
) && aSVGContext
;
874 bool haveContextPaint
= aSVGContext
&& aSVGContext
->GetContextPaint();
875 bool blockContextPaint
= false;
876 if (haveContextPaint
) {
877 blockContextPaint
= !SVGContextPaint::IsAllowedForImageFromURI(mURI
);
880 if (overridePAR
|| blockContextPaint
) {
881 // The key that we create for the image surface cache must match the way
882 // that the image will be painted, so we need to initialize a new matching
883 // SVGImageContext here in order to generate the correct key.
885 aNewSVGContext
= aSVGContext
; // copy
888 // The SVGImageContext must take account of the preserveAspectRatio
890 MOZ_ASSERT(!aSVGContext
->GetPreserveAspectRatio(),
891 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE is not expected if a "
892 "preserveAspectRatio override is supplied");
893 Maybe
<SVGPreserveAspectRatio
> aspectRatio
= Some(SVGPreserveAspectRatio(
894 SVG_PRESERVEASPECTRATIO_NONE
, SVG_MEETORSLICE_UNKNOWN
));
895 aNewSVGContext
->SetPreserveAspectRatio(aspectRatio
);
898 if (blockContextPaint
) {
899 // The SVGImageContext must not include context paint if the image is
900 // not allowed to use it:
901 aNewSVGContext
->ClearContextPaint();
905 return haveContextPaint
&& !blockContextPaint
;
908 //******************************************************************************
909 NS_IMETHODIMP_(ImgDrawResult
)
910 VectorImage::Draw(gfxContext
* aContext
, const nsIntSize
& aSize
,
911 const ImageRegion
& aRegion
, uint32_t aWhichFrame
,
912 SamplingFilter aSamplingFilter
,
913 const Maybe
<SVGImageContext
>& aSVGContext
, uint32_t aFlags
,
915 if (aWhichFrame
> FRAME_MAX_VALUE
) {
916 return ImgDrawResult::BAD_ARGS
;
920 return ImgDrawResult::BAD_ARGS
;
924 return ImgDrawResult::BAD_IMAGE
;
927 if (!mIsFullyLoaded
) {
928 return ImgDrawResult::NOT_READY
;
931 if (mAnimationConsumers
== 0) {
932 SendOnUnlockedDraw(aFlags
);
935 // We should bypass the cache when:
936 // - We are using a DrawTargetRecording because we prefer the drawing commands
937 // in general to the rasterized surface. This allows blob images to avoid
938 // rasterized SVGs with WebRender.
939 // - The size exceeds what we are willing to cache as a rasterized surface.
940 // We don't do this for WebRender because the performance of the fallback
941 // path is quite bad and upscaling the SVG from the clamped size is better
942 // than bringing the browser to a crawl.
943 if (aContext
->GetDrawTarget()->GetBackendType() == BackendType::RECORDING
||
944 (!gfxVars::UseWebRender() &&
945 aSize
!= SurfaceCache::ClampVectorSize(aSize
))) {
946 aFlags
|= FLAG_BYPASS_SURFACE_CACHE
;
949 MOZ_ASSERT(!(aFlags
& FLAG_FORCE_PRESERVEASPECTRATIO_NONE
) ||
950 (aSVGContext
&& aSVGContext
->GetViewportSize()),
951 "Viewport size is required when using "
952 "FLAG_FORCE_PRESERVEASPECTRATIO_NONE");
954 float animTime
= (aWhichFrame
== FRAME_FIRST
)
956 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
958 Maybe
<SVGImageContext
> newSVGContext
;
960 MaybeRestrictSVGContext(newSVGContext
, aSVGContext
, aFlags
);
962 SVGDrawingParameters
params(aContext
, aSize
, aSize
, aRegion
, aSamplingFilter
,
963 newSVGContext
? newSVGContext
: aSVGContext
,
964 animTime
, aFlags
, aOpacity
);
966 // If we have an prerasterized version of this image that matches the
967 // drawing parameters, use that.
968 RefPtr
<SourceSurface
> sourceSurface
;
969 Tie(sourceSurface
, params
.size
) =
970 LookupCachedSurface(aSize
, params
.svgContext
, aFlags
);
972 RefPtr
<gfxDrawable
> drawable
=
973 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
974 Show(drawable
, params
);
975 return ImgDrawResult::SUCCESS
;
978 // else, we need to paint the image:
981 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
982 return ImgDrawResult::TEMPORARY_ERROR
;
985 AutoRestoreSVGState
autoRestore(params
, mSVGDocumentWrapper
, mIsDrawing
,
988 bool didCache
; // Was the surface put into the cache?
989 RefPtr
<gfxDrawable
> svgDrawable
= CreateSVGDrawable(params
);
990 sourceSurface
= CreateSurface(params
, svgDrawable
, didCache
);
991 if (!sourceSurface
) {
992 MOZ_ASSERT(!didCache
);
993 Show(svgDrawable
, params
);
994 return ImgDrawResult::SUCCESS
;
997 RefPtr
<gfxDrawable
> drawable
=
998 new gfxSurfaceDrawable(sourceSurface
, params
.size
);
999 Show(drawable
, params
);
1000 SendFrameComplete(didCache
, params
.flags
);
1001 return ImgDrawResult::SUCCESS
;
1004 already_AddRefed
<gfxDrawable
> VectorImage::CreateSVGDrawable(
1005 const SVGDrawingParameters
& aParams
) {
1006 RefPtr
<gfxDrawingCallback
> cb
= new SVGDrawingCallback(
1007 mSVGDocumentWrapper
, aParams
.viewportSize
, aParams
.size
, aParams
.flags
);
1009 RefPtr
<gfxDrawable
> svgDrawable
= new gfxCallbackDrawable(cb
, aParams
.size
);
1010 return svgDrawable
.forget();
1013 Tuple
<RefPtr
<SourceSurface
>, IntSize
> VectorImage::LookupCachedSurface(
1014 const IntSize
& aSize
, const Maybe
<SVGImageContext
>& aSVGContext
,
1016 // If we're not allowed to use a cached surface, don't attempt a lookup.
1017 if (aFlags
& FLAG_BYPASS_SURFACE_CACHE
) {
1018 return MakeTuple(RefPtr
<SourceSurface
>(), aSize
);
1021 // We don't do any caching if we have animation, so don't bother with a lookup
1022 // in this case either.
1023 if (mHaveAnimations
) {
1024 return MakeTuple(RefPtr
<SourceSurface
>(), aSize
);
1027 LookupResult
result(MatchType::NOT_FOUND
);
1028 SurfaceKey surfaceKey
= VectorSurfaceKey(aSize
, aSVGContext
);
1029 if ((aFlags
& FLAG_SYNC_DECODE
) || !(aFlags
& FLAG_HIGH_QUALITY_SCALING
)) {
1030 result
= SurfaceCache::Lookup(ImageKey(this), surfaceKey
,
1031 /* aMarkUsed = */ true);
1033 result
= SurfaceCache::LookupBestMatch(ImageKey(this), surfaceKey
,
1034 /* aMarkUsed = */ true);
1037 IntSize rasterSize
=
1038 result
.SuggestedSize().IsEmpty() ? aSize
: result
.SuggestedSize();
1039 MOZ_ASSERT(result
.Type() != MatchType::SUBSTITUTE_BECAUSE_PENDING
);
1040 if (!result
|| result
.Type() == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND
) {
1041 // No matching surface, or the OS freed the volatile buffer.
1042 return MakeTuple(RefPtr
<SourceSurface
>(), rasterSize
);
1045 RefPtr
<SourceSurface
> sourceSurface
= result
.Surface()->GetSourceSurface();
1046 if (!sourceSurface
) {
1047 // Something went wrong. (Probably a GPU driver crash or device reset.)
1048 // Attempt to recover.
1049 RecoverFromLossOfSurfaces();
1050 return MakeTuple(RefPtr
<SourceSurface
>(), rasterSize
);
1053 return MakeTuple(std::move(sourceSurface
), rasterSize
);
1056 already_AddRefed
<SourceSurface
> VectorImage::CreateSurface(
1057 const SVGDrawingParameters
& aParams
, gfxDrawable
* aSVGDrawable
,
1059 MOZ_ASSERT(mIsDrawing
);
1061 mSVGDocumentWrapper
->UpdateViewportBounds(aParams
.viewportSize
);
1062 mSVGDocumentWrapper
->FlushImageTransformInvalidation();
1064 // Determine whether or not we should put the surface to be created into
1065 // the cache. If we fail, we need to reset this to false to let the caller
1066 // know nothing was put in the cache.
1067 aWillCache
= !(aParams
.flags
& FLAG_BYPASS_SURFACE_CACHE
) &&
1068 // Refuse to cache animated images:
1069 // XXX(seth): We may remove this restriction in bug 922893.
1071 // The image is too big to fit in the cache:
1072 SurfaceCache::CanHold(aParams
.size
);
1074 // If we weren't given a context, then we know we just want the rasterized
1075 // surface. We will create the frame below but only insert it into the cache
1076 // if we actually need to.
1077 if (!aWillCache
&& aParams
.context
) {
1081 // We're about to rerasterize, which may mean that some of the previous
1082 // surfaces we've rasterized aren't useful anymore. We can allow them to
1083 // expire from the cache by unlocking them here, and then sending out an
1084 // invalidation. If this image is locked, any surfaces that are still useful
1085 // will become locked again when Draw touches them, and the remainder will
1086 // eventually expire.
1088 SurfaceCache::UnlockEntries(ImageKey(this));
1091 // If there is no context, the default backend is fine.
1092 BackendType backend
=
1093 aParams
.context
? aParams
.context
->GetDrawTarget()->GetBackendType()
1094 : gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1096 // Try to create an imgFrame, initializing the surface it contains by drawing
1097 // our gfxDrawable into it. (We use FILTER_NEAREST since we never scale here.)
1098 auto frame
= MakeNotNull
<RefPtr
<imgFrame
>>();
1099 nsresult rv
= frame
->InitWithDrawable(
1100 aSVGDrawable
, aParams
.size
, SurfaceFormat::OS_RGBA
, SamplingFilter::POINT
,
1101 aParams
.flags
, backend
);
1103 // If we couldn't create the frame, it was probably because it would end
1104 // up way too big. Generally it also wouldn't fit in the cache, but the prefs
1105 // could be set such that the cache isn't the limiting factor.
1106 if (NS_FAILED(rv
)) {
1111 // Take a strong reference to the frame's surface and make sure it hasn't
1112 // already been purged by the operating system.
1113 RefPtr
<SourceSurface
> surface
= frame
->GetSourceSurface();
1119 // We created the frame, but only because we had no context to draw to
1120 // directly. All the caller wants is the surface in this case.
1122 return surface
.forget();
1125 // Attempt to cache the frame.
1126 SurfaceKey surfaceKey
= VectorSurfaceKey(aParams
.size
, aParams
.svgContext
);
1127 NotNull
<RefPtr
<ISurfaceProvider
>> provider
=
1128 MakeNotNull
<SimpleSurfaceProvider
*>(ImageKey(this), surfaceKey
, frame
);
1130 if (SurfaceCache::Insert(provider
) == InsertOutcome::SUCCESS
) {
1131 if (aParams
.size
!= aParams
.drawSize
) {
1132 // We created a new surface that wasn't the size we requested, which means
1133 // we entered factor-of-2 mode. We should purge any surfaces we no longer
1134 // need rather than waiting for the cache to expire them.
1135 SurfaceCache::PruneImage(ImageKey(this));
1141 return surface
.forget();
1144 void VectorImage::SendFrameComplete(bool aDidCache
, uint32_t aFlags
) {
1145 // If the cache was not updated, we have nothing to do.
1150 // Send out an invalidation so that surfaces that are still in use get
1151 // re-locked. See the discussion of the UnlockSurfaces call above.
1152 if (!(aFlags
& FLAG_ASYNC_NOTIFY
)) {
1153 mProgressTracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1154 GetMaxSizedIntRect());
1156 NotNull
<RefPtr
<VectorImage
>> image
= WrapNotNull(this);
1157 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1158 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1159 RefPtr
<ProgressTracker
> tracker
= image
->GetProgressTracker();
1161 tracker
->SyncNotifyProgress(FLAG_FRAME_COMPLETE
,
1162 GetMaxSizedIntRect());
1168 void VectorImage::Show(gfxDrawable
* aDrawable
,
1169 const SVGDrawingParameters
& aParams
) {
1170 // The surface size may differ from the size at which we wish to draw. As
1171 // such, we may need to adjust the context/region to take this into account.
1172 gfxContextMatrixAutoSaveRestore
saveMatrix(aParams
.context
);
1173 ImageRegion
region(aParams
.region
);
1174 if (aParams
.drawSize
!= aParams
.size
) {
1175 gfx::Size
scale(double(aParams
.drawSize
.width
) / aParams
.size
.width
,
1176 double(aParams
.drawSize
.height
) / aParams
.size
.height
);
1177 aParams
.context
->Multiply(gfxMatrix::Scaling(scale
.width
, scale
.height
));
1178 region
.Scale(1.0 / scale
.width
, 1.0 / scale
.height
);
1181 MOZ_ASSERT(aDrawable
, "Should have a gfxDrawable by now");
1182 gfxUtils::DrawPixelSnapped(aParams
.context
, aDrawable
,
1183 SizeDouble(aParams
.size
), region
,
1184 SurfaceFormat::OS_RGBA
, aParams
.samplingFilter
,
1185 aParams
.flags
, aParams
.opacity
, false);
1187 AutoProfilerImagePaintMarker
PROFILER_RAII(this);
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 imgIContainer::DecodeResult
VectorImage::RequestDecodeWithResult(
1216 uint32_t aFlags
, uint32_t aWhichFrame
) {
1217 // SVG images are ready to draw when they are loaded and don't have an error.
1220 return imgIContainer::DECODE_REQUEST_FAILED
;
1223 if (!mIsFullyLoaded
) {
1224 return imgIContainer::DECODE_REQUESTED
;
1227 return imgIContainer::DECODE_SURFACE_AVAILABLE
;
1231 VectorImage::RequestDecodeForSize(const nsIntSize
& aSize
, uint32_t aFlags
,
1232 uint32_t aWhichFrame
) {
1233 // Nothing to do for SVG images, though in theory we could rasterize to the
1234 // provided size ahead of time if we supported off-main-thread SVG
1239 //******************************************************************************
1242 VectorImage::LockImage() {
1243 MOZ_ASSERT(NS_IsMainThread());
1246 return NS_ERROR_FAILURE
;
1251 if (mLockCount
== 1) {
1252 // Lock this image's surfaces in the SurfaceCache.
1253 SurfaceCache::LockImage(ImageKey(this));
1259 //******************************************************************************
1262 VectorImage::UnlockImage() {
1263 MOZ_ASSERT(NS_IsMainThread());
1266 return NS_ERROR_FAILURE
;
1269 if (mLockCount
== 0) {
1270 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1271 return NS_ERROR_ABORT
;
1276 if (mLockCount
== 0) {
1277 // Unlock this image's surfaces in the SurfaceCache.
1278 SurfaceCache::UnlockImage(ImageKey(this));
1284 //******************************************************************************
1287 VectorImage::RequestDiscard() {
1288 MOZ_ASSERT(NS_IsMainThread());
1290 if (mDiscardable
&& mLockCount
== 0) {
1291 SurfaceCache::RemoveImage(ImageKey(this));
1292 mProgressTracker
->OnDiscard();
1298 void VectorImage::OnSurfaceDiscarded(const SurfaceKey
& aSurfaceKey
) {
1299 MOZ_ASSERT(mProgressTracker
);
1301 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1303 &ProgressTracker::OnDiscard
));
1306 //******************************************************************************
1308 VectorImage::ResetAnimation() {
1310 return NS_ERROR_FAILURE
;
1313 if (!mIsFullyLoaded
|| !mHaveAnimations
) {
1314 return NS_OK
; // There are no animations to be reset.
1317 mSVGDocumentWrapper
->ResetAnimation();
1322 NS_IMETHODIMP_(float)
1323 VectorImage::GetFrameIndex(uint32_t aWhichFrame
) {
1324 MOZ_ASSERT(aWhichFrame
<= FRAME_MAX_VALUE
, "Invalid argument");
1325 return aWhichFrame
== FRAME_FIRST
1327 : mSVGDocumentWrapper
->GetCurrentTimeAsFloat();
1330 //------------------------------------------------------------------------------
1331 // nsIRequestObserver methods
1333 //******************************************************************************
1335 VectorImage::OnStartRequest(nsIRequest
* aRequest
) {
1336 MOZ_ASSERT(!mSVGDocumentWrapper
,
1337 "Repeated call to OnStartRequest -- can this happen?");
1339 mSVGDocumentWrapper
= new SVGDocumentWrapper();
1340 nsresult rv
= mSVGDocumentWrapper
->OnStartRequest(aRequest
);
1341 if (NS_FAILED(rv
)) {
1342 mSVGDocumentWrapper
= nullptr;
1347 // Create a listener to wait until the SVG document is fully loaded, which
1348 // will signal that this image is ready to render. Certain error conditions
1349 // will prevent us from ever getting this notification, so we also create a
1350 // listener that waits for parsing to complete and cancels the
1351 // SVGLoadEventListener if needed. The listeners are automatically attached
1352 // to the document by their constructors.
1353 SVGDocument
* document
= mSVGDocumentWrapper
->GetDocument();
1354 mLoadEventListener
= new SVGLoadEventListener(document
, this);
1355 mParseCompleteListener
= new SVGParseCompleteListener(document
, this);
1357 // Displayed documents will call InitUseCounters under SetScriptGlobalObject,
1358 // but SVG image documents never get a script global object, so we initialize
1359 // use counters here, right after the document has been created.
1360 document
->InitUseCounters();
1365 //******************************************************************************
1367 VectorImage::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
1369 return NS_ERROR_FAILURE
;
1372 return mSVGDocumentWrapper
->OnStopRequest(aRequest
, aStatus
);
1375 void VectorImage::OnSVGDocumentParsed() {
1376 MOZ_ASSERT(mParseCompleteListener
, "Should have the parse complete listener");
1377 MOZ_ASSERT(mLoadEventListener
, "Should have the load event listener");
1379 if (!mSVGDocumentWrapper
->GetRootSVGElem()) {
1380 // This is an invalid SVG document. It may have failed to parse, or it may
1381 // be missing the <svg> root element, or the <svg> root element may not
1382 // declare the correct namespace. In any of these cases, we'll never be
1383 // notified that the SVG finished loading, so we need to treat this as an
1385 OnSVGDocumentError();
1389 void VectorImage::CancelAllListeners() {
1390 if (mParseCompleteListener
) {
1391 mParseCompleteListener
->Cancel();
1392 mParseCompleteListener
= nullptr;
1394 if (mLoadEventListener
) {
1395 mLoadEventListener
->Cancel();
1396 mLoadEventListener
= nullptr;
1400 void VectorImage::OnSVGDocumentLoaded() {
1401 MOZ_ASSERT(mSVGDocumentWrapper
->GetRootSVGElem(),
1402 "Should have parsed successfully");
1403 MOZ_ASSERT(!mIsFullyLoaded
&& !mHaveAnimations
,
1404 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1405 "Duplicate calls to OnSVGDocumentLoaded?");
1407 CancelAllListeners();
1409 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1410 mSVGDocumentWrapper
->FlushLayout();
1412 // This is the earliest point that we can get accurate use counter data
1413 // for a valid SVG document. Without the FlushLayout call, we would miss
1414 // any CSS property usage that comes from SVG presentation attributes.
1415 mSVGDocumentWrapper
->GetDocument()->ReportDocumentUseCounters();
1417 mIsFullyLoaded
= true;
1418 mHaveAnimations
= mSVGDocumentWrapper
->IsAnimated();
1420 // Start listening to our image for rendering updates.
1421 mRenderingObserver
= new SVGRootRenderingObserver(mSVGDocumentWrapper
, this);
1423 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1424 // stick around long enough to complete our work.
1425 RefPtr
<VectorImage
> kungFuDeathGrip(this);
1427 // Tell *our* observers that we're done loading.
1428 if (mProgressTracker
) {
1429 Progress progress
= FLAG_SIZE_AVAILABLE
| FLAG_HAS_TRANSPARENCY
|
1430 FLAG_FRAME_COMPLETE
| FLAG_DECODE_COMPLETE
;
1432 if (mHaveAnimations
) {
1433 progress
|= FLAG_IS_ANIMATED
;
1436 // Merge in any saved progress from OnImageDataComplete.
1437 if (mLoadProgress
) {
1438 progress
|= *mLoadProgress
;
1439 mLoadProgress
= Nothing();
1442 mProgressTracker
->SyncNotifyProgress(progress
, GetMaxSizedIntRect());
1445 EvaluateAnimation();
1448 void VectorImage::OnSVGDocumentError() {
1449 CancelAllListeners();
1453 // We won't enter OnSVGDocumentLoaded, so report use counters now for this
1454 // invalid document.
1455 ReportDocumentUseCounters();
1457 if (mProgressTracker
) {
1458 // Notify observers about the error and unblock page load.
1459 Progress progress
= FLAG_HAS_ERROR
;
1461 // Merge in any saved progress from OnImageDataComplete.
1462 if (mLoadProgress
) {
1463 progress
|= *mLoadProgress
;
1464 mLoadProgress
= Nothing();
1467 mProgressTracker
->SyncNotifyProgress(progress
);
1471 //------------------------------------------------------------------------------
1472 // nsIStreamListener method
1474 //******************************************************************************
1476 VectorImage::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
1477 uint64_t aSourceOffset
, uint32_t aCount
) {
1479 return NS_ERROR_FAILURE
;
1482 return mSVGDocumentWrapper
->OnDataAvailable(aRequest
, aInStr
, aSourceOffset
,
1486 // --------------------------
1487 // Invalidation helper method
1489 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1490 if (mHasPendingInvalidation
) {
1494 mHasPendingInvalidation
= true;
1496 // Animated images can wait for the refresh tick.
1497 if (mHaveAnimations
) {
1501 // Non-animated images won't get the refresh tick, so we should just send an
1502 // invalidation outside the current execution context. We need to defer
1503 // because the layout tree is in the middle of invalidation, and the tree
1504 // state needs to be consistent. Specifically only some of the frames have
1505 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1506 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1507 // get cleared when we repaint the SVG into a surface by
1508 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1509 nsCOMPtr
<nsIEventTarget
> eventTarget
;
1510 if (mProgressTracker
) {
1511 eventTarget
= mProgressTracker
->GetEventTarget();
1513 eventTarget
= do_GetMainThread();
1516 RefPtr
<VectorImage
> self(this);
1517 nsCOMPtr
<nsIRunnable
> ev(NS_NewRunnableFunction(
1518 "VectorImage::SendInvalidationNotifications",
1519 [=]() -> void { self
->SendInvalidationNotifications(); }));
1520 eventTarget
->Dispatch(CreateMediumHighRunnable(ev
.forget()),
1521 NS_DISPATCH_NORMAL
);
1524 void VectorImage::PropagateUseCounters(Document
* aReferencingDocument
) {
1525 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1526 doc
->PropagateImageUseCounters(aReferencingDocument
);
1530 nsIntSize
VectorImage::OptimalImageSizeForDest(const gfxSize
& aDest
,
1531 uint32_t aWhichFrame
,
1532 SamplingFilter aSamplingFilter
,
1534 MOZ_ASSERT(aDest
.width
>= 0 || ceil(aDest
.width
) <= INT32_MAX
||
1535 aDest
.height
>= 0 || ceil(aDest
.height
) <= INT32_MAX
,
1536 "Unexpected destination size");
1538 // We can rescale SVGs freely, so just return the provided destination size.
1539 return nsIntSize::Ceil(aDest
.width
, aDest
.height
);
1542 already_AddRefed
<imgIContainer
> VectorImage::Unwrap() {
1543 nsCOMPtr
<imgIContainer
> self(this);
1544 return self
.forget();
1547 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1548 const MediaFeatureChange
& aChange
) {
1549 if (!mSVGDocumentWrapper
) {
1553 // Don't bother if the document hasn't loaded yet.
1554 if (!mIsFullyLoaded
) {
1558 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1559 if (RefPtr
<nsPresContext
> presContext
= doc
->GetPresContext()) {
1560 presContext
->MediaFeatureValuesChanged(
1561 aChange
, MediaFeatureChangePropagation::All
);
1562 // Media feature value changes don't happen in the middle of layout,
1563 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1564 // to invalidate asynchronously.
1565 if (presContext
->FlushPendingMediaFeatureValuesChanged()) {
1566 // NOTE(emilio): SendInvalidationNotifications flushes layout via
1567 // VectorImage::CreateSurface -> FlushImageTransformInvalidation.
1568 SendInvalidationNotifications();
1574 nsresult
VectorImage::GetHotspotX(int32_t* aX
) {
1575 return Image::GetHotspotX(aX
);
1578 nsresult
VectorImage::GetHotspotY(int32_t* aY
) {
1579 return Image::GetHotspotY(aY
);
1582 void VectorImage::ReportDocumentUseCounters() {
1583 if (!mSVGDocumentWrapper
) {
1587 if (Document
* doc
= mSVGDocumentWrapper
->GetDocument()) {
1588 doc
->ReportDocumentUseCounters();
1592 } // namespace image
1593 } // namespace mozilla