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