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 "DocumentTimeline.h"
62 #include "DocumentType.h"
65 #include "ElementIterator.h"
66 #include "EventHandler.h"
67 #include "ExtensionStyleSheets.h"
68 #include "FocusController.h"
69 #include "FocusEvent.h"
70 #include "FontFaceSet.h"
71 #include "FormController.h"
72 #include "FrameLoader.h"
73 #include "FrameLoaderClient.h"
74 #include "FrameView.h"
75 #include "GenericCachedHTMLCollection.h"
76 #include "HTMLAllCollection.h"
77 #include "HTMLAnchorElement.h"
78 #include "HTMLAttachmentElement.h"
79 #include "HTMLBaseElement.h"
80 #include "HTMLBodyElement.h"
81 #include "HTMLCanvasElement.h"
82 #include "HTMLDocument.h"
83 #include "HTMLElementFactory.h"
84 #include "HTMLFormControlElement.h"
85 #include "HTMLFrameOwnerElement.h"
86 #include "HTMLFrameSetElement.h"
87 #include "HTMLHeadElement.h"
88 #include "HTMLHtmlElement.h"
89 #include "HTMLImageElement.h"
90 #include "HTMLInputElement.h"
91 #include "HTMLLinkElement.h"
92 #include "HTMLMediaElement.h"
93 #include "HTMLNameCollection.h"
94 #include "HTMLParserIdioms.h"
95 #include "HTMLPictureElement.h"
96 #include "HTMLPlugInElement.h"
97 #include "HTMLScriptElement.h"
98 #include "HTMLStyleElement.h"
99 #include "HTMLTitleElement.h"
100 #include "HTMLUnknownElement.h"
101 #include "HTTPHeaderNames.h"
102 #include "HTTPParsers.h"
103 #include "HashChangeEvent.h"
105 #include "HitTestResult.h"
106 #include "ImageBitmapRenderingContext.h"
107 #include "ImageLoader.h"
108 #include "InspectorInstrumentation.h"
109 #include "JSCustomElementInterface.h"
110 #include "JSDOMPromiseDeferred.h"
111 #include "JSLazyEventListener.h"
112 #include "KeyboardEvent.h"
113 #include "LayoutDisallowedScope.h"
114 #include "LoaderStrategy.h"
116 #include "MainFrame.h"
117 #include "MediaCanStartListener.h"
118 #include "MediaProducer.h"
119 #include "MediaQueryList.h"
120 #include "MediaQueryMatcher.h"
121 #include "MessageEvent.h"
122 #include "MouseEventWithHitTestResults.h"
123 #include "MutationEvent.h"
124 #include "NameNodeList.h"
125 #include "NavigationDisabler.h"
126 #include "NavigationScheduler.h"
127 #include "NestingLevelIncrementer.h"
128 #include "NoEventDispatchAssertion.h"
129 #include "NodeIterator.h"
130 #include "NodeRareData.h"
131 #include "NodeWithIndex.h"
132 #include "OriginAccessEntry.h"
133 #include "OverflowEvent.h"
134 #include "PageConsoleClient.h"
135 #include "PageGroup.h"
136 #include "PageTransitionEvent.h"
137 #include "PlatformLocale.h"
138 #include "PlatformMediaSessionManager.h"
139 #include "PlatformScreen.h"
140 #include "PlatformStrategies.h"
141 #include "PlugInsResources.h"
142 #include "PluginDocument.h"
143 #include "PointerLockController.h"
144 #include "PopStateEvent.h"
145 #include "ProcessingInstruction.h"
146 #include "PublicSuffix.h"
147 #include "RealtimeMediaSourceCenter.h"
148 #include "RenderChildIterator.h"
149 #include "RenderLayerCompositor.h"
150 #include "RenderTreeUpdater.h"
151 #include "RenderView.h"
152 #include "RenderWidget.h"
153 #include "RequestAnimationFrameCallback.h"
154 #include "ResourceLoadObserver.h"
155 #include "RuntimeApplicationChecks.h"
156 #include "RuntimeEnabledFeatures.h"
157 #include "SVGDocumentExtensions.h"
158 #include "SVGElement.h"
159 #include "SVGElementFactory.h"
160 #include "SVGNames.h"
161 #include "SVGSVGElement.h"
162 #include "SVGTitleElement.h"
163 #include "SVGUseElement.h"
164 #include "SVGZoomEvent.h"
165 #include "SWClientConnection.h"
166 #include "SchemeRegistry.h"
167 #include "ScopedEventQueue.h"
168 #include "ScriptController.h"
169 #include "ScriptModuleLoader.h"
170 #include "ScriptRunner.h"
171 #include "ScriptSourceCode.h"
172 #include "ScriptState.h"
173 #include "ScriptedAnimationController.h"
174 #include "ScrollingCoordinator.h"
175 #include "SecurityOrigin.h"
176 #include "SecurityOriginData.h"
177 #include "SecurityOriginPolicy.h"
178 #include "SecurityPolicy.h"
179 #include "SegmentedString.h"
180 #include "SelectorQuery.h"
181 #include "ServiceWorkerClientData.h"
182 #include "ServiceWorkerProvider.h"
183 #include "Settings.h"
184 #include "ShadowRoot.h"
185 #include "SocketProvider.h"
186 #include "StorageEvent.h"
187 #include "StringCallback.h"
188 #include "StyleProperties.h"
189 #include "StyleResolveForDocument.h"
190 #include "StyleResolver.h"
191 #include "StyleScope.h"
192 #include "StyleSheetContents.h"
193 #include "StyleSheetList.h"
194 #include "StyleTreeResolver.h"
195 #include "SubresourceLoader.h"
196 #include "TextAutoSizing.h"
197 #include "TextEvent.h"
198 #include "TextNodeTraversal.h"
199 #include "TransformSource.h"
200 #include "TreeWalker.h"
201 #include "UserGestureIndicator.h"
202 #include "ValidationMessageClient.h"
203 #include "VisibilityChangeClient.h"
204 #include "VisitedLinkState.h"
205 #include "WebAnimation.h"
206 #include "WheelEvent.h"
207 #include "WindowFeatures.h"
208 #include "XMLDocument.h"
209 #include "XMLDocumentParser.h"
210 #include "XMLNSNames.h"
211 #include "XMLNames.h"
212 #include "XPathEvaluator.h"
213 #include "XPathExpression.h"
214 #include "XPathNSResolver.h"
215 #include "XPathResult.h"
217 #include <inspector/ConsoleMessage.h>
218 #include <inspector/ScriptCallStack.h>
219 #include <wtf/CurrentTime.h>
220 #include <wtf/Language.h>
221 #include <wtf/NeverDestroyed.h>
222 #include <wtf/SetForScope.h>
223 #include <wtf/SystemTracing.h>
224 #include <wtf/UUID.h>
225 #include <wtf/text/StringBuffer.h>
226 #include <wtf/text/TextStream.h>
227 #include <yarr/RegularExpression.h>
229 #if ENABLE(DEVICE_ORIENTATION)
230 #include "DeviceMotionEvent.h"
231 #include "DeviceOrientationEvent.h"
234 #if ENABLE(FULLSCREEN_API)
235 #include "RenderFullScreen.h"
238 #if ENABLE(INDEXED_DATABASE)
239 #include "IDBConnectionProxy.h"
240 #include "IDBOpenDBRequest.h"
244 #include "CSSFontSelector.h"
245 #include "DeviceMotionClientIOS.h"
246 #include "DeviceMotionController.h"
247 #include "DeviceOrientationClientIOS.h"
248 #include "DeviceOrientationController.h"
249 #include "Geolocation.h"
250 #include "Navigator.h"
251 #include "NavigatorGeolocation.h"
252 #include "WKContentObservation.h"
255 #if ENABLE(IOS_GESTURE_EVENTS)
256 #include "GestureEvent.h"
260 #include "MathMLElement.h"
261 #include "MathMLElementFactory.h"
262 #include "MathMLNames.h"
265 #if ENABLE(MEDIA_SESSION)
266 #include "MediaSession.h"
270 #include "QuickLook.h"
273 #if ENABLE(TOUCH_EVENTS)
274 #include "TouchEvent.h"
277 #if ENABLE(VIDEO_TRACK)
278 #include "CaptionUserPreferences.h"
281 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
282 #include "MediaPlaybackTargetClient.h"
286 #include "XSLTProcessor.h"
289 #if ENABLE(MEDIA_STREAM)
290 #include "MediaStream.h"
291 #include "MediaStreamRegistry.h"
295 #include "WebGLRenderingContext.h"
298 #include "WebGL2RenderingContext.h"
301 #include "WebGPURenderingContext.h"
308 using namespace Unicode;
310 using namespace HTMLNames;
312 static const unsigned cMaxWriteRecursionDepth = 21;
313 bool Document::hasEverCreatedAnAXObjectCache = false;
315 // DOM Level 2 says (letters added):
317 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
318 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
319 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
320 // 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.
321 // 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.
322 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
323 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
324 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
325 // i) Characters ':' and '_' are allowed as name-start characters.
326 // j) Characters '-' and '.' are allowed as name characters.
328 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
330 static inline bool isValidNameStart(UChar32 c)
333 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
337 if (c == ':' || c == '_')
340 // rules (a) and (f) above
341 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)))
345 if (c >= 0xF900 && c < 0xFFFE)
349 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
350 if (type == U_DT_FONT || type == U_DT_COMPAT)
356 static inline bool isValidNamePart(UChar32 c)
358 // rules (a), (e), and (i) above
359 if (isValidNameStart(c))
362 // rules (g) and (h) above
363 if (c == 0x00B7 || c == 0x0387)
367 if (c == '-' || c == '.')
370 // rules (b) and (f) above
371 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
375 if (c >= 0xF900 && c < 0xFFFE)
379 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
380 if (type == U_DT_FONT || type == U_DT_COMPAT)
386 static Widget* widgetForElement(Element* focusedElement)
390 auto* renderer = focusedElement->renderer();
391 if (!is<RenderWidget>(renderer))
393 return downcast<RenderWidget>(*renderer).widget();
396 static bool acceptsEditingFocus(const Element& element)
398 ASSERT(element.hasEditableStyle());
400 auto* root = element.rootEditableElement();
401 Frame* frame = element.document().frame();
405 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
408 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
410 // targetFrame can be 0 when we're trying to navigate a top-level frame
411 // that has a 0 opener.
415 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
416 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
417 Document* ancestorDocument = ancestorFrame->document();
418 // FIXME: Should be an ASSERT? Frames should alway have documents.
419 if (!ancestorDocument)
422 const SecurityOrigin& ancestorSecurityOrigin = ancestorDocument->securityOrigin();
423 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
426 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
427 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
428 // something more general instead?
429 if (isLocalActiveOrigin && ancestorSecurityOrigin.isLocal())
436 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
438 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
440 // FIXME: should we print to the console of the document performing the navigation instead?
441 frame->document()->domWindow()->printErrorMessage(message);
444 uint64_t Document::s_globalTreeVersion = 0;
446 auto Document::allDocumentsMap() -> DocumentsMap&
448 static NeverDestroyed<DocumentsMap> documents;
452 auto Document::allDocuments() -> DocumentsMap::ValuesIteratorRange
454 return allDocumentsMap().values();
457 static inline int currentOrientation(Frame* frame)
459 #if ENABLE(ORIENTATION_EVENTS)
461 return frame->orientation();
468 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
469 : ContainerNode(*this, CreateDocument)
471 , FrameDestructionObserver(frame)
472 #if ENABLE(IOS_TOUCH_EVENTS)
473 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
475 , m_settings(frame ? Ref<Settings>(frame->settings()) : Settings::create(nullptr))
476 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
477 , m_domTreeVersion(++s_globalTreeVersion)
478 , m_styleScope(std::make_unique<Style::Scope>(*this))
479 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
480 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
481 , m_markers(std::make_unique<DocumentMarkerController>(*this))
482 , m_styleRecalcTimer([this] { updateStyleIfNeeded(); })
483 , m_documentCreationTime(MonotonicTime::now())
484 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
485 , m_moduleLoader(std::make_unique<ScriptModuleLoader>(*this))
487 , m_applyPendingXSLTransformsTimer(*this, &Document::applyPendingXSLTransformsTimerFired)
489 , m_xmlVersion(ASCIILiteral("1.0"))
490 , m_constantPropertyMap(std::make_unique<ConstantPropertyMap>(*this))
491 , m_documentClasses(documentClasses)
492 , m_eventQueue(*this)
493 #if ENABLE(FULLSCREEN_API)
494 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
496 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
498 #if ENABLE(DEVICE_ORIENTATION)
499 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
500 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
501 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
502 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
505 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
506 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
507 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
508 , m_fontSelector(CSSFontSelector::create(*this))
509 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
510 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
511 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
512 , m_isSynthesized(constructionFlags & Synthesized)
513 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
514 , m_orientationNotifier(currentOrientation(frame))
515 , m_identifier(generateObjectIdentifier<DocumentIdentifierType>())
517 auto addResult = allDocumentsMap().add(m_identifier, this);
518 ASSERT_UNUSED(addResult, addResult.isNewEntry);
520 // We depend on the url getting immediately set in subframes, but we
521 // also depend on the url NOT getting immediately set in opened windows.
522 // See fast/dom/early-frame-url.html
523 // and fast/dom/location-new-window-no-crash.html, respectively.
524 // FIXME: Can/should we unify this behavior?
525 if ((frame && frame->ownerElement()) || !url.isEmpty())
528 m_cachedResourceLoader->setDocument(this);
531 resetVisitedLinkColor();
532 resetActiveLinkColor();
534 initSecurityContext();
537 m_fontSelector->registerForInvalidationCallbacks(*this);
539 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
540 nodeListAndCollectionCount = 0;
543 #if ENABLE(FULLSCREEN_API)
545 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
550 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
552 } while ((owner = owner->document().ownerElement()));
558 Ref<Document> Document::create(Document& contextDocument)
560 auto document = adoptRef(*new Document(nullptr, URL()));
561 document->setContextDocument(contextDocument);
562 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
566 Document::~Document()
568 bool wasRemoved = allDocumentsMap().remove(m_identifier);
569 ASSERT_UNUSED(wasRemoved, wasRemoved);
571 ASSERT(!renderView());
572 ASSERT(m_pageCacheState != InPageCache);
573 ASSERT(m_ranges.isEmpty());
574 ASSERT(!m_parentTreeScope);
575 ASSERT(!m_disabledFieldsetElementsCount);
576 ASSERT(m_inDocumentShadowRoots.isEmpty());
578 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
579 m_deviceMotionClient->deviceMotionControllerDestroyed();
580 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
583 if (m_templateDocument)
584 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
586 // FIXME: Should we reset m_domWindow when we detach from the Frame?
588 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
590 m_scriptRunner = nullptr;
591 m_moduleLoader = nullptr;
593 removeAllEventListeners();
595 // Currently we believe that Document can never outlive the parser.
596 // Although the Document may be replaced synchronously, DocumentParsers
597 // generally keep at least one reference to an Element which would in turn
598 // has a reference to the Document. If you hit this ASSERT, then that
599 // assumption is wrong. DocumentParser::detach() should ensure that even
600 // if the DocumentParser outlives the Document it won't cause badness.
601 ASSERT(!m_parser || m_parser->refCount() == 1);
604 if (this == &topDocument())
605 clearAXObjectCache();
609 if (m_styleSheetList)
610 m_styleSheetList->detachFromDocument();
612 extensionStyleSheets().detachFromDocument();
614 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
615 m_fontSelector->clearDocument();
616 m_fontSelector->unregisterForInvalidationCallbacks(*this);
618 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
619 // load the initial empty document and the SVGDocument with the same DocumentLoader).
620 if (m_cachedResourceLoader->document() == this)
621 m_cachedResourceLoader->setDocument(nullptr);
624 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
625 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
628 // We must call clearRareData() here since a Document class inherits TreeScope
629 // as well as Node. See a comment on TreeScope.h for the reason.
633 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_listsInvalidatedAtDocument.isEmpty());
634 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_collectionsInvalidatedAtDocument.isEmpty());
635 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_svgUseElements.isEmpty());
637 for (unsigned count : m_nodeListAndCollectionCounts)
638 ASSERT_UNUSED(count, !count);
641 m_logger->removeObserver(*this);
644 void Document::removedLastRef()
646 ASSERT(!m_deletionHasBegun);
647 if (m_referencingNodeCount) {
648 // If removing a child removes the last node reference, we don't want the scope to be destroyed
649 // until after removeDetachedChildren returns, so we protect ourselves.
650 incrementReferencingNodeCount();
652 RELEASE_ASSERT(!hasLivingRenderTree());
653 // We must make sure not to be retaining any of our children through
654 // these extra pointers or we will create a reference cycle.
655 m_focusedElement = nullptr;
656 m_hoveredElement = nullptr;
657 m_activeElement = nullptr;
658 m_titleElement = nullptr;
659 m_documentElement = nullptr;
660 m_focusNavigationStartingNode = nullptr;
661 m_userActionElements.clear();
662 #if ENABLE(FULLSCREEN_API)
663 m_fullScreenElement = nullptr;
664 m_fullScreenElementStack.clear();
666 m_associatedFormControls.clear();
670 // removeDetachedChildren() doesn't always unregister IDs,
671 // so tear down scope information up front to avoid having
672 // stale references in the map.
674 destroyTreeScopeData();
675 removeDetachedChildren();
676 m_formController = nullptr;
680 m_cssCanvasElements.clear();
685 // We need to do this right now since selfOnlyDeref() can delete this.
686 m_inRemovedLastRefFunction = false;
688 decrementReferencingNodeCount();
691 m_inRemovedLastRefFunction = false;
692 m_deletionHasBegun = true;
698 void Document::commonTeardown()
701 accessSVGExtensions().pauseAnimations();
703 clearScriptedAnimationController();
706 Element* Document::getElementByAccessKey(const String& key)
710 if (!m_accessKeyMapValid) {
711 buildAccessKeyMap(this);
712 m_accessKeyMapValid = true;
714 return m_elementsByAccessKey.get(key.impl());
717 void Document::buildAccessKeyMap(TreeScope* scope)
720 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
721 const AtomicString& accessKey = element.attributeWithoutSynchronization(accesskeyAttr);
722 if (!accessKey.isEmpty())
723 m_elementsByAccessKey.set(accessKey.impl(), &element);
725 if (ShadowRoot* root = element.shadowRoot())
726 buildAccessKeyMap(root);
730 void Document::invalidateAccessKeyMap()
732 m_accessKeyMapValid = false;
733 m_elementsByAccessKey.clear();
736 void Document::addImageElementByUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
738 return m_imagesByUsemap.add(name, element, *this);
741 void Document::removeImageElementByUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
743 return m_imagesByUsemap.remove(name, element);
746 HTMLImageElement* Document::imageElementByUsemap(const AtomicStringImpl& name) const
748 return m_imagesByUsemap.getElementByUsemap(name, *this);
751 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
753 if (selectorString.isEmpty())
754 return Exception { SyntaxError };
755 if (!m_selectorQueryCache)
756 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
757 return m_selectorQueryCache->add(selectorString, *this);
760 void Document::clearSelectorQueryCache()
762 m_selectorQueryCache = nullptr;
765 MediaQueryMatcher& Document::mediaQueryMatcher()
767 if (!m_mediaQueryMatcher)
768 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
769 return *m_mediaQueryMatcher;
772 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
774 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
776 bool wasInQuirksMode = inQuirksMode();
777 m_compatibilityMode = mode;
779 clearSelectorQueryCache();
781 if (inQuirksMode() != wasInQuirksMode) {
782 // All user stylesheets have to reparse using the different mode.
783 extensionStyleSheets().clearPageUserSheet();
784 extensionStyleSheets().invalidateInjectedStyleSheetCache();
788 String Document::compatMode() const
790 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
793 void Document::resetLinkColor()
795 m_linkColor = Color(0, 0, 238);
798 void Document::resetVisitedLinkColor()
800 m_visitedLinkColor = Color(85, 26, 139);
803 void Document::resetActiveLinkColor()
805 m_activeLinkColor = Color(255, 0, 0);
808 DOMImplementation& Document::implementation()
810 if (!m_implementation)
811 m_implementation = std::make_unique<DOMImplementation>(*this);
812 return *m_implementation;
815 bool Document::hasManifest() const
817 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
820 DocumentType* Document::doctype() const
822 for (Node* node = firstChild(); node; node = node->nextSibling()) {
823 if (node->isDocumentTypeNode())
824 return static_cast<DocumentType*>(node);
829 void Document::childrenChanged(const ChildChange& change)
831 ContainerNode::childrenChanged(change);
833 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
834 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
835 // otherwise, we need to detect the doc type changes before updating the viewport.
836 if (Page* page = this->page())
837 page->chrome().didReceiveDocType(*frame());
839 Element* newDocumentElement = childrenOfType<Element>(*this).first();
840 if (newDocumentElement == m_documentElement)
842 m_documentElement = newDocumentElement;
843 // The root style used for media query matching depends on the document element.
844 styleScope().clearResolver();
847 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
849 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled()
850 || Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
851 return HTMLUnknownElement::create(name, document);
853 auto element = HTMLElement::create(name, document);
854 element->setIsCustomElementUpgradeCandidate();
858 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const AtomicString& localName)
860 return createUpgradeCandidateElement(document, QualifiedName { nullAtom(), localName, xhtmlNamespaceURI });
863 static inline bool isValidHTMLElementName(const AtomicString& localName)
865 return Document::isValidName(localName);
868 static inline bool isValidHTMLElementName(const QualifiedName& name)
870 return Document::isValidName(name.localName());
873 template<typename NameType>
874 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const NameType& name)
876 auto element = HTMLElementFactory::createKnownElement(name, document);
878 return Ref<Element> { element.releaseNonNull() };
880 if (auto* window = document.domWindow()) {
881 auto* registry = window->customElementRegistry();
882 if (UNLIKELY(registry)) {
883 if (auto* elementInterface = registry->findInterface(name))
884 return elementInterface->constructElementWithFallback(document, name);
888 if (UNLIKELY(!isValidHTMLElementName(name)))
889 return Exception { InvalidCharacterError };
891 return Ref<Element> { createUpgradeCandidateElement(document, name) };
894 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomicString& name)
896 if (isHTMLDocument())
897 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
899 if (isXHTMLDocument())
900 return createHTMLElementWithNameValidation(*this, name);
902 if (!isValidName(name))
903 return Exception { InvalidCharacterError };
905 return createElement(QualifiedName(nullAtom(), name, nullAtom()), false);
908 Ref<DocumentFragment> Document::createDocumentFragment()
910 return DocumentFragment::create(document());
913 Ref<Text> Document::createTextNode(const String& data)
915 return Text::create(*this, data);
918 Ref<Comment> Document::createComment(const String& data)
920 return Comment::create(*this, data);
923 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
925 if (isHTMLDocument())
926 return Exception { NotSupportedError };
927 return CDATASection::create(*this, data);
930 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
932 if (!isValidName(target))
933 return Exception { InvalidCharacterError };
935 if (data.contains("?>"))
936 return Exception { InvalidCharacterError };
938 return ProcessingInstruction::create(*this, target, data);
941 Ref<Text> Document::createEditingTextNode(const String& text)
943 return Text::createEditingText(*this, text);
946 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
948 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
949 return propertySet->ensureCSSStyleDeclaration();
952 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
954 switch (nodeToImport.nodeType()) {
955 case DOCUMENT_FRAGMENT_NODE:
956 if (nodeToImport.isShadowRoot())
961 case CDATA_SECTION_NODE:
962 case PROCESSING_INSTRUCTION_NODE:
964 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
967 // FIXME: This will "Attr::normalize" child nodes of Attr.
968 return Ref<Node> { Attr::create(*this, QualifiedName(nullAtom(), downcast<Attr>(nodeToImport).name(), nullAtom()), downcast<Attr>(nodeToImport).value()) };
970 case DOCUMENT_NODE: // Can't import a document into another document.
971 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
975 return Exception { NotSupportedError };
979 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
981 EventQueueScope scope;
983 switch (source.nodeType()) {
985 return Exception { NotSupportedError };
986 case ATTRIBUTE_NODE: {
987 auto& attr = downcast<Attr>(source);
988 if (auto* element = attr.ownerElement()) {
989 auto result = element->removeAttributeNode(attr);
990 if (result.hasException())
991 return result.releaseException();
996 if (source.isShadowRoot()) {
997 // ShadowRoot cannot disconnect itself from the host node.
998 return Exception { HierarchyRequestError };
1000 if (is<HTMLFrameOwnerElement>(source)) {
1001 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
1002 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
1003 return Exception { HierarchyRequestError };
1005 auto result = source.remove();
1006 if (result.hasException())
1007 return result.releaseException();
1008 RELEASE_ASSERT(!source.isConnected());
1009 RELEASE_ASSERT(!source.parentNode());
1012 source.setTreeScopeRecursively(*this);
1014 return Ref<Node> { source };
1017 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1019 // These checks are from DOM Core Level 2, createElementNS
1020 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1021 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1023 if (qName.prefix() == xmlAtom() && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1026 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1027 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1028 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1029 if (qName.prefix() == xmlnsAtom() || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom()))
1030 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1031 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1034 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1036 return hasValidNamespaceForElements(qName);
1039 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1041 if (auto* window = document.domWindow()) {
1042 auto* registry = window->customElementRegistry();
1043 if (UNLIKELY(registry)) {
1044 if (auto* elementInterface = registry->findInterface(name)) {
1045 auto element = HTMLElement::create(name, document);
1046 element->enqueueToUpgrade(*elementInterface);
1051 // FIXME: Should we also check the equality of prefix between the custom element and name?
1052 return createUpgradeCandidateElement(document, name);
1055 // FIXME: This should really be in a possible ElementFactory class.
1056 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1058 RefPtr<Element> element;
1060 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1061 if (name.namespaceURI() == xhtmlNamespaceURI) {
1062 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1063 if (UNLIKELY(!element))
1064 element = createFallbackHTMLElement(*this, name);
1065 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1066 element = SVGElementFactory::createElement(name, *this, createdByParser);
1068 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1069 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1073 m_sawElementsInKnownNamespaces = true;
1075 element = Element::create(name, document());
1077 // <image> uses imgTag so we need a special rule.
1078 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1080 return element.releaseNonNull();
1083 // https://html.spec.whatwg.org/#valid-custom-element-name
1085 struct UnicodeCodePointRange {
1090 #if !ASSERT_DISABLED
1092 static inline bool operator<(const UnicodeCodePointRange& a, const UnicodeCodePointRange& b)
1094 ASSERT(a.minimum <= a.maximum);
1095 ASSERT(b.minimum <= b.maximum);
1096 return a.maximum < b.minimum;
1101 static inline bool operator<(const UnicodeCodePointRange& a, UChar32 b)
1103 ASSERT(a.minimum <= a.maximum);
1104 return a.maximum < b;
1107 static inline bool operator<(UChar32 a, const UnicodeCodePointRange& b)
1109 ASSERT(b.minimum <= b.maximum);
1110 return a < b.minimum;
1113 static inline bool isPotentialCustomElementNameCharacter(UChar32 character)
1115 static const UnicodeCodePointRange ranges[] = {
1132 { 0x10000, 0xEFFFF },
1135 ASSERT(std::is_sorted(std::begin(ranges), std::end(ranges)));
1136 return std::binary_search(std::begin(ranges), std::end(ranges), character);
1139 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomicString& localName)
1141 if (!isASCIILower(localName[0]))
1142 return CustomElementNameValidationStatus::FirstCharacterIsNotLowercaseASCIILetter;
1144 bool containsHyphen = false;
1145 for (auto character : StringView(localName).codePoints()) {
1146 if (isASCIIUpper(character))
1147 return CustomElementNameValidationStatus::ContainsUppercaseASCIILetter;
1148 if (!isPotentialCustomElementNameCharacter(character))
1149 return CustomElementNameValidationStatus::ContainsDisallowedCharacter;
1150 if (character == '-')
1151 containsHyphen = true;
1154 if (!containsHyphen)
1155 return CustomElementNameValidationStatus::ContainsNoHyphen;
1158 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag->localName();
1160 static NeverDestroyed<const AtomicString> annotationXmlLocalName("annotation-xml", AtomicString::ConstructFromLiteral);
1163 if (localName == SVGNames::color_profileTag->localName()
1164 || localName == SVGNames::font_faceTag->localName()
1165 || localName == SVGNames::font_face_formatTag->localName()
1166 || localName == SVGNames::font_face_nameTag->localName()
1167 || localName == SVGNames::font_face_srcTag->localName()
1168 || localName == SVGNames::font_face_uriTag->localName()
1169 || localName == SVGNames::missing_glyphTag->localName()
1170 || localName == annotationXmlLocalName)
1171 return CustomElementNameValidationStatus::ConflictsWithStandardElementName;
1173 return CustomElementNameValidationStatus::Valid;
1176 bool Document::isCSSGridLayoutEnabled() const
1178 return RuntimeEnabledFeatures::sharedFeatures().isCSSGridLayoutEnabled();
1181 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName)
1183 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1184 if (parseResult.hasException())
1185 return parseResult.releaseException();
1186 QualifiedName parsedName { parseResult.releaseReturnValue() };
1187 if (!hasValidNamespaceForElements(parsedName))
1188 return Exception { NamespaceError };
1190 if (parsedName.namespaceURI() == xhtmlNamespaceURI)
1191 return createHTMLElementWithNameValidation(*this, parsedName);
1193 return createElement(parsedName, false);
1196 void Document::setReadyState(ReadyState readyState)
1198 if (readyState == m_readyState)
1201 switch (readyState) {
1203 if (!m_documentTiming.domLoading)
1204 m_documentTiming.domLoading = MonotonicTime::now();
1207 if (!m_documentTiming.domInteractive)
1208 m_documentTiming.domInteractive = MonotonicTime::now();
1211 if (!m_documentTiming.domComplete)
1212 m_documentTiming.domComplete = MonotonicTime::now();
1216 m_readyState = readyState;
1217 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1219 if (settings().suppressesIncrementalRendering())
1220 setVisualUpdatesAllowed(readyState);
1223 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1225 ASSERT(settings().suppressesIncrementalRendering());
1226 switch (readyState) {
1228 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1229 ASSERT(m_visualUpdatesAllowed);
1230 setVisualUpdatesAllowed(false);
1233 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1236 if (m_visualUpdatesSuppressionTimer.isActive()) {
1237 ASSERT(!m_visualUpdatesAllowed);
1239 if (view() && !view()->visualUpdatesAllowedByClient())
1242 setVisualUpdatesAllowed(true);
1244 ASSERT(m_visualUpdatesAllowed);
1249 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1251 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1254 m_visualUpdatesAllowed = visualUpdatesAllowed;
1256 if (visualUpdatesAllowed)
1257 m_visualUpdatesSuppressionTimer.stop();
1259 m_visualUpdatesSuppressionTimer.startOneShot(1_s * settings().incrementalRenderingSuppressionTimeoutInSeconds());
1261 if (!visualUpdatesAllowed)
1264 RefPtr<FrameView> frameView = view();
1265 bool needsLayout = frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout());
1269 if (Page* page = this->page()) {
1270 if (frame()->isMainFrame()) {
1271 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1272 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1273 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1278 frameView->updateCompositingLayersAfterLayout();
1280 if (RenderView* renderView = this->renderView())
1281 renderView->repaintViewAndCompositedLayers();
1283 if (Frame* frame = this->frame())
1284 frame->loader().forcePageTransitionIfNeeded();
1287 void Document::visualUpdatesSuppressionTimerFired()
1289 ASSERT(!m_visualUpdatesAllowed);
1291 // If the client is extending the visual update suppression period explicitly, the
1292 // watchdog should not re-enable visual updates itself, but should wait for the client.
1293 if (view() && !view()->visualUpdatesAllowedByClient())
1296 setVisualUpdatesAllowed(true);
1299 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1301 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1302 // both of which we can determine by looking at the timer.
1304 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1305 setVisualUpdatesAllowed(true);
1308 String Document::characterSetWithUTF8Fallback() const
1310 AtomicString name = encoding();
1313 return UTF8Encoding().domName();
1316 String Document::defaultCharsetForLegacyBindings() const
1319 UTF8Encoding().domName();
1320 return settings().defaultTextEncodingName();
1323 void Document::setCharset(const String& charset)
1327 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1330 void Document::setContentLanguage(const String& language)
1332 if (m_contentLanguage == language)
1334 m_contentLanguage = language;
1336 // Recalculate style so language is used when selecting the initial font.
1337 m_styleScope->didChangeStyleSheetEnvironment();
1340 ExceptionOr<void> Document::setXMLVersion(const String& version)
1342 if (!XMLDocumentParser::supportsXMLVersion(version))
1343 return Exception { NotSupportedError };
1345 m_xmlVersion = version;
1349 void Document::setXMLStandalone(bool standalone)
1351 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1354 void Document::setDocumentURI(const String& uri)
1356 // This property is read-only from JavaScript, but writable from Objective-C.
1357 m_documentURI = uri;
1361 void Document::setContent(const String& content)
1364 // FIXME: This should probably use insert(), but that's (intentionally)
1365 // not implemented for the XML parser as it's normally synonymous with
1366 // document.write(). append() will end up yielding, but close() will
1367 // pump the tokenizer syncrhonously and finish the parse.
1368 m_parser->append(content.impl());
1372 String Document::suggestedMIMEType() const
1374 if (isXHTMLDocument())
1375 return ASCIILiteral("application/xhtml+xml");
1376 if (isSVGDocument())
1377 return ASCIILiteral("image/svg+xml");
1378 if (xmlStandalone())
1379 return ASCIILiteral("text/xml");
1380 if (isHTMLDocument())
1381 return ASCIILiteral("text/html");
1382 if (DocumentLoader* loader = this->loader())
1383 return loader->responseMIMEType();
1387 void Document::overrideMIMEType(const String& mimeType)
1389 m_overriddenMIMEType = mimeType;
1392 String Document::contentType() const
1394 if (!m_overriddenMIMEType.isNull())
1395 return m_overriddenMIMEType;
1397 if (DocumentLoader* documentLoader = loader())
1398 return documentLoader->currentContentType();
1400 String mimeType = suggestedMIMEType();
1401 if (!mimeType.isNull())
1404 return ASCIILiteral("application/xml");
1407 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1409 return caretRangeFromPoint(LayoutPoint(x, y));
1412 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1414 if (!hasLivingRenderTree())
1417 LayoutPoint localPoint;
1418 Node* node = nodeFromPoint(clientPoint, &localPoint);
1422 RenderObject* renderer = node->renderer();
1425 Position rangeCompliantPosition = renderer->positionForPoint(localPoint).parentAnchoredEquivalent();
1426 if (rangeCompliantPosition.isNull())
1429 unsigned offset = rangeCompliantPosition.offsetInContainerNode();
1430 node = &retargetToScope(*rangeCompliantPosition.containerNode());
1431 if (node != rangeCompliantPosition.containerNode())
1434 return Range::create(*this, node, offset, node, offset);
1437 Element* Document::scrollingElement()
1439 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1440 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1445 template<typename CharacterType> static inline String canonicalizedTitle(Document& document, const String& title)
1447 // FIXME: Compiling a separate copy of this for LChar and UChar is likely unnecessary.
1448 // FIXME: Missing an optimized case for when title is fine as-is. This unnecessarily allocates
1449 // and keeps around a new copy, and it's even the less optimal type of StringImpl with a separate buffer.
1450 // Could probably just use StringBuilder instead.
1452 auto* characters = title.characters<CharacterType>();
1453 unsigned length = title.length();
1455 StringBuffer<CharacterType> buffer { length };
1456 unsigned bufferLength = 0;
1458 auto* decoder = document.decoder();
1459 auto backslashAsCurrencySymbol = decoder ? decoder->encoding().backslashAsCurrencySymbol() : '\\';
1461 // Collapse runs of HTML spaces into single space characters.
1462 // Strip leading and trailing spaces.
1463 // Replace backslashes with currency symbols.
1464 bool previousCharacterWasHTMLSpace = false;
1465 for (unsigned i = 0; i < length; ++i) {
1466 auto character = characters[i];
1467 if (isHTMLSpace(character))
1468 previousCharacterWasHTMLSpace = true;
1470 if (character == '\\')
1471 character = backslashAsCurrencySymbol;
1472 if (previousCharacterWasHTMLSpace && bufferLength)
1473 buffer[bufferLength++] = ' ';
1474 buffer[bufferLength++] = character;
1475 previousCharacterWasHTMLSpace = false;
1481 buffer.shrink(bufferLength);
1482 return String::adopt(WTFMove(buffer));
1485 void Document::updateTitle(const StringWithDirection& title)
1487 if (m_rawTitle == title)
1493 if (!m_title.string.isEmpty()) {
1494 if (m_title.string.is8Bit())
1495 m_title.string = canonicalizedTitle<LChar>(*this, m_title.string);
1497 m_title.string = canonicalizedTitle<UChar>(*this, m_title.string);
1500 if (auto* loader = this->loader())
1501 loader->setTitle(m_title);
1504 void Document::updateTitleFromTitleElement()
1506 if (!m_titleElement) {
1511 if (is<HTMLTitleElement>(*m_titleElement))
1512 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1513 else if (is<SVGTitleElement>(*m_titleElement)) {
1514 // FIXME: Does the SVG title element have a text direction?
1515 updateTitle({ downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR });
1519 void Document::setTitle(const String& title)
1521 if (!m_titleElement) {
1522 if (isHTMLDocument() || isXHTMLDocument()) {
1523 auto* headElement = head();
1526 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1527 headElement->appendChild(*m_titleElement);
1528 } else if (isSVGDocument()) {
1529 auto* element = documentElement();
1530 if (!is<SVGSVGElement>(element))
1532 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1533 element->insertBefore(*m_titleElement, element->firstChild());
1535 } else if (!isHTMLDocument() && !isXHTMLDocument() && !isSVGDocument()) {
1536 // FIXME: What exactly is the point of this? This seems like a strange moment
1537 // in time to demote something from being m_titleElement, when setting the
1538 // value of the title attribute. Do we have test coverage for this?
1539 m_titleElement = nullptr;
1542 if (is<HTMLTitleElement>(m_titleElement.get()))
1543 downcast<HTMLTitleElement>(*m_titleElement).setTextContent(title);
1544 else if (is<SVGTitleElement>(m_titleElement.get()))
1545 downcast<SVGTitleElement>(*m_titleElement).setTextContent(title);
1547 updateTitle({ title, LTR });
1550 template<typename> struct TitleTraits;
1552 template<> struct TitleTraits<HTMLTitleElement> {
1553 static bool isInEligibleLocation(HTMLTitleElement& element) { return element.isConnected() && !element.isInShadowTree(); }
1554 static HTMLTitleElement* findTitleElement(Document& document) { return descendantsOfType<HTMLTitleElement>(document).first(); }
1557 template<> struct TitleTraits<SVGTitleElement> {
1558 static bool isInEligibleLocation(SVGTitleElement& element) { return element.parentNode() == element.document().documentElement(); }
1559 static SVGTitleElement* findTitleElement(Document& document) { return childrenOfType<SVGTitleElement>(*document.documentElement()).first(); }
1562 template<typename TitleElement> Element* selectNewTitleElement(Document& document, Element* oldTitleElement, Element& changingTitleElement)
1564 using Traits = TitleTraits<TitleElement>;
1566 if (!is<TitleElement>(changingTitleElement)) {
1567 ASSERT(oldTitleElement == Traits::findTitleElement(document));
1568 return oldTitleElement;
1571 if (oldTitleElement)
1572 return Traits::findTitleElement(document);
1574 // Optimized common case: We have no title element yet.
1575 // We can figure out which title element should be used without searching.
1576 bool isEligible = Traits::isInEligibleLocation(downcast<TitleElement>(changingTitleElement));
1577 auto* newTitleElement = isEligible ? &changingTitleElement : nullptr;
1578 ASSERT(newTitleElement == Traits::findTitleElement(document));
1579 return newTitleElement;
1582 void Document::updateTitleElement(Element& changingTitleElement)
1584 // Most documents use HTML title rules.
1585 // Documents with SVG document elements use SVG title rules.
1586 auto selectTitleElement = is<SVGSVGElement>(documentElement())
1587 ? selectNewTitleElement<SVGTitleElement> : selectNewTitleElement<HTMLTitleElement>;
1588 auto newTitleElement = selectTitleElement(*this, m_titleElement.get(), changingTitleElement);
1589 if (m_titleElement == newTitleElement)
1591 m_titleElement = newTitleElement;
1592 updateTitleFromTitleElement();
1595 void Document::titleElementAdded(Element& titleElement)
1597 if (m_titleElement == &titleElement)
1600 updateTitleElement(titleElement);
1603 void Document::titleElementRemoved(Element& titleElement)
1605 if (m_titleElement != &titleElement)
1608 updateTitleElement(titleElement);
1611 void Document::titleElementTextChanged(Element& titleElement)
1613 if (m_titleElement != &titleElement)
1616 updateTitleFromTitleElement();
1619 void Document::registerForVisibilityStateChangedCallbacks(VisibilityChangeClient* client)
1621 m_visibilityStateCallbackClients.add(client);
1624 void Document::unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient* client)
1626 m_visibilityStateCallbackClients.remove(client);
1629 void Document::visibilityStateChanged()
1631 enqueueDocumentEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1632 for (auto* client : m_visibilityStateCallbackClients)
1633 client->visibilityStateChanged();
1635 notifyMediaCaptureOfVisibilityChanged();
1638 VisibilityState Document::visibilityState() const
1640 // The visibility of the document is inherited from the visibility of the
1641 // page. If there is no page associated with the document, we will assume
1642 // that the page is hidden, as specified by the spec:
1643 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1644 if (!m_frame || !m_frame->page())
1645 return VisibilityState::Hidden;
1646 return m_frame->page()->visibilityState();
1649 bool Document::hidden() const
1651 return visibilityState() != VisibilityState::Visible;
1656 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1658 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1661 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1663 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1666 void Document::allowsMediaDocumentInlinePlaybackChanged()
1668 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1669 element->allowsMediaDocumentInlinePlaybackChanged();
1674 String Document::nodeName() const
1676 return ASCIILiteral("#document");
1679 Node::NodeType Document::nodeType() const
1681 return DOCUMENT_NODE;
1684 FormController& Document::formController()
1686 if (!m_formController)
1687 m_formController = std::make_unique<FormController>();
1688 return *m_formController;
1691 Vector<String> Document::formElementsState() const
1693 if (!m_formController)
1694 return Vector<String>();
1695 return m_formController->formElementsState();
1698 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1700 if (!stateVector.size() && !m_formController)
1702 formController().setStateForNewFormElements(stateVector);
1705 FrameView* Document::view() const
1707 return m_frame ? m_frame->view() : nullptr;
1710 Page* Document::page() const
1712 return m_frame ? m_frame->page() : nullptr;
1715 Ref<Range> Document::createRange()
1717 return Range::create(*this);
1720 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1722 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1725 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1727 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1730 void Document::scheduleForcedStyleRecalc()
1732 m_pendingStyleRecalcShouldForce = true;
1733 scheduleStyleRecalc();
1736 void Document::scheduleStyleRecalc()
1738 ASSERT(!m_renderView || !m_renderView->inHitTesting());
1740 if (m_styleRecalcTimer.isActive() || pageCacheState() != NotInPageCache)
1743 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1745 // FIXME: Why on earth is this here? This is clearly misplaced.
1746 invalidateAccessKeyMap();
1748 m_styleRecalcTimer.startOneShot(0_s);
1750 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1753 void Document::unscheduleStyleRecalc()
1755 ASSERT(!childNeedsStyleRecalc());
1757 m_styleRecalcTimer.stop();
1758 m_pendingStyleRecalcShouldForce = false;
1761 bool Document::hasPendingStyleRecalc() const
1763 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1766 bool Document::hasPendingForcedStyleRecalc() const
1768 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1771 void Document::resolveStyle(ResolveStyleType type)
1773 ASSERT(!view() || !view()->isPainting());
1775 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1779 FrameView& frameView = m_renderView->frameView();
1780 Ref<FrameView> protect(frameView);
1781 if (frameView.isPainting())
1784 if (m_inStyleRecalc)
1785 return; // Guard against re-entrancy. -dwh
1787 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1789 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1790 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1792 // FIXME: Do this update per tree scope.
1794 auto elements = copyToVectorOf<RefPtr<SVGUseElement>>(m_svgUseElements);
1795 // We can't clear m_svgUseElements here because updateShadowTree may end up executing arbitrary scripts
1796 // which may insert new SVG use elements or remove existing ones inside sync IPC via ImageLoader::updateFromElement.
1797 for (auto& element : elements)
1798 element->updateShadowTree();
1801 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1802 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1803 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1804 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1805 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1806 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1809 NoEventDispatchAssertion::InMainThread noEventDispatchAssertion;
1810 styleScope().flushPendingUpdate();
1811 frameView.willRecalcStyle();
1814 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1816 bool updatedCompositingLayers = false;
1818 Style::PostResolutionCallbackDisabler disabler(*this);
1819 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1820 NoEventDispatchAssertion::InMainThread noEventDispatchAssertion;
1822 m_inStyleRecalc = true;
1824 if (m_pendingStyleRecalcShouldForce)
1825 type = ResolveStyleType::Rebuild;
1827 if (type == ResolveStyleType::Rebuild) {
1828 // This may get set again during style resolve.
1829 m_hasNodesWithNonFinalStyle = false;
1830 m_hasNodesWithMissingStyle = false;
1832 auto documentStyle = Style::resolveForDocument(*this);
1834 // Inserting the pictograph font at the end of the font fallback list is done by the
1835 // font selector, so set a font selector if needed.
1836 if (settings().fontFallbackPrefersPictographs())
1837 documentStyle.fontCascade().update(&fontSelector());
1839 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
1840 if (documentChange != Style::NoChange)
1841 renderView()->setStyle(WTFMove(documentStyle));
1843 if (auto* documentElement = this->documentElement())
1844 documentElement->invalidateStyleForSubtree();
1847 Style::TreeResolver resolver(*this);
1848 auto styleUpdate = resolver.resolve();
1850 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
1853 clearChildNeedsStyleRecalc();
1854 unscheduleStyleRecalc();
1856 m_inStyleRecalc = false;
1859 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1861 RenderTreeUpdater updater(*this);
1862 updater.commit(WTFMove(styleUpdate));
1864 frameView.styleDidChange();
1867 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1869 if (m_renderView->needsLayout())
1870 frameView.layoutContext().scheduleLayout();
1872 // Usually this is handled by post-layout.
1873 if (!frameView.needsLayout())
1874 frameView.frame().selection().scheduleAppearanceUpdateAfterStyleChange();
1876 // As a result of the style recalculation, the currently hovered element might have been
1877 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1878 // to check if any other elements ended up under the mouse pointer due to re-layout.
1879 if (m_hoveredElement && !m_hoveredElement->renderer())
1880 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1882 ++m_styleRecalcCount;
1883 // FIXME: Assert ASSERT(!needsStyleRecalc()) here. Do we still have some cases where it's not true?
1886 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1887 if (m_closeAfterStyleRecalc) {
1888 m_closeAfterStyleRecalc = false;
1892 InspectorInstrumentation::didRecalculateStyle(cookie);
1894 // Some animated images may now be inside the viewport due to style recalc,
1895 // resume them if necessary if there is no layout pending. Otherwise, we'll
1896 // check if they need to be resumed after layout.
1897 if (updatedCompositingLayers && !frameView.needsLayout())
1898 frameView.viewportContentsChanged();
1900 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
1901 frameView.scrollToFragment(m_url);
1904 void Document::updateTextRenderer(Text& text, unsigned offsetOfReplacedText, unsigned lengthOfReplacedText)
1906 ASSERT(!m_inRenderTreeUpdate);
1907 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1909 auto textUpdate = std::make_unique<Style::Update>(*this);
1910 textUpdate->addText(text, { offsetOfReplacedText, lengthOfReplacedText, std::nullopt });
1912 RenderTreeUpdater renderTreeUpdater(*this);
1913 renderTreeUpdater.commit(WTFMove(textUpdate));
1916 bool Document::needsStyleRecalc() const
1918 if (pageCacheState() != NotInPageCache)
1921 if (m_pendingStyleRecalcShouldForce)
1924 if (childNeedsStyleRecalc())
1927 if (styleScope().hasPendingUpdate())
1930 // Ensure this happens eventually as it is currently in resolveStyle. This can be removed if the code moves.
1931 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
1937 inline bool static isSafeToUpdateStyleOrLayout(FrameView* frameView)
1939 bool isSafeToExecuteScript = NoEventDispatchAssertion::InMainThread::isEventAllowed();
1940 bool isInFrameFlattening = frameView && frameView->isInChildFrameWithFrameFlattening();
1941 return isSafeToExecuteScript || isInFrameFlattening || !isInWebProcess();
1944 bool Document::updateStyleIfNeeded()
1946 RefPtr<FrameView> frameView = view();
1948 NoEventDispatchAssertion::InMainThread noEventDispatchAssertion;
1949 ASSERT(isMainThread());
1950 ASSERT(!frameView || !frameView->isPainting());
1952 if (!frameView || frameView->layoutContext().isInRenderTreeLayout())
1955 styleScope().flushPendingUpdate();
1957 if (!needsStyleRecalc())
1961 // The early exit above for !needsStyleRecalc() is needed when updateWidgetPositions() is called in runOrScheduleAsynchronousTasks().
1962 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(frameView.get()));
1968 void Document::updateLayout()
1970 ASSERT(isMainThread());
1971 ASSERT(LayoutDisallowedScope::isLayoutAllowed());
1973 RefPtr<FrameView> frameView = view();
1974 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
1975 // View layout should not be re-entrant.
1976 ASSERT_NOT_REACHED();
1979 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(frameView.get()));
1981 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1983 if (HTMLFrameOwnerElement* owner = ownerElement())
1984 owner->document().updateLayout();
1986 updateStyleIfNeeded();
1988 StackStats::LayoutCheckPoint layoutCheckPoint;
1990 // Only do a layout if changes have occurred that make it necessary.
1991 if (frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
1992 frameView->layoutContext().layout();
1995 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1997 bool oldIgnore = m_ignorePendingStylesheets;
1999 if (!haveStylesheetsLoaded()) {
2000 m_ignorePendingStylesheets = true;
2001 // FIXME: This should just invalidate elements with missing styles.
2002 if (m_hasNodesWithMissingStyle)
2003 scheduleForcedStyleRecalc();
2008 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
2009 view()->flushAnyPendingPostLayoutTasks();
2011 m_ignorePendingStylesheets = oldIgnore;
2014 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle, PseudoId pseudoElementSpecifier)
2016 ASSERT(&element.document() == this);
2017 ASSERT(!element.isPseudoElement() || !pseudoElementSpecifier);
2018 ASSERT(!pseudoElementSpecifier || parentStyle);
2020 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
2021 Style::PostResolutionCallbackDisabler disabler(*this);
2023 SetForScope<bool> change(m_ignorePendingStylesheets, true);
2024 auto& resolver = element.styleResolver();
2026 if (pseudoElementSpecifier)
2027 return resolver.pseudoStyleForElement(element, PseudoStyleRequest(pseudoElementSpecifier), *parentStyle);
2029 auto elementStyle = resolver.styleForElement(element, parentStyle);
2030 if (elementStyle.relations) {
2031 Style::Update emptyUpdate(*this);
2032 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
2035 return WTFMove(elementStyle.renderStyle);
2038 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2040 ASSERT(isMainThread());
2042 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2043 if (!haveStylesheetsLoaded()) {
2044 updateLayoutIgnorePendingStylesheets();
2048 // Check for re-entrancy and assert (same code that is in updateLayout()).
2049 RefPtr<FrameView> frameView = view();
2050 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
2051 // View layout should not be re-entrant.
2052 ASSERT_NOT_REACHED();
2056 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2058 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2060 bool requireFullLayout = false;
2061 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2062 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2063 requireFullLayout = true;
2066 updateStyleIfNeeded();
2068 RenderObject* renderer = element.renderer();
2069 if (!renderer || renderer->needsLayout()) {
2070 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2071 requireFullLayout = true;
2074 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2075 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2076 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2077 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2079 if (!requireFullLayout) {
2080 RenderBox* previousBox = nullptr;
2081 RenderBox* currentBox = nullptr;
2083 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2084 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2086 // Require the entire container chain to be boxes.
2087 if (!is<RenderBox>(currRenderer)) {
2088 requireFullLayout = true;
2092 previousBox = currentBox;
2093 currentBox = downcast<RenderBox>(currRenderer);
2095 // If a box needs layout for itself or if a box has changed children and sizes its width to
2096 // its content, then require a full layout.
2097 if (currentBox->selfNeedsLayout() ||
2098 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2099 requireFullLayout = true;
2103 // If a block contains floats and the child's height isn't specified, then
2104 // give up also, since our height could end up being influenced by the floats.
2105 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2106 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2107 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2108 requireFullLayout = true;
2113 if (!currentBox->isRenderBlockFlow() || currentBox->enclosingFragmentedFlow() || currentBox->isWritingModeRoot()) {
2114 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2115 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2116 // Disallow columns from having the optimization.
2117 // Give up if the writing mode changes at all in the containing block chain.
2118 requireFullLayout = true;
2122 if (currRenderer == frameView->layoutContext().subtreeLayoutRoot())
2127 StackStats::LayoutCheckPoint layoutCheckPoint;
2129 // Only do a layout if changes have occurred that make it necessary.
2130 if (requireFullLayout && frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
2131 frameView->layoutContext().layout();
2133 return requireFullLayout;
2136 bool Document::isPageBoxVisible(int pageIndex)
2138 updateStyleIfNeeded();
2139 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2140 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2143 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2145 updateStyleIfNeeded();
2146 auto style = styleScope().resolver().styleForPage(pageIndex);
2148 int width = pageSize.width();
2149 int height = pageSize.height();
2150 switch (style->pageSizeType()) {
2151 case PAGE_SIZE_AUTO:
2153 case PAGE_SIZE_AUTO_LANDSCAPE:
2155 std::swap(width, height);
2157 case PAGE_SIZE_AUTO_PORTRAIT:
2159 std::swap(width, height);
2161 case PAGE_SIZE_RESOLVED: {
2162 auto& size = style->pageSize();
2163 ASSERT(size.width.isFixed());
2164 ASSERT(size.height.isFixed());
2165 width = valueForLength(size.width, 0);
2166 height = valueForLength(size.height, 0);
2170 ASSERT_NOT_REACHED();
2172 pageSize = IntSize(width, height);
2174 // The percentage is calculated with respect to the width even for margin top and bottom.
2175 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2176 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2177 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2178 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2179 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2182 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2184 if (!m_userAgentShadowTreeStyleResolver)
2185 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2186 return *m_userAgentShadowTreeStyleResolver;
2189 void Document::fontsNeedUpdate(FontSelector&)
2191 invalidateMatchedPropertiesCacheAndForceStyleRecalc();
2194 void Document::invalidateMatchedPropertiesCacheAndForceStyleRecalc()
2196 if (auto* resolver = styleScope().resolverIfExists())
2197 resolver->invalidateMatchedPropertiesCache();
2198 if (pageCacheState() != NotInPageCache || !renderView())
2200 scheduleForcedStyleRecalc();
2203 void Document::didClearStyleResolver()
2205 m_userAgentShadowTreeStyleResolver = nullptr;
2208 void Document::createRenderTree()
2210 ASSERT(!renderView());
2211 ASSERT(m_pageCacheState != InPageCache);
2212 ASSERT(!m_axObjectCache || this != &topDocument());
2214 if (m_isNonRenderedPlaceholder)
2217 // FIXME: It would be better if we could pass the resolved document style directly here.
2218 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2219 Node::setRenderer(m_renderView.get());
2221 renderView()->setIsInWindow(true);
2223 resolveStyle(ResolveStyleType::Rebuild);
2226 void Document::didBecomeCurrentDocumentInFrame()
2228 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2229 // If so, then m_frame could become 0, and we need to do something about that.
2231 m_frame->script().updateDocument();
2233 if (!hasLivingRenderTree())
2236 updateViewportArguments();
2238 // FIXME: Doing this only for the main frame is insufficient.
2239 // Changing a subframe can also change the wheel event handler count.
2240 // FIXME: Doing this only when a document goes into the frame is insufficient.
2241 // Removing a document can also change the wheel event handler count.
2242 // FIXME: Doing this every time is a waste. If the current document and its
2243 // subframes' documents have no wheel event handlers, then the count did not change,
2244 // unless the documents they are replacing had wheel event handlers.
2245 if (page() && m_frame->isMainFrame())
2246 wheelEventHandlersChanged();
2248 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2249 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2250 // page cache, or simply newly created).
2251 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2252 m_frame->animation().suspendAnimationsForDocument(this);
2253 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2255 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2256 m_frame->animation().resumeAnimationsForDocument(this);
2260 void Document::frameDestroyed()
2262 // detachFromFrame() must be called before destroying the Frame.
2263 RELEASE_ASSERT(!m_frame);
2264 FrameDestructionObserver::frameDestroyed();
2267 void Document::attachToCachedFrame(CachedFrameBase& cachedFrame)
2269 RELEASE_ASSERT(cachedFrame.document() == this);
2270 ASSERT(cachedFrame.view());
2271 ASSERT(m_pageCacheState == Document::InPageCache);
2272 observeFrame(&cachedFrame.view()->frame());
2275 void Document::detachFromCachedFrame(CachedFrameBase& cachedFrame)
2277 ASSERT_UNUSED(cachedFrame, cachedFrame.view());
2278 RELEASE_ASSERT(cachedFrame.document() == this);
2279 ASSERT(m_frame == &cachedFrame.view()->frame());
2280 ASSERT(m_pageCacheState == Document::InPageCache);
2284 void Document::destroyRenderTree()
2286 ASSERT(hasLivingRenderTree());
2288 ASSERT(frame()->document() == this);
2291 // Prevent Widget tree changes from committing until the RenderView is dead and gone.
2292 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2294 SetForScope<bool> change(m_renderTreeBeingDestroyed, true);
2296 if (this == &topDocument())
2297 clearAXObjectCache();
2299 documentWillBecomeInactive();
2302 view()->willDestroyRenderTree();
2304 if (m_documentElement)
2305 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2307 clearChildNeedsStyleRecalc();
2309 unscheduleStyleRecalc();
2311 // FIXME: RenderObject::view() uses m_renderView and we can't null it before destruction is completed
2312 m_renderView->destroy();
2313 m_renderView.release();
2315 Node::setRenderer(nullptr);
2317 #if ENABLE(TEXT_AUTOSIZING)
2318 m_textAutoSizing = nullptr;
2322 view()->didDestroyRenderTree();
2325 void Document::prepareForDestruction()
2327 if (m_hasPreparedForDestruction)
2331 m_timeline->detachFromDocument();
2332 m_timeline = nullptr;
2336 m_frame->animation().detachFromDocument(this);
2338 #if ENABLE(SERVICE_WORKER)
2339 setActiveServiceWorker(nullptr);
2340 setServiceWorkerConnection(nullptr);
2343 #if ENABLE(IOS_TOUCH_EVENTS)
2344 clearTouchEventHandlersAndListeners();
2347 #if HAVE(ACCESSIBILITY)
2348 if (this != &topDocument()) {
2349 // Let the ax cache know that this subframe goes out of scope.
2350 if (auto* cache = existingAXObjectCache())
2351 cache->prepareForDocumentDestruction(*this);
2356 NavigationDisabler navigationDisabler(m_frame);
2357 disconnectDescendantFrames();
2360 if (m_domWindow && m_frame)
2361 m_domWindow->willDetachDocumentFromFrame();
2363 if (hasLivingRenderTree())
2364 destroyRenderTree();
2366 if (is<PluginDocument>(*this))
2367 downcast<PluginDocument>(*this).detachFromPluginElement();
2369 #if ENABLE(POINTER_LOCK)
2371 page()->pointerLockController().documentDetached(*this);
2374 if (auto* page = this->page()) {
2375 if (auto* validationMessageClient = page->validationMessageClient())
2376 validationMessageClient->documentDetached(*this);
2379 InspectorInstrumentation::documentDetached(*this);
2381 stopActiveDOMObjects();
2382 m_eventQueue.close();
2383 #if ENABLE(FULLSCREEN_API)
2384 m_fullScreenChangeEventTargetQueue.clear();
2385 m_fullScreenErrorEventTargetQueue.clear();
2390 #if ENABLE(TOUCH_EVENTS)
2391 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2392 parentDocument()->didRemoveEventTargetNode(*this);
2395 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2396 parentDocument()->didRemoveEventTargetNode(*this);
2398 if (m_mediaQueryMatcher)
2399 m_mediaQueryMatcher->documentDestroyed();
2401 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2402 if (!m_clientToIDMap.isEmpty() && page()) {
2403 for (auto* client : copyToVector(m_clientToIDMap.keys()))
2404 removePlaybackTargetPickerClient(*client);
2408 m_cachedResourceLoader->stopUnusedPreloadsTimer();
2410 if (page() && m_mediaState != MediaProducer::IsNotPlaying) {
2411 m_mediaState = MediaProducer::IsNotPlaying;
2412 page()->updateIsPlayingMedia(HTMLMediaElementInvalidID);
2417 m_hasPreparedForDestruction = true;
2419 // Note that m_pageCacheState can be Document::AboutToEnterPageCache if our frame
2420 // was removed in an onpagehide event handler fired when the top-level frame is
2421 // about to enter the page cache.
2422 RELEASE_ASSERT(m_pageCacheState != Document::InPageCache);
2425 void Document::removeAllEventListeners()
2427 EventTarget::removeAllEventListeners();
2430 m_domWindow->removeAllEventListeners();
2432 #if ENABLE(IOS_TOUCH_EVENTS)
2433 clearTouchEventHandlersAndListeners();
2435 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2436 node->removeAllEventListeners();
2438 #if ENABLE(TOUCH_EVENTS)
2439 m_touchEventTargets = nullptr;
2441 m_wheelEventTargets = nullptr;
2444 void Document::suspendDeviceMotionAndOrientationUpdates()
2446 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2448 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2449 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2450 if (m_deviceMotionController)
2451 m_deviceMotionController->suspendUpdates();
2452 if (m_deviceOrientationController)
2453 m_deviceOrientationController->suspendUpdates();
2457 void Document::resumeDeviceMotionAndOrientationUpdates()
2459 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2461 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2462 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2463 if (m_deviceMotionController)
2464 m_deviceMotionController->resumeUpdates();
2465 if (m_deviceOrientationController)
2466 m_deviceOrientationController->resumeUpdates();
2470 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2472 JSC::CallFrame* callFrame = commonVM().topCallFrame;
2473 if (callFrame == JSC::CallFrame::noCaller())
2475 DOMWrapperWorld& domWrapperWorld = currentWorld(callFrame);
2476 if (domWrapperWorld.isNormal())
2481 void Document::platformSuspendOrStopActiveDOMObjects()
2484 if (WebThreadCountOfObservedContentModifiers() > 0) {
2485 if (auto* frame = this->frame()) {
2486 if (auto* page = frame->page())
2487 page->chrome().client().clearContentChangeObservers(*frame);
2493 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2495 ScriptExecutionContext::suspendActiveDOMObjects(why);
2496 suspendDeviceMotionAndOrientationUpdates();
2497 platformSuspendOrStopActiveDOMObjects();
2500 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2502 ScriptExecutionContext::resumeActiveDOMObjects(why);
2503 resumeDeviceMotionAndOrientationUpdates();
2504 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2507 void Document::stopActiveDOMObjects()
2509 ScriptExecutionContext::stopActiveDOMObjects();
2510 platformSuspendOrStopActiveDOMObjects();
2513 void Document::clearAXObjectCache()
2515 ASSERT(&topDocument() == this);
2516 // Clear the cache member variable before calling delete because attempts
2517 // are made to access it during destruction.
2518 m_axObjectCache = nullptr;
2521 AXObjectCache* Document::existingAXObjectCacheSlow() const
2523 ASSERT(hasEverCreatedAnAXObjectCache);
2524 return topDocument().m_axObjectCache.get();
2527 AXObjectCache* Document::axObjectCache() const
2529 if (!AXObjectCache::accessibilityEnabled())
2532 // The only document that actually has a AXObjectCache is the top-level
2533 // document. This is because we need to be able to get from any WebCoreAXObject
2534 // to any other WebCoreAXObject on the same page. Using a single cache allows
2535 // lookups across nested webareas (i.e. multiple documents).
2536 Document& topDocument = this->topDocument();
2538 // If the document has already been detached, do not make a new axObjectCache.
2539 if (!topDocument.hasLivingRenderTree())
2542 ASSERT(&topDocument == this || !m_axObjectCache);
2543 if (!topDocument.m_axObjectCache) {
2544 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2545 hasEverCreatedAnAXObjectCache = true;
2547 return topDocument.m_axObjectCache.get();
2550 void Document::setVisuallyOrdered()
2552 m_visuallyOrdered = true;
2554 renderView()->mutableStyle().setRTLOrdering(VisualOrder);
2557 Ref<DocumentParser> Document::createParser()
2559 // FIXME: this should probably pass the frame instead
2560 return XMLDocumentParser::create(*this, view());
2563 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2565 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2568 ExceptionOr<RefPtr<DOMWindow>> Document::openForBindings(DOMWindow& activeWindow, DOMWindow& firstWindow, const String& url, const AtomicString& name, const String& features)
2571 return Exception { InvalidAccessError };
2573 return m_domWindow->open(activeWindow, firstWindow, url, name, features);
2576 // FIXME: Add support for the 'type' and 'replace' parameters.
2577 ExceptionOr<Document&> Document::openForBindings(Document* responsibleDocument, const String&, const String&)
2579 if (!isHTMLDocument())
2580 return Exception { InvalidStateError };
2582 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2584 open(responsibleDocument);
2588 void Document::open(Document* responsibleDocument)
2590 if (m_ignoreOpensDuringUnloadCount)
2593 if (responsibleDocument) {
2594 setURL(responsibleDocument->url());
2595 setCookieURL(responsibleDocument->cookieURL());
2596 setSecurityOriginPolicy(responsibleDocument->securityOriginPolicy());
2600 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2601 if (parser->isParsing()) {
2602 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2603 if (parser->isExecutingScript())
2606 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2611 if (m_frame->loader().state() == FrameStateProvisional)
2612 m_frame->loader().stopAllLoaders();
2615 removeAllEventListeners();
2617 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2618 parser->setWasCreatedByScript(true);
2621 m_frame->loader().didExplicitOpen();
2624 void Document::detachParser()
2632 void Document::cancelParsing()
2637 // We have to clear the parser to avoid possibly triggering
2638 // the onload handler when closing as a side effect of a cancel-style
2639 // change, such as opening a new document or closing the window while
2645 void Document::implicitOpen()
2649 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2652 m_parser = createParser();
2654 setReadyState(Loading);
2657 HTMLBodyElement* Document::body() const
2659 auto* element = documentElement();
2662 return childrenOfType<HTMLBodyElement>(*element).first();
2665 HTMLElement* Document::bodyOrFrameset() const
2667 // Return the first body or frameset child of the html element.
2668 auto* element = documentElement();
2669 if (!is<HTMLHtmlElement>(element))
2671 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2672 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2678 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2680 if (!is<HTMLBodyElement>(newBody) && !is<HTMLFrameSetElement>(newBody))
2681 return Exception { HierarchyRequestError };
2683 auto* currentBody = bodyOrFrameset();
2684 if (newBody == currentBody)
2687 if (!m_documentElement)
2688 return Exception { HierarchyRequestError };
2691 return m_documentElement->replaceChild(*newBody, *currentBody);
2692 return m_documentElement->appendChild(*newBody);
2695 Location* Document::location() const
2697 auto* window = domWindow();
2701 return window->location();
2704 HTMLHeadElement* Document::head()
2706 if (auto element = documentElement())
2707 return childrenOfType<HTMLHeadElement>(*element).first();
2711 ExceptionOr<void> Document::closeForBindings()
2713 // FIXME: We should follow the specification more closely:
2714 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2716 if (!isHTMLDocument())
2717 return Exception { InvalidStateError };
2719 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2725 void Document::close()
2727 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2733 void Document::explicitClose()
2735 if (RefPtr<DocumentParser> parser = m_parser)
2739 // Because we have no frame, we don't know if all loading has completed,
2740 // so we just call implicitClose() immediately. FIXME: This might fire
2741 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2749 void Document::implicitClose()
2751 // 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.
2752 if (m_inStyleRecalc) {
2753 m_closeAfterStyleRecalc = true;
2757 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2758 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2763 // Call to dispatchWindowLoadEvent can blow us from underneath.
2764 Ref<Document> protectedThis(*this);
2766 m_processingLoadEvent = true;
2768 ScriptableDocumentParser* parser = scriptableDocumentParser();
2769 m_wellFormed = parser && parser->wellFormed();
2771 // We have to clear the parser, in case someone document.write()s from the
2772 // onLoad event handler, as in Radar 3206524.
2775 // FIXME: We kick off the icon loader when the Document is done parsing.
2776 // There are earlier opportunities we could start it:
2777 // -When the <head> finishes parsing
2778 // -When any new HTMLLinkElement is inserted into the document
2779 // But those add a dynamic component to the favicon that has UI
2780 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2781 RefPtr<Frame> f = frame();
2784 // Apply XSL transforms before load events so that event handlers can access the transformed DOM tree.
2785 applyPendingXSLTransformsNowIfScheduled();
2788 if (auto* documentLoader = loader())
2789 documentLoader->startIconLoading();
2791 f->animation().startAnimationsIfNotSuspended(this);
2793 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2794 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2795 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2796 ImageLoader::dispatchPendingBeforeLoadEvents();
2797 ImageLoader::dispatchPendingLoadEvents();
2798 ImageLoader::dispatchPendingErrorEvents();
2799 HTMLLinkElement::dispatchPendingLoadEvents();
2800 HTMLStyleElement::dispatchPendingLoadEvents();
2802 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2803 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2804 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2805 if (svgExtensions())
2806 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2809 dispatchWindowLoadEvent();
2810 dispatchPageshowEvent(PageshowEventNotPersisted);
2811 if (m_pendingStateObject)
2812 dispatchPopstateEvent(WTFMove(m_pendingStateObject));
2815 f->loader().dispatchOnloadEvents();
2817 // An event handler may have removed the frame
2819 m_processingLoadEvent = false;
2823 // Make sure both the initial layout and reflow happen after the onload
2824 // fires. This will improve onload scores, and other browsers do it.
2825 // If they wanna cheat, we can too. -dwh
2827 if (frame()->navigationScheduler().locationChangePending() && timeSinceDocumentCreation() < settings().layoutInterval()) {
2828 // Just bail out. Before or during the onload we were shifted to another page.
2829 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2830 m_processingLoadEvent = false;
2831 view()->layoutContext().unscheduleLayout();
2835 frame()->loader().checkCallImplicitClose();
2837 // We used to force a synchronous display and flush here. This really isn't
2838 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2839 // (if your platform is syncing flushes and limiting them to 60fps).
2840 m_overMinimumLayoutThreshold = true;
2841 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2842 updateStyleIfNeeded();
2844 // Always do a layout after loading if needed.
2845 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2846 view()->layoutContext().layout();
2849 m_processingLoadEvent = false;
2851 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK)
2852 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2853 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2854 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2855 // exists in the cache (we ignore the return value because we don't need it here). This is
2856 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2858 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2859 // catch new AND page history loads, and that uses AXLoadComplete
2861 axObjectCache()->getOrCreate(renderView());
2862 if (this == &topDocument())
2863 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2865 // AXLoadComplete can only be posted on the top document, so if it's a document
2866 // in an iframe that just finished loading, post AXLayoutComplete instead.
2867 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2872 if (svgExtensions())
2873 accessSVGExtensions().startAnimations();
2876 void Document::setParsing(bool b)
2880 if (m_bParsing && !m_sharedObjectPool)
2881 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2883 if (!m_bParsing && view() && !view()->needsLayout())
2884 view()->fireLayoutRelatedMilestonesIfNeeded();
2887 bool Document::shouldScheduleLayout()
2889 if (!documentElement())
2891 if (!is<HTMLHtmlElement>(*documentElement()))
2893 if (!bodyOrFrameset())
2895 if (styleScope().hasPendingSheetsBeforeBody())
2901 bool Document::isLayoutTimerActive()
2903 return view() && view()->layoutContext().isLayoutPending() && !minimumLayoutDelay();
2906 Seconds Document::minimumLayoutDelay()
2908 if (m_overMinimumLayoutThreshold)
2911 auto elapsed = timeSinceDocumentCreation();
2912 m_overMinimumLayoutThreshold = elapsed > settings().layoutInterval();
2914 // We'll want to schedule the timer to fire at the minimum layout threshold.
2915 return std::max(0_s, settings().layoutInterval() - elapsed);
2918 Seconds Document::timeSinceDocumentCreation() const
2920 return MonotonicTime::now() - m_documentCreationTime;
2923 void Document::write(Document* responsibleDocument, SegmentedString&& text)
2925 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2927 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2928 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2930 if (m_writeRecursionIsTooDeep)
2933 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2934 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2937 if (!hasInsertionPoint)
2938 open(responsibleDocument);
2941 m_parser->insert(WTFMove(text));
2944 ExceptionOr<void> Document::write(Document* responsibleDocument, Vector<String>&& strings)
2946 if (!isHTMLDocument())
2947 return Exception { InvalidStateError };
2949 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2951 SegmentedString text;
2952 for (auto& string : strings)
2953 text.append(WTFMove(string));
2955 write(responsibleDocument, WTFMove(text));
2960 ExceptionOr<void> Document::writeln(Document* responsibleDocument, Vector<String>&& strings)
2962 if (!isHTMLDocument())
2963 return Exception { InvalidStateError };
2965 // FIXME: This should also throw if "document's throw-on-dynamic-markup-insertion counter is greater than 0".
2967 SegmentedString text;
2968 for (auto& string : strings)
2969 text.append(WTFMove(string));
2971 text.append(ASCIILiteral { "\n" });
2972 write(responsibleDocument, WTFMove(text));
2977 Seconds Document::minimumDOMTimerInterval() const
2979 auto* page = this->page();
2981 return ScriptExecutionContext::minimumDOMTimerInterval();
2982 return page->settings().minimumDOMTimerInterval();
2985 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2987 if (m_isTimerThrottlingEnabled == shouldThrottle)
2990 m_isTimerThrottlingEnabled = shouldThrottle;
2991 didChangeTimerAlignmentInterval();
2994 Seconds Document::domTimerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2996 auto alignmentInterval = ScriptExecutionContext::domTimerAlignmentInterval(hasReachedMaxNestingLevel);
2997 if (!hasReachedMaxNestingLevel)
2998 return alignmentInterval;
3000 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
3001 if (m_isTimerThrottlingEnabled)
3002 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
3004 if (Page* page = this->page())
3005 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
3007 if (!topOrigin().canAccess(securityOrigin()) && !hasHadUserInteraction())
3008 alignmentInterval = std::max(alignmentInterval, DOMTimer::nonInteractedCrossOriginFrameAlignmentInterval());
3010 return alignmentInterval;
3013 EventTarget* Document::errorEventTarget()
3015 return m_domWindow.get();
3018 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
3020 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
3023 void Document::setURL(const URL& url)
3025 const URL& newURL = url.isEmpty() ? blankURL() : url;
3026 if (newURL == m_url)
3030 m_documentURI = m_url.string();
3034 void Document::updateBaseURL()
3036 URL oldBaseURL = m_baseURL;
3037 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
3038 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
3039 // from the Document interface otherwise.
3040 if (!m_baseElementURL.isEmpty())
3041 m_baseURL = m_baseElementURL;
3042 else if (!m_baseURLOverride.isEmpty())
3043 m_baseURL = m_baseURLOverride;
3045 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
3046 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
3047 // and DOM 3 Core does not specify how it should be resolved.
3048 m_baseURL = URL(ParsedURLString, documentURI());
3051 clearSelectorQueryCache();
3053 if (!m_baseURL.isValid())
3056 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
3057 // Base URL change changes any relative visited links.
3058 // 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.
3059 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
3060 anchor.invalidateCachedVisitedLinkHash();
3064 void Document::setBaseURLOverride(const URL& url)
3066 m_baseURLOverride = url;
3070 void Document::processBaseElement()
3072 // Find the first href attribute in a base element and the first target attribute in a base element.
3073 const AtomicString* href = nullptr;
3074 const AtomicString* target = nullptr;
3075 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3076 for (auto& base : baseDescendants) {
3078 const AtomicString& value = base.attributeWithoutSynchronization(hrefAttr);
3079 if (!value.isNull()) {
3086 const AtomicString& value = base.attributeWithoutSynchronization(targetAttr);
3087 if (!value.isNull()) {
3095 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3098 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3099 if (!strippedHref.isEmpty())
3100 baseElementURL = URL(url(), strippedHref);
3102 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3103 m_baseElementURL = baseElementURL;
3107 m_baseTarget = target ? *target : nullAtom();
3110 String Document::userAgent(const URL& url) const
3112 return frame() ? frame()->loader().userAgent(url) : String();
3115 void Document::disableEval(const String& errorMessage)
3120 frame()->script().disableEval(errorMessage);
3123 void Document::disableWebAssembly(const String& errorMessage)
3128 frame()->script().disableWebAssembly(errorMessage);
3131 #if ENABLE(INDEXED_DATABASE)
3132 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
3134 if (!m_idbConnectionProxy) {
3135 Page* currentPage = page();
3138 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
3140 return m_idbConnectionProxy.get();
3144 SocketProvider* Document::socketProvider()
3146 return m_socketProvider.get();
3149 bool Document::canNavigate(Frame* targetFrame)
3154 // FIXME: We shouldn't call this function without a target frame, but
3155 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3156 // returning true when supplied with a 0 targetFrame.
3160 // Cases (i), (ii) and (iii) pass the tests from the specifications but might not pass the "security origin" tests.
3162 // i. A frame can navigate its top ancestor when its 'allow-top-navigation' flag is set (sometimes known as 'frame-busting').
3163 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3166 // 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.
3167 if (!isSandboxed(SandboxTopNavigationByUserActivation) && UserGestureIndicator::processingUserGesture() && targetFrame == &m_frame->tree().top())
3170 // iii. A sandboxed frame can always navigate its descendants.
3171 if (isSandboxed(SandboxNavigation) && targetFrame->tree().isDescendantOf(m_frame))
3174 // From https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate.
3175 // 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
3176 // flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.
3177 if (m_frame != targetFrame && isSandboxed(SandboxNavigation) && targetFrame->tree().parent() && !targetFrame->tree().isDescendantOf(m_frame)) {
3178 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."));
3182 // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
3183 if (m_frame != targetFrame && targetFrame == &m_frame->tree().top()) {
3184 bool triggeredByUserActivation = UserGestureIndicator::processingUserGesture();
3185 // 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.
3186 if (triggeredByUserActivation && isSandboxed(SandboxTopNavigationByUserActivation)) {
3187 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."));
3190 // 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.
3191 if (!triggeredByUserActivation && isSandboxed(SandboxTopNavigation)) {
3192 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set."));
3197 // 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
3198 // sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.
3199 if (!targetFrame->tree().parent() && m_frame != targetFrame && targetFrame != &m_frame->tree().top() && isSandboxed(SandboxNavigation) && targetFrame->loader().opener() != m_frame) {
3200 printNavigationErrorMessage(targetFrame, url(), ASCIILiteral("The frame attempting navigation is sandboxed, and is not allowed to navigate this popup."));
3204 // 4. Otherwise, terminate positively!
3206 // This is the normal case. A document can navigate its descendant frames,
3207 // or, more generally, a document can navigate a frame if the document is
3208 // in the same origin as any of that frame's ancestors (in the frame
3211 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3212 // historical information about this security check.
3213 if (canAccessAncestor(securityOrigin(), targetFrame))
3216 // Top-level frames are easier to navigate than other frames because they
3217 // display their URLs in the address bar (in most browsers). However, there
3218 // are still some restrictions on navigation to avoid nuisance attacks.
3219 // Specifically, a document can navigate a top-level frame if that frame
3220 // opened the document or if the document is the same-origin with any of
3221 // the top-level frame's opener's ancestors (in the frame hierarchy).
3223 // In both of these cases, the document performing the navigation is in
3224 // some way related to the frame being navigate (e.g., by the "opener"
3225 // and/or "parent" relation). Requiring some sort of relation prevents a
3226 // document from navigating arbitrary, unrelated top-level frames.
3227 if (!targetFrame->tree().parent()) {
3228 if (targetFrame == m_frame->loader().opener())
3231 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3235 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3239 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3241 Frame* currentFrame = m_frame;
3245 Frame* ancestorFrame = currentFrame->tree().parent();
3247 while (ancestorFrame) {
3248 if (!ancestorFrame->document()->securityOrigin().canAccess(securityOrigin()))
3249 return currentFrame;
3250 currentFrame = ancestorFrame;
3251 ancestorFrame = ancestorFrame->tree().parent();
3256 void Document::didRemoveAllPendingStylesheet()
3258 if (auto* parser = scriptableDocumentParser())
3259 parser->executeScriptsWaitingForStylesheetsSoon();
3262 bool Document::usesStyleBasedEditability() const
3264 if (m_hasElementUsingStyleBasedEditability)
3267 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3268 ASSERT(!m_inStyleRecalc);
3270 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3271 styleScope.flushPendingUpdate();
3272 return styleScope.usesStyleBasedEditability();
3275 void Document::setHasElementUsingStyleBasedEditability()
3277 m_hasElementUsingStyleBasedEditability = true;
3280 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3282 ASSERT(!equiv.isNull());
3283 ASSERT(!content.isNull());
3285 HttpEquivPolicy policy = httpEquivPolicy();
3286 if (policy != HttpEquivPolicy::Enabled) {
3289 case HttpEquivPolicy::Enabled:
3290 ASSERT_NOT_REACHED();
3292 case HttpEquivPolicy::DisabledBySettings:
3293 reason = "by the embedder.";
3295 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3296 reason = "for documents with Content-Disposition: attachment.";
3299 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3300 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3304 Frame* frame = this->frame();
3306 HTTPHeaderName headerName;
3307 if (!findHTTPHeaderName(equiv, headerName))
3310 switch (headerName) {
3311 case HTTPHeaderName::DefaultStyle:
3312 // The preferred style set has been overridden as per section
3313 // 14.3.2 of the HTML4.0 specification. We need to update the
3314 // sheet used variable and then update our style selector.
3315 // For more info, see the test at:
3316 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3318 styleScope().setSelectedStylesheetSetName(content);
3319 styleScope().setPreferredStylesheetSetName(content);
3322 case HTTPHeaderName::Refresh: {
3325 if (frame && parseMetaHTTPEquivRefresh(content, delay, urlString)) {
3327 if (urlString.isEmpty())
3328 completedURL = m_url;
3330 completedURL = completeURL(urlString);
3331 if (!protocolIsJavaScript(completedURL))
3332 frame->navigationScheduler().scheduleRedirect(*this, delay, completedURL);
3334 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3335 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3342 case HTTPHeaderName::SetCookie:
3343 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3344 if (is<HTMLDocument>(*this)) {
3345 // Exception (for sandboxed documents) ignored.
3346 downcast<HTMLDocument>(*this).setCookie(content);
3350 case HTTPHeaderName::ContentLanguage:
3351 setContentLanguage(content);
3354 case HTTPHeaderName::XDNSPrefetchControl:
3355 parseDNSPrefetchControlHeader(content);
3358 case HTTPHeaderName::XFrameOptions:
3360 FrameLoader& frameLoader = frame->loader();
3361 unsigned long requestIdentifier = 0;
3362 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3363 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3365 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.";
3366 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3370 case HTTPHeaderName::ContentSecurityPolicy:
3371 if (isInDocumentHead)
3372 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::Enforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3375 case HTTPHeaderName::XWebKitCSP:
3376 if (isInDocumentHead)
3377 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::PrefixedEnforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3385 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3387 ASSERT(!features.isNull());
3389 LOG_WITH_STREAM(Viewports, stream << "Document::processViewport " << features);
3391 if (origin < m_viewportArguments.type)
3394 m_viewportArguments = ViewportArguments(origin);
3396 LOG_WITH_STREAM(Viewports, stream << " resolved to " << m_viewportArguments);
3398 processFeaturesString(features, FeatureMode::Viewport, [this](StringView key, StringView value) {
3399 setViewportFeature(m_viewportArguments, *this, key, value);
3402 updateViewportArguments();
3405 void Document::updateViewportArguments()
3407 if (page() && frame()->isMainFrame()) {
3409 m_didDispatchViewportPropertiesChanged = true;
3411 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3412 page()->chrome().didReceiveDocType(*frame());
3418 void Document::processFormatDetection(const String& features)
3420 // FIXME: Find a better place for this function.
3421 processFeaturesString(features, FeatureMode::Viewport, [this](StringView key, StringView value) {
3422 if (equalLettersIgnoringASCIICase(key, "telephone") && equalLettersIgnoringASCIICase(value, "no"))
3423 setIsTelephoneNumberParsingAllowed(false);
3427 void Document::processWebAppOrientations()
3429 if (Page* page = this->page())
3430 page->chrome().client().webAppOrientationsUpdated();
3435 void Document::processReferrerPolicy(const String& policy)
3437 ASSERT(!policy.isNull());
3439 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3440 // even if the document has a meta tag saying otherwise.
3441 if (shouldEnforceContentDispositionAttachmentSandbox())
3445 if (shouldEnforceQuickLookSandbox())
3449 // "never" / "default" / "always" are legacy keywords that we will support. They were defined in:
3450 // https://www.w3.org/TR/2014/WD-referrer-policy-20140807/#referrer-policy-delivery-meta
3451 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3452 setReferrerPolicy(ReferrerPolicy::NoReferrer);
3453 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3454 setReferrerPolicy(ReferrerPolicy::UnsafeUrl);
3455 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3456 setReferrerPolicy(ReferrerPolicy::Origin);
3457 else if (equalLettersIgnoringASCIICase(policy, "origin-when-cross-origin"))
3458 setReferrerPolicy(ReferrerPolicy::OriginWhenCrossOrigin);
3459 else if (equalLettersIgnoringASCIICase(policy, "same-origin"))
3460 setReferrerPolicy(ReferrerPolicy::SameOrigin);
3461 else if (equalLettersIgnoringASCIICase(policy, "strict-origin"))
3462 setReferrerPolicy(ReferrerPolicy::StrictOrigin);
3463 else if (equalLettersIgnoringASCIICase(policy, "strict-origin-when-cross-origin"))
3464 setReferrerPolicy(ReferrerPolicy::StrictOriginWhenCrossOrigin);
3465 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3466 setReferrerPolicy(ReferrerPolicy::NoReferrerWhenDowngrade);
3468 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'.");
3469 setReferrerPolicy(ReferrerPolicy::NoReferrer);
3473 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3475 if (!hasLivingRenderTree())
3476 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3478 HitTestResult result(documentPoint);
3479 renderView()->hitTest(request, result);
3481 if (!request.readOnly())
3482 updateHoverActiveState(request, result.targetElement());
3484 return MouseEventWithHitTestResults(event, result);
3487 // DOM Section 1.1.1
3488 bool Document::childTypeAllowed(NodeType type) const
3491 case ATTRIBUTE_NODE:
3492 case CDATA_SECTION_NODE:
3493 case DOCUMENT_FRAGMENT_NODE:
3498 case PROCESSING_INSTRUCTION_NODE:
3500 case DOCUMENT_TYPE_NODE:
3502 // Documents may contain no more than one of each of these.
3503 // (One Element and one DocumentType.)
3504 for (Node* c = firstChild(); c; c = c->nextSibling())
3505 if (c->nodeType() == type)
3512 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3514 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3517 switch (newChild.nodeType()) {
3518 case ATTRIBUTE_NODE:
3519 case CDATA_SECTION_NODE:
3524 case PROCESSING_INSTRUCTION_NODE:
3526 case DOCUMENT_FRAGMENT_NODE: {
3527 bool hasSeenElementChild = false;
3528 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3529 if (is<Element>(*node)) {
3530 if (hasSeenElementChild)
3532 hasSeenElementChild = true;
3534 if (!canAcceptChild(*node, refChild, operation))
3539 case DOCUMENT_TYPE_NODE: {
3540 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3541 if (operation == AcceptChildOperation::Replace) {
3542 // parent has a doctype child that is not child, or an element is preceding child.
3543 if (existingDocType && existingDocType != refChild)
3545 if (refChild->previousElementSibling())
3548 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3549 if (existingDocType)
3551 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3556 case ELEMENT_NODE: {
3557 auto* existingElementChild = firstElementChild();
3558 if (operation == AcceptChildOperation::Replace) {
3559 if (existingElementChild && existingElementChild != refChild)
3561 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3562 if (is<DocumentType>(*child))
3566 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3567 if (existingElementChild)
3569 for (auto* child = refChild; child; child = child->nextSibling()) {
3570 if (is<DocumentType>(*child))
3580 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3582 Ref<Document> clone = cloneDocumentWithoutChildren();
3583 clone->cloneDataFromDocument(*this);
3585 case CloningOperation::OnlySelf:
3586 case CloningOperation::SelfWithTemplateContent:
3588 case CloningOperation::Everything:
3589 cloneChildNodes(clone);
3592 return WTFMove(clone);
3595 Ref<Document> Document::cloneDocumentWithoutChildren() const
3597 if (isXMLDocument()) {
3598 if (isXHTMLDocument())
3599 return XMLDocument::createXHTML(nullptr, url());
3600 return XMLDocument::create(nullptr, url());
3602 return create(nullptr, url());
3605 void Document::cloneDataFromDocument(const Document& other)
3607 ASSERT(m_url == other.url());
3608 m_baseURL = other.baseURL();
3609 m_baseURLOverride = other.baseURLOverride();
3610 m_documentURI = other.documentURI();
3612 setCompatibilityMode(other.m_compatibilityMode);
3613 setContextDocument(other.contextDocument());
3614 setSecurityOriginPolicy(other.securityOriginPolicy());
3615 overrideMIMEType(other.contentType());
3616 setDecoder(other.decoder());
3619 StyleSheetList& Document::styleSheets()
3621 if (!m_styleSheetList)
3622 m_styleSheetList = StyleSheetList::create(this);
3623 return *m_styleSheetList;
3626 String Document::preferredStylesheetSet() const
3628 return styleScope().preferredStylesheetSetName();
3631 String Document::selectedStylesheetSet() const
3633 return styleScope().selectedStylesheetSetName();
3636 void Document::setSelectedStylesheetSet(const String& aString)
3638 styleScope().setSelectedStylesheetSetName(aString);
3641 void Document::evaluateMediaQueryList()
3643 if (m_mediaQueryMatcher)
3644 m_mediaQueryMatcher->styleResolverChanged();
3646 checkViewportDependentPictures();
3649 void Document::checkViewportDependentPictures()
3651 Vector<HTMLPictureElement*, 16> changedPictures;
3652 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3653 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3654 if ((*it)->viewportChangeAffectedPicture())
3655 changedPictures.append(*it);
3657 for (auto* picture : changedPictures)
3658 picture->sourcesChanged();
3661 void Document::updateViewportUnitsOnResize()
3663 if (!hasStyleWithViewportUnits())
3666 styleScope().resolver().clearCachedPropertiesAffectedByViewportUnits();
3668 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3669 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3670 auto* renderer = element->renderer();
3671 if (renderer && renderer->style().hasViewportUnits())
3672 element->invalidateStyle();
3676 void Document::addAudioProducer(MediaProducer* audioProducer)
3678 m_audioProducers.add(audioProducer);
3679 updateIsPlayingMedia();
3682 void Document::removeAudioProducer(MediaProducer* audioProducer)
3684 m_audioProducers.remove(audioProducer);
3685 updateIsPlayingMedia();
3688 void Document::noteUserInteractionWithMediaElement()
3690 if (m_userHasInteractedWithMediaElement)
3693 if (!topDocument().userDidInteractWithPage())
3696 m_userHasInteractedWithMediaElement = true;
3697 updateIsPlayingMedia();
3700 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3702 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3703 for (auto* audioProducer : m_audioProducers)
3704 state |= audioProducer->mediaState();
3706 #if ENABLE(MEDIA_SESSION)
3707 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3708 if (sourceElement->isPlaying())
3709 state |= MediaProducer::IsSourceElementPlaying;
3711 if (auto* session = sourceElement->session()) {
3712 if (auto* controls = session->controls()) {
3713 if (controls->previousTrackEnabled())
3714 state |= MediaProducer::IsPreviousTrackControlEnabled;
3715 if (controls->nextTrackEnabled())
3716 state |= MediaProducer::IsNextTrackControlEnabled;
3722 if (m_userHasInteractedWithMediaElement)
3723 state |= MediaProducer::HasUserInteractedWithMediaElement;
3725 if (state == m_mediaState)
3728 #if ENABLE(MEDIA_STREAM)
3729 bool captureStateChanged = MediaProducer::isCapturing(m_mediaState) != MediaProducer::isCapturing(state);
3732 m_mediaState = state;
3735 page()->updateIsPlayingMedia(sourceElementID);
3737 #if ENABLE(MEDIA_STREAM)
3738 if (captureStateChanged)
3739 mediaStreamCaptureStateChanged();
3743 void Document::pageMutedStateDidChange()
3745 for (auto* audioProducer : m_audioProducers)
3746 audioProducer->pageMutedStateDidChange();
3749 static bool isNodeInSubtree(Node& node, Node& container, bool amongChildrenOnly)
3751 if (amongChildrenOnly)
3752 return node.isDescendantOf(container);
3754 return &node == &container || node.isDescendantOf(container);
3757 void Document::removeFocusedNodeOfSubtree(Node& node, bool amongChildrenOnly)
3759 if (!m_focusedElement || pageCacheState() != NotInPageCache) // If the document is in the page cache, then we don't need to clear out the focused node.
3762 Element* focusedElement = node.treeScope().focusedElementInScope();
3763 if (!focusedElement)
3766 if (isNodeInSubtree(*focusedElement, node, amongChildrenOnly)) {
3767 // FIXME: We should avoid synchronously updating the style inside setFocusedElement.
3768 // FIXME: Object elements should avoid loading a frame synchronously in a post style recalc callback.
3769 SubframeLoadingDisabler disabler(is<ContainerNode>(node) ? &downcast<ContainerNode>(node) : nullptr);
3770 setFocusedElement(nullptr, FocusDirectionNone, FocusRemovalEventsMode::DoNotDispatch);
3771 // Set the focus navigation starting node to the previous focused element so that
3772 // we can fallback to the siblings or parent node for the next search.
3773 // Also we need to call removeFocusNavigationNodeOfSubtree after this function because
3774 // setFocusedElement(nullptr) will reset m_focusNavigationStartingNode.
3775 setFocusNavigationStartingNode(focusedElement);
3779 void Document::hoveredElementDidDetach(Element* element)
3781 if (!m_hoveredElement || element != m_hoveredElement)
3784 m_hoveredElement = element->parentElement();
3785 while (m_hoveredElement && !m_hoveredElement->renderer())
3786 m_hoveredElement = m_hoveredElement->parentElement();
3788 frame()->eventHandler().scheduleHoverStateUpdate();
3791 void Document::elementInActiveChainDidDetach(Element* element)
3793 if (!m_activeElement || element != m_activeElement)
3796 m_activeElement = element->parentElement();
3797 while (m_activeElement && !m_activeElement->renderer())
3798 m_activeElement = m_activeElement->parentElement();
3801 #if ENABLE(DASHBOARD_SUPPORT)
3803 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3805 return m_annotatedRegions;
3808 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3810 m_annotatedRegions = regions;
3811 setAnnotatedRegionsDirty(false);
3816 bool Document::setFocusedElement(Element* element, FocusDirection direction, FocusRemovalEventsMode eventsMode)
3818 RefPtr<Element> newFocusedElement = element;
3819 // Make sure newFocusedElement is actually in this document
3820 if (newFocusedElement && (&newFocusedElement->document() != this))
3823 if (m_focusedElement == newFocusedElement)
3826 if (pageCacheState() != NotInPageCache)
3829 bool focusChangeBlocked = false;
3830 RefPtr<Element> oldFocusedElement = WTFMove(m_focusedElement);
3832 // Remove focus from the existing focus node (if any)
3833 if (oldFocusedElement) {
3834 oldFocusedElement->setFocus(false);
3835 setFocusNavigationStartingNode(nullptr);
3837 if (eventsMode == FocusRemovalEventsMode::Dispatch) {
3838 // Dispatch a change event for form control elements that have been edited.
3839 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3840 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3841 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3842 formControlElement.dispatchFormControlChangeEvent();
3845 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3846 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3848 if (m_focusedElement) {
3849 // handler shifted focus
3850 focusChangeBlocked = true;
3851 newFocusedElement = nullptr;
3854 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3855 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3856 // on it, probably when <rdar://problem/8503958> is resolved.
3857 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3859 if (m_focusedElement) {
3860 // handler shifted focus
3861 focusChangeBlocked = true;
3862 newFocusedElement = nullptr;
3865 // Match the order in HTMLTextFormControlElement::dispatchBlurEvent.
3866 if (is<HTMLInputElement>(*oldFocusedElement))
3867 downcast<HTMLInputElement>(*oldFocusedElement).endEditing();
3869 page()->chrome().client().elementDidBlur(*oldFocusedElement);
3870 ASSERT(!m_focusedElement);
3873 if (oldFocusedElement->isRootEditableElement())
3874 frame()->editor().didEndEditing();
3877 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3878 oldWidget->setFocus(false);
3880 view()->setFocus(false);
3883 if (is<HTMLInputElement>(oldFocusedElement)) {
3884 // HTMLInputElement::didBlur just scrolls text fields back to the beginning.
3885 // FIXME: This could be done asynchronusly.
3886 // Updating style may dispatch events due to PostResolutionCallback
3887 if (eventsMode == FocusRemovalEventsMode::Dispatch)
3888 updateStyleIfNeeded();
3889 downcast<HTMLInputElement>(*oldFocusedElement).didBlur();
3893 if (newFocusedElement && newFocusedElement->isFocusable()) {
3894 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3895 // delegate blocks focus change
3896 focusChangeBlocked = true;
3897 goto SetFocusedNodeDone;
3899 // Set focus on the new node
3900 m_focusedElement = newFocusedElement;
3901 setFocusNavigationStartingNode(m_focusedElement.get());
3903 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3904 m_focusedElement->dispatchFocusEvent(oldFocusedElement.copyRef(), direction);
3906 if (m_focusedElement != newFocusedElement) {
3907 // handler shifted focus
3908 focusChangeBlocked = true;
3909 goto SetFocusedNodeDone;
3912 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.copyRef()); // DOM level 3 bubbling focus event.
3914 if (m_focusedElement != newFocusedElement) {
3915 // handler shifted focus
3916 focusChangeBlocked = true;
3917 goto SetFocusedNodeDone;
3920 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3921 // on it, probably when <rdar://problem/8503958> is m.
3922 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement.copyRef()); // DOM level 2 for compatibility.
3924 if (m_focusedElement != newFocusedElement) {
3925 // handler shifted focus
3926 focusChangeBlocked = true;
3927 goto SetFocusedNodeDone;
3930 m_focusedElement->setFocus(true);
3932 // The setFocus call triggers a blur and a focus event. Event handlers could cause the focused element to be cleared.
3933 if (m_focusedElement != newFocusedElement) {
3934 // handler shifted focus
3935 focusChangeBlocked = true;
3936 goto SetFocusedNodeDone;
3939 if (m_focusedElement->isRootEditableElement())
3940 frame()->editor().didBeginEditing();
3942 // eww, I suck. set the qt focus correctly
3943 // ### find a better place in the code for this
3945 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3947 // Make sure a widget has the right size before giving it focus.
3948 // Otherwise, we are testing edge cases of the Widget code.
3949 // Specifically, in WebCore this does not work well for text fields.
3951 // Re-get the widget in case updating the layout changed things.
3952 focusWidget = widgetForElement(m_focusedElement.get());
3955 focusWidget->setFocus(true);
3957 view()->setFocus(true);
3961 if (!focusChangeBlocked && m_focusedElement) {
3962 // Create the AXObject cache in a focus change because GTK relies on it.
3963 if (AXObjectCache* cache = axObjectCache())
3964 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3967 if (!focusChangeBlocked && page())
3968 page()->chrome().focusedElementChanged(m_focusedElement.get());
3971 // Updating style may dispatch events due to PostResolutionCallback
3972 // FIXME: Why is synchronous style update needed here at all?
3973 if (eventsMode == FocusRemovalEventsMode::Dispatch)
3974 updateStyleIfNeeded();
3975 return !focusChangeBlocked;
3978 static bool shouldResetFocusNavigationStartingNode(Node& node)
3980 // Setting focus navigation starting node to the following nodes means that we should start
3981 // the search from the beginning of the document.
3982 return is<HTMLHtmlElement>(node) || is<HTMLDocument>(node);
3985 void Document::setFocusNavigationStartingNode(Node* node)
3990 m_focusNavigationStartingNodeIsRemoved = false;
3991 if (!node || shouldResetFocusNavigationStartingNode(*node)) {
3992 m_focusNavigationStartingNode = nullptr;
3996 m_focusNavigationStartingNode = node;
3999 Element* Document::focusNavigationStartingNode(FocusDirection direction) const
4001 if (m_focusedElement) {
4002 if (!m_focusNavigationStartingNode || !m_focusNavigationStartingNode->isDescendantOf(m_focusedElement.get()))
4003 return m_focusedElement.get();
4006 if (!m_focusNavigationStartingNode)
4009 Node* node = m_focusNavigationStartingNode.get();
4011 // When the node was removed from the document tree. This case is not specified in the spec:
4012 // https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation-starting-point
4013 // Current behaivor is to move the sequential navigation node to / after (based on the focus direction)
4014 // the previous sibling of the removed node.
4015 if (m_focusNavigationStartingNodeIsRemoved) {
4016 Node* nextNode = NodeTraversal::next(*node);
4019 if (direction == FocusDirectionForward)
4020 return ElementTraversal::previous(*nextNode);
4021 if (is<Element>(*nextNode))
4022 return downcast<Element>(nextNode);
4023 return ElementTraversal::next(*nextNode);
4026 if (is<Element>(*node))
4027 return downcast<Element>(node);
4028 if (Element* elementBeforeNextFocusableElement = direction == FocusDirectionForward ? ElementTraversal::previous(*node) : ElementTraversal::next(*node))
4029 return elementBeforeNextFocusableElement;
4030 return node->parentOrShadowHostElement();
4033 void Document::setCSSTarget(Element* targetNode)
4036 m_cssTarget->invalidateStyleForSubtree();
4037 m_cssTarget = targetNode;
4039 targetNode->invalidateStyleForSubtree();
4042 void Document::registerNodeListForInvalidation(LiveNodeList& list)
4044 m_nodeListAndCollectionCounts[list.invalidationType()]++;
4045 if (!list.isRootedAtDocument())
4047 ASSERT(!list.isRegisteredForInvalidationAtDocument());
4048 list.setRegisteredForInvalidationAtDocument(true);
4049 m_listsInvalidatedAtDocument.add(&list);
4052 void Document::unregisterNodeListForInvalidation(LiveNodeList& list)
4054 m_nodeListAndCollectionCounts[list.invalidationType()]--;
4055 if (!list.isRegisteredForInvalidationAtDocument())
4058 list.setRegisteredForInvalidationAtDocument(false);
4059 ASSERT(m_listsInvalidatedAtDocument.contains(&list));
4060 m_listsInvalidatedAtDocument.remove(&list);
4063 void Document::registerCollection(HTMLCollection& collection)
4065 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
4066 if (collection.isRootedAtDocument())
4067 m_collectionsInvalidatedAtDocument.add(&collection);
4070 void Document::unregisterCollection(HTMLCollection& collection)
4072 ASSERT(m_nodeListAndCollectionCounts[collection.invalidationType()]);
4073 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
4074 if (!collection.isRootedAtDocument())
4077 m_collectionsInvalidatedAtDocument.remove(&collection);
4080 void Document::collectionCachedIdNameMap(const HTMLCollection& collection)
4082 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
4083 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
4086 void Document::collectionWillClearIdNameMap(const HTMLCollection& collection)
4088 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
4089 ASSERT(m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]);
4090 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
4093 void Document::attachNodeIterator(NodeIterator* ni)
4095 m_nodeIterators.add(ni);
4098 void Document::detachNodeIterator(NodeIterator* ni)
4100 // The node iterator can be detached without having been attached if its root node didn't have a document
4101 // when the iterator was created, but has it now.
4102 m_nodeIterators.remove(ni);
4105 void Document::moveNodeIteratorsToNewDocumentSlowCase(Node& node, Document& newDocument)
4107 ASSERT(!m_nodeIterators.isEmpty());
4108 for (auto* it : copyToVector(m_nodeIterators)) {
4109 if (&it->root() == &node) {
4110 detachNodeIterator(it);
4111 newDocument.attachNodeIterator(it);
4116 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
4118 for (auto* range : m_ranges)
4119 range->nodeChildrenChanged(container);
4122 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
4124 ASSERT(!NoEventDispatchAssertion::InMainThread::isEventAllowed());
4126 removeFocusedNodeOfSubtree(container, true /* amongChildrenOnly */);
4127 removeFocusNavigationNodeOfSubtree(container, true /* amongChildrenOnly */);
4129 #if ENABLE(FULLSCREEN_API)
4130 removeFullScreenElementOfSubtree(container, true /* amongChildrenOnly */);
4133 for (auto* range : m_ranges)
4134 range->nodeChildrenWillBeRemoved(container);
4136 for (auto* it : m_nodeIterators) {
4137 for (Node* n = container.firstChild(); n; n = n->nextSibling())
4138 it->nodeWillBeRemoved(*n);
4141 if (RefPtr<Frame> frame = this->frame()) {
4142 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
4143 frame->eventHandler().nodeWillBeRemoved(*n);
4144 frame->selection().nodeWillBeRemoved(*n);
4145 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
4149 if (m_markers->hasMarkers()) {
4150 for (Text* textNode = TextNodeTraversal::firstChild(container); textNode; textNode = TextNodeTraversal::nextSibling(*textNode))
4151 m_markers->removeMarkers(textNode);
4155 void Document::nodeWillBeRemoved(Node& node)
4157 ASSERT(!NoEventDispatchAssertion::InMainThread::isEventAllowed());
4159 removeFocusedNodeOfSubtree(node);
4160 removeFocusNavigationNodeOfSubtree(node);
4162 #if ENABLE(FULLSCREEN_API)
4163 removeFullScreenElementOfSubtree(node);
4166 for (auto* it : m_nodeIterators)
4167 it->nodeWillBeRemoved(node);
4169 for (auto* range : m_ranges)
4170 range->nodeWillBeRemoved(node);
4172 if (RefPtr<Frame> frame = this->frame()) {
4173 frame->eventHandler().nodeWillBeRemoved(node);
4174 frame->selection().nodeWillBeRemoved(node);
4175 frame->page()->dragCaretController().nodeWillBeRemoved(node);
4179 m_markers->removeMarkers(&node);
4182 static Node* fallbackFocusNavigationStartingNodeAfterRemoval(Node& node)
4184 return node.previousSibling() ? node.previousSibling() : node.parentNode();
4187 void Document::removeFocusNavigationNodeOfSubtree(Node& node, bool amongChildrenOnly)
4189 if (!m_focusNavigationStartingNode)
4192 if (isNodeInSubtree(*m_focusNavigationStartingNode, node, amongChildrenOnly)) {
4193 m_focusNavigationStartingNode = amongChildrenOnly ? &node : fallbackFocusNavigationStartingNodeAfterRemoval(node);
4194 m_focusNavigationStartingNodeIsRemoved = true;
4198 void Document::textInserted(Node* text, unsigned offset, unsigned length)
4200 if (!m_ranges.isEmpty()) {
4201 for (auto* range : m_ranges)
4202 range->textInserted(text, offset, length);
4205 // Update the markers for spelling and grammar checking.
4206 m_markers->shiftMarkers(text, offset, length);
4209 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
4211 if (!m_ranges.isEmpty()) {
4212 for (auto* range : m_ranges)
4213 range->textRemoved(text, offset, length);
4216 // Update the markers for spelling and grammar checking.
4217 m_markers->removeMarkers(text, offset, length);
4218 m_markers->shiftMarkers(text, offset + length, 0 - length);
4221 void Document::textNodesMerged(Text* oldNode, unsigned offset)
4223 if (!m_ranges.isEmpty()) {
4224 NodeWithIndex oldNodeWithIndex(oldNode);
4225 for (auto* range : m_ranges)
4226 range->textNodesMerged(oldNodeWithIndex, offset);
4229 // FIXME: This should update markers for spelling and grammar checking.
4232 void Document::textNodeSplit(Text* oldNode)
4234 for (auto* range : m_ranges)
4235 range->textNodeSplit(oldNode);
4237 // FIXME: This should update markers for spelling and grammar checking.
4240 void Document::createDOMWindow()
4243 ASSERT(!m_domWindow);
4245 m_domWindow = DOMWindow::create(*this);
4247 ASSERT(m_domWindow->document() == this);
4248 ASSERT(m_domWindow->frame() == m_frame);
4251 void Document::takeDOMWindowFrom(Document* document)
4254 ASSERT(!m_domWindow);
4255 ASSERT(document->m_domWindow);
4256 // A valid DOMWindow is needed by CachedFrame for its documents.
4257 ASSERT(pageCacheState() == NotInPageCache);
4259 m_domWindow = WTFMove(document->m_domWindow);
4260 m_domWindow->didSecureTransitionTo(*this);
4262 ASSERT(m_domWindow->document() == this);
4263 ASSERT(m_domWindow->frame() == m_frame);
4266 Document& Document::contextDocument() const
4268 if (m_contextDocument)
4269 return *m_contextDocument.get();
4270 return const_cast<Document&>(*this);
4273 void Document::setAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue, DOMWrapperWorld& isolatedWorld)
4275 setAttributeEventListener(eventType, JSLazyEventListener::create(*this, attributeName, attributeValue), isolatedWorld);
4278 void Document::setWindowAttributeEventListener(const AtomicString& eventType, RefPtr<EventListener>&& listener, DOMWrapperWorld& isolatedWorld)
4282 m_domWindow->setAttributeEventListener(eventType, WTFMove(listener), isolatedWorld);
4285 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue, DOMWrapperWorld& isolatedWorld)