summaryrefslogtreecommitdiffstats
path: root/image/SVGDocumentWrapper.cpp
blob: 2c081afb9ec57d360eaf01bf53762b3e17503bda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "SVGDocumentWrapper.h"

#include "mozilla/PresShell.h"
#include "mozilla/SMILAnimationController.h"
#include "mozilla/SVGObserverUtils.h"
#include "mozilla/dom/Animation.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ImageTracker.h"
#include "mozilla/dom/SVGDocument.h"
#include "mozilla/dom/SVGSVGElement.h"
#include "nsICategoryManager.h"
#include "nsIChannel.h"
#include "nsIContentViewer.h"
#include "nsIDocumentLoaderFactory.h"
#include "nsIHttpChannel.h"
#include "nsIObserverService.h"
#include "nsIParser.h"
#include "nsIRequest.h"
#include "nsIStreamListener.h"
#include "nsIXMLContentSink.h"
#include "nsNetCID.h"
#include "nsComponentManagerUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsMimeTypes.h"
#include "nsRefreshDriver.h"

namespace mozilla {

using namespace dom;
using namespace gfx;

namespace image {

NS_IMPL_ISUPPORTS(SVGDocumentWrapper, nsIStreamListener, nsIRequestObserver,
                  nsIObserver, nsISupportsWeakReference)

SVGDocumentWrapper::SVGDocumentWrapper()
    : mIgnoreInvalidation(false),
      mRegisteredForXPCOMShutdown(false),
      mIsDrawing(false) {}

SVGDocumentWrapper::~SVGDocumentWrapper() {
  DestroyViewer();
  if (mRegisteredForXPCOMShutdown) {
    UnregisterForXPCOMShutdown();
  }
}

void SVGDocumentWrapper::DestroyViewer() {
  if (mViewer) {
    mViewer->GetDocument()->OnPageHide(false, nullptr);
    mViewer->Close(nullptr);
    mViewer->Destroy();
    mViewer = nullptr;
  }
}

nsIFrame* SVGDocumentWrapper::GetRootLayoutFrame() {
  Element* rootElem = GetRootSVGElem();
  return rootElem ? rootElem->GetPrimaryFrame() : nullptr;
}

void SVGDocumentWrapper::UpdateViewportBounds(const nsIntSize& aViewportSize) {
  MOZ_ASSERT(!mIgnoreInvalidation, "shouldn't be reentrant");
  mIgnoreInvalidation = true;

  nsIntRect currentBounds;
  mViewer->GetBounds(currentBounds);

  // If the bounds have changed, we need to do a layout flush.
  if (currentBounds.Size() != aViewportSize) {
    mViewer->SetBounds(IntRect(IntPoint(0, 0), aViewportSize));
    FlushLayout();
  }

  mIgnoreInvalidation = false;
}

void SVGDocumentWrapper::FlushImageTransformInvalidation() {
  MOZ_ASSERT(!mIgnoreInvalidation, "shouldn't be reentrant");

  SVGSVGElement* svgElem = GetRootSVGElem();
  if (!svgElem) {
    return;
  }

  mIgnoreInvalidation = true;
  svgElem->FlushImageTransformInvalidation();
  FlushLayout();
  mIgnoreInvalidation = false;
}

bool SVGDocumentWrapper::IsAnimated() {
  // Can be called for animated images during shutdown, after we've
  // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
  if (!mViewer) {
    return false;
  }

  Document* doc = mViewer->GetDocument();
  if (!doc) {
    return false;
  }
  if (doc->Timeline()->HasAnimations()) {
    // CSS animations (technically HasAnimations() also checks for CSS
    // transitions and Web animations but since SVG-as-an-image doesn't run
    // script they will never run in the document that we wrap).
    return true;
  }
  if (doc->HasAnimationController() &&
      doc->GetAnimationController()->HasRegisteredAnimations()) {
    // SMIL animations
    return true;
  }
  return false;
}

void SVGDocumentWrapper::StartAnimation() {
  // Can be called for animated images during shutdown, after we've
  // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
  if (!mViewer) {
    return;
  }

  Document* doc = mViewer->GetDocument();
  if (doc) {
    SMILAnimationController* controller = doc->GetAnimationController();
    if (controller) {
      controller->Resume(SMILTimeContainer::PAUSE_IMAGE);
    }
    doc->ImageTracker()->SetAnimatingState(true);
  }
}

void SVGDocumentWrapper::StopAnimation() {
  // Can be called for animated images during shutdown, after we've
  // already Observe()'d XPCOM shutdown and cleared out our mViewer pointer.
  if (!mViewer) {
    return;
  }

  Document* doc = mViewer->GetDocument();
  if (doc) {
    SMILAnimationController* controller = doc->GetAnimationController();
    if (controller) {
      controller->Pause(SMILTimeContainer::PAUSE_IMAGE);
    }
    doc->ImageTracker()->SetAnimatingState(false);
  }
}

void SVGDocumentWrapper::ResetAnimation() {
  SVGSVGElement* svgElem = GetRootSVGElem();
  if (!svgElem) {
    return;
  }

  svgElem->SetCurrentTime(0.0f);
}

float SVGDocumentWrapper::GetCurrentTimeAsFloat() {
  SVGSVGElement* svgElem = GetRootSVGElem();
  return svgElem ? svgElem->GetCurrentTimeAsFloat() : 0.0f;
}

void SVGDocumentWrapper::SetCurrentTime(float aTime) {
  SVGSVGElement* svgElem = GetRootSVGElem();
  if (svgElem && svgElem->GetCurrentTimeAsFloat() != aTime) {
    svgElem->SetCurrentTime(aTime);
  }
}

void SVGDocumentWrapper::TickRefreshDriver() {
  if (RefPtr<PresShell> presShell = mViewer->GetPresShell()) {
    if (RefPtr<nsPresContext> presContext = presShell->GetPresContext()) {
      if (RefPtr<nsRefreshDriver> driver = presContext->RefreshDriver()) {
        driver->DoTick();
      }
    }
  }
}

/** nsIStreamListener methods **/

NS_IMETHODIMP
SVGDocumentWrapper::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* inStr,
                                    uint64_t sourceOffset, uint32_t count) {
  return mListener->OnDataAvailable(aRequest, inStr, sourceOffset, count);
}

/** nsIRequestObserver methods **/

NS_IMETHODIMP
SVGDocumentWrapper::OnStartRequest(nsIRequest* aRequest) {
  nsresult rv = SetupViewer(aRequest, getter_AddRefs(mViewer),
                            getter_AddRefs(mLoadGroup));

  if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(mListener->OnStartRequest(aRequest))) {
    mViewer->GetDocument()->SetIsBeingUsedAsImage();
    StopAnimation();  // otherwise animations start automatically in helper doc

    rv = mViewer->Init(nullptr, nsIntRect(0, 0, 0, 0), nullptr);
    if (NS_SUCCEEDED(rv)) {
      rv = mViewer->Open(nullptr, nullptr);
    }
  }
  return rv;
}

NS_IMETHODIMP
SVGDocumentWrapper::OnStopRequest(nsIRequest* aRequest, nsresult status) {
  if (mListener) {
    mListener->OnStopRequest(aRequest, status);
    mListener = nullptr;
  }

  return NS_OK;
}

/** nsIObserver Methods **/
NS_IMETHODIMP
SVGDocumentWrapper::Observe(nsISupports* aSubject, const char* aTopic,
                            const char16_t* aData) {
  if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
    // Sever ties from rendering observers to helper-doc's root SVG node
    SVGSVGElement* svgElem = GetRootSVGElem();
    if (svgElem) {
      SVGObserverUtils::RemoveAllRenderingObservers(svgElem);
    }

    // Clean up at XPCOM shutdown time.
    DestroyViewer();
    if (mListener) {
      mListener = nullptr;
    }
    if (mLoadGroup) {
      mLoadGroup = nullptr;
    }

    // Turn off "registered" flag, or else we'll try to unregister when we die.
    // (No need for that now, and the try would fail anyway -- it's too late.)
    mRegisteredForXPCOMShutdown = false;
  } else {
    NS_ERROR("Unexpected observer topic.");
  }
  return NS_OK;
}

/** Private helper methods **/

// This method is largely cribbed from
// nsExternalResourceMap::PendingLoad::SetupViewer.
nsresult SVGDocumentWrapper::SetupViewer(nsIRequest* aRequest,
                                         nsIContentViewer** aViewer,
                                         nsILoadGroup** aLoadGroup) {
  nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
  NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);

  // Check for HTTP error page
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
  if (httpChannel) {
    bool requestSucceeded;
    if (NS_FAILED(httpChannel->GetRequestSucceeded(&requestSucceeded)) ||
        !requestSucceeded) {
      return NS_ERROR_FAILURE;
    }
  }

  // Give this document its own loadgroup
  nsCOMPtr<nsILoadGroup> loadGroup;
  chan->GetLoadGroup(getter_AddRefs(loadGroup));

  nsCOMPtr<nsILoadGroup> newLoadGroup =
      do_CreateInstance(NS_LOADGROUP_CONTRACTID);
  NS_ENSURE_TRUE(newLoadGroup, NS_ERROR_OUT_OF_MEMORY);
  newLoadGroup->SetLoadGroup(loadGroup);

  nsCOMPtr<nsICategoryManager> catMan =
      do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
  NS_ENSURE_TRUE(catMan, NS_ERROR_NOT_AVAILABLE);
  nsCString contractId;
  nsresult rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", IMAGE_SVG_XML,
                                         contractId);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIDocumentLoaderFactory> docLoaderFactory =
      do_GetService(contractId.get());
  NS_ENSURE_TRUE(docLoaderFactory, NS_ERROR_NOT_AVAILABLE);

  nsCOMPtr<nsIContentViewer> viewer;
  nsCOMPtr<nsIStreamListener> listener;
  rv = docLoaderFactory->CreateInstance(
      "external-resource", chan, newLoadGroup, nsLiteralCString(IMAGE_SVG_XML),
      nullptr, nullptr, getter_AddRefs(listener), getter_AddRefs(viewer));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);

  // Create a navigation time object and pass it to the SVG document through
  // the viewer.
  // The timeline(DocumentTimeline, used in CSS animation) of this SVG
  // document needs this navigation timing object for time computation, such
  // as to calculate current time stamp based on the start time of navigation
  // time object.
  //
  // For a root document, DocShell would do these sort of things
  // automatically. Since there is no DocShell for this wrapped SVG document,
  // we must set it up manually.
  RefPtr<nsDOMNavigationTiming> timing = new nsDOMNavigationTiming(nullptr);
  timing->NotifyNavigationStart(
      nsDOMNavigationTiming::DocShellState::eInactive);
  viewer->SetNavigationTiming(timing);

  nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
  NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);

  // XML-only, because this is for SVG content
  nsCOMPtr<nsIContentSink> sink = parser->GetContentSink();
  NS_ENSURE_TRUE(sink, NS_ERROR_UNEXPECTED);

  listener.swap(mListener);
  viewer.forget(aViewer);
  newLoadGroup.forget(aLoadGroup);

  RegisterForXPCOMShutdown();
  return NS_OK;
}

void SVGDocumentWrapper::RegisterForXPCOMShutdown() {
  MOZ_ASSERT(!mRegisteredForXPCOMShutdown, "re-registering for XPCOM shutdown");
  // Listen for xpcom-shutdown so that we can drop references to our
  // helper-document at that point. (Otherwise, we won't get cleaned up
  // until imgLoader::Shutdown, which can happen after the JAR service
  // and RDF service have been unregistered.)
  nsresult rv;
  nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
  if (NS_FAILED(rv) || NS_FAILED(obsSvc->AddObserver(
                           this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true))) {
    NS_WARNING("Failed to register as observer of XPCOM shutdown");
  } else {
    mRegisteredForXPCOMShutdown = true;
  }
}

void SVGDocumentWrapper::UnregisterForXPCOMShutdown() {
  MOZ_ASSERT(mRegisteredForXPCOMShutdown,
             "unregistering for XPCOM shutdown w/out being registered");

  nsresult rv;
  nsCOMPtr<nsIObserverService> obsSvc = do_GetService(OBSERVER_SVC_CID, &rv);
  if (NS_FAILED(rv) ||
      NS_FAILED(obsSvc->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID))) {
    NS_WARNING("Failed to unregister as observer of XPCOM shutdown");
  } else {
    mRegisteredForXPCOMShutdown = false;
  }
}

void SVGDocumentWrapper::FlushLayout() {
  if (SVGDocument* doc = GetDocument()) {
    doc->FlushPendingNotifications(FlushType::Layout);
  }
}

SVGDocument* SVGDocumentWrapper::GetDocument() {
  if (!mViewer) {
    return nullptr;
  }
  Document* doc = mViewer->GetDocument();
  if (!doc) {
    return nullptr;
  }
  return doc->AsSVGDocument();
}

SVGSVGElement* SVGDocumentWrapper::GetRootSVGElem() {
  if (!mViewer) {
    return nullptr;  // Can happen during destruction
  }

  Document* doc = mViewer->GetDocument();
  if (!doc) {
    return nullptr;  // Can happen during destruction
  }

  Element* rootElem = mViewer->GetDocument()->GetRootElement();
  if (!rootElem || !rootElem->IsSVGElement(nsGkAtoms::svg)) {
    return nullptr;
  }

  return static_cast<SVGSVGElement*>(rootElem);
}

}  // namespace image
}  // namespace mozilla