Home | History | Annotate | Download | only in dom
      1 /*
      2  * Copyright (C) 1999 Lars Knoll (knoll (at) kde.org)
      3  *           (C) 1999 Antti Koivisto (koivisto (at) kde.org)
      4  *           (C) 2001 Dirk Mueller (mueller (at) kde.org)
      5  *           (C) 2006 Alexey Proskuryakov (ap (at) webkit.org)
      6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
      7  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
      8  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
      9  *
     10  * This library is free software; you can redistribute it and/or
     11  * modify it under the terms of the GNU Library General Public
     12  * License as published by the Free Software Foundation; either
     13  * version 2 of the License, or (at your option) any later version.
     14  *
     15  * This library is distributed in the hope that it will be useful,
     16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     18  * Library General Public License for more details.
     19  *
     20  * You should have received a copy of the GNU Library General Public License
     21  * along with this library; see the file COPYING.LIB.  If not, write to
     22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     23  * Boston, MA 02110-1301, USA.
     24  *
     25  */
     26 
     27 #ifndef Document_h
     28 #define Document_h
     29 
     30 #include "CheckedRadioButtons.h"
     31 #include "CollectionCache.h"
     32 #include "CollectionType.h"
     33 #include "Color.h"
     34 #include "DOMTimeStamp.h"
     35 #include "DocumentTiming.h"
     36 #include "QualifiedName.h"
     37 #include "ScriptExecutionContext.h"
     38 #include "StringWithDirection.h"
     39 #include "Timer.h"
     40 #include "TreeScope.h"
     41 #include "ViewportArguments.h"
     42 #include <wtf/FixedArray.h>
     43 #include <wtf/OwnPtr.h>
     44 #include <wtf/PassOwnPtr.h>
     45 #include <wtf/PassRefPtr.h>
     46 
     47 namespace WebCore {
     48 
     49 class AXObjectCache;
     50 class Attr;
     51 class CDATASection;
     52 class CSSPrimitiveValueCache;
     53 class CSSStyleDeclaration;
     54 class CSSStyleSelector;
     55 class CSSStyleSheet;
     56 class CachedCSSStyleSheet;
     57 class CachedResourceLoader;
     58 class CachedScript;
     59 class CanvasRenderingContext;
     60 class CharacterData;
     61 class Comment;
     62 class ContentSecurityPolicy;
     63 class DOMImplementation;
     64 class DOMSelection;
     65 class DOMWindow;
     66 class Database;
     67 class DatabaseThread;
     68 class DocumentFragment;
     69 class DocumentLoader;
     70 class DocumentMarkerController;
     71 class DocumentType;
     72 class DocumentWeakReference;
     73 class EditingText;
     74 class Element;
     75 class EntityReference;
     76 class Event;
     77 class EventListener;
     78 class EventQueue;
     79 class FormAssociatedElement;
     80 class Frame;
     81 class FrameView;
     82 class HTMLCanvasElement;
     83 class HTMLCollection;
     84 class HTMLAllCollection;
     85 class HTMLDocument;
     86 class HTMLElement;
     87 class HTMLFormElement;
     88 class HTMLFrameOwnerElement;
     89 class HTMLHeadElement;
     90 class HTMLInputElement;
     91 class HTMLMapElement;
     92 class HitTestRequest;
     93 class HitTestResult;
     94 class IntPoint;
     95 class DOMWrapperWorld;
     96 class JSNode;
     97 class MediaCanStartListener;
     98 class MediaQueryList;
     99 class MediaQueryMatcher;
    100 class MouseEventWithHitTestResults;
    101 class NodeFilter;
    102 class NodeIterator;
    103 class Page;
    104 class PlatformMouseEvent;
    105 class ProcessingInstruction;
    106 class Range;
    107 class RegisteredEventListener;
    108 class RenderArena;
    109 class RenderView;
    110 class RenderFullScreen;
    111 class ScriptableDocumentParser;
    112 class ScriptElementData;
    113 class ScriptRunner;
    114 class SecurityOrigin;
    115 class SerializedScriptValue;
    116 class SegmentedString;
    117 class Settings;
    118 class StyleSheet;
    119 class StyleSheetList;
    120 class Text;
    121 class TextResourceDecoder;
    122 class DocumentParser;
    123 class TreeWalker;
    124 class XMLHttpRequest;
    125 
    126 #if ENABLE(SVG)
    127 class SVGDocumentExtensions;
    128 #endif
    129 
    130 #if ENABLE(XSLT)
    131 class TransformSource;
    132 #endif
    133 
    134 #if ENABLE(XPATH)
    135 class XPathEvaluator;
    136 class XPathExpression;
    137 class XPathNSResolver;
    138 class XPathResult;
    139 #endif
    140 
    141 #if ENABLE(DASHBOARD_SUPPORT)
    142 struct DashboardRegionValue;
    143 #endif
    144 
    145 #if ENABLE(TOUCH_EVENTS)
    146 class Touch;
    147 class TouchList;
    148 #endif
    149 
    150 #if ENABLE(REQUEST_ANIMATION_FRAME)
    151 class RequestAnimationFrameCallback;
    152 class ScriptedAnimationController;
    153 #endif
    154 
    155 typedef int ExceptionCode;
    156 
    157 class FormElementKey {
    158 public:
    159     FormElementKey(AtomicStringImpl* = 0, AtomicStringImpl* = 0);
    160     ~FormElementKey();
    161     FormElementKey(const FormElementKey&);
    162     FormElementKey& operator=(const FormElementKey&);
    163 
    164     AtomicStringImpl* name() const { return m_name; }
    165     AtomicStringImpl* type() const { return m_type; }
    166 
    167     // Hash table deleted values, which are only constructed and never copied or destroyed.
    168     FormElementKey(WTF::HashTableDeletedValueType) : m_name(hashTableDeletedValue()) { }
    169     bool isHashTableDeletedValue() const { return m_name == hashTableDeletedValue(); }
    170 
    171 private:
    172     void ref() const;
    173     void deref() const;
    174 
    175     static AtomicStringImpl* hashTableDeletedValue() { return reinterpret_cast<AtomicStringImpl*>(-1); }
    176 
    177     AtomicStringImpl* m_name;
    178     AtomicStringImpl* m_type;
    179 };
    180 
    181 inline bool operator==(const FormElementKey& a, const FormElementKey& b)
    182 {
    183     return a.name() == b.name() && a.type() == b.type();
    184 }
    185 
    186 struct FormElementKeyHash {
    187     static unsigned hash(const FormElementKey&);
    188     static bool equal(const FormElementKey& a, const FormElementKey& b) { return a == b; }
    189     static const bool safeToCompareToEmptyOrDeleted = true;
    190 };
    191 
    192 struct FormElementKeyHashTraits : WTF::GenericHashTraits<FormElementKey> {
    193     static void constructDeletedValue(FormElementKey& slot) { new (&slot) FormElementKey(WTF::HashTableDeletedValue); }
    194     static bool isDeletedValue(const FormElementKey& value) { return value.isHashTableDeletedValue(); }
    195 };
    196 
    197 enum PageshowEventPersistence {
    198     PageshowEventNotPersisted = 0,
    199     PageshowEventPersisted = 1
    200 };
    201 
    202 enum StyleSelectorUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle };
    203 
    204 class Document : public TreeScope, public ScriptExecutionContext {
    205 public:
    206     static PassRefPtr<Document> create(Frame* frame, const KURL& url)
    207     {
    208         return adoptRef(new Document(frame, url, false, false));
    209     }
    210     static PassRefPtr<Document> createXHTML(Frame* frame, const KURL& url)
    211     {
    212         return adoptRef(new Document(frame, url, true, false));
    213     }
    214     virtual ~Document();
    215 
    216     MediaQueryMatcher* mediaQueryMatcher();
    217 
    218     using TreeScope::ref;
    219     using TreeScope::deref;
    220 
    221     // Nodes belonging to this document hold guard references -
    222     // these are enough to keep the document from being destroyed, but
    223     // not enough to keep it from removing its children. This allows a
    224     // node that outlives its document to still have a valid document
    225     // pointer without introducing reference cycles.
    226     void guardRef()
    227     {
    228         ASSERT(!m_deletionHasBegun);
    229         ++m_guardRefCount;
    230     }
    231 
    232     void guardDeref()
    233     {
    234         ASSERT(!m_deletionHasBegun);
    235         --m_guardRefCount;
    236         if (!m_guardRefCount && !refCount()) {
    237 #ifndef NDEBUG
    238             m_deletionHasBegun = true;
    239 #endif
    240             delete this;
    241         }
    242     }
    243 
    244     virtual void removedLastRef();
    245 
    246     Element* getElementById(const AtomicString& id) const;
    247 
    248     // DOM methods & attributes for Document
    249 
    250     DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
    251     DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
    252     DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
    253     DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
    254     DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
    255     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
    256     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
    257     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
    258     DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
    259     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
    260     DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
    261     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
    262     DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
    263     DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
    264     DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
    265     DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
    266     DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
    267     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
    268     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
    269     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
    270     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
    271     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
    272     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
    273     DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
    274     DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
    275     DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
    276 
    277     DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
    278     DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
    279     DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
    280     DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
    281     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
    282 
    283     // WebKit extensions
    284     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
    285     DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
    286     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
    287     DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
    288     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
    289     DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
    290     DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
    291     DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
    292     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
    293     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
    294 #if ENABLE(TOUCH_EVENTS)
    295     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
    296     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
    297     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
    298     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
    299 #endif
    300 #if ENABLE(FULLSCREEN_API)
    301     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
    302 #endif
    303 
    304     ViewportArguments viewportArguments() const { return m_viewportArguments; }
    305 
    306     DocumentType* doctype() const { return m_docType.get(); }
    307 
    308     DOMImplementation* implementation();
    309 
    310     Element* documentElement() const
    311     {
    312         if (!m_documentElement)
    313             cacheDocumentElement();
    314         return m_documentElement.get();
    315     }
    316 
    317     virtual PassRefPtr<Element> createElement(const AtomicString& tagName, ExceptionCode&);
    318     PassRefPtr<DocumentFragment> createDocumentFragment();
    319     PassRefPtr<Text> createTextNode(const String& data);
    320     PassRefPtr<Comment> createComment(const String& data);
    321     PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionCode&);
    322     PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionCode&);
    323     PassRefPtr<Attr> createAttribute(const String& name, ExceptionCode&);
    324     PassRefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&, bool shouldIgnoreNamespaceChecks = false);
    325     PassRefPtr<EntityReference> createEntityReference(const String& name, ExceptionCode&);
    326     PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionCode&);
    327     virtual PassRefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&);
    328     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
    329 
    330     /**
    331      * Retrieve all nodes that intersect a rect in the window's document, until it is fully enclosed by
    332      * the boundaries of a node.
    333      *
    334      * @param centerX x reference for the rectangle in CSS pixels
    335      * @param centerY y reference for the rectangle in CSS pixels
    336      * @param topPadding How much to expand the top of the rectangle
    337      * @param rightPadding How much to expand the right of the rectangle
    338      * @param bottomPadding How much to expand the bottom of the rectangle
    339      * @param leftPadding How much to expand the left of the rectangle
    340      * @param ignoreClipping whether or not to ignore the root scroll frame when retrieving the element.
    341      *        If false, this method returns null for coordinates outside of the viewport.
    342      */
    343     PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
    344                                        unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping) const;
    345     Element* elementFromPoint(int x, int y) const;
    346     PassRefPtr<Range> caretRangeFromPoint(int x, int y);
    347 
    348     String readyState() const;
    349 
    350     String defaultCharset() const;
    351 
    352     String inputEncoding() const { return Document::encoding(); }
    353     String charset() const { return Document::encoding(); }
    354     String characterSet() const { return Document::encoding(); }
    355 
    356     void setCharset(const String&);
    357 
    358     void setContent(const String&);
    359 
    360     String contentLanguage() const { return m_contentLanguage; }
    361     void setContentLanguage(const String& lang) { m_contentLanguage = lang; }
    362 
    363     String xmlEncoding() const { return m_xmlEncoding; }
    364     String xmlVersion() const { return m_xmlVersion; }
    365     bool xmlStandalone() const { return m_xmlStandalone; }
    366 
    367     void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
    368     void setXMLVersion(const String&, ExceptionCode&);
    369     void setXMLStandalone(bool, ExceptionCode&);
    370 
    371     String documentURI() const { return m_documentURI; }
    372     void setDocumentURI(const String&);
    373 
    374     virtual KURL baseURI() const;
    375 
    376     PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionCode&);
    377 
    378     PassRefPtr<HTMLCollection> images();
    379     PassRefPtr<HTMLCollection> embeds();
    380     PassRefPtr<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
    381     PassRefPtr<HTMLCollection> applets();
    382     PassRefPtr<HTMLCollection> links();
    383     PassRefPtr<HTMLCollection> forms();
    384     PassRefPtr<HTMLCollection> anchors();
    385     PassRefPtr<HTMLCollection> objects();
    386     PassRefPtr<HTMLCollection> scripts();
    387     PassRefPtr<HTMLCollection> windowNamedItems(const String& name);
    388     PassRefPtr<HTMLCollection> documentNamedItems(const String& name);
    389 
    390     PassRefPtr<HTMLAllCollection> all();
    391 
    392     CollectionCache* collectionInfo(CollectionType type)
    393     {
    394         ASSERT(type >= FirstUnnamedDocumentCachedType);
    395         unsigned index = type - FirstUnnamedDocumentCachedType;
    396         ASSERT(index < NumUnnamedDocumentCachedTypes);
    397         m_collectionInfo[index].checkConsistency();
    398         return &m_collectionInfo[index];
    399     }
    400 
    401     CollectionCache* nameCollectionInfo(CollectionType, const AtomicString& name);
    402 
    403     // Other methods (not part of DOM)
    404     bool isHTMLDocument() const { return m_isHTML; }
    405     bool isXHTMLDocument() const { return m_isXHTML; }
    406     virtual bool isImageDocument() const { return false; }
    407 #if ENABLE(SVG)
    408     virtual bool isSVGDocument() const { return false; }
    409     bool hasSVGRootNode() const;
    410 #else
    411     static bool isSVGDocument() { return false; }
    412     static bool hasSVGRootNode() { return false; }
    413 #endif
    414     virtual bool isPluginDocument() const { return false; }
    415     virtual bool isMediaDocument() const { return false; }
    416 #if ENABLE(WML)
    417     virtual bool isWMLDocument() const { return false; }
    418 #endif
    419 #if ENABLE(XHTMLMP)
    420     bool isXHTMLMPDocument() const;
    421     bool shouldProcessNoscriptElement() const { return m_shouldProcessNoScriptElement; }
    422     void setShouldProcessNoscriptElement(bool shouldDo) { m_shouldProcessNoScriptElement = shouldDo; }
    423 #endif
    424     virtual bool isFrameSet() const { return false; }
    425 
    426     PassRefPtr<CSSPrimitiveValueCache> cssPrimitiveValueCache() const;
    427 
    428     CSSStyleSelector* styleSelectorIfExists() const { return m_styleSelector.get(); }
    429 
    430     bool usesViewSourceStyles() const { return m_usesViewSourceStyles; }
    431     void setUsesViewSourceStyles(bool usesViewSourceStyles) { m_usesViewSourceStyles = usesViewSourceStyles; }
    432 
    433     bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
    434 
    435     CSSStyleSelector* styleSelector()
    436     {
    437         if (!m_styleSelector)
    438             createStyleSelector();
    439         return m_styleSelector.get();
    440     }
    441 
    442     /**
    443      * Updates the pending sheet count and then calls updateStyleSelector.
    444      */
    445     void removePendingSheet();
    446 
    447     /**
    448      * This method returns true if all top-level stylesheets have loaded (including
    449      * any @imports that they may be loading).
    450      */
    451     bool haveStylesheetsLoaded() const
    452     {
    453         return m_pendingStylesheets <= 0 || m_ignorePendingStylesheets;
    454     }
    455 
    456     /**
    457      * Increments the number of pending sheets.  The <link> elements
    458      * invoke this to add themselves to the loading list.
    459      */
    460     void addPendingSheet() { m_pendingStylesheets++; }
    461 
    462     void addStyleSheetCandidateNode(Node*, bool createdByParser);
    463     void removeStyleSheetCandidateNode(Node*);
    464 
    465     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
    466     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
    467 
    468     /**
    469      * Called when one or more stylesheets in the document may have been added, removed or changed.
    470      *
    471      * Creates a new style selector and assign it to this document. This is done by iterating through all nodes in
    472      * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
    473      * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
    474      * constructed from these which is used to create the a new style selector which collates all of the stylesheets
    475      * found and is used to calculate the derived styles for all rendering objects.
    476      */
    477     void styleSelectorChanged(StyleSelectorUpdateFlag);
    478     void recalcStyleSelector();
    479 
    480     bool usesSiblingRules() const { return m_usesSiblingRules || m_usesSiblingRulesOverride; }
    481     void setUsesSiblingRules(bool b) { m_usesSiblingRulesOverride = b; }
    482     bool usesFirstLineRules() const { return m_usesFirstLineRules; }
    483     bool usesFirstLetterRules() const { return m_usesFirstLetterRules; }
    484     void setUsesFirstLetterRules(bool b) { m_usesFirstLetterRules = b; }
    485     bool usesBeforeAfterRules() const { return m_usesBeforeAfterRules || m_usesBeforeAfterRulesOverride; }
    486     void setUsesBeforeAfterRules(bool b) { m_usesBeforeAfterRulesOverride = b; }
    487     bool usesRemUnits() const { return m_usesRemUnits; }
    488     void setUsesRemUnits(bool b) { m_usesRemUnits = b; }
    489     bool usesLinkRules() const { return linkColor() != visitedLinkColor() || m_usesLinkRules; }
    490     void setUsesLinkRules(bool b) { m_usesLinkRules = b; }
    491 
    492     // Machinery for saving and restoring state when you leave and then go back to a page.
    493     void registerFormElementWithState(Element* e) { m_formElementsWithState.add(e); }
    494     void unregisterFormElementWithState(Element* e) { m_formElementsWithState.remove(e); }
    495     Vector<String> formElementsState() const;
    496     void setStateForNewFormElements(const Vector<String>&);
    497     bool hasStateForNewFormElements() const;
    498     bool takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state);
    499 
    500     void registerFormElementWithFormAttribute(FormAssociatedElement*);
    501     void unregisterFormElementWithFormAttribute(FormAssociatedElement*);
    502     void resetFormElementsOwner(HTMLFormElement*);
    503 
    504     FrameView* view() const; // can be NULL
    505     Frame* frame() const { return m_frame; } // can be NULL
    506     Page* page() const; // can be NULL
    507     Settings* settings() const; // can be NULL
    508 
    509     PassRefPtr<Range> createRange();
    510 
    511     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow,
    512         PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
    513 
    514     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow,
    515         PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
    516 
    517     // Special support for editing
    518     PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
    519     PassRefPtr<EditingText> createEditingTextNode(const String&);
    520 
    521     virtual void recalcStyle(StyleChange = NoChange);
    522     bool childNeedsAndNotInStyleRecalc();
    523     virtual void updateStyleIfNeeded();
    524     void updateLayout();
    525     void updateLayoutIgnorePendingStylesheets();
    526     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
    527     PassRefPtr<RenderStyle> styleForPage(int pageIndex);
    528 
    529     // Returns true if page box (margin boxes and page borders) is visible.
    530     bool isPageBoxVisible(int pageIndex);
    531 
    532     // Returns the preferred page size and margins in pixels, assuming 96
    533     // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
    534     // marginLeft must be initialized to the default values that are used if
    535     // auto is specified.
    536     void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
    537 
    538     static void updateStyleForAllDocuments(); // FIXME: Try to reduce the # of calls to this function.
    539     CachedResourceLoader* cachedResourceLoader() { return m_cachedResourceLoader.get(); }
    540 
    541     virtual void attach();
    542     virtual void detach();
    543 
    544     RenderArena* renderArena() { return m_renderArena.get(); }
    545 
    546     RenderView* renderView() const;
    547 
    548     void clearAXObjectCache();
    549     AXObjectCache* axObjectCache() const;
    550     bool axObjectCacheExists() const;
    551 
    552     // to get visually ordered hebrew and arabic pages right
    553     void setVisuallyOrdered();
    554     bool visuallyOrdered() const { return m_visuallyOrdered; }
    555 
    556     DocumentLoader* loader() const;
    557 
    558     void open(Document* ownerDocument = 0);
    559     void implicitOpen();
    560 
    561     // close() is the DOM API document.close()
    562     void close();
    563     // In some situations (see the code), we ignore document.close().
    564     // explicitClose() bypass these checks and actually tries to close the
    565     // input stream.
    566     void explicitClose();
    567     // implicitClose() actually does the work of closing the input stream.
    568     void implicitClose();
    569 
    570     void cancelParsing();
    571 
    572     void write(const SegmentedString& text, Document* ownerDocument = 0);
    573     void write(const String& text, Document* ownerDocument = 0);
    574     void writeln(const String& text, Document* ownerDocument = 0);
    575     void finishParsing();
    576 
    577     bool wellFormed() const { return m_wellFormed; }
    578 
    579     const KURL& url() const { return m_url; }
    580     void setURL(const KURL&);
    581 
    582     const KURL& baseURL() const { return m_baseURL; }
    583     const String& baseTarget() const { return m_baseTarget; }
    584     void processBaseElement();
    585 
    586     KURL completeURL(const String&) const;
    587 
    588     virtual String userAgent(const KURL&) const;
    589 
    590     CSSStyleSheet* pageUserSheet();
    591     void clearPageUserSheet();
    592     void updatePageUserSheet();
    593 
    594     const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets() const;
    595     void clearPageGroupUserSheets();
    596     void updatePageGroupUserSheets();
    597 
    598     CSSStyleSheet* elementSheet();
    599     CSSStyleSheet* mappedElementSheet();
    600 
    601     virtual PassRefPtr<DocumentParser> createParser();
    602     DocumentParser* parser() const { return m_parser.get(); }
    603     ScriptableDocumentParser* scriptableDocumentParser() const;
    604 
    605     bool printing() const { return m_printing; }
    606     void setPrinting(bool p) { m_printing = p; }
    607 
    608     bool paginatedForScreen() const { return m_paginatedForScreen; }
    609     void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
    610 
    611     bool paginated() const { return printing() || paginatedForScreen(); }
    612 
    613     enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
    614 
    615     virtual void setCompatibilityModeFromDoctype() { }
    616     void setCompatibilityMode(CompatibilityMode m);
    617     void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
    618     CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
    619 
    620     String compatMode() const;
    621 
    622     bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
    623     bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
    624     bool inNoQuirksMode() const { return m_compatibilityMode == NoQuirksMode; }
    625 
    626     enum ReadyState {
    627         Loading,
    628         Interactive,
    629         Complete
    630     };
    631     void setReadyState(ReadyState);
    632     void setParsing(bool);
    633     bool parsing() const { return m_bParsing; }
    634     int minimumLayoutDelay();
    635 
    636     // This method is used by Android.
    637     void setExtraLayoutDelay(int delay) { m_extraLayoutDelay = delay; }
    638 
    639     bool shouldScheduleLayout();
    640     bool isLayoutTimerActive();
    641     int elapsedTime() const;
    642 
    643     void setTextColor(const Color& color) { m_textColor = color; }
    644     Color textColor() const { return m_textColor; }
    645 
    646     const Color& linkColor() const { return m_linkColor; }
    647     const Color& visitedLinkColor() const { return m_visitedLinkColor; }
    648     const Color& activeLinkColor() const { return m_activeLinkColor; }
    649     void setLinkColor(const Color& c) { m_linkColor = c; }
    650     void setVisitedLinkColor(const Color& c) { m_visitedLinkColor = c; }
    651     void setActiveLinkColor(const Color& c) { m_activeLinkColor = c; }
    652     void resetLinkColor();
    653     void resetVisitedLinkColor();
    654     void resetActiveLinkColor();
    655 
    656     MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const IntPoint&, const PlatformMouseEvent&);
    657 
    658     StyleSheetList* styleSheets();
    659 
    660     /* Newly proposed CSS3 mechanism for selecting alternate
    661        stylesheets using the DOM. May be subject to change as
    662        spec matures. - dwh
    663     */
    664     String preferredStylesheetSet() const;
    665     String selectedStylesheetSet() const;
    666     void setSelectedStylesheetSet(const String&);
    667 
    668     bool setFocusedNode(PassRefPtr<Node>);
    669     Node* focusedNode() const { return m_focusedNode.get(); }
    670 
    671     void getFocusableNodes(Vector<RefPtr<Node> >&);
    672 
    673     // The m_ignoreAutofocus flag specifies whether or not the document has been changed by the user enough
    674     // for WebCore to ignore the autofocus attribute on any form controls
    675     bool ignoreAutofocus() const { return m_ignoreAutofocus; };
    676     void setIgnoreAutofocus(bool shouldIgnore = true) { m_ignoreAutofocus = shouldIgnore; };
    677 
    678     void setHoverNode(PassRefPtr<Node>);
    679     Node* hoverNode() const { return m_hoverNode.get(); }
    680 
    681     void setActiveNode(PassRefPtr<Node>);
    682     Node* activeNode() const { return m_activeNode.get(); }
    683 
    684     void focusedNodeRemoved();
    685     void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
    686     void hoveredNodeDetached(Node*);
    687     void activeChainNodeDetached(Node*);
    688 
    689     // Updates for :target (CSS3 selector).
    690     void setCSSTarget(Element*);
    691     Element* cssTarget() const { return m_cssTarget; }
    692 
    693     void scheduleForcedStyleRecalc();
    694     void scheduleStyleRecalc();
    695     void unscheduleStyleRecalc();
    696     bool isPendingStyleRecalc() const;
    697     void styleRecalcTimerFired(Timer<Document>*);
    698 
    699     void attachNodeIterator(NodeIterator*);
    700     void detachNodeIterator(NodeIterator*);
    701     void moveNodeIteratorsToNewDocument(Node*, Document*);
    702 
    703     void attachRange(Range*);
    704     void detachRange(Range*);
    705 
    706     void nodeChildrenChanged(ContainerNode*);
    707     // nodeChildrenWillBeRemoved is used when removing all node children at once.
    708     void nodeChildrenWillBeRemoved(ContainerNode*);
    709     // nodeWillBeRemoved is only safe when removing one node at a time.
    710     void nodeWillBeRemoved(Node*);
    711 
    712     void textInserted(Node*, unsigned offset, unsigned length);
    713     void textRemoved(Node*, unsigned offset, unsigned length);
    714     void textNodesMerged(Text* oldNode, unsigned offset);
    715     void textNodeSplit(Text* oldNode);
    716 
    717     DOMWindow* defaultView() const { return domWindow(); }
    718     DOMWindow* domWindow() const;
    719 
    720     // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
    721     void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
    722     EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
    723     void dispatchWindowEvent(PassRefPtr<Event>, PassRefPtr<EventTarget> = 0);
    724     void dispatchWindowLoadEvent();
    725 
    726     PassRefPtr<Event> createEvent(const String& eventType, ExceptionCode&);
    727 
    728     // keep track of what types of event listeners are registered, so we don't
    729     // dispatch events unnecessarily
    730     enum ListenerType {
    731         DOMSUBTREEMODIFIED_LISTENER          = 0x01,
    732         DOMNODEINSERTED_LISTENER             = 0x02,
    733         DOMNODEREMOVED_LISTENER              = 0x04,
    734         DOMNODEREMOVEDFROMDOCUMENT_LISTENER  = 0x08,
    735         DOMNODEINSERTEDINTODOCUMENT_LISTENER = 0x10,
    736         DOMATTRMODIFIED_LISTENER             = 0x20,
    737         DOMCHARACTERDATAMODIFIED_LISTENER    = 0x40,
    738         OVERFLOWCHANGED_LISTENER             = 0x80,
    739         ANIMATIONEND_LISTENER                = 0x100,
    740         ANIMATIONSTART_LISTENER              = 0x200,
    741         ANIMATIONITERATION_LISTENER          = 0x400,
    742         TRANSITIONEND_LISTENER               = 0x800,
    743         BEFORELOAD_LISTENER                  = 0x1000,
    744         TOUCH_LISTENER                       = 0x2000,
    745         BEFOREPROCESS_LISTENER               = 0x4000
    746     };
    747 
    748     bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
    749     void addListenerType(ListenerType listenerType) { m_listenerTypes = m_listenerTypes | listenerType; }
    750     void addListenerTypeIfNeeded(const AtomicString& eventType);
    751 
    752     CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
    753 
    754     /**
    755      * Searches through the document, starting from fromNode, for the next selectable element that comes after fromNode.
    756      * The order followed is as specified in section 17.11.1 of the HTML4 spec, which is elements with tab indexes
    757      * first (from lowest to highest), and then elements without tab indexes (in document order).
    758      *
    759      * @param fromNode The node from which to start searching. The node after this will be focused. May be null.
    760      *
    761      * @return The focus node that comes after fromNode
    762      *
    763      * See http://www.w3.org/TR/html4/interact/forms.html#h-17.11.1
    764      */
    765     Node* nextFocusableNode(Node* start, KeyboardEvent*);
    766 
    767     /**
    768      * Searches through the document, starting from fromNode, for the previous selectable element (that comes _before_)
    769      * fromNode. The order followed is as specified in section 17.11.1 of the HTML4 spec, which is elements with tab
    770      * indexes first (from lowest to highest), and then elements without tab indexes (in document order).
    771      *
    772      * @param fromNode The node from which to start searching. The node before this will be focused. May be null.
    773      *
    774      * @return The focus node that comes before fromNode
    775      *
    776      * See http://www.w3.org/TR/html4/interact/forms.html#h-17.11.1
    777      */
    778     Node* previousFocusableNode(Node* start, KeyboardEvent*);
    779 
    780     int nodeAbsIndex(Node*);
    781     Node* nodeWithAbsIndex(int absIndex);
    782 
    783     /**
    784      * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
    785      * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
    786      * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
    787      * specified in a HTML file.
    788      *
    789      * @param equiv The http header name (value of the meta tag's "equiv" attribute)
    790      * @param content The header value (value of the meta tag's "content" attribute)
    791      */
    792     void processHttpEquiv(const String& equiv, const String& content);
    793     void processViewport(const String& features);
    794 
    795 #ifdef ANDROID_META_SUPPORT
    796      /**
    797       * Handles format-detection like <meta name = "format-detection" content = "telephone=no">
    798       */
    799      void processMetadataSettings(const String& content);
    800 #endif
    801 
    802     // Returns the owning element in the parent document.
    803     // Returns 0 if this is the top level document.
    804     HTMLFrameOwnerElement* ownerElement() const;
    805 
    806     // Used by DOM bindings; no direction known.
    807     String title() const { return m_title.string(); }
    808     void setTitle(const String&);
    809 
    810     void setTitleElement(const StringWithDirection&, Element* titleElement);
    811     void removeTitle(Element* titleElement);
    812 
    813     String cookie(ExceptionCode&) const;
    814     void setCookie(const String&, ExceptionCode&);
    815 
    816     String referrer() const;
    817 
    818     String domain() const;
    819     void setDomain(const String& newDomain, ExceptionCode&);
    820 
    821     String lastModified() const;
    822 
    823     // The cookieURL is used to query the cookie database for this document's
    824     // cookies. For example, if the cookie URL is http://example.com, we'll
    825     // use the non-Secure cookies for example.com when computing
    826     // document.cookie.
    827     //
    828     // Q: How is the cookieURL different from the document's URL?
    829     // A: The two URLs are the same almost all the time.  However, if one
    830     //    document inherits the security context of another document, it
    831     //    inherits its cookieURL but not its URL.
    832     //
    833     const KURL& cookieURL() const { return m_cookieURL; }
    834 
    835     // The firstPartyForCookies is used to compute whether this document
    836     // appears in a "third-party" context for the purpose of third-party
    837     // cookie blocking.  The document is in a third-party context if the
    838     // cookieURL and the firstPartyForCookies are from different hosts.
    839     //
    840     // Note: Some ports (including possibly Apple's) only consider the
    841     //       document in a third-party context if the cookieURL and the
    842     //       firstPartyForCookies have a different registry-controlled
    843     //       domain.
    844     //
    845     const KURL& firstPartyForCookies() const { return m_firstPartyForCookies; }
    846     void setFirstPartyForCookies(const KURL& url) { m_firstPartyForCookies = url; }
    847 
    848     // The following implements the rule from HTML 4 for what valid names are.
    849     // To get this right for all the XML cases, we probably have to improve this or move it
    850     // and make it sensitive to the type of document.
    851     static bool isValidName(const String&);
    852 
    853     // The following breaks a qualified name into a prefix and a local name.
    854     // It also does a validity check, and returns false if the qualified name
    855     // is invalid.  It also sets ExceptionCode when name is invalid.
    856     static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode&);
    857 
    858     // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
    859     static bool hasPrefixNamespaceMismatch(const QualifiedName&);
    860 
    861     HTMLElement* body() const;
    862     void setBody(PassRefPtr<HTMLElement>, ExceptionCode&);
    863 
    864     HTMLHeadElement* head();
    865 
    866     DocumentMarkerController* markers() const { return m_markers.get(); }
    867 
    868     bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
    869     bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
    870     void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
    871     void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
    872 
    873     bool execCommand(const String& command, bool userInterface = false, const String& value = String());
    874     bool queryCommandEnabled(const String& command);
    875     bool queryCommandIndeterm(const String& command);
    876     bool queryCommandState(const String& command);
    877     bool queryCommandSupported(const String& command);
    878     String queryCommandValue(const String& command);
    879 
    880     // designMode support
    881     enum InheritedBool { off = false, on = true, inherit };
    882     void setDesignMode(InheritedBool value);
    883     InheritedBool getDesignMode() const;
    884     bool inDesignMode() const;
    885 
    886     Document* parentDocument() const;
    887     Document* topDocument() const;
    888 
    889     int docID() const { return m_docID; }
    890 
    891     ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
    892 
    893 #if ENABLE(XSLT)
    894     void applyXSLTransform(ProcessingInstruction* pi);
    895     PassRefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
    896     void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
    897 
    898     void setTransformSource(PassOwnPtr<TransformSource>);
    899     TransformSource* transformSource() const { return m_transformSource.get(); }
    900 #endif
    901 
    902     void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
    903     uint64_t domTreeVersion() const { return m_domTreeVersion; }
    904 
    905 #ifdef ANDROID_STYLE_VERSION
    906     void incStyleVersion() { ++m_styleVersion; }
    907     unsigned styleVersion() const { return m_styleVersion; }
    908 #endif
    909 
    910     void setDocType(PassRefPtr<DocumentType>);
    911 
    912 #if ENABLE(XPATH)
    913     // XPathEvaluator methods
    914     PassRefPtr<XPathExpression> createExpression(const String& expression,
    915                                                  XPathNSResolver* resolver,
    916                                                  ExceptionCode& ec);
    917     PassRefPtr<XPathNSResolver> createNSResolver(Node *nodeResolver);
    918     PassRefPtr<XPathResult> evaluate(const String& expression,
    919                                      Node* contextNode,
    920                                      XPathNSResolver* resolver,
    921                                      unsigned short type,
    922                                      XPathResult* result,
    923                                      ExceptionCode& ec);
    924 #endif // ENABLE(XPATH)
    925 
    926     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
    927 
    928     bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
    929 
    930     void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
    931 
    932     const String& iconURL() const { return m_iconURL; }
    933     void setIconURL(const String& iconURL, const String& type);
    934 
    935     void setUseSecureKeyboardEntryWhenActive(bool);
    936     bool useSecureKeyboardEntryWhenActive() const;
    937 
    938     void updateFocusAppearanceSoon(bool restorePreviousSelection);
    939     void cancelFocusAppearanceUpdate();
    940 
    941     // FF method for accessing the selection added for compatibility.
    942     DOMSelection* getSelection() const;
    943 
    944     // Extension for manipulating canvas drawing contexts for use in CSS
    945     CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
    946     HTMLCanvasElement* getCSSCanvasElement(const String& name);
    947 
    948     bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
    949     void parseDNSPrefetchControlHeader(const String&);
    950 
    951     virtual void addMessage(MessageSource, MessageType, MessageLevel, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>);
    952     virtual void postTask(PassOwnPtr<Task>); // Executes the task on context's thread asynchronously.
    953 
    954     virtual void suspendScriptedAnimationControllerCallbacks();
    955     virtual void resumeScriptedAnimationControllerCallbacks();
    956 
    957     virtual void finishedParsing();
    958 
    959     bool inPageCache() const { return m_inPageCache; }
    960     void setInPageCache(bool flag);
    961 
    962     // Elements can register themselves for the "documentWillBecomeInactive()" and
    963     // "documentDidBecomeActive()" callbacks
    964     void registerForDocumentActivationCallbacks(Element*);
    965     void unregisterForDocumentActivationCallbacks(Element*);
    966     void documentWillBecomeInactive();
    967     void documentDidBecomeActive();
    968 
    969     void registerForMediaVolumeCallbacks(Element*);
    970     void unregisterForMediaVolumeCallbacks(Element*);
    971     void mediaVolumeDidChange();
    972 
    973     void registerForPrivateBrowsingStateChangedCallbacks(Element*);
    974     void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
    975     void privateBrowsingStateDidChange();
    976 
    977     void setShouldCreateRenderers(bool);
    978     bool shouldCreateRenderers();
    979 
    980     void setDecoder(PassRefPtr<TextResourceDecoder>);
    981     TextResourceDecoder* decoder() const { return m_decoder.get(); }
    982 
    983     String displayStringModifiedByEncoding(const String&) const;
    984     PassRefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
    985     void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const;
    986 
    987     // Quirk for the benefit of Apple's Dictionary application.
    988     void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
    989     bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
    990 
    991 #if ENABLE(DASHBOARD_SUPPORT)
    992     void setDashboardRegionsDirty(bool f) { m_dashboardRegionsDirty = f; }
    993     bool dashboardRegionsDirty() const { return m_dashboardRegionsDirty; }
    994     bool hasDashboardRegions () const { return m_hasDashboardRegions; }
    995     void setHasDashboardRegions(bool f) { m_hasDashboardRegions = f; }
    996     const Vector<DashboardRegionValue>& dashboardRegions() const;
    997     void setDashboardRegions(const Vector<DashboardRegionValue>&);
    998 #endif
    999 
   1000     virtual void removeAllEventListeners();
   1001 
   1002     CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
   1003 
   1004 #if ENABLE(SVG)
   1005     const SVGDocumentExtensions* svgExtensions();
   1006     SVGDocumentExtensions* accessSVGExtensions();
   1007 #endif
   1008 
   1009     void initSecurityContext();
   1010 
   1011     // Explicitly override the security origin for this document.
   1012     // Note: It is dangerous to change the security origin of a document
   1013     //       that already contains content.
   1014     void setSecurityOrigin(SecurityOrigin*);
   1015 
   1016     void updateURLForPushOrReplaceState(const KURL&);
   1017     void statePopped(SerializedScriptValue*);
   1018 
   1019     bool processingLoadEvent() const { return m_processingLoadEvent; }
   1020 
   1021 #if ENABLE(DATABASE)
   1022     virtual bool allowDatabaseAccess() const;
   1023     virtual void databaseExceededQuota(const String& name);
   1024 #endif
   1025 
   1026     virtual bool isContextThread() const;
   1027     virtual bool isJSExecutionForbidden() const { return false; }
   1028 
   1029     void setUsingGeolocation(bool f) { m_usingGeolocation = f; }
   1030     bool usingGeolocation() const { return m_usingGeolocation; };
   1031 
   1032 #if ENABLE(WML)
   1033     void setContainsWMLContent(bool value) { m_containsWMLContent = value; }
   1034     bool containsWMLContent() const { return m_containsWMLContent; }
   1035 
   1036     void resetWMLPageState();
   1037     void initializeWMLPageState();
   1038 #endif
   1039 
   1040     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
   1041     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
   1042 
   1043     void enqueueWindowEvent(PassRefPtr<Event>);
   1044     void enqueueDocumentEvent(PassRefPtr<Event>);
   1045     void enqueuePageshowEvent(PageshowEventPersistence);
   1046     void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
   1047     void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
   1048     EventQueue* eventQueue() const { return m_eventQueue.get(); }
   1049 
   1050     void addMediaCanStartListener(MediaCanStartListener*);
   1051     void removeMediaCanStartListener(MediaCanStartListener*);
   1052     MediaCanStartListener* takeAnyMediaCanStartListener();
   1053 
   1054     const QualifiedName& idAttributeName() const { return m_idAttributeName; }
   1055 
   1056 #if ENABLE(FULLSCREEN_API)
   1057     bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
   1058     bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
   1059     Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
   1060     void webkitRequestFullScreenForElement(Element*, unsigned short flags);
   1061     void webkitCancelFullScreen();
   1062 
   1063     void webkitWillEnterFullScreenForElement(Element*);
   1064     void webkitDidEnterFullScreenForElement(Element*);
   1065     void webkitWillExitFullScreenForElement(Element*);
   1066     void webkitDidExitFullScreenForElement(Element*);
   1067 
   1068     void setFullScreenRenderer(RenderFullScreen*);
   1069     RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
   1070 
   1071     void setFullScreenRendererSize(const IntSize&);
   1072     void setFullScreenRendererBackgroundColor(Color);
   1073 
   1074     void fullScreenChangeDelayTimerFired(Timer<Document>*);
   1075     bool fullScreenIsAllowedForElement(Element*) const;
   1076 #endif
   1077 
   1078     // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
   1079     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
   1080     void decrementLoadEventDelayCount();
   1081     bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
   1082 
   1083 #if ENABLE(TOUCH_EVENTS)
   1084     PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, ExceptionCode&) const;
   1085     PassRefPtr<TouchList> createTouchList(ExceptionCode&) const;
   1086 #endif
   1087 
   1088     const DocumentTiming* timing() const { return &m_documentTiming; }
   1089 
   1090 #if ENABLE(REQUEST_ANIMATION_FRAME)
   1091     int webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>, Element*);
   1092     void webkitCancelRequestAnimationFrame(int id);
   1093     void serviceScriptedAnimations(DOMTimeStamp);
   1094 #endif
   1095 
   1096     virtual EventTarget* errorEventTarget();
   1097     virtual void logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>);
   1098 
   1099     void initDNSPrefetch();
   1100 
   1101     ContentSecurityPolicy* contentSecurityPolicy() { return m_contentSecurityPolicy.get(); }
   1102 
   1103 protected:
   1104     Document(Frame*, const KURL&, bool isXHTML, bool isHTML);
   1105 
   1106     void clearXMLVersion() { m_xmlVersion = String(); }
   1107 
   1108 
   1109 private:
   1110     friend class IgnoreDestructiveWriteCountIncrementer;
   1111 
   1112     void detachParser();
   1113 
   1114     typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
   1115     void processArguments(const String& features, void* data, ArgumentsCallback);
   1116 
   1117     virtual bool isDocument() const { return true; }
   1118 
   1119     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
   1120 
   1121     virtual String nodeName() const;
   1122     virtual NodeType nodeType() const;
   1123     virtual bool childTypeAllowed(NodeType) const;
   1124     virtual PassRefPtr<Node> cloneNode(bool deep);
   1125     virtual bool canReplaceChild(Node* newChild, Node* oldChild);
   1126 
   1127     virtual void refScriptExecutionContext() { ref(); }
   1128     virtual void derefScriptExecutionContext() { deref(); }
   1129 
   1130     virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
   1131     virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
   1132 
   1133     virtual double minimumTimerInterval() const;
   1134 
   1135     String encoding() const;
   1136 
   1137     void updateTitle(const StringWithDirection&);
   1138     void updateFocusAppearanceTimerFired(Timer<Document>*);
   1139     void updateBaseURL();
   1140 
   1141     void cacheDocumentElement() const;
   1142 
   1143     void createStyleSelector();
   1144 
   1145     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
   1146 
   1147     void loadEventDelayTimerFired(Timer<Document>*);
   1148 
   1149     int m_guardRefCount;
   1150 
   1151     OwnPtr<CSSStyleSelector> m_styleSelector;
   1152     bool m_didCalculateStyleSelector;
   1153     bool m_hasDirtyStyleSelector;
   1154 
   1155     mutable RefPtr<CSSPrimitiveValueCache> m_cssPrimitiveValueCache;
   1156 
   1157     Frame* m_frame;
   1158     OwnPtr<CachedResourceLoader> m_cachedResourceLoader;
   1159     RefPtr<DocumentParser> m_parser;
   1160     bool m_wellFormed;
   1161 
   1162     // Document URLs.
   1163     KURL m_url; // Document.URL: The URL from which this document was retrieved.
   1164     KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
   1165     KURL m_baseElementURL; // The URL set by the <base> element.
   1166     KURL m_cookieURL; // The URL to use for cookie access.
   1167     KURL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
   1168 
   1169     // Document.documentURI:
   1170     // Although URL-like, Document.documentURI can actually be set to any
   1171     // string by content.  Document.documentURI affects m_baseURL unless the
   1172     // document contains a <base> element, in which case the <base> element
   1173     // takes precedence.
   1174     String m_documentURI;
   1175 
   1176     String m_baseTarget;
   1177 
   1178     RefPtr<DocumentType> m_docType;
   1179     mutable RefPtr<DOMImplementation> m_implementation;
   1180 
   1181     // Track the number of currently loading top-level stylesheets needed for rendering.
   1182     // Sheets loaded using the @import directive are not included in this count.
   1183     // We use this count of pending sheets to detect when we can begin attaching
   1184     // elements and when it is safe to execute scripts.
   1185     int m_pendingStylesheets;
   1186 
   1187     // But sometimes you need to ignore pending stylesheet count to
   1188     // force an immediate layout when requested by JS.
   1189     bool m_ignorePendingStylesheets;
   1190 
   1191     // If we do ignore the pending stylesheet count, then we need to add a boolean
   1192     // to track that this happened so that we can do a full repaint when the stylesheets
   1193     // do eventually load.
   1194     PendingSheetLayout m_pendingSheetLayout;
   1195 
   1196     bool m_hasNodesWithPlaceholderStyle;
   1197 
   1198     RefPtr<CSSStyleSheet> m_elemSheet;
   1199     RefPtr<CSSStyleSheet> m_mappedElementSheet;
   1200     RefPtr<CSSStyleSheet> m_pageUserSheet;
   1201     mutable OwnPtr<Vector<RefPtr<CSSStyleSheet> > > m_pageGroupUserSheets;
   1202     mutable bool m_pageGroupUserSheetCacheValid;
   1203 
   1204     bool m_printing;
   1205     bool m_paginatedForScreen;
   1206 
   1207     bool m_ignoreAutofocus;
   1208 
   1209     CompatibilityMode m_compatibilityMode;
   1210     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
   1211 
   1212     Color m_textColor;
   1213 
   1214     RefPtr<Node> m_focusedNode;
   1215     RefPtr<Node> m_hoverNode;
   1216     RefPtr<Node> m_activeNode;
   1217     mutable RefPtr<Element> m_documentElement;
   1218 
   1219     uint64_t m_domTreeVersion;
   1220     static uint64_t s_globalTreeVersion;
   1221 #ifdef ANDROID_STYLE_VERSION
   1222     unsigned m_styleVersion;
   1223 #endif
   1224 
   1225     HashSet<NodeIterator*> m_nodeIterators;
   1226     HashSet<Range*> m_ranges;
   1227 
   1228     unsigned short m_listenerTypes;
   1229 
   1230     RefPtr<StyleSheetList> m_styleSheets; // All of the stylesheets that are currently in effect for our media type and stylesheet set.
   1231 
   1232     typedef ListHashSet<Node*, 32> StyleSheetCandidateListHashSet;
   1233     StyleSheetCandidateListHashSet m_styleSheetCandidateNodes; // All of the nodes that could potentially provide stylesheets to the document (<link>, <style>, <?xml-stylesheet>)
   1234 
   1235     typedef ListHashSet<Element*, 64> FormElementListHashSet;
   1236     FormElementListHashSet m_formElementsWithState;
   1237     typedef ListHashSet<FormAssociatedElement*, 32> FormAssociatedElementListHashSet;
   1238     FormAssociatedElementListHashSet m_formElementsWithFormAttribute;
   1239 
   1240     typedef HashMap<FormElementKey, Vector<String>, FormElementKeyHash, FormElementKeyHashTraits> FormElementStateMap;
   1241     FormElementStateMap m_stateForNewFormElements;
   1242 
   1243     Color m_linkColor;
   1244     Color m_visitedLinkColor;
   1245     Color m_activeLinkColor;
   1246 
   1247     String m_preferredStylesheetSet;
   1248     String m_selectedStylesheetSet;
   1249 
   1250     bool m_loadingSheet;
   1251     bool m_visuallyOrdered;
   1252     ReadyState m_readyState;
   1253     bool m_bParsing;
   1254 
   1255     Timer<Document> m_styleRecalcTimer;
   1256     bool m_pendingStyleRecalcShouldForce;
   1257     bool m_inStyleRecalc;
   1258     bool m_closeAfterStyleRecalc;
   1259 
   1260     bool m_usesSiblingRules;
   1261     bool m_usesSiblingRulesOverride;
   1262     bool m_usesFirstLineRules;
   1263     bool m_usesFirstLetterRules;
   1264     bool m_usesBeforeAfterRules;
   1265     bool m_usesBeforeAfterRulesOverride;
   1266     bool m_usesRemUnits;
   1267     bool m_usesLinkRules;
   1268     bool m_gotoAnchorNeededAfterStylesheetsLoad;
   1269     bool m_isDNSPrefetchEnabled;
   1270     bool m_haveExplicitlyDisabledDNSPrefetch;
   1271     bool m_frameElementsShouldIgnoreScrolling;
   1272     bool m_containsValidityStyleRules;
   1273     bool m_updateFocusAppearanceRestoresSelection;
   1274 
   1275     // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
   1276     unsigned m_ignoreDestructiveWriteCount;
   1277 
   1278     StringWithDirection m_title;
   1279     StringWithDirection m_rawTitle;
   1280     bool m_titleSetExplicitly;
   1281     RefPtr<Element> m_titleElement;
   1282 
   1283     OwnPtr<RenderArena> m_renderArena;
   1284 
   1285 #if !PLATFORM(ANDROID)
   1286     mutable AXObjectCache* m_axObjectCache;
   1287 #endif
   1288     OwnPtr<DocumentMarkerController> m_markers;
   1289 
   1290     Timer<Document> m_updateFocusAppearanceTimer;
   1291 
   1292     Element* m_cssTarget;
   1293 
   1294     bool m_processingLoadEvent;
   1295     RefPtr<SerializedScriptValue> m_pendingStateObject;
   1296     double m_startTime;
   1297     bool m_overMinimumLayoutThreshold;
   1298     // This is used to increase the minimum delay between re-layouts. It is set
   1299     // using setExtraLayoutDelay to modify the minimum delay used at different
   1300     // points during the lifetime of the Document.
   1301     int m_extraLayoutDelay;
   1302 
   1303     OwnPtr<ScriptRunner> m_scriptRunner;
   1304 
   1305 #if ENABLE(XSLT)
   1306     OwnPtr<TransformSource> m_transformSource;
   1307     RefPtr<Document> m_transformSourceDocument;
   1308 #endif
   1309 
   1310     int m_docID; // A unique document identifier used for things like document-specific mapped attributes.
   1311 
   1312     String m_xmlEncoding;
   1313     String m_xmlVersion;
   1314     bool m_xmlStandalone;
   1315 
   1316     String m_contentLanguage;
   1317 
   1318 #if ENABLE(XHTMLMP)
   1319     bool m_shouldProcessNoScriptElement;
   1320 #endif
   1321 
   1322     RenderObject* m_savedRenderer;
   1323 
   1324     RefPtr<TextResourceDecoder> m_decoder;
   1325 
   1326     InheritedBool m_designMode;
   1327 
   1328     CheckedRadioButtons m_checkedRadioButtons;
   1329 
   1330     typedef HashMap<AtomicStringImpl*, CollectionCache*> NamedCollectionMap;
   1331     FixedArray<CollectionCache, NumUnnamedDocumentCachedTypes> m_collectionInfo;
   1332     FixedArray<NamedCollectionMap, NumNamedDocumentCachedTypes> m_nameCollectionInfo;
   1333 
   1334 #if ENABLE(XPATH)
   1335     RefPtr<XPathEvaluator> m_xpathEvaluator;
   1336 #endif
   1337 
   1338 #if ENABLE(SVG)
   1339     OwnPtr<SVGDocumentExtensions> m_svgExtensions;
   1340 #endif
   1341 
   1342 #if ENABLE(DASHBOARD_SUPPORT)
   1343     Vector<DashboardRegionValue> m_dashboardRegions;
   1344     bool m_hasDashboardRegions;
   1345     bool m_dashboardRegionsDirty;
   1346 #endif
   1347 
   1348     HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
   1349 
   1350     bool m_createRenderers;
   1351     bool m_inPageCache;
   1352     String m_iconURL;
   1353 
   1354     HashSet<Element*> m_documentActivationCallbackElements;
   1355     HashSet<Element*> m_mediaVolumeCallbackElements;
   1356     HashSet<Element*> m_privateBrowsingStateChangedElements;
   1357 
   1358     bool m_useSecureKeyboardEntryWhenActive;
   1359 
   1360     bool m_isXHTML;
   1361     bool m_isHTML;
   1362 
   1363     bool m_usesViewSourceStyles;
   1364     bool m_sawElementsInKnownNamespaces;
   1365 
   1366     bool m_usingGeolocation;
   1367 
   1368     RefPtr<EventQueue> m_eventQueue;
   1369 
   1370 #if ENABLE(WML)
   1371     bool m_containsWMLContent;
   1372 #endif
   1373 
   1374     RefPtr<DocumentWeakReference> m_weakReference;
   1375 
   1376     HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
   1377 
   1378     QualifiedName m_idAttributeName;
   1379 
   1380 #if ENABLE(FULLSCREEN_API)
   1381     bool m_areKeysEnabledInFullScreen;
   1382     RefPtr<Element> m_fullScreenElement;
   1383     RenderFullScreen* m_fullScreenRenderer;
   1384     Timer<Document> m_fullScreenChangeDelayTimer;
   1385 #endif
   1386 
   1387     int m_loadEventDelayCount;
   1388     Timer<Document> m_loadEventDelayTimer;
   1389 
   1390     ViewportArguments m_viewportArguments;
   1391 
   1392     bool m_directionSetOnDocumentElement;
   1393     bool m_writingModeSetOnDocumentElement;
   1394 
   1395     DocumentTiming m_documentTiming;
   1396     RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
   1397     bool m_writeRecursionIsTooDeep;
   1398     unsigned m_writeRecursionDepth;
   1399 
   1400 #if ENABLE(REQUEST_ANIMATION_FRAME)
   1401     OwnPtr<ScriptedAnimationController> m_scriptedAnimationController;
   1402 #endif
   1403 
   1404     RefPtr<ContentSecurityPolicy> m_contentSecurityPolicy;
   1405 };
   1406 
   1407 // Put these methods here, because they require the Document definition, but we really want to inline them.
   1408 
   1409 inline bool Node::isDocumentNode() const
   1410 {
   1411     return this == m_document;
   1412 }
   1413 
   1414 inline Node::Node(Document* document, ConstructionType type)
   1415     : m_document(document)
   1416     , m_previous(0)
   1417     , m_next(0)
   1418     , m_renderer(0)
   1419     , m_nodeFlags(type)
   1420 {
   1421     if (m_document)
   1422         m_document->guardRef();
   1423 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
   1424     trackForDebugging();
   1425 #endif
   1426 }
   1427 
   1428 } // namespace WebCore
   1429 
   1430 #endif // Document_h
   1431