Thu, 15 Jan 2015 21:03:48 +0100
Integrate friendly tips from Tor colleagues to make (or not) 4.5 alpha 3;
This includes removal of overloaded (but unused) methods, and addition of
a overlooked call to DataStruct::SetData(nsISupports, uint32_t, bool.)
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * Base class for all our document implementations.
9 */
11 #ifndef nsDocument_h___
12 #define nsDocument_h___
14 #include "nsIDocument.h"
16 #include "nsCOMPtr.h"
17 #include "nsAutoPtr.h"
18 #include "nsCRT.h"
19 #include "nsWeakReference.h"
20 #include "nsWeakPtr.h"
21 #include "nsVoidArray.h"
22 #include "nsTArray.h"
23 #include "nsIDOMXMLDocument.h"
24 #include "nsIDOMDocumentXBL.h"
25 #include "nsStubDocumentObserver.h"
26 #include "nsIScriptGlobalObject.h"
27 #include "nsIContent.h"
28 #include "nsIPrincipal.h"
29 #include "nsIParser.h"
30 #include "nsBindingManager.h"
31 #include "nsINodeInfo.h"
32 #include "nsInterfaceHashtable.h"
33 #include "nsJSThingHashtable.h"
34 #include "nsIBoxObject.h"
35 #include "nsPIBoxObject.h"
36 #include "nsIScriptObjectPrincipal.h"
37 #include "nsIURI.h"
38 #include "nsScriptLoader.h"
39 #include "nsIRadioGroupContainer.h"
40 #include "nsILayoutHistoryState.h"
41 #include "nsIRequest.h"
42 #include "nsILoadGroup.h"
43 #include "nsTObserverArray.h"
44 #include "nsStubMutationObserver.h"
45 #include "nsIChannel.h"
46 #include "nsCycleCollectionParticipant.h"
47 #include "nsContentList.h"
48 #include "nsGkAtoms.h"
49 #include "nsIApplicationCache.h"
50 #include "nsIApplicationCacheContainer.h"
51 #include "nsStyleSet.h"
52 #include "pldhash.h"
53 #include "nsAttrAndChildArray.h"
54 #include "nsDOMAttributeMap.h"
55 #include "nsIContentViewer.h"
56 #include "nsIDOMXPathNSResolver.h"
57 #include "nsIInterfaceRequestor.h"
58 #include "nsILoadContext.h"
59 #include "nsIProgressEventSink.h"
60 #include "nsISecurityEventSink.h"
61 #include "nsIChannelEventSink.h"
62 #include "imgIRequest.h"
63 #include "mozilla/EventListenerManager.h"
64 #include "mozilla/EventStates.h"
65 #include "mozilla/MemoryReporting.h"
66 #include "mozilla/dom/DOMImplementation.h"
67 #include "mozilla/dom/StyleSheetList.h"
68 #include "nsIDOMTouchEvent.h"
69 #include "nsDataHashtable.h"
70 #include "mozilla/TimeStamp.h"
71 #include "mozilla/Attributes.h"
72 #include "nsIDOMXPathEvaluator.h"
73 #include "jsfriendapi.h"
75 #define XML_DECLARATION_BITS_DECLARATION_EXISTS (1 << 0)
76 #define XML_DECLARATION_BITS_ENCODING_EXISTS (1 << 1)
77 #define XML_DECLARATION_BITS_STANDALONE_EXISTS (1 << 2)
78 #define XML_DECLARATION_BITS_STANDALONE_YES (1 << 3)
81 class nsDOMStyleSheetSetList;
82 class nsIOutputStream;
83 class nsDocument;
84 class nsIDTD;
85 class nsIRadioVisitor;
86 class nsIFormControl;
87 struct nsRadioGroupStruct;
88 class nsOnloadBlocker;
89 class nsUnblockOnloadEvent;
90 class nsChildContentList;
91 class nsHTMLStyleSheet;
92 class nsHTMLCSSStyleSheet;
93 class nsDOMNavigationTiming;
94 class nsWindowSizes;
95 class nsHtml5TreeOpExecutor;
96 class nsDocumentOnStack;
97 class nsPointerLockPermissionRequest;
98 class nsISecurityConsoleMessage;
100 namespace mozilla {
101 class EventChainPreVisitor;
102 namespace dom {
103 class UndoManager;
104 class LifecycleCallbacks;
105 class CallbackFunction;
106 }
107 }
109 /**
110 * Right now our identifier map entries contain information for 'name'
111 * and 'id' mappings of a given string. This is so that
112 * nsHTMLDocument::ResolveName only has to do one hash lookup instead
113 * of two. It's not clear whether this still matters for performance.
114 *
115 * We also store the document.all result list here. This is mainly so that
116 * when all elements with the given ID are removed and we remove
117 * the ID's nsIdentifierMapEntry, the document.all result is released too.
118 * Perhaps the document.all results should have their own hashtable
119 * in nsHTMLDocument.
120 */
121 class nsIdentifierMapEntry : public nsStringHashKey
122 {
123 public:
124 typedef mozilla::dom::Element Element;
126 nsIdentifierMapEntry(const nsAString& aKey) :
127 nsStringHashKey(&aKey), mNameContentList(nullptr)
128 {
129 }
130 nsIdentifierMapEntry(const nsAString *aKey) :
131 nsStringHashKey(aKey), mNameContentList(nullptr)
132 {
133 }
134 nsIdentifierMapEntry(const nsIdentifierMapEntry& aOther) :
135 nsStringHashKey(&aOther.GetKey())
136 {
137 NS_ERROR("Should never be called");
138 }
139 ~nsIdentifierMapEntry();
141 void AddNameElement(nsINode* aDocument, Element* aElement);
142 void RemoveNameElement(Element* aElement);
143 bool IsEmpty();
144 nsBaseContentList* GetNameContentList() {
145 return mNameContentList;
146 }
147 bool HasNameElement() const {
148 return mNameContentList && mNameContentList->Length() != 0;
149 }
151 /**
152 * Returns the element if we know the element associated with this
153 * id. Otherwise returns null.
154 */
155 Element* GetIdElement();
156 /**
157 * Returns the list of all elements associated with this id.
158 */
159 const nsSmallVoidArray* GetIdElements() const {
160 return &mIdContentList;
161 }
162 /**
163 * If this entry has a non-null image element set (using SetImageElement),
164 * the image element will be returned, otherwise the same as GetIdElement().
165 */
166 Element* GetImageIdElement();
167 /**
168 * Append all the elements with this id to aElements
169 */
170 void AppendAllIdContent(nsCOMArray<nsIContent>* aElements);
171 /**
172 * This can fire ID change callbacks.
173 * @return true if the content could be added, false if we failed due
174 * to OOM.
175 */
176 bool AddIdElement(Element* aElement);
177 /**
178 * This can fire ID change callbacks.
179 */
180 void RemoveIdElement(Element* aElement);
181 /**
182 * Set the image element override for this ID. This will be returned by
183 * GetIdElement(true) if non-null.
184 */
185 void SetImageElement(Element* aElement);
186 bool HasIdElementExposedAsHTMLDocumentProperty();
188 bool HasContentChangeCallback() { return mChangeCallbacks != nullptr; }
189 void AddContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
190 void* aData, bool aForImage);
191 void RemoveContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
192 void* aData, bool aForImage);
194 void Traverse(nsCycleCollectionTraversalCallback* aCallback);
196 struct ChangeCallback {
197 nsIDocument::IDTargetObserver mCallback;
198 void* mData;
199 bool mForImage;
200 };
202 struct ChangeCallbackEntry : public PLDHashEntryHdr {
203 typedef const ChangeCallback KeyType;
204 typedef const ChangeCallback* KeyTypePointer;
206 ChangeCallbackEntry(const ChangeCallback* key) :
207 mKey(*key) { }
208 ChangeCallbackEntry(const ChangeCallbackEntry& toCopy) :
209 mKey(toCopy.mKey) { }
211 KeyType GetKey() const { return mKey; }
212 bool KeyEquals(KeyTypePointer aKey) const {
213 return aKey->mCallback == mKey.mCallback &&
214 aKey->mData == mKey.mData &&
215 aKey->mForImage == mKey.mForImage;
216 }
218 static KeyTypePointer KeyToPointer(KeyType& aKey) { return &aKey; }
219 static PLDHashNumber HashKey(KeyTypePointer aKey)
220 {
221 return mozilla::HashGeneric(aKey->mCallback, aKey->mData);
222 }
223 enum { ALLOW_MEMMOVE = true };
225 ChangeCallback mKey;
226 };
228 static size_t SizeOfExcludingThis(nsIdentifierMapEntry* aEntry,
229 mozilla::MallocSizeOf aMallocSizeOf,
230 void* aArg);
232 private:
233 void FireChangeCallbacks(Element* aOldElement, Element* aNewElement,
234 bool aImageOnly = false);
236 // empty if there are no elements with this ID.
237 // The elements are stored as weak pointers.
238 nsSmallVoidArray mIdContentList;
239 nsRefPtr<nsBaseContentList> mNameContentList;
240 nsAutoPtr<nsTHashtable<ChangeCallbackEntry> > mChangeCallbacks;
241 nsRefPtr<Element> mImageElement;
242 };
244 namespace mozilla {
245 namespace dom {
247 class CustomElementHashKey : public PLDHashEntryHdr
248 {
249 public:
250 typedef CustomElementHashKey *KeyType;
251 typedef const CustomElementHashKey *KeyTypePointer;
253 CustomElementHashKey(int32_t aNamespaceID, nsIAtom *aAtom)
254 : mNamespaceID(aNamespaceID),
255 mAtom(aAtom)
256 {}
257 CustomElementHashKey(const CustomElementHashKey *aKey)
258 : mNamespaceID(aKey->mNamespaceID),
259 mAtom(aKey->mAtom)
260 {}
261 ~CustomElementHashKey()
262 {}
264 KeyType GetKey() const { return const_cast<KeyType>(this); }
265 bool KeyEquals(const KeyTypePointer aKey) const
266 {
267 MOZ_ASSERT(mNamespaceID != kNameSpaceID_Unknown,
268 "This equals method is not transitive, nor symmetric. "
269 "A key with a namespace of kNamespaceID_Unknown should "
270 "not be stored in a hashtable.");
271 return (kNameSpaceID_Unknown == aKey->mNamespaceID ||
272 mNamespaceID == aKey->mNamespaceID) &&
273 aKey->mAtom == mAtom;
274 }
276 static KeyTypePointer KeyToPointer(KeyType aKey) { return aKey; }
277 static PLDHashNumber HashKey(const KeyTypePointer aKey)
278 {
279 return aKey->mAtom->hash();
280 }
281 enum { ALLOW_MEMMOVE = true };
283 private:
284 int32_t mNamespaceID;
285 nsCOMPtr<nsIAtom> mAtom;
286 };
288 struct LifecycleCallbackArgs
289 {
290 nsString name;
291 nsString oldValue;
292 nsString newValue;
293 };
295 struct CustomElementData;
297 class CustomElementCallback
298 {
299 public:
300 CustomElementCallback(Element* aThisObject,
301 nsIDocument::ElementCallbackType aCallbackType,
302 mozilla::dom::CallbackFunction* aCallback,
303 CustomElementData* aOwnerData);
304 void Traverse(nsCycleCollectionTraversalCallback& aCb) const;
305 void Call();
306 void SetArgs(LifecycleCallbackArgs& aArgs)
307 {
308 MOZ_ASSERT(mType == nsIDocument::eAttributeChanged,
309 "Arguments are only used by attribute changed callback.");
310 mArgs = aArgs;
311 }
313 private:
314 // The this value to use for invocation of the callback.
315 nsRefPtr<mozilla::dom::Element> mThisObject;
316 nsRefPtr<mozilla::dom::CallbackFunction> mCallback;
317 // The type of callback (eCreated, eAttached, etc.)
318 nsIDocument::ElementCallbackType mType;
319 // Arguments to be passed to the callback,
320 // used by the attribute changed callback.
321 LifecycleCallbackArgs mArgs;
322 // CustomElementData that contains this callback in the
323 // callback queue.
324 CustomElementData* mOwnerData;
325 };
327 // Each custom element has an associated callback queue and an element is
328 // being created flag.
329 struct CustomElementData
330 {
331 CustomElementData(nsIAtom* aType);
332 // Objects in this array are transient and empty after each microtask
333 // checkpoint.
334 nsTArray<nsAutoPtr<CustomElementCallback>> mCallbackQueue;
335 // Custom element type, for <button is="x-button"> or <x-button>
336 // this would be x-button.
337 nsCOMPtr<nsIAtom> mType;
338 // The callback that is next to be processed upon calling RunCallbackQueue.
339 int32_t mCurrentCallback;
340 // Element is being created flag as described in the custom elements spec.
341 bool mElementIsBeingCreated;
342 // Flag to determine if the created callback has been invoked, thus it
343 // determines if other callbacks can be enqueued.
344 bool mCreatedCallbackInvoked;
345 // The microtask level associated with the callbacks in the callback queue,
346 // it is used to determine if a new queue needs to be pushed onto the
347 // processing stack.
348 int32_t mAssociatedMicroTask;
350 // Empties the callback queue.
351 void RunCallbackQueue();
352 };
354 // The required information for a custom element as defined in:
355 // https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html
356 struct CustomElementDefinition
357 {
358 CustomElementDefinition(JSObject* aPrototype,
359 nsIAtom* aType,
360 nsIAtom* aLocalName,
361 mozilla::dom::LifecycleCallbacks* aCallbacks,
362 uint32_t aNamespaceID,
363 uint32_t aDocOrder);
365 // The prototype to use for new custom elements of this type.
366 JS::Heap<JSObject *> mPrototype;
368 // The type (name) for this custom element.
369 nsCOMPtr<nsIAtom> mType;
371 // The localname to (e.g. <button is=type> -- this would be button).
372 nsCOMPtr<nsIAtom> mLocalName;
374 // The lifecycle callbacks to call for this custom element.
375 nsAutoPtr<mozilla::dom::LifecycleCallbacks> mCallbacks;
377 // Whether we're currently calling the created callback for a custom element
378 // of this type.
379 bool mElementIsBeingCreated;
381 // Element namespace.
382 int32_t mNamespaceID;
384 // The document custom element order.
385 uint32_t mDocOrder;
386 };
388 class Registry : public nsISupports
389 {
390 public:
391 friend class ::nsDocument;
393 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
394 NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Registry)
396 Registry();
397 virtual ~Registry();
399 protected:
400 typedef nsClassHashtable<mozilla::dom::CustomElementHashKey,
401 mozilla::dom::CustomElementDefinition>
402 DefinitionMap;
403 typedef nsClassHashtable<mozilla::dom::CustomElementHashKey,
404 nsTArray<nsRefPtr<mozilla::dom::Element>>>
405 CandidateMap;
407 // Hashtable for custom element definitions in web components.
408 // Custom prototypes are in the document's compartment.
409 DefinitionMap mCustomDefinitions;
411 // The "upgrade candidates map" from the web components spec. Maps from a
412 // namespace id and local name to a list of elements to upgrade if that
413 // element is registered as a custom element.
414 CandidateMap mCandidatesMap;
415 };
417 } // namespace dom
418 } // namespace mozilla
420 class nsDocHeaderData
421 {
422 public:
423 nsDocHeaderData(nsIAtom* aField, const nsAString& aData)
424 : mField(aField), mData(aData), mNext(nullptr)
425 {
426 }
428 ~nsDocHeaderData(void)
429 {
430 delete mNext;
431 }
433 nsCOMPtr<nsIAtom> mField;
434 nsString mData;
435 nsDocHeaderData* mNext;
436 };
438 class nsDOMStyleSheetList : public mozilla::dom::StyleSheetList,
439 public nsStubDocumentObserver
440 {
441 public:
442 nsDOMStyleSheetList(nsIDocument *aDocument);
443 virtual ~nsDOMStyleSheetList();
445 NS_DECL_ISUPPORTS_INHERITED
447 // nsIDocumentObserver
448 NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETADDED
449 NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETREMOVED
451 // nsIMutationObserver
452 NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED
454 virtual nsINode* GetParentObject() const MOZ_OVERRIDE
455 {
456 return mDocument;
457 }
459 virtual uint32_t Length() MOZ_OVERRIDE;
460 virtual nsCSSStyleSheet* IndexedGetter(uint32_t aIndex, bool& aFound) MOZ_OVERRIDE;
462 protected:
463 int32_t mLength;
464 nsIDocument* mDocument;
465 };
467 class nsOnloadBlocker MOZ_FINAL : public nsIRequest
468 {
469 public:
470 nsOnloadBlocker() {}
472 NS_DECL_ISUPPORTS
473 NS_DECL_NSIREQUEST
475 private:
476 ~nsOnloadBlocker() {}
477 };
479 class nsExternalResourceMap
480 {
481 public:
482 typedef nsIDocument::ExternalResourceLoad ExternalResourceLoad;
483 nsExternalResourceMap();
485 /**
486 * Request an external resource document. This does exactly what
487 * nsIDocument::RequestExternalResource is documented to do.
488 */
489 nsIDocument* RequestResource(nsIURI* aURI,
490 nsINode* aRequestingNode,
491 nsDocument* aDisplayDocument,
492 ExternalResourceLoad** aPendingLoad);
494 /**
495 * Enumerate the resource documents. See
496 * nsIDocument::EnumerateExternalResources.
497 */
498 void EnumerateResources(nsIDocument::nsSubDocEnumFunc aCallback, void* aData);
500 /**
501 * Traverse ourselves for cycle-collection
502 */
503 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
505 /**
506 * Shut ourselves down (used for cycle-collection unlink), as well
507 * as for document destruction.
508 */
509 void Shutdown()
510 {
511 mPendingLoads.Clear();
512 mMap.Clear();
513 mHaveShutDown = true;
514 }
516 bool HaveShutDown() const
517 {
518 return mHaveShutDown;
519 }
521 // Needs to be public so we can traverse them sanely
522 struct ExternalResource
523 {
524 ~ExternalResource();
525 nsCOMPtr<nsIDocument> mDocument;
526 nsCOMPtr<nsIContentViewer> mViewer;
527 nsCOMPtr<nsILoadGroup> mLoadGroup;
528 };
530 // Hide all our viewers
531 void HideViewers();
533 // Show all our viewers
534 void ShowViewers();
536 protected:
537 class PendingLoad : public ExternalResourceLoad,
538 public nsIStreamListener
539 {
540 public:
541 PendingLoad(nsDocument* aDisplayDocument) :
542 mDisplayDocument(aDisplayDocument)
543 {}
545 NS_DECL_ISUPPORTS
546 NS_DECL_NSISTREAMLISTENER
547 NS_DECL_NSIREQUESTOBSERVER
549 /**
550 * Start aURI loading. This will perform the necessary security checks and
551 * so forth.
552 */
553 nsresult StartLoad(nsIURI* aURI, nsINode* aRequestingNode);
555 /**
556 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
557 * put null in *aViewer and *aLoadGroup on all failures.
558 */
559 nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
560 nsILoadGroup** aLoadGroup);
562 private:
563 nsRefPtr<nsDocument> mDisplayDocument;
564 nsCOMPtr<nsIStreamListener> mTargetListener;
565 nsCOMPtr<nsIURI> mURI;
566 };
567 friend class PendingLoad;
569 class LoadgroupCallbacks MOZ_FINAL : public nsIInterfaceRequestor
570 {
571 public:
572 LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
573 : mCallbacks(aOtherCallbacks)
574 {}
575 NS_DECL_ISUPPORTS
576 NS_DECL_NSIINTERFACEREQUESTOR
577 private:
578 // The only reason it's safe to hold a strong ref here without leaking is
579 // that the notificationCallbacks on a loadgroup aren't the docshell itself
580 // but a shim that holds a weak reference to the docshell.
581 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
583 // Use shims for interfaces that docshell implements directly so that we
584 // don't hand out references to the docshell. The shims should all allow
585 // getInterface back on us, but other than that each one should only
586 // implement one interface.
588 // XXXbz I wish we could just derive the _allcaps thing from _i
589 #define DECL_SHIM(_i, _allcaps) \
590 class _i##Shim MOZ_FINAL : public nsIInterfaceRequestor, \
591 public _i \
592 { \
593 public: \
594 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
595 : mIfReq(aIfreq), mRealPtr(aRealPtr) \
596 { \
597 NS_ASSERTION(mIfReq, "Expected non-null here"); \
598 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
599 } \
600 NS_DECL_ISUPPORTS \
601 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
602 NS_FORWARD_##_allcaps(mRealPtr->) \
603 private: \
604 nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
605 nsCOMPtr<_i> mRealPtr; \
606 };
608 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
609 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
610 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
611 DECL_SHIM(nsISecurityEventSink, NSISECURITYEVENTSINK)
612 DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
613 #undef DECL_SHIM
614 };
616 /**
617 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
618 * when this is called if the URI didn't result in an XML document. This
619 * function makes sure to remove the pending load for aURI, if any, from our
620 * hashtable, and to notify its observers, if any.
621 */
622 nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
623 nsILoadGroup* aLoadGroup,
624 nsIDocument* aDisplayDocument);
626 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
627 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
628 bool mHaveShutDown;
629 };
631 class CSPErrorQueue
632 {
633 public:
634 /**
635 * Note this was designed to be passed string literals. If you give it
636 * a dynamically allocated string, it is your responsibility to make sure
637 * it never dies and is properly freed!
638 */
639 void Add(const char* aMessageName);
640 void Flush(nsIDocument* aDocument);
642 CSPErrorQueue()
643 {
644 }
646 ~CSPErrorQueue()
647 {
648 }
650 private:
651 nsAutoTArray<const char*,5> mErrors;
652 };
654 // Base class for our document implementations.
655 //
656 // Note that this class *implements* nsIDOMXMLDocument, but it's not
657 // really an nsIDOMXMLDocument. The reason for implementing
658 // nsIDOMXMLDocument on this class is to avoid having to duplicate all
659 // its inherited methods on document classes that *are*
660 // nsIDOMXMLDocument's. nsDocument's QI should *not* claim to support
661 // nsIDOMXMLDocument unless someone writes a real implementation of
662 // the interface.
663 class nsDocument : public nsIDocument,
664 public nsIDOMXMLDocument, // inherits nsIDOMDocument
665 public nsIDOMDocumentXBL,
666 public nsSupportsWeakReference,
667 public nsIScriptObjectPrincipal,
668 public nsIRadioGroupContainer,
669 public nsIApplicationCacheContainer,
670 public nsStubMutationObserver,
671 public nsIObserver,
672 public nsIDOMXPathEvaluator
673 {
674 public:
675 typedef mozilla::dom::Element Element;
676 using nsIDocument::GetElementsByTagName;
678 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
680 NS_DECL_SIZEOF_EXCLUDING_THIS
682 virtual void Reset(nsIChannel *aChannel, nsILoadGroup *aLoadGroup) MOZ_OVERRIDE;
683 virtual void ResetToURI(nsIURI *aURI, nsILoadGroup *aLoadGroup,
684 nsIPrincipal* aPrincipal) MOZ_OVERRIDE;
686 // StartDocumentLoad is pure virtual so that subclasses must override it.
687 // The nsDocument StartDocumentLoad does some setup, but does NOT set
688 // *aDocListener; this is the job of subclasses.
689 virtual nsresult StartDocumentLoad(const char* aCommand,
690 nsIChannel* aChannel,
691 nsILoadGroup* aLoadGroup,
692 nsISupports* aContainer,
693 nsIStreamListener **aDocListener,
694 bool aReset = true,
695 nsIContentSink* aContentSink = nullptr) MOZ_OVERRIDE = 0;
697 virtual void StopDocumentLoad() MOZ_OVERRIDE;
699 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement) MOZ_OVERRIDE;
701 virtual void SetDocumentURI(nsIURI* aURI) MOZ_OVERRIDE;
703 virtual void SetChromeXHRDocURI(nsIURI* aURI) MOZ_OVERRIDE;
705 virtual void SetChromeXHRDocBaseURI(nsIURI* aURI) MOZ_OVERRIDE;
707 /**
708 * Set the principal responsible for this document.
709 */
710 virtual void SetPrincipal(nsIPrincipal *aPrincipal) MOZ_OVERRIDE;
712 /**
713 * Get the Content-Type of this document.
714 */
715 // NS_IMETHOD GetContentType(nsAString& aContentType);
716 // Already declared in nsIDOMDocument
718 /**
719 * Set the Content-Type of this document.
720 */
721 virtual void SetContentType(const nsAString& aContentType) MOZ_OVERRIDE;
723 virtual nsresult SetBaseURI(nsIURI* aURI) MOZ_OVERRIDE;
725 /**
726 * Get/Set the base target of a link in a document.
727 */
728 virtual void GetBaseTarget(nsAString &aBaseTarget) MOZ_OVERRIDE;
730 /**
731 * Return a standard name for the document's character set. This will
732 * trigger a startDocumentLoad if necessary to answer the question.
733 */
734 virtual void SetDocumentCharacterSet(const nsACString& aCharSetID) MOZ_OVERRIDE;
736 /**
737 * Add an observer that gets notified whenever the charset changes.
738 */
739 virtual nsresult AddCharSetObserver(nsIObserver* aObserver) MOZ_OVERRIDE;
741 /**
742 * Remove a charset observer.
743 */
744 virtual void RemoveCharSetObserver(nsIObserver* aObserver) MOZ_OVERRIDE;
746 virtual Element* AddIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
747 void* aData, bool aForImage) MOZ_OVERRIDE;
748 virtual void RemoveIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
749 void* aData, bool aForImage) MOZ_OVERRIDE;
751 /**
752 * Access HTTP header data (this may also get set from other sources, like
753 * HTML META tags).
754 */
755 virtual void GetHeaderData(nsIAtom* aHeaderField, nsAString& aData) const MOZ_OVERRIDE;
756 virtual void SetHeaderData(nsIAtom* aheaderField,
757 const nsAString& aData) MOZ_OVERRIDE;
759 /**
760 * Create a new presentation shell that will use aContext for
761 * its presentation context (presentation contexts <b>must not</b> be
762 * shared among multiple presentation shells).
763 */
764 virtual already_AddRefed<nsIPresShell> CreateShell(nsPresContext* aContext,
765 nsViewManager* aViewManager,
766 nsStyleSet* aStyleSet) MOZ_OVERRIDE;
767 virtual void DeleteShell() MOZ_OVERRIDE;
769 virtual nsresult GetAllowPlugins(bool* aAllowPlugins) MOZ_OVERRIDE;
771 virtual already_AddRefed<mozilla::dom::UndoManager> GetUndoManager() MOZ_OVERRIDE;
773 virtual nsresult SetSubDocumentFor(Element* aContent,
774 nsIDocument* aSubDoc) MOZ_OVERRIDE;
775 virtual nsIDocument* GetSubDocumentFor(nsIContent* aContent) const MOZ_OVERRIDE;
776 virtual Element* FindContentForSubDocument(nsIDocument *aDocument) const MOZ_OVERRIDE;
777 virtual Element* GetRootElementInternal() const MOZ_OVERRIDE;
779 /**
780 * Get the style sheets owned by this document.
781 * These are ordered, highest priority last
782 */
783 virtual int32_t GetNumberOfStyleSheets() const MOZ_OVERRIDE;
784 virtual nsIStyleSheet* GetStyleSheetAt(int32_t aIndex) const MOZ_OVERRIDE;
785 virtual int32_t GetIndexOfStyleSheet(nsIStyleSheet* aSheet) const MOZ_OVERRIDE;
786 virtual void AddStyleSheet(nsIStyleSheet* aSheet) MOZ_OVERRIDE;
787 virtual void RemoveStyleSheet(nsIStyleSheet* aSheet) MOZ_OVERRIDE;
789 virtual void UpdateStyleSheets(nsCOMArray<nsIStyleSheet>& aOldSheets,
790 nsCOMArray<nsIStyleSheet>& aNewSheets) MOZ_OVERRIDE;
791 virtual void AddStyleSheetToStyleSets(nsIStyleSheet* aSheet);
792 virtual void RemoveStyleSheetFromStyleSets(nsIStyleSheet* aSheet);
794 virtual void InsertStyleSheetAt(nsIStyleSheet* aSheet, int32_t aIndex) MOZ_OVERRIDE;
795 virtual void SetStyleSheetApplicableState(nsIStyleSheet* aSheet,
796 bool aApplicable) MOZ_OVERRIDE;
798 virtual int32_t GetNumberOfCatalogStyleSheets() const MOZ_OVERRIDE;
799 virtual nsIStyleSheet* GetCatalogStyleSheetAt(int32_t aIndex) const MOZ_OVERRIDE;
800 virtual void AddCatalogStyleSheet(nsCSSStyleSheet* aSheet) MOZ_OVERRIDE;
801 virtual void EnsureCatalogStyleSheet(const char *aStyleSheetURI) MOZ_OVERRIDE;
803 virtual nsresult LoadAdditionalStyleSheet(additionalSheetType aType, nsIURI* aSheetURI) MOZ_OVERRIDE;
804 virtual void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI) MOZ_OVERRIDE;
805 virtual nsIStyleSheet* FirstAdditionalAuthorSheet() MOZ_OVERRIDE;
807 virtual nsIChannel* GetChannel() const MOZ_OVERRIDE {
808 return mChannel;
809 }
811 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject) MOZ_OVERRIDE;
813 virtual void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject) MOZ_OVERRIDE;
815 virtual nsIGlobalObject* GetScopeObject() const MOZ_OVERRIDE;
816 void SetScopeObject(nsIGlobalObject* aGlobal) MOZ_OVERRIDE;
817 /**
818 * Get the script loader for this document
819 */
820 virtual nsScriptLoader* ScriptLoader() MOZ_OVERRIDE;
822 /**
823 * Add/Remove an element to the document's id and name hashes
824 */
825 virtual void AddToIdTable(Element* aElement, nsIAtom* aId) MOZ_OVERRIDE;
826 virtual void RemoveFromIdTable(Element* aElement, nsIAtom* aId) MOZ_OVERRIDE;
827 virtual void AddToNameTable(Element* aElement, nsIAtom* aName) MOZ_OVERRIDE;
828 virtual void RemoveFromNameTable(Element* aElement, nsIAtom* aName) MOZ_OVERRIDE;
830 /**
831 * Add a new observer of document change notifications. Whenever
832 * content is changed, appended, inserted or removed the observers are
833 * informed.
834 */
835 virtual void AddObserver(nsIDocumentObserver* aObserver) MOZ_OVERRIDE;
837 /**
838 * Remove an observer of document change notifications. This will
839 * return false if the observer cannot be found.
840 */
841 virtual bool RemoveObserver(nsIDocumentObserver* aObserver) MOZ_OVERRIDE;
843 // Observation hooks used to propagate notifications to document
844 // observers.
845 virtual void BeginUpdate(nsUpdateType aUpdateType) MOZ_OVERRIDE;
846 virtual void EndUpdate(nsUpdateType aUpdateType) MOZ_OVERRIDE;
847 virtual void BeginLoad() MOZ_OVERRIDE;
848 virtual void EndLoad() MOZ_OVERRIDE;
850 virtual void SetReadyStateInternal(ReadyState rs) MOZ_OVERRIDE;
852 virtual void ContentStateChanged(nsIContent* aContent,
853 mozilla::EventStates aStateMask)
854 MOZ_OVERRIDE;
855 virtual void DocumentStatesChanged(
856 mozilla::EventStates aStateMask) MOZ_OVERRIDE;
858 virtual void StyleRuleChanged(nsIStyleSheet* aStyleSheet,
859 nsIStyleRule* aOldStyleRule,
860 nsIStyleRule* aNewStyleRule) MOZ_OVERRIDE;
861 virtual void StyleRuleAdded(nsIStyleSheet* aStyleSheet,
862 nsIStyleRule* aStyleRule) MOZ_OVERRIDE;
863 virtual void StyleRuleRemoved(nsIStyleSheet* aStyleSheet,
864 nsIStyleRule* aStyleRule) MOZ_OVERRIDE;
866 virtual void FlushPendingNotifications(mozFlushType aType) MOZ_OVERRIDE;
867 virtual void FlushExternalResources(mozFlushType aType) MOZ_OVERRIDE;
868 virtual void SetXMLDeclaration(const char16_t *aVersion,
869 const char16_t *aEncoding,
870 const int32_t aStandalone) MOZ_OVERRIDE;
871 virtual void GetXMLDeclaration(nsAString& aVersion,
872 nsAString& aEncoding,
873 nsAString& Standalone) MOZ_OVERRIDE;
874 virtual bool IsScriptEnabled() MOZ_OVERRIDE;
876 virtual void OnPageShow(bool aPersisted, mozilla::dom::EventTarget* aDispatchStartTarget) MOZ_OVERRIDE;
877 virtual void OnPageHide(bool aPersisted, mozilla::dom::EventTarget* aDispatchStartTarget) MOZ_OVERRIDE;
879 virtual void WillDispatchMutationEvent(nsINode* aTarget) MOZ_OVERRIDE;
880 virtual void MutationEventDispatched(nsINode* aTarget) MOZ_OVERRIDE;
882 // nsINode
883 virtual bool IsNodeOfType(uint32_t aFlags) const MOZ_OVERRIDE;
884 virtual nsIContent *GetChildAt(uint32_t aIndex) const MOZ_OVERRIDE;
885 virtual nsIContent * const * GetChildArray(uint32_t* aChildCount) const MOZ_OVERRIDE;
886 virtual int32_t IndexOf(const nsINode* aPossibleChild) const MOZ_OVERRIDE;
887 virtual uint32_t GetChildCount() const MOZ_OVERRIDE;
888 virtual nsresult InsertChildAt(nsIContent* aKid, uint32_t aIndex,
889 bool aNotify) MOZ_OVERRIDE;
890 virtual nsresult AppendChildTo(nsIContent* aKid, bool aNotify);
891 virtual void RemoveChildAt(uint32_t aIndex, bool aNotify) MOZ_OVERRIDE;
892 virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const MOZ_OVERRIDE
893 {
894 return NS_ERROR_NOT_IMPLEMENTED;
895 }
897 // nsIRadioGroupContainer
898 NS_IMETHOD WalkRadioGroup(const nsAString& aName,
899 nsIRadioVisitor* aVisitor,
900 bool aFlushContent) MOZ_OVERRIDE;
901 virtual void
902 SetCurrentRadioButton(const nsAString& aName,
903 mozilla::dom::HTMLInputElement* aRadio) MOZ_OVERRIDE;
904 virtual mozilla::dom::HTMLInputElement*
905 GetCurrentRadioButton(const nsAString& aName) MOZ_OVERRIDE;
906 NS_IMETHOD
907 GetNextRadioButton(const nsAString& aName,
908 const bool aPrevious,
909 mozilla::dom::HTMLInputElement* aFocusedRadio,
910 mozilla::dom::HTMLInputElement** aRadioOut) MOZ_OVERRIDE;
911 virtual void AddToRadioGroup(const nsAString& aName,
912 nsIFormControl* aRadio) MOZ_OVERRIDE;
913 virtual void RemoveFromRadioGroup(const nsAString& aName,
914 nsIFormControl* aRadio) MOZ_OVERRIDE;
915 virtual uint32_t GetRequiredRadioCount(const nsAString& aName) const MOZ_OVERRIDE;
916 virtual void RadioRequiredChanged(const nsAString& aName,
917 nsIFormControl* aRadio) MOZ_OVERRIDE;
918 virtual bool GetValueMissingState(const nsAString& aName) const MOZ_OVERRIDE;
919 virtual void SetValueMissingState(const nsAString& aName, bool aValue) MOZ_OVERRIDE;
921 // for radio group
922 nsRadioGroupStruct* GetRadioGroup(const nsAString& aName) const;
923 nsRadioGroupStruct* GetOrCreateRadioGroup(const nsAString& aName);
925 virtual nsViewportInfo GetViewportInfo(const mozilla::ScreenIntSize& aDisplaySize) MOZ_OVERRIDE;
927 private:
928 nsRadioGroupStruct* GetRadioGroupInternal(const nsAString& aName) const;
929 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
931 public:
932 // nsIDOMNode
933 NS_FORWARD_NSIDOMNODE_TO_NSINODE_OVERRIDABLE
935 // nsIDOMDocument
936 NS_DECL_NSIDOMDOCUMENT
938 // nsIDOMXMLDocument
939 NS_DECL_NSIDOMXMLDOCUMENT
941 // nsIDOMDocumentXBL
942 NS_DECL_NSIDOMDOCUMENTXBL
944 // nsIDOMEventTarget
945 virtual nsresult PreHandleEvent(
946 mozilla::EventChainPreVisitor& aVisitor) MOZ_OVERRIDE;
947 virtual mozilla::EventListenerManager*
948 GetOrCreateListenerManager() MOZ_OVERRIDE;
949 virtual mozilla::EventListenerManager*
950 GetExistingListenerManager() const MOZ_OVERRIDE;
952 // nsIScriptObjectPrincipal
953 virtual nsIPrincipal* GetPrincipal() MOZ_OVERRIDE;
955 // nsIApplicationCacheContainer
956 NS_DECL_NSIAPPLICATIONCACHECONTAINER
958 // nsIObserver
959 NS_DECL_NSIOBSERVER
961 NS_DECL_NSIDOMXPATHEVALUATOR
963 virtual nsresult Init();
965 virtual nsresult CreateElem(const nsAString& aName, nsIAtom *aPrefix,
966 int32_t aNamespaceID,
967 nsIContent **aResult) MOZ_OVERRIDE;
969 virtual NS_HIDDEN_(void) Sanitize();
971 virtual NS_HIDDEN_(void) EnumerateSubDocuments(nsSubDocEnumFunc aCallback,
972 void *aData);
974 virtual NS_HIDDEN_(bool) CanSavePresentation(nsIRequest *aNewRequest);
975 virtual NS_HIDDEN_(void) Destroy();
976 virtual NS_HIDDEN_(void) RemovedFromDocShell();
977 virtual NS_HIDDEN_(already_AddRefed<nsILayoutHistoryState>) GetLayoutHistoryState() const;
979 virtual NS_HIDDEN_(void) BlockOnload();
980 virtual NS_HIDDEN_(void) UnblockOnload(bool aFireSync);
982 virtual NS_HIDDEN_(void) AddStyleRelevantLink(mozilla::dom::Link* aLink);
983 virtual NS_HIDDEN_(void) ForgetLink(mozilla::dom::Link* aLink);
985 NS_HIDDEN_(void) ClearBoxObjectFor(nsIContent* aContent);
986 already_AddRefed<nsIBoxObject> GetBoxObjectFor(mozilla::dom::Element* aElement,
987 mozilla::ErrorResult& aRv) MOZ_OVERRIDE;
989 virtual NS_HIDDEN_(Element*)
990 GetAnonymousElementByAttribute(nsIContent* aElement,
991 nsIAtom* aAttrName,
992 const nsAString& aAttrValue) const;
994 virtual NS_HIDDEN_(Element*) ElementFromPointHelper(float aX, float aY,
995 bool aIgnoreRootScrollFrame,
996 bool aFlushLayout);
998 virtual NS_HIDDEN_(nsresult) NodesFromRectHelper(float aX, float aY,
999 float aTopSize, float aRightSize,
1000 float aBottomSize, float aLeftSize,
1001 bool aIgnoreRootScrollFrame,
1002 bool aFlushLayout,
1003 nsIDOMNodeList** aReturn);
1005 virtual NS_HIDDEN_(void) FlushSkinBindings();
1007 virtual NS_HIDDEN_(nsresult) InitializeFrameLoader(nsFrameLoader* aLoader);
1008 virtual NS_HIDDEN_(nsresult) FinalizeFrameLoader(nsFrameLoader* aLoader);
1009 virtual NS_HIDDEN_(void) TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
1010 virtual NS_HIDDEN_(bool) FrameLoaderScheduledToBeFinalized(nsIDocShell* aShell);
1011 virtual NS_HIDDEN_(nsIDocument*)
1012 RequestExternalResource(nsIURI* aURI,
1013 nsINode* aRequestingNode,
1014 ExternalResourceLoad** aPendingLoad);
1015 virtual NS_HIDDEN_(void)
1016 EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData);
1018 nsTArray<nsCString> mHostObjectURIs;
1020 // Returns our (lazily-initialized) animation controller.
1021 // If HasAnimationController is true, this is guaranteed to return non-null.
1022 nsSMILAnimationController* GetAnimationController() MOZ_OVERRIDE;
1024 void SetImagesNeedAnimating(bool aAnimating) MOZ_OVERRIDE;
1026 virtual void SuppressEventHandling(SuppressionType aWhat,
1027 uint32_t aIncrease) MOZ_OVERRIDE;
1029 virtual void UnsuppressEventHandlingAndFireEvents(SuppressionType aWhat,
1030 bool aFireEvents) MOZ_OVERRIDE;
1032 void DecreaseEventSuppression() {
1033 MOZ_ASSERT(mEventsSuppressed);
1034 --mEventsSuppressed;
1035 MaybeRescheduleAnimationFrameNotifications();
1036 }
1038 void ResumeAnimations() {
1039 MOZ_ASSERT(mAnimationsPaused);
1040 --mAnimationsPaused;
1041 MaybeRescheduleAnimationFrameNotifications();
1042 }
1044 virtual nsIDocument* GetTemplateContentsOwner() MOZ_OVERRIDE;
1046 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsDocument,
1047 nsIDocument)
1049 void DoNotifyPossibleTitleChange();
1051 nsExternalResourceMap& ExternalResourceMap()
1052 {
1053 return mExternalResourceMap;
1054 }
1056 void SetLoadedAsData(bool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
1057 void SetLoadedAsInteractiveData(bool aLoadedAsInteractiveData)
1058 {
1059 mLoadedAsInteractiveData = aLoadedAsInteractiveData;
1060 }
1062 nsresult CloneDocHelper(nsDocument* clone) const;
1064 void MaybeInitializeFinalizeFrameLoaders();
1066 void MaybeEndOutermostXBLUpdate();
1068 virtual void MaybePreLoadImage(nsIURI* uri,
1069 const nsAString &aCrossOriginAttr) MOZ_OVERRIDE;
1071 virtual void PreloadStyle(nsIURI* uri, const nsAString& charset,
1072 const nsAString& aCrossOriginAttr) MOZ_OVERRIDE;
1074 virtual nsresult LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
1075 nsCSSStyleSheet** sheet) MOZ_OVERRIDE;
1077 virtual nsISupports* GetCurrentContentSink() MOZ_OVERRIDE;
1079 virtual mozilla::EventStates GetDocumentState() MOZ_OVERRIDE;
1081 virtual void RegisterHostObjectUri(const nsACString& aUri) MOZ_OVERRIDE;
1082 virtual void UnregisterHostObjectUri(const nsACString& aUri) MOZ_OVERRIDE;
1084 // Only BlockOnload should call this!
1085 void AsyncBlockOnload();
1087 virtual void SetScrollToRef(nsIURI *aDocumentURI) MOZ_OVERRIDE;
1088 virtual void ScrollToRef() MOZ_OVERRIDE;
1089 virtual void ResetScrolledToRefAlready() MOZ_OVERRIDE;
1090 virtual void SetChangeScrollPosWhenScrollingToRef(bool aValue) MOZ_OVERRIDE;
1092 virtual Element *GetElementById(const nsAString& aElementId) MOZ_OVERRIDE;
1093 virtual const nsSmallVoidArray* GetAllElementsForId(const nsAString& aElementId) const MOZ_OVERRIDE;
1095 virtual Element *LookupImageElement(const nsAString& aElementId) MOZ_OVERRIDE;
1096 virtual void MozSetImageElement(const nsAString& aImageElementId,
1097 Element* aElement) MOZ_OVERRIDE;
1099 virtual NS_HIDDEN_(nsresult) AddImage(imgIRequest* aImage);
1100 virtual NS_HIDDEN_(nsresult) RemoveImage(imgIRequest* aImage, uint32_t aFlags);
1101 virtual NS_HIDDEN_(nsresult) SetImageLockingState(bool aLocked);
1103 // AddPlugin adds a plugin-related element to mPlugins when the element is
1104 // added to the tree.
1105 virtual nsresult AddPlugin(nsIObjectLoadingContent* aPlugin) MOZ_OVERRIDE;
1106 // RemovePlugin removes a plugin-related element to mPlugins when the
1107 // element is removed from the tree.
1108 virtual void RemovePlugin(nsIObjectLoadingContent* aPlugin) MOZ_OVERRIDE;
1109 // GetPlugins returns the plugin-related elements from
1110 // the frame and any subframes.
1111 virtual void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins) MOZ_OVERRIDE;
1113 virtual nsresult GetStateObject(nsIVariant** aResult) MOZ_OVERRIDE;
1115 virtual nsDOMNavigationTiming* GetNavigationTiming() const MOZ_OVERRIDE;
1116 virtual nsresult SetNavigationTiming(nsDOMNavigationTiming* aTiming) MOZ_OVERRIDE;
1118 virtual Element* FindImageMap(const nsAString& aNormalizedMapName) MOZ_OVERRIDE;
1120 virtual Element* GetFullScreenElement() MOZ_OVERRIDE;
1121 virtual void AsyncRequestFullScreen(Element* aElement) MOZ_OVERRIDE;
1122 virtual void RestorePreviousFullScreenState() MOZ_OVERRIDE;
1123 virtual bool IsFullscreenLeaf() MOZ_OVERRIDE;
1124 virtual bool IsFullScreenDoc() MOZ_OVERRIDE;
1125 virtual void SetApprovedForFullscreen(bool aIsApproved) MOZ_OVERRIDE;
1126 virtual nsresult RemoteFrameFullscreenChanged(nsIDOMElement* aFrameElement,
1127 const nsAString& aNewOrigin) MOZ_OVERRIDE;
1129 virtual nsresult RemoteFrameFullscreenReverted() MOZ_OVERRIDE;
1130 virtual nsIDocument* GetFullscreenRoot() MOZ_OVERRIDE;
1131 virtual void SetFullscreenRoot(nsIDocument* aRoot) MOZ_OVERRIDE;
1133 static void ExitFullscreen(nsIDocument* aDoc);
1135 // This is called asynchronously by nsIDocument::AsyncRequestFullScreen()
1136 // to move this document into full-screen mode if allowed. aWasCallerChrome
1137 // should be true when nsIDocument::AsyncRequestFullScreen() was called
1138 // by chrome code. aNotifyOnOriginChange denotes whether we should send a
1139 // fullscreen-origin-change notification if requesting fullscreen in this
1140 // document causes the origin which is fullscreen to change. We may want to
1141 // *not* send this notification if we're calling RequestFullscreen() as part
1142 // of a continuation of a request in a subdocument, whereupon the caller will
1143 // need to send the notification with the origin of the document which
1144 // originally requested fullscreen, not *this* document's origin.
1145 void RequestFullScreen(Element* aElement,
1146 bool aWasCallerChrome,
1147 bool aNotifyOnOriginChange);
1149 // Removes all elements from the full-screen stack, removing full-scren
1150 // styles from the top element in the stack.
1151 void CleanupFullscreenState();
1153 // Add/remove "fullscreen-approved" observer service notification listener.
1154 // Chrome sends us a notification when fullscreen is approved for a
1155 // document, with the notification subject as the document that was approved.
1156 // We maintain this listener while in fullscreen mode.
1157 nsresult AddFullscreenApprovedObserver();
1158 nsresult RemoveFullscreenApprovedObserver();
1160 // Pushes aElement onto the full-screen stack, and removes full-screen styles
1161 // from the former full-screen stack top, and its ancestors, and applies the
1162 // styles to aElement. aElement becomes the new "full-screen element".
1163 bool FullScreenStackPush(Element* aElement);
1165 // Remove the top element from the full-screen stack. Removes the full-screen
1166 // styles from the former top element, and applies them to the new top
1167 // element, if there is one.
1168 void FullScreenStackPop();
1170 // Returns the top element from the full-screen stack.
1171 Element* FullScreenStackTop();
1173 // DOM-exposed fullscreen API
1174 virtual bool MozFullScreenEnabled() MOZ_OVERRIDE;
1175 virtual Element* GetMozFullScreenElement(mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1177 void RequestPointerLock(Element* aElement) MOZ_OVERRIDE;
1178 bool ShouldLockPointer(Element* aElement, Element* aCurrentLock,
1179 bool aNoFocusCheck = false);
1180 bool SetPointerLock(Element* aElement, int aCursorStyle);
1181 static void UnlockPointer(nsIDocument* aDoc = nullptr);
1183 // This method may fire a DOM event; if it does so it will happen
1184 // synchronously.
1185 void UpdateVisibilityState();
1186 // Posts an event to call UpdateVisibilityState
1187 virtual void PostVisibilityUpdateEvent() MOZ_OVERRIDE;
1189 virtual void DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const MOZ_OVERRIDE;
1190 // DocAddSizeOfIncludingThis is inherited from nsIDocument.
1192 virtual nsIDOMNode* AsDOMNode() MOZ_OVERRIDE { return this; }
1194 virtual void EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
1195 Element* aCustomElement,
1196 mozilla::dom::LifecycleCallbackArgs* aArgs = nullptr,
1197 mozilla::dom::CustomElementDefinition* aDefinition = nullptr) MOZ_OVERRIDE;
1199 static void ProcessTopElementQueue(bool aIsBaseQueue = false);
1201 void GetCustomPrototype(int32_t aNamespaceID,
1202 nsIAtom* aAtom,
1203 JS::MutableHandle<JSObject*> prototype)
1204 {
1205 if (!mRegistry) {
1206 prototype.set(nullptr);
1207 return;
1208 }
1210 mozilla::dom::CustomElementHashKey key(aNamespaceID, aAtom);
1211 mozilla::dom::CustomElementDefinition* definition;
1212 if (mRegistry->mCustomDefinitions.Get(&key, &definition)) {
1213 prototype.set(definition->mPrototype);
1214 } else {
1215 prototype.set(nullptr);
1216 }
1217 }
1219 static bool RegisterEnabled();
1221 virtual nsresult RegisterUnresolvedElement(mozilla::dom::Element* aElement,
1222 nsIAtom* aTypeName = nullptr) MOZ_OVERRIDE;
1224 // WebIDL bits
1225 virtual mozilla::dom::DOMImplementation*
1226 GetImplementation(mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1227 virtual void
1228 RegisterElement(JSContext* aCx, const nsAString& aName,
1229 const mozilla::dom::ElementRegistrationOptions& aOptions,
1230 JS::MutableHandle<JSObject*> aRetval,
1231 mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1232 virtual mozilla::dom::StyleSheetList* StyleSheets() MOZ_OVERRIDE;
1233 virtual void SetSelectedStyleSheetSet(const nsAString& aSheetSet) MOZ_OVERRIDE;
1234 virtual void GetLastStyleSheetSet(nsString& aSheetSet) MOZ_OVERRIDE;
1235 virtual mozilla::dom::DOMStringList* StyleSheetSets() MOZ_OVERRIDE;
1236 virtual void EnableStyleSheetsForSet(const nsAString& aSheetSet) MOZ_OVERRIDE;
1237 using nsIDocument::CreateElement;
1238 using nsIDocument::CreateElementNS;
1239 virtual already_AddRefed<Element> CreateElement(const nsAString& aTagName,
1240 const nsAString& aTypeExtension,
1241 mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1242 virtual already_AddRefed<Element> CreateElementNS(const nsAString& aNamespaceURI,
1243 const nsAString& aQualifiedName,
1244 const nsAString& aTypeExtension,
1245 mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1246 virtual void UseRegistryFromDocument(nsIDocument* aDocument) MOZ_OVERRIDE;
1248 virtual void UnblockDOMContentLoaded() MOZ_OVERRIDE;
1250 protected:
1251 friend class nsNodeUtils;
1252 friend class nsDocumentOnStack;
1254 void IncreaseStackRefCnt()
1255 {
1256 ++mStackRefCnt;
1257 }
1259 void DecreaseStackRefCnt()
1260 {
1261 if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
1262 mNeedsReleaseAfterStackRefCntRelease = false;
1263 NS_RELEASE_THIS();
1264 }
1265 }
1267 // Returns true if a request for DOM full-screen is currently enabled in
1268 // this document. This returns true if there are no windowed plugins in this
1269 // doc tree, and if the document is visible, and if the api is not
1270 // disabled by pref. aIsCallerChrome must contain the return value of
1271 // nsContentUtils::IsCallerChrome() from the context we're checking.
1272 // If aLogFailure is true, an appropriate warning message is logged to the
1273 // console, and a "mozfullscreenerror" event is dispatched to this document.
1274 bool IsFullScreenEnabled(bool aIsCallerChrome, bool aLogFailure);
1276 /**
1277 * Check that aId is not empty and log a message to the console
1278 * service if it is.
1279 * @returns true if aId looks correct, false otherwise.
1280 */
1281 inline bool CheckGetElementByIdArg(const nsAString& aId)
1282 {
1283 if (aId.IsEmpty()) {
1284 ReportEmptyGetElementByIdArg();
1285 return false;
1286 }
1287 return true;
1288 }
1290 void ReportEmptyGetElementByIdArg();
1292 void DispatchContentLoadedEvents();
1294 void RetrieveRelevantHeaders(nsIChannel *aChannel);
1296 void TryChannelCharset(nsIChannel *aChannel,
1297 int32_t& aCharsetSource,
1298 nsACString& aCharset,
1299 nsHtml5TreeOpExecutor* aExecutor);
1301 // Call this before the document does something that will unbind all content.
1302 // That will stop us from doing a lot of work as each element is removed.
1303 void DestroyElementMaps();
1305 // Refreshes the hrefs of all the links in the document.
1306 void RefreshLinkHrefs();
1308 nsIContent* GetFirstBaseNodeWithHref();
1309 nsresult SetFirstBaseNodeWithHref(nsIContent *node);
1311 // Get the first <title> element with the given IsNodeOfType type, or
1312 // return null if there isn't one
1313 nsIContent* GetTitleContent(uint32_t aNodeType);
1314 // Find the first "title" element in the given IsNodeOfType type and
1315 // append the concatenation of its text node children to aTitle. Do
1316 // nothing if there is no such element.
1317 void GetTitleFromElement(uint32_t aNodeType, nsAString& aTitle);
1318 public:
1319 // Get our title
1320 virtual void GetTitle(nsString& aTitle) MOZ_OVERRIDE;
1321 // Set our title
1322 virtual void SetTitle(const nsAString& aTitle, mozilla::ErrorResult& rv) MOZ_OVERRIDE;
1324 static void XPCOMShutdown();
1326 bool mIsTopLevelContentDocument:1;
1328 bool IsTopLevelContentDocument();
1330 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument);
1332 js::ExpandoAndGeneration mExpandoAndGeneration;
1334 protected:
1335 already_AddRefed<nsIPresShell> doCreateShell(nsPresContext* aContext,
1336 nsViewManager* aViewManager,
1337 nsStyleSet* aStyleSet,
1338 nsCompatibility aCompatMode);
1340 void RemoveDocStyleSheetsFromStyleSets();
1341 void RemoveStyleSheetsFromStyleSets(nsCOMArray<nsIStyleSheet>& aSheets,
1342 nsStyleSet::sheetType aType);
1343 void ResetStylesheetsToURI(nsIURI* aURI);
1344 void FillStyleSet(nsStyleSet* aStyleSet);
1346 // Return whether all the presshells for this document are safe to flush
1347 bool IsSafeToFlush() const;
1349 void DispatchPageTransition(mozilla::dom::EventTarget* aDispatchTarget,
1350 const nsAString& aType,
1351 bool aPersisted);
1353 virtual nsPIDOMWindow *GetWindowInternal() const MOZ_OVERRIDE;
1354 virtual nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const MOZ_OVERRIDE;
1355 virtual bool InternalAllowXULXBL() MOZ_OVERRIDE;
1357 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
1358 NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, nsIDocumentObserver, \
1359 func_, params_);
1361 #ifdef DEBUG
1362 void VerifyRootContentState();
1363 #endif
1365 nsDocument(const char* aContentType);
1366 virtual ~nsDocument();
1368 void EnsureOnloadBlocker();
1370 void NotifyStyleSheetApplicableStateChanged();
1372 nsTArray<nsIObserver*> mCharSetObservers;
1374 PLDHashTable *mSubDocuments;
1376 // Array of owning references to all children
1377 nsAttrAndChildArray mChildren;
1379 // Pointer to our parser if we're currently in the process of being
1380 // parsed into.
1381 nsCOMPtr<nsIParser> mParser;
1383 // Weak reference to our sink for in case we no longer have a parser. This
1384 // will allow us to flush out any pending stuff from the sink even if
1385 // EndLoad() has already happened.
1386 nsWeakPtr mWeakSink;
1388 nsCOMArray<nsIStyleSheet> mStyleSheets;
1389 nsCOMArray<nsIStyleSheet> mCatalogSheets;
1390 nsCOMArray<nsIStyleSheet> mAdditionalSheets[SheetTypeCount];
1392 // Array of observers
1393 nsTObserverArray<nsIDocumentObserver*> mObservers;
1395 // Weak reference to the scope object (aka the script global object)
1396 // that, unlike mScriptGlobalObject, is never unset once set. This
1397 // is a weak reference to avoid leaks due to circular references.
1398 nsWeakPtr mScopeObject;
1400 // Stack of full-screen elements. When we request full-screen we push the
1401 // full-screen element onto this stack, and when we cancel full-screen we
1402 // pop one off this stack, restoring the previous full-screen state
1403 nsTArray<nsWeakPtr> mFullScreenStack;
1405 // The root of the doc tree in which this document is in. This is only
1406 // non-null when this document is in fullscreen mode.
1407 nsWeakPtr mFullscreenRoot;
1409 private:
1410 // Array representing the processing stack in the custom elements
1411 // specification. The processing stack is conceptually a stack of
1412 // element queues. Each queue is represented by a sequence of
1413 // CustomElementData in this array, separated by nullptr that
1414 // represent the boundaries of the items in the stack. The first
1415 // queue in the stack is the base element queue.
1416 static mozilla::Maybe<nsTArray<mozilla::dom::CustomElementData*>> sProcessingStack;
1418 // Flag to prevent re-entrance into base element queue as described in the
1419 // custom elements speicification.
1420 static bool sProcessingBaseElementQueue;
1422 static bool CustomElementConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp);
1424 public:
1425 static void ProcessBaseElementQueue();
1427 // Modify the prototype and "is" attribute of newly created custom elements.
1428 virtual void SwizzleCustomElement(Element* aElement,
1429 const nsAString& aTypeExtension,
1430 uint32_t aNamespaceID,
1431 mozilla::ErrorResult& rv);
1433 static bool IsRegisterElementEnabled(JSContext* aCx, JSObject* aObject);
1435 // The "registry" from the web components spec.
1436 nsRefPtr<mozilla::dom::Registry> mRegistry;
1438 nsRefPtr<mozilla::EventListenerManager> mListenerManager;
1439 nsRefPtr<mozilla::dom::StyleSheetList> mDOMStyleSheets;
1440 nsRefPtr<nsDOMStyleSheetSetList> mStyleSheetSetList;
1441 nsRefPtr<nsScriptLoader> mScriptLoader;
1442 nsDocHeaderData* mHeaderData;
1443 /* mIdentifierMap works as follows for IDs:
1444 * 1) Attribute changes affect the table immediately (removing and adding
1445 * entries as needed).
1446 * 2) Removals from the DOM affect the table immediately
1447 * 3) Additions to the DOM always update existing entries for names, and add
1448 * new ones for IDs.
1449 */
1450 nsTHashtable<nsIdentifierMapEntry> mIdentifierMap;
1452 nsClassHashtable<nsStringHashKey, nsRadioGroupStruct> mRadioGroups;
1454 // Recorded time of change to 'loading' state.
1455 mozilla::TimeStamp mLoadingTimeStamp;
1457 // True if the document has been detached from its content viewer.
1458 bool mIsGoingAway:1;
1459 // True if the document is being destroyed.
1460 bool mInDestructor:1;
1462 // True if this document has ever had an HTML or SVG <title> element
1463 // bound to it
1464 bool mMayHaveTitleElement:1;
1466 bool mHasWarnedAboutBoxObjects:1;
1468 bool mDelayFrameLoaderInitialization:1;
1470 bool mSynchronousDOMContentLoaded:1;
1472 bool mInXBLUpdate:1;
1474 // Whether we're currently holding a lock on all of our images.
1475 bool mLockingImages:1;
1477 // Whether we currently require our images to animate
1478 bool mAnimatingImages:1;
1480 // Whether we're currently under a FlushPendingNotifications call to
1481 // our presshell. This is used to handle flush reentry correctly.
1482 bool mInFlush:1;
1484 // Parser aborted. True if the parser of this document was forcibly
1485 // terminated instead of letting it finish at its own pace.
1486 bool mParserAborted:1;
1488 // Whether this document has been approved for fullscreen, either by explicit
1489 // approval via the fullscreen-approval UI, or because it received
1490 // approval because its document's host already had the "fullscreen"
1491 // permission granted when the document requested fullscreen.
1492 //
1493 // Note if a document's principal doesn't have a host, the permission manager
1494 // can't store permissions for it, so we can only manage approval using this
1495 // flag.
1496 //
1497 // Note we must track this separately from the "fullscreen" permission,
1498 // so that pending pointer lock requests can determine whether documents
1499 // whose principal doesn't have a host (i.e. those which can't store
1500 // permissions in the permission manager) have been approved for fullscreen.
1501 bool mIsApprovedForFullscreen:1;
1503 // Whether this document has a fullscreen approved observer. Only documents
1504 // which request fullscreen and which don't have a pre-existing approval for
1505 // fullscreen will have an observer.
1506 bool mHasFullscreenApprovedObserver:1;
1508 friend class nsPointerLockPermissionRequest;
1509 friend class nsCallRequestFullScreen;
1510 // When set, trying to lock the pointer doesn't require permission from the
1511 // user.
1512 bool mAllowRelocking:1;
1514 bool mAsyncFullscreenPending:1;
1516 // Keeps track of whether we have a pending
1517 // 'style-sheet-applicable-state-changed' notification.
1518 bool mSSApplicableStateNotificationPending:1;
1520 uint32_t mCancelledPointerLockRequests;
1522 uint8_t mXMLDeclarationBits;
1524 nsInterfaceHashtable<nsPtrHashKey<nsIContent>, nsPIBoxObject> *mBoxObjectTable;
1526 // A document "without a browsing context" that owns the content of
1527 // HTMLTemplateElement.
1528 nsCOMPtr<nsIDocument> mTemplateContentsOwner;
1530 // Our update nesting level
1531 uint32_t mUpdateNestLevel;
1533 // The application cache that this document is associated with, if
1534 // any. This can change during the lifetime of the document.
1535 nsCOMPtr<nsIApplicationCache> mApplicationCache;
1537 nsCOMPtr<nsIContent> mFirstBaseNodeWithHref;
1539 mozilla::EventStates mDocumentState;
1540 mozilla::EventStates mGotDocumentState;
1542 nsRefPtr<nsDOMNavigationTiming> mTiming;
1543 private:
1544 friend class nsUnblockOnloadEvent;
1545 // Recomputes the visibility state but doesn't set the new value.
1546 mozilla::dom::VisibilityState GetVisibilityState() const;
1547 void NotifyStyleSheetAdded(nsIStyleSheet* aSheet, bool aDocumentSheet);
1548 void NotifyStyleSheetRemoved(nsIStyleSheet* aSheet, bool aDocumentSheet);
1550 void PostUnblockOnloadEvent();
1551 void DoUnblockOnload();
1553 nsresult CheckFrameOptions();
1554 nsresult InitCSP(nsIChannel* aChannel);
1556 void FlushCSPWebConsoleErrorQueue()
1557 {
1558 mCSPWebConsoleErrorQueue.Flush(this);
1559 }
1561 /**
1562 * Find the (non-anonymous) content in this document for aFrame. It will
1563 * be aFrame's content node if that content is in this document and not
1564 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
1565 * element containing the subdocument containing aFrame, and/or find the
1566 * nearest non-anonymous ancestor in this document.
1567 * Returns null if there is no such element.
1568 */
1569 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
1571 // Just like EnableStyleSheetsForSet, but doesn't check whether
1572 // aSheetSet is null and allows the caller to control whether to set
1573 // aSheetSet as the preferred set in the CSSLoader.
1574 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
1575 bool aUpdateCSSLoader);
1577 // Revoke any pending notifications due to mozRequestAnimationFrame calls
1578 void RevokeAnimationFrameNotifications();
1579 // Reschedule any notifications we need to handle
1580 // mozRequestAnimationFrame, if it's OK to do so.
1581 void MaybeRescheduleAnimationFrameNotifications();
1583 // These are not implemented and not supported.
1584 nsDocument(const nsDocument& aOther);
1585 nsDocument& operator=(const nsDocument& aOther);
1587 // The layout history state that should be used by nodes in this
1588 // document. We only actually store a pointer to it when:
1589 // 1) We have no script global object.
1590 // 2) We haven't had Destroy() called on us yet.
1591 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
1593 // Currently active onload blockers
1594 uint32_t mOnloadBlockCount;
1595 // Onload blockers which haven't been activated yet
1596 uint32_t mAsyncOnloadBlockCount;
1597 nsCOMPtr<nsIRequest> mOnloadBlocker;
1599 // A hashtable of styled links keyed by address pointer.
1600 nsTHashtable<nsPtrHashKey<mozilla::dom::Link> > mStyledLinks;
1601 #ifdef DEBUG
1602 // Indicates whether mStyledLinks was cleared or not. This is used to track
1603 // state so we can provide useful assertions to consumers of ForgetLink and
1604 // AddStyleRelevantLink.
1605 bool mStyledLinksCleared;
1606 #endif
1608 // Member to store out last-selected stylesheet set.
1609 nsString mLastStyleSheetSet;
1611 nsTArray<nsRefPtr<nsFrameLoader> > mInitializableFrameLoaders;
1612 nsTArray<nsRefPtr<nsFrameLoader> > mFinalizableFrameLoaders;
1613 nsRefPtr<nsRunnableMethod<nsDocument> > mFrameLoaderRunner;
1615 nsRevocableEventPtr<nsRunnableMethod<nsDocument, void, false> >
1616 mPendingTitleChangeEvent;
1618 nsExternalResourceMap mExternalResourceMap;
1620 // All images in process of being preloaded
1621 nsCOMArray<imgIRequest> mPreloadingImages;
1623 nsRefPtr<mozilla::dom::DOMImplementation> mDOMImplementation;
1625 nsRefPtr<nsContentList> mImageMaps;
1627 nsCString mScrollToRef;
1628 uint8_t mScrolledToRefAlready : 1;
1629 uint8_t mChangeScrollPosWhenScrollingToRef : 1;
1631 // Tracking for images in the document.
1632 nsDataHashtable< nsPtrHashKey<imgIRequest>, uint32_t> mImageTracker;
1634 // Tracking for plugins in the document.
1635 nsTHashtable< nsPtrHashKey<nsIObjectLoadingContent> > mPlugins;
1637 nsRefPtr<mozilla::dom::UndoManager> mUndoManager;
1639 enum ViewportType {
1640 DisplayWidthHeight,
1641 DisplayWidthHeightNoZoom,
1642 Specified,
1643 Unknown
1644 };
1646 ViewportType mViewportType;
1648 // These member variables cache information about the viewport so we don't have to
1649 // recalculate it each time.
1650 bool mValidWidth, mValidHeight;
1651 mozilla::LayoutDeviceToScreenScale mScaleMinFloat;
1652 mozilla::LayoutDeviceToScreenScale mScaleMaxFloat;
1653 mozilla::LayoutDeviceToScreenScale mScaleFloat;
1654 mozilla::CSSToLayoutDeviceScale mPixelRatio;
1655 bool mAutoSize, mAllowZoom, mAllowDoubleTapZoom, mValidScaleFloat, mValidMaxScale, mScaleStrEmpty, mWidthStrEmpty;
1656 mozilla::CSSIntSize mViewportSize;
1658 nsrefcnt mStackRefCnt;
1659 bool mNeedsReleaseAfterStackRefCntRelease;
1661 CSPErrorQueue mCSPWebConsoleErrorQueue;
1663 #ifdef DEBUG
1664 protected:
1665 bool mWillReparent;
1666 #endif
1667 };
1669 class nsDocumentOnStack
1670 {
1671 public:
1672 nsDocumentOnStack(nsDocument* aDoc) : mDoc(aDoc)
1673 {
1674 mDoc->IncreaseStackRefCnt();
1675 }
1676 ~nsDocumentOnStack()
1677 {
1678 mDoc->DecreaseStackRefCnt();
1679 }
1680 private:
1681 nsDocument* mDoc;
1682 };
1684 #endif /* nsDocument_h___ */