Bug 1374207 - part1: nsTextEditorState should use mozilla::TextEditor instead of editor interfaces r=smaug
authorMasayuki Nakano <masayuki@d-toybox.com>
Tue, 20 Jun 2017 22:57:08 +0900
changeset 416646 621ec6b67f20406ab14fad047386ada44a44b39a
parent 416645 d250b1796b875571019aa99f635fc7b7653b2c0a
child 416647 8230a1deb27fbeed8e96c93e7d57d29342aae71e
push id1517
push userjlorenzo@mozilla.com
push dateThu, 14 Sep 2017 16:50:54 +0000
treeherdermozilla-release@3b41fd564418 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerssmaug
bugs1374207
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1374207 - part1: nsTextEditorState should use mozilla::TextEditor instead of editor interfaces r=smaug Using concrete class rather than interface classes (nsI*Editor) will allow to reduce QI and some virtual calls. Therefore, Editor classes should be used as concrete class as far as possible. Unfortunately, if classes referring editor are initialized via scriptable interface, we cannot do this because nsI*Editor is still not marked as builtinclass. Therefore, their editor may be implemented by JS. E.g., inline nsIInlineSpellChecker.init() and nsIDocShell.editor. Such remaining cases should be fixed after nsI*Editor classes are marked as builtinclass. Note that this patch also creates nsIdentifierMapEntry.h which is separated from nsDocument.h because ShadowRoot.h needs the class but exposing nsDocument.h to the global and includes it causes bustage on Linux and Android. Therefore, for fixing the include hell, this patch touches them and ContentChild.cpp. MozReview-Commit-ID: i6fLWw6Qeo
dom/base/FragmentOrElement.h
dom/base/ShadowRoot.h
dom/base/moz.build
dom/base/nsDocument.h
dom/base/nsIdentifierMapEntry.h
dom/html/HTMLInputElement.cpp
dom/html/HTMLTextAreaElement.h
dom/html/nsTextEditorState.cpp
dom/html/nsTextEditorState.h
dom/ipc/ContentChild.cpp
editor/libeditor/EditorBase.cpp
editor/libeditor/EditorBase.h
editor/libeditor/TextEditor.cpp
editor/libeditor/TextEditor.h
--- a/dom/base/FragmentOrElement.h
+++ b/dom/base/FragmentOrElement.h
@@ -17,16 +17,17 @@
 #include "mozilla/MemoryReporting.h"
 #include "nsAttrAndChildArray.h"          // member
 #include "nsCycleCollectionParticipant.h" // NS_DECL_CYCLE_*
 #include "nsIContent.h"                   // base class
 #include "nsIWeakReference.h"             // base class
 #include "nsNodeUtils.h"                  // class member nsNodeUtils::CloneNodeImpl
 #include "nsIHTMLCollection.h"
 #include "nsDataHashtable.h"
+#include "nsXBLBinding.h"
 
 class ContentUnbinder;
 class nsContentList;
 class nsLabelsNodeList;
 class nsDOMAttributeMap;
 class nsDOMTokenList;
 class nsIControllers;
 class nsICSSDeclaration;
--- a/dom/base/ShadowRoot.h
+++ b/dom/base/ShadowRoot.h
@@ -8,18 +8,18 @@
 #define mozilla_dom_shadowroot_h__
 
 #include "mozilla/dom/DocumentFragment.h"
 #include "mozilla/dom/StyleSheetList.h"
 #include "mozilla/StyleSheet.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIContentInlines.h"
+#include "nsIdentifierMapEntry.h"
 #include "nsTHashtable.h"
-#include "nsDocument.h"
 
 class nsIAtom;
 class nsIContent;
 class nsXBLPrototypeBinding;
 
 namespace mozilla {
 namespace dom {
 
--- a/dom/base/moz.build
+++ b/dom/base/moz.build
@@ -79,16 +79,17 @@ EXPORTS += [
     'nsGkAtomList.h',
     'nsGkAtoms.h',
     'nsIAnimationObserver.h',
     'nsIAttribute.h',
     'nsIContent.h',
     'nsIContentInlines.h',
     'nsIContentIterator.h',
     'nsIContentSerializer.h',
+    'nsIdentifierMapEntry.h',
     'nsIDocument.h',
     'nsIDocumentInlines.h',
     'nsIDocumentObserver.h',
     'nsIDOMClassInfo.h',
     'nsIGlobalObject.h',
     'nsImageLoadingContent.h',
     'nsIMutationObserver.h',
     'nsINode.h',
--- a/dom/base/nsDocument.h
+++ b/dom/base/nsDocument.h
@@ -14,16 +14,17 @@
 #include "nsIDocument.h"
 
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsCRT.h"
 #include "nsWeakReference.h"
 #include "nsWeakPtr.h"
 #include "nsTArray.h"
+#include "nsIdentifierMapEntry.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsStubDocumentObserver.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIContent.h"
 #include "nsIPrincipal.h"
 #include "nsIParser.h"
 #include "nsBindingManager.h"
@@ -125,224 +126,16 @@ public:
   // request in a subdocument in different process, whereupon the caller
   // need to send some notification itself with the real origin.
   bool mShouldNotifyNewOrigin = true;
 };
 
 } // namespace dom
 } // namespace mozilla
 
-/**
- * Right now our identifier map entries contain information for 'name'
- * and 'id' mappings of a given string. This is so that
- * nsHTMLDocument::ResolveName only has to do one hash lookup instead
- * of two. It's not clear whether this still matters for performance.
- *
- * We also store the document.all result list here. This is mainly so that
- * when all elements with the given ID are removed and we remove
- * the ID's nsIdentifierMapEntry, the document.all result is released too.
- * Perhaps the document.all results should have their own hashtable
- * in nsHTMLDocument.
- */
-class nsIdentifierMapEntry : public PLDHashEntryHdr
-{
-public:
-  struct AtomOrString
-  {
-    MOZ_IMPLICIT AtomOrString(nsIAtom* aAtom) : mAtom(aAtom) {}
-    MOZ_IMPLICIT AtomOrString(const nsAString& aString) : mString(aString) {}
-    AtomOrString(const AtomOrString& aOther)
-      : mAtom(aOther.mAtom)
-      , mString(aOther.mString)
-    {
-    }
-
-    AtomOrString(AtomOrString&& aOther)
-      : mAtom(aOther.mAtom.forget())
-      , mString(aOther.mString)
-    {
-    }
-
-    nsCOMPtr<nsIAtom> mAtom;
-    const nsString mString;
-  };
-
-  typedef const AtomOrString& KeyType;
-  typedef const AtomOrString* KeyTypePointer;
-
-  typedef mozilla::dom::Element Element;
-  typedef mozilla::net::ReferrerPolicy ReferrerPolicy;
-
-  explicit nsIdentifierMapEntry(const AtomOrString& aKey)
-    : mKey(aKey)
-  {
-  }
-  explicit nsIdentifierMapEntry(const AtomOrString* aKey)
-    : mKey(aKey ? *aKey : nullptr)
-  {
-  }
-  nsIdentifierMapEntry(nsIdentifierMapEntry&& aOther) :
-    mKey(mozilla::Move(aOther.GetKey())),
-    mIdContentList(mozilla::Move(aOther.mIdContentList)),
-    mNameContentList(aOther.mNameContentList.forget()),
-    mChangeCallbacks(aOther.mChangeCallbacks.forget()),
-    mImageElement(aOther.mImageElement.forget())
-  {
-  }
-  ~nsIdentifierMapEntry();
-
-  KeyType GetKey() const { return mKey; }
-
-  nsString GetKeyAsString() const
-  {
-    if (mKey.mAtom) {
-      return nsAtomString(mKey.mAtom);
-    }
-
-    return mKey.mString;
-  }
-
-  bool KeyEquals(const KeyTypePointer aOtherKey) const
-  {
-    if (mKey.mAtom) {
-      if (aOtherKey->mAtom) {
-        return mKey.mAtom == aOtherKey->mAtom;
-      }
-
-      return mKey.mAtom->Equals(aOtherKey->mString);
-    }
-
-    if (aOtherKey->mAtom) {
-      return aOtherKey->mAtom->Equals(mKey.mString);
-    }
-
-    return mKey.mString.Equals(aOtherKey->mString);
-  }
-
-  static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
-
-  static PLDHashNumber HashKey(const KeyTypePointer aKey)
-  {
-    return aKey->mAtom ?
-      aKey->mAtom->hash() : mozilla::HashString(aKey->mString);
-  }
-
-  enum { ALLOW_MEMMOVE = false };
-
-  void AddNameElement(nsINode* aDocument, Element* aElement);
-  void RemoveNameElement(Element* aElement);
-  bool IsEmpty();
-  nsBaseContentList* GetNameContentList() {
-    return mNameContentList;
-  }
-  bool HasNameElement() const {
-    return mNameContentList && mNameContentList->Length() != 0;
-  }
-
-  /**
-   * Returns the element if we know the element associated with this
-   * id. Otherwise returns null.
-   */
-  Element* GetIdElement();
-  /**
-   * Returns the list of all elements associated with this id.
-   */
-  const nsTArray<Element*>& GetIdElements() const {
-    return mIdContentList;
-  }
-  /**
-   * If this entry has a non-null image element set (using SetImageElement),
-   * the image element will be returned, otherwise the same as GetIdElement().
-   */
-  Element* GetImageIdElement();
-  /**
-   * Append all the elements with this id to aElements
-   */
-  void AppendAllIdContent(nsCOMArray<nsIContent>* aElements);
-  /**
-   * This can fire ID change callbacks.
-   * @return true if the content could be added, false if we failed due
-   * to OOM.
-   */
-  bool AddIdElement(Element* aElement);
-  /**
-   * This can fire ID change callbacks.
-   */
-  void RemoveIdElement(Element* aElement);
-  /**
-   * Set the image element override for this ID. This will be returned by
-   * GetIdElement(true) if non-null.
-   */
-  void SetImageElement(Element* aElement);
-  bool HasIdElementExposedAsHTMLDocumentProperty();
-
-  bool HasContentChangeCallback() { return mChangeCallbacks != nullptr; }
-  void AddContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
-                                void* aData, bool aForImage);
-  void RemoveContentChangeCallback(nsIDocument::IDTargetObserver aCallback,
-                                void* aData, bool aForImage);
-
-  void Traverse(nsCycleCollectionTraversalCallback* aCallback);
-
-  struct ChangeCallback {
-    nsIDocument::IDTargetObserver mCallback;
-    void* mData;
-    bool mForImage;
-  };
-
-  struct ChangeCallbackEntry : public PLDHashEntryHdr {
-    typedef const ChangeCallback KeyType;
-    typedef const ChangeCallback* KeyTypePointer;
-
-    explicit ChangeCallbackEntry(const ChangeCallback* aKey) :
-      mKey(*aKey) { }
-    ChangeCallbackEntry(const ChangeCallbackEntry& toCopy) :
-      mKey(toCopy.mKey) { }
-
-    KeyType GetKey() const { return mKey; }
-    bool KeyEquals(KeyTypePointer aKey) const {
-      return aKey->mCallback == mKey.mCallback &&
-             aKey->mData == mKey.mData &&
-             aKey->mForImage == mKey.mForImage;
-    }
-
-    static KeyTypePointer KeyToPointer(KeyType& aKey) { return &aKey; }
-    static PLDHashNumber HashKey(KeyTypePointer aKey)
-    {
-      return mozilla::HashGeneric(aKey->mCallback, aKey->mData);
-    }
-    enum { ALLOW_MEMMOVE = true };
-
-    ChangeCallback mKey;
-  };
-
-  size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
-
-private:
-  nsIdentifierMapEntry(const nsIdentifierMapEntry& aOther) = delete;
-  nsIdentifierMapEntry& operator=(const nsIdentifierMapEntry& aOther) = delete;
-
-  void FireChangeCallbacks(Element* aOldElement, Element* aNewElement,
-                           bool aImageOnly = false);
-
-  AtomOrString mKey;
-  // empty if there are no elements with this ID.
-  // The elements are stored as weak pointers.
-  AutoTArray<Element*, 1> mIdContentList;
-  RefPtr<nsBaseContentList> mNameContentList;
-  nsAutoPtr<nsTHashtable<ChangeCallbackEntry> > mChangeCallbacks;
-  RefPtr<Element> mImageElement;
-};
-
-namespace mozilla {
-namespace dom {
-
-} // namespace dom
-} // namespace mozilla
-
 class nsDocHeaderData
 {
 public:
   nsDocHeaderData(nsIAtom* aField, const nsAString& aData)
     : mField(aField), mData(aData), mNext(nullptr)
   {
   }
 
copy from dom/base/nsDocument.h
copy to dom/base/nsIdentifierMapEntry.h
--- a/dom/base/nsDocument.h
+++ b/dom/base/nsIdentifierMapEntry.h
@@ -3,137 +3,35 @@
 /* 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/. */
 
 /*
  * Base class for all our document implementations.
  */
 
-#ifndef nsDocument_h___
-#define nsDocument_h___
-
-#include "nsIDocument.h"
+#ifndef nsIdentifierMapEntry_h
+#define nsIdentifierMapEntry_h
 
-#include "nsCOMPtr.h"
-#include "nsAutoPtr.h"
-#include "nsCRT.h"
-#include "nsWeakReference.h"
-#include "nsWeakPtr.h"
-#include "nsTArray.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMDocumentXBL.h"
-#include "nsStubDocumentObserver.h"
-#include "nsIScriptGlobalObject.h"
-#include "nsIContent.h"
-#include "nsIPrincipal.h"
-#include "nsIParser.h"
-#include "nsBindingManager.h"
-#include "nsInterfaceHashtable.h"
-#include "nsJSThingHashtable.h"
-#include "nsIScriptObjectPrincipal.h"
-#include "nsIURI.h"
-#include "nsIRadioGroupContainer.h"
-#include "nsILayoutHistoryState.h"
-#include "nsIRequest.h"
-#include "nsILoadGroup.h"
-#include "nsTObserverArray.h"
-#include "nsStubMutationObserver.h"
-#include "nsIChannel.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsContentList.h"
-#include "nsGkAtoms.h"
-#include "nsIApplicationCache.h"
-#include "nsIApplicationCacheContainer.h"
-#include "mozilla/StyleSetHandle.h"
 #include "PLDHashTable.h"
-#include "nsAttrAndChildArray.h"
-#include "nsDOMAttributeMap.h"
-#include "nsIContentViewer.h"
-#include "nsIInterfaceRequestor.h"
-#include "nsILoadContext.h"
-#include "nsIProgressEventSink.h"
-#include "nsISecurityEventSink.h"
-#include "nsIChannelEventSink.h"
-#include "imgIRequest.h"
-#include "mozilla/EventListenerManager.h"
-#include "mozilla/EventStates.h"
+
 #include "mozilla/MemoryReporting.h"
-#include "mozilla/PendingAnimationTracker.h"
-#include "mozilla/dom/DOMImplementation.h"
-#include "mozilla/dom/ScriptLoader.h"
-#include "mozilla/dom/StyleSheetList.h"
-#include "nsDataHashtable.h"
-#include "mozilla/TimeStamp.h"
-#include "mozilla/Attributes.h"
-#include "nsIDOMXPathEvaluator.h"
-#include "jsfriendapi.h"
-#include "mozilla/LinkedList.h"
-#include "CustomElementRegistry.h"
-#include "mozilla/dom/Performance.h"
-#include "mozilla/Maybe.h"
-
-#define XML_DECLARATION_BITS_DECLARATION_EXISTS   (1 << 0)
-#define XML_DECLARATION_BITS_ENCODING_EXISTS      (1 << 1)
-#define XML_DECLARATION_BITS_STANDALONE_EXISTS    (1 << 2)
-#define XML_DECLARATION_BITS_STANDALONE_YES       (1 << 3)
-
-
-class nsDOMStyleSheetSetList;
-class nsDocument;
-class nsIRadioVisitor;
-class nsIFormControl;
-struct nsRadioGroupStruct;
-class nsOnloadBlocker;
-class nsUnblockOnloadEvent;
-class nsDOMNavigationTiming;
-class nsWindowSizes;
-class nsHtml5TreeOpExecutor;
-class nsDocumentOnStack;
-class nsISecurityConsoleMessage;
-class nsPIBoxObject;
+#include "mozilla/Move.h"
+#include "mozilla/dom/Element.h"
+#include "mozilla/net/ReferrerPolicy.h"
 
-namespace mozilla {
-class EventChainPreVisitor;
-namespace dom {
-class BoxObject;
-class ImageTracker;
-struct LifecycleCallbacks;
-class CallbackFunction;
-class DOMIntersectionObserver;
-class Performance;
-
-struct FullscreenRequest : public LinkedListElement<FullscreenRequest>
-{
-  explicit FullscreenRequest(Element* aElement);
-  FullscreenRequest(const FullscreenRequest&) = delete;
-  ~FullscreenRequest();
-
-  Element* GetElement() const { return mElement; }
-  nsDocument* GetDocument() const { return mDocument; }
+#include "nsCOMArray.h"
+#include "nsCOMPtr.h"
+#include "nsContentList.h"
+#include "nsIAtom.h"
+#include "nsIDocument.h"
+#include "nsTArray.h"
+#include "nsTHashtable.h"
 
-private:
-  RefPtr<Element> mElement;
-  RefPtr<nsDocument> mDocument;
-
-public:
-  // This value should be true if the fullscreen request is
-  // originated from chrome code.
-  bool mIsCallerChrome = false;
-  // This value denotes whether we should trigger a NewOrigin event if
-  // requesting fullscreen in its document causes the origin which is
-  // fullscreen to change. We may want *not* to trigger that event if
-  // we're calling RequestFullScreen() as part of a continuation of a
-  // request in a subdocument in different process, whereupon the caller
-  // need to send some notification itself with the real origin.
-  bool mShouldNotifyNewOrigin = true;
-};
-
-} // namespace dom
-} // namespace mozilla
+class nsIContent;
 
 /**
  * Right now our identifier map entries contain information for 'name'
  * and 'id' mappings of a given string. This is so that
  * nsHTMLDocument::ResolveName only has to do one hash lookup instead
  * of two. It's not clear whether this still matters for performance.
  *
  * We also store the document.all result list here. This is mainly so that
@@ -327,1327 +225,9 @@ private:
   // empty if there are no elements with this ID.
   // The elements are stored as weak pointers.
   AutoTArray<Element*, 1> mIdContentList;
   RefPtr<nsBaseContentList> mNameContentList;
   nsAutoPtr<nsTHashtable<ChangeCallbackEntry> > mChangeCallbacks;
   RefPtr<Element> mImageElement;
 };
 
-namespace mozilla {
-namespace dom {
-
-} // namespace dom
-} // namespace mozilla
-
-class nsDocHeaderData
-{
-public:
-  nsDocHeaderData(nsIAtom* aField, const nsAString& aData)
-    : mField(aField), mData(aData), mNext(nullptr)
-  {
-  }
-
-  ~nsDocHeaderData(void)
-  {
-    delete mNext;
-  }
-
-  nsCOMPtr<nsIAtom> mField;
-  nsString          mData;
-  nsDocHeaderData*  mNext;
-};
-
-class nsDOMStyleSheetList : public mozilla::dom::StyleSheetList,
-                            public nsStubDocumentObserver
-{
-public:
-  explicit nsDOMStyleSheetList(nsIDocument* aDocument);
-
-  NS_DECL_ISUPPORTS_INHERITED
-
-  // nsIDocumentObserver
-  NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETADDED
-  NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETREMOVED
-
-  // nsIMutationObserver
-  NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED
-
-  virtual nsINode* GetParentObject() const override
-  {
-    return mDocument;
-  }
-
-  uint32_t Length() override;
-  mozilla::StyleSheet* IndexedGetter(uint32_t aIndex, bool& aFound) override;
-
-protected:
-  virtual ~nsDOMStyleSheetList();
-
-  int32_t       mLength;
-  nsIDocument*  mDocument;
-};
-
-class nsOnloadBlocker final : public nsIRequest
-{
-public:
-  nsOnloadBlocker() {}
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIREQUEST
-
-private:
-  ~nsOnloadBlocker() {}
-};
-
-class nsExternalResourceMap
-{
-public:
-  typedef nsIDocument::ExternalResourceLoad ExternalResourceLoad;
-  nsExternalResourceMap();
-
-  /**
-   * Request an external resource document.  This does exactly what
-   * nsIDocument::RequestExternalResource is documented to do.
-   */
-  nsIDocument* RequestResource(nsIURI* aURI,
-                               nsINode* aRequestingNode,
-                               nsDocument* aDisplayDocument,
-                               ExternalResourceLoad** aPendingLoad);
-
-  /**
-   * Enumerate the resource documents.  See
-   * nsIDocument::EnumerateExternalResources.
-   */
-  void EnumerateResources(nsIDocument::nsSubDocEnumFunc aCallback, void* aData);
-
-  /**
-   * Traverse ourselves for cycle-collection
-   */
-  void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
-
-  /**
-   * Shut ourselves down (used for cycle-collection unlink), as well
-   * as for document destruction.
-   */
-  void Shutdown()
-  {
-    mPendingLoads.Clear();
-    mMap.Clear();
-    mHaveShutDown = true;
-  }
-
-  bool HaveShutDown() const
-  {
-    return mHaveShutDown;
-  }
-
-  // Needs to be public so we can traverse them sanely
-  struct ExternalResource
-  {
-    ~ExternalResource();
-    nsCOMPtr<nsIDocument> mDocument;
-    nsCOMPtr<nsIContentViewer> mViewer;
-    nsCOMPtr<nsILoadGroup> mLoadGroup;
-  };
-
-  // Hide all our viewers
-  void HideViewers();
-
-  // Show all our viewers
-  void ShowViewers();
-
-protected:
-  class PendingLoad : public ExternalResourceLoad,
-                      public nsIStreamListener
-  {
-    ~PendingLoad() {}
-
-  public:
-    explicit PendingLoad(nsDocument* aDisplayDocument) :
-      mDisplayDocument(aDisplayDocument)
-    {}
-
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSISTREAMLISTENER
-    NS_DECL_NSIREQUESTOBSERVER
-
-    /**
-     * Start aURI loading.  This will perform the necessary security checks and
-     * so forth.
-     */
-    nsresult StartLoad(nsIURI* aURI, nsINode* aRequestingNode);
-
-    /**
-     * Set up an nsIContentViewer based on aRequest.  This is guaranteed to
-     * put null in *aViewer and *aLoadGroup on all failures.
-     */
-    nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
-                         nsILoadGroup** aLoadGroup);
-
-  private:
-    RefPtr<nsDocument> mDisplayDocument;
-    nsCOMPtr<nsIStreamListener> mTargetListener;
-    nsCOMPtr<nsIURI> mURI;
-  };
-  friend class PendingLoad;
-
-  class LoadgroupCallbacks final : public nsIInterfaceRequestor
-  {
-    ~LoadgroupCallbacks() {}
-  public:
-    explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
-      : mCallbacks(aOtherCallbacks)
-    {}
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSIINTERFACEREQUESTOR
-  private:
-    // The only reason it's safe to hold a strong ref here without leaking is
-    // that the notificationCallbacks on a loadgroup aren't the docshell itself
-    // but a shim that holds a weak reference to the docshell.
-    nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
-
-    // Use shims for interfaces that docshell implements directly so that we
-    // don't hand out references to the docshell.  The shims should all allow
-    // getInterface back on us, but other than that each one should only
-    // implement one interface.
-
-    // XXXbz I wish we could just derive the _allcaps thing from _i
-#define DECL_SHIM(_i, _allcaps)                                              \
-    class _i##Shim final : public nsIInterfaceRequestor,                     \
-                           public _i                                         \
-    {                                                                        \
-      ~_i##Shim() {}                                                         \
-    public:                                                                  \
-      _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr)                  \
-        : mIfReq(aIfreq), mRealPtr(aRealPtr)                                 \
-      {                                                                      \
-        NS_ASSERTION(mIfReq, "Expected non-null here");                      \
-        NS_ASSERTION(mRealPtr, "Expected non-null here");                    \
-      }                                                                      \
-      NS_DECL_ISUPPORTS                                                      \
-      NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->)                             \
-      NS_FORWARD_##_allcaps(mRealPtr->)                                      \
-    private:                                                                 \
-      nsCOMPtr<nsIInterfaceRequestor> mIfReq;                                \
-      nsCOMPtr<_i> mRealPtr;                                                 \
-    };
-
-    DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
-    DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
-    DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
-    DECL_SHIM(nsISecurityEventSink, NSISECURITYEVENTSINK)
-    DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
-#undef DECL_SHIM
-  };
-
-  /**
-   * Add an ExternalResource for aURI.  aViewer and aLoadGroup might be null
-   * when this is called if the URI didn't result in an XML document.  This
-   * function makes sure to remove the pending load for aURI, if any, from our
-   * hashtable, and to notify its observers, if any.
-   */
-  nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
-                               nsILoadGroup* aLoadGroup,
-                               nsIDocument* aDisplayDocument);
-
-  nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
-  nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
-  bool mHaveShutDown;
-};
-
-// Base class for our document implementations.
-class nsDocument : public nsIDocument,
-                   public nsIDOMDocument,
-                   public nsIDOMDocumentXBL,
-                   public nsSupportsWeakReference,
-                   public nsIScriptObjectPrincipal,
-                   public nsIRadioGroupContainer,
-                   public nsIApplicationCacheContainer,
-                   public nsStubMutationObserver,
-                   public nsIObserver,
-                   public nsIDOMXPathEvaluator
-{
-  friend class nsIDocument;
-
-public:
-  typedef mozilla::dom::Element Element;
-  using nsIDocument::GetElementsByTagName;
-  typedef mozilla::net::ReferrerPolicy ReferrerPolicy;
-
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-
-  NS_DECL_SIZEOF_EXCLUDING_THIS
-
-  virtual void Reset(nsIChannel *aChannel, nsILoadGroup *aLoadGroup) override;
-  virtual void ResetToURI(nsIURI *aURI, nsILoadGroup *aLoadGroup,
-                          nsIPrincipal* aPrincipal) override;
-
-  already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(nsIPrincipal* aPrincipal);
-
-  // StartDocumentLoad is pure virtual so that subclasses must override it.
-  // The nsDocument StartDocumentLoad does some setup, but does NOT set
-  // *aDocListener; this is the job of subclasses.
-  virtual nsresult StartDocumentLoad(const char* aCommand,
-                                     nsIChannel* aChannel,
-                                     nsILoadGroup* aLoadGroup,
-                                     nsISupports* aContainer,
-                                     nsIStreamListener **aDocListener,
-                                     bool aReset = true,
-                                     nsIContentSink* aContentSink = nullptr) override = 0;
-
-  virtual void StopDocumentLoad() override;
-
-  virtual void NotifyPossibleTitleChange(bool aBoundTitleElement) override;
-
-  virtual void SetDocumentURI(nsIURI* aURI) override;
-
-  virtual void SetChromeXHRDocURI(nsIURI* aURI) override;
-
-  virtual void SetChromeXHRDocBaseURI(nsIURI* aURI) override;
-
-  virtual void ApplySettingsFromCSP(bool aSpeculative) override;
-
-  virtual already_AddRefed<nsIParser> CreatorParserOrNull() override;
-
-  /**
-   * Set the principal responsible for this document.
-   */
-  virtual void SetPrincipal(nsIPrincipal *aPrincipal) override;
-
-  /**
-   * Get the Content-Type of this document.
-   */
-  // NS_IMETHOD GetContentType(nsAString& aContentType);
-  // Already declared in nsIDOMDocument
-
-  /**
-   * Set the Content-Type of this document.
-   */
-  virtual void SetContentType(const nsAString& aContentType) override;
-
-  virtual void SetBaseURI(nsIURI* aURI) override;
-
-  /**
-   * Get/Set the base target of a link in a document.
-   */
-  virtual void GetBaseTarget(nsAString &aBaseTarget) override;
-
-  /**
-   * Return a standard name for the document's character set. This will
-   * trigger a startDocumentLoad if necessary to answer the question.
-   */
-  virtual void SetDocumentCharacterSet(const nsACString& aCharSetID) override;
-
-  /**
-   * Add an observer that gets notified whenever the charset changes.
-   */
-  virtual nsresult AddCharSetObserver(nsIObserver* aObserver) override;
-
-  /**
-   * Remove a charset observer.
-   */
-  virtual void RemoveCharSetObserver(nsIObserver* aObserver) override;
-
-  virtual Element* AddIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
-                                       void* aData, bool aForImage) override;
-  virtual void RemoveIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
-                                      void* aData, bool aForImage) override;
-
-  /**
-   * Access HTTP header data (this may also get set from other sources, like
-   * HTML META tags).
-   */
-  virtual void GetHeaderData(nsIAtom* aHeaderField, nsAString& aData) const override;
-  virtual void SetHeaderData(nsIAtom* aheaderField,
-                             const nsAString& aData) override;
-
-  /**
-   * Create a new presentation shell that will use aContext for
-   * its presentation context (presentation contexts <b>must not</b> be
-   * shared among multiple presentation shells).
-   */
-  already_AddRefed<nsIPresShell> CreateShell(nsPresContext* aContext,
-                                             nsViewManager* aViewManager,
-                                             mozilla::StyleSetHandle aStyleSet)
-    final;
-  virtual void DeleteShell() override;
-
-  virtual bool GetAllowPlugins() override;
-
-  static bool IsElementAnimateEnabled(JSContext* aCx, JSObject* aObject);
-  static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
-  virtual mozilla::dom::DocumentTimeline* Timeline() override;
-  virtual void GetAnimations(
-      nsTArray<RefPtr<mozilla::dom::Animation>>& aAnimations) override;
-  mozilla::LinkedList<mozilla::dom::DocumentTimeline>& Timelines() override
-  {
-    return mTimelines;
-  }
-
-  virtual nsresult SetSubDocumentFor(Element* aContent,
-                                     nsIDocument* aSubDoc) override;
-  virtual nsIDocument* GetSubDocumentFor(nsIContent* aContent) const override;
-  virtual Element* FindContentForSubDocument(nsIDocument *aDocument) const override;
-  virtual Element* GetRootElementInternal() const override;
-
-  virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet) override;
-
-  /**
-   * Get the (document) style sheets owned by this document.
-   * These are ordered, highest priority last
-   */
-  virtual int32_t GetNumberOfStyleSheets() const override;
-  virtual mozilla::StyleSheet* GetStyleSheetAt(int32_t aIndex) const override;
-  virtual int32_t GetIndexOfStyleSheet(
-      const mozilla::StyleSheet* aSheet) const override;
-  virtual void AddStyleSheet(mozilla::StyleSheet* aSheet) override;
-  virtual void RemoveStyleSheet(mozilla::StyleSheet* aSheet) override;
-
-  virtual void UpdateStyleSheets(
-      nsTArray<RefPtr<mozilla::StyleSheet>>& aOldSheets,
-      nsTArray<RefPtr<mozilla::StyleSheet>>& aNewSheets) override;
-  virtual void AddStyleSheetToStyleSets(mozilla::StyleSheet* aSheet);
-  virtual void RemoveStyleSheetFromStyleSets(mozilla::StyleSheet* aSheet);
-
-  virtual void InsertStyleSheetAt(mozilla::StyleSheet* aSheet,
-                                  int32_t aIndex) override;
-  virtual void SetStyleSheetApplicableState(mozilla::StyleSheet* aSheet,
-                                            bool aApplicable) override;
-
-  virtual nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
-                                            nsIURI* aSheetURI) override;
-  virtual nsresult AddAdditionalStyleSheet(additionalSheetType aType,
-                                           mozilla::StyleSheet* aSheet) override;
-  virtual void RemoveAdditionalStyleSheet(additionalSheetType aType,
-                                          nsIURI* sheetURI) override;
-  virtual mozilla::StyleSheet* GetFirstAdditionalAuthorSheet() override;
-
-  virtual nsIChannel* GetChannel() const override {
-    return mChannel;
-  }
-
-  virtual nsIChannel* GetFailedChannel() const override {
-    return mFailedChannel;
-  }
-  virtual void SetFailedChannel(nsIChannel* aChannel) override {
-    mFailedChannel = aChannel;
-  }
-
-  virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject) override;
-
-  virtual void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject) override;
-
-  virtual nsIGlobalObject* GetScopeObject() const override;
-  void SetScopeObject(nsIGlobalObject* aGlobal) override;
-  /**
-   * Get the script loader for this document
-   */
-  virtual mozilla::dom::ScriptLoader* ScriptLoader() override;
-
-  /**
-   * Add/Remove an element to the document's id and name hashes
-   */
-  virtual void AddToIdTable(Element* aElement, nsIAtom* aId) override;
-  virtual void RemoveFromIdTable(Element* aElement, nsIAtom* aId) override;
-  virtual void AddToNameTable(Element* aElement, nsIAtom* aName) override;
-  virtual void RemoveFromNameTable(Element* aElement, nsIAtom* aName) override;
-
-  /**
-   * Add a new observer of document change notifications. Whenever
-   * content is changed, appended, inserted or removed the observers are
-   * informed.
-   */
-  virtual void AddObserver(nsIDocumentObserver* aObserver) override;
-
-  /**
-   * Remove an observer of document change notifications. This will
-   * return false if the observer cannot be found.
-   */
-  virtual bool RemoveObserver(nsIDocumentObserver* aObserver) override;
-
-  // Observation hooks used to propagate notifications to document
-  // observers.
-  virtual void BeginUpdate(nsUpdateType aUpdateType) override;
-  virtual void EndUpdate(nsUpdateType aUpdateType) override;
-  virtual void BeginLoad() override;
-  virtual void EndLoad() override;
-
-  virtual void SetReadyStateInternal(ReadyState rs) override;
-
-  virtual void ContentStateChanged(nsIContent* aContent,
-                                   mozilla::EventStates aStateMask)
-                                     override;
-  virtual void DocumentStatesChanged(
-                 mozilla::EventStates aStateMask) override;
-
-  virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet,
-                                mozilla::css::Rule* aStyleRule) override;
-  virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet,
-                              mozilla::css::Rule* aStyleRule) override;
-  virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet,
-                                mozilla::css::Rule* aStyleRule) override;
-
-  virtual void FlushPendingNotifications(mozilla::FlushType aType) override;
-  virtual void FlushExternalResources(mozilla::FlushType aType) override;
-  virtual void SetXMLDeclaration(const char16_t *aVersion,
-                                 const char16_t *aEncoding,
-                                 const int32_t aStandalone) override;
-  virtual void GetXMLDeclaration(nsAString& aVersion,
-                                 nsAString& aEncoding,
-                                 nsAString& Standalone) override;
-  virtual bool IsScriptEnabled() override;
-
-  virtual void OnPageShow(bool aPersisted, mozilla::dom::EventTarget* aDispatchStartTarget) override;
-  virtual void OnPageHide(bool aPersisted, mozilla::dom::EventTarget* aDispatchStartTarget) override;
-
-  virtual void WillDispatchMutationEvent(nsINode* aTarget) override;
-  virtual void MutationEventDispatched(nsINode* aTarget) override;
-
-  // nsINode
-  virtual bool IsNodeOfType(uint32_t aFlags) const override;
-  virtual nsIContent *GetChildAt(uint32_t aIndex) const override;
-  virtual nsIContent * const * GetChildArray(uint32_t* aChildCount) const override;
-  virtual int32_t IndexOf(const nsINode* aPossibleChild) const override;
-  virtual uint32_t GetChildCount() const override;
-  virtual nsresult InsertChildAt(nsIContent* aKid, uint32_t aIndex,
-                                 bool aNotify) override;
-  virtual void RemoveChildAt(uint32_t aIndex, bool aNotify) override;
-  virtual nsresult Clone(mozilla::dom::NodeInfo *aNodeInfo, nsINode **aResult,
-                         bool aPreallocateChildren) const override
-  {
-    return NS_ERROR_NOT_IMPLEMENTED;
-  }
-
-  // nsIRadioGroupContainer
-  NS_IMETHOD WalkRadioGroup(const nsAString& aName,
-                            nsIRadioVisitor* aVisitor,
-                            bool aFlushContent) override;
-  virtual void
-    SetCurrentRadioButton(const nsAString& aName,
-                          mozilla::dom::HTMLInputElement* aRadio) override;
-  virtual mozilla::dom::HTMLInputElement*
-    GetCurrentRadioButton(const nsAString& aName) override;
-  NS_IMETHOD
-    GetNextRadioButton(const nsAString& aName,
-                       const bool aPrevious,
-                       mozilla::dom::HTMLInputElement*  aFocusedRadio,
-                       mozilla::dom::HTMLInputElement** aRadioOut) override;
-  virtual void AddToRadioGroup(const nsAString& aName,
-                               nsIFormControl* aRadio) override;
-  virtual void RemoveFromRadioGroup(const nsAString& aName,
-                                    nsIFormControl* aRadio) override;
-  virtual uint32_t GetRequiredRadioCount(const nsAString& aName) const override;
-  virtual void RadioRequiredWillChange(const nsAString& aName,
-                                       bool aRequiredAdded) override;
-  virtual bool GetValueMissingState(const nsAString& aName) const override;
-  virtual void SetValueMissingState(const nsAString& aName, bool aValue) override;
-
-  // for radio group
-  nsRadioGroupStruct* GetRadioGroup(const nsAString& aName) const;
-  nsRadioGroupStruct* GetOrCreateRadioGroup(const nsAString& aName);
-
-  virtual nsViewportInfo GetViewportInfo(const mozilla::ScreenIntSize& aDisplaySize) override;
-
-  enum class UseCounterReportKind {
-    // Flush the document's use counters only; the use counters for any
-    // external resource documents will be flushed when the external
-    // resource documents themselves are destroyed.
-    eDefault,
-
-    // Flush use counters for the document and for its external resource
-    // documents. (Should only be necessary for tests, where we need
-    // flushing to happen synchronously and deterministically.)
-    eIncludeExternalResources,
-  };
-
-  void ReportUseCounters(UseCounterReportKind aKind = UseCounterReportKind::eDefault);
-
-  virtual void AddIntersectionObserver(
-    mozilla::dom::DOMIntersectionObserver* aObserver) override;
-  virtual void RemoveIntersectionObserver(
-    mozilla::dom::DOMIntersectionObserver* aObserver) override;
-  virtual void UpdateIntersectionObservations() override;
-  virtual void ScheduleIntersectionObserverNotification() override;
-  virtual void NotifyIntersectionObservers() override;
-
-  virtual void NotifyLayerManagerRecreated() override;
-
-  virtual void ScheduleSVGForPresAttrEvaluation(nsSVGElement* aSVG) override;
-  virtual void UnscheduleSVGForPresAttrEvaluation(nsSVGElement* aSVG) override;
-  virtual void ResolveScheduledSVGPresAttrs() override;
-
-private:
-  void AddOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet);
-  void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
-
-public:
-  // nsIDOMNode
-  NS_FORWARD_NSIDOMNODE_TO_NSINODE_OVERRIDABLE
-
-  // nsIDOMDocument
-  NS_DECL_NSIDOMDOCUMENT
-
-  // nsIDOMDocumentXBL
-  NS_DECL_NSIDOMDOCUMENTXBL
-
-  // nsIDOMEventTarget
-  virtual nsresult GetEventTargetParent(
-                     mozilla::EventChainPreVisitor& aVisitor) override;
-  virtual mozilla::EventListenerManager*
-    GetOrCreateListenerManager() override;
-  virtual mozilla::EventListenerManager*
-    GetExistingListenerManager() const override;
-
-  // nsIScriptObjectPrincipal
-  virtual nsIPrincipal* GetPrincipal() override;
-
-  // nsIApplicationCacheContainer
-  NS_DECL_NSIAPPLICATIONCACHECONTAINER
-
-  // nsIObserver
-  NS_DECL_NSIOBSERVER
-
-  NS_DECL_NSIDOMXPATHEVALUATOR
-
-  virtual nsresult Init();
-
-  virtual already_AddRefed<Element> CreateElem(const nsAString& aName,
-                                               nsIAtom* aPrefix,
-                                               int32_t aNamespaceID,
-                                               const nsAString* aIs = nullptr) override;
-
-  virtual void Sanitize() override;
-
-  virtual void EnumerateSubDocuments(nsSubDocEnumFunc aCallback,
-                                                 void *aData) override;
-
-  virtual bool CanSavePresentation(nsIRequest *aNewRequest) override;
-  virtual void Destroy() override;
-  virtual void RemovedFromDocShell() override;
-  virtual already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const override;
-
-  virtual void BlockOnload() override;
-  virtual void UnblockOnload(bool aFireSync) override;
-
-  virtual void AddStyleRelevantLink(mozilla::dom::Link* aLink) override;
-  virtual void ForgetLink(mozilla::dom::Link* aLink) override;
-
-  virtual void ClearBoxObjectFor(nsIContent* aContent) override;
-
-  virtual already_AddRefed<mozilla::dom::BoxObject>
-  GetBoxObjectFor(mozilla::dom::Element* aElement,
-                  mozilla::ErrorResult& aRv) override;
-
-  virtual Element*
-    GetAnonymousElementByAttribute(nsIContent* aElement,
-                                   nsIAtom* aAttrName,
-                                   const nsAString& aAttrValue) const override;
-
-  virtual Element* ElementFromPointHelper(float aX, float aY,
-                                          bool aIgnoreRootScrollFrame,
-                                          bool aFlushLayout) override;
-
-  virtual void ElementsFromPointHelper(float aX, float aY,
-                                       uint32_t aFlags,
-                                       nsTArray<RefPtr<mozilla::dom::Element>>& aElements) override;
-
-  virtual nsresult NodesFromRectHelper(float aX, float aY,
-                                                   float aTopSize, float aRightSize,
-                                                   float aBottomSize, float aLeftSize,
-                                                   bool aIgnoreRootScrollFrame,
-                                                   bool aFlushLayout,
-                                                   nsIDOMNodeList** aReturn) override;
-
-  virtual void FlushSkinBindings() override;
-
-  virtual nsresult InitializeFrameLoader(nsFrameLoader* aLoader) override;
-  virtual nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer) override;
-  virtual void TryCancelFrameLoaderInitialization(nsIDocShell* aShell) override;
-  virtual nsIDocument*
-    RequestExternalResource(nsIURI* aURI,
-                            nsINode* aRequestingNode,
-                            ExternalResourceLoad** aPendingLoad) override;
-  virtual void
-    EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData) override;
-
-  // Returns our (lazily-initialized) animation controller.
-  // If HasAnimationController is true, this is guaranteed to return non-null.
-  nsSMILAnimationController* GetAnimationController() override;
-
-  virtual mozilla::PendingAnimationTracker*
-  GetPendingAnimationTracker() final override
-  {
-    return mPendingAnimationTracker;
-  }
-
-  virtual mozilla::PendingAnimationTracker*
-  GetOrCreatePendingAnimationTracker() override;
-
-  virtual void SuppressEventHandling(uint32_t aIncrease) override;
-
-  virtual void UnsuppressEventHandlingAndFireEvents(bool aFireEvents) override;
-
-  void DecreaseEventSuppression() {
-    MOZ_ASSERT(mEventsSuppressed);
-    --mEventsSuppressed;
-    UpdateFrameRequestCallbackSchedulingState();
-  }
-
-  virtual nsIDocument* GetTemplateContentsOwner() override;
-
-  NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsDocument,
-                                                                   nsIDocument)
-
-  void DoNotifyPossibleTitleChange();
-
-  nsExternalResourceMap& ExternalResourceMap()
-  {
-    return mExternalResourceMap;
-  }
-
-  void SetLoadedAsData(bool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
-  void SetLoadedAsInteractiveData(bool aLoadedAsInteractiveData)
-  {
-    mLoadedAsInteractiveData = aLoadedAsInteractiveData;
-  }
-
-  nsresult CloneDocHelper(nsDocument* clone, bool aPreallocateChildren) const;
-
-  void MaybeInitializeFinalizeFrameLoaders();
-
-  void MaybeEndOutermostXBLUpdate();
-
-  virtual void PreloadPictureOpened() override;
-  virtual void PreloadPictureClosed() override;
-
-  virtual void
-    PreloadPictureImageSource(const nsAString& aSrcsetAttr,
-                              const nsAString& aSizesAttr,
-                              const nsAString& aTypeAttr,
-                              const nsAString& aMediaAttr) override;
-
-  virtual already_AddRefed<nsIURI>
-    ResolvePreloadImage(nsIURI *aBaseURI,
-                        const nsAString& aSrcAttr,
-                        const nsAString& aSrcsetAttr,
-                        const nsAString& aSizesAttr) override;
-
-  virtual void MaybePreLoadImage(nsIURI* uri,
-                                 const nsAString &aCrossOriginAttr,
-                                 ReferrerPolicy aReferrerPolicy) override;
-  virtual void ForgetImagePreload(nsIURI* aURI) override;
-
-  virtual void MaybePreconnect(nsIURI* uri,
-                               mozilla::CORSMode aCORSMode) override;
-
-  virtual void PreloadStyle(nsIURI* uri, const nsAString& charset,
-                            const nsAString& aCrossOriginAttr,
-                            ReferrerPolicy aReferrerPolicy,
-                            const nsAString& aIntegrity) override;
-
-  virtual nsresult LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
-                                       RefPtr<mozilla::StyleSheet>* aSheet) override;
-
-  virtual nsISupports* GetCurrentContentSink() override;
-
-  virtual mozilla::EventStates GetDocumentState() final;
-  // GetDocumentState() mutates the state due to lazy resolution;
-  // and can't be used during parallel traversal. Use this instead,
-  // and ensure GetDocumentState() has been called first.
-  // This will assert if the state is stale.
-  virtual mozilla::EventStates ThreadSafeGetDocumentState() const final;
-
-  // Only BlockOnload should call this!
-  void AsyncBlockOnload();
-
-  virtual void SetScrollToRef(nsIURI *aDocumentURI) override;
-  virtual void ScrollToRef() override;
-  virtual void ResetScrolledToRefAlready() override;
-  virtual void SetChangeScrollPosWhenScrollingToRef(bool aValue) override;
-
-  virtual Element *GetElementById(const nsAString& aElementId) override;
-  virtual const nsTArray<Element*>* GetAllElementsForId(const nsAString& aElementId) const override;
-
-  virtual Element *LookupImageElement(const nsAString& aElementId) override;
-  virtual void MozSetImageElement(const nsAString& aImageElementId,
-                                  Element* aElement) override;
-
-  // AddPlugin adds a plugin-related element to mPlugins when the element is
-  // added to the tree.
-  virtual nsresult AddPlugin(nsIObjectLoadingContent* aPlugin) override;
-  // RemovePlugin removes a plugin-related element to mPlugins when the
-  // element is removed from the tree.
-  virtual void RemovePlugin(nsIObjectLoadingContent* aPlugin) override;
-  // GetPlugins returns the plugin-related elements from
-  // the frame and any subframes.
-  virtual void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins) override;
-
-  // Adds an element to mResponsiveContent when the element is
-  // added to the tree.
-  virtual nsresult AddResponsiveContent(nsIContent* aContent) override;
-  // Removes an element from mResponsiveContent when the element is
-  // removed from the tree.
-  virtual void RemoveResponsiveContent(nsIContent* aContent) override;
-  // Notifies any responsive content added by AddResponsiveContent upon media
-  // features values changing.
-  virtual void NotifyMediaFeatureValuesChanged() override;
-
-  virtual nsresult GetStateObject(nsIVariant** aResult) override;
-
-  virtual nsDOMNavigationTiming* GetNavigationTiming() const override;
-  virtual nsresult SetNavigationTiming(nsDOMNavigationTiming* aTiming) override;
-
-  virtual Element* FindImageMap(const nsAString& aNormalizedMapName) override;
-
-  virtual nsTArray<Element*> GetFullscreenStack() const override;
-  virtual void AsyncRequestFullScreen(
-    mozilla::UniquePtr<FullscreenRequest>&& aRequest) override;
-  virtual void RestorePreviousFullScreenState() override;
-  virtual bool IsFullscreenLeaf() override;
-  virtual nsresult
-    RemoteFrameFullscreenChanged(nsIDOMElement* aFrameElement) override;
-
-  virtual nsresult RemoteFrameFullscreenReverted() override;
-  virtual nsIDocument* GetFullscreenRoot() override;
-  virtual void SetFullscreenRoot(nsIDocument* aRoot) override;
-
-  // Returns the size of the mBlockedTrackingNodes array. (nsIDocument.h)
-  //
-  // This array contains nodes that have been blocked to prevent
-  // user tracking. They most likely have had their nsIChannel
-  // canceled by the URL classifier (Safebrowsing).
-  //
-  // A script can subsequently use GetBlockedTrackingNodes()
-  // to get a list of references to these nodes.
-  //
-  // Note:
-  // This expresses how many tracking nodes have been blocked for this
-  // document since its beginning, not how many of them are still around
-  // in the DOM tree. Weak references to blocked nodes are added in the
-  // mBlockedTrackingNodesArray but they are not removed when those nodes
-  // are removed from the tree or even garbage collected.
-  long BlockedTrackingNodeCount() const;
-
-  //
-  // Returns strong references to mBlockedTrackingNodes. (nsIDocument.h)
-  //
-  // This array contains nodes that have been blocked to prevent
-  // user tracking. They most likely have had their nsIChannel
-  // canceled by the URL classifier (Safebrowsing).
-  //
-  already_AddRefed<nsSimpleContentList> BlockedTrackingNodes() const;
-
-  static bool IsUnprefixedFullscreenEnabled(JSContext* aCx, JSObject* aObject);
-
-  // Do the "fullscreen element ready check" from the fullscreen spec.
-  // It returns true if the given element is allowed to go into fullscreen.
-  bool FullscreenElementReadyCheck(Element* aElement, bool aWasCallerChrome);
-
-  // This is called asynchronously by nsIDocument::AsyncRequestFullScreen()
-  // to move this document into full-screen mode if allowed.
-  void RequestFullScreen(mozilla::UniquePtr<FullscreenRequest>&& aRequest);
-
-  // Removes all elements from the full-screen stack, removing full-scren
-  // styles from the top element in the stack.
-  void CleanupFullscreenState();
-
-  // Pushes aElement onto the full-screen stack, and removes full-screen styles
-  // from the former full-screen stack top, and its ancestors, and applies the
-  // styles to aElement. aElement becomes the new "full-screen element".
-  bool FullScreenStackPush(Element* aElement);
-
-  // Remove the top element from the full-screen stack. Removes the full-screen
-  // styles from the former top element, and applies them to the new top
-  // element, if there is one.
-  void FullScreenStackPop();
-
-  // Returns the top element from the full-screen stack.
-  Element* FullScreenStackTop();
-
-  // DOM-exposed fullscreen API
-  bool FullscreenEnabled(mozilla::dom::CallerType aCallerType) override;
-  Element* GetFullscreenElement() override;
-
-  void RequestPointerLock(Element* aElement,
-                          mozilla::dom::CallerType aCallerType) override;
-  bool SetPointerLock(Element* aElement, int aCursorStyle);
-  static void UnlockPointer(nsIDocument* aDoc = nullptr);
-
-  void SetCurrentOrientation(mozilla::dom::OrientationType aType,
-                             uint16_t aAngle) override;
-  uint16_t CurrentOrientationAngle() const override;
-  mozilla::dom::OrientationType CurrentOrientationType() const override;
-  void SetOrientationPendingPromise(mozilla::dom::Promise* aPromise) override;
-  mozilla::dom::Promise* GetOrientationPendingPromise() const override;
-
-  // This method may fire a DOM event; if it does so it will happen
-  // synchronously.
-  void UpdateVisibilityState();
-  // Posts an event to call UpdateVisibilityState
-  virtual void PostVisibilityUpdateEvent() override;
-
-  // Since we wouldn't automatically play media from non-visited page, we need
-  // to notify window when the page was first visited.
-  void MaybeActiveMediaComponents();
-
-  virtual void DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const override;
-  // DocAddSizeOfIncludingThis is inherited from nsIDocument.
-
-  virtual nsIDOMNode* AsDOMNode() override { return this; }
-
-  // WebIDL bits
-  virtual mozilla::dom::DOMImplementation*
-    GetImplementation(mozilla::ErrorResult& rv) override;
-  virtual void
-    RegisterElement(JSContext* aCx, const nsAString& aName,
-                    const mozilla::dom::ElementRegistrationOptions& aOptions,
-                    JS::MutableHandle<JSObject*> aRetval,
-                    mozilla::ErrorResult& rv) override;
-  virtual mozilla::dom::StyleSheetList* StyleSheets() override;
-  virtual void SetSelectedStyleSheetSet(const nsAString& aSheetSet) override;
-  virtual void GetLastStyleSheetSet(nsString& aSheetSet) override;
-  virtual mozilla::dom::DOMStringList* StyleSheetSets() override;
-  virtual void EnableStyleSheetsForSet(const nsAString& aSheetSet) override;
-  virtual already_AddRefed<Element> CreateElement(const nsAString& aTagName,
-                                                  const mozilla::dom::ElementCreationOptionsOrString& aOptions,
-                                                  ErrorResult& rv) override;
-  virtual already_AddRefed<Element> CreateElementNS(const nsAString& aNamespaceURI,
-                                                    const nsAString& aQualifiedName,
-                                                    const mozilla::dom::ElementCreationOptionsOrString& aOptions,
-                                                    mozilla::ErrorResult& rv) override;
-
-  virtual void UnblockDOMContentLoaded() override;
-
-protected:
-  friend class nsNodeUtils;
-  friend class nsDocumentOnStack;
-
-  void IncreaseStackRefCnt()
-  {
-    ++mStackRefCnt;
-  }
-
-  void DecreaseStackRefCnt()
-  {
-    if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
-      mNeedsReleaseAfterStackRefCntRelease = false;
-      NS_RELEASE_THIS();
-    }
-  }
-
-  /**
-   * Check that aId is not empty and log a message to the console
-   * service if it is.
-   * @returns true if aId looks correct, false otherwise.
-   */
-  inline bool CheckGetElementByIdArg(const nsAString& aId)
-  {
-    if (aId.IsEmpty()) {
-      ReportEmptyGetElementByIdArg();
-      return false;
-    }
-    return true;
-  }
-
-  void ReportEmptyGetElementByIdArg();
-
-  void DispatchContentLoadedEvents();
-
-  void RetrieveRelevantHeaders(nsIChannel *aChannel);
-
-  void TryChannelCharset(nsIChannel *aChannel,
-                         int32_t& aCharsetSource,
-                         nsACString& aCharset,
-                         nsHtml5TreeOpExecutor* aExecutor);
-
-  // Call this before the document does something that will unbind all content.
-  // That will stop us from doing a lot of work as each element is removed.
-  void DestroyElementMaps();
-
-  // Refreshes the hrefs of all the links in the document.
-  void RefreshLinkHrefs();
-
-  nsIContent* GetFirstBaseNodeWithHref();
-  nsresult SetFirstBaseNodeWithHref(nsIContent *node);
-
-  /**
-   * Returns the title element of the document as defined by the HTML
-   * specification, or null if there isn't one.  For documents whose root
-   * element is an <svg:svg>, this is the first <svg:title> element that's a
-   * child of the root.  For other documents, it's the first HTML title element
-   * in the document.
-   */
-  Element* GetTitleElement();
-
-public:
-  // Get our title
-  virtual void GetTitle(nsString& aTitle) override;
-  // Set our title
-  virtual void SetTitle(const nsAString& aTitle, mozilla::ErrorResult& rv) override;
-
-  js::ExpandoAndGeneration mExpandoAndGeneration;
-
-  bool ContainsEMEContent();
-
-  bool ContainsMSEContent();
-
-protected:
-  void RemoveDocStyleSheetsFromStyleSets();
-  void RemoveStyleSheetsFromStyleSets(
-      const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets,
-      mozilla::SheetType aType);
-  void ResetStylesheetsToURI(nsIURI* aURI);
-  void FillStyleSet(mozilla::StyleSetHandle aStyleSet);
-
-  // Return whether all the presshells for this document are safe to flush
-  bool IsSafeToFlush() const;
-
-  void DispatchPageTransition(mozilla::dom::EventTarget* aDispatchTarget,
-                              const nsAString& aType,
-                              bool aPersisted);
-
-  virtual nsPIDOMWindowOuter* GetWindowInternal() const override;
-  virtual nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const override;
-  virtual bool InternalAllowXULXBL() override;
-
-  void UpdateScreenOrientation();
-
-  virtual mozilla::dom::FlashClassification DocumentFlashClassification() override;
-  virtual bool IsThirdParty() override;
-
-#define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_)                        \
-  NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, nsIDocumentObserver, \
-                                           func_, params_);
-
-#ifdef DEBUG
-  void VerifyRootContentState();
-#endif
-
-  explicit nsDocument(const char* aContentType);
-  virtual ~nsDocument();
-
-  void EnsureOnloadBlocker();
-
-  void NotifyStyleSheetApplicableStateChanged();
-
-  // Apply the fullscreen state to the document, and trigger related
-  // events. It returns false if the fullscreen element ready check
-  // fails and nothing gets changed.
-  bool ApplyFullscreen(const FullscreenRequest& aRequest);
-
-  // Retrieves the classification of the Flash plugins in the document based on
-  // the classification lists.
-  mozilla::dom::FlashClassification PrincipalFlashClassification();
-
-  // Attempts to determine the Flash classification of this page based on the
-  // the classification lists and the classification of parent documents.
-  mozilla::dom::FlashClassification ComputeFlashClassification();
-
-  nsTArray<nsIObserver*> mCharSetObservers;
-
-  PLDHashTable *mSubDocuments;
-
-  // Array of owning references to all children
-  nsAttrAndChildArray mChildren;
-
-  // Pointer to our parser if we're currently in the process of being
-  // parsed into.
-  nsCOMPtr<nsIParser> mParser;
-
-  // Weak reference to our sink for in case we no longer have a parser.  This
-  // will allow us to flush out any pending stuff from the sink even if
-  // EndLoad() has already happened.
-  nsWeakPtr mWeakSink;
-
-  nsTArray<RefPtr<mozilla::StyleSheet>> mStyleSheets;
-  nsTArray<RefPtr<mozilla::StyleSheet>> mOnDemandBuiltInUASheets;
-  nsTArray<RefPtr<mozilla::StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
-
-  // Array of observers
-  nsTObserverArray<nsIDocumentObserver*> mObservers;
-
-  // Array of intersection observers
-  nsTHashtable<nsPtrHashKey<mozilla::dom::DOMIntersectionObserver>>
-    mIntersectionObservers;
-
-  // Tracker for animations that are waiting to start.
-  // nullptr until GetOrCreatePendingAnimationTracker is called.
-  RefPtr<mozilla::PendingAnimationTracker> mPendingAnimationTracker;
-
-  // Weak reference to the scope object (aka the script global object)
-  // that, unlike mScriptGlobalObject, is never unset once set. This
-  // is a weak reference to avoid leaks due to circular references.
-  nsWeakPtr mScopeObject;
-
-  // Stack of full-screen elements. When we request full-screen we push the
-  // full-screen element onto this stack, and when we cancel full-screen we
-  // pop one off this stack, restoring the previous full-screen state
-  nsTArray<nsWeakPtr> mFullScreenStack;
-
-  // The root of the doc tree in which this document is in. This is only
-  // non-null when this document is in fullscreen mode.
-  nsWeakPtr mFullscreenRoot;
-
-  mozilla::dom::FlashClassification mFlashClassification;
-  // Do not use this value directly. Call the |IsThirdParty()| method, which
-  // caches its result here.
-  mozilla::Maybe<bool> mIsThirdParty;
-private:
-  void UpdatePossiblyStaleDocumentState();
-  static bool CustomElementConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp);
-
-public:
-  virtual already_AddRefed<mozilla::dom::CustomElementRegistry>
-    GetCustomElementRegistry() override;
-
-  // Check whether web components are enabled for the global of aObject.
-  static bool IsWebComponentsEnabled(JSContext* aCx, JSObject* aObject);
-  // Check whether web components are enabled for the global of the document
-  // this nodeinfo comes from.
-  static bool IsWebComponentsEnabled(mozilla::dom::NodeInfo* aNodeInfo);
-
-  RefPtr<mozilla::EventListenerManager> mListenerManager;
-  RefPtr<mozilla::dom::StyleSheetList> mDOMStyleSheets;
-  RefPtr<nsDOMStyleSheetSetList> mStyleSheetSetList;
-  RefPtr<mozilla::dom::ScriptLoader> mScriptLoader;
-  nsDocHeaderData* mHeaderData;
-  /* mIdentifierMap works as follows for IDs:
-   * 1) Attribute changes affect the table immediately (removing and adding
-   *    entries as needed).
-   * 2) Removals from the DOM affect the table immediately
-   * 3) Additions to the DOM always update existing entries for names, and add
-   *    new ones for IDs.
-   */
-  nsTHashtable<nsIdentifierMapEntry> mIdentifierMap;
-
-  nsClassHashtable<nsStringHashKey, nsRadioGroupStruct> mRadioGroups;
-
-  // Recorded time of change to 'loading' state.
-  mozilla::TimeStamp mLoadingTimeStamp;
-
-  // True if the document has been detached from its content viewer.
-  bool mIsGoingAway:1;
-  // True if the document is being destroyed.
-  bool mInDestructor:1;
-
-  // True if this document has ever had an HTML or SVG <title> element
-  // bound to it
-  bool mMayHaveTitleElement:1;
-
-  bool mHasWarnedAboutBoxObjects:1;
-
-  bool mDelayFrameLoaderInitialization:1;
-
-  bool mSynchronousDOMContentLoaded:1;
-
-  bool mInXBLUpdate:1;
-
-  // Parser aborted. True if the parser of this document was forcibly
-  // terminated instead of letting it finish at its own pace.
-  bool mParserAborted:1;
-
-  friend class nsCallRequestFullScreen;
-
-  // ScreenOrientation "pending promise" as described by
-  // http://www.w3.org/TR/screen-orientation/
-  RefPtr<mozilla::dom::Promise> mOrientationPendingPromise;
-
-  uint16_t mCurrentOrientationAngle;
-  mozilla::dom::OrientationType mCurrentOrientationType;
-
-  // Keeps track of whether we have a pending
-  // 'style-sheet-applicable-state-changed' notification.
-  bool mSSApplicableStateNotificationPending:1;
-
-  // Whether we have reported use counters for this document with Telemetry yet.
-  // Normally this is only done at document destruction time, but for image
-  // documents (SVG documents) that are not guaranteed to be destroyed, we
-  // report use counters when the image cache no longer has any imgRequestProxys
-  // pointing to them.  We track whether we ever reported use counters so
-  // that we only report them once for the document.
-  bool mReportedUseCounters:1;
-
-  // Whether we have filled our pres shell's style set with the document's
-  // additional sheets and sheets from the nsStyleSheetService.
-  bool mStyleSetFilled:1;
-
-  uint8_t mPendingFullscreenRequests;
-
-  uint8_t mXMLDeclarationBits;
-
-  nsInterfaceHashtable<nsPtrHashKey<nsIContent>, nsPIBoxObject> *mBoxObjectTable;
-
-  // A document "without a browsing context" that owns the content of
-  // HTMLTemplateElement.
-  nsCOMPtr<nsIDocument> mTemplateContentsOwner;
-
-  // Our update nesting level
-  uint32_t mUpdateNestLevel;
-
-  // The application cache that this document is associated with, if
-  // any.  This can change during the lifetime of the document.
-  nsCOMPtr<nsIApplicationCache> mApplicationCache;
-
-  nsCOMPtr<nsIContent> mFirstBaseNodeWithHref;
-
-  mozilla::EventStates mDocumentState;
-  mozilla::EventStates mGotDocumentState;
-
-  RefPtr<nsDOMNavigationTiming> mTiming;
-private:
-  friend class nsUnblockOnloadEvent;
-  // Recomputes the visibility state but doesn't set the new value.
-  mozilla::dom::VisibilityState GetVisibilityState() const;
-  void NotifyStyleSheetAdded(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
-  void NotifyStyleSheetRemoved(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
-
-  void PostUnblockOnloadEvent();
-  void DoUnblockOnload();
-
-  nsresult InitCSP(nsIChannel* aChannel);
-
-  /**
-   * Find the (non-anonymous) content in this document for aFrame. It will
-   * be aFrame's content node if that content is in this document and not
-   * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
-   * element containing the subdocument containing aFrame, and/or find the
-   * nearest non-anonymous ancestor in this document.
-   * Returns null if there is no such element.
-   */
-  nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
-
-  // Just like EnableStyleSheetsForSet, but doesn't check whether
-  // aSheetSet is null and allows the caller to control whether to set
-  // aSheetSet as the preferred set in the CSSLoader.
-  void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
-                                       bool aUpdateCSSLoader);
-
-  void ClearAllBoxObjects();
-
-  // Returns true if the scheme for the url for this document is "about"
-  bool IsAboutPage() const;
-
-  // These are not implemented and not supported.
-  nsDocument(const nsDocument& aOther);
-  nsDocument& operator=(const nsDocument& aOther);
-
-  // The layout history state that should be used by nodes in this
-  // document.  We only actually store a pointer to it when:
-  // 1)  We have no script global object.
-  // 2)  We haven't had Destroy() called on us yet.
-  nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
-
-  // Currently active onload blockers
-  uint32_t mOnloadBlockCount;
-  // Onload blockers which haven't been activated yet
-  uint32_t mAsyncOnloadBlockCount;
-  nsCOMPtr<nsIRequest> mOnloadBlocker;
-
-  // A hashtable of styled links keyed by address pointer.
-  nsTHashtable<nsPtrHashKey<mozilla::dom::Link> > mStyledLinks;
-#ifdef DEBUG
-  // Indicates whether mStyledLinks was cleared or not.  This is used to track
-  // state so we can provide useful assertions to consumers of ForgetLink and
-  // AddStyleRelevantLink.
-  bool mStyledLinksCleared;
-#endif
-
-  // A set of responsive images keyed by address pointer.
-  nsTHashtable< nsPtrHashKey<nsIContent> > mResponsiveContent;
-
-  // Member to store out last-selected stylesheet set.
-  nsString mLastStyleSheetSet;
-
-  nsTArray<RefPtr<nsFrameLoader> > mInitializableFrameLoaders;
-  nsTArray<nsCOMPtr<nsIRunnable> > mFrameLoaderFinalizers;
-  RefPtr<nsRunnableMethod<nsDocument> > mFrameLoaderRunner;
-
-  nsCOMPtr<nsIRunnable> mMaybeEndOutermostXBLUpdateRunner;
-
-  nsRevocableEventPtr<nsRunnableMethod<nsDocument, void, false> >
-    mPendingTitleChangeEvent;
-
-  nsExternalResourceMap mExternalResourceMap;
-
-  // All images in process of being preloaded.  This is a hashtable so
-  // we can remove them as the real image loads start; that way we
-  // make sure to not keep the image load going when no one cares
-  // about it anymore.
-  nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
-
-  // A list of preconnects initiated by the preloader. This prevents
-  // the same uri from being used more than once, and allows the dom
-  // builder to not repeat the work of the preloader.
-  nsDataHashtable< nsURIHashKey, bool> mPreloadedPreconnects;
-
-  // Current depth of picture elements from parser
-  int32_t mPreloadPictureDepth;
-
-  // Set if we've found a URL for the current picture
-  nsString mPreloadPictureFoundSource;
-
-  RefPtr<mozilla::dom::DOMImplementation> mDOMImplementation;
-
-  RefPtr<nsContentList> mImageMaps;
-
-  nsCString mScrollToRef;
-  uint8_t mScrolledToRefAlready : 1;
-  uint8_t mChangeScrollPosWhenScrollingToRef : 1;
-
-  // Tracking for plugins in the document.
-  nsTHashtable< nsPtrHashKey<nsIObjectLoadingContent> > mPlugins;
-
-  RefPtr<mozilla::dom::DocumentTimeline> mDocumentTimeline;
-  mozilla::LinkedList<mozilla::dom::DocumentTimeline> mTimelines;
-
-  enum ViewportType {
-    DisplayWidthHeight,
-    Specified,
-    Unknown
-  };
-
-  ViewportType mViewportType;
-
-  // These member variables cache information about the viewport so we don't have to
-  // recalculate it each time.
-  bool mValidWidth, mValidHeight;
-  mozilla::LayoutDeviceToScreenScale mScaleMinFloat;
-  mozilla::LayoutDeviceToScreenScale mScaleMaxFloat;
-  mozilla::LayoutDeviceToScreenScale mScaleFloat;
-  mozilla::CSSToLayoutDeviceScale mPixelRatio;
-  bool mAutoSize, mAllowZoom, mAllowDoubleTapZoom, mValidScaleFloat, mValidMaxScale, mScaleStrEmpty, mWidthStrEmpty;
-  mozilla::CSSSize mViewportSize;
-
-  nsrefcnt mStackRefCnt;
-  bool mNeedsReleaseAfterStackRefCntRelease;
-
-  // Set to true when the document is possibly controlled by the ServiceWorker.
-  // Used to prevent multiple requests to ServiceWorkerManager.
-  bool mMaybeServiceWorkerControlled;
-
-  // We lazily calculate declaration blocks for SVG elements
-  // with mapped attributes in Servo mode. This list contains all elements which
-  // need lazy resolution
-  nsTHashtable<nsPtrHashKey<nsSVGElement>> mLazySVGPresElements;
-
-#ifdef DEBUG
-public:
-  bool mWillReparent;
-#endif
-};
-
-class nsDocumentOnStack
-{
-public:
-  explicit nsDocumentOnStack(nsDocument* aDoc) : mDoc(aDoc)
-  {
-    mDoc->IncreaseStackRefCnt();
-  }
-  ~nsDocumentOnStack()
-  {
-    mDoc->DecreaseStackRefCnt();
-  }
-private:
-  nsDocument* mDoc;
-};
-
-#endif /* nsDocument_h___ */
+#endif // #ifndef nsIdentifierMapEntry_h
--- a/dom/html/HTMLInputElement.cpp
+++ b/dom/html/HTMLInputElement.cpp
@@ -2615,17 +2615,17 @@ HTMLInputElement::SetUserInput(const nsA
   return NS_OK;
 }
 
 nsIEditor*
 HTMLInputElement::GetEditor()
 {
   nsTextEditorState* state = GetEditorState();
   if (state) {
-    return state->GetEditor();
+    return state->GetTextEditor();
   }
   return nullptr;
 }
 
 NS_IMETHODIMP_(nsIEditor*)
 HTMLInputElement::GetTextEditor()
 {
   return GetEditor();
--- a/dom/html/HTMLTextAreaElement.h
+++ b/dom/html/HTMLTextAreaElement.h
@@ -296,17 +296,17 @@ public:
   Nullable<uint32_t> GetSelectionEnd(ErrorResult& aError);
   void SetSelectionEnd(const Nullable<uint32_t>& aSelectionEnd, ErrorResult& aError);
   void GetSelectionDirection(nsAString& aDirection, ErrorResult& aError);
   void SetSelectionDirection(const nsAString& aDirection, ErrorResult& aError);
   void SetSelectionRange(uint32_t aSelectionStart, uint32_t aSelectionEnd, const Optional<nsAString>& aDirecton, ErrorResult& aError);
   nsIControllers* GetControllers(ErrorResult& aError);
   nsIEditor* GetEditor()
   {
-    return mState.GetEditor();
+    return mState.GetTextEditor();
   }
 
 protected:
   virtual ~HTMLTextAreaElement() {}
 
   // get rid of the compiler warning
   using nsGenericHTMLFormElementWithState::IsSingleLineTextControl;
 
--- a/dom/html/nsTextEditorState.cpp
+++ b/dom/html/nsTextEditorState.cpp
@@ -8,17 +8,16 @@
 
 #include "nsCOMPtr.h"
 #include "nsIPresShell.h"
 #include "nsView.h"
 #include "nsCaret.h"
 #include "nsEditorCID.h"
 #include "nsLayoutCID.h"
 #include "nsITextControlFrame.h" 
-#include "nsIPlaintextEditor.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsTextControlFrame.h"
 #include "nsIControllers.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsITransactionManager.h"
@@ -28,17 +27,16 @@
 #include "nsGenericHTMLElement.h"
 #include "nsIDOMEventListener.h"
 #include "nsIEditorObserver.h"
 #include "nsIWidget.h"
 #include "nsIDocumentEncoder.h"
 #include "nsISelectionPrivate.h"
 #include "nsPIDOMWindow.h"
 #include "nsServiceManagerUtils.h"
-#include "nsIEditor.h"
 #include "mozilla/dom/Selection.h"
 #include "mozilla/TextEditRules.h"
 #include "mozilla/EventListenerManager.h"
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsTextNode.h"
 #include "nsIController.h"
 #include "mozilla/AutoRestore.h"
@@ -55,37 +53,36 @@ using namespace mozilla;
 using namespace mozilla::dom;
 using mozilla::layers::ScrollInputMethod;
 
 static NS_DEFINE_CID(kTextEditorCID, NS_TEXTEDITOR_CID);
 
 class MOZ_STACK_CLASS ValueSetter
 {
 public:
-  explicit ValueSetter(nsIEditor* aEditor)
-    : mEditor(aEditor)
-  {
-    MOZ_ASSERT(aEditor);
-  
+  explicit ValueSetter(TextEditor* aTextEditor)
+    : mTextEditor(aTextEditor)
     // To protect against a reentrant call to SetValue, we check whether
     // another SetValue is already happening for this editor.  If it is,
     // we must wait until we unwind to re-enable oninput events.
-    mEditor->GetSuppressDispatchingInputEvent(&mOuterTransaction);
+    , mOuterTransaction(aTextEditor->IsSuppressingDispatchingInputEvent())
+  {
+    MOZ_ASSERT(aTextEditor);
   }
   ~ValueSetter()
   {
-    mEditor->SetSuppressDispatchingInputEvent(mOuterTransaction);
+    mTextEditor->SetSuppressDispatchingInputEvent(mOuterTransaction);
   }
   void Init()
   {
-    mEditor->SetSuppressDispatchingInputEvent(true);
+    mTextEditor->SetSuppressDispatchingInputEvent(true);
   }
 
 private:
-  nsCOMPtr<nsIEditor> mEditor;
+  RefPtr<TextEditor> mTextEditor;
   bool mOuterTransaction;
 };
 
 class RestoreSelectionState : public Runnable {
 public:
   RestoreSelectionState(nsTextEditorState *aState, nsTextControlFrame *aFrame)
     : mFrame(aFrame),
       mTextEditorState(aState)
@@ -132,77 +129,72 @@ public:
 private:
   nsTextControlFrame* mFrame;
   nsTextEditorState* mTextEditorState;
 };
 
 class MOZ_RAII AutoRestoreEditorState final
 {
 public:
-  explicit AutoRestoreEditorState(nsIEditor* aEditor,
-                                  nsIPlaintextEditor* aPlaintextEditor
+  explicit AutoRestoreEditorState(TextEditor* aTextEditor
                                   MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-    : mEditor(aEditor)
-    , mPlaintextEditor(aPlaintextEditor)
+    : mTextEditor(aTextEditor)
+    , mSavedFlags(mTextEditor->Flags())
+    , mSavedMaxLength(mTextEditor->MaxTextLength())
   {
     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-    MOZ_ASSERT(mEditor);
-    MOZ_ASSERT(mPlaintextEditor);
-
-    uint32_t flags;
-    mEditor->GetFlags(&mSavedFlags);
-    flags = mSavedFlags;
+    MOZ_ASSERT(mTextEditor);
+
+    uint32_t flags = mSavedFlags;
     flags &= ~(nsIPlaintextEditor::eEditorDisabledMask);
     flags &= ~(nsIPlaintextEditor::eEditorReadonlyMask);
     flags |= nsIPlaintextEditor::eEditorDontEchoPassword;
-    mEditor->SetFlags(flags);
-
-    mPlaintextEditor->GetMaxTextLength(&mSavedMaxLength);
-    mPlaintextEditor->SetMaxTextLength(-1);
+    mTextEditor->SetFlags(flags);
+
+    mTextEditor->SetMaxTextLength(-1);
   }
 
   ~AutoRestoreEditorState()
   {
-     mPlaintextEditor->SetMaxTextLength(mSavedMaxLength);
-     mEditor->SetFlags(mSavedFlags);
+     mTextEditor->SetMaxTextLength(mSavedMaxLength);
+     mTextEditor->SetFlags(mSavedFlags);
   }
 
 private:
-  nsIEditor* mEditor;
-  nsIPlaintextEditor* mPlaintextEditor;
+  TextEditor* mTextEditor;
   uint32_t mSavedFlags;
   int32_t mSavedMaxLength;
   MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 class MOZ_RAII AutoDisableUndo final
 {
 public:
-  explicit AutoDisableUndo(nsIEditor* aEditor
+  explicit AutoDisableUndo(TextEditor* aTextEditor
                            MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-    : mEditor(aEditor)
+    : mTextEditor(aTextEditor)
     , mPreviousEnabled(true)
   {
     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-    MOZ_ASSERT(mEditor);
+    MOZ_ASSERT(mTextEditor);
 
     bool canUndo;
-    DebugOnly<nsresult> rv = mEditor->CanUndo(&mPreviousEnabled, &canUndo);
+    DebugOnly<nsresult> rv = mTextEditor->CanUndo(&mPreviousEnabled, &canUndo);
     MOZ_ASSERT(NS_SUCCEEDED(rv));
 
-    mEditor->EnableUndo(false);
+    mTextEditor->EnableUndo(false);
   }
 
   ~AutoDisableUndo()
   {
-    mEditor->EnableUndo(mPreviousEnabled);
+    mTextEditor->EnableUndo(mPreviousEnabled);
   }
 
 private:
-  nsIEditor* mEditor;
+  TextEditor* mTextEditor;
   bool mPreviousEnabled;
   MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 /*static*/
 bool
 nsITextControlElement::GetWrapPropertyEnum(nsIContent* aContent,
   nsITextControlElement::nsHTMLTextWrap& aWrapProp)
@@ -1188,61 +1180,61 @@ void
 nsTextEditorState::Clear()
 {
   if (mBoundFrame) {
     // Oops, we still have a frame!
     // This should happen when the type of a text input control is being changed
     // to something which is not a text control.  In this case, we should pretend
     // that a frame is being destroyed, and clean up after ourselves properly.
     UnbindFromFrame(mBoundFrame);
-    mEditor = nullptr;
+    mTextEditor = nullptr;
   } else {
     // If we have a bound frame around, UnbindFromFrame will call DestroyEditor
     // for us.
     DestroyEditor();
   }
   mTextListener = nullptr;
 }
 
 void nsTextEditorState::Unlink()
 {
   nsTextEditorState* tmp = this;
   tmp->Clear();
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelCon)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mEditor)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTextEditor)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mRootNode)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mPlaceholderDiv)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mPreviewDiv)
 }
 
 void nsTextEditorState::Traverse(nsCycleCollectionTraversalCallback& cb)
 {
   nsTextEditorState* tmp = this;
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelCon)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEditor)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTextEditor)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRootNode)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPlaceholderDiv)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPreviewDiv)
 }
 
 nsFrameSelection*
 nsTextEditorState::GetConstFrameSelection() {
   if (mSelCon)
     return mSelCon->GetConstFrameSelection();
   return nullptr;
 }
 
-nsIEditor*
-nsTextEditorState::GetEditor()
+TextEditor*
+nsTextEditorState::GetTextEditor()
 {
-  if (!mEditor) {
+  if (!mTextEditor) {
     nsresult rv = PrepareEditor();
     NS_ENSURE_SUCCESS(rv, nullptr);
   }
-  return mEditor;
+  return mTextEditor;
 }
 
 nsISelectionController*
 nsTextEditorState::GetSelectionController() const
 {
   return mSelCon;
 }
 
@@ -1290,17 +1282,17 @@ nsTextEditorState::BindToFrame(nsTextCon
   NS_ENSURE_ARG_POINTER(aFrame);
 
   NS_ASSERTION(!mBoundFrame, "Cannot bind twice, need to unbind first");
   NS_ENSURE_TRUE(!mBoundFrame, NS_ERROR_FAILURE);
 
   // If we'll need to transfer our current value to the editor, save it before
   // binding to the frame.
   nsAutoString currentValue;
-  if (mEditor) {
+  if (mTextEditor) {
     GetValue(currentValue, true);
   }
 
   mBoundFrame = aFrame;
 
   nsresult rv = CreateRootNode();
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1337,57 +1329,51 @@ nsTextEditorState::BindToFrame(nsTextCon
       }
     }
 
     selPriv->AddSelectionListener(static_cast<nsISelectionListener*>
                                              (mTextListener));
   }
 
   // If an editor exists from before, prepare it for usage
-  if (mEditor) {
+  if (mTextEditor) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(mTextCtrlElement);
     NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
 
     // Set the correct direction on the newly created root node
-    uint32_t flags;
-    nsresult rv = mEditor->GetFlags(&flags);
-    NS_ENSURE_SUCCESS(rv, rv);
-    if (flags & nsIPlaintextEditor::eEditorRightToLeft) {
+    if (mTextEditor->IsRightToLeft()) {
       rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("rtl"), false);
-    } else if (flags & nsIPlaintextEditor::eEditorLeftToRight) {
+    } else if (mTextEditor->IsLeftToRight()) {
       rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, NS_LITERAL_STRING("ltr"), false);
     } else {
       // otherwise, inherit the content node's direction
     }
 
     nsContentUtils::AddScriptRunner(
       new PrepareEditorEvent(*this, content, currentValue));
   }
 
   return NS_OK;
 }
 
 struct PreDestroyer
 {
-  void Init(nsIEditor* aEditor)
-  {
-    mNewEditor = aEditor;
-  }
+  void Init(TextEditor* aTextEditor) { mTextEditor = aTextEditor; }
   ~PreDestroyer()
   {
-    if (mNewEditor) {
-      mNewEditor->PreDestroy(true);
+    if (mTextEditor) {
+      mTextEditor->PreDestroy(true);
     }
   }
-  void Swap(nsCOMPtr<nsIEditor>& aEditor)
+  void Swap(RefPtr<TextEditor>& aTextEditor)
   {
-    return mNewEditor.swap(aEditor);
+    return mTextEditor.swap(aTextEditor);
   }
 private:
-  nsCOMPtr<nsIEditor> mNewEditor;
+  RefPtr<TextEditor> mTextEditor;
 };
 
 nsresult
 nsTextEditorState::PrepareEditor(const nsAString *aValue)
 {
   if (!mBoundFrame) {
     // Cannot create an editor without a bound frame.
     // Don't return a failure code, because js callers can't handle that.
@@ -1402,19 +1388,19 @@ nsTextEditorState::PrepareEditor(const n
   AutoHideSelectionChanges hideSelectionChanges(GetConstFrameSelection());
 
   // Don't attempt to initialize recursively!
   InitializationGuard guard(*this);
   if (guard.IsInitializingRecursively()) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
-  // Note that we don't check mEditor here, because we might already have one
-  // around, in which case we don't create a new one, and we'll just tie the
-  // required machinery to it.
+  // Note that we don't check mTextEditor here, because we might already have
+  // one around, in which case we don't create a new one, and we'll just tie
+  // the required machinery to it.
 
   nsPresContext *presContext = mBoundFrame->PresContext();
   nsIPresShell *shell = presContext->GetPresShell();
 
   // Setup the editor flags
   uint32_t editorFlags = 0;
   if (IsPlainTextControl())
     editorFlags |= nsIPlaintextEditor::eEditorPlaintextMask;
@@ -1426,49 +1412,46 @@ nsTextEditorState::PrepareEditor(const n
   // All nsTextControlFrames are widgets
   editorFlags |= nsIPlaintextEditor::eEditorWidgetMask;
 
   // Spell check is diabled at creation time. It is enabled once
   // the editor comes into focus.
   editorFlags |= nsIPlaintextEditor::eEditorSkipSpellCheck;
 
   bool shouldInitializeEditor = false;
-  nsCOMPtr<nsIEditor> newEditor; // the editor that we might create
+  RefPtr<TextEditor> newTextEditor; // the editor that we might create
   nsresult rv = NS_OK;
   PreDestroyer preDestroyer;
-  if (!mEditor) {
+  if (!mTextEditor) {
     shouldInitializeEditor = true;
 
     // Create an editor
-    newEditor = do_CreateInstance(kTextEditorCID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-    preDestroyer.Init(newEditor);
+    newTextEditor = new TextEditor();
+    preDestroyer.Init(newTextEditor);
 
     // Make sure we clear out the non-breaking space before we initialize the editor
     rv = mBoundFrame->UpdateValueDisplay(true, true);
     NS_ENSURE_SUCCESS(rv, rv);
   } else {
     if (aValue || !mEditorInitialized) {
       // Set the correct value in the root node
       rv = mBoundFrame->UpdateValueDisplay(true, !mEditorInitialized, aValue);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
-    newEditor = mEditor; // just pretend that we have a new editor!
+    newTextEditor = mTextEditor; // just pretend that we have a new editor!
 
     // Don't lose application flags in the process.
-    uint32_t originalFlags = 0;
-    newEditor->GetFlags(&originalFlags);
-    if (originalFlags & nsIPlaintextEditor::eEditorMailMask) {
+    if (newTextEditor->IsMailEditor()) {
       editorFlags |= nsIPlaintextEditor::eEditorMailMask;
     }
   }
 
   // Get the current value of the textfield from the content.
-  // Note that if we've created a new editor, mEditor is null at this stage,
+  // Note that if we've created a new editor, mTextEditor is null at this stage,
   // so we will get the real value from the content.
   nsAutoString defaultValue;
   if (aValue) {
     defaultValue = *aValue;
   } else {
     GetValue(defaultValue, true);
   }
 
@@ -1487,18 +1470,18 @@ nsTextEditorState::PrepareEditor(const n
     // for its content manipulations, and it causes it to fail some security
     // checks deep inside when initializing. So we explictly make it clear that
     // we're native code.
     // Note that any script that's directly trying to access our value
     // has to be going through some scriptable object to do that and that
     // already does the relevant security checks.
     AutoNoJSAPI nojsapi;
 
-    rv = newEditor->Init(domdoc, GetRootNode(), mSelCon, editorFlags,
-                         defaultValue);
+    rv = newTextEditor->Init(domdoc, GetRootNode(), mSelCon, editorFlags,
+                             defaultValue);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Initialize the controller for the editor
 
   if (!SuppressEventHandlers(presContext)) {
     nsCOMPtr<nsIControllers> controllers;
     nsCOMPtr<nsIDOMHTMLInputElement> inputElement =
@@ -1523,110 +1506,111 @@ nsTextEditorState::PrepareEditor(const n
       rv = controllers->GetControllerCount(&numControllers);
       for (uint32_t i = 0; i < numControllers; i ++) {
         nsCOMPtr<nsIController> controller;
         rv = controllers->GetControllerAt(i, getter_AddRefs(controller));
         if (NS_SUCCEEDED(rv) && controller) {
           nsCOMPtr<nsIControllerContext> editController =
             do_QueryInterface(controller);
           if (editController) {
-            editController->SetCommandContext(newEditor);
+            editController->SetCommandContext(
+              static_cast<nsIEditor*>(newTextEditor));
             found = true;
           }
         }
       }
       if (!found)
         rv = NS_ERROR_FAILURE;
     }
   }
 
   // Initialize the plaintext editor
-  nsCOMPtr<nsIPlaintextEditor> textEditor = do_QueryInterface(newEditor);
-  if (textEditor) {
-    if (shouldInitializeEditor) {
-      // Set up wrapping
-      textEditor->SetWrapColumn(GetWrapCols());
-    }
-
-    // Set max text field length
-    textEditor->SetMaxTextLength(GetMaxLength());
+  if (shouldInitializeEditor) {
+    // Set up wrapping
+    newTextEditor->SetWrapColumn(GetWrapCols());
   }
 
+  // Set max text field length
+  newTextEditor->SetMaxTextLength(GetMaxLength());
+
   nsCOMPtr<nsIContent> content = do_QueryInterface(mTextCtrlElement);
   if (content) {
-    rv = newEditor->GetFlags(&editorFlags);
-    NS_ENSURE_SUCCESS(rv, rv);
+    editorFlags = newTextEditor->Flags();
 
     // Check if the readonly attribute is set.
     if (content->HasAttr(kNameSpaceID_None, nsGkAtoms::readonly))
       editorFlags |= nsIPlaintextEditor::eEditorReadonlyMask;
 
     // Check if the disabled attribute is set.
     // TODO: call IsDisabled() here!
     if (content->HasAttr(kNameSpaceID_None, nsGkAtoms::disabled)) 
       editorFlags |= nsIPlaintextEditor::eEditorDisabledMask;
 
     // Disable the selection if necessary.
     if (editorFlags & nsIPlaintextEditor::eEditorDisabledMask)
       mSelCon->SetDisplaySelection(nsISelectionController::SELECTION_OFF);
 
-    newEditor->SetFlags(editorFlags);
+    newTextEditor->SetFlags(editorFlags);
   }
 
   if (shouldInitializeEditor) {
     // Hold on to the newly created editor
-    preDestroyer.Swap(mEditor);
+    preDestroyer.Swap(mTextEditor);
   }
 
   // If we have a default value, insert it under the div we created
   // above, but be sure to use the editor so that '*' characters get
   // displayed for password fields, etc. SetValue() will call the
   // editor for us.
 
   if (!defaultValue.IsEmpty()) {
-    rv = newEditor->SetFlags(editorFlags);
+    rv = newTextEditor->SetFlags(editorFlags);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Now call SetValue() which will make the necessary editor calls to set
     // the default value.  Make sure to turn off undo before setting the default
     // value, and turn it back on afterwards. This will make sure we can't undo
     // past the default value.
     // So, we use eSetValue_Internal flag only that it will turn off undo.
 
     bool success = SetValue(defaultValue, eSetValue_Internal);
     NS_ENSURE_TRUE(success, NS_ERROR_OUT_OF_MEMORY);
 
     // Now restore the original editor flags.
-    rv = newEditor->SetFlags(editorFlags);
+    rv = newTextEditor->SetFlags(editorFlags);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  nsCOMPtr<nsITransactionManager> transMgr;
-  newEditor->GetTransactionManager(getter_AddRefs(transMgr));
-  NS_ENSURE_TRUE(transMgr, NS_ERROR_FAILURE);
-
-  transMgr->SetMaxTransactionCount(nsITextControlElement::DEFAULT_UNDO_CAP);
+  nsCOMPtr<nsITransactionManager> transactionManager =
+    newTextEditor->GetTransactionManager();
+  if (NS_WARN_IF(!transactionManager)) {
+    return NS_ERROR_FAILURE;
+  }
+
+  transactionManager->SetMaxTransactionCount(
+                        nsITextControlElement::DEFAULT_UNDO_CAP);
 
   if (IsPasswordTextControl()) {
     // Disable undo for password textfields.  Note that we want to do this at
     // the very end of InitEditor, so the calls to EnableUndo when setting the
     // default value don't screw us up.
     // Since changing the control type does a reframe, we don't have to worry
     // about dynamic type changes here.
-    newEditor->EnableUndo(false);
+    newTextEditor->EnableUndo(false);
   }
 
   if (!mEditorInitialized) {
-    newEditor->PostCreate();
+    newTextEditor->PostCreate();
     mEverInited = true;
     mEditorInitialized = true;
   }
 
-  if (mTextListener)
-    newEditor->AddEditorObserver(mTextListener);
+  if (mTextListener) {
+    newTextEditor->AddEditorObserver(mTextListener);
+  }
 
   // Restore our selection after being bound to a new frame
   HTMLInputElement* number = GetParentNumberControl(mBoundFrame);
   if (number ? number->IsSelectionCached() : mSelectionCached) {
     if (mRestoringSelection) // paranoia
       mRestoringSelection->Revoke();
     mRestoringSelection = new RestoreSelectionState(this, mBoundFrame);
     if (mRestoringSelection) {
@@ -2085,20 +2069,20 @@ nsTextEditorState::GetParentNumberContro
   return nullptr;
 }
 
 void
 nsTextEditorState::DestroyEditor()
 {
   // notify the editor that we are going away
   if (mEditorInitialized) {
-    if (mTextListener)
-      mEditor->RemoveEditorObserver(mTextListener);
-
-    mEditor->PreDestroy(true);
+    if (mTextListener) {
+      mTextEditor->RemoveEditorObserver(mTextListener);
+    }
+    mTextEditor->PreDestroy(true);
     mEditorInitialized = false;
   }
   ClearValueCache();
 }
 
 void
 nsTextEditorState::UnbindFromFrame(nsTextControlFrame* aFrame)
 {
@@ -2106,20 +2090,18 @@ nsTextEditorState::UnbindFromFrame(nsTex
 
   // If it was, however, it should be unbounded from the same frame.
   NS_ASSERTION(!aFrame || aFrame == mBoundFrame, "Unbinding from the wrong frame");
   NS_ENSURE_TRUE_VOID(!aFrame || aFrame == mBoundFrame);
 
   // If the editor is modified but nsIEditorObserver::EditAction() hasn't been
   // called yet, we need to notify it here because editor may be destroyed
   // before EditAction() is called if selection listener causes flushing layout.
-  bool isInEditAction = false;
-  if (mTextListener && mEditor && mEditorInitialized &&
-      NS_SUCCEEDED(mEditor->GetIsInEditAction(&isInEditAction)) &&
-      isInEditAction) {
+  if (mTextListener && mTextEditor && mEditorInitialized &&
+      mTextEditor->IsInEditAction()) {
     mTextListener->EditAction();
   }
 
   // We need to start storing the value outside of the editor if we're not
   // going to use it anymore, so retrieve it for now.
   nsAutoString value;
   GetValue(value, true);
 
@@ -2426,17 +2408,18 @@ nsTextEditorState::GetValue(nsAString& a
   // IME, GetValue() may be called for appending text or something.  Then, we
   // need to return the latest aValue of SetValue() since the value hasn't
   // been set to the editor yet.
   if (mIsCommittingComposition) {
     aValue = mValueBeingSet;
     return;
   }
 
-  if (mEditor && mBoundFrame && (mEditorInitialized || !IsSingleLineTextControl())) {
+  if (mTextEditor && mBoundFrame &&
+      (mEditorInitialized || !IsSingleLineTextControl())) {
     bool canCache = aIgnoreWrap && !IsSingleLineTextControl();
     if (canCache && !mCachedValue.IsEmpty()) {
       aValue = mCachedValue;
       return;
     }
 
     aValue.Truncate(); // initialize out param
 
@@ -2469,18 +2452,18 @@ nsTextEditorState::GetValue(nsAString& a
     // has to be going through some scriptable object to do that and that
     // already does the relevant security checks.
     // XXXbz if we could just get the textContent of our anonymous content (eg
     // if plaintext editor didn't create <br> nodes all over), we wouldn't need
     // this.
     { /* Scope for AutoNoJSAPI. */
       AutoNoJSAPI nojsapi;
 
-      mEditor->OutputToString(NS_LITERAL_STRING("text/plain"), flags,
-                              aValue);
+      mTextEditor->OutputToString(NS_LITERAL_STRING("text/plain"), flags,
+                                  aValue);
     }
     if (canCache) {
       mCachedValue = aValue;
     } else {
       mCachedValue.Truncate();
     }
   } else {
     if (!mTextCtrlElement->ValueChanged() || !mValue) {
@@ -2558,17 +2541,18 @@ nsTextEditorState::SetValue(const nsAStr
       //       forcibly committing composition.
       if (nsContentUtils::IsSafeToRunScript()) {
         WeakPtr<nsTextEditorState> self(this);
         // WARNING: During this call, compositionupdate, compositionend, input
         // events will be fired.  Therefore, everything can occur.  E.g., the
         // document may be unloaded.
         mValueBeingSet = aValue;
         mIsCommittingComposition = true;
-        nsresult rv = mEditor->ForceCompositionEnd();
+        RefPtr<TextEditor> textEditor = mTextEditor;
+        nsresult rv = textEditor->ForceCompositionEnd();
         if (!self.get()) {
           return true;
         }
         mIsCommittingComposition = false;
         // If this is called recursively during committing composition and
         // some of them may be skipped above.  Therefore, we need to set
         // value to the editor with the aValue of the latest call.
         newValue = mValueBeingSet;
@@ -2587,17 +2571,17 @@ nsTextEditorState::SetValue(const nsAStr
   }
 
   // \r is an illegal character in the dom, but people use them,
   // so convert windows and mac platform linebreaks to \n:
   if (!nsContentUtils::PlatformToDOMLineBreaks(newValue, fallible)) {
     return false;
   }
 
-  if (mEditor && mBoundFrame) {
+  if (mTextEditor && mBoundFrame) {
     // The InsertText call below might flush pending notifications, which
     // could lead into a scheduled PrepareEditor to be called.  That will
     // lead to crashes (or worse) because we'd be initializing the editor
     // before InsertText returns.  This script blocker makes sure that
     // PrepareEditor cannot be called prematurely.
     nsAutoScriptBlocker scriptBlocker;
 
 #ifdef DEBUG
@@ -2616,51 +2600,47 @@ nsTextEditorState::SetValue(const nsAStr
       currentValue.Assign(*aOldValue);
     } else {
       mBoundFrame->GetText(currentValue);
     }
 
     AutoWeakFrame weakFrame(mBoundFrame);
 
     // this is necessary to avoid infinite recursion
-    if (!currentValue.Equals(newValue))
-    {
-      ValueSetter valueSetter(mEditor);
-
-      nsCOMPtr<nsIDOMDocument> domDoc;
-      mEditor->GetDocument(getter_AddRefs(domDoc));
-      if (!domDoc) {
-        NS_WARNING("Why don't we have a document?");
+    if (!currentValue.Equals(newValue)) {
+      RefPtr<TextEditor> textEditor = mTextEditor;
+      ValueSetter valueSetter(textEditor);
+
+      nsCOMPtr<nsIDocument> document = textEditor->GetDocument();
+      if (NS_WARN_IF(!document)) {
         return true;
       }
 
       // Time to mess with our security context... See comments in GetValue()
       // for why this is needed.  Note that we have to do this up here, because
       // otherwise SelectAll() will fail.
       {
         AutoNoJSAPI nojsapi;
 
         nsCOMPtr<nsISelection> domSel;
         mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                               getter_AddRefs(domSel));
         SelectionBatcher selectionBatcher(domSel ? domSel->AsSelection() :
                                                    nullptr);
 
-        nsCOMPtr<nsIPlaintextEditor> plaintextEditor = do_QueryInterface(mEditor);
-        if (!plaintextEditor || !weakFrame.IsAlive()) {
-          NS_WARNING("Somehow not a plaintext editor?");
+        if (NS_WARN_IF(!weakFrame.IsAlive())) {
           return true;
         }
 
         valueSetter.Init();
 
         // get the flags, remove readonly, disabled and max-length,
         // set the value, restore flags
         {
-          AutoRestoreEditorState restoreState(mEditor, plaintextEditor);
+          AutoRestoreEditorState restoreState(textEditor);
 
           mTextListener->SettingValue(true);
           bool notifyValueChanged = !!(aFlags & eSetValue_Notify);
           mTextListener->SetValueChanged(notifyValueChanged);
 
           if (aFlags & eSetValue_BySetUserInput) {
             nsCOMPtr<nsISelectionController> kungFuDeathGrip = mSelCon.get();
             uint32_t currentLength = currentValue.Length();
@@ -2673,29 +2653,29 @@ nsTextEditorState::SetValue(const nsAStr
             } else {
               // Collapse selection to the end so that we can append data.
               mBoundFrame->SelectAllOrCollapseToEndOfText(false);
             }
             const nsAString& insertValue =
               StringTail(newValue, newlength - currentLength);
 
             if (insertValue.IsEmpty()) {
-              mEditor->DeleteSelection(nsIEditor::eNone, nsIEditor::eStrip);
+              textEditor->DeleteSelection(nsIEditor::eNone, nsIEditor::eStrip);
             } else {
-              plaintextEditor->InsertText(insertValue);
+              textEditor->InsertText(insertValue);
             }
           } else {
-            AutoDisableUndo disableUndo(mEditor);
+            AutoDisableUndo disableUndo(textEditor);
             if (domSel) {
               // Since we don't use undo transaction, we don't need to store
               // selection state.  SetText will set selection to tail.
               domSel->RemoveAllRanges();
             }
 
-            plaintextEditor->SetText(newValue);
+            textEditor->SetText(newValue);
           }
 
           mTextListener->SetValueChanged(true);
           mTextListener->SettingValue(false);
 
           if (!notifyValueChanged) {
             // Listener doesn't update frame, but it is required for placeholder
             ValueWasChanged(true);
@@ -2772,20 +2752,20 @@ nsTextEditorState::SetValue(const nsAStr
                                    /* aWasInteractiveUserChange = */ false);
 
   return true;
 }
 
 bool
 nsTextEditorState::HasNonEmptyValue()
 {
-  if (mEditor && mBoundFrame && mEditorInitialized &&
+  if (mTextEditor && mBoundFrame && mEditorInitialized &&
       !mIsCommittingComposition) {
     bool empty;
-    nsresult rv = mEditor->GetDocumentIsEmpty(&empty);
+    nsresult rv = mTextEditor->GetDocumentIsEmpty(&empty);
     if (NS_SUCCEEDED(rv)) {
       return !empty;
     }
   }
 
   nsAutoString value;
   GetValue(value, true);
   return !value.IsEmpty();
@@ -2903,20 +2883,17 @@ nsTextEditorState::HideSelectionIfBlurre
   if (!nsContentUtils::IsFocusedContent(content)) {
     mSelCon->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);
   }
 }
 
 bool
 nsTextEditorState::EditorHasComposition()
 {
-  bool isComposing = false;
-  return mEditor &&
-         NS_SUCCEEDED(mEditor->GetComposing(&isComposing)) &&
-         isComposing;
+  return mTextEditor && mTextEditor->IsIMEComposing();
 }
 
 NS_IMPL_ISUPPORTS(nsAnonDivObserver, nsIMutationObserver)
 
 void
 nsAnonDivObserver::CharacterDataChanged(nsIDocument*             aDocument,
                                         nsIContent*              aContent,
                                         CharacterDataChangeInfo* aInfo)
--- a/dom/html/nsTextEditorState.h
+++ b/dom/html/nsTextEditorState.h
@@ -9,27 +9,27 @@
 
 #include "nsString.h"
 #include "nsITextControlElement.h"
 #include "nsITextControlFrame.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Maybe.h"
+#include "mozilla/TextEditor.h"
 #include "mozilla/WeakPtr.h"
 #include "mozilla/dom/HTMLInputElementBinding.h"
 #include "mozilla/dom/Nullable.h"
 
 class nsTextInputListener;
 class nsTextControlFrame;
 class nsTextInputSelectionImpl;
 class nsAnonDivObserver;
 class nsISelectionController;
 class nsFrameSelection;
-class nsIEditor;
 class nsITextControlElement;
 class nsFrame;
 
 namespace mozilla {
 
 class ErrorResult;
 
 namespace dom {
@@ -148,17 +148,17 @@ public:
     Unlink();
     mValue.reset();
     mCachedValue.Truncate();
     mValueBeingSet.Truncate();
     mTextCtrlElement = nullptr;
     MOZ_ASSERT(!mMutationObserver);
   }
 
-  nsIEditor* GetEditor();
+  mozilla::TextEditor* GetTextEditor();
   nsISelectionController* GetSelectionController() const;
   nsFrameSelection* GetConstFrameSelection();
   nsresult BindToFrame(nsTextControlFrame* aFrame);
   void UnbindFromFrame(nsTextControlFrame* aFrame);
   nsresult PrepareEditor(const nsAString *aValue = nullptr);
   void InitializeKeyboardEventListeners();
 
   enum SetValueFlags
@@ -445,17 +445,17 @@ private:
   friend class PrepareEditorEvent;
 
   // The text control element owns this object, and ensures that this object
   // has a smaller lifetime.
   nsITextControlElement* MOZ_NON_OWNING_REF mTextCtrlElement;
   // mSelCon is non-null while we have an mBoundFrame.
   RefPtr<nsTextInputSelectionImpl> mSelCon;
   RefPtr<RestoreSelectionState> mRestoringSelection;
-  nsCOMPtr<nsIEditor> mEditor;
+  RefPtr<mozilla::TextEditor> mTextEditor;
   nsCOMPtr<mozilla::dom::Element> mRootNode;
   nsCOMPtr<mozilla::dom::Element> mPlaceholderDiv;
   nsCOMPtr<mozilla::dom::Element> mPreviewDiv;
   nsTextControlFrame* mBoundFrame;
   RefPtr<nsTextInputListener> mTextListener;
   mozilla::Maybe<nsString> mValue;
   RefPtr<nsAnonDivObserver> mMutationObserver;
   mutable nsString mCachedValue; // Caches non-hard-wrapped value on a multiline control.
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -93,16 +93,17 @@
 #endif
 #endif
 
 #include "mozilla/Unused.h"
 
 #include "mozInlineSpellChecker.h"
 #include "nsDocShell.h"
 #include "nsIConsoleListener.h"
+#include "nsIContentViewer.h"
 #include "nsICycleCollectorListener.h"
 #include "nsIIdlePeriod.h"
 #include "nsIDragService.h"
 #include "nsIIPCBackgroundChildCreateCallback.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIMemoryReporter.h"
 #include "nsIMemoryInfoDumper.h"
 #include "nsIMutable.h"
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -476,17 +476,19 @@ EditorBase::PreDestroy(bool aDestroyingF
 
   mDidPreDestroy = true;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::GetFlags(uint32_t* aFlags)
 {
-  *aFlags = mFlags;
+  // NOTE: If you need to override this method, you need to make Flags()
+  //       virtual.
+  *aFlags = Flags();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::SetFlags(uint32_t aFlags)
 {
   if (mFlags == aFlags) {
     return NS_OK;
@@ -788,25 +790,35 @@ EditorBase::GetNumberOfRedoItems(int32_t
 {
   *aNumItems = 0;
   return mTxnMgr ? mTxnMgr->GetNumberOfRedoItems(aNumItems) : NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::GetTransactionManager(nsITransactionManager** aTxnManager)
 {
-  NS_ENSURE_ARG_POINTER(aTxnManager);
-
-  *aTxnManager = nullptr;
-  NS_ENSURE_TRUE(mTxnMgr, NS_ERROR_FAILURE);
-
-  NS_ADDREF(*aTxnManager = mTxnMgr);
+  // NOTE: If you need to override this method, you need to make
+  //       GetTransactionManager() virtual.
+  if (NS_WARN_IF(!aTxnManager)) {
+    return NS_ERROR_INVALID_ARG;
+  }
+  *aTxnManager = GetTransactionManager().take();
+  if (NS_WARN_IF(!*aTxnManager)) {
+    return NS_ERROR_FAILURE;
+  }
   return NS_OK;
 }
 
+already_AddRefed<nsITransactionManager>
+EditorBase::GetTransactionManager() const
+{
+  nsCOMPtr<nsITransactionManager> transactionManager = mTxnMgr.get();
+  return transactionManager.forget();
+}
+
 NS_IMETHODIMP
 EditorBase::Undo(uint32_t aCount)
 {
   ForceCompositionEnd();
 
   bool hasTxnMgr, hasTransaction = false;
   CanUndo(&hasTxnMgr, &hasTransaction);
   NS_ENSURE_TRUE(hasTransaction, NS_OK);
@@ -5226,33 +5238,39 @@ EditorBase::OnFocus(nsIDOMEventTarget* a
     mInlineSpellChecker->UpdateCurrentDictionary();
     mSpellCheckerDictionaryUpdated = true;
   }
 }
 
 NS_IMETHODIMP
 EditorBase::GetSuppressDispatchingInputEvent(bool* aSuppressed)
 {
-  NS_ENSURE_ARG_POINTER(aSuppressed);
-  *aSuppressed = !mDispatchInputEvent;
+  // NOTE: If you need to override this method, you need to make
+  //       IsSuppressingDispatchingInputEvent() virtual.
+  if (NS_WARN_IF(aSuppressed)) {
+    return NS_ERROR_INVALID_ARG;
+  }
+  *aSuppressed = IsSuppressingDispatchingInputEvent();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::SetSuppressDispatchingInputEvent(bool aSuppress)
 {
   mDispatchInputEvent = !aSuppress;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::GetIsInEditAction(bool* aIsInEditAction)
 {
+  // NOTE: If you need to override this method, you need to make
+  //       IsInEditAction() virtual.
   MOZ_ASSERT(aIsInEditAction, "aIsInEditAction must not be null");
-  *aIsInEditAction = mIsInEditAction;
+  *aIsInEditAction = IsInEditAction();
   return NS_OK;
 }
 
 int32_t
 EditorBase::GetIMESelectionStartOffsetIn(nsINode* aTextNode)
 {
   MOZ_ASSERT(aTextNode, "aTextNode must not be nullptr");
 
--- a/editor/libeditor/EditorBase.h
+++ b/editor/libeditor/EditorBase.h
@@ -862,31 +862,44 @@ public:
    * Likewise, but gets the text control element instead of the root for
    * plaintext editors.
    */
   Element* GetExposedRoot();
 
   /**
    * Accessor methods to flags.
    */
+  uint32_t Flags() const { return mFlags; }
+
   bool IsPlaintextEditor() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorPlaintextMask) != 0;
   }
 
   bool IsSingleLineEditor() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorSingleLineMask) != 0;
   }
 
   bool IsPasswordEditor() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorPasswordMask) != 0;
   }
 
+  // FYI: Both IsRightToLeft() and IsLeftToRight() may return false if
+  //      the editor inherits the content node's direction.
+  bool IsRightToLeft() const
+  {
+    return (mFlags & nsIPlaintextEditor::eEditorRightToLeft) != 0;
+  }
+  bool IsLeftToRight() const
+  {
+    return (mFlags & nsIPlaintextEditor::eEditorLeftToRight) != 0;
+  }
+
   bool IsReadonly() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorReadonlyMask) != 0;
   }
 
   bool IsDisabled() const
   {
     return (mFlags & nsIPlaintextEditor::eEditorDisabledMask) != 0;
@@ -944,16 +957,37 @@ public:
   }
 
   bool IsModifiable() const
   {
     return !IsReadonly();
   }
 
   /**
+   * IsInEditAction() return true while the instance is handling an edit action.
+   * Otherwise, false.
+   */
+  bool IsInEditAction() const { return mIsInEditAction; }
+
+  /**
+   * IsSuppressingDispatchingInputEvent() returns true if the editor stops
+   * dispatching input event.  Otherwise, false.
+   */
+  bool IsSuppressingDispatchingInputEvent() const
+  {
+    return !mDispatchInputEvent;
+  }
+
+  /**
+   * GetTransactionManager() returns transaction manager associated with the
+   * editor.  This may return nullptr if undo/redo hasn't been enabled.
+   */
+  already_AddRefed<nsITransactionManager> GetTransactionManager() const;
+
+  /**
    * Get the input event target. This might return null.
    */
   virtual already_AddRefed<nsIContent> GetInputEventTargetContent() = 0;
 
   /**
    * Get the focused content, if we're focused.  Returns null otherwise.
    */
   virtual already_AddRefed<nsIContent> GetFocusedContent();
--- a/editor/libeditor/TextEditor.cpp
+++ b/editor/libeditor/TextEditor.cpp
@@ -965,18 +965,22 @@ TextEditor::SetMaxTextLength(int32_t aMa
 {
   mMaxTextLength = aMaxTextLength;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TextEditor::GetMaxTextLength(int32_t* aMaxTextLength)
 {
-  NS_ENSURE_TRUE(aMaxTextLength, NS_ERROR_INVALID_POINTER);
-  *aMaxTextLength = mMaxTextLength;
+  // NOTE: If you need to override this method, you need to make
+  //       MaxTextLength() virtual.
+  if (NS_WARN_IF(!aMaxTextLength)) {
+    return NS_ERROR_INVALID_POINTER;
+  }
+  *aMaxTextLength = MaxTextLength();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TextEditor::GetWrapWidth(int32_t* aWrapColumn)
 {
   NS_ENSURE_TRUE( aWrapColumn, NS_ERROR_NULL_POINTER);
 
--- a/editor/libeditor/TextEditor.h
+++ b/editor/libeditor/TextEditor.h
@@ -172,16 +172,18 @@ public:
    * principals match, or we are in a editor context where this doesn't matter.
    * Otherwise, the data must be sanitized first.
    */
   bool IsSafeToInsertData(nsIDOMDocument* aSourceDoc);
 
   static void GetDefaultEditorPrefs(int32_t& aNewLineHandling,
                                     int32_t& aCaretStyle);
 
+  int32_t MaxTextLength() const { return mMaxTextLength; }
+
 protected:
   virtual ~TextEditor();
 
   NS_IMETHOD InitRules();
   void BeginEditorInit();
   nsresult EndEditorInit();
 
   already_AddRefed<nsIDocumentEncoder> GetAndInitDocEncoder(