Bug 1654678 Part 2 - Make CUPSPrinter own its CUPS dest data r=nordzilla
[gecko.git] / image / SVGDocumentWrapper.cpp
blobb58aa727562fd772d8f6a819231bd6d8668923e2
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/SVGObserverUtils.h"
11 #include "mozilla/dom/Document.h"
12 #include "mozilla/dom/DocumentTimeline.h"
13 #include "mozilla/dom/Element.h"
14 #include "mozilla/dom/ImageTracker.h"
15 #include "mozilla/dom/SVGDocument.h"
16 #include "mozilla/dom/SVGSVGElement.h"
17 #include "nsICategoryManager.h"
18 #include "nsIChannel.h"
19 #include "nsIContentViewer.h"
20 #include "nsIDocumentLoaderFactory.h"
21 #include "nsIHttpChannel.h"
22 #include "nsIObserverService.h"
23 #include "nsIParser.h"
24 #include "nsIRequest.h"
25 #include "nsIStreamListener.h"
26 #include "nsIXMLContentSink.h"
27 #include "nsNetCID.h"
28 #include "nsComponentManagerUtils.h"
29 #include "nsServiceManagerUtils.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, nsLiteralCString(IMAGE_SVG_XML),
294 nullptr, nullptr, getter_AddRefs(listener), getter_AddRefs(viewer));
295 NS_ENSURE_SUCCESS(rv, rv);
297 NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);
299 // Create a navigation time object and pass it to the SVG document through
300 // the viewer.
301 // The timeline(DocumentTimeline, used in CSS animation) of this SVG
302 // document needs this navigation timing object for time computation, such
303 // as to calculate current time stamp based on the start time of navigation
304 // time object.
306 // For a root document, DocShell would do these sort of things
307 // automatically. Since there is no DocShell for this wrapped SVG document,
308 // we must set it up manually.
309 RefPtr<nsDOMNavigationTiming> timing = new nsDOMNavigationTiming(nullptr);
310 timing->NotifyNavigationStart(
311 nsDOMNavigationTiming::DocShellState::eInactive);
312 viewer->SetNavigationTiming(timing);
314 nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
315 NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);
317 // XML-only, because this is for SVG content
318 nsCOMPtr<nsIContentSink> sink = parser->GetContentSink();
319 NS_ENSURE_TRUE(sink, NS_ERROR_UNEXPECTED);
321 listener.swap(mListener);
322 viewer.forget(aViewer);
323 newLoadGroup.forget(aLoadGroup);
325 RegisterForXPCOMShutdown();
326 return NS_OK;
329 void SVGDocumentWrapper::RegisterForXPCOMShutdown() {
330 MOZ_ASSERT(!mRegisteredForXPCOMShutdown, "re-registering for XPCOM shutdown");
331 // Listen for xpcom-shutdown so that we can drop references to our
332 // helper-document at that point. (Otherwise, we won't get cleaned up
333 // until imgLoader::Shutdown, which can happen after the JAR service
334 // and RDF service have been unregistered.)
335 nsresult rv;
336 nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
337 if (NS_FAILED(rv) || NS_FAILED(obsSvc->AddObserver(
338 this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true))) {
339 NS_WARNING("Failed to register as observer of XPCOM shutdown");
340 } else {
341 mRegisteredForXPCOMShutdown = true;
345 void SVGDocumentWrapper::UnregisterForXPCOMShutdown() {
346 MOZ_ASSERT(mRegisteredForXPCOMShutdown,
347 "unregistering for XPCOM shutdown w/out being registered");
349 nsresult rv;
350 nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
351 if (NS_FAILED(rv) ||
352 NS_FAILED(obsSvc->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID))) {
353 NS_WARNING("Failed to unregister as observer of XPCOM shutdown");
354 } else {
355 mRegisteredForXPCOMShutdown = false;
359 void SVGDocumentWrapper::FlushLayout() {
360 if (SVGDocument* doc = GetDocument()) {
361 doc->FlushPendingNotifications(FlushType::Layout);
365 SVGDocument* SVGDocumentWrapper::GetDocument() {
366 if (!mViewer) {
367 return nullptr;
369 Document* doc = mViewer->GetDocument();
370 if (!doc) {
371 return nullptr;
373 return doc->AsSVGDocument();
376 SVGSVGElement* SVGDocumentWrapper::GetRootSVGElem() {
377 if (!mViewer) {
378 return nullptr; // Can happen during destruction
381 Document* doc = mViewer->GetDocument();
382 if (!doc) {
383 return nullptr; // Can happen during destruction
386 Element* rootElem = mViewer->GetDocument()->GetRootElement();
387 if (!rootElem || !rootElem->IsSVGElement(nsGkAtoms::svg)) {
388 return nullptr;
391 return static_cast<SVGSVGElement*>(rootElem);
394 } // namespace image
395 } // namespace mozilla