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