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-2010, 2012-2013, 2015 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 "CollectionType.h"
32#include "Color.h"
33#include "ContainerNode.h"
34#include "DocumentEventQueue.h"
35#include "DocumentTiming.h"
36#include "FocusDirection.h"
37#include "FontSelector.h"
38#include "MediaProducer.h"
39#include "MutationObserver.h"
40#include "PageVisibilityState.h"
41#include "PlatformEvent.h"
42#include "PlatformScreen.h"
43#include "ReferrerPolicy.h"
44#include "Region.h"
45#include "RenderPtr.h"
46#include "ScriptExecutionContext.h"
47#include "StringWithDirection.h"
48#include "StyleChange.h"
49#include "TextResourceDecoder.h"
50#include "Timer.h"
51#include "TreeScope.h"
52#include "UserActionElementSet.h"
53#include "ViewportArguments.h"
54#include <chrono>
55#include <memory>
56#include <wtf/Deque.h>
57#include <wtf/HashSet.h>
58#include <wtf/PassRefPtr.h>
59#include <wtf/WeakPtr.h>
60
61namespace JSC {
62class ExecState;
63#if ENABLE(WEB_REPLAY)
64class InputCursor;
65#endif
66}
67
68namespace WebCore {
69
70class AXObjectCache;
71class Attr;
72class AuthorStyleSheets;
73class CDATASection;
74class CSSFontSelector;
75class CSSStyleDeclaration;
76class CSSStyleSheet;
77class CachedCSSStyleSheet;
78class CachedResourceLoader;
79class CachedScript;
80class CanvasRenderingContext;
81class CharacterData;
82class Comment;
83class DOMImplementation;
84class DOMNamedFlowCollection;
85class DOMSelection;
86class DOMWindow;
87class DOMWrapperWorld;
88class Database;
89class DatabaseThread;
90class DocumentFragment;
91class DocumentLoader;
92class DocumentMarkerController;
93class DocumentParser;
94class DocumentSharedObjectPool;
95class DocumentType;
96class Element;
97class EntityReference;
98class Event;
99class EventListener;
100class ExtensionStyleSheets;
101class FloatRect;
102class FloatQuad;
103class FormController;
104class Frame;
105class FrameView;
106class HTMLAllCollection;
107class HTMLBodyElement;
108class HTMLCanvasElement;
109class HTMLCollection;
110class HTMLDocument;
111class HTMLElement;
112class HTMLFrameOwnerElement;
113class HTMLHeadElement;
114class HTMLIFrameElement;
115class HTMLImageElement;
116class HTMLMapElement;
117class HTMLMediaElement;
118class HTMLPictureElement;
119class HTMLScriptElement;
120class HitTestRequest;
121class HitTestResult;
122class IntPoint;
123class LayoutPoint;
124class LayoutRect;
125class LiveNodeList;
126class JSModuleLoader;
127class JSNode;
128class Locale;
129class Location;
130class MediaCanStartListener;
131class MediaPlaybackTarget;
132class MediaPlaybackTargetClient;
133class MediaQueryList;
134class MediaQueryMatcher;
135class MouseEventWithHitTestResults;
136class NamedFlowCollection;
137class NodeFilter;
138class NodeIterator;
139class Page;
140class PlatformMouseEvent;
141class ProcessingInstruction;
142class QualifiedName;
143class Range;
144class RegisteredEventListener;
145class RenderView;
146class RenderFullScreen;
147class ScriptableDocumentParser;
148class ScriptElementData;
149class ScriptRunner;
150class SecurityOrigin;
151class SelectorQuery;
152class SelectorQueryCache;
153class SerializedScriptValue;
154class SegmentedString;
155class Settings;
156class StyleResolver;
157class StyleSheet;
158class StyleSheetContents;
159class StyleSheetList;
160class SVGDocumentExtensions;
161class Text;
162class TextResourceDecoder;
163class TreeWalker;
164class VisitedLinkState;
165class WebKitNamedFlow;
166class XMLHttpRequest;
167class XPathEvaluator;
168class XPathExpression;
169class XPathNSResolver;
170class XPathResult;
171
172enum class ShouldOpenExternalURLsPolicy;
173
174#if ENABLE(XSLT)
175class TransformSource;
176#endif
177
178#if ENABLE(CUSTOM_ELEMENTS)
179class CustomElementDefinitions;
180#endif
181
182#if ENABLE(DASHBOARD_SUPPORT)
183struct AnnotatedRegionValue;
184#endif
185
186#if ENABLE(IOS_TOUCH_EVENTS)
187#include <WebKitAdditions/DocumentIOSForward.h>
188#endif
189
190#if ENABLE(TOUCH_EVENTS) || ENABLE(IOS_TOUCH_EVENTS)
191class Touch;
192class TouchList;
193#endif
194
195#if ENABLE(REQUEST_ANIMATION_FRAME)
196class RequestAnimationFrameCallback;
197class ScriptedAnimationController;
198#endif
199
200#if ENABLE(TEXT_AUTOSIZING)
201class TextAutosizer;
202#endif
203
204#if ENABLE(FONT_LOAD_EVENTS)
205class FontLoader;
206#endif
207
208typedef int ExceptionCode;
209
210#if PLATFORM(IOS)
211class DeviceMotionClient;
212class DeviceMotionController;
213class DeviceOrientationClient;
214class DeviceOrientationController;
215#endif
216
217#if ENABLE(IOS_TEXT_AUTOSIZING)
218struct TextAutoSizingHash;
219class TextAutoSizingKey;
220class TextAutoSizingValue;
221
222struct TextAutoSizingTraits : WTF::GenericHashTraits<TextAutoSizingKey> {
223 static const bool emptyValueIsZero = true;
224 static void constructDeletedValue(TextAutoSizingKey& slot);
225 static bool isDeletedValue(const TextAutoSizingKey& value);
226};
227#endif
228
229#if ENABLE(MEDIA_SESSION)
230class MediaSession;
231#endif
232
233const uint64_t HTMLMediaElementInvalidID = 0;
234
235enum PageshowEventPersistence {
236 PageshowEventNotPersisted = 0,
237 PageshowEventPersisted = 1
238};
239
240enum StyleResolverUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle, RecalcStyleIfNeeded, DeferRecalcStyleIfNeeded };
241
242enum NodeListInvalidationType {
243 DoNotInvalidateOnAttributeChanges = 0,
244 InvalidateOnClassAttrChange,
245 InvalidateOnIdNameAttrChange,
246 InvalidateOnNameAttrChange,
247 InvalidateOnForAttrChange,
248 InvalidateForFormControls,
249 InvalidateOnHRefAttrChange,
250 InvalidateOnAnyAttrChange,
251};
252const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
253
254enum class EventHandlerRemoval { One, All };
255typedef HashCountedSet<Node*> EventTargetSet;
256
257enum DocumentClass {
258 DefaultDocumentClass = 0,
259 HTMLDocumentClass = 1,
260 XHTMLDocumentClass = 1 << 1,
261 ImageDocumentClass = 1 << 2,
262 PluginDocumentClass = 1 << 3,
263 MediaDocumentClass = 1 << 4,
264 SVGDocumentClass = 1 << 5,
265 TextDocumentClass = 1 << 6,
266 XMLDocumentClass = 1 << 7,
267};
268
269typedef unsigned char DocumentClassFlags;
270
271enum class DocumentCompatibilityMode : unsigned char {
272 NoQuirksMode = 1,
273 QuirksMode = 1 << 1,
274 LimitedQuirksMode = 1 << 2
275};
276
277enum DimensionsCheck { WidthDimensionsCheck = 1 << 0, HeightDimensionsCheck = 1 << 1, AllDimensionsCheck = 1 << 2 };
278
279enum class SelectionRestorationMode {
280 Restore,
281 SetDefault,
282};
283
284enum class SelectionRevealMode {
285 Reveal,
286 DoNotReveal
287};
288
289enum class HttpEquivPolicy {
290 Enabled,
291 DisabledBySettings,
292 DisabledByContentDispositionAttachmentSandbox
293};
294
295class Document : public ContainerNode, public TreeScope, public ScriptExecutionContext, public FontSelectorClient {
296public:
297 static Ref<Document> create(Frame* frame, const URL& url)
298 {
299 return adoptRef(*new Document(frame, url));
300 }
301
302 static Ref<Document> createNonRenderedPlaceholder(Frame* frame, const URL& url)
303 {
304 return adoptRef(*new Document(frame, url, DefaultDocumentClass, NonRenderedPlaceholder));
305 }
306 static Ref<Document> create(ScriptExecutionContext&);
307
308 virtual ~Document();
309
310 // Nodes belonging to this document increase referencingNodeCount -
311 // these are enough to keep the document from being destroyed, but
312 // not enough to keep it from removing its children. This allows a
313 // node that outlives its document to still have a valid document
314 // pointer without introducing reference cycles.
315 void incrementReferencingNodeCount()
316 {
317 ASSERT(!m_deletionHasBegun);
318 ++m_referencingNodeCount;
319 }
320
321 void decrementReferencingNodeCount()
322 {
323 ASSERT(!m_deletionHasBegun || !m_referencingNodeCount);
324 --m_referencingNodeCount;
325 if (!m_referencingNodeCount && !refCount()) {
326#if !ASSERT_DISABLED
327 m_deletionHasBegun = true;
328#endif
329 delete this;
330 }
331 }
332
333 unsigned referencingNodeCount() const { return m_referencingNodeCount; }
334
335 void removedLastRef();
336
337 WEBCORE_EXPORT static HashSet<Document*>& allDocuments();
338
339 MediaQueryMatcher& mediaQueryMatcher();
340
341 using ContainerNode::ref;
342 using ContainerNode::deref;
343
344 virtual bool canContainRangeEndPoint() const override final { return true; }
345
346 Element* getElementByAccessKey(const String& key);
347 void invalidateAccessKeyMap();
348
349 void addImageElementByCaseFoldedUsemap(const AtomicStringImpl&, HTMLImageElement&);
350 void removeImageElementByCaseFoldedUsemap(const AtomicStringImpl&, HTMLImageElement&);
351 HTMLImageElement* imageElementByCaseFoldedUsemap(const AtomicStringImpl&) const;
352
353 SelectorQuery* selectorQueryForString(const String&, ExceptionCode&);
354 void clearSelectorQueryCache();
355
356 // DOM methods & attributes for Document
357
358 void setViewportArguments(const ViewportArguments& viewportArguments) { m_viewportArguments = viewportArguments; }
359 ViewportArguments viewportArguments() const { return m_viewportArguments; }
360#ifndef NDEBUG
361 bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
362#endif
363
364 void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
365 ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
366
367 DocumentType* doctype() const;
368
369 DOMImplementation& implementation();
370
371 Element* documentElement() const
372 {
373 return m_documentElement.get();
374 }
375 static ptrdiff_t documentElementMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentElement); }
376
377 Element* activeElement();
378 bool hasFocus() const;
379
380 bool hasManifest() const;
381
382 WEBCORE_EXPORT RefPtr<Element> createElementForBindings(const AtomicString& tagName, ExceptionCode&);
383 WEBCORE_EXPORT Ref<DocumentFragment> createDocumentFragment();
384 WEBCORE_EXPORT Ref<Text> createTextNode(const String& data);
385 Ref<Comment> createComment(const String& data);
386 RefPtr<CDATASection> createCDATASection(const String& data, ExceptionCode&);
387 RefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionCode&);
388 RefPtr<Attr> createAttribute(const String& name, ExceptionCode&);
389 RefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&, bool shouldIgnoreNamespaceChecks = false);
390 RefPtr<EntityReference> createEntityReference(const String& name, ExceptionCode&);
391 RefPtr<Node> importNode(Node* importedNode, ExceptionCode& ec) { return importNode(importedNode, false, ec); }
392 RefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionCode&);
393 WEBCORE_EXPORT RefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&);
394 WEBCORE_EXPORT Ref<Element> createElement(const QualifiedName&, bool createdByParser);
395
396 bool cssRegionsEnabled() const;
397 bool cssCompositingEnabled() const;
398#if ENABLE(CSS_REGIONS)
399 RefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
400#endif
401
402 NamedFlowCollection& namedFlows();
403
404 Element* elementFromPoint(int x, int y) { return elementFromPoint(LayoutPoint(x, y)); }
405 Element* elementFromPoint(const LayoutPoint& clientPoint);
406
407 RefPtr<Range> caretRangeFromPoint(int x, int y);
408 RefPtr<Range> caretRangeFromPoint(const LayoutPoint& clientPoint);
409
410 Element* scrollingElement();
411
412 String readyState() const;
413
414 String defaultCharset() const;
415
416 String charset() const { return Document::encoding(); }
417 String characterSetWithUTF8Fallback() const;
418 TextEncoding textEncoding() const;
419
420 AtomicString encoding() const { return textEncoding().domName(); }
421
422 void setCharset(const String&); // Used by ObjC / GOBject bindings only.
423
424 void setContent(const String&);
425
426 String suggestedMIMEType() const;
427
428 void overrideMIMEType(const String&);
429 String contentType() const;
430
431 String contentLanguage() const { return m_contentLanguage; }
432 void setContentLanguage(const String&);
433
434 String xmlEncoding() const { return m_xmlEncoding; }
435 String xmlVersion() const { return m_xmlVersion; }
436 enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
437 bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
438 StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
439 bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
440
441 void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
442 void setXMLVersion(const String&, ExceptionCode&);
443 void setXMLStandalone(bool, ExceptionCode&);
444 void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
445
446 String documentURI() const { return m_documentURI; }
447 void setDocumentURI(const String&);
448
449#if ENABLE(WEB_REPLAY)
450 JSC::InputCursor& inputCursor() const { return *m_inputCursor; }
451 void setInputCursor(PassRefPtr<JSC::InputCursor>);
452#endif
453
454 void visibilityStateChanged();
455 String visibilityState() const;
456 bool hidden() const;
457
458 void setTimerThrottlingEnabled(bool);
459 bool isTimerThrottlingEnabled() const { return m_isTimerThrottlingEnabled; }
460
461 RefPtr<Node> adoptNode(Node* source, ExceptionCode&);
462
463 Ref<HTMLCollection> images();
464 Ref<HTMLCollection> embeds();
465 Ref<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
466 Ref<HTMLCollection> applets();
467 Ref<HTMLCollection> links();
468 Ref<HTMLCollection> forms();
469 Ref<HTMLCollection> anchors();
470 Ref<HTMLCollection> scripts();
471 Ref<HTMLCollection> all();
472
473 Ref<HTMLCollection> windowNamedItems(const AtomicString& name);
474 Ref<HTMLCollection> documentNamedItems(const AtomicString& name);
475
476 // Other methods (not part of DOM)
477 bool isSynthesized() const { return m_isSynthesized; }
478 bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
479 bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
480 bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
481 bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
482 bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
483 bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
484 bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
485 bool isTextDocument() const { return m_documentClasses & TextDocumentClass; }
486 bool hasSVGRootNode() const;
487 virtual bool isFrameSet() const { return false; }
488
489 static ptrdiff_t documentClassesMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentClasses); }
490 static uint32_t isHTMLDocumentClassFlag() { return HTMLDocumentClass; }
491
492 bool isSrcdocDocument() const { return m_isSrcdocDocument; }
493
494 StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
495
496 bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
497
498 StyleResolver& ensureStyleResolver()
499 {
500 if (!m_styleResolver)
501 createStyleResolver();
502 return *m_styleResolver;
503 }
504 StyleResolver& userAgentShadowTreeStyleResolver();
505
506 CSSFontSelector& fontSelector();
507
508 void notifyRemovePendingSheetIfNeeded();
509
510 WEBCORE_EXPORT bool haveStylesheetsLoaded() const;
511
512 // This is a DOM function.
513 StyleSheetList& styleSheets();
514
515 AuthorStyleSheets& authorStyleSheets() { return *m_authorStyleSheets; }
516 const AuthorStyleSheets& authorStyleSheets() const { return *m_authorStyleSheets; }
517 ExtensionStyleSheets& extensionStyleSheets() { return *m_extensionStyleSheets; }
518 const ExtensionStyleSheets& extensionStyleSheets() const { return *m_extensionStyleSheets; }
519
520 bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
521 void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
522
523 /**
524 * Called when one or more stylesheets in the document may have been added, removed or changed.
525 *
526 * Creates a new style resolver and assign it to this document. This is done by iterating through all nodes in
527 * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
528 * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
529 * constructed from these which is used to create the a new style selector which collates all of the stylesheets
530 * found and is used to calculate the derived styles for all rendering objects.
531 */
532 WEBCORE_EXPORT void styleResolverChanged(StyleResolverUpdateFlag);
533
534 void scheduleOptimizedStyleSheetUpdate();
535
536 void evaluateMediaQueryList();
537
538 FormController& formController();
539 Vector<String> formElementsState() const;
540 void setStateForNewFormElements(const Vector<String>&);
541
542 WEBCORE_EXPORT FrameView* view() const; // can be NULL
543 Frame* frame() const { return m_frame; } // can be NULL
544 WEBCORE_EXPORT Page* page() const; // can be NULL
545 WEBCORE_EXPORT Settings* settings() const; // can be NULL
546
547 float deviceScaleFactor() const;
548
549 WEBCORE_EXPORT Ref<Range> createRange();
550
551 RefPtr<NodeIterator> createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&&, bool, ExceptionCode&); // For ObjC bindings.
552 RefPtr<NodeIterator> createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&&, ExceptionCode&);
553 RefPtr<NodeIterator> createNodeIterator(Node* root, unsigned long whatToShow, ExceptionCode&);
554 RefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionCode&);
555
556 RefPtr<TreeWalker> createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&&, bool, ExceptionCode&); // For ObjC bindings.
557 RefPtr<TreeWalker> createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&&, ExceptionCode&);
558 RefPtr<TreeWalker> createTreeWalker(Node* root, unsigned long whatToShow, ExceptionCode&);
559 RefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionCode&);
560
561 // Special support for editing
562 Ref<CSSStyleDeclaration> createCSSStyleDeclaration();
563 Ref<Text> createEditingTextNode(const String&);
564
565 void recalcStyle(Style::Change = Style::NoChange);
566 WEBCORE_EXPORT void updateStyleIfNeeded();
567 bool needsStyleRecalc() const { return !inPageCache() && (m_pendingStyleRecalcShouldForce || childNeedsStyleRecalc() || m_optimizedStyleSheetUpdateTimer.isActive()); }
568
569 WEBCORE_EXPORT void updateLayout();
570
571 // updateLayoutIgnorePendingStylesheets() forces layout even if we are waiting for pending stylesheet loads,
572 // so calling this may cause a flash of unstyled content (FOUC).
573 enum class RunPostLayoutTasks {
574 Asynchronously,
575 Synchronously,
576 };
577 WEBCORE_EXPORT void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasks::Asynchronously);
578
579 Ref<RenderStyle> styleForElementIgnoringPendingStylesheets(Element&, RenderStyle* parentStyle);
580
581 // Returns true if page box (margin boxes and page borders) is visible.
582 WEBCORE_EXPORT bool isPageBoxVisible(int pageIndex);
583
584 // Returns the preferred page size and margins in pixels, assuming 96
585 // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
586 // marginLeft must be initialized to the default values that are used if
587 // auto is specified.
588 WEBCORE_EXPORT void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
589
590 CachedResourceLoader& cachedResourceLoader() { return m_cachedResourceLoader; }
591
592 void didBecomeCurrentDocumentInFrame();
593 void destroyRenderTree();
594 void disconnectFromFrame();
595 void prepareForDestruction();
596
597 // Override ScriptExecutionContext methods to do additional work
598 bool shouldBypassMainWorldContentSecurityPolicy() const override final;
599 virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) override final;
600 virtual void resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) override final;
601 virtual void stopActiveDOMObjects() override final;
602
603 void suspendDeviceMotionAndOrientationUpdates();
604 void resumeDeviceMotionAndOrientationUpdates();
605
606 RenderView* renderView() const { return m_renderView.get(); }
607
608 bool renderTreeBeingDestroyed() const { return m_renderTreeBeingDestroyed; }
609 bool hasLivingRenderTree() const { return renderView() && !renderTreeBeingDestroyed(); }
610
611 bool updateLayoutIfDimensionsOutOfDate(Element&, DimensionsCheck = AllDimensionsCheck);
612
613 AXObjectCache* existingAXObjectCache() const;
614 WEBCORE_EXPORT AXObjectCache* axObjectCache() const;
615 void clearAXObjectCache();
616
617 // to get visually ordered hebrew and arabic pages right
618 void setVisuallyOrdered();
619 bool visuallyOrdered() const { return m_visuallyOrdered; }
620
621 WEBCORE_EXPORT DocumentLoader* loader() const;
622
623 void open(Document* ownerDocument = nullptr);
624 void implicitOpen();
625
626 // close() is the DOM API document.close()
627 void close();
628 // In some situations (see the code), we ignore document.close().
629 // explicitClose() bypass these checks and actually tries to close the
630 // input stream.
631 void explicitClose();
632 // implicitClose() actually does the work of closing the input stream.
633 void implicitClose();
634
635 void cancelParsing();
636
637 void write(const SegmentedString& text, Document* ownerDocument = nullptr);
638 void write(const String& text, Document* ownerDocument = nullptr);
639 void writeln(const String& text, Document* ownerDocument = nullptr);
640
641 bool wellFormed() const { return m_wellFormed; }
642
643 virtual const URL& url() const override final { return m_url; }
644 void setURL(const URL&);
645 const URL& urlForBindings() const { return m_url.isEmpty() ? blankURL() : m_url; }
646
647 // To understand how these concepts relate to one another, please see the
648 // comments surrounding their declaration.
649 const URL& baseURL() const { return m_baseURL; }
650 void setBaseURLOverride(const URL&);
651 const URL& baseURLOverride() const { return m_baseURLOverride; }
652 const URL& baseElementURL() const { return m_baseElementURL; }
653 const String& baseTarget() const { return m_baseTarget; }
654 void processBaseElement();
655
656 WEBCORE_EXPORT virtual URL completeURL(const String&) const override final;
657 URL completeURL(const String&, const URL& baseURLOverride) const;
658
659 virtual String userAgent(const URL&) const override final;
660
661 virtual void disableEval(const String& errorMessage) override final;
662
663 bool canNavigate(Frame* targetFrame);
664 Frame* findUnsafeParentScrollPropagationBoundary();
665
666 CSSStyleSheet& elementSheet();
667 bool usesStyleBasedEditability() const;
668
669 virtual Ref<DocumentParser> createParser();
670 DocumentParser* parser() const { return m_parser.get(); }
671 ScriptableDocumentParser* scriptableDocumentParser() const;
672
673 bool printing() const { return m_printing; }
674 void setPrinting(bool p) { m_printing = p; }
675
676 bool paginatedForScreen() const { return m_paginatedForScreen; }
677 void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
678
679 bool paginated() const { return printing() || paginatedForScreen(); }
680
681 void setCompatibilityMode(DocumentCompatibilityMode);
682 void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
683 static ptrdiff_t compatibilityModeMemoryOffset() { return OBJECT_OFFSETOF(Document, m_compatibilityMode); }
684
685 String compatMode() const;
686
687 bool inQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::QuirksMode; }
688 bool inLimitedQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::LimitedQuirksMode; }
689 bool inNoQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::NoQuirksMode; }
690
691 enum ReadyState {
692 Loading,
693 Interactive,
694 Complete
695 };
696 void setReadyState(ReadyState);
697 void setParsing(bool);
698 bool parsing() const { return m_bParsing; }
699 std::chrono::milliseconds minimumLayoutDelay();
700
701 bool shouldScheduleLayout();
702 bool isLayoutTimerActive();
703 std::chrono::milliseconds elapsedTime() const;
704
705 void setTextColor(const Color& color) { m_textColor = color; }
706 Color textColor() const { return m_textColor; }
707
708 const Color& linkColor() const { return m_linkColor; }
709 const Color& visitedLinkColor() const { return m_visitedLinkColor; }
710 const Color& activeLinkColor() const { return m_activeLinkColor; }
711 void setLinkColor(const Color& c) { m_linkColor = c; }
712 void setVisitedLinkColor(const Color& c) { m_visitedLinkColor = c; }
713 void setActiveLinkColor(const Color& c) { m_activeLinkColor = c; }
714 void resetLinkColor();
715 void resetVisitedLinkColor();
716 void resetActiveLinkColor();
717 VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
718
719 MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
720
721 /* Newly proposed CSS3 mechanism for selecting alternate
722 stylesheets using the DOM. May be subject to change as
723 spec matures. - dwh
724 */
725 String preferredStylesheetSet() const;
726 String selectedStylesheetSet() const;
727 void setSelectedStylesheetSet(const String&);
728
729 WEBCORE_EXPORT bool setFocusedElement(Element*, FocusDirection = FocusDirectionNone);
730 Element* focusedElement() const { return m_focusedElement.get(); }
731 UserActionElementSet& userActionElements() { return m_userActionElements; }
732 const UserActionElementSet& userActionElements() const { return m_userActionElements; }
733
734 void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
735 void hoveredElementDidDetach(Element*);
736 void elementInActiveChainDidDetach(Element*);
737
738 void updateHoverActiveState(const HitTestRequest&, Element*, StyleResolverUpdateFlag = RecalcStyleIfNeeded);
739
740 // Updates for :target (CSS3 selector).
741 void setCSSTarget(Element*);
742 Element* cssTarget() const { return m_cssTarget; }
743 static ptrdiff_t cssTargetMemoryOffset() { return OBJECT_OFFSETOF(Document, m_cssTarget); }
744
745 WEBCORE_EXPORT void scheduleForcedStyleRecalc();
746 void scheduleStyleRecalc();
747 void unscheduleStyleRecalc();
748 bool hasPendingStyleRecalc() const;
749 bool hasPendingForcedStyleRecalc() const;
750 void optimizedStyleSheetUpdateTimerFired();
751
752 void registerNodeListForInvalidation(LiveNodeList&);
753 void unregisterNodeListForInvalidation(LiveNodeList&);
754 void registerCollection(HTMLCollection&);
755 void unregisterCollection(HTMLCollection&);
756 void collectionCachedIdNameMap(const HTMLCollection&);
757 void collectionWillClearIdNameMap(const HTMLCollection&);
758 bool shouldInvalidateNodeListAndCollectionCaches(const QualifiedName* attrName = nullptr) const;
759 void invalidateNodeListAndCollectionCaches(const QualifiedName* attrName);
760
761 void attachNodeIterator(NodeIterator*);
762 void detachNodeIterator(NodeIterator*);
763 void moveNodeIteratorsToNewDocument(Node*, Document*);
764
765 void attachRange(Range*);
766 void detachRange(Range*);
767
768 void updateRangesAfterChildrenChanged(ContainerNode&);
769 // nodeChildrenWillBeRemoved is used when removing all node children at once.
770 void nodeChildrenWillBeRemoved(ContainerNode&);
771 // nodeWillBeRemoved is only safe when removing one node at a time.
772 void nodeWillBeRemoved(Node&);
773 enum class AcceptChildOperation { Replace, InsertOrAdd };
774 bool canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation) const;
775
776 void textInserted(Node*, unsigned offset, unsigned length);
777 void textRemoved(Node*, unsigned offset, unsigned length);
778 void textNodesMerged(Text* oldNode, unsigned offset);
779 void textNodeSplit(Text* oldNode);
780
781 void createDOMWindow();
782 void takeDOMWindowFrom(Document*);
783
784 DOMWindow* domWindow() const { return m_domWindow.get(); }
785 // In DOM Level 2, the Document's DOMWindow is called the defaultView.
786 DOMWindow* defaultView() const { return domWindow(); }
787
788 // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
789 void setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& value);
790 void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
791 EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
792 WEBCORE_EXPORT void dispatchWindowEvent(Event&, EventTarget* = nullptr);
793 void dispatchWindowLoadEvent();
794
795 RefPtr<Event> createEvent(const String& eventType, ExceptionCode&);
796
797 // keep track of what types of event listeners are registered, so we don't
798 // dispatch events unnecessarily
799 enum ListenerType {
800 DOMSUBTREEMODIFIED_LISTENER = 1,
801 DOMNODEINSERTED_LISTENER = 1 << 1,
802 DOMNODEREMOVED_LISTENER = 1 << 2,
803 DOMNODEREMOVEDFROMDOCUMENT_LISTENER = 1 << 3,
804 DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
805 DOMCHARACTERDATAMODIFIED_LISTENER = 1 << 5,
806 OVERFLOWCHANGED_LISTENER = 1 << 6,
807 ANIMATIONEND_LISTENER = 1 << 7,
808 ANIMATIONSTART_LISTENER = 1 << 8,
809 ANIMATIONITERATION_LISTENER = 1 << 9,
810 TRANSITIONEND_LISTENER = 1 << 10,
811 BEFORELOAD_LISTENER = 1 << 11,
812 SCROLL_LISTENER = 1 << 12,
813 FORCEWILLBEGIN_LISTENER = 1 << 13,
814 FORCECHANGED_LISTENER = 1 << 14,
815 FORCEDOWN_LISTENER = 1 << 15,
816 FORCEUP_LISTENER = 1 << 16
817 };
818
819 bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
820 bool hasListenerTypeForEventType(PlatformEvent::Type) const;
821 void addListenerTypeIfNeeded(const AtomicString& eventType);
822
823 bool hasMutationObserversOfType(MutationObserver::MutationType type) const
824 {
825 return m_mutationObserverTypes & type;
826 }
827 bool hasMutationObservers() const { return m_mutationObserverTypes; }
828 void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
829
830 CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
831
832 /**
833 * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
834 * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
835 * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
836 * specified in a HTML file.
837 *
838 * @param equiv The http header name (value of the meta tag's "equiv" attribute)
839 * @param content The header value (value of the meta tag's "content" attribute)
840 */
841 void processHttpEquiv(const String& equiv, const String& content);
842
843#if PLATFORM(IOS)
844 void processFormatDetection(const String&);
845
846 // Called when <meta name="apple-mobile-web-app-orientations"> changes.
847 void processWebAppOrientations();
848#endif
849
850 void processViewport(const String& features, ViewportArguments::Type origin);
851 void updateViewportArguments();
852 void processReferrerPolicy(const String& policy);
853
854 // Returns the owning element in the parent document.
855 // Returns 0 if this is the top level document.
856 HTMLFrameOwnerElement* ownerElement() const;
857
858 // Used by DOM bindings; no direction known.
859 String title() const { return m_title.string(); }
860 void setTitle(const String&);
861
862 void titleElementAdded(Element& titleElement);
863 void titleElementRemoved(Element& titleElement);
864 void titleElementTextChanged(Element& titleElement);
865
866 String cookie(ExceptionCode&);
867 void setCookie(const String&, ExceptionCode&);
868
869 String referrer() const;
870
871 String origin() const;
872
873 WEBCORE_EXPORT String domain() const;
874 void setDomain(const String& newDomain, ExceptionCode&);
875
876 String lastModified() const;
877
878 // The cookieURL is used to query the cookie database for this document's
879 // cookies. For example, if the cookie URL is http://example.com, we'll
880 // use the non-Secure cookies for example.com when computing
881 // document.cookie.
882 //
883 // Q: How is the cookieURL different from the document's URL?
884 // A: The two URLs are the same almost all the time. However, if one
885 // document inherits the security context of another document, it
886 // inherits its cookieURL but not its URL.
887 //
888 const URL& cookieURL() const { return m_cookieURL; }
889 void setCookieURL(const URL&);
890
891 // The firstPartyForCookies is used to compute whether this document
892 // appears in a "third-party" context for the purpose of third-party
893 // cookie blocking. The document is in a third-party context if the
894 // cookieURL and the firstPartyForCookies are from different hosts.
895 //
896 // Note: Some ports (including possibly Apple's) only consider the
897 // document in a third-party context if the cookieURL and the
898 // firstPartyForCookies have a different registry-controlled
899 // domain.
900 //
901 const URL& firstPartyForCookies() const { return m_firstPartyForCookies; }
902 void setFirstPartyForCookies(const URL& url) { m_firstPartyForCookies = url; }
903
904 // The following implements the rule from HTML 4 for what valid names are.
905 // To get this right for all the XML cases, we probably have to improve this or move it
906 // and make it sensitive to the type of document.
907 static bool isValidName(const String&);
908
909 // The following breaks a qualified name into a prefix and a local name.
910 // It also does a validity check, and returns false if the qualified name
911 // is invalid. It also sets ExceptionCode when name is invalid.
912 static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode&);
913
914 // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
915 static bool hasValidNamespaceForElements(const QualifiedName&);
916 static bool hasValidNamespaceForAttributes(const QualifiedName&);
917
918 HTMLBodyElement* body() const;
919 WEBCORE_EXPORT HTMLElement* bodyOrFrameset() const;
920 void setBodyOrFrameset(RefPtr<HTMLElement>&&, ExceptionCode&);
921
922 Location* location() const;
923
924 WEBCORE_EXPORT HTMLHeadElement* head();
925
926 DocumentMarkerController& markers() const { return *m_markers; }
927
928 bool execCommand(const String& command, bool userInterface = false, const String& value = String());
929 bool queryCommandEnabled(const String& command);
930 bool queryCommandIndeterm(const String& command);
931 bool queryCommandState(const String& command);
932 bool queryCommandSupported(const String& command);
933 String queryCommandValue(const String& command);
934
935 // designMode support
936 enum InheritedBool { off = false, on = true, inherit };
937 void setDesignMode(InheritedBool value);
938 InheritedBool getDesignMode() const;
939 bool inDesignMode() const;
940
941 Document* parentDocument() const;
942 Document& topDocument() const;
943
944 ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
945 JSModuleLoader* moduleLoader() { return m_moduleLoader.get(); }
946
947 HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : nullptr; }
948 void pushCurrentScript(HTMLScriptElement*);
949 void popCurrentScript();
950
951#if ENABLE(XSLT)
952 void applyXSLTransform(ProcessingInstruction* pi);
953 RefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
954 void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
955
956 void setTransformSource(std::unique_ptr<TransformSource>);
957 TransformSource* transformSource() const { return m_transformSource.get(); }
958#endif
959
960 void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
961 uint64_t domTreeVersion() const { return m_domTreeVersion; }
962
963 // XPathEvaluator methods
964 RefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionCode&);
965 RefPtr<XPathNSResolver> createNSResolver(Node* nodeResolver);
966 RefPtr<XPathResult> evaluate(const String& expression, Node* contextNode, XPathNSResolver*, unsigned short type, XPathResult*, ExceptionCode&);
967
968 enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
969
970 bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
971
972 bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
973 void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
974
975 void updateFocusAppearanceSoon(SelectionRestorationMode);
976 void cancelFocusAppearanceUpdate();
977
978 // Extension for manipulating canvas drawing contexts for use in CSS
979 CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
980 HTMLCanvasElement* getCSSCanvasElement(const String& name);
981
982 bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
983 void parseDNSPrefetchControlHeader(const String&);
984
985 virtual void postTask(Task) override final; // Executes the task on context's thread asynchronously.
986
987#if ENABLE(REQUEST_ANIMATION_FRAME)
988 ScriptedAnimationController* scriptedAnimationController() { return m_scriptedAnimationController.get(); }
989#endif
990 void suspendScriptedAnimationControllerCallbacks();
991 void resumeScriptedAnimationControllerCallbacks();
992 void scriptedAnimationControllerSetThrottled(bool);
993
994 void windowScreenDidChange(PlatformDisplayID);
995
996 void finishedParsing();
997
998 enum PageCacheState { NotInPageCache, AboutToEnterPageCache, InPageCache };
999
1000 PageCacheState pageCacheState() const { return m_pageCacheState; }
1001 void setPageCacheState(PageCacheState);
1002
1003 // FIXME: Update callers to use pageCacheState() instead.
1004 bool inPageCache() const { return m_pageCacheState != NotInPageCache; }
1005
1006 // Elements can register themselves for the "suspend()" and
1007 // "resume()" callbacks
1008 void registerForDocumentSuspensionCallbacks(Element*);
1009 void unregisterForDocumentSuspensionCallbacks(Element*);
1010
1011 void documentWillBecomeInactive();
1012 void suspend(ActiveDOMObject::ReasonForSuspension);
1013 void resume(ActiveDOMObject::ReasonForSuspension);
1014
1015 void registerForMediaVolumeCallbacks(Element*);
1016 void unregisterForMediaVolumeCallbacks(Element*);
1017 void mediaVolumeDidChange();
1018
1019#if ENABLE(MEDIA_SESSION)
1020 MediaSession& defaultMediaSession();
1021#endif
1022
1023 void registerForPrivateBrowsingStateChangedCallbacks(Element*);
1024 void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
1025 void storageBlockingStateDidChange();
1026 void privateBrowsingStateDidChange();
1027
1028#if ENABLE(VIDEO_TRACK)
1029 void registerForCaptionPreferencesChangedCallbacks(Element*);
1030 void unregisterForCaptionPreferencesChangedCallbacks(Element*);
1031 void captionPreferencesChanged();
1032#endif
1033
1034#if ENABLE(MEDIA_CONTROLS_SCRIPT)
1035 void registerForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
1036 void unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
1037 void pageScaleFactorChangedAndStable();
1038#endif
1039
1040 void registerForVisibilityStateChangedCallbacks(Element*);
1041 void unregisterForVisibilityStateChangedCallbacks(Element*);
1042
1043#if ENABLE(VIDEO)
1044 void registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
1045 void unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
1046 void allowsMediaDocumentInlinePlaybackChanged();
1047#endif
1048
1049 WEBCORE_EXPORT void setShouldCreateRenderers(bool);
1050 bool shouldCreateRenderers();
1051
1052 void setDecoder(RefPtr<TextResourceDecoder>&&);
1053 TextResourceDecoder* decoder() const { return m_decoder.get(); }
1054
1055 WEBCORE_EXPORT String displayStringModifiedByEncoding(const String&) const;
1056 RefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
1057 void displayBufferModifiedByEncoding(LChar* buffer, unsigned len) const
1058 {
1059 displayBufferModifiedByEncodingInternal(buffer, len);
1060 }
1061 void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
1062 {
1063 displayBufferModifiedByEncodingInternal(buffer, len);
1064 }
1065
1066 // Quirk for the benefit of Apple's Dictionary application.
1067 void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
1068 bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
1069
1070#if ENABLE(DASHBOARD_SUPPORT)
1071 void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
1072 bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
1073 bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
1074 void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
1075 WEBCORE_EXPORT const Vector<AnnotatedRegionValue>& annotatedRegions() const;
1076 void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
1077#endif
1078
1079 virtual void removeAllEventListeners() override final;
1080
1081 WEBCORE_EXPORT const SVGDocumentExtensions* svgExtensions();
1082 WEBCORE_EXPORT SVGDocumentExtensions& accessSVGExtensions();
1083
1084 void initSecurityContext();
1085 void initContentSecurityPolicy();
1086
1087 void updateURLForPushOrReplaceState(const URL&);
1088 void statePopped(PassRefPtr<SerializedScriptValue>);
1089
1090 bool processingLoadEvent() const { return m_processingLoadEvent; }
1091 bool loadEventFinished() const { return m_loadEventFinished; }
1092
1093 virtual bool isContextThread() const override final;
1094 virtual bool isJSExecutionForbidden() const override final { return false; }
1095
1096 void enqueueWindowEvent(Ref<Event>&&);
1097 void enqueueDocumentEvent(Ref<Event>&&);
1098 void enqueueOverflowEvent(Ref<Event>&&);
1099 void enqueuePageshowEvent(PageshowEventPersistence);
1100 void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1101 void enqueuePopstateEvent(RefPtr<SerializedScriptValue>&& stateObject);
1102 virtual DocumentEventQueue& eventQueue() const override final { return m_eventQueue; }
1103
1104 WEBCORE_EXPORT void addMediaCanStartListener(MediaCanStartListener*);
1105 WEBCORE_EXPORT void removeMediaCanStartListener(MediaCanStartListener*);
1106 MediaCanStartListener* takeAnyMediaCanStartListener();
1107
1108#if ENABLE(FULLSCREEN_API)
1109 bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
1110 bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
1111 Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
1112
1113 enum FullScreenCheckType {
1114 EnforceIFrameAllowFullScreenRequirement,
1115 ExemptIFrameAllowFullScreenRequirement,
1116 };
1117
1118 void requestFullScreenForElement(Element*, unsigned short flags, FullScreenCheckType);
1119 WEBCORE_EXPORT void webkitCancelFullScreen();
1120
1121 WEBCORE_EXPORT void webkitWillEnterFullScreenForElement(Element*);
1122 WEBCORE_EXPORT void webkitDidEnterFullScreenForElement(Element*);
1123 WEBCORE_EXPORT void webkitWillExitFullScreenForElement(Element*);
1124 WEBCORE_EXPORT void webkitDidExitFullScreenForElement(Element*);
1125
1126 void setFullScreenRenderer(RenderFullScreen*);
1127 RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
1128 void fullScreenRendererDestroyed();
1129
1130 void fullScreenChangeDelayTimerFired();
1131 bool fullScreenIsAllowedForElement(Element*) const;
1132 void fullScreenElementRemoved();
1133 void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
1134 bool isAnimatingFullScreen() const;
1135 WEBCORE_EXPORT void setAnimatingFullScreen(bool);
1136
1137 // W3C API
1138 bool webkitFullscreenEnabled() const;
1139 Element* webkitFullscreenElement() const { return !m_fullScreenElementStack.isEmpty() ? m_fullScreenElementStack.last().get() : nullptr; }
1140 void webkitExitFullscreen();
1141#endif
1142
1143#if ENABLE(POINTER_LOCK)
1144 void exitPointerLock();
1145 Element* pointerLockElement() const;
1146#endif
1147
1148 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
1149 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1150 void decrementLoadEventDelayCount();
1151 bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1152
1153#if ENABLE(IOS_TOUCH_EVENTS)
1154#include <WebKitAdditions/DocumentIOS.h>
1155#elif ENABLE(TOUCH_EVENTS)
1156 RefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force, ExceptionCode&) const;
1157#endif
1158
1159#if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1160 DeviceMotionController* deviceMotionController() const;
1161 DeviceOrientationController* deviceOrientationController() const;
1162#endif
1163
1164#if ENABLE(WEB_TIMING)
1165 const DocumentTiming& timing() const { return m_documentTiming; }
1166#endif
1167
1168#if ENABLE(REQUEST_ANIMATION_FRAME)
1169 int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
1170 void cancelAnimationFrame(int id);
1171 void serviceScriptedAnimations(double monotonicAnimationStartTime);
1172#endif
1173
1174 void sendWillRevealEdgeEventsIfNeeded(const IntPoint& oldPosition, const IntPoint& newPosition, const IntRect& visibleRect, const IntSize& contentsSize, Element* target = nullptr);
1175
1176 virtual EventTarget* errorEventTarget() override final;
1177 virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&&) override final;
1178
1179 void initDNSPrefetch();
1180
1181 void didAddWheelEventHandler(Node&);
1182 void didRemoveWheelEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1183
1184 double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
1185 void updateLastHandledUserGestureTimestamp();
1186
1187#if ENABLE(TOUCH_EVENTS)
1188 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
1189#else
1190 bool hasTouchEventHandlers() const { return false; }
1191#endif
1192
1193 // Used for testing. Count handlers in the main document, and one per frame which contains handlers.
1194 WEBCORE_EXPORT unsigned wheelEventHandlerCount() const;
1195 WEBCORE_EXPORT unsigned touchEventHandlerCount() const;
1196
1197 WEBCORE_EXPORT void startTrackingStyleRecalcs();
1198 WEBCORE_EXPORT unsigned styleRecalcCount() const;
1199
1200 void didAddTouchEventHandler(Node&);
1201 void didRemoveTouchEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1202
1203 void didRemoveEventTargetNode(Node&);
1204
1205 const EventTargetSet* touchEventTargets() const
1206 {
1207#if ENABLE(TOUCH_EVENTS)
1208 return m_touchEventTargets.get();
1209#else
1210 return nullptr;
1211#endif
1212 }
1213
1214#if ENABLE(CUSTOM_ELEMENTS)
1215 CustomElementDefinitions* customElementDefinitions() { return m_customElementDefinitions.get(); }
1216 CustomElementDefinitions& ensureCustomElementDefinitions();
1217#endif
1218
1219 const EventTargetSet* wheelEventTargets() const { return m_wheelEventTargets.get(); }
1220
1221 typedef std::pair<Region, bool> RegionFixedPair;
1222 RegionFixedPair absoluteRegionForEventTargets(const EventTargetSet*);
1223
1224 LayoutRect absoluteEventHandlerBounds(bool&) override final;
1225
1226 bool visualUpdatesAllowed() const { return m_visualUpdatesAllowed; }
1227
1228 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
1229
1230 void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1231 void resumeScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1232
1233#if ENABLE(CSS_DEVICE_ADAPTATION)
1234 IntSize initialViewportSize() const;
1235#endif
1236
1237#if ENABLE(TEXT_AUTOSIZING)
1238 TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
1239#endif
1240
1241 void adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(Vector<FloatQuad>&, const RenderStyle&);
1242 void adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect&, const RenderStyle&);
1243
1244 bool hasActiveParser();
1245 void incrementActiveParserCount() { ++m_activeParserCount; }
1246 void decrementActiveParserCount();
1247
1248 DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
1249
1250 void didRemoveAllPendingStylesheet();
1251 void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
1252 void clearStyleResolver();
1253
1254 bool inStyleRecalc() { return m_inStyleRecalc; }
1255
1256 // Return a Locale for the default locale if the argument is null or empty.
1257 Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1258
1259#if ENABLE(TEMPLATE_ELEMENT)
1260 const Document* templateDocument() const;
1261 Document& ensureTemplateDocument();
1262 void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = templateDocumentHost; }
1263 Document* templateDocumentHost() { return m_templateDocumentHost; }
1264#endif
1265
1266 void didAssociateFormControl(Element*);
1267 bool hasDisabledFieldsetElement() const { return m_disabledFieldsetElementsCount; }
1268 void addDisabledFieldsetElement() { m_disabledFieldsetElementsCount++; }
1269 void removeDisabledFieldsetElement() { ASSERT(m_disabledFieldsetElementsCount); m_disabledFieldsetElementsCount--; }
1270
1271 WEBCORE_EXPORT virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) override final;
1272
1273 WEBCORE_EXPORT virtual SecurityOrigin* topOrigin() const override final;
1274
1275#if ENABLE(FONT_LOAD_EVENTS)
1276 RefPtr<FontLoader> fonts();
1277#endif
1278
1279 void ensurePlugInsInjectedScript(DOMWrapperWorld&);
1280
1281 void setVisualUpdatesAllowedByClient(bool);
1282
1283#if ENABLE(SUBTLE_CRYPTO)
1284 virtual bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) override final;
1285 virtual bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) override final;
1286#endif
1287
1288 void setHasStyleWithViewportUnits() { m_hasStyleWithViewportUnits = true; }
1289 bool hasStyleWithViewportUnits() const { return m_hasStyleWithViewportUnits; }
1290 void updateViewportUnitsOnResize();
1291
1292 WEBCORE_EXPORT void addAudioProducer(MediaProducer*);
1293 WEBCORE_EXPORT void removeAudioProducer(MediaProducer*);
1294 MediaProducer::MediaStateFlags mediaState() const { return m_mediaState; }
1295 WEBCORE_EXPORT void updateIsPlayingMedia(uint64_t = HTMLMediaElementInvalidID);
1296 void pageMutedStateDidChange();
1297 WeakPtr<Document> createWeakPtr() { return m_weakFactory.createWeakPtr(); }
1298
1299#if ENABLE(WIRELESS_PLAYBACK_TARGET)
1300 void addPlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1301 void removePlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1302 void showPlaybackTargetPicker(MediaPlaybackTargetClient&, bool);
1303 void playbackTargetPickerClientStateDidChange(MediaPlaybackTargetClient&, MediaProducer::MediaStateFlags);
1304
1305 void setPlaybackTarget(uint64_t, Ref<MediaPlaybackTarget>&&);
1306 void playbackTargetAvailabilityDidChange(uint64_t, bool);
1307 void setShouldPlayToPlaybackTarget(uint64_t, bool);
1308#endif
1309
1310 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToPropagate() const;
1311 bool shouldEnforceContentDispositionAttachmentSandbox() const;
1312 void applyContentDispositionAttachmentSandbox();
1313
1314 void addViewportDependentPicture(HTMLPictureElement&);
1315 void removeViewportDependentPicture(HTMLPictureElement&);
1316
1317#if ENABLE(MEDIA_STREAM)
1318 void setHasActiveMediaStreamTrack() { m_hasHadActiveMediaStreamTrack = true; }
1319 bool hasHadActiveMediaStreamTrack() const { return m_hasHadActiveMediaStreamTrack; }
1320#endif
1321
1322protected:
1323 enum ConstructionFlags { Synthesized = 1, NonRenderedPlaceholder = 1 << 1 };
1324 Document(Frame*, const URL&, unsigned = DefaultDocumentClass, unsigned constructionFlags = 0);
1325
1326 void clearXMLVersion() { m_xmlVersion = String(); }
1327
1328 virtual Ref<Document> cloneDocumentWithoutChildren() const;
1329
1330private:
1331 friend class Node;
1332 friend class IgnoreDestructiveWriteCountIncrementer;
1333 friend class IgnoreOpensDuringUnloadCountIncrementer;
1334
1335 void updateTitleElement(Element* newTitleElement);
1336
1337 void commonTeardown();
1338
1339 RenderObject* renderer() const = delete;
1340 void setRenderer(RenderObject*) = delete;
1341
1342 void createRenderTree();
1343 void detachParser();
1344
1345 // FontSelectorClient
1346 virtual void fontsNeedUpdate(FontSelector&) override final;
1347
1348 virtual bool isDocument() const override final { return true; }
1349
1350 virtual void childrenChanged(const ChildChange&) override final;
1351
1352 virtual String nodeName() const override final;
1353 virtual NodeType nodeType() const override final;
1354 virtual bool childTypeAllowed(NodeType) const override final;
1355 virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) override final;
1356 void cloneDataFromDocument(const Document&);
1357
1358 virtual void refScriptExecutionContext() override final { ref(); }
1359 virtual void derefScriptExecutionContext() override final { deref(); }
1360
1361 virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, RefPtr<Inspector::ScriptCallStack>&&, JSC::ExecState* = nullptr, unsigned long requestIdentifier = 0) override final;
1362
1363 virtual double minimumTimerInterval() const override final;
1364
1365 virtual double timerAlignmentInterval(bool hasReachedMaxNestingLevel) const override final;
1366
1367 void updateTitleFromTitleElement();
1368 void updateTitle(const StringWithDirection&);
1369 void updateFocusAppearanceTimerFired();
1370 void updateBaseURL();
1371
1372 void buildAccessKeyMap(TreeScope* root);
1373
1374 void createStyleResolver();
1375
1376 void loadEventDelayTimerFired();
1377
1378 void pendingTasksTimerFired();
1379
1380 template <typename CharacterType>
1381 void displayBufferModifiedByEncodingInternal(CharacterType*, unsigned) const;
1382
1383 PageVisibilityState pageVisibilityState() const;
1384
1385 Node* nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint = nullptr);
1386
1387 template <CollectionType collectionType>
1388 Ref<HTMLCollection> ensureCachedCollection();
1389
1390#if ENABLE(FULLSCREEN_API)
1391 void dispatchFullScreenChangeOrErrorEvent(Deque<RefPtr<Node>>&, const AtomicString& eventName, bool shouldNotifyMediaElement);
1392 void clearFullscreenElementStack();
1393 void popFullscreenElementStack();
1394 void pushFullscreenElementStack(Element*);
1395 void addDocumentToFullScreenChangeEventQueue(Document*);
1396#endif
1397
1398 void setVisualUpdatesAllowed(ReadyState);
1399 void setVisualUpdatesAllowed(bool);
1400 void visualUpdatesSuppressionTimerFired();
1401
1402 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1403
1404 void didAssociateFormControlsTimerFired();
1405
1406 void wheelEventHandlersChanged();
1407
1408 HttpEquivPolicy httpEquivPolicy() const;
1409
1410 // DOM Cookies caching.
1411 const String& cachedDOMCookies() const { return m_cachedDOMCookies; }
1412 void setCachedDOMCookies(const String&);
1413 bool isDOMCookieCacheValid() const { return m_cookieCacheExpiryTimer.isActive(); }
1414 void invalidateDOMCookieCache();
1415 virtual void didLoadResourceSynchronously(const ResourceRequest&) override final;
1416
1417 void checkViewportDependentPictures();
1418
1419 unsigned m_referencingNodeCount;
1420
1421 std::unique_ptr<StyleResolver> m_styleResolver;
1422 std::unique_ptr<StyleResolver> m_userAgentShadowTreeStyleResolver;
1423 bool m_didCalculateStyleResolver;
1424 bool m_hasNodesWithPlaceholderStyle;
1425 bool m_needsNotifyRemoveAllPendingStylesheet;
1426 // But sometimes you need to ignore pending stylesheet count to
1427 // force an immediate layout when requested by JS.
1428 bool m_ignorePendingStylesheets;
1429
1430 // If we do ignore the pending stylesheet count, then we need to add a boolean
1431 // to track that this happened so that we can do a full repaint when the stylesheets
1432 // do eventually load.
1433 PendingSheetLayout m_pendingSheetLayout;
1434
1435 Frame* m_frame;
1436 RefPtr<DOMWindow> m_domWindow;
1437
1438 Ref<CachedResourceLoader> m_cachedResourceLoader;
1439 RefPtr<DocumentParser> m_parser;
1440 unsigned m_activeParserCount;
1441
1442 bool m_wellFormed;
1443
1444 // Document URLs.
1445 URL m_url; // Document.URL: The URL from which this document was retrieved.
1446 URL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1447 URL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1448 URL m_baseElementURL; // The URL set by the <base> element.
1449 URL m_cookieURL; // The URL to use for cookie access.
1450 URL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1451
1452 // Document.documentURI:
1453 // Although URL-like, Document.documentURI can actually be set to any
1454 // string by content. Document.documentURI affects m_baseURL unless the
1455 // document contains a <base> element, in which case the <base> element
1456 // takes precedence.
1457 //
1458 // This property is read-only from JavaScript, but writable from Objective C.
1459 String m_documentURI;
1460
1461 String m_baseTarget;
1462
1463 // MIME type of the document in case it was cloned or created by XHR.
1464 String m_overriddenMIMEType;
1465
1466 std::unique_ptr<DOMImplementation> m_implementation;
1467
1468 RefPtr<CSSStyleSheet> m_elementSheet;
1469
1470 bool m_printing;
1471 bool m_paginatedForScreen;
1472
1473 DocumentCompatibilityMode m_compatibilityMode;
1474 bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1475
1476 Color m_textColor;
1477
1478 RefPtr<Element> m_focusedElement;
1479 RefPtr<Element> m_hoveredElement;
1480 RefPtr<Element> m_activeElement;
1481 RefPtr<Element> m_documentElement;
1482 UserActionElementSet m_userActionElements;
1483
1484 uint64_t m_domTreeVersion;
1485 static uint64_t s_globalTreeVersion;
1486
1487 HashSet<NodeIterator*> m_nodeIterators;
1488 HashSet<Range*> m_ranges;
1489
1490 unsigned m_listenerTypes;
1491
1492 MutationObserverOptions m_mutationObserverTypes;
1493
1494 std::unique_ptr<AuthorStyleSheets> m_authorStyleSheets;
1495 std::unique_ptr<ExtensionStyleSheets> m_extensionStyleSheets;
1496 RefPtr<StyleSheetList> m_styleSheetList;
1497
1498 std::unique_ptr<FormController> m_formController;
1499
1500 Color m_linkColor;
1501 Color m_visitedLinkColor;
1502 Color m_activeLinkColor;
1503 const std::unique_ptr<VisitedLinkState> m_visitedLinkState;
1504
1505 bool m_visuallyOrdered;
1506 ReadyState m_readyState;
1507 bool m_bParsing;
1508
1509 Timer m_optimizedStyleSheetUpdateTimer;
1510 Timer m_styleRecalcTimer;
1511 bool m_pendingStyleRecalcShouldForce;
1512 bool m_inStyleRecalc;
1513 bool m_closeAfterStyleRecalc;
1514
1515 bool m_gotoAnchorNeededAfterStylesheetsLoad;
1516 bool m_isDNSPrefetchEnabled;
1517 bool m_haveExplicitlyDisabledDNSPrefetch;
1518 bool m_frameElementsShouldIgnoreScrolling;
1519 SelectionRestorationMode m_updateFocusAppearanceRestoresSelection;
1520
1521 // https://html.spec.whatwg.org/multipage/webappapis.html#ignore-destructive-writes-counter
1522 unsigned m_ignoreDestructiveWriteCount { 0 };
1523
1524 // https://html.spec.whatwg.org/multipage/webappapis.html#ignore-opens-during-unload-counter
1525 unsigned m_ignoreOpensDuringUnloadCount { 0 };
1526
1527 unsigned m_styleRecalcCount { 0 };
1528
1529 StringWithDirection m_title;
1530 StringWithDirection m_rawTitle;
1531 RefPtr<Element> m_titleElement;
1532
1533 std::unique_ptr<AXObjectCache> m_axObjectCache;
1534 const std::unique_ptr<DocumentMarkerController> m_markers;
1535
1536 Timer m_updateFocusAppearanceTimer;
1537
1538 Element* m_cssTarget;
1539
1540 // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
1541 // is almost a duplication of this data, so that should probably get merged in too.
1542 // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadDispatched are roughly the same
1543 // and should be merged.
1544 bool m_processingLoadEvent;
1545 bool m_loadEventFinished;
1546
1547 RefPtr<SerializedScriptValue> m_pendingStateObject;
1548 std::chrono::steady_clock::time_point m_startTime;
1549 bool m_overMinimumLayoutThreshold;
1550
1551 std::unique_ptr<ScriptRunner> m_scriptRunner;
1552 std::unique_ptr<JSModuleLoader> m_moduleLoader;
1553
1554 Vector<RefPtr<HTMLScriptElement>> m_currentScriptStack;
1555
1556#if ENABLE(XSLT)
1557 std::unique_ptr<TransformSource> m_transformSource;
1558 RefPtr<Document> m_transformSourceDocument;
1559#endif
1560
1561 String m_xmlEncoding;
1562 String m_xmlVersion;
1563 unsigned m_xmlStandalone : 2;
1564 unsigned m_hasXMLDeclaration : 1;
1565
1566 String m_contentLanguage;
1567
1568 RefPtr<TextResourceDecoder> m_decoder;
1569
1570 InheritedBool m_designMode;
1571
1572 HashSet<LiveNodeList*> m_listsInvalidatedAtDocument;
1573 HashSet<HTMLCollection*> m_collectionsInvalidatedAtDocument;
1574 unsigned m_nodeListAndCollectionCounts[numNodeListInvalidationTypes];
1575
1576 RefPtr<XPathEvaluator> m_xpathEvaluator;
1577
1578 std::unique_ptr<SVGDocumentExtensions> m_svgExtensions;
1579
1580#if ENABLE(DASHBOARD_SUPPORT)
1581 Vector<AnnotatedRegionValue> m_annotatedRegions;
1582 bool m_hasAnnotatedRegions;
1583 bool m_annotatedRegionsDirty;
1584#endif
1585
1586 HashMap<String, RefPtr<HTMLCanvasElement>> m_cssCanvasElements;
1587
1588 bool m_createRenderers;
1589 PageCacheState m_pageCacheState { NotInPageCache };
1590
1591 HashSet<Element*> m_documentSuspensionCallbackElements;
1592 HashSet<Element*> m_mediaVolumeCallbackElements;
1593 HashSet<Element*> m_privateBrowsingStateChangedElements;
1594#if ENABLE(VIDEO_TRACK)
1595 HashSet<Element*> m_captionPreferencesChangedElements;
1596#endif
1597
1598#if ENABLE(MEDIA_CONTROLS_SCRIPT)
1599 HashSet<HTMLMediaElement*> m_pageScaleFactorChangedElements;
1600#endif
1601
1602 HashSet<Element*> m_visibilityStateCallbackElements;
1603#if ENABLE(VIDEO)
1604 HashSet<HTMLMediaElement*> m_allowsMediaDocumentInlinePlaybackElements;
1605#endif
1606
1607 HashMap<StringImpl*, Element*, ASCIICaseInsensitiveHash> m_elementsByAccessKey;
1608 bool m_accessKeyMapValid;
1609
1610 DocumentOrderedMap m_imagesByUsemap;
1611
1612 std::unique_ptr<SelectorQueryCache> m_selectorQueryCache;
1613
1614 DocumentClassFlags m_documentClasses;
1615
1616 bool m_isSynthesized;
1617 bool m_isNonRenderedPlaceholder;
1618
1619 bool m_sawElementsInKnownNamespaces;
1620 bool m_isSrcdocDocument;
1621
1622 RenderPtr<RenderView> m_renderView;
1623 mutable DocumentEventQueue m_eventQueue;
1624
1625 WeakPtrFactory<Document> m_weakFactory;
1626
1627 HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1628
1629#if ENABLE(FULLSCREEN_API)
1630 bool m_areKeysEnabledInFullScreen;
1631 RefPtr<Element> m_fullScreenElement;
1632 Vector<RefPtr<Element>> m_fullScreenElementStack;
1633 RenderFullScreen* m_fullScreenRenderer;
1634 Timer m_fullScreenChangeDelayTimer;
1635 Deque<RefPtr<Node>> m_fullScreenChangeEventTargetQueue;
1636 Deque<RefPtr<Node>> m_fullScreenErrorEventTargetQueue;
1637 bool m_isAnimatingFullScreen;
1638 LayoutRect m_savedPlaceholderFrameRect;
1639 RefPtr<RenderStyle> m_savedPlaceholderRenderStyle;
1640#endif
1641
1642 HashSet<HTMLPictureElement*> m_viewportDependentPictures;
1643
1644 int m_loadEventDelayCount;
1645 Timer m_loadEventDelayTimer;
1646
1647 ViewportArguments m_viewportArguments;
1648
1649 ReferrerPolicy m_referrerPolicy;
1650
1651#if ENABLE(WEB_TIMING)
1652 DocumentTiming m_documentTiming;
1653#endif
1654
1655 RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1656 bool m_writeRecursionIsTooDeep;
1657 unsigned m_writeRecursionDepth;
1658
1659#if ENABLE(TOUCH_EVENTS)
1660 std::unique_ptr<EventTargetSet> m_touchEventTargets;
1661#endif
1662 std::unique_ptr<EventTargetSet> m_wheelEventTargets;
1663
1664 double m_lastHandledUserGestureTimestamp;
1665
1666#if ENABLE(REQUEST_ANIMATION_FRAME)
1667 void clearScriptedAnimationController();
1668 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1669#endif
1670
1671#if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1672 std::unique_ptr<DeviceMotionClient> m_deviceMotionClient;
1673 std::unique_ptr<DeviceMotionController> m_deviceMotionController;
1674 std::unique_ptr<DeviceOrientationClient> m_deviceOrientationClient;
1675 std::unique_ptr<DeviceOrientationController> m_deviceOrientationController;
1676#endif
1677
1678// FIXME: Find a better place for this functionality.
1679#if ENABLE(TELEPHONE_NUMBER_DETECTION)
1680public:
1681
1682 // These functions provide a two-level setting:
1683 // - A user-settable wantsTelephoneNumberParsing (at the Page / WebView level)
1684 // - A read-only telephoneNumberParsingAllowed which is set by the
1685 // document if it has the appropriate meta tag.
1686 // - isTelephoneNumberParsingEnabled() == isTelephoneNumberParsingAllowed() && page()->settings()->isTelephoneNumberParsingEnabled()
1687
1688 WEBCORE_EXPORT bool isTelephoneNumberParsingAllowed() const;
1689 WEBCORE_EXPORT bool isTelephoneNumberParsingEnabled() const;
1690
1691private:
1692 friend void setParserFeature(const String& key, const String& value, Document*, void* userData);
1693 void setIsTelephoneNumberParsingAllowed(bool);
1694
1695 bool m_isTelephoneNumberParsingAllowed;
1696#endif
1697
1698 Timer m_pendingTasksTimer;
1699 Vector<Task> m_pendingTasks;
1700
1701#if ENABLE(IOS_TEXT_AUTOSIZING)
1702public:
1703 void addAutoSizingNode(Node*, float size);
1704 void validateAutoSizingNodes();
1705 void resetAutoSizingNodes();
1706
1707private:
1708 typedef HashMap<TextAutoSizingKey, RefPtr<TextAutoSizingValue>, TextAutoSizingHash, TextAutoSizingTraits> TextAutoSizingMap;
1709 TextAutoSizingMap m_textAutoSizedNodes;
1710#endif
1711
1712#if ENABLE(TEXT_AUTOSIZING)
1713 std::unique_ptr<TextAutosizer> m_textAutosizer;
1714#endif
1715
1716 void platformSuspendOrStopActiveDOMObjects();
1717
1718 bool m_scheduledTasksAreSuspended;
1719
1720 bool m_visualUpdatesAllowed;
1721 Timer m_visualUpdatesSuppressionTimer;
1722
1723 RefPtr<NamedFlowCollection> m_namedFlows;
1724
1725 void clearSharedObjectPool();
1726 Timer m_sharedObjectPoolClearTimer;
1727
1728 std::unique_ptr<DocumentSharedObjectPool> m_sharedObjectPool;
1729
1730#ifndef NDEBUG
1731 bool m_didDispatchViewportPropertiesChanged;
1732#endif
1733
1734 typedef HashMap<AtomicString, std::unique_ptr<Locale>> LocaleIdentifierToLocaleMap;
1735 LocaleIdentifierToLocaleMap m_localeCache;
1736
1737#if ENABLE(TEMPLATE_ELEMENT)
1738 RefPtr<Document> m_templateDocument;
1739 Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
1740#endif
1741
1742#if ENABLE(CUSTOM_ELEMENTS)
1743 std::unique_ptr<CustomElementDefinitions> m_customElementDefinitions;
1744#endif
1745
1746 RefPtr<CSSFontSelector> m_fontSelector;
1747
1748#if ENABLE(FONT_LOAD_EVENTS)
1749 RefPtr<FontLoader> m_fontloader;
1750#endif
1751
1752#if ENABLE(WEB_REPLAY)
1753 RefPtr<JSC::InputCursor> m_inputCursor;
1754#endif
1755
1756 Timer m_didAssociateFormControlsTimer;
1757 Timer m_cookieCacheExpiryTimer;
1758 String m_cachedDOMCookies;
1759 HashSet<RefPtr<Element>> m_associatedFormControls;
1760 unsigned m_disabledFieldsetElementsCount;
1761
1762 bool m_hasInjectedPlugInsScript;
1763 bool m_renderTreeBeingDestroyed { false };
1764 bool m_hasPreparedForDestruction { false };
1765
1766 bool m_hasStyleWithViewportUnits;
1767 bool m_isTimerThrottlingEnabled { false };
1768 bool m_isSuspended { false };
1769
1770 HashSet<MediaProducer*> m_audioProducers;
1771 MediaProducer::MediaStateFlags m_mediaState { MediaProducer::IsNotPlaying };
1772
1773#if ENABLE(WIRELESS_PLAYBACK_TARGET)
1774 typedef HashMap<uint64_t, WebCore::MediaPlaybackTargetClient*> TargetIdToClientMap;
1775 TargetIdToClientMap m_idToClientMap;
1776 typedef HashMap<WebCore::MediaPlaybackTargetClient*, uint64_t> TargetClientToIdMap;
1777 TargetClientToIdMap m_clientToIDMap;
1778#endif
1779
1780#if ENABLE(MEDIA_SESSION)
1781 RefPtr<MediaSession> m_defaultMediaSession;
1782#endif
1783 bool m_areDeviceMotionAndOrientationUpdatesSuspended { false };
1784
1785#if ENABLE(MEDIA_STREAM)
1786 bool m_hasHadActiveMediaStreamTrack { false };
1787#endif
1788};
1789
1790inline void Document::notifyRemovePendingSheetIfNeeded()
1791{
1792 if (m_needsNotifyRemoveAllPendingStylesheet)
1793 didRemoveAllPendingStylesheet();
1794}
1795
1796inline TextEncoding Document::textEncoding() const
1797{
1798 if (auto* decoder = this->decoder())
1799 return decoder->encoding();
1800 return TextEncoding();
1801}
1802
1803#if ENABLE(TEMPLATE_ELEMENT)
1804inline const Document* Document::templateDocument() const
1805{
1806 // If DOCUMENT does not have a browsing context, Let TEMPLATE CONTENTS OWNER be DOCUMENT and abort these steps.
1807 if (!m_frame)
1808 return this;
1809
1810 return m_templateDocument.get();
1811}
1812#endif
1813
1814// Put these methods here, because they require the Document definition, but we really want to inline them.
1815
1816inline bool Node::isDocumentNode() const
1817{
1818 return this == &document();
1819}
1820
1821inline ScriptExecutionContext* Node::scriptExecutionContext() const
1822{
1823 return &document();
1824}
1825
1826Element* eventTargetElementForDocument(Document*);
1827
1828} // namespace WebCore
1829
1830SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Document)
1831 static bool isType(const WebCore::ScriptExecutionContext& context) { return context.isDocument(); }
1832 static bool isType(const WebCore::Node& node) { return node.isDocumentNode(); }
1833SPECIALIZE_TYPE_TRAITS_END()
1834
1835#endif // Document_h
1836