OSDN Git Service

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