OSDN Git Service

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