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