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