Bug 1608150 [wpt PR 21112] - Add missing space in `./wpt lint` command line docs...
[gecko.git] / image / SVGDocumentWrapper.cpp
blob9f018c376c75fc53343c51b8ffa08d7682b669d6
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 "SVGDocumentWrapper.h"
8 #include "mozilla/PresShell.h"
9 #include "mozilla/SMILAnimationController.h"
10 #include "mozilla/dom/Document.h"
11 #include "mozilla/dom/DocumentTimeline.h"
12 #include "mozilla/dom/Element.h"
13 #include "mozilla/dom/ImageTracker.h"
14 #include "mozilla/dom/SVGDocument.h"
15 #include "mozilla/dom/SVGSVGElement.h"
16 #include "nsICategoryManager.h"
17 #include "nsIChannel.h"
18 #include "nsIContentViewer.h"
19 #include "nsIDocumentLoaderFactory.h"
20 #include "nsIHttpChannel.h"
21 #include "nsIObserverService.h"
22 #include "nsIParser.h"
23 #include "nsIRequest.h"
24 #include "nsIStreamListener.h"
25 #include "nsIXMLContentSink.h"
26 #include "nsNetCID.h"
27 #include "nsComponentManagerUtils.h"
28 #include "nsServiceManagerUtils.h"
29 #include "SVGObserverUtils.h"
30 #include "nsMimeTypes.h"
32 namespace mozilla {
34 using namespace dom;
35 using namespace gfx;
37 namespace image {
39 NS_IMPL_ISUPPORTS(SVGDocumentWrapper, nsIStreamListener, nsIRequestObserver,
40 nsIObserver, nsISupportsWeakReference)
42 SVGDocumentWrapper::SVGDocumentWrapper()
43 : mIgnoreInvalidation(false), mRegisteredForXPCOMShutdown(false) {}
45 SVGDocumentWrapper::~SVGDocumentWrapper() {
46 DestroyViewer();
47 if (mRegisteredForXPCOMShutdown) {
48 UnregisterForXPCOMShutdown();
52 void SVGDocumentWrapper::DestroyViewer() {
53 if (mViewer) {
54 mViewer->GetDocument()->OnPageHide(false, nullptr);
55 mViewer->Close(nullptr);
56 mViewer->Destroy();
57 mViewer = nullptr;
61 nsIFrame* SVGDocumentWrapper::GetRootLayoutFrame() {
62 Element* rootElem = GetRootSVGElem();
63 return rootElem ? rootElem->GetPrimaryFrame() : nullptr;
66 void SVGDocumentWrapper::UpdateViewportBounds(const nsIntSize& aViewportSize) {
67 MOZ_ASSERT(!mIgnoreInvalidation, "shouldn't be reentrant");
68 mIgnoreInvalidation = true;
70 nsIntRect currentBounds;
71 mViewer->GetBounds(currentBounds);
73 // If the bounds have changed, we need to do a layout flush.
74 if (currentBounds.Size() != aViewportSize) {
75 mViewer->SetBounds(IntRect(IntPoint(0, 0), aViewportSize));
76 FlushLayout();
79 mIgnoreInvalidation = false;
82 void SVGDocumentWrapper::FlushImageTransformInvalidation() {
83 MOZ_ASSERT(!mIgnoreInvalidation, "shouldn't be reentrant");
85 SVGSVGElement* svgElem = GetRootSVGElem();
86 if (!svgElem) {
87 return;
90 mIgnoreInvalidation = true;
91 svgElem->FlushImageTransformInvalidation();
92 FlushLayout();
93 mIgnoreInvalidation = false;
96 bool SVGDocumentWrapper::IsAnimated() {
97 // Can be called for animated images during shutdown, after we've
98 // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
99 if (!mViewer) {
100 return false;
103 Document* doc = mViewer->GetDocument();
104 if (!doc) {
105 return false;
107 if (doc->Timeline()->HasAnimations()) {
108 // CSS animations (technically HasAnimations() also checks for CSS
109 // transitions and Web animations but since SVG-as-an-image doesn't run
110 // script they will never run in the document that we wrap).
111 return true;
113 if (doc->HasAnimationController() &&
114 doc->GetAnimationController()->HasRegisteredAnimations()) {
115 // SMIL animations
116 return true;
118 return false;
121 void SVGDocumentWrapper::StartAnimation() {
122 // Can be called for animated images during shutdown, after we've
123 // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
124 if (!mViewer) {
125 return;
128 Document* doc = mViewer->GetDocument();
129 if (doc) {
130 SMILAnimationController* controller = doc->GetAnimationController();
131 if (controller) {
132 controller->Resume(SMILTimeContainer::PAUSE_IMAGE);
134 doc->ImageTracker()->SetAnimatingState(true);
138 void SVGDocumentWrapper::StopAnimation() {
139 // Can be called for animated images during shutdown, after we've
140 // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
141 if (!mViewer) {
142 return;
145 Document* doc = mViewer->GetDocument();
146 if (doc) {
147 SMILAnimationController* controller = doc->GetAnimationController();
148 if (controller) {
149 controller->Pause(SMILTimeContainer::PAUSE_IMAGE);
151 doc->ImageTracker()->SetAnimatingState(false);
155 void SVGDocumentWrapper::ResetAnimation() {
156 SVGSVGElement* svgElem = GetRootSVGElem();
157 if (!svgElem) {
158 return;
161 svgElem->SetCurrentTime(0.0f);
164 float SVGDocumentWrapper::GetCurrentTimeAsFloat() {
165 SVGSVGElement* svgElem = GetRootSVGElem();
166 return svgElem ? svgElem->GetCurrentTimeAsFloat() : 0.0f;
169 void SVGDocumentWrapper::SetCurrentTime(float aTime) {
170 SVGSVGElement* svgElem = GetRootSVGElem();
171 if (svgElem && svgElem->GetCurrentTimeAsFloat() != aTime) {
172 svgElem->SetCurrentTime(aTime);
176 void SVGDocumentWrapper::TickRefreshDriver() {
177 if (RefPtr<PresShell> presShell = mViewer->GetPresShell()) {
178 if (RefPtr<nsPresContext> presContext = presShell->GetPresContext()) {
179 presContext->RefreshDriver()->DoTick();
184 /** nsIStreamListener methods **/
186 NS_IMETHODIMP
187 SVGDocumentWrapper::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* inStr,
188 uint64_t sourceOffset, uint32_t count) {
189 return mListener->OnDataAvailable(aRequest, inStr, sourceOffset, count);
192 /** nsIRequestObserver methods **/
194 NS_IMETHODIMP
195 SVGDocumentWrapper::OnStartRequest(nsIRequest* aRequest) {
196 nsresult rv = SetupViewer(aRequest, getter_AddRefs(mViewer),
197 getter_AddRefs(mLoadGroup));
199 if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(mListener->OnStartRequest(aRequest))) {
200 mViewer->GetDocument()->SetIsBeingUsedAsImage();
201 StopAnimation(); // otherwise animations start automatically in helper doc
203 rv = mViewer->Init(nullptr, nsIntRect(0, 0, 0, 0), nullptr);
204 if (NS_SUCCEEDED(rv)) {
205 rv = mViewer->Open(nullptr, nullptr);
208 return rv;
211 NS_IMETHODIMP
212 SVGDocumentWrapper::OnStopRequest(nsIRequest* aRequest, nsresult status) {
213 if (mListener) {
214 mListener->OnStopRequest(aRequest, status);
215 mListener = nullptr;
218 return NS_OK;
221 /** nsIObserver Methods **/
222 NS_IMETHODIMP
223 SVGDocumentWrapper::Observe(nsISupports* aSubject, const char* aTopic,
224 const char16_t* aData) {
225 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
226 // Sever ties from rendering observers to helper-doc's root SVG node
227 SVGSVGElement* svgElem = GetRootSVGElem();
228 if (svgElem) {
229 SVGObserverUtils::RemoveAllRenderingObservers(svgElem);
232 // Clean up at XPCOM shutdown time.
233 DestroyViewer();
234 if (mListener) {
235 mListener = nullptr;
237 if (mLoadGroup) {
238 mLoadGroup = nullptr;
241 // Turn off "registered" flag, or else we'll try to unregister when we die.
242 // (No need for that now, and the try would fail anyway -- it's too late.)
243 mRegisteredForXPCOMShutdown = false;
244 } else {
245 NS_ERROR("Unexpected observer topic.");
247 return NS_OK;
250 /** Private helper methods **/
252 // This method is largely cribbed from
253 // nsExternalResourceMap::PendingLoad::SetupViewer.
254 nsresult SVGDocumentWrapper::SetupViewer(nsIRequest* aRequest,
255 nsIContentViewer** aViewer,
256 nsILoadGroup** aLoadGroup) {
257 nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
258 NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);
260 // Check for HTTP error page
261 nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
262 if (httpChannel) {
263 bool requestSucceeded;
264 if (NS_FAILED(httpChannel->GetRequestSucceeded(&requestSucceeded)) ||
265 !requestSucceeded) {
266 return NS_ERROR_FAILURE;
270 // Give this document its own loadgroup
271 nsCOMPtr<nsILoadGroup> loadGroup;
272 chan->GetLoadGroup(getter_AddRefs(loadGroup));
274 nsCOMPtr<nsILoadGroup> newLoadGroup =
275 do_CreateInstance(NS_LOADGROUP_CONTRACTID);
276 NS_ENSURE_TRUE(newLoadGroup, NS_ERROR_OUT_OF_MEMORY);
277 newLoadGroup->SetLoadGroup(loadGroup);
279 nsCOMPtr<nsICategoryManager> catMan =
280 do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
281 NS_ENSURE_TRUE(catMan, NS_ERROR_NOT_AVAILABLE);
282 nsCString contractId;
283 nsresult rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", IMAGE_SVG_XML,
284 contractId);
285 NS_ENSURE_SUCCESS(rv, rv);
286 nsCOMPtr<nsIDocumentLoaderFactory> docLoaderFactory =
287 do_GetService(contractId.get());
288 NS_ENSURE_TRUE(docLoaderFactory, NS_ERROR_NOT_AVAILABLE);
290 nsCOMPtr<nsIContentViewer> viewer;
291 nsCOMPtr<nsIStreamListener> listener;
292 rv = docLoaderFactory->CreateInstance(
293 "external-resource", chan, newLoadGroup,
294 NS_LITERAL_CSTRING(IMAGE_SVG_XML), nullptr, nullptr,
295 getter_AddRefs(listener), getter_AddRefs(viewer));
296 NS_ENSURE_SUCCESS(rv, rv);
298 NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);
300 // Create a navigation time object and pass it to the SVG document through
301 // the viewer.
302 // The timeline(DocumentTimeline, used in CSS animation) of this SVG
303 // document needs this navigation timing object for time computation, such
304 // as to calculate current time stamp based on the start time of navigation
305 // time object.
307 // For a root document, DocShell would do these sort of things
308 // automatically. Since there is no DocShell for this wrapped SVG document,
309 // we must set it up manually.
310 RefPtr<nsDOMNavigationTiming> timing = new nsDOMNavigationTiming(nullptr);
311 timing->NotifyNavigationStart(
312 nsDOMNavigationTiming::DocShellState::eInactive);
313 viewer->SetNavigationTiming(timing);
315 nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
316 NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);
318 // XML-only, because this is for SVG content
319 nsCOMPtr<nsIContentSink> sink = parser->GetContentSink();
320 NS_ENSURE_TRUE(sink, NS_ERROR_UNEXPECTED);
322 listener.swap(mListener);
323 viewer.forget(aViewer);
324 newLoadGroup.forget(aLoadGroup);
326 RegisterForXPCOMShutdown();
327 return NS_OK;
330 void SVGDocumentWrapper::RegisterForXPCOMShutdown() {
331 MOZ_ASSERT(!mRegisteredForXPCOMShutdown, "re-registering for XPCOM shutdown");
332 // Listen for xpcom-shutdown so that we can drop references to our
333 // helper-document at that point. (Otherwise, we won't get cleaned up
334 // until imgLoader::Shutdown, which can happen after the JAR service
335 // and RDF service have been unregistered.)
336 nsresult rv;
337 nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
338 if (NS_FAILED(rv) || NS_FAILED(obsSvc->AddObserver(
339 this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true))) {
340 NS_WARNING("Failed to register as observer of XPCOM shutdown");
341 } else {
342 mRegisteredForXPCOMShutdown = true;
346 void SVGDocumentWrapper::UnregisterForXPCOMShutdown() {
347 MOZ_ASSERT(mRegisteredForXPCOMShutdown,
348 "unregistering for XPCOM shutdown w/out being registered");
350 nsresult rv;
351 nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
352 if (NS_FAILED(rv) ||
353 NS_FAILED(obsSvc->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID))) {
354 NS_WARNING("Failed to unregister as observer of XPCOM shutdown");
355 } else {
356 mRegisteredForXPCOMShutdown = false;
360 void SVGDocumentWrapper::FlushLayout() {
361 if (SVGDocument* doc = GetDocument()) {
362 doc->FlushPendingNotifications(FlushType::Layout);
366 SVGDocument* SVGDocumentWrapper::GetDocument() {
367 if (!mViewer) {
368 return nullptr;
370 Document* doc = mViewer->GetDocument();
371 if (!doc) {
372 return nullptr;
374 return doc->AsSVGDocument();
377 SVGSVGElement* SVGDocumentWrapper::GetRootSVGElem() {
378 if (!mViewer) {
379 return nullptr; // Can happen during destruction
382 Document* doc = mViewer->GetDocument();
383 if (!doc) {
384 return nullptr; // Can happen during destruction
387 Element* rootElem = mViewer->GetDocument()->GetRootElement();
388 if (!rootElem || !rootElem->IsSVGElement(nsGkAtoms::svg)) {
389 return nullptr;
392 return static_cast<SVGSVGElement*>(rootElem);
395 } // namespace image
396 } // namespace mozilla