OSDN Git Service

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