• 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     void setDocType(PassRefPtr<DocumentType>);
909 
910 #if ENABLE(XPATH)
911     // XPathEvaluator methods
912     PassRefPtr<XPathExpression> createExpression(const String& expression,
913                                                  XPathNSResolver* resolver,
914                                                  ExceptionCode& ec);
915     PassRefPtr<XPathNSResolver> createNSResolver(Node *nodeResolver);
916     PassRefPtr<XPathResult> evaluate(const String& expression,
917                                      Node* contextNode,
918                                      XPathNSResolver* resolver,
919                                      unsigned short type,
920                                      XPathResult* result,
921                                      ExceptionCode& ec);
922 #endif // ENABLE(XPATH)
923 
924     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
925 
didLayoutWithPendingStylesheets()926     bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
927 
setHasNodesWithPlaceholderStyle()928     void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
929 
iconURL()930     const String& iconURL() const { return m_iconURL; }
931     void setIconURL(const String& iconURL, const String& type);
932 
933     void setUseSecureKeyboardEntryWhenActive(bool);
934     bool useSecureKeyboardEntryWhenActive() const;
935 
936     void updateFocusAppearanceSoon(bool restorePreviousSelection);
937     void cancelFocusAppearanceUpdate();
938 
939     // FF method for accessing the selection added for compatibility.
940     DOMSelection* getSelection() const;
941 
942     // Extension for manipulating canvas drawing contexts for use in CSS
943     CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
944     HTMLCanvasElement* getCSSCanvasElement(const String& name);
945 
isDNSPrefetchEnabled()946     bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
947     void parseDNSPrefetchControlHeader(const String&);
948 
949     virtual void addMessage(MessageSource, MessageType, MessageLevel, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>);
950     virtual void postTask(PassOwnPtr<Task>); // Executes the task on context's thread asynchronously.
951 
952     virtual void suspendScriptedAnimationControllerCallbacks();
953     virtual void resumeScriptedAnimationControllerCallbacks();
954 
955     virtual void finishedParsing();
956 
inPageCache()957     bool inPageCache() const { return m_inPageCache; }
958     void setInPageCache(bool flag);
959 
960     // Elements can register themselves for the "documentWillBecomeInactive()" and
961     // "documentDidBecomeActive()" callbacks
962     void registerForDocumentActivationCallbacks(Element*);
963     void unregisterForDocumentActivationCallbacks(Element*);
964     void documentWillBecomeInactive();
965     void documentDidBecomeActive();
966 
967     void registerForMediaVolumeCallbacks(Element*);
968     void unregisterForMediaVolumeCallbacks(Element*);
969     void mediaVolumeDidChange();
970 
971     void registerForPrivateBrowsingStateChangedCallbacks(Element*);
972     void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
973     void privateBrowsingStateDidChange();
974 
975     void setShouldCreateRenderers(bool);
976     bool shouldCreateRenderers();
977 
978     void setDecoder(PassRefPtr<TextResourceDecoder>);
decoder()979     TextResourceDecoder* decoder() const { return m_decoder.get(); }
980 
981     String displayStringModifiedByEncoding(const String&) const;
982     PassRefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
983     void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const;
984 
985     // Quirk for the benefit of Apple's Dictionary application.
setFrameElementsShouldIgnoreScrolling(bool ignore)986     void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
frameElementsShouldIgnoreScrolling()987     bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
988 
989 #if ENABLE(DASHBOARD_SUPPORT)
setDashboardRegionsDirty(bool f)990     void setDashboardRegionsDirty(bool f) { m_dashboardRegionsDirty = f; }
dashboardRegionsDirty()991     bool dashboardRegionsDirty() const { return m_dashboardRegionsDirty; }
hasDashboardRegions()992     bool hasDashboardRegions () const { return m_hasDashboardRegions; }
setHasDashboardRegions(bool f)993     void setHasDashboardRegions(bool f) { m_hasDashboardRegions = f; }
994     const Vector<DashboardRegionValue>& dashboardRegions() const;
995     void setDashboardRegions(const Vector<DashboardRegionValue>&);
996 #endif
997 
998     virtual void removeAllEventListeners();
999 
checkedRadioButtons()1000     CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
1001 
1002 #if ENABLE(SVG)
1003     const SVGDocumentExtensions* svgExtensions();
1004     SVGDocumentExtensions* accessSVGExtensions();
1005 #endif
1006 
1007     void initSecurityContext();
1008 
1009     // Explicitly override the security origin for this document.
1010     // Note: It is dangerous to change the security origin of a document
1011     //       that already contains content.
1012     void setSecurityOrigin(SecurityOrigin*);
1013 
1014     void updateURLForPushOrReplaceState(const KURL&);
1015     void statePopped(SerializedScriptValue*);
1016 
processingLoadEvent()1017     bool processingLoadEvent() const { return m_processingLoadEvent; }
1018 
1019 #if ENABLE(DATABASE)
1020     virtual bool allowDatabaseAccess() const;
1021     virtual void databaseExceededQuota(const String& name);
1022 #endif
1023 
1024     virtual bool isContextThread() const;
isJSExecutionForbidden()1025     virtual bool isJSExecutionForbidden() const { return false; }
1026 
setUsingGeolocation(bool f)1027     void setUsingGeolocation(bool f) { m_usingGeolocation = f; }
usingGeolocation()1028     bool usingGeolocation() const { return m_usingGeolocation; };
1029 
1030 #if ENABLE(WML)
setContainsWMLContent(bool value)1031     void setContainsWMLContent(bool value) { m_containsWMLContent = value; }
containsWMLContent()1032     bool containsWMLContent() const { return m_containsWMLContent; }
1033 
1034     void resetWMLPageState();
1035     void initializeWMLPageState();
1036 #endif
1037 
containsValidityStyleRules()1038     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
setContainsValidityStyleRules()1039     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
1040 
1041     void enqueueWindowEvent(PassRefPtr<Event>);
1042     void enqueueDocumentEvent(PassRefPtr<Event>);
1043     void enqueuePageshowEvent(PageshowEventPersistence);
1044     void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1045     void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
eventQueue()1046     EventQueue* eventQueue() const { return m_eventQueue.get(); }
1047 
1048     void addMediaCanStartListener(MediaCanStartListener*);
1049     void removeMediaCanStartListener(MediaCanStartListener*);
1050     MediaCanStartListener* takeAnyMediaCanStartListener();
1051 
idAttributeName()1052     const QualifiedName& idAttributeName() const { return m_idAttributeName; }
1053 
1054 #if ENABLE(FULLSCREEN_API)
webkitIsFullScreen()1055     bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
webkitFullScreenKeyboardInputAllowed()1056     bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
webkitCurrentFullScreenElement()1057     Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
1058     void webkitRequestFullScreenForElement(Element*, unsigned short flags);
1059     void webkitCancelFullScreen();
1060 
1061     void webkitWillEnterFullScreenForElement(Element*);
1062     void webkitDidEnterFullScreenForElement(Element*);
1063     void webkitWillExitFullScreenForElement(Element*);
1064     void webkitDidExitFullScreenForElement(Element*);
1065 
1066     void setFullScreenRenderer(RenderFullScreen*);
fullScreenRenderer()1067     RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
1068 
1069     void setFullScreenRendererSize(const IntSize&);
1070     void setFullScreenRendererBackgroundColor(Color);
1071 
1072     void fullScreenChangeDelayTimerFired(Timer<Document>*);
1073     bool fullScreenIsAllowedForElement(Element*) const;
1074 #endif
1075 
1076     // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
incrementLoadEventDelayCount()1077     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1078     void decrementLoadEventDelayCount();
isDelayingLoadEvent()1079     bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1080 
1081 #if ENABLE(TOUCH_EVENTS)
1082     PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, ExceptionCode&) const;
1083 #endif
1084 
timing()1085     const DocumentTiming* timing() const { return &m_documentTiming; }
1086 
1087 #if ENABLE(REQUEST_ANIMATION_FRAME)
1088     int webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>, Element*);
1089     void webkitCancelRequestAnimationFrame(int id);
1090     void serviceScriptedAnimations(DOMTimeStamp);
1091 #endif
1092 
1093     virtual EventTarget* errorEventTarget();
1094     virtual void logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack>);
1095 
1096     void initDNSPrefetch();
1097 
contentSecurityPolicy()1098     ContentSecurityPolicy* contentSecurityPolicy() { return m_contentSecurityPolicy.get(); }
1099 
1100 protected:
1101     Document(Frame*, const KURL&, bool isXHTML, bool isHTML);
1102 
clearXMLVersion()1103     void clearXMLVersion() { m_xmlVersion = String(); }
1104 
1105 
1106 private:
1107     friend class IgnoreDestructiveWriteCountIncrementer;
1108 
1109     void detachParser();
1110 
1111     typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
1112     void processArguments(const String& features, void* data, ArgumentsCallback);
1113 
isDocument()1114     virtual bool isDocument() const { return true; }
1115 
1116     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
1117 
1118     virtual String nodeName() const;
1119     virtual NodeType nodeType() const;
1120     virtual bool childTypeAllowed(NodeType) const;
1121     virtual PassRefPtr<Node> cloneNode(bool deep);
1122     virtual bool canReplaceChild(Node* newChild, Node* oldChild);
1123 
refScriptExecutionContext()1124     virtual void refScriptExecutionContext() { ref(); }
derefScriptExecutionContext()1125     virtual void derefScriptExecutionContext() { deref(); }
1126 
1127     virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
1128     virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
1129 
1130     virtual double minimumTimerInterval() const;
1131 
1132     String encoding() const;
1133 
1134     void updateTitle(const StringWithDirection&);
1135     void updateFocusAppearanceTimerFired(Timer<Document>*);
1136     void updateBaseURL();
1137 
1138     void cacheDocumentElement() const;
1139 
1140     void createStyleSelector();
1141 
1142     void deleteRetiredCustomFonts();
1143 
1144     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
1145 
1146     void loadEventDelayTimerFired(Timer<Document>*);
1147 
1148     int m_guardRefCount;
1149 
1150     OwnPtr<CSSStyleSelector> m_styleSelector;
1151     bool m_didCalculateStyleSelector;
1152     bool m_hasDirtyStyleSelector;
1153     Vector<OwnPtr<FontData> > m_retiredCustomFonts;
1154 
1155     mutable RefPtr<CSSPrimitiveValueCache> m_cssPrimitiveValueCache;
1156 
1157     Frame* m_frame;
1158     OwnPtr<CachedResourceLoader> m_cachedResourceLoader;
1159     RefPtr<DocumentParser> m_parser;
1160     bool m_wellFormed;
1161 
1162     // Document URLs.
1163     KURL m_url; // Document.URL: The URL from which this document was retrieved.
1164     KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1165     KURL m_baseElementURL; // The URL set by the <base> element.
1166     KURL m_cookieURL; // The URL to use for cookie access.
1167     KURL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1168 
1169     // Document.documentURI:
1170     // Although URL-like, Document.documentURI can actually be set to any
1171     // string by content.  Document.documentURI affects m_baseURL unless the
1172     // document contains a <base> element, in which case the <base> element
1173     // takes precedence.
1174     String m_documentURI;
1175 
1176     String m_baseTarget;
1177 
1178     RefPtr<DocumentType> m_docType;
1179     mutable RefPtr<DOMImplementation> m_implementation;
1180 
1181     // Track the number of currently loading top-level stylesheets needed for rendering.
1182     // Sheets loaded using the @import directive are not included in this count.
1183     // We use this count of pending sheets to detect when we can begin attaching
1184     // elements and when it is safe to execute scripts.
1185     int m_pendingStylesheets;
1186 
1187     // But sometimes you need to ignore pending stylesheet count to
1188     // force an immediate layout when requested by JS.
1189     bool m_ignorePendingStylesheets;
1190 
1191     // If we do ignore the pending stylesheet count, then we need to add a boolean
1192     // to track that this happened so that we can do a full repaint when the stylesheets
1193     // do eventually load.
1194     PendingSheetLayout m_pendingSheetLayout;
1195 
1196     bool m_hasNodesWithPlaceholderStyle;
1197 
1198     RefPtr<CSSStyleSheet> m_elemSheet;
1199     RefPtr<CSSStyleSheet> m_mappedElementSheet;
1200     RefPtr<CSSStyleSheet> m_pageUserSheet;
1201     mutable OwnPtr<Vector<RefPtr<CSSStyleSheet> > > m_pageGroupUserSheets;
1202     mutable bool m_pageGroupUserSheetCacheValid;
1203 
1204     bool m_printing;
1205     bool m_paginatedForScreen;
1206 
1207     bool m_ignoreAutofocus;
1208 
1209     CompatibilityMode m_compatibilityMode;
1210     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1211 
1212     Color m_textColor;
1213 
1214     RefPtr<Node> m_focusedNode;
1215     RefPtr<Node> m_hoverNode;
1216     RefPtr<Node> m_activeNode;
1217     mutable RefPtr<Element> m_documentElement;
1218 
1219     uint64_t m_domTreeVersion;
1220     static uint64_t s_globalTreeVersion;
1221 
1222     HashSet<NodeIterator*> m_nodeIterators;
1223     HashSet<Range*> m_ranges;
1224 
1225     unsigned short m_listenerTypes;
1226 
1227     RefPtr<StyleSheetList> m_styleSheets; // All of the stylesheets that are currently in effect for our media type and stylesheet set.
1228 
1229     typedef ListHashSet<Node*, 32> StyleSheetCandidateListHashSet;
1230     StyleSheetCandidateListHashSet m_styleSheetCandidateNodes; // All of the nodes that could potentially provide stylesheets to the document (<link>, <style>, <?xml-stylesheet>)
1231 
1232     typedef ListHashSet<Element*, 64> FormElementListHashSet;
1233     FormElementListHashSet m_formElementsWithState;
1234     typedef ListHashSet<FormAssociatedElement*, 32> FormAssociatedElementListHashSet;
1235     FormAssociatedElementListHashSet m_formElementsWithFormAttribute;
1236 
1237     typedef HashMap<FormElementKey, Vector<String>, FormElementKeyHash, FormElementKeyHashTraits> FormElementStateMap;
1238     FormElementStateMap m_stateForNewFormElements;
1239 
1240     Color m_linkColor;
1241     Color m_visitedLinkColor;
1242     Color m_activeLinkColor;
1243 
1244     String m_preferredStylesheetSet;
1245     String m_selectedStylesheetSet;
1246 
1247     bool m_loadingSheet;
1248     bool m_visuallyOrdered;
1249     ReadyState m_readyState;
1250     bool m_bParsing;
1251 
1252     Timer<Document> m_styleRecalcTimer;
1253     bool m_pendingStyleRecalcShouldForce;
1254     bool m_inStyleRecalc;
1255     bool m_closeAfterStyleRecalc;
1256 
1257     bool m_usesSiblingRules;
1258     bool m_usesSiblingRulesOverride;
1259     bool m_usesFirstLineRules;
1260     bool m_usesFirstLetterRules;
1261     bool m_usesBeforeAfterRules;
1262     bool m_usesBeforeAfterRulesOverride;
1263     bool m_usesRemUnits;
1264     bool m_usesLinkRules;
1265     bool m_gotoAnchorNeededAfterStylesheetsLoad;
1266     bool m_isDNSPrefetchEnabled;
1267     bool m_haveExplicitlyDisabledDNSPrefetch;
1268     bool m_frameElementsShouldIgnoreScrolling;
1269     bool m_containsValidityStyleRules;
1270     bool m_updateFocusAppearanceRestoresSelection;
1271 
1272     // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1273     unsigned m_ignoreDestructiveWriteCount;
1274 
1275     StringWithDirection m_title;
1276     StringWithDirection m_rawTitle;
1277     bool m_titleSetExplicitly;
1278     RefPtr<Element> m_titleElement;
1279 
1280     OwnPtr<RenderArena> m_renderArena;
1281 
1282 #if !PLATFORM(ANDROID)
1283     mutable AXObjectCache* m_axObjectCache;
1284 #endif
1285     OwnPtr<DocumentMarkerController> m_markers;
1286 
1287     Timer<Document> m_updateFocusAppearanceTimer;
1288 
1289     Element* m_cssTarget;
1290 
1291     bool m_processingLoadEvent;
1292     RefPtr<SerializedScriptValue> m_pendingStateObject;
1293     double m_startTime;
1294     bool m_overMinimumLayoutThreshold;
1295     // This is used to increase the minimum delay between re-layouts. It is set
1296     // using setExtraLayoutDelay to modify the minimum delay used at different
1297     // points during the lifetime of the Document.
1298     int m_extraLayoutDelay;
1299 
1300     OwnPtr<ScriptRunner> m_scriptRunner;
1301 
1302 #if ENABLE(XSLT)
1303     OwnPtr<TransformSource> m_transformSource;
1304     RefPtr<Document> m_transformSourceDocument;
1305 #endif
1306 
1307     int m_docID; // A unique document identifier used for things like document-specific mapped attributes.
1308 
1309     String m_xmlEncoding;
1310     String m_xmlVersion;
1311     bool m_xmlStandalone;
1312 
1313     String m_contentLanguage;
1314 
1315 #if ENABLE(XHTMLMP)
1316     bool m_shouldProcessNoScriptElement;
1317 #endif
1318 
1319     RenderObject* m_savedRenderer;
1320 
1321     RefPtr<TextResourceDecoder> m_decoder;
1322 
1323     InheritedBool m_designMode;
1324 
1325     CheckedRadioButtons m_checkedRadioButtons;
1326 
1327     typedef HashMap<AtomicStringImpl*, CollectionCache*> NamedCollectionMap;
1328     FixedArray<CollectionCache, NumUnnamedDocumentCachedTypes> m_collectionInfo;
1329     FixedArray<NamedCollectionMap, NumNamedDocumentCachedTypes> m_nameCollectionInfo;
1330 
1331 #if ENABLE(XPATH)
1332     RefPtr<XPathEvaluator> m_xpathEvaluator;
1333 #endif
1334 
1335 #if ENABLE(SVG)
1336     OwnPtr<SVGDocumentExtensions> m_svgExtensions;
1337 #endif
1338 
1339 #if ENABLE(DASHBOARD_SUPPORT)
1340     Vector<DashboardRegionValue> m_dashboardRegions;
1341     bool m_hasDashboardRegions;
1342     bool m_dashboardRegionsDirty;
1343 #endif
1344 
1345     HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
1346 
1347     bool m_createRenderers;
1348     bool m_inPageCache;
1349     String m_iconURL;
1350 
1351     HashSet<Element*> m_documentActivationCallbackElements;
1352     HashSet<Element*> m_mediaVolumeCallbackElements;
1353     HashSet<Element*> m_privateBrowsingStateChangedElements;
1354 
1355     bool m_useSecureKeyboardEntryWhenActive;
1356 
1357     bool m_isXHTML;
1358     bool m_isHTML;
1359 
1360     bool m_usesViewSourceStyles;
1361     bool m_sawElementsInKnownNamespaces;
1362 
1363     bool m_usingGeolocation;
1364 
1365     RefPtr<EventQueue> m_eventQueue;
1366 
1367 #if ENABLE(WML)
1368     bool m_containsWMLContent;
1369 #endif
1370 
1371     RefPtr<DocumentWeakReference> m_weakReference;
1372 
1373     HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1374 
1375     QualifiedName m_idAttributeName;
1376 
1377 #if ENABLE(FULLSCREEN_API)
1378     bool m_areKeysEnabledInFullScreen;
1379     RefPtr<Element> m_fullScreenElement;
1380     RenderFullScreen* m_fullScreenRenderer;
1381     Timer<Document> m_fullScreenChangeDelayTimer;
1382 #endif
1383 
1384     int m_loadEventDelayCount;
1385     Timer<Document> m_loadEventDelayTimer;
1386 
1387     ViewportArguments m_viewportArguments;
1388 
1389     bool m_directionSetOnDocumentElement;
1390     bool m_writingModeSetOnDocumentElement;
1391 
1392     DocumentTiming m_documentTiming;
1393     RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1394     bool m_writeRecursionIsTooDeep;
1395     unsigned m_writeRecursionDepth;
1396 
1397 #if ENABLE(REQUEST_ANIMATION_FRAME)
1398     OwnPtr<ScriptedAnimationController> m_scriptedAnimationController;
1399 #endif
1400 
1401     RefPtr<ContentSecurityPolicy> m_contentSecurityPolicy;
1402 };
1403 
1404 // Put these methods here, because they require the Document definition, but we really want to inline them.
1405 
isDocumentNode()1406 inline bool Node::isDocumentNode() const
1407 {
1408     return this == m_document;
1409 }
1410 
Node(Document * document,ConstructionType type)1411 inline Node::Node(Document* document, ConstructionType type)
1412     : m_document(document)
1413     , m_previous(0)
1414     , m_next(0)
1415     , m_renderer(0)
1416     , m_nodeFlags(type)
1417 {
1418     if (m_document)
1419         m_document->guardRef();
1420 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
1421     trackForDebugging();
1422 #endif
1423 }
1424 
1425 } // namespace WebCore
1426 
1427 #endif // Document_h
1428