Bug 1619273 [wpt PR 22036] - Don't compare px rounded font sizes., a=testonly
[gecko.git] / image / VectorImage.cpp
blob2564a970dd7b05c7c229c3c0d2ce068f7c870391
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "VectorImage.h"
8 #include "gfx2DGlue.h"
9 #include "gfxContext.h"
10 #include "gfxDrawable.h"
11 #include "gfxPlatform.h"
12 #include "gfxUtils.h"
13 #include "imgFrame.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"
28 #include "nsRect.h"
29 #include "nsString.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"
44 namespace mozilla {
46 using namespace dom;
47 using namespace dom::SVGPreserveAspectRatio_Binding;
48 using namespace gfx;
49 using namespace layers;
51 namespace image {
53 // Helper-class: SVGRootRenderingObserver
54 class SVGRootRenderingObserver final : public SVGRenderingObserver {
55 public:
56 NS_DECL_ISUPPORTS
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");
67 StartObserving();
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; }
77 protected:
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.
81 StopObserving();
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.
96 return;
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;
113 // Private data
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 {
122 public:
123 NS_DECL_ISUPPORTS
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);
133 private:
134 ~SVGParseCompleteListener() {
135 if (mDocument) {
136 // The document must have been destroyed before we got our event.
137 // Otherwise this can't happen, since documents hold strong references to
138 // their observers.
139 Cancel();
143 public:
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();
154 void Cancel() {
155 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
156 if (mDocument) {
157 mDocument->RemoveObserver(this);
158 mDocument = nullptr;
162 private:
163 RefPtr<SVGDocument> mDocument;
164 VectorImage* const mImage; // Raw pointer to owner.
167 NS_IMPL_ISUPPORTS(SVGParseCompleteListener, nsIDocumentObserver)
169 class SVGLoadEventListener final : public nsIDOMEventListener {
170 public:
171 NS_DECL_ISUPPORTS
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"),
179 this, true, false);
180 mDocument->AddEventListener(NS_LITERAL_STRING("SVGAbort"), this, true,
181 false);
182 mDocument->AddEventListener(NS_LITERAL_STRING("SVGError"), this, true,
183 false);
186 private:
187 ~SVGLoadEventListener() {
188 if (mDocument) {
189 // The document must have been destroyed before we got our event.
190 // Otherwise this can't happen, since documents hold strong references to
191 // their observers.
192 Cancel();
196 public:
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();
213 } else {
214 mImage->OnSVGDocumentError();
217 return NS_OK;
220 void Cancel() {
221 MOZ_ASSERT(mDocument, "Duplicate call to Cancel");
222 if (mDocument) {
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);
227 mDocument = nullptr;
231 private:
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 {
240 public:
241 SVGDrawingCallback(SVGDocumentWrapper* aSVGDocumentWrapper,
242 const IntSize& aViewportSize, const IntSize& aSize,
243 uint32_t aImageFlags)
244 : mSVGDocumentWrapper(aSVGDocumentWrapper),
245 mViewportSize(aViewportSize),
246 mSize(aSize),
247 mImageFlags(aImageFlags) {}
248 virtual bool operator()(gfxContext* aContext, const gfxRect& aFillRect,
249 const SamplingFilter aSamplingFilter,
250 const gfxMatrix& aTransform) override;
252 private:
253 RefPtr<SVGDocumentWrapper> mSVGDocumentWrapper;
254 const IntSize mViewportSize;
255 const IntSize mSize;
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"));
277 #endif
279 gfxContextAutoSaveRestore contextRestorer(aContext);
281 // Clip to aFillRect so that we don't paint outside.
282 aContext->NewPath();
283 aContext->Rectangle(aFillRect);
284 aContext->Clip();
286 gfxMatrix matrix = aTransform;
287 if (!matrix.Invert()) {
288 return false;
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
309 aContext);
311 return true;
314 class MOZ_STACK_CLASS AutoRestoreSVGState final {
315 public:
316 AutoRestoreSVGState(const SVGDrawingParameters& aParams,
317 SVGDocumentWrapper* aSVGDocumentWrapper, bool& aIsDrawing,
318 bool aContextPaint)
319 : mIsDrawing(aIsDrawing)
320 // Apply any 'preserveAspectRatio' override (if specified) to the root
321 // element:
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());
330 aIsDrawing = true;
332 // Set context paint (if specified) on the document:
333 if (aContextPaint) {
334 MOZ_ASSERT(aParams.svgContext->GetContextPaint());
335 mContextPaint.emplace(*aParams.svgContext->GetContextPaint(),
336 *aSVGDocumentWrapper->GetDocument());
340 private:
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,
349 nsIRequestObserver)
351 //------------------------------------------------------------------------------
352 // Constructor / Destructor
354 VectorImage::VectorImage(nsIURI* aURI /* = nullptr */)
355 : ImageResource(aURI), // invoke superclass's constructor
356 mLockCount(0),
357 mIsInitialized(false),
358 mDiscardable(false),
359 mIsFullyLoaded(false),
360 mIsDrawing(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.
385 if (!mDiscardable) {
386 mLockCount++;
387 SurfaceCache::LockImage(ImageKey(this));
390 mIsInitialized = true;
391 return NS_OK;
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();
401 if (!doc) {
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.
414 return 100 * 1024;
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);
443 } else {
444 // Record our progress so far; we'll actually send the notifications in
445 // OnSVGDocumentLoaded or OnSVGDocumentError.
446 mLoadProgress = Some(loadProgress);
449 return finalStatus;
452 nsresult VectorImage::OnImageDataAvailable(nsIRequest* aRequest,
453 nsISupports* aContext,
454 nsIInputStream* aInStr,
455 uint64_t aSourceOffset,
456 uint32_t aCount) {
457 return OnDataAvailable(aRequest, aInStr, aSourceOffset, aCount);
460 nsresult VectorImage::StartAnimation() {
461 if (mError) {
462 return NS_ERROR_FAILURE;
465 MOZ_ASSERT(ShouldAnimate(), "Should not animate!");
467 mSVGDocumentWrapper->StartAnimation();
468 return NS_OK;
471 nsresult VectorImage::StopAnimation() {
472 nsresult rv = NS_OK;
473 if (mError) {
474 rv = NS_ERROR_FAILURE;
475 } else {
476 MOZ_ASSERT(mIsFullyLoaded && mHaveAnimations,
477 "Should not have been animating!");
479 mSVGDocumentWrapper->StopAnimation();
482 mAnimating = false;
483 return rv;
486 bool VectorImage::ShouldAnimate() {
487 return ImageResource::ShouldAnimate() && mIsFullyLoaded && mHaveAnimations;
490 NS_IMETHODIMP_(void)
491 VectorImage::SetAnimationStartTime(const TimeStamp& aTime) {
492 // We don't care about animation start time.
495 //------------------------------------------------------------------------------
496 // imgIContainer methods
498 //******************************************************************************
499 NS_IMETHODIMP
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.
505 *aWidth = 0;
506 return NS_ERROR_FAILURE;
509 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
510 MOZ_ASSERT(rootElem,
511 "Should have a root SVG elem, since we finished "
512 "loading without errors");
513 int32_t rootElemWidth = rootElem->GetIntrinsicWidth();
514 if (rootElemWidth < 0) {
515 *aWidth = 0;
516 return NS_ERROR_FAILURE;
518 *aWidth = rootElemWidth;
519 return NS_OK;
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 //******************************************************************************
531 NS_IMETHODIMP_(void)
532 VectorImage::RequestRefresh(const TimeStamp& aTime) {
533 if (HadRecentRefresh(aTime)) {
534 return;
537 PendingAnimationTracker* tracker =
538 mSVGDocumentWrapper->GetDocument()->GetPendingAnimationTracker();
539 if (tracker && ShouldAnimate()) {
540 tracker->TriggerPendingAnimationsOnNextTick(aTime);
543 EvaluateAnimation();
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) {
587 return aRect;
590 //******************************************************************************
591 NS_IMETHODIMP
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.
597 *aHeight = 0;
598 return NS_ERROR_FAILURE;
601 SVGSVGElement* rootElem = mSVGDocumentWrapper->GetRootSVGElem();
602 MOZ_ASSERT(rootElem,
603 "Should have a root SVG elem, since we finished "
604 "loading without errors");
605 int32_t rootElemHeight = rootElem->GetIntrinsicHeight();
606 if (rootElemHeight < 0) {
607 *aHeight = 0;
608 return NS_ERROR_FAILURE;
610 *aHeight = rootElemHeight;
611 return NS_OK;
614 //******************************************************************************
615 NS_IMETHODIMP
616 VectorImage::GetIntrinsicSize(nsSize* aSize) {
617 if (mError || !mIsFullyLoaded) {
618 return NS_ERROR_FAILURE;
621 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
622 if (!rootFrame) {
623 return NS_ERROR_FAILURE;
626 *aSize = nsSize(-1, -1);
627 IntrinsicSize rfSize = rootFrame->GetIntrinsicSize();
628 if (rfSize.width) {
629 aSize->width = *rfSize.width;
631 if (rfSize.height) {
632 aSize->height = *rfSize.height;
634 return NS_OK;
637 //******************************************************************************
638 Maybe<AspectRatio> VectorImage::GetIntrinsicRatio() {
639 if (mError || !mIsFullyLoaded) {
640 return Nothing();
643 nsIFrame* rootFrame = mSVGDocumentWrapper->GetRootLayoutFrame();
644 if (!rootFrame) {
645 return Nothing();
648 return Some(rootFrame->GetIntrinsicRatio());
651 NS_IMETHODIMP_(Orientation)
652 VectorImage::GetOrientation() { return Orientation(); }
654 //******************************************************************************
655 NS_IMETHODIMP
656 VectorImage::GetType(uint16_t* aType) {
657 NS_ENSURE_ARG_POINTER(aType);
659 *aType = imgIContainer::TYPE_VECTOR;
660 return NS_OK;
663 //******************************************************************************
664 NS_IMETHODIMP
665 VectorImage::GetProducerId(uint32_t* aId) {
666 NS_ENSURE_ARG_POINTER(aId);
668 *aId = ImageResource::GetImageProducerId();
669 return NS_OK;
672 //******************************************************************************
673 NS_IMETHODIMP
674 VectorImage::GetAnimated(bool* aAnimated) {
675 if (mError || !mIsFullyLoaded) {
676 return NS_ERROR_FAILURE;
679 *aAnimated = mSVGDocumentWrapper->IsAnimated();
680 return NS_OK;
683 //******************************************************************************
684 int32_t VectorImage::GetFirstFrameDelay() {
685 if (mError) {
686 return -1;
689 if (!mSVGDocumentWrapper->IsAnimated()) {
690 return -1;
693 // We don't really have a frame delay, so just pretend that we constantly
694 // need updates.
695 return 0;
698 NS_IMETHODIMP_(bool)
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) {
706 if (mError) {
707 return nullptr;
710 // Look up height & width
711 // ----------------------
712 SVGSVGElement* svgElem = mSVGDocumentWrapper->GetRootSVGElem();
713 MOZ_ASSERT(svgElem,
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
721 // height.
722 return nullptr;
725 return GetFrameAtSize(imageIntSize, aWhichFrame, aFlags);
728 NS_IMETHODIMP_(already_AddRefed<SourceSurface>)
729 VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame,
730 uint32_t aFlags) {
731 #ifdef DEBUG
732 NotifyDrawingObservers();
733 #endif
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>());
749 if (mError) {
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;
758 IntSize decodeSize;
759 Tie(sourceSurface, decodeSize) =
760 LookupCachedSurface(aSize, aSVGContext, aFlags);
761 if (sourceSurface) {
762 return MakeTuple(ImgDrawResult::SUCCESS, decodeSize,
763 std::move(sourceSurface));
766 if (mIsDrawing) {
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
776 // cannot cache.
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,
786 contextPaint);
788 RefPtr<gfxDrawable> svgDrawable = CreateSVGDrawable(params);
789 RefPtr<SourceSurface> surface = CreateSurface(params, svgDrawable, didCache);
790 if (!surface) {
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) {
803 if (mError) {
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);
825 NS_IMETHODIMP_(bool)
826 VectorImage::IsImageContainerAvailable(LayerManager* aManager,
827 uint32_t aFlags) {
828 if (mError || !mIsFullyLoaded || mHaveAnimations ||
829 aManager->GetBackendType() != LayersBackend::LAYERS_WR) {
830 return false;
833 return true;
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!");
841 return nullptr;
844 //******************************************************************************
845 NS_IMETHODIMP_(bool)
846 VectorImage::IsImageContainerAvailableAtSize(LayerManager* aManager,
847 const IntSize& aSize,
848 uint32_t aFlags) {
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,
859 uint32_t aFlags,
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) {
875 bool overridePAR =
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
891 if (overridePAR) {
892 // The SVGImageContext must take account of the preserveAspectRatio
893 // override:
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,
918 float aOpacity) {
919 if (aWhichFrame > FRAME_MAX_VALUE) {
920 return ImgDrawResult::BAD_ARGS;
923 if (!aContext) {
924 return ImgDrawResult::BAD_ARGS;
927 if (mError) {
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)
959 ? 0.0f
960 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
962 Maybe<SVGImageContext> newSVGContext;
963 bool contextPaint =
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);
975 if (sourceSurface) {
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:
984 if (mIsDrawing) {
985 NS_WARNING("Refusing to make re-entrant call to VectorImage::Draw");
986 return ImgDrawResult::TEMPORARY_ERROR;
989 AutoRestoreSVGState autoRestore(params, mSVGDocumentWrapper, mIsDrawing,
990 contextPaint);
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,
1019 uint32_t aFlags) {
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);
1036 } else {
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,
1062 bool& aWillCache) {
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.
1074 !mHaveAnimations &&
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) {
1082 return nullptr;
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.
1091 if (aWillCache) {
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)) {
1111 aWillCache = false;
1112 return nullptr;
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();
1118 if (!surface) {
1119 aWillCache = false;
1120 return nullptr;
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.
1125 if (!aWillCache) {
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 if (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));
1141 } else {
1142 aWillCache = false;
1145 return surface.forget();
1148 void VectorImage::SendFrameComplete(bool aDidCache, uint32_t aFlags) {
1149 // If the cache was not updated, we have nothing to do.
1150 if (!aDidCache) {
1151 return;
1154 // Send out an invalidation so that surfaces that are still in use get
1155 // re-locked. See the discussion of the UnlockSurfaces call above.
1156 if (!(aFlags & FLAG_ASYNC_NOTIFY)) {
1157 mProgressTracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1158 GetMaxSizedIntRect());
1159 } else {
1160 NotNull<RefPtr<VectorImage>> image = WrapNotNull(this);
1161 NS_DispatchToMainThread(CreateMediumHighRunnable(NS_NewRunnableFunction(
1162 "ProgressTracker::SyncNotifyProgress", [=]() -> void {
1163 RefPtr<ProgressTracker> tracker = image->GetProgressTracker();
1164 if (tracker) {
1165 tracker->SyncNotifyProgress(FLAG_FRAME_COMPLETE,
1166 GetMaxSizedIntRect());
1168 })));
1172 void VectorImage::Show(gfxDrawable* aDrawable,
1173 const SVGDrawingParameters& aParams) {
1174 // The surface size may differ from the size at which we wish to draw. As
1175 // such, we may need to adjust the context/region to take this into account.
1176 gfxContextMatrixAutoSaveRestore saveMatrix(aParams.context);
1177 ImageRegion region(aParams.region);
1178 if (aParams.drawSize != aParams.size) {
1179 gfx::Size scale(double(aParams.drawSize.width) / aParams.size.width,
1180 double(aParams.drawSize.height) / aParams.size.height);
1181 aParams.context->Multiply(gfxMatrix::Scaling(scale.width, scale.height));
1182 region.Scale(1.0 / scale.width, 1.0 / scale.height);
1185 MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
1186 gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
1187 SizeDouble(aParams.size), region,
1188 SurfaceFormat::OS_RGBA, aParams.samplingFilter,
1189 aParams.flags, aParams.opacity, false);
1191 #ifdef DEBUG
1192 NotifyDrawingObservers();
1193 #endif
1195 MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
1196 mRenderingObserver->ResumeHonoringInvalidations();
1199 void VectorImage::RecoverFromLossOfSurfaces() {
1200 NS_WARNING("An imgFrame became invalid. Attempting to recover...");
1202 // Discard all existing frames, since they're probably all now invalid.
1203 SurfaceCache::RemoveImage(ImageKey(this));
1206 NS_IMETHODIMP
1207 VectorImage::StartDecoding(uint32_t aFlags, uint32_t aWhichFrame) {
1208 // Nothing to do for SVG images
1209 return NS_OK;
1212 bool VectorImage::StartDecodingWithResult(uint32_t aFlags,
1213 uint32_t aWhichFrame) {
1214 // SVG images are ready to draw when they are loaded
1215 return mIsFullyLoaded;
1218 bool VectorImage::RequestDecodeWithResult(uint32_t aFlags,
1219 uint32_t aWhichFrame) {
1220 // SVG images are ready to draw when they are loaded
1221 return mIsFullyLoaded;
1224 NS_IMETHODIMP
1225 VectorImage::RequestDecodeForSize(const nsIntSize& aSize, uint32_t aFlags,
1226 uint32_t aWhichFrame) {
1227 // Nothing to do for SVG images, though in theory we could rasterize to the
1228 // provided size ahead of time if we supported off-main-thread SVG
1229 // rasterization...
1230 return NS_OK;
1233 //******************************************************************************
1235 NS_IMETHODIMP
1236 VectorImage::LockImage() {
1237 MOZ_ASSERT(NS_IsMainThread());
1239 if (mError) {
1240 return NS_ERROR_FAILURE;
1243 mLockCount++;
1245 if (mLockCount == 1) {
1246 // Lock this image's surfaces in the SurfaceCache.
1247 SurfaceCache::LockImage(ImageKey(this));
1250 return NS_OK;
1253 //******************************************************************************
1255 NS_IMETHODIMP
1256 VectorImage::UnlockImage() {
1257 MOZ_ASSERT(NS_IsMainThread());
1259 if (mError) {
1260 return NS_ERROR_FAILURE;
1263 if (mLockCount == 0) {
1264 MOZ_ASSERT_UNREACHABLE("Calling UnlockImage with a zero lock count");
1265 return NS_ERROR_ABORT;
1268 mLockCount--;
1270 if (mLockCount == 0) {
1271 // Unlock this image's surfaces in the SurfaceCache.
1272 SurfaceCache::UnlockImage(ImageKey(this));
1275 return NS_OK;
1278 //******************************************************************************
1280 NS_IMETHODIMP
1281 VectorImage::RequestDiscard() {
1282 MOZ_ASSERT(NS_IsMainThread());
1284 if (mDiscardable && mLockCount == 0) {
1285 SurfaceCache::RemoveImage(ImageKey(this));
1286 mProgressTracker->OnDiscard();
1289 if (Document* doc =
1290 mSVGDocumentWrapper ? mSVGDocumentWrapper->GetDocument() : nullptr) {
1291 doc->ReportUseCounters();
1294 return NS_OK;
1297 void VectorImage::OnSurfaceDiscarded(const SurfaceKey& aSurfaceKey) {
1298 MOZ_ASSERT(mProgressTracker);
1300 NS_DispatchToMainThread(NewRunnableMethod("ProgressTracker::OnDiscard",
1301 mProgressTracker,
1302 &ProgressTracker::OnDiscard));
1305 //******************************************************************************
1306 NS_IMETHODIMP
1307 VectorImage::ResetAnimation() {
1308 if (mError) {
1309 return NS_ERROR_FAILURE;
1312 if (!mIsFullyLoaded || !mHaveAnimations) {
1313 return NS_OK; // There are no animations to be reset.
1316 mSVGDocumentWrapper->ResetAnimation();
1318 return NS_OK;
1321 NS_IMETHODIMP_(float)
1322 VectorImage::GetFrameIndex(uint32_t aWhichFrame) {
1323 MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE, "Invalid argument");
1324 return aWhichFrame == FRAME_FIRST
1325 ? 0.0f
1326 : mSVGDocumentWrapper->GetCurrentTimeAsFloat();
1329 //------------------------------------------------------------------------------
1330 // nsIRequestObserver methods
1332 //******************************************************************************
1333 NS_IMETHODIMP
1334 VectorImage::OnStartRequest(nsIRequest* aRequest) {
1335 MOZ_ASSERT(!mSVGDocumentWrapper,
1336 "Repeated call to OnStartRequest -- can this happen?");
1338 mSVGDocumentWrapper = new SVGDocumentWrapper();
1339 nsresult rv = mSVGDocumentWrapper->OnStartRequest(aRequest);
1340 if (NS_FAILED(rv)) {
1341 mSVGDocumentWrapper = nullptr;
1342 mError = true;
1343 return rv;
1346 // Create a listener to wait until the SVG document is fully loaded, which
1347 // will signal that this image is ready to render. Certain error conditions
1348 // will prevent us from ever getting this notification, so we also create a
1349 // listener that waits for parsing to complete and cancels the
1350 // SVGLoadEventListener if needed. The listeners are automatically attached
1351 // to the document by their constructors.
1352 SVGDocument* document = mSVGDocumentWrapper->GetDocument();
1353 mLoadEventListener = new SVGLoadEventListener(document, this);
1354 mParseCompleteListener = new SVGParseCompleteListener(document, this);
1356 return NS_OK;
1359 //******************************************************************************
1360 NS_IMETHODIMP
1361 VectorImage::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
1362 if (mError) {
1363 return NS_ERROR_FAILURE;
1366 return mSVGDocumentWrapper->OnStopRequest(aRequest, aStatus);
1369 void VectorImage::OnSVGDocumentParsed() {
1370 MOZ_ASSERT(mParseCompleteListener, "Should have the parse complete listener");
1371 MOZ_ASSERT(mLoadEventListener, "Should have the load event listener");
1373 if (!mSVGDocumentWrapper->GetRootSVGElem()) {
1374 // This is an invalid SVG document. It may have failed to parse, or it may
1375 // be missing the <svg> root element, or the <svg> root element may not
1376 // declare the correct namespace. In any of these cases, we'll never be
1377 // notified that the SVG finished loading, so we need to treat this as an
1378 // error.
1379 OnSVGDocumentError();
1383 void VectorImage::CancelAllListeners() {
1384 if (mParseCompleteListener) {
1385 mParseCompleteListener->Cancel();
1386 mParseCompleteListener = nullptr;
1388 if (mLoadEventListener) {
1389 mLoadEventListener->Cancel();
1390 mLoadEventListener = nullptr;
1394 void VectorImage::OnSVGDocumentLoaded() {
1395 MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(),
1396 "Should have parsed successfully");
1397 MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations,
1398 "These flags shouldn't get set until OnSVGDocumentLoaded. "
1399 "Duplicate calls to OnSVGDocumentLoaded?");
1401 CancelAllListeners();
1403 // XXX Flushing is wasteful if embedding frame hasn't had initial reflow.
1404 mSVGDocumentWrapper->FlushLayout();
1406 mIsFullyLoaded = true;
1407 mHaveAnimations = mSVGDocumentWrapper->IsAnimated();
1409 // Start listening to our image for rendering updates.
1410 mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this);
1412 // ProgressTracker::SyncNotifyProgress may release us, so ensure we
1413 // stick around long enough to complete our work.
1414 RefPtr<VectorImage> kungFuDeathGrip(this);
1416 // Tell *our* observers that we're done loading.
1417 if (mProgressTracker) {
1418 Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY |
1419 FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE;
1421 if (mHaveAnimations) {
1422 progress |= FLAG_IS_ANIMATED;
1425 // Merge in any saved progress from OnImageDataComplete.
1426 if (mLoadProgress) {
1427 progress |= *mLoadProgress;
1428 mLoadProgress = Nothing();
1431 mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect());
1434 EvaluateAnimation();
1437 void VectorImage::OnSVGDocumentError() {
1438 CancelAllListeners();
1440 mError = true;
1442 if (mProgressTracker) {
1443 // Notify observers about the error and unblock page load.
1444 Progress progress = FLAG_HAS_ERROR;
1446 // Merge in any saved progress from OnImageDataComplete.
1447 if (mLoadProgress) {
1448 progress |= *mLoadProgress;
1449 mLoadProgress = Nothing();
1452 mProgressTracker->SyncNotifyProgress(progress);
1456 //------------------------------------------------------------------------------
1457 // nsIStreamListener method
1459 //******************************************************************************
1460 NS_IMETHODIMP
1461 VectorImage::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
1462 uint64_t aSourceOffset, uint32_t aCount) {
1463 if (mError) {
1464 return NS_ERROR_FAILURE;
1467 return mSVGDocumentWrapper->OnDataAvailable(aRequest, aInStr, aSourceOffset,
1468 aCount);
1471 // --------------------------
1472 // Invalidation helper method
1474 void VectorImage::InvalidateObserversOnNextRefreshDriverTick() {
1475 if (mHasPendingInvalidation) {
1476 return;
1479 mHasPendingInvalidation = true;
1481 // Animated images can wait for the refresh tick.
1482 if (mHaveAnimations) {
1483 return;
1486 // Non-animated images won't get the refresh tick, so we should just send an
1487 // invalidation outside the current execution context. We need to defer
1488 // because the layout tree is in the middle of invalidation, and the tree
1489 // state needs to be consistent. Specifically only some of the frames have
1490 // had the NS_FRAME_DESCENDANT_NEEDS_PAINT and/or NS_FRAME_NEEDS_PAINT bits
1491 // set by InvalidateFrameInternal in layout/generic/nsFrame.cpp. These bits
1492 // get cleared when we repaint the SVG into a surface by
1493 // nsIFrame::ClearInvalidationStateBits in nsDisplayList::PaintRoot.
1494 nsCOMPtr<nsIEventTarget> eventTarget;
1495 if (mProgressTracker) {
1496 eventTarget = mProgressTracker->GetEventTarget();
1497 } else {
1498 eventTarget = do_GetMainThread();
1501 RefPtr<VectorImage> self(this);
1502 nsCOMPtr<nsIRunnable> ev(NS_NewRunnableFunction(
1503 "VectorImage::SendInvalidationNotifications",
1504 [=]() -> void { self->SendInvalidationNotifications(); }));
1505 eventTarget->Dispatch(CreateMediumHighRunnable(ev.forget()),
1506 NS_DISPATCH_NORMAL);
1509 void VectorImage::PropagateUseCounters(Document* aParentDocument) {
1510 Document* doc = mSVGDocumentWrapper->GetDocument();
1511 if (doc) {
1512 doc->PropagateUseCounters(aParentDocument);
1516 nsIntSize VectorImage::OptimalImageSizeForDest(const gfxSize& aDest,
1517 uint32_t aWhichFrame,
1518 SamplingFilter aSamplingFilter,
1519 uint32_t aFlags) {
1520 MOZ_ASSERT(aDest.width >= 0 || ceil(aDest.width) <= INT32_MAX ||
1521 aDest.height >= 0 || ceil(aDest.height) <= INT32_MAX,
1522 "Unexpected destination size");
1524 // We can rescale SVGs freely, so just return the provided destination size.
1525 return nsIntSize::Ceil(aDest.width, aDest.height);
1528 already_AddRefed<imgIContainer> VectorImage::Unwrap() {
1529 nsCOMPtr<imgIContainer> self(this);
1530 return self.forget();
1533 void VectorImage::MediaFeatureValuesChangedAllDocuments(
1534 const MediaFeatureChange& aChange) {
1535 if (!mSVGDocumentWrapper) {
1536 return;
1539 // Don't bother if the document hasn't loaded yet.
1540 if (!mIsFullyLoaded) {
1541 return;
1544 if (Document* doc = mSVGDocumentWrapper->GetDocument()) {
1545 if (nsPresContext* presContext = doc->GetPresContext()) {
1546 presContext->MediaFeatureValuesChangedAllDocuments(aChange);
1547 // Media feature value changes don't happen in the middle of layout,
1548 // so we don't need to call InvalidateObserversOnNextRefreshDriverTick
1549 // to invalidate asynchronously.
1551 // Ideally we would not invalidate images if the media feature value
1552 // change did not cause any updates to the document, but since non-
1553 // animated SVG images do not have their refresh driver ticked, it
1554 // is the invalidation (and then the painting) which is what causes
1555 // the document to be flushed. Theme and system metrics changes are
1556 // rare, though, so it's not a big deal to invalidate even if it
1557 // doesn't cause any change.
1558 SendInvalidationNotifications();
1563 } // namespace image
1564 } // namespace mozilla