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-2017 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
33 #include "BeforeUnloadEvent.h"
34 #include "CDATASection.h"
35 #include "CSSAnimationController.h"
36 #include "CSSFontSelector.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedFrame.h"
41 #include "CachedResourceLoader.h"
42 #include "CanvasRenderingContext2D.h"
44 #include "ChromeClient.h"
47 #include "CompositionEvent.h"
48 #include "ConstantPropertyMap.h"
49 #include "ContentSecurityPolicy.h"
50 #include "CookieJar.h"
51 #include "CustomElementReactionQueue.h"
52 #include "CustomElementRegistry.h"
53 #include "CustomEvent.h"
54 #include "DOMImplementation.h"
55 #include "DOMWindow.h"
56 #include "DateComponents.h"
57 #include "DebugPageOverlays.h"
58 #include "DocumentLoader.h"
59 #include "DocumentMarkerController.h"
60 #include "DocumentSharedObjectPool.h"
61 #include "DocumentType.h"
64 #include "ElementIterator.h"
65 #include "EventHandler.h"
66 #include "ExtensionStyleSheets.h"
67 #include "FocusController.h"
68 #include "FocusEvent.h"
69 #include "FontFaceSet.h"
70 #include "FormController.h"
71 #include "FrameLoader.h"
72 #include "FrameLoaderClient.h"
73 #include "FrameView.h"
74 #include "GenericCachedHTMLCollection.h"
75 #include "HTMLAllCollection.h"
76 #include "HTMLAnchorElement.h"
77 #include "HTMLBaseElement.h"
78 #include "HTMLBodyElement.h"
79 #include "HTMLCanvasElement.h"
80 #include "HTMLDocument.h"
81 #include "HTMLElementFactory.h"
82 #include "HTMLFormControlElement.h"
83 #include "HTMLFrameOwnerElement.h"
84 #include "HTMLFrameSetElement.h"
85 #include "HTMLHeadElement.h"
86 #include "HTMLHtmlElement.h"
87 #include "HTMLImageElement.h"
88 #include "HTMLInputElement.h"
89 #include "HTMLLinkElement.h"
90 #include "HTMLMediaElement.h"
91 #include "HTMLNameCollection.h"
92 #include "HTMLParserIdioms.h"
93 #include "HTMLPictureElement.h"
94 #include "HTMLPlugInElement.h"
95 #include "HTMLScriptElement.h"
96 #include "HTMLStyleElement.h"
97 #include "HTMLTitleElement.h"
98 #include "HTMLUnknownElement.h"
99 #include "HTTPHeaderNames.h"
100 #include "HTTPParsers.h"
101 #include "HashChangeEvent.h"
103 #include "HitTestResult.h"
104 #include "ImageBitmapRenderingContext.h"
105 #include "ImageLoader.h"
106 #include "InspectorInstrumentation.h"
107 #include "JSCustomElementInterface.h"
108 #include "JSDOMPromiseDeferred.h"
109 #include "JSLazyEventListener.h"
110 #include "KeyboardEvent.h"
111 #include "LayoutDisallowedScope.h"
112 #include "LoaderStrategy.h"
114 #include "MainFrame.h"
115 #include "MediaCanStartListener.h"
116 #include "MediaProducer.h"
117 #include "MediaQueryList.h"
118 #include "MediaQueryMatcher.h"
119 #include "MessageEvent.h"
120 #include "MouseEventWithHitTestResults.h"
121 #include "MutationEvent.h"
122 #include "NameNodeList.h"
123 #include "NavigationDisabler.h"
124 #include "NavigationScheduler.h"
125 #include "NestingLevelIncrementer.h"
126 #include "NoEventDispatchAssertion.h"
127 #include "NodeIterator.h"
128 #include "NodeRareData.h"
129 #include "NodeWithIndex.h"
130 #include "OriginAccessEntry.h"
131 #include "OverflowEvent.h"
132 #include "PageConsoleClient.h"
133 #include "PageGroup.h"
134 #include "PageTransitionEvent.h"
135 #include "PlatformLocale.h"
136 #include "PlatformMediaSessionManager.h"
137 #include "PlatformScreen.h"
138 #include "PlatformStrategies.h"
139 #include "PlugInsResources.h"
140 #include "PluginDocument.h"
141 #include "PointerLockController.h"
142 #include "PopStateEvent.h"
143 #include "ProcessingInstruction.h"
144 #include "PublicSuffix.h"
145 #include "RealtimeMediaSourceCenter.h"
146 #include "RenderChildIterator.h"
147 #include "RenderLayerCompositor.h"
148 #include "RenderTreeUpdater.h"
149 #include "RenderView.h"
150 #include "RenderWidget.h"
151 #include "RequestAnimationFrameCallback.h"
152 #include "ResourceLoadObserver.h"
153 #include "RuntimeEnabledFeatures.h"
154 #include "SVGDocumentExtensions.h"
155 #include "SVGElement.h"
156 #include "SVGElementFactory.h"
157 #include "SVGNames.h"
158 #include "SVGSVGElement.h"
159 #include "SVGTitleElement.h"
160 #include "SVGZoomEvent.h"
161 #include "SchemeRegistry.h"
162 #include "ScopedEventQueue.h"
163 #include "ScriptController.h"
164 #include "ScriptModuleLoader.h"
165 #include "ScriptRunner.h"
166 #include "ScriptSourceCode.h"
167 #include "ScriptedAnimationController.h"
168 #include "ScrollingCoordinator.h"
169 #include "SecurityOrigin.h"
170 #include "SecurityOriginData.h"
171 #include "SecurityOriginPolicy.h"
172 #include "SecurityPolicy.h"
173 #include "SegmentedString.h"
174 #include "SelectorQuery.h"
175 #include "Settings.h"
176 #include "ShadowRoot.h"
177 #include "SocketProvider.h"
178 #include "StorageEvent.h"
179 #include "StringCallback.h"
180 #include "StyleProperties.h"
181 #include "StyleResolveForDocument.h"
182 #include "StyleResolver.h"
183 #include "StyleScope.h"
184 #include "StyleSheetContents.h"
185 #include "StyleSheetList.h"
186 #include "StyleTreeResolver.h"
187 #include "SubresourceLoader.h"
188 #include "TextAutoSizing.h"
189 #include "TextEvent.h"
190 #include "TextNodeTraversal.h"
191 #include "TransformSource.h"
192 #include "TreeWalker.h"
193 #include "UserGestureIndicator.h"
194 #include "ValidationMessageClient.h"
195 #include "VisibilityChangeClient.h"
196 #include "VisitedLinkState.h"
197 #include "WheelEvent.h"
198 #include "WindowFeatures.h"
199 #include "XMLDocument.h"
200 #include "XMLDocumentParser.h"
201 #include "XMLNSNames.h"
202 #include "XMLNames.h"
203 #include "XPathEvaluator.h"
204 #include "XPathExpression.h"
205 #include "XPathNSResolver.h"
206 #include "XPathResult.h"
208 #include <inspector/ConsoleMessage.h>
209 #include <inspector/ScriptCallStack.h>
210 #include <pal/Logger.h>
211 #include <wtf/CurrentTime.h>
212 #include <wtf/Language.h>
213 #include <wtf/NeverDestroyed.h>
214 #include <wtf/SetForScope.h>
215 #include <wtf/SystemTracing.h>
216 #include <wtf/UUID.h>
217 #include <wtf/text/StringBuffer.h>
218 #include <yarr/RegularExpression.h>
220 #if ENABLE(DEVICE_ORIENTATION)
221 #include "DeviceMotionEvent.h"
222 #include "DeviceOrientationEvent.h"
225 #if ENABLE(FULLSCREEN_API)
226 #include "RenderFullScreen.h"
229 #if ENABLE(INDEXED_DATABASE)
230 #include "IDBConnectionProxy.h"
231 #include "IDBOpenDBRequest.h"
235 #include "CSSFontSelector.h"
236 #include "DeviceMotionClientIOS.h"
237 #include "DeviceMotionController.h"
238 #include "DeviceOrientationClientIOS.h"
239 #include "DeviceOrientationController.h"
240 #include "Geolocation.h"
241 #include "Navigator.h"
242 #include "NavigatorGeolocation.h"
243 #include "WKContentObservation.h"
246 #if ENABLE(IOS_GESTURE_EVENTS)
247 #include "GestureEvent.h"
251 #include "MathMLElement.h"
252 #include "MathMLElementFactory.h"
253 #include "MathMLNames.h"
256 #if ENABLE(MEDIA_SESSION)
257 #include "MediaSession.h"
261 #include "QuickLook.h"
264 #if ENABLE(TOUCH_EVENTS)
265 #include "TouchEvent.h"
268 #if ENABLE(VIDEO_TRACK)
269 #include "CaptionUserPreferences.h"
272 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
273 #include "MediaPlaybackTargetClient.h"
277 #include "XSLTProcessor.h"
280 #if ENABLE(MEDIA_STREAM)
281 #include "MediaStream.h"
282 #include "MediaStreamRegistry.h"
286 #include "WebGLRenderingContext.h"
289 #include "WebGL2RenderingContext.h"
292 #include "WebGPURenderingContext.h"
299 using namespace Unicode;
301 using namespace HTMLNames;
303 static const unsigned cMaxWriteRecursionDepth = 21;
304 bool Document::hasEverCreatedAnAXObjectCache = false;
306 // DOM Level 2 says (letters added):
308 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
309 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
310 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
311 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
312 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
313 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
314 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
315 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
316 // i) Characters ':' and '_' are allowed as name-start characters.
317 // j) Characters '-' and '.' are allowed as name characters.
319 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
321 static inline bool isValidNameStart(UChar32 c)
324 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
328 if (c == ':' || c == '_')
331 // rules (a) and (f) above
332 if (!(U_GET_GC_MASK(c) & (U_GC_LL_MASK | U_GC_LU_MASK | U_GC_LO_MASK | U_GC_LT_MASK | U_GC_NL_MASK)))
336 if (c >= 0xF900 && c < 0xFFFE)
340 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
341 if (type == U_DT_FONT || type == U_DT_COMPAT)
347 static inline bool isValidNamePart(UChar32 c)
349 // rules (a), (e), and (i) above
350 if (isValidNameStart(c))
353 // rules (g) and (h) above
354 if (c == 0x00B7 || c == 0x0387)
358 if (c == '-' || c == '.')
361 // rules (b) and (f) above
362 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
366 if (c >= 0xF900 && c < 0xFFFE)
370 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
371 if (type == U_DT_FONT || type == U_DT_COMPAT)
377 static Widget* widgetForElement(Element* focusedElement)
381 auto* renderer = focusedElement->renderer();
382 if (!is<RenderWidget>(renderer))
384 return downcast<RenderWidget>(*renderer).widget();
387 static bool acceptsEditingFocus(const Element& element)
389 ASSERT(element.hasEditableStyle());
391 auto* root = element.rootEditableElement();
392 Frame* frame = element.document().frame();
396 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
399 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
401 // targetFrame can be 0 when we're trying to navigate a top-level frame
402 // that has a 0 opener.
406 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
407 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
408 Document* ancestorDocument = ancestorFrame->document();
409 // FIXME: Should be an ASSERT? Frames should alway have documents.
410 if (!ancestorDocument)
413 const SecurityOrigin& ancestorSecurityOrigin = ancestorDocument->securityOrigin();
414 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
417 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
418 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
419 // something more general instead?
420 if (isLocalActiveOrigin && ancestorSecurityOrigin.isLocal())
427 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
429 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
431 // FIXME: should we print to the console of the document performing the navigation instead?
432 frame->document()->domWindow()->printErrorMessage(message);
435 uint64_t Document::s_globalTreeVersion = 0;
437 HashSet<Document*>& Document::allDocuments()
439 static NeverDestroyed<HashSet<Document*>> documents;
443 static inline int currentOrientation(Frame* frame)
445 #if ENABLE(ORIENTATION_EVENTS)
447 return frame->orientation();
454 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
455 : ContainerNode(*this, CreateDocument)
457 , FrameDestructionObserver(frame)
458 #if ENABLE(IOS_TOUCH_EVENTS)
459 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
461 , m_settings(frame ? Ref<Settings>(frame->settings()) : Settings::create(nullptr))
462 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
463 , m_domTreeVersion(++s_globalTreeVersion)
464 , m_styleScope(std::make_unique<Style::Scope>(*this))
465 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
466 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
467 , m_markers(std::make_unique<DocumentMarkerController>(*this))
468 , m_styleRecalcTimer([this] { updateStyleIfNeeded(); })
469 , m_documentCreationTime(MonotonicTime::now())
470 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
471 , m_moduleLoader(std::make_unique<ScriptModuleLoader>(*this))
472 , m_applyPendingXSLTransformsTimer(*this, &Document::applyPendingXSLTransformsTimerFired)
473 , m_xmlVersion(ASCIILiteral("1.0"))
474 , m_constantPropertyMap(std::make_unique<ConstantPropertyMap>(*this))
475 , m_documentClasses(documentClasses)
476 , m_eventQueue(*this)
477 #if ENABLE(FULLSCREEN_API)
478 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
480 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
482 #if ENABLE(DEVICE_ORIENTATION)
483 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
484 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
485 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
486 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
489 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
490 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
491 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
492 , m_fontSelector(CSSFontSelector::create(*this))
493 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
494 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
495 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
496 , m_isSynthesized(constructionFlags & Synthesized)
497 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
498 , m_orientationNotifier(currentOrientation(frame))
500 allDocuments().add(this);
502 // We depend on the url getting immediately set in subframes, but we
503 // also depend on the url NOT getting immediately set in opened windows.
504 // See fast/dom/early-frame-url.html
505 // and fast/dom/location-new-window-no-crash.html, respectively.
506 // FIXME: Can/should we unify this behavior?
507 if ((frame && frame->ownerElement()) || !url.isEmpty())
510 m_cachedResourceLoader->setDocument(this);
513 resetVisitedLinkColor();
514 resetActiveLinkColor();
516 initSecurityContext();
519 m_fontSelector->registerForInvalidationCallbacks(*this);
521 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
522 nodeListAndCollectionCount = 0;
525 #if ENABLE(FULLSCREEN_API)
527 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
532 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
534 } while ((owner = owner->document().ownerElement()));
540 Ref<Document> Document::create(Document& contextDocument)
542 auto document = adoptRef(*new Document(nullptr, URL()));
543 document->setContextDocument(contextDocument);
544 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
548 Document::~Document()
550 allDocuments().remove(this);
552 ASSERT(!renderView());
553 ASSERT(m_pageCacheState != InPageCache);
554 ASSERT(m_ranges.isEmpty());
555 ASSERT(!m_parentTreeScope);
556 ASSERT(!m_disabledFieldsetElementsCount);
557 ASSERT(m_inDocumentShadowRoots.isEmpty());
559 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
560 m_deviceMotionClient->deviceMotionControllerDestroyed();
561 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
564 if (m_templateDocument)
565 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
567 // FIXME: Should we reset m_domWindow when we detach from the Frame?
569 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
571 m_scriptRunner = nullptr;
572 m_moduleLoader = nullptr;
574 removeAllEventListeners();
576 // Currently we believe that Document can never outlive the parser.
577 // Although the Document may be replaced synchronously, DocumentParsers
578 // generally keep at least one reference to an Element which would in turn
579 // has a reference to the Document. If you hit this ASSERT, then that
580 // assumption is wrong. DocumentParser::detach() should ensure that even
581 // if the DocumentParser outlives the Document it won't cause badness.
582 ASSERT(!m_parser || m_parser->refCount() == 1);
585 if (this == &topDocument())
586 clearAXObjectCache();
590 if (m_styleSheetList)
591 m_styleSheetList->detachFromDocument();
593 extensionStyleSheets().detachFromDocument();
595 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
596 m_fontSelector->clearDocument();
597 m_fontSelector->unregisterForInvalidationCallbacks(*this);
599 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
600 // load the initial empty document and the SVGDocument with the same DocumentLoader).
601 if (m_cachedResourceLoader->document() == this)
602 m_cachedResourceLoader->setDocument(nullptr);
605 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
606 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
609 // We must call clearRareData() here since a Document class inherits TreeScope
610 // as well as Node. See a comment on TreeScope.h for the reason.
614 ASSERT(m_listsInvalidatedAtDocument.isEmpty());
615 ASSERT(m_collectionsInvalidatedAtDocument.isEmpty());
617 for (unsigned count : m_nodeListAndCollectionCounts)
618 ASSERT_UNUSED(count, !count);
621 m_logger->removeObserver(*this);
624 void Document::removedLastRef()
626 ASSERT(!m_deletionHasBegun);
627 if (m_referencingNodeCount) {
628 // If removing a child removes the last node reference, we don't want the scope to be destroyed
629 // until after removeDetachedChildren returns, so we protect ourselves.
630 incrementReferencingNodeCount();
632 RELEASE_ASSERT(!hasLivingRenderTree());
633 // We must make sure not to be retaining any of our children through
634 // these extra pointers or we will create a reference cycle.
635 m_focusedElement = nullptr;
636 m_hoveredElement = nullptr;
637 m_activeElement = nullptr;
638 m_titleElement = nullptr;
639 m_documentElement = nullptr;
640 m_focusNavigationStartingNode = nullptr;
641 m_userActionElements.documentDidRemoveLastRef();
642 #if ENABLE(FULLSCREEN_API)
643 m_fullScreenElement = nullptr;
644 m_fullScreenElementStack.clear();
646 m_associatedFormControls.clear();
650 // removeDetachedChildren() doesn't always unregister IDs,
651 // so tear down scope information up front to avoid having
652 // stale references in the map.
654 destroyTreeScopeData();
655 removeDetachedChildren();
656 m_formController = nullptr;
660 m_cssCanvasElements.clear();
665 // We need to do this right now since selfOnlyDeref() can delete this.
666 m_inRemovedLastRefFunction = false;
668 decrementReferencingNodeCount();
671 m_inRemovedLastRefFunction = false;
672 m_deletionHasBegun = true;
678 void Document::commonTeardown()
681 accessSVGExtensions().pauseAnimations();
683 clearScriptedAnimationController();
686 Element* Document::getElementByAccessKey(const String& key)
690 if (!m_accessKeyMapValid) {
691 buildAccessKeyMap(this);
692 m_accessKeyMapValid = true;
694 return m_elementsByAccessKey.get(key.impl());
697 void Document::buildAccessKeyMap(TreeScope* scope)
700 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
701 const AtomicString& accessKey = element.attributeWithoutSynchronization(accesskeyAttr);
702 if (!accessKey.isEmpty())
703 m_elementsByAccessKey.set(accessKey.impl(), &element);
705 if (ShadowRoot* root = element.shadowRoot())
706 buildAccessKeyMap(root);
710 void Document::invalidateAccessKeyMap()
712 m_accessKeyMapValid = false;
713 m_elementsByAccessKey.clear();
716 void Document::addImageElementByUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
718 return m_imagesByUsemap.add(name, element, *this);
721 void Document::removeImageElementByUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
723 return m_imagesByUsemap.remove(name, element);
726 HTMLImageElement* Document::imageElementByUsemap(const AtomicStringImpl& name) const
728 return m_imagesByUsemap.getElementByUsemap(name, *this);
731 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
733 if (selectorString.isEmpty())
734 return Exception { SyntaxError };
735 if (!m_selectorQueryCache)
736 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
737 return m_selectorQueryCache->add(selectorString, *this);
740 void Document::clearSelectorQueryCache()
742 m_selectorQueryCache = nullptr;
745 MediaQueryMatcher& Document::mediaQueryMatcher()
747 if (!m_mediaQueryMatcher)
748 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
749 return *m_mediaQueryMatcher;
752 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
754 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
756 bool wasInQuirksMode = inQuirksMode();
757 m_compatibilityMode = mode;
759 clearSelectorQueryCache();
761 if (inQuirksMode() != wasInQuirksMode) {
762 // All user stylesheets have to reparse using the different mode.
763 extensionStyleSheets().clearPageUserSheet();
764 extensionStyleSheets().invalidateInjectedStyleSheetCache();
768 String Document::compatMode() const
770 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
773 void Document::resetLinkColor()
775 m_linkColor = Color(0, 0, 238);
778 void Document::resetVisitedLinkColor()
780 m_visitedLinkColor = Color(85, 26, 139);
783 void Document::resetActiveLinkColor()
785 m_activeLinkColor = Color(255, 0, 0);
788 DOMImplementation& Document::implementation()
790 if (!m_implementation)
791 m_implementation = std::make_unique<DOMImplementation>(*this);
792 return *m_implementation;
795 bool Document::hasManifest() const
797 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
800 DocumentType* Document::doctype() const
802 for (Node* node = firstChild(); node; node = node->nextSibling()) {
803 if (node->isDocumentTypeNode())
804 return static_cast<DocumentType*>(node);
809 void Document::childrenChanged(const ChildChange& change)
811 ContainerNode::childrenChanged(change);
813 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
814 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
815 // otherwise, we need to detect the doc type changes before updating the viewport.
816 if (Page* page = this->page())
817 page->chrome().didReceiveDocType(*frame());
819 Element* newDocumentElement = childrenOfType<Element>(*this).first();
820 if (newDocumentElement == m_documentElement)
822 m_documentElement = newDocumentElement;
823 // The root style used for media query matching depends on the document element.
824 styleScope().clearResolver();
827 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
829 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled()
830 || Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
831 return HTMLUnknownElement::create(name, document);
833 auto element = HTMLElement::create(name, document);
834 element->setIsCustomElementUpgradeCandidate();
838 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const AtomicString& localName)
840 return createUpgradeCandidateElement(document, QualifiedName { nullAtom(), localName, xhtmlNamespaceURI });
843 static inline bool isValidHTMLElementName(const AtomicString& localName)
845 return Document::isValidName(localName);
848 static inline bool isValidHTMLElementName(const QualifiedName& name)
850 return Document::isValidName(name.localName());
853 template<typename NameType>
854 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const NameType& name)
856 auto element = HTMLElementFactory::createKnownElement(name, document);
858 return Ref<Element> { element.releaseNonNull() };
860 if (auto* window = document.domWindow()) {
861 auto* registry = window->customElementRegistry();
862 if (UNLIKELY(registry)) {
863 if (auto* elementInterface = registry->findInterface(name))
864 return elementInterface->constructElementWithFallback(document, name);
868 if (UNLIKELY(!isValidHTMLElementName(name)))
869 return Exception { InvalidCharacterError };
871 return Ref<Element> { createUpgradeCandidateElement(document, name) };
874 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomicString& name)
876 if (isHTMLDocument())
877 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
879 if (isXHTMLDocument())
880 return createHTMLElementWithNameValidation(*this, name);
882 if (!isValidName(name))
883 return Exception { InvalidCharacterError };
885 return createElement(QualifiedName(nullAtom(), name, nullAtom()), false);
888 Ref<DocumentFragment> Document::createDocumentFragment()
890 return DocumentFragment::create(document());
893 Ref<Text> Document::createTextNode(const String& data)
895 return Text::create(*this, data);
898 Ref<Comment> Document::createComment(const String& data)
900 return Comment::create(*this, data);
903 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
905 if (isHTMLDocument())
906 return Exception { NotSupportedError };
907 return CDATASection::create(*this, data);
910 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
912 if (!isValidName(target))
913 return Exception { InvalidCharacterError };
915 if (data.contains("?>"))
916 return Exception { InvalidCharacterError };
918 return ProcessingInstruction::create(*this, target, data);
921 Ref<Text> Document::createEditingTextNode(const String& text)
923 return Text::createEditingText(*this, text);
926 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
928 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
929 return propertySet->ensureCSSStyleDeclaration();
932 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
934 switch (nodeToImport.nodeType()) {
935 case DOCUMENT_FRAGMENT_NODE:
936 if (nodeToImport.isShadowRoot())
941 case CDATA_SECTION_NODE:
942 case PROCESSING_INSTRUCTION_NODE:
944 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
947 // FIXME: This will "Attr::normalize" child nodes of Attr.
948 return Ref<Node> { Attr::create(*this, QualifiedName(nullAtom(), downcast<Attr>(nodeToImport).name(), nullAtom()), downcast<Attr>(nodeToImport).value()) };
950 case DOCUMENT_NODE: // Can't import a document into another document.
951 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
955 return Exception { NotSupportedError };
959 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
961 EventQueueScope scope;
963 switch (source.nodeType()) {
965 return Exception { NotSupportedError };
966 case ATTRIBUTE_NODE: {
967 auto& attr = downcast<Attr>(source);
968 if (auto* element = attr.ownerElement()) {
969 auto result = element->removeAttributeNode(attr);
970 if (result.hasException())
971 return result.releaseException();
976 if (source.isShadowRoot()) {
977 // ShadowRoot cannot disconnect itself from the host node.
978 return Exception { HierarchyRequestError };
980 if (is<HTMLFrameOwnerElement>(source)) {
981 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
982 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
983 return Exception { HierarchyRequestError };
985 auto result = source.remove();
986 if (result.hasException())
987 return result.releaseException();
988 RELEASE_ASSERT(!source.isConnected());
989 RELEASE_ASSERT(!source.parentNode());
992 source.setTreeScopeRecursively(*this);
994 return Ref<Node> { source };
997 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
999 // These checks are from DOM Core Level 2, createElementNS
1000 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1001 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1003 if (qName.prefix() == xmlAtom() && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1006 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1007 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1008 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1009 if (qName.prefix() == xmlnsAtom() || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom()))
1010 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1011 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1014 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1016 return hasValidNamespaceForElements(qName);
1019 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1021 if (auto* window = document.domWindow()) {
1022 auto* registry = window->customElementRegistry();
1023 if (UNLIKELY(registry)) {
1024 if (auto* elementInterface = registry->findInterface(name)) {
1025 auto element = HTMLElement::create(name, document);
1026 element->enqueueToUpgrade(*elementInterface);
1031 // FIXME: Should we also check the equality of prefix between the custom element and name?
1032 return createUpgradeCandidateElement(document, name);
1035 // FIXME: This should really be in a possible ElementFactory class.
1036 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1038 RefPtr<Element> element;
1040 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1041 if (name.namespaceURI() == xhtmlNamespaceURI) {
1042 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1043 if (UNLIKELY(!element))
1044 element = createFallbackHTMLElement(*this, name);
1045 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1046 element = SVGElementFactory::createElement(name, *this, createdByParser);
1048 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1049 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1053 m_sawElementsInKnownNamespaces = true;
1055 element = Element::create(name, document());
1057 // <image> uses imgTag so we need a special rule.
1058 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1060 return element.releaseNonNull();
1063 // https://html.spec.whatwg.org/#valid-custom-element-name
1065 struct UnicodeCodePointRange {
1070 #if !ASSERT_DISABLED
1072 static inline bool operator<(const UnicodeCodePointRange& a, const UnicodeCodePointRange& b)
1074 ASSERT(a.minimum <= a.maximum);
1075 ASSERT(b.minimum <= b.maximum);
1076 return a.maximum < b.minimum;
1081 static inline bool operator<(const UnicodeCodePointRange& a, UChar32 b)
1083 ASSERT(a.minimum <= a.maximum);
1084 return a.maximum < b;
1087 static inline bool operator<(UChar32 a, const UnicodeCodePointRange& b)
1089 ASSERT(b.minimum <= b.maximum);
1090 return a < b.minimum;
1093 static inline bool isPotentialCustomElementNameCharacter(UChar32 character)
1095 static const UnicodeCodePointRange ranges[] = {
1112 { 0x10000, 0xEFFFF },
1115 ASSERT(std::is_sorted(std::begin(ranges), std::end(ranges)));
1116 return std::binary_search(std::begin(ranges), std::end(ranges), character);
1119 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomicString& localName)
1121 if (!isASCIILower(localName[0]))
1122 return CustomElementNameValidationStatus::FirstCharacterIsNotLowercaseASCIILetter;
1124 bool containsHyphen = false;
1125 for (auto character : StringView(localName).codePoints()) {
1126 if (isASCIIUpper(character))
1127 return CustomElementNameValidationStatus::ContainsUppercaseASCIILetter;
1128 if (!isPotentialCustomElementNameCharacter(character))
1129 return CustomElementNameValidationStatus::ContainsDisallowedCharacter;
1130 if (character == '-')
1131 containsHyphen = true;
1134 if (!containsHyphen)
1135 return CustomElementNameValidationStatus::ContainsNoHyphen;
1138 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag.localName();
1140 static NeverDestroyed<const AtomicString> annotationXmlLocalName("annotation-xml", AtomicString::ConstructFromLiteral);
1143 if (localName == SVGNames::color_profileTag.localName()
1144 || localName == SVGNames::font_faceTag.localName()
1145 || localName == SVGNames::font_face_formatTag.localName()
1146 || localName == SVGNames::font_face_nameTag.localName()
1147 || localName == SVGNames::font_face_srcTag.localName()
1148 || localName == SVGNames::font_face_uriTag.localName()
1149 || localName == SVGNames::missing_glyphTag.localName()
1150 || localName == annotationXmlLocalName)
1151 return CustomElementNameValidationStatus::ConflictsWithStandardElementName;
1153 return CustomElementNameValidationStatus::Valid;
1156 bool Document::isCSSGridLayoutEnabled() const
1158 return RuntimeEnabledFeatures::sharedFeatures().isCSSGridLayoutEnabled();
1161 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName)
1163 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1164 if (parseResult.hasException())
1165 return parseResult.releaseException();
1166 QualifiedName parsedName { parseResult.releaseReturnValue() };
1167 if (!hasValidNamespaceForElements(parsedName))
1168 return Exception { NamespaceError };
1170 if (parsedName.namespaceURI() == xhtmlNamespaceURI)
1171 return createHTMLElementWithNameValidation(*this, parsedName);
1173 return createElement(parsedName, false);
1176 void Document::setReadyState(ReadyState readyState)
1178 if (readyState == m_readyState)
1181 switch (readyState) {
1183 if (!m_documentTiming.domLoading)
1184 m_documentTiming.domLoading = MonotonicTime::now();
1187 if (!m_documentTiming.domInteractive)
1188 m_documentTiming.domInteractive = MonotonicTime::now();
1191 if (!m_documentTiming.domComplete)
1192 m_documentTiming.domComplete = MonotonicTime::now();
1196 m_readyState = readyState;
1197 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1199 if (settings().suppressesIncrementalRendering())
1200 setVisualUpdatesAllowed(readyState);
1203 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1205 ASSERT(settings().suppressesIncrementalRendering());
1206 switch (readyState) {
1208 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1209 ASSERT(m_visualUpdatesAllowed);
1210 setVisualUpdatesAllowed(false);
1213 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1216 if (m_visualUpdatesSuppressionTimer.isActive()) {
1217 ASSERT(!m_visualUpdatesAllowed);
1219 if (!view()->visualUpdatesAllowedByClient())
1222 setVisualUpdatesAllowed(true);
1224 ASSERT(m_visualUpdatesAllowed);
1229 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1231 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1234 m_visualUpdatesAllowed = visualUpdatesAllowed;
1236 if (visualUpdatesAllowed)
1237 m_visualUpdatesSuppressionTimer.stop();
1239 m_visualUpdatesSuppressionTimer.startOneShot(1_s * settings().incrementalRenderingSuppressionTimeoutInSeconds());
1241 if (!visualUpdatesAllowed)
1244 RefPtr<FrameView> frameView = view();
1245 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1249 if (Page* page = this->page()) {
1250 if (frame()->isMainFrame()) {
1251 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1252 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1253 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1258 view()->updateCompositingLayersAfterLayout();
1260 if (RenderView* renderView = this->renderView())
1261 renderView->repaintViewAndCompositedLayers();
1263 if (Frame* frame = this->frame())
1264 frame->loader().forcePageTransitionIfNeeded();
1267 void Document::visualUpdatesSuppressionTimerFired()
1269 ASSERT(!m_visualUpdatesAllowed);
1271 // If the client is extending the visual update suppression period explicitly, the
1272 // watchdog should not re-enable visual updates itself, but should wait for the client.
1273 if (!view()->visualUpdatesAllowedByClient())
1276 setVisualUpdatesAllowed(true);
1279 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1281 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1282 // both of which we can determine by looking at the timer.
1284 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1285 setVisualUpdatesAllowed(true);
1288 String Document::characterSetWithUTF8Fallback() const
1290 AtomicString name = encoding();
1293 return UTF8Encoding().domName();
1296 String Document::defaultCharsetForLegacyBindings() const
1299 UTF8Encoding().domName();
1300 return settings().defaultTextEncodingName();
1303 void Document::setCharset(const String& charset)
1307 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1310 void Document::setContentLanguage(const String& language)
1312 if (m_contentLanguage == language)
1314 m_contentLanguage = language;
1316 // Recalculate style so language is used when selecting the initial font.
1317 m_styleScope->didChangeStyleSheetEnvironment();
1320 ExceptionOr<void> Document::setXMLVersion(const String& version)
1322 if (!XMLDocumentParser::supportsXMLVersion(version))
1323 return Exception { NotSupportedError };
1325 m_xmlVersion = version;
1329 void Document::setXMLStandalone(bool standalone)
1331 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1334 void Document::setDocumentURI(const String& uri)
1336 // This property is read-only from JavaScript, but writable from Objective-C.
1337 m_documentURI = uri;
1341 void Document::setContent(const String& content)
1344 // FIXME: This should probably use insert(), but that's (intentionally)
1345 // not implemented for the XML parser as it's normally synonymous with
1346 // document.write(). append() will end up yielding, but close() will
1347 // pump the tokenizer syncrhonously and finish the parse.
1348 m_parser->append(content.impl());
1352 String Document::suggestedMIMEType() const
1354 if (isXHTMLDocument())
1355 return ASCIILiteral("application/xhtml+xml");
1356 if (isSVGDocument())
1357 return ASCIILiteral("image/svg+xml");
1358 if (xmlStandalone())
1359 return ASCIILiteral("text/xml");
1360 if (isHTMLDocument())
1361 return ASCIILiteral("text/html");
1362 if (DocumentLoader* loader = this->loader())
1363 return loader->responseMIMEType();
1367 void Document::overrideMIMEType(const String& mimeType)
1369 m_overriddenMIMEType = mimeType;
1372 String Document::contentType() const
1374 if (!m_overriddenMIMEType.isNull())
1375 return m_overriddenMIMEType;
1377 if (DocumentLoader* documentLoader = loader())
1378 return documentLoader->currentContentType();
1380 String mimeType = suggestedMIMEType();
1381 if (!mimeType.isNull())
1384 return ASCIILiteral("application/xml");
1387 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1389 return caretRangeFromPoint(LayoutPoint(x, y));
1392 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1394 if (!hasLivingRenderTree())
1397 LayoutPoint localPoint;
1398 Node* node = nodeFromPoint(clientPoint, &localPoint);
1402 RenderObject* renderer = node->renderer();
1405 Position rangeCompliantPosition = renderer->positionForPoint(localPoint).parentAnchoredEquivalent();
1406 if (rangeCompliantPosition.isNull())
1409 unsigned offset = rangeCompliantPosition.offsetInContainerNode();
1410 node = &retargetToScope(*rangeCompliantPosition.containerNode());
1411 if (node != rangeCompliantPosition.containerNode())
1414 return Range::create(*this, node, offset, node, offset);
1417 Element* Document::scrollingElement()
1419 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1420 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1425 template<typename CharacterType> static inline String canonicalizedTitle(Document& document, const String& title)
1427 // FIXME: Compiling a separate copy of this for LChar and UChar is likely unnecessary.
1428 // FIXME: Missing an optimized case for when title is fine as-is. This unnecessarily allocates
1429 // and keeps around a new copy, and it's even the less optimal type of StringImpl with a separate buffer.
1430 // Could probably just use StringBuilder instead.
1432 auto* characters = title.characters<CharacterType>();
1433 unsigned length = title.length();
1435 StringBuffer<CharacterType> buffer { length };
1436 unsigned bufferLength = 0;
1438 auto* decoder = document.decoder();
1439 auto backslashAsCurrencySymbol = decoder ? decoder->encoding().backslashAsCurrencySymbol() : '\\';
1441 // Collapse runs of HTML spaces into single space characters.
1442 // Strip leading and trailing spaces.
1443 // Replace backslashes with currency symbols.
1444 bool previousCharacterWasHTMLSpace = false;
1445 for (unsigned i = 0; i < length; ++i) {
1446 auto character = characters[i];
1447 if (isHTMLSpace(character))
1448 previousCharacterWasHTMLSpace = true;
1450 if (character == '\\')
1451 character = backslashAsCurrencySymbol;
1452 if (previousCharacterWasHTMLSpace && bufferLength)
1453 buffer[bufferLength++] = ' ';
1454 buffer[bufferLength++] = character;
1455 previousCharacterWasHTMLSpace = false;
1461 buffer.shrink(bufferLength);
1462 return String::adopt(WTFMove(buffer));
1465 void Document::updateTitle(const StringWithDirection& title)
1467 if (m_rawTitle == title)
1473 if (!m_title.string.isEmpty()) {
1474 if (m_title.string.is8Bit())
1475 m_title.string = canonicalizedTitle<LChar>(*this, m_title.string);
1477 m_title.string = canonicalizedTitle<UChar>(*this, m_title.string);
1480 if (auto* loader = this->loader())
1481 loader->setTitle(m_title);
1484 void Document::updateTitleFromTitleElement()
1486 if (!m_titleElement) {
1491 if (is<HTMLTitleElement>(*m_titleElement))
1492 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1493 else if (is<SVGTitleElement>(*m_titleElement)) {
1494 // FIXME: Does the SVG title element have a text direction?
1495 updateTitle({ downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR });
1499 void Document::setTitle(const String& title)
1501 if (!m_titleElement) {
1502 if (isHTMLDocument() || isXHTMLDocument()) {
1503 auto* headElement = head();
1506 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1507 headElement->appendChild(*m_titleElement);
1508 } else if (isSVGDocument()) {
1509 auto* element = documentElement();
1510 if (!is<SVGSVGElement>(element))
1512 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1513 element->insertBefore(*m_titleElement, element->firstChild());
1515 } else if (!isHTMLDocument() && !isXHTMLDocument() && !isSVGDocument()) {
1516 // FIXME: What exactly is the point of this? This seems like a strange moment
1517 // in time to demote something from being m_titleElement, when setting the
1518 // value of the title attribute. Do we have test coverage for this?
1519 m_titleElement = nullptr;
1522 if (is<HTMLTitleElement>(m_titleElement.get()))
1523 downcast<HTMLTitleElement>(*m_titleElement).setTextContent(title);
1524 else if (is<SVGTitleElement>(m_titleElement.get()))
1525 downcast<SVGTitleElement>(*m_titleElement).setTextContent(title);
1527 updateTitle({ title, LTR });
1530 template<typename> struct TitleTraits;
1532 template<> struct TitleTraits<HTMLTitleElement> {
1533 static bool isInEligibleLocation(HTMLTitleElement& element) { return element.isConnected() && !element.isInShadowTree(); }
1534 static HTMLTitleElement* findTitleElement(Document& document) { return descendantsOfType<HTMLTitleElement>(document).first(); }
1537 template<> struct TitleTraits<SVGTitleElement> {
1538 static bool isInEligibleLocation(SVGTitleElement& element) { return element.parentNode() == element.document().documentElement(); }
1539 static SVGTitleElement* findTitleElement(Document& document) { return childrenOfType<SVGTitleElement>(*document.documentElement()).first(); }
1542 template<typename TitleElement> Element* selectNewTitleElement(Document& document, Element* oldTitleElement, Element& changingTitleElement)
1544 using Traits = TitleTraits<TitleElement>;
1546 if (!is<TitleElement>(changingTitleElement)) {
1547 ASSERT(oldTitleElement == Traits::findTitleElement(document));
1548 return oldTitleElement;
1551 if (oldTitleElement)
1552 return Traits::findTitleElement(document);
1554 // Optimized common case: We have no title element yet.
1555 // We can figure out which title element should be used without searching.
1556 bool isEligible = Traits::isInEligibleLocation(downcast<TitleElement>(changingTitleElement));
1557 auto* newTitleElement = isEligible ? &changingTitleElement : nullptr;
1558 ASSERT(newTitleElement == Traits::findTitleElement(document));
1559 return newTitleElement;
1562 void Document::updateTitleElement(Element& changingTitleElement)
1564 // Most documents use HTML title rules.
1565 // Documents with SVG document elements use SVG title rules.
1566 auto selectTitleElement = is<SVGSVGElement>(documentElement())
1567 ? selectNewTitleElement<SVGTitleElement> : selectNewTitleElement<HTMLTitleElement>;
1568 auto newTitleElement = selectTitleElement(*this, m_titleElement.get(), changingTitleElement);
1569 if (m_titleElement == newTitleElement)
1571 m_titleElement = newTitleElement;
1572 updateTitleFromTitleElement();
1575 void Document::titleElementAdded(Element& titleElement)
1577 if (m_titleElement == &titleElement)
1580 updateTitleElement(titleElement);
1583 void Document::titleElementRemoved(Element& titleElement)
1585 if (m_titleElement != &titleElement)
1588 updateTitleElement(titleElement);
1591 void Document::titleElementTextChanged(Element& titleElement)
1593 if (m_titleElement != &titleElement)
1596 updateTitleFromTitleElement();
1599 void Document::registerForVisibilityStateChangedCallbacks(VisibilityChangeClient* client)
1601 m_visibilityStateCallbackClients.add(client);
1604 void Document::unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient* client)
1606 m_visibilityStateCallbackClients.remove(client);
1609 void Document::visibilityStateChanged()
1611 enqueueDocumentEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1612 for (auto* client : m_visibilityStateCallbackClients)
1613 client->visibilityStateChanged();
1615 notifyMediaCaptureOfVisibilityChanged();
1618 VisibilityState Document::visibilityState() const
1620 // The visibility of the document is inherited from the visibility of the
1621 // page. If there is no page associated with the document, we will assume
1622 // that the page is hidden, as specified by the spec:
1623 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1624 if (!m_frame || !m_frame->page())
1625 return VisibilityState::Hidden;
1626 return m_frame->page()->visibilityState();
1629 bool Document::hidden() const
1631 return visibilityState() != VisibilityState::Visible;
1636 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1638 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1641 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1643 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1646 void Document::allowsMediaDocumentInlinePlaybackChanged()
1648 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1649 element->allowsMediaDocumentInlinePlaybackChanged();
1654 String Document::nodeName() const
1656 return ASCIILiteral("#document");
1659 Node::NodeType Document::nodeType() const
1661 return DOCUMENT_NODE;
1664 FormController& Document::formController()
1666 if (!m_formController)
1667 m_formController = std::make_unique<FormController>();
1668 return *m_formController;
1671 Vector<String> Document::formElementsState() const
1673 if (!m_formController)
1674 return Vector<String>();
1675 return m_formController->formElementsState();
1678 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1680 if (!stateVector.size() && !m_formController)
1682 formController().setStateForNewFormElements(stateVector);
1685 FrameView* Document::view() const
1687 return m_frame ? m_frame->view() : nullptr;
1690 Page* Document::page() const
1692 return m_frame ? m_frame->page() : nullptr;
1695 Ref<Range> Document::createRange()
1697 return Range::create(*this);
1700 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1702 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1705 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1707 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1710 void Document::scheduleForcedStyleRecalc()
1712 m_pendingStyleRecalcShouldForce = true;
1713 scheduleStyleRecalc();
1716 void Document::scheduleStyleRecalc()
1718 ASSERT(!m_renderView || !m_renderView->inHitTesting());
1720 if (m_styleRecalcTimer.isActive() || pageCacheState() != NotInPageCache)
1723 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1725 // FIXME: Why on earth is this here? This is clearly misplaced.
1726 invalidateAccessKeyMap();
1728 m_styleRecalcTimer.startOneShot(0_s);
1730 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1733 void Document::unscheduleStyleRecalc()
1735 ASSERT(!childNeedsStyleRecalc());
1737 m_styleRecalcTimer.stop();
1738 m_pendingStyleRecalcShouldForce = false;
1741 bool Document::hasPendingStyleRecalc() const
1743 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1746 bool Document::hasPendingForcedStyleRecalc() const
1748 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1751 void Document::resolveStyle(ResolveStyleType type)
1753 ASSERT(!view() || !view()->isPainting());
1755 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1759 FrameView& frameView = m_renderView->frameView();
1760 Ref<FrameView> protect(frameView);
1761 if (frameView.isPainting())
1764 if (m_inStyleRecalc)
1765 return; // Guard against re-entrancy. -dwh
1767 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1769 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1770 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1772 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1773 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1774 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1775 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1776 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1777 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1780 NoEventDispatchAssertion noEventDispatchAssertion;
1781 styleScope().flushPendingUpdate();
1782 frameView.willRecalcStyle();
1785 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1787 bool updatedCompositingLayers = false;
1789 Style::PostResolutionCallbackDisabler disabler(*this);
1790 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1791 NoEventDispatchAssertion noEventDispatchAssertion;
1793 m_inStyleRecalc = true;
1795 if (m_pendingStyleRecalcShouldForce)
1796 type = ResolveStyleType::Rebuild;
1798 if (type == ResolveStyleType::Rebuild) {
1799 // This may get set again during style resolve.
1800 m_hasNodesWithNonFinalStyle = false;
1801 m_hasNodesWithMissingStyle = false;
1803 auto documentStyle = Style::resolveForDocument(*this);
1805 // Inserting the pictograph font at the end of the font fallback list is done by the
1806 // font selector, so set a font selector if needed.
1807 if (settings().fontFallbackPrefersPictographs())
1808 documentStyle.fontCascade().update(&fontSelector());
1810 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
1811 if (documentChange != Style::NoChange)
1812 renderView()->setStyle(WTFMove(documentStyle));
1814 if (auto* documentElement = this->documentElement())
1815 documentElement->invalidateStyleForSubtree();
1818 Style::TreeResolver resolver(*this);
1819 auto styleUpdate = resolver.resolve();
1821 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
1824 clearChildNeedsStyleRecalc();
1825 unscheduleStyleRecalc();
1827 m_inStyleRecalc = false;
1830 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1832 RenderTreeUpdater updater(*this);
1833 updater.commit(WTFMove(styleUpdate));
1835 frameView.styleDidChange();
1838 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1840 if (m_renderView->needsLayout())
1841 frameView.scheduleRelayout();
1843 // Usually this is handled by post-layout.
1844 if (!frameView.needsLayout())
1845 frameView.frame().selection().scheduleAppearanceUpdateAfterStyleChange();
1847 // As a result of the style recalculation, the currently hovered element might have been
1848 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1849 // to check if any other elements ended up under the mouse pointer due to re-layout.
1850 if (m_hoveredElement && !m_hoveredElement->renderer())
1851 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1853 ++m_styleRecalcCount;
1854 // FIXME: Assert ASSERT(!needsStyleRecalc()) here. Do we still have some cases where it's not true?
1857 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1858 if (m_closeAfterStyleRecalc) {
1859 m_closeAfterStyleRecalc = false;
1863 InspectorInstrumentation::didRecalculateStyle(cookie);
1865 // Some animated images may now be inside the viewport due to style recalc,
1866 // resume them if necessary if there is no layout pending. Otherwise, we'll
1867 // check if they need to be resumed after layout.
1868 if (updatedCompositingLayers && !frameView.needsLayout())
1869 frameView.viewportContentsChanged();
1871 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
1872 frameView.scrollToFragment(m_url);
1875 void Document::updateTextRenderer(Text& text, unsigned offsetOfReplacedText, unsigned lengthOfReplacedText)
1877 ASSERT(!m_inRenderTreeUpdate);
1878 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1880 auto textUpdate = std::make_unique<Style::Update>(*this);
1881 textUpdate->addText(text, { offsetOfReplacedText, lengthOfReplacedText, std::nullopt });
1883 RenderTreeUpdater renderTreeUpdater(*this);
1884 renderTreeUpdater.commit(WTFMove(textUpdate));
1887 bool Document::needsStyleRecalc() const
1889 if (pageCacheState() != NotInPageCache)
1892 if (m_pendingStyleRecalcShouldForce)
1895 if (childNeedsStyleRecalc())
1898 if (styleScope().hasPendingUpdate())
1901 // Ensure this happens eventually as it is currently in resolveStyle. This can be removed if the code moves.
1902 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
1908 bool Document::updateStyleIfNeeded()
1911 NoEventDispatchAssertion noEventDispatchAssertion;
1912 ASSERT(isMainThread());
1913 ASSERT(!view() || !view()->isPainting());
1915 if (!view() || view()->isInRenderTreeLayout())
1918 styleScope().flushPendingUpdate();
1920 if (!needsStyleRecalc())
1928 void Document::updateLayout()
1930 ASSERT(LayoutDisallowedScope::isLayoutAllowed());
1931 ASSERT(isMainThread());
1933 RefPtr<FrameView> frameView = view();
1934 if (frameView && frameView->isInRenderTreeLayout()) {
1935 // View layout should not be re-entrant.
1936 ASSERT_NOT_REACHED();
1940 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1942 if (HTMLFrameOwnerElement* owner = ownerElement())
1943 owner->document().updateLayout();
1945 updateStyleIfNeeded();
1947 StackStats::LayoutCheckPoint layoutCheckPoint;
1949 // Only do a layout if changes have occurred that make it necessary.
1950 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1951 frameView->layout();
1954 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1956 bool oldIgnore = m_ignorePendingStylesheets;
1958 if (!haveStylesheetsLoaded()) {
1959 m_ignorePendingStylesheets = true;
1960 // FIXME: This should just invalidate elements with missing styles.
1961 if (m_hasNodesWithMissingStyle)
1962 scheduleForcedStyleRecalc();
1967 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1968 view()->flushAnyPendingPostLayoutTasks();
1970 m_ignorePendingStylesheets = oldIgnore;
1973 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle, PseudoId pseudoElementSpecifier)
1975 ASSERT(&element.document() == this);
1976 ASSERT(!element.isPseudoElement() || !pseudoElementSpecifier);
1977 ASSERT(!pseudoElementSpecifier || parentStyle);
1979 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1980 Style::PostResolutionCallbackDisabler disabler(*this);
1982 SetForScope<bool> change(m_ignorePendingStylesheets, true);
1983 auto& resolver = element.styleResolver();
1985 if (pseudoElementSpecifier)
1986 return resolver.pseudoStyleForElement(element, PseudoStyleRequest(pseudoElementSpecifier), *parentStyle);
1988 auto elementStyle = resolver.styleForElement(element, parentStyle);
1989 if (elementStyle.relations) {
1990 Style::Update emptyUpdate(*this);
1991 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
1994 return WTFMove(elementStyle.renderStyle);
1997 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
1999 ASSERT(isMainThread());
2001 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2002 if (!haveStylesheetsLoaded()) {
2003 updateLayoutIgnorePendingStylesheets();
2007 // Check for re-entrancy and assert (same code that is in updateLayout()).
2008 RefPtr<FrameView> frameView = view();
2009 if (frameView && frameView->isInRenderTreeLayout()) {
2010 // View layout should not be re-entrant.
2011 ASSERT_NOT_REACHED();
2015 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2017 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2019 bool requireFullLayout = false;
2020 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2021 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2022 requireFullLayout = true;
2025 updateStyleIfNeeded();
2027 RenderObject* renderer = element.renderer();
2028 if (!renderer || renderer->needsLayout()) {
2029 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2030 requireFullLayout = true;
2033 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2034 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2035 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2036 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2038 if (!requireFullLayout) {
2039 RenderBox* previousBox = nullptr;
2040 RenderBox* currentBox = nullptr;
2042 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2043 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2045 // Require the entire container chain to be boxes.
2046 if (!is<RenderBox>(currRenderer)) {
2047 requireFullLayout = true;
2051 previousBox = currentBox;
2052 currentBox = downcast<RenderBox>(currRenderer);
2054 // If a box needs layout for itself or if a box has changed children and sizes its width to
2055 // its content, then require a full layout.
2056 if (currentBox->selfNeedsLayout() ||
2057 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2058 requireFullLayout = true;
2062 // If a block contains floats and the child's height isn't specified, then
2063 // give up also, since our height could end up being influenced by the floats.
2064 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2065 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2066 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2067 requireFullLayout = true;
2072 if (!currentBox->isRenderBlockFlow() || currentBox->enclosingFragmentedFlow() || currentBox->isWritingModeRoot()) {
2073 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2074 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2075 // Disallow columns from having the optimization.
2076 // Give up if the writing mode changes at all in the containing block chain.
2077 requireFullLayout = true;
2081 if (currRenderer == frameView->subtreeLayoutRoot())
2086 StackStats::LayoutCheckPoint layoutCheckPoint;
2088 // Only do a layout if changes have occurred that make it necessary.
2089 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2090 frameView->layout();
2092 return requireFullLayout;
2095 bool Document::isPageBoxVisible(int pageIndex)
2097 updateStyleIfNeeded();
2098 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2099 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2102 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2104 updateStyleIfNeeded();
2105 auto style = styleScope().resolver().styleForPage(pageIndex);
2107 int width = pageSize.width();
2108 int height = pageSize.height();
2109 switch (style->pageSizeType()) {
2110 case PAGE_SIZE_AUTO:
2112 case PAGE_SIZE_AUTO_LANDSCAPE:
2114 std::swap(width, height);
2116 case PAGE_SIZE_AUTO_PORTRAIT:
2118 std::swap(width, height);
2120 case PAGE_SIZE_RESOLVED: {
2121 auto& size = style->pageSize();
2122 ASSERT(size.width.isFixed());
2123 ASSERT(size.height.isFixed());
2124 width = valueForLength(size.width, 0);
2125 height = valueForLength(size.height, 0);
2129 ASSERT_NOT_REACHED();
2131 pageSize = IntSize(width, height);
2133 // The percentage is calculated with respect to the width even for margin top and bottom.
2134 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2135 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2136 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2137 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2138 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2141 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2143 if (!m_userAgentShadowTreeStyleResolver)
2144 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2145 return *m_userAgentShadowTreeStyleResolver;
2148 void Document::fontsNeedUpdate(FontSelector&)
2150 invalidateMatchedPropertiesCacheAndForceStyleRecalc();
2153 void Document::invalidateMatchedPropertiesCacheAndForceStyleRecalc()
2155 if (auto* resolver = styleScope().resolverIfExists())
2156 resolver->invalidateMatchedPropertiesCache();
2157 if (pageCacheState() != NotInPageCache || !renderView())
2159 scheduleForcedStyleRecalc();
2162 void Document::didClearStyleResolver()
2164 m_userAgentShadowTreeStyleResolver = nullptr;
2167 void Document::createRenderTree()
2169 ASSERT(!renderView());
2170 ASSERT(m_pageCacheState != InPageCache);
2171 ASSERT(!m_axObjectCache || this != &topDocument());
2173 if (m_isNonRenderedPlaceholder)
2176 // FIXME: It would be better if we could pass the resolved document style directly here.
2177 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2178 Node::setRenderer(m_renderView.get());
2180 renderView()->setIsInWindow(true);
2182 resolveStyle(ResolveStyleType::Rebuild);
2185 void Document::didBecomeCurrentDocumentInFrame()
2187 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2188 // If so, then m_frame could become 0, and we need to do something about that.
2190 m_frame->script().updateDocument();
2192 if (!hasLivingRenderTree())
2195 updateViewportArguments();
2197 // FIXME: Doing this only for the main frame is insufficient.
2198 // Changing a subframe can also change the wheel event handler count.
2199 // FIXME: Doing this only when a document goes into the frame is insufficient.
2200 // Removing a document can also change the wheel event handler count.
2201 // FIXME: Doing this every time is a waste. If the current document and its
2202 // subframes' documents have no wheel event handlers, then the count did not change,
2203 // unless the documents they are replacing had wheel event handlers.
2204 if (page() && m_frame->isMainFrame())
2205 wheelEventHandlersChanged();
2207 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2208 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2209 // page cache, or simply newly created).
2210 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2211 m_frame->animation().suspendAnimationsForDocument(this);
2212 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2214 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2215 m_frame->animation().resumeAnimationsForDocument(this);
2219 void Document::frameDestroyed()
2221 // detachFromFrame() must be called before destroying the Frame.
2222 RELEASE_ASSERT(!m_frame);
2223 FrameDestructionObserver::frameDestroyed();
2226 void Document::attachToCachedFrame(CachedFrameBase& cachedFrame)
2228 RELEASE_ASSERT(cachedFrame.document() == this);
2229 ASSERT(cachedFrame.view());
2230 ASSERT(m_pageCacheState == Document::InPageCache);
2231 observeFrame(&cachedFrame.view()->frame());
2234 void Document::detachFromCachedFrame(CachedFrameBase& cachedFrame)
2236 ASSERT_UNUSED(cachedFrame, cachedFrame.view());
2237 RELEASE_ASSERT(cachedFrame.document() == this);
2238 ASSERT(m_frame == &cachedFrame.view()->frame());
2239 ASSERT(m_pageCacheState == Document::InPageCache);
2243 void Document::destroyRenderTree()
2245 ASSERT(hasLivingRenderTree());
2247 ASSERT(frame()->document() == this);
2250 // Prevent Widget tree changes from committing until the RenderView is dead and gone.
2251 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2253 SetForScope<bool> change(m_renderTreeBeingDestroyed, true);
2255 if (this == &topDocument())
2256 clearAXObjectCache();
2258 documentWillBecomeInactive();
2261 view()->willDestroyRenderTree();
2263 if (m_documentElement)
2264 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2266 clearChildNeedsStyleRecalc();
2268 unscheduleStyleRecalc();
2270 // FIXME: RenderObject::view() uses m_renderView and we can't null it before destruction is completed
2271 m_renderView->destroy();
2272 m_renderView.release();
2274 Node::setRenderer(nullptr);
2276 #if ENABLE(TEXT_AUTOSIZING)
2277 m_textAutoSizing = nullptr;
2281 view()->didDestroyRenderTree();
2284 void Document::prepareForDestruction()
2286 if (m_hasPreparedForDestruction)
2290 m_frame->animation().detachFromDocument(this);
2292 #if ENABLE(IOS_TOUCH_EVENTS)
2293 clearTouchEventHandlersAndListeners();
2296 #if HAVE(ACCESSIBILITY)
2297 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2298 if (this != &topDocument()) {
2299 if (AXObjectCache* cache = existingAXObjectCache())
2300 cache->clearTextMarkerNodesInUse(this);
2305 NavigationDisabler navigationDisabler(m_frame);
2306 disconnectDescendantFrames();
2309 if (m_domWindow && m_frame)
2310 m_domWindow->willDetachDocumentFromFrame();
2312 if (hasLivingRenderTree())
2313 destroyRenderTree();
2315 if (is<PluginDocument>(*this))
2316 downcast<PluginDocument>(*this).detachFromPluginElement();
2318 #if ENABLE(POINTER_LOCK)
2320 page()->pointerLockController().documentDetached(*this);
2323 if (auto* page = this->page()) {
2324 if (auto* validationMessageClient = page->validationMessageClient())
2325 validationMessageClient->documentDetached(*this);
2328 InspectorInstrumentation::documentDetached(*this);
2330 stopActiveDOMObjects();
2331 m_eventQueue.close();
2332 #if ENABLE(FULLSCREEN_API)
2333 m_fullScreenChangeEventTargetQueue.clear();
2334 m_fullScreenErrorEventTargetQueue.clear();
2339 #if ENABLE(TOUCH_EVENTS)
2340 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2341 parentDocument()->didRemoveEventTargetNode(*this);
2344 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2345 parentDocument()->didRemoveEventTargetNode(*this);
2347 if (m_mediaQueryMatcher)
2348 m_mediaQueryMatcher->documentDestroyed();
2350 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2351 if (!m_clientToIDMap.isEmpty() && page()) {
2352 for (auto* client : copyToVector(m_clientToIDMap.keys()))
2353 removePlaybackTargetPickerClient(*client);
2357 m_cachedResourceLoader->stopUnusedPreloadsTimer();
2359 if (page() && m_mediaState != MediaProducer::IsNotPlaying) {
2360 m_mediaState = MediaProducer::IsNotPlaying;
2361 page()->updateIsPlayingMedia(HTMLMediaElementInvalidID);
2366 m_hasPreparedForDestruction = true;
2368 // Note that m_pageCacheState can be Document::AboutToEnterPageCache if our frame
2369 // was removed in an onpagehide event handler fired when the top-level frame is
2370 // about to enter the page cache.
2371 RELEASE_ASSERT(m_pageCacheState != Document::InPageCache);
2374 void Document::removeAllEventListeners()
2376 EventTarget::removeAllEventListeners();
2379 m_domWindow->removeAllEventListeners();
2381 #if ENABLE(IOS_TOUCH_EVENTS)
2382 clearTouchEventHandlersAndListeners();
2384 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2385 node->removeAllEventListeners();
2387 #if ENABLE(TOUCH_EVENTS)
2388 m_touchEventTargets = nullptr;
2390 m_wheelEventTargets = nullptr;
2393 void Document::suspendDeviceMotionAndOrientationUpdates()
2395 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2397 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2398 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2399 if (m_deviceMotionController)
2400 m_deviceMotionController->suspendUpdates();
2401 if (m_deviceOrientationController)
2402 m_deviceOrientationController->suspendUpdates();
2406 void Document::resumeDeviceMotionAndOrientationUpdates()
2408 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2410 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2411 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2412 if (m_deviceMotionController)
2413 m_deviceMotionController->resumeUpdates();
2414 if (m_deviceOrientationController)
2415 m_deviceOrientationController->resumeUpdates();
2419 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2421 JSC::CallFrame* callFrame = commonVM().topCallFrame;
2422 if (callFrame == JSC::CallFrame::noCaller())
2424 DOMWrapperWorld& domWrapperWorld = currentWorld(callFrame);
2425 if (domWrapperWorld.isNormal())
2430 void Document::platformSuspendOrStopActiveDOMObjects()
2433 if (WebThreadCountOfObservedContentModifiers() > 0) {
2434 if (auto* frame = this->frame()) {
2435 if (auto* page = frame->page())
2436 page->chrome().client().clearContentChangeObservers(*frame);
2442 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2444 ScriptExecutionContext::suspendActiveDOMObjects(why);
2445 suspendDeviceMotionAndOrientationUpdates();
2446 platformSuspendOrStopActiveDOMObjects();
2449 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2451 ScriptExecutionContext::resumeActiveDOMObjects(why);
2452 resumeDeviceMotionAndOrientationUpdates();
2453 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2456 void Document::stopActiveDOMObjects()
2458 ScriptExecutionContext::stopActiveDOMObjects();
2459 platformSuspendOrStopActiveDOMObjects();
2462 void Document::clearAXObjectCache()
2464 ASSERT(&topDocument() == this);
2465 // Clear the cache member variable before calling delete because attempts
2466 // are made to access it during destruction.
2467 m_axObjectCache = nullptr;
2470 AXObjectCache* Document::existingAXObjectCacheSlow() const
2472 ASSERT(hasEverCreatedAnAXObjectCache);
2473 Document& topDocument = this->topDocument();
2474 if (!topDocument.hasLivingRenderTree())
2476 return topDocument.m_axObjectCache.get();
2479 AXObjectCache* Document::axObjectCache() const
2481 if (!AXObjectCache::accessibilityEnabled())
2484 // The only document that actually has a AXObjectCache is the top-level
2485 // document. This is because we need to be able to get from any WebCoreAXObject
2486 // to any other WebCoreAXObject on the same page. Using a single cache allows
2487 // lookups across nested webareas (i.e. multiple documents).
2488 Document& topDocument = this->topDocument();
2490 // If the document has already been detached, do not make a new axObjectCache.
2491 if (!topDocument.hasLivingRenderTree())
2494 ASSERT(&topDocument == this || !m_axObjectCache);
2495 if (!topDocument.m_axObjectCache) {
2496 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2497 hasEverCreatedAnAXObjectCache = true;
2499 return topDocument.m_axObjectCache.get();
2502 void Document::setVisuallyOrdered()
2504 m_visuallyOrdered = true;
2506 renderView()->mutableStyle().setRTLOrdering(VisualOrder);
2509 Ref<DocumentParser> Document::createParser()
2511 // FIXME: this should probably pass the frame instead
2512 return XMLDocumentParser::create(*this, view());
2515 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2517 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2520 ExceptionOr<RefPtr<DOMWindow>> Document::openForBindings(DOMWindow& activeWindow, DOMWindow& firstWindow, const String& url, const AtomicString& name, const String& features)
2523 return Exception { InvalidAccessError };
2525 return m_domWindow->open(activeWindow, firstWindow, url, name, features);
2528 // FIXME: Add support for the 'type' and 'replace' parameters.
2529 ExceptionOr<Document&> Document::openForBindings(Document* responsibleDocument, const String&, const String&)
2531 if (!isHTMLDocument())
2532 return Exception { InvalidStateError };
2534 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2536 open(responsibleDocument);
2540 void Document::open(Document* responsibleDocument)
2542 if (m_ignoreOpensDuringUnloadCount)
2545 if (responsibleDocument) {
2546 setURL(responsibleDocument->url());
2547 setCookieURL(responsibleDocument->cookieURL());
2548 setSecurityOriginPolicy(responsibleDocument->securityOriginPolicy());
2552 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2553 if (parser->isParsing()) {
2554 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2555 if (parser->isExecutingScript())
2558 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2563 if (m_frame->loader().state() == FrameStateProvisional)
2564 m_frame->loader().stopAllLoaders();
2567 removeAllEventListeners();
2569 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2570 parser->setWasCreatedByScript(true);
2573 m_frame->loader().didExplicitOpen();
2576 void Document::detachParser()
2584 void Document::cancelParsing()
2589 // We have to clear the parser to avoid possibly triggering
2590 // the onload handler when closing as a side effect of a cancel-style
2591 // change, such as opening a new document or closing the window while
2597 void Document::implicitOpen()
2601 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2604 m_parser = createParser();
2606 setReadyState(Loading);
2609 HTMLBodyElement* Document::body() const
2611 auto* element = documentElement();
2614 return childrenOfType<HTMLBodyElement>(*element).first();
2617 HTMLElement* Document::bodyOrFrameset() const
2619 // Return the first body or frameset child of the html element.
2620 auto* element = documentElement();
2621 if (!is<HTMLHtmlElement>(element))
2623 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2624 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2630 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2632 if (!is<HTMLBodyElement>(newBody.get()) && !is<HTMLFrameSetElement>(newBody.get()))
2633 return Exception { HierarchyRequestError };
2635 auto* currentBody = bodyOrFrameset();
2636 if (newBody == currentBody)
2639 if (!m_documentElement)
2640 return Exception { HierarchyRequestError };
2643 return m_documentElement->replaceChild(*newBody, *currentBody);
2644 return m_documentElement->appendChild(*newBody);
2647 Location* Document::location() const
2649 auto* window = domWindow();
2653 return window->location();
2656 HTMLHeadElement* Document::head()
2658 if (auto element = documentElement())
2659 return childrenOfType<HTMLHeadElement>(*element).first();
2663 ExceptionOr<void> Document::closeForBindings()
2665 // FIXME: We should follow the specification more closely:
2666 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2668 if (!isHTMLDocument())
2669 return Exception { InvalidStateError };
2671 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2677 void Document::close()
2679 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2685 void Document::explicitClose()
2687 if (RefPtr<DocumentParser> parser = m_parser)
2691 // Because we have no frame, we don't know if all loading has completed,
2692 // so we just call implicitClose() immediately. FIXME: This might fire
2693 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2701 void Document::implicitClose()
2703 // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
2704 if (m_inStyleRecalc) {
2705 m_closeAfterStyleRecalc = true;
2709 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2710 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2715 // Call to dispatchWindowLoadEvent can blow us from underneath.
2716 Ref<Document> protectedThis(*this);
2718 m_processingLoadEvent = true;
2720 ScriptableDocumentParser* parser = scriptableDocumentParser();
2721 m_wellFormed = parser && parser->wellFormed();
2723 // We have to clear the parser, in case someone document.write()s from the
2724 // onLoad event handler, as in Radar 3206524.
2727 // FIXME: We kick off the icon loader when the Document is done parsing.
2728 // There are earlier opportunities we could start it:
2729 // -When the <head> finishes parsing
2730 // -When any new HTMLLinkElement is inserted into the document
2731 // But those add a dynamic component to the favicon that has UI
2732 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2733 RefPtr<Frame> f = frame();
2735 // Apply XSL transforms before load events so that event handlers can access the transformed DOM tree.
2736 applyPendingXSLTransformsNowIfScheduled();
2738 if (auto* documentLoader = loader())
2739 documentLoader->startIconLoading();
2741 f->animation().startAnimationsIfNotSuspended(this);
2743 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2744 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2745 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2746 ImageLoader::dispatchPendingBeforeLoadEvents();
2747 ImageLoader::dispatchPendingLoadEvents();
2748 ImageLoader::dispatchPendingErrorEvents();
2749 HTMLLinkElement::dispatchPendingLoadEvents();
2750 HTMLStyleElement::dispatchPendingLoadEvents();
2752 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2753 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2754 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2755 if (svgExtensions())
2756 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2759 dispatchWindowLoadEvent();
2760 dispatchPageshowEvent(PageshowEventNotPersisted);
2761 if (m_pendingStateObject)
2762 dispatchPopstateEvent(WTFMove(m_pendingStateObject));
2765 f->loader().dispatchOnloadEvents();
2767 // An event handler may have removed the frame
2769 m_processingLoadEvent = false;
2773 // Make sure both the initial layout and reflow happen after the onload
2774 // fires. This will improve onload scores, and other browsers do it.
2775 // If they wanna cheat, we can too. -dwh
2777 if (frame()->navigationScheduler().locationChangePending() && timeSinceDocumentCreation() < settings().layoutInterval()) {
2778 // Just bail out. Before or during the onload we were shifted to another page.
2779 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2780 m_processingLoadEvent = false;
2781 view()->unscheduleRelayout();
2785 frame()->loader().checkCallImplicitClose();
2787 // We used to force a synchronous display and flush here. This really isn't
2788 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2789 // (if your platform is syncing flushes and limiting them to 60fps).
2790 m_overMinimumLayoutThreshold = true;
2791 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2792 updateStyleIfNeeded();
2794 // Always do a layout after loading if needed.
2795 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2799 m_processingLoadEvent = false;
2801 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK)
2802 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2803 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2804 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2805 // exists in the cache (we ignore the return value because we don't need it here). This is
2806 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2808 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2809 // catch new AND page history loads, and that uses AXLoadComplete
2811 axObjectCache()->getOrCreate(renderView());
2812 if (this == &topDocument())
2813 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2815 // AXLoadComplete can only be posted on the top document, so if it's a document
2816 // in an iframe that just finished loading, post AXLayoutComplete instead.
2817 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2822 if (svgExtensions())
2823 accessSVGExtensions().startAnimations();
2826 void Document::setParsing(bool b)
2830 if (m_bParsing && !m_sharedObjectPool)
2831 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2833 if (!m_bParsing && view() && !view()->needsLayout())
2834 view()->fireLayoutRelatedMilestonesIfNeeded();
2837 bool Document::shouldScheduleLayout()
2839 if (!documentElement())
2841 if (!is<HTMLHtmlElement>(*documentElement()))
2843 if (!bodyOrFrameset())
2845 if (styleScope().hasPendingSheetsBeforeBody())
2851 bool Document::isLayoutTimerActive()
2853 return view() && view()->layoutPending() && !minimumLayoutDelay();
2856 Seconds Document::minimumLayoutDelay()
2858 if (m_overMinimumLayoutThreshold)
2861 auto elapsed = timeSinceDocumentCreation();
2862 m_overMinimumLayoutThreshold = elapsed > settings().layoutInterval();
2864 // We'll want to schedule the timer to fire at the minimum layout threshold.
2865 return std::max(0_s, settings().layoutInterval() - elapsed);
2868 Seconds Document::timeSinceDocumentCreation() const
2870 return MonotonicTime::now() - m_documentCreationTime;
2873 void Document::write(Document* responsibleDocument, SegmentedString&& text)
2875 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2877 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2878 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2880 if (m_writeRecursionIsTooDeep)
2883 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2884 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2887 if (!hasInsertionPoint)
2888 open(responsibleDocument);
2891 m_parser->insert(WTFMove(text));
2894 ExceptionOr<void> Document::write(Document* responsibleDocument, Vector<String>&& strings)
2896 if (!isHTMLDocument())
2897 return Exception { InvalidStateError };
2899 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2901 SegmentedString text;
2902 for (auto& string : strings)
2903 text.append(WTFMove(string));
2905 write(responsibleDocument, WTFMove(text));
2910 ExceptionOr<void> Document::writeln(Document* responsibleDocument, Vector<String>&& strings)
2912 if (!isHTMLDocument())
2913 return Exception { InvalidStateError };
2915 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2917 SegmentedString text;
2918 for (auto& string : strings)
2919 text.append(WTFMove(string));
2921 text.append(ASCIILiteral { "\n" });
2922 write(responsibleDocument, WTFMove(text));
2927 Seconds Document::minimumDOMTimerInterval() const
2929 auto* page = this->page();
2931 return ScriptExecutionContext::minimumDOMTimerInterval();
2932 return page->settings().minimumDOMTimerInterval();
2935 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2937 if (m_isTimerThrottlingEnabled == shouldThrottle)
2940 m_isTimerThrottlingEnabled = shouldThrottle;
2941 didChangeTimerAlignmentInterval();
2944 Seconds Document::domTimerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2946 auto alignmentInterval = ScriptExecutionContext::domTimerAlignmentInterval(hasReachedMaxNestingLevel);
2947 if (!hasReachedMaxNestingLevel)
2948 return alignmentInterval;
2950 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2951 if (m_isTimerThrottlingEnabled)
2952 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
2954 if (Page* page = this->page())
2955 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
2957 if (!topOrigin().canAccess(securityOrigin()) && !hasHadUserInteraction())
2958 alignmentInterval = std::max(alignmentInterval, DOMTimer::nonInteractedCrossOriginFrameAlignmentInterval());
2960 return alignmentInterval;
2963 EventTarget* Document::errorEventTarget()
2965 return m_domWindow.get();
2968 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2970 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2973 void Document::setURL(const URL& url)
2975 const URL& newURL = url.isEmpty() ? blankURL() : url;
2976 if (newURL == m_url)
2980 m_documentURI = m_url.string();
2984 void Document::updateBaseURL()
2986 URL oldBaseURL = m_baseURL;
2987 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2988 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2989 // from the Document interface otherwise.
2990 if (!m_baseElementURL.isEmpty())
2991 m_baseURL = m_baseElementURL;
2992 else if (!m_baseURLOverride.isEmpty())
2993 m_baseURL = m_baseURLOverride;
2995 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2996 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2997 // and DOM 3 Core does not specify how it should be resolved.
2998 m_baseURL = URL(ParsedURLString, documentURI());
3001 clearSelectorQueryCache();
3003 if (!m_baseURL.isValid())
3006 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
3007 // Base URL change changes any relative visited links.
3008 // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
3009 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
3010 anchor.invalidateCachedVisitedLinkHash();
3014 void Document::setBaseURLOverride(const URL& url)
3016 m_baseURLOverride = url;
3020 void Document::processBaseElement()
3022 // Find the first href attribute in a base element and the first target attribute in a base element.
3023 const AtomicString* href = nullptr;
3024 const AtomicString* target = nullptr;
3025 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3026 for (auto& base : baseDescendants) {
3028 const AtomicString& value = base.attributeWithoutSynchronization(hrefAttr);
3029 if (!value.isNull()) {
3036 const AtomicString& value = base.attributeWithoutSynchronization(targetAttr);
3037 if (!value.isNull()) {
3045 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3048 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3049 if (!strippedHref.isEmpty())
3050 baseElementURL = URL(url(), strippedHref);
3052 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3053 m_baseElementURL = baseElementURL;
3057 m_baseTarget = target ? *target : nullAtom();
3060 String Document::userAgent(const URL& url) const
3062 return frame() ? frame()->loader().userAgent(url) : String();
3065 void Document::disableEval(const String& errorMessage)
3070 frame()->script().disableEval(errorMessage);
3073 void Document::disableWebAssembly(const String& errorMessage)
3078 frame()->script().disableWebAssembly(errorMessage);
3081 #if ENABLE(INDEXED_DATABASE)
3082 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
3084 if (!m_idbConnectionProxy) {
3085 Page* currentPage = page();
3088 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
3090 return m_idbConnectionProxy.get();
3094 SocketProvider* Document::socketProvider()
3096 return m_socketProvider.get();
3099 bool Document::canNavigate(Frame* targetFrame)
3104 // FIXME: We shouldn't call this function without a target frame, but
3105 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3106 // returning true when supplied with a 0 targetFrame.
3110 // Cases (i), (ii) and (iii) pass the tests from the specifications but might not pass the "security origin" tests.
3112 // i. A frame can navigate its top ancestor when its 'allow-top-navigation' flag is set (sometimes known as 'frame-busting').
3113 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3116 // ii. A frame can navigate its top ancestor when its 'allow-top-navigation-by-user-activation' flag is set and navigation is triggered by user activation.
3117 if (!isSandboxed(SandboxTopNavigationByUserActivation) && UserGestureIndicator::processingUserGesture() && targetFrame == &m_frame->tree().top())
3120 // iii. A sandboxed frame can always navigate its descendants.
3121 if (isSandboxed(SandboxNavigation) && targetFrame->tree().isDescendantOf(m_frame))
3124 // From https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate.
3125 // 1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A's active document's active sandboxing
3126 // flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.
3127 if (m_frame != targetFrame && isSandboxed(SandboxNavigation) && targetFrame->tree().parent() && !targetFrame->tree().isDescendantOf(m_frame)) {
3128 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."));
3132 // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
3133 if (m_frame != targetFrame && targetFrame == &m_frame->tree().top()) {
3134 bool triggeredByUserActivation = UserGestureIndicator::processingUserGesture();
3135 // 1. If this algorithm is triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set, then abort these steps negatively.
3136 if (triggeredByUserActivation && isSandboxed(SandboxTopNavigationByUserActivation)) {
3137 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation-by-user-activation' flag is not set and navigation is not triggered by user activation."));
3140 // 2. Otherwise, If this algorithm is not triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set, then abort these steps negatively.
3141 if (!triggeredByUserActivation && isSandboxed(SandboxTopNavigation)) {
3142 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set."));
3147 // 3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A's Document's active sandboxing flag set has its
3148 // sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.
3149 if (!targetFrame->tree().parent() && m_frame != targetFrame && targetFrame != &m_frame->tree().top() && isSandboxed(SandboxNavigation) && targetFrame->loader().opener() != m_frame) {
3150 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation is sandboxed, and is not allowed to navigate this popup."));
3154 // 4. Otherwise, terminate positively!
3156 // This is the normal case. A document can navigate its descendant frames,
3157 // or, more generally, a document can navigate a frame if the document is
3158 // in the same origin as any of that frame's ancestors (in the frame
3161 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3162 // historical information about this security check.
3163 if (canAccessAncestor(securityOrigin(), targetFrame))
3166 // Top-level frames are easier to navigate than other frames because they
3167 // display their URLs in the address bar (in most browsers). However, there
3168 // are still some restrictions on navigation to avoid nuisance attacks.
3169 // Specifically, a document can navigate a top-level frame if that frame
3170 // opened the document or if the document is the same-origin with any of
3171 // the top-level frame's opener's ancestors (in the frame hierarchy).
3173 // In both of these cases, the document performing the navigation is in
3174 // some way related to the frame being navigate (e.g., by the "opener"
3175 // and/or "parent" relation). Requiring some sort of relation prevents a
3176 // document from navigating arbitrary, unrelated top-level frames.
3177 if (!targetFrame->tree().parent()) {
3178 if (targetFrame == m_frame->loader().opener())
3181 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3185 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3189 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3191 Frame* currentFrame = m_frame;
3195 Frame* ancestorFrame = currentFrame->tree().parent();
3197 while (ancestorFrame) {
3198 if (!ancestorFrame->document()->securityOrigin().canAccess(securityOrigin()))
3199 return currentFrame;
3200 currentFrame = ancestorFrame;
3201 ancestorFrame = ancestorFrame->tree().parent();
3206 void Document::didRemoveAllPendingStylesheet()
3208 if (auto* parser = scriptableDocumentParser())
3209 parser->executeScriptsWaitingForStylesheetsSoon();
3212 bool Document::usesStyleBasedEditability() const
3214 if (m_hasElementUsingStyleBasedEditability)
3217 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3218 ASSERT(!m_inStyleRecalc);
3220 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3221 styleScope.flushPendingUpdate();
3222 return styleScope.usesStyleBasedEditability();
3225 void Document::setHasElementUsingStyleBasedEditability()
3227 m_hasElementUsingStyleBasedEditability = true;
3230 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3232 ASSERT(!equiv.isNull());
3233 ASSERT(!content.isNull());
3235 HttpEquivPolicy policy = httpEquivPolicy();
3236 if (policy != HttpEquivPolicy::Enabled) {
3239 case HttpEquivPolicy::Enabled:
3240 ASSERT_NOT_REACHED();
3242 case HttpEquivPolicy::DisabledBySettings:
3243 reason = "by the embedder.";
3245 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3246 reason = "for documents with Content-Disposition: attachment.";
3249 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3250 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3254 Frame* frame = this->frame();
3256 HTTPHeaderName headerName;
3257 if (!findHTTPHeaderName(equiv, headerName))
3260 switch (headerName) {
3261 case HTTPHeaderName::DefaultStyle:
3262 // The preferred style set has been overridden as per section
3263 // 14.3.2 of the HTML4.0 specification. We need to update the
3264 // sheet used variable and then update our style selector.
3265 // For more info, see the test at:
3266 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3268 styleScope().setSelectedStylesheetSetName(content);
3269 styleScope().setPreferredStylesheetSetName(content);
3272 case HTTPHeaderName::Refresh: {
3275 if (frame && parseMetaHTTPEquivRefresh(content, delay, urlString)) {
3277 if (urlString.isEmpty())
3278 completedURL = m_url;
3280 completedURL = completeURL(urlString);
3281 if (!protocolIsJavaScript(completedURL))
3282 frame->navigationScheduler().scheduleRedirect(*this, delay, completedURL);
3284 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3285 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3292 case HTTPHeaderName::SetCookie:
3293 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3294 if (is<HTMLDocument>(*this)) {
3295 // Exception (for sandboxed documents) ignored.
3296 downcast<HTMLDocument>(*this).setCookie(content);
3300 case HTTPHeaderName::ContentLanguage:
3301 setContentLanguage(content);
3304 case HTTPHeaderName::XDNSPrefetchControl:
3305 parseDNSPrefetchControlHeader(content);
3308 case HTTPHeaderName::XFrameOptions:
3310 FrameLoader& frameLoader = frame->loader();
3311 unsigned long requestIdentifier = 0;
3312 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3313 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3315 String message = "The X-Frame-Option '" + content + "' supplied in a <meta> element was ignored. X-Frame-Options may only be provided by an HTTP header sent with the document.";
3316 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3320 case HTTPHeaderName::ContentSecurityPolicy:
3321 if (isInDocumentHead)
3322 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::Enforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3325 case HTTPHeaderName::XWebKitCSP:
3326 if (isInDocumentHead)
3327 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::PrefixedEnforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3335 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3337 ASSERT(!features.isNull());
3339 if (origin < m_viewportArguments.type)
3342 m_viewportArguments = ViewportArguments(origin);
3344 processFeaturesString(features, FeatureMode::Viewport, [this](StringView key, StringView value) {
3345 setViewportFeature(m_viewportArguments, *this, key, value);
3348 updateViewportArguments();
3351 void Document::updateViewportArguments()
3353 if (page() && frame()->isMainFrame()) {
3355 m_didDispatchViewportPropertiesChanged = true;
3357 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3358 page()->chrome().didReceiveDocType(*frame());
3364 void Document::processFormatDetection(const String& features)
3366 // FIXME: Find a better place for this function.
3367 processFeaturesString(features, FeatureMode::Viewport, [this](StringView key, StringView value) {
3368 if (equalLettersIgnoringASCIICase(key, "telephone") && equalLettersIgnoringASCIICase(value, "no"))
3369 setIsTelephoneNumberParsingAllowed(false);
3373 void Document::processWebAppOrientations()
3375 if (Page* page = this->page())
3376 page->chrome().client().webAppOrientationsUpdated();
3381 void Document::processReferrerPolicy(const String& policy)
3383 ASSERT(!policy.isNull());
3385 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3386 // even if the document has a meta tag saying otherwise.
3387 if (shouldEnforceContentDispositionAttachmentSandbox())
3391 if (shouldEnforceQuickLookSandbox())
3395 // "never" / "default" / "always" are legacy keywords that we will support. They were defined in:
3396 // https://www.w3.org/TR/2014/WD-referrer-policy-20140807/#referrer-policy-delivery-meta
3397 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3398 setReferrerPolicy(ReferrerPolicy::NoReferrer);
3399 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3400 setReferrerPolicy(ReferrerPolicy::UnsafeUrl);
3401 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3402 setReferrerPolicy(ReferrerPolicy::Origin);
3403 else if (equalLettersIgnoringASCIICase(policy, "origin-when-cross-origin"))
3404 setReferrerPolicy(ReferrerPolicy::OriginWhenCrossOrigin);
3405 else if (equalLettersIgnoringASCIICase(policy, "same-origin"))
3406 setReferrerPolicy(ReferrerPolicy::SameOrigin);
3407 else if (equalLettersIgnoringASCIICase(policy, "strict-origin"))
3408 setReferrerPolicy(ReferrerPolicy::StrictOrigin);
3409 else if (equalLettersIgnoringASCIICase(policy, "strict-origin-when-cross-origin"))
3410 setReferrerPolicy(ReferrerPolicy::StrictOriginWhenCrossOrigin);
3411 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3412 setReferrerPolicy(ReferrerPolicy::NoReferrerWhenDowngrade);
3414 addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, "Failed to set referrer policy: The value '" + policy + "' is not one of 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin' or 'unsafe-url'. Defaulting to 'no-referrer'.");
3415 setReferrerPolicy(ReferrerPolicy::NoReferrer);
3419 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3421 if (!hasLivingRenderTree())
3422 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3424 HitTestResult result(documentPoint);
3425 renderView()->hitTest(request, result);
3427 if (!request.readOnly())
3428 updateHoverActiveState(request, result.targetElement());
3430 return MouseEventWithHitTestResults(event, result);
3433 // DOM Section 1.1.1
3434 bool Document::childTypeAllowed(NodeType type) const
3437 case ATTRIBUTE_NODE:
3438 case CDATA_SECTION_NODE:
3439 case DOCUMENT_FRAGMENT_NODE:
3444 case PROCESSING_INSTRUCTION_NODE:
3446 case DOCUMENT_TYPE_NODE:
3448 // Documents may contain no more than one of each of these.
3449 // (One Element and one DocumentType.)
3450 for (Node* c = firstChild(); c; c = c->nextSibling())
3451 if (c->nodeType() == type)
3458 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3460 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3463 switch (newChild.nodeType()) {
3464 case ATTRIBUTE_NODE:
3465 case CDATA_SECTION_NODE:
3470 case PROCESSING_INSTRUCTION_NODE:
3472 case DOCUMENT_FRAGMENT_NODE: {
3473 bool hasSeenElementChild = false;
3474 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3475 if (is<Element>(*node)) {
3476 if (hasSeenElementChild)
3478 hasSeenElementChild = true;
3480 if (!canAcceptChild(*node, refChild, operation))
3485 case DOCUMENT_TYPE_NODE: {
3486 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3487 if (operation == AcceptChildOperation::Replace) {
3488 // parent has a doctype child that is not child, or an element is preceding child.
3489 if (existingDocType && existingDocType != refChild)
3491 if (refChild->previousElementSibling())
3494 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3495 if (existingDocType)
3497 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3502 case ELEMENT_NODE: {
3503 auto* existingElementChild = firstElementChild();
3504 if (operation == AcceptChildOperation::Replace) {
3505 if (existingElementChild && existingElementChild != refChild)
3507 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3508 if (is<DocumentType>(*child))
3512 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3513 if (existingElementChild)
3515 for (auto* child = refChild; child; child = child->nextSibling()) {
3516 if (is<DocumentType>(*child))
3526 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3528 Ref<Document> clone = cloneDocumentWithoutChildren();
3529 clone->cloneDataFromDocument(*this);
3531 case CloningOperation::OnlySelf:
3532 case CloningOperation::SelfWithTemplateContent:
3534 case CloningOperation::Everything:
3535 cloneChildNodes(clone);
3538 return WTFMove(clone);
3541 Ref<Document> Document::cloneDocumentWithoutChildren() const
3543 if (isXMLDocument()) {
3544 if (isXHTMLDocument())
3545 return XMLDocument::createXHTML(nullptr, url());
3546 return XMLDocument::create(nullptr, url());
3548 return create(nullptr, url());
3551 void Document::cloneDataFromDocument(const Document& other)
3553 ASSERT(m_url == other.url());
3554 m_baseURL = other.baseURL();
3555 m_baseURLOverride = other.baseURLOverride();
3556 m_documentURI = other.documentURI();
3558 setCompatibilityMode(other.m_compatibilityMode);
3559 setContextDocument(other.contextDocument());
3560 setSecurityOriginPolicy(other.securityOriginPolicy());
3561 overrideMIMEType(other.contentType());
3562 setDecoder(other.decoder());
3565 StyleSheetList& Document::styleSheets()
3567 if (!m_styleSheetList)
3568 m_styleSheetList = StyleSheetList::create(this);
3569 return *m_styleSheetList;
3572 String Document::preferredStylesheetSet() const
3574 return styleScope().preferredStylesheetSetName();
3577 String Document::selectedStylesheetSet() const
3579 return styleScope().selectedStylesheetSetName();
3582 void Document::setSelectedStylesheetSet(const String& aString)
3584 styleScope().setSelectedStylesheetSetName(aString);
3587 void Document::evaluateMediaQueryList()
3589 if (m_mediaQueryMatcher)
3590 m_mediaQueryMatcher->styleResolverChanged();
3592 checkViewportDependentPictures();
3595 void Document::checkViewportDependentPictures()
3597 Vector<HTMLPictureElement*, 16> changedPictures;
3598 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3599 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3600 if ((*it)->viewportChangeAffectedPicture())
3601 changedPictures.append(*it);
3603 for (auto* picture : changedPictures)
3604 picture->sourcesChanged();
3607 void Document::updateViewportUnitsOnResize()
3609 if (!hasStyleWithViewportUnits())
3612 styleScope().resolver().clearCachedPropertiesAffectedByViewportUnits();
3614 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3615 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3616 auto* renderer = element->renderer();
3617 if (renderer && renderer->style().hasViewportUnits())
3618 element->invalidateStyle();
3622 void Document::addAudioProducer(MediaProducer* audioProducer)
3624 m_audioProducers.add(audioProducer);
3625 updateIsPlayingMedia();
3628 void Document::removeAudioProducer(MediaProducer* audioProducer)
3630 m_audioProducers.remove(audioProducer);
3631 updateIsPlayingMedia();
3634 void Document::noteUserInteractionWithMediaElement()
3636 if (m_userHasInteractedWithMediaElement)
3639 if (!topDocument().userDidInteractWithPage())