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-2019 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"
32 #include "ApplicationStateChangeListener.h"
34 #include "BeforeUnloadEvent.h"
35 #include "CDATASection.h"
36 #include "CSSAnimationController.h"
37 #include "CSSFontSelector.h"
38 #include "CSSStyleDeclaration.h"
39 #include "CSSStyleSheet.h"
40 #include "CachedCSSStyleSheet.h"
41 #include "CachedFrame.h"
42 #include "CachedResourceLoader.h"
43 #include "CanvasRenderingContext2D.h"
45 #include "ChromeClient.h"
48 #include "ComposedTreeIterator.h"
49 #include "CompositionEvent.h"
50 #include "ConstantPropertyMap.h"
51 #include "ContentSecurityPolicy.h"
52 #include "CookieJar.h"
53 #include "CustomElementReactionQueue.h"
54 #include "CustomElementRegistry.h"
55 #include "CustomEvent.h"
56 #include "CustomHeaderFields.h"
57 #include "DOMImplementation.h"
58 #include "DOMWindow.h"
59 #include "DateComponents.h"
60 #include "DebugPageOverlays.h"
61 #include "DeprecatedGlobalSettings.h"
62 #include "DocumentLoader.h"
63 #include "DocumentMarkerController.h"
64 #include "DocumentSharedObjectPool.h"
65 #include "DocumentTimeline.h"
66 #include "DocumentType.h"
69 #include "ElementIterator.h"
70 #include "EventHandler.h"
71 #include "ExtensionStyleSheets.h"
72 #include "FocusController.h"
73 #include "FocusEvent.h"
74 #include "FontFaceSet.h"
75 #include "FormController.h"
77 #include "FrameLoader.h"
78 #include "FrameLoaderClient.h"
79 #include "FrameView.h"
80 #include "FullscreenManager.h"
81 #include "GenericCachedHTMLCollection.h"
82 #include "HTMLAllCollection.h"
83 #include "HTMLAnchorElement.h"
84 #include "HTMLAttachmentElement.h"
85 #include "HTMLBaseElement.h"
86 #include "HTMLBodyElement.h"
87 #include "HTMLCanvasElement.h"
88 #include "HTMLDocument.h"
89 #include "HTMLElementFactory.h"
90 #include "HTMLFormControlElement.h"
91 #include "HTMLFrameOwnerElement.h"
92 #include "HTMLFrameSetElement.h"
93 #include "HTMLHeadElement.h"
94 #include "HTMLHtmlElement.h"
95 #include "HTMLImageElement.h"
96 #include "HTMLInputElement.h"
97 #include "HTMLLinkElement.h"
98 #include "HTMLMediaElement.h"
99 #include "HTMLNameCollection.h"
100 #include "HTMLParserIdioms.h"
101 #include "HTMLPictureElement.h"
102 #include "HTMLPlugInElement.h"
103 #include "HTMLScriptElement.h"
104 #include "HTMLStyleElement.h"
105 #include "HTMLTitleElement.h"
106 #include "HTMLUnknownElement.h"
107 #include "HTTPHeaderNames.h"
108 #include "HTTPParsers.h"
109 #include "HashChangeEvent.h"
111 #include "HitTestResult.h"
112 #include "IdleCallbackController.h"
113 #include "ImageBitmapRenderingContext.h"
114 #include "ImageLoader.h"
115 #include "InspectorInstrumentation.h"
116 #include "IntersectionObserver.h"
117 #include "JSCustomElementInterface.h"
118 #include "JSLazyEventListener.h"
119 #include "KeyboardEvent.h"
120 #include "KeyframeEffect.h"
121 #include "LayoutDisallowedScope.h"
122 #include "LegacySchemeRegistry.h"
123 #include "LibWebRTCProvider.h"
124 #include "LoaderStrategy.h"
126 #include "MediaCanStartListener.h"
127 #include "MediaProducer.h"
128 #include "MediaQueryList.h"
129 #include "MediaQueryMatcher.h"
130 #include "MediaStream.h"
131 #include "MessageEvent.h"
132 #include "Microtasks.h"
133 #include "MouseEventWithHitTestResults.h"
134 #include "MutationEvent.h"
135 #include "NameNodeList.h"
136 #include "NavigationDisabler.h"
137 #include "NavigationScheduler.h"
138 #include "NestingLevelIncrementer.h"
139 #include "NodeIterator.h"
140 #include "NodeRareData.h"
141 #include "NodeWithIndex.h"
142 #include "OverflowEvent.h"
143 #include "PageConsoleClient.h"
144 #include "PageGroup.h"
145 #include "PageTransitionEvent.h"
146 #include "PaintWorkletGlobalScope.h"
147 #include "PlatformLocale.h"
148 #include "PlatformMediaSessionManager.h"
149 #include "PlatformScreen.h"
150 #include "PlatformStrategies.h"
151 #include "PlugInsResources.h"
152 #include "PluginDocument.h"
153 #include "PointerLockController.h"
154 #include "PolicyChecker.h"
155 #include "PopStateEvent.h"
156 #include "ProcessingInstruction.h"
157 #include "PublicSuffix.h"
159 #include "RealtimeMediaSourceCenter.h"
160 #include "RenderChildIterator.h"
161 #include "RenderInline.h"
162 #include "RenderLayerCompositor.h"
163 #include "RenderLineBreak.h"
164 #include "RenderTreeUpdater.h"
165 #include "RenderView.h"
166 #include "RenderWidget.h"
167 #include "RequestAnimationFrameCallback.h"
168 #include "ResizeObserver.h"
169 #include "ResourceLoadObserver.h"
170 #include "RuntimeApplicationChecks.h"
171 #include "RuntimeEnabledFeatures.h"
172 #include "SVGDocumentExtensions.h"
173 #include "SVGElement.h"
174 #include "SVGElementFactory.h"
175 #include "SVGNames.h"
176 #include "SVGSVGElement.h"
177 #include "SVGTitleElement.h"
178 #include "SVGUseElement.h"
179 #include "SVGZoomEvent.h"
180 #include "SWClientConnection.h"
181 #include "ScopedEventQueue.h"
182 #include "ScriptController.h"
183 #include "ScriptDisallowedScope.h"
184 #include "ScriptModuleLoader.h"
185 #include "ScriptRunner.h"
186 #include "ScriptSourceCode.h"
187 #include "ScriptState.h"
188 #include "ScriptedAnimationController.h"
189 #include "ScrollbarTheme.h"
190 #include "ScrollingCoordinator.h"
191 #include "SecurityOrigin.h"
192 #include "SecurityOriginData.h"
193 #include "SecurityOriginPolicy.h"
194 #include "SecurityPolicy.h"
195 #include "SegmentedString.h"
196 #include "SelectorQuery.h"
197 #include "ServiceWorkerClientData.h"
198 #include "ServiceWorkerContainer.h"
199 #include "ServiceWorkerProvider.h"
200 #include "Settings.h"
201 #include "ShadowRoot.h"
202 #include "SocketProvider.h"
203 #include "StorageEvent.h"
204 #include "StringCallback.h"
205 #include "StyleColor.h"
206 #include "StyleProperties.h"
207 #include "StyleResolveForDocument.h"
208 #include "StyleResolver.h"
209 #include "StyleScope.h"
210 #include "StyleSheetContents.h"
211 #include "StyleSheetList.h"
212 #include "StyleTreeResolver.h"
213 #include "SubresourceLoader.h"
214 #include "TextAutoSizing.h"
215 #include "TextEvent.h"
216 #include "TextManipulationController.h"
217 #include "TextNodeTraversal.h"
218 #include "TouchAction.h"
219 #include "TransformSource.h"
220 #include "TreeWalker.h"
221 #include "UndoManager.h"
222 #include "UserGestureIndicator.h"
223 #include "ValidationMessageClient.h"
224 #include "VisibilityChangeClient.h"
225 #include "VisitedLinkState.h"
226 #include "WebAnimation.h"
227 #include "WheelEvent.h"
228 #include "WindowEventLoop.h"
229 #include "WindowFeatures.h"
231 #include "XMLDocument.h"
232 #include "XMLDocumentParser.h"
233 #include "XMLNSNames.h"
234 #include "XMLNames.h"
235 #include "XPathEvaluator.h"
236 #include "XPathExpression.h"
237 #include "XPathNSResolver.h"
238 #include "XPathResult.h"
239 #include <JavaScriptCore/ConsoleMessage.h>
240 #include <JavaScriptCore/RegularExpression.h>
241 #include <JavaScriptCore/ScriptCallStack.h>
242 #include <JavaScriptCore/VM.h>
244 #include <wtf/IsoMallocInlines.h>
245 #include <wtf/Language.h>
246 #include <wtf/NeverDestroyed.h>
247 #include <wtf/SetForScope.h>
248 #include <wtf/SystemTracing.h>
249 #include <wtf/UUID.h>
250 #include <wtf/text/StringBuffer.h>
251 #include <wtf/text/TextStream.h>
253 #if ENABLE(DEVICE_ORIENTATION)
254 #include "DeviceMotionEvent.h"
255 #include "DeviceOrientationAndMotionAccessController.h"
256 #include "DeviceOrientationEvent.h"
259 #if ENABLE(FULLSCREEN_API)
260 #include "RenderFullScreen.h"
263 #if ENABLE(INDEXED_DATABASE)
264 #include "IDBConnectionProxy.h"
265 #include "IDBOpenDBRequest.h"
268 #if PLATFORM(IOS_FAMILY)
269 #include "ContentChangeObserver.h"
270 #include "CSSFontSelector.h"
271 #include "DOMTimerHoldingTank.h"
272 #include "DeviceMotionClientIOS.h"
273 #include "DeviceMotionController.h"
274 #include "DeviceOrientationClientIOS.h"
275 #include "DeviceOrientationController.h"
276 #include "Geolocation.h"
277 #include "Navigator.h"
278 #include "NavigatorGeolocation.h"
281 #if ENABLE(IOS_GESTURE_EVENTS)
282 #include "GestureEvent.h"
286 #include "MathMLElement.h"
287 #include "MathMLElementFactory.h"
288 #include "MathMLNames.h"
291 #if ENABLE(MEDIA_SESSION)
292 #include "MediaSession.h"
296 #include "QuickLook.h"
299 #if ENABLE(TOUCH_EVENTS)
300 #include "TouchEvent.h"
303 #if ENABLE(VIDEO_TRACK)
304 #include "CaptionUserPreferences.h"
307 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
308 #include "MediaPlaybackTargetClient.h"
312 #include "XSLTProcessor.h"
316 #include "WebGLRenderingContext.h"
319 #include "WebGL2RenderingContext.h"
322 #include "GPUCanvasContext.h"
325 #if ENABLE(POINTER_EVENTS)
326 #include "PointerCaptureController.h"
329 #if ENABLE(PICTURE_IN_PICTURE_API)
330 #include "HTMLVideoElement.h"
335 WTF_MAKE_ISO_ALLOCATED_IMPL(Document);
337 using namespace HTMLNames;
339 using namespace WTF::Unicode;
341 static const unsigned cMaxWriteRecursionDepth = 21;
342 bool Document::hasEverCreatedAnAXObjectCache = false;
343 static const Seconds maxIntervalForUserGestureForwardingAfterMediaFinishesPlaying { 1_s };
345 struct FrameFlatteningLayoutDisallower {
346 FrameFlatteningLayoutDisallower(FrameView& frameView)
347 : m_frameView(frameView)
348 , m_disallowLayout(frameView.effectiveFrameFlattening() != FrameFlattening::Disabled)
350 if (m_disallowLayout)
351 m_frameView.startDisallowingLayout();
354 ~FrameFlatteningLayoutDisallower()
356 if (m_disallowLayout)
357 m_frameView.endDisallowingLayout();
361 FrameView& m_frameView;
362 bool m_disallowLayout { false };
365 #if ENABLE(INTERSECTION_OBSERVER)
366 static const Seconds intersectionObserversInitialUpdateDelay { 2000_ms };
369 // DOM Level 2 says (letters added):
371 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
372 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
373 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
374 // 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.
375 // 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.
376 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
377 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
378 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
379 // i) Characters ':' and '_' are allowed as name-start characters.
380 // j) Characters '-' and '.' are allowed as name characters.
382 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
384 static inline bool isValidNameStart(UChar32 c)
387 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
391 if (c == ':' || c == '_')
394 // rules (a) and (f) above
395 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)))
399 if (c >= 0xF900 && c < 0xFFFE)
403 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
404 if (type == U_DT_FONT || type == U_DT_COMPAT)
410 static inline bool isValidNamePart(UChar32 c)
412 // rules (a), (e), and (i) above
413 if (isValidNameStart(c))
416 // rules (g) and (h) above
417 if (c == 0x00B7 || c == 0x0387)
421 if (c == '-' || c == '.')
424 // rules (b) and (f) above
425 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
429 if (c >= 0xF900 && c < 0xFFFE)
433 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
434 if (type == U_DT_FONT || type == U_DT_COMPAT)
440 static Widget* widgetForElement(Element* focusedElement)
444 auto* renderer = focusedElement->renderer();
445 if (!is<RenderWidget>(renderer))
447 return downcast<RenderWidget>(*renderer).widget();
450 static bool acceptsEditingFocus(const Element& element)
452 ASSERT(element.hasEditableStyle());
454 auto* root = element.rootEditableElement();
455 Frame* frame = element.document().frame();
459 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
462 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
464 // targetFrame can be 0 when we're trying to navigate a top-level frame
465 // that has a 0 opener.
469 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
470 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
471 Document* ancestorDocument = ancestorFrame->document();
472 // FIXME: Should be an ASSERT? Frames should alway have documents.
473 if (!ancestorDocument)
476 const SecurityOrigin& ancestorSecurityOrigin = ancestorDocument->securityOrigin();
477 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
480 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
481 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
482 // something more general instead?
483 if (isLocalActiveOrigin && ancestorSecurityOrigin.isLocal())
490 static void printNavigationErrorMessage(Frame& frame, const URL& activeURL, const char* reason)
492 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
494 // FIXME: should we print to the console of the document performing the navigation instead?
495 frame.document()->domWindow()->printErrorMessage(message);
498 uint64_t Document::s_globalTreeVersion = 0;
500 auto Document::allDocumentsMap() -> DocumentsMap&
502 static NeverDestroyed<DocumentsMap> documents;
506 auto Document::allDocuments() -> DocumentsMap::ValuesIteratorRange
508 return allDocumentsMap().values();
511 static inline int currentOrientation(Frame* frame)
513 #if ENABLE(ORIENTATION_EVENTS)
515 return frame->orientation();
522 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
523 : ContainerNode(*this, CreateDocument)
525 , FrameDestructionObserver(frame)
526 #if ENABLE(IOS_TOUCH_EVENTS)
527 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
529 , m_settings(frame ? Ref<Settings>(frame->settings()) : Settings::create(nullptr))
530 , m_quirks(makeUniqueRef<Quirks>(*this))
531 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
532 , m_domTreeVersion(++s_globalTreeVersion)
533 , m_styleScope(makeUnique<Style::Scope>(*this))
534 , m_extensionStyleSheets(makeUnique<ExtensionStyleSheets>(*this))
535 , m_visitedLinkState(makeUnique<VisitedLinkState>(*this))
536 , m_markers(makeUnique<DocumentMarkerController>(*this))
537 , m_styleRecalcTimer([this] { updateStyleIfNeeded(); })
538 , m_documentCreationTime(MonotonicTime::now())
539 , m_scriptRunner(makeUnique<ScriptRunner>(*this))
540 , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this))
542 , m_applyPendingXSLTransformsTimer(*this, &Document::applyPendingXSLTransformsTimerFired)
544 , m_xmlVersion("1.0"_s)
545 , m_constantPropertyMap(makeUnique<ConstantPropertyMap>(*this))
546 , m_documentClasses(documentClasses)
547 , m_eventQueue(*this)
548 #if ENABLE(FULLSCREEN_API)
549 , m_fullscreenManager { makeUniqueRef<FullscreenManager>(*this) }
551 #if ENABLE(INTERSECTION_OBSERVER)
552 , m_intersectionObserversNotifyTimer(*this, &Document::notifyIntersectionObserversTimerFired)
553 , m_intersectionObserversInitialUpdateTimer(*this, &Document::scheduleTimedRenderingUpdate)
555 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
556 #if PLATFORM(IOS_FAMILY) && ENABLE(DEVICE_ORIENTATION)
557 , m_deviceMotionClient(makeUnique<DeviceMotionClientIOS>())
558 , m_deviceMotionController(makeUnique<DeviceMotionController>(*m_deviceMotionClient))
559 , m_deviceOrientationClient(makeUnique<DeviceOrientationClientIOS>())
560 , m_deviceOrientationController(makeUnique<DeviceOrientationController>(*m_deviceOrientationClient))
562 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
563 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
564 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
565 , m_fontSelector(CSSFontSelector::create(*this))
566 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
567 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
568 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
569 , m_isSynthesized(constructionFlags & Synthesized)
570 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
571 , m_orientationNotifier(currentOrientation(frame))
572 , m_identifier(DocumentIdentifier::generate())
573 , m_undoManager(UndoManager::create(*this))
575 auto addResult = allDocumentsMap().add(m_identifier, this);
576 ASSERT_UNUSED(addResult, addResult.isNewEntry);
578 // We depend on the url getting immediately set in subframes, but we
579 // also depend on the url NOT getting immediately set in opened windows.
580 // See fast/dom/early-frame-url.html
581 // and fast/dom/location-new-window-no-crash.html, respectively.
582 // FIXME: Can/should we unify this behavior?
583 if ((frame && frame->ownerElement()) || !url.isEmpty())
586 m_cachedResourceLoader->setDocument(this);
589 resetVisitedLinkColor();
590 resetActiveLinkColor();
592 initSecurityContext();
595 m_fontSelector->registerForInvalidationCallbacks(*this);
597 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
598 nodeListAndCollectionCount = 0;
600 InspectorInstrumentation::addEventListenersToNode(*this);
603 Ref<Document> Document::create(Document& contextDocument)
605 auto document = adoptRef(*new Document(nullptr, URL()));
606 document->setContextDocument(contextDocument);
607 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
611 Ref<Document> Document::createNonRenderedPlaceholder(Frame& frame, const URL& url)
613 return adoptRef(*new Document(&frame, url, DefaultDocumentClass, NonRenderedPlaceholder));
616 Document::~Document()
619 m_logger->removeObserver(*this);
621 ASSERT(allDocumentsMap().contains(m_identifier));
622 allDocumentsMap().remove(m_identifier);
623 // We need to remove from the contexts map very early in the destructor so that calling postTask() on this Document from another thread is safe.
624 removeFromContextsMap();
626 ASSERT(!renderView());
627 ASSERT(m_backForwardCacheState != InBackForwardCache);
628 ASSERT(m_ranges.isEmpty());
629 ASSERT(!m_parentTreeScope);
630 ASSERT(!m_disabledFieldsetElementsCount);
631 ASSERT(m_inDocumentShadowRoots.isEmpty());
633 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
634 m_deviceMotionClient->deviceMotionControllerDestroyed();
635 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
638 if (m_templateDocument)
639 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
641 // FIXME: Should we reset m_domWindow when we detach from the Frame?
643 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
645 m_scriptRunner = nullptr;
646 m_moduleLoader = nullptr;
648 removeAllEventListeners();
650 // Currently we believe that Document can never outlive the parser.
651 // Although the Document may be replaced synchronously, DocumentParsers
652 // generally keep at least one reference to an Element which would in turn
653 // has a reference to the Document. If you hit this ASSERT, then that
654 // assumption is wrong. DocumentParser::detach() should ensure that even
655 // if the DocumentParser outlives the Document it won't cause badness.
656 ASSERT(!m_parser || m_parser->refCount() == 1);
659 if (this == &topDocument())
660 clearAXObjectCache();
664 if (m_styleSheetList)
665 m_styleSheetList->detach();
667 extensionStyleSheets().detachFromDocument();
669 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
670 m_fontSelector->clearDocument();
671 m_fontSelector->unregisterForInvalidationCallbacks(*this);
673 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
674 // load the initial empty document and the SVGDocument with the same DocumentLoader).
675 if (m_cachedResourceLoader->document() == this)
676 m_cachedResourceLoader->setDocument(nullptr);
679 stopAllMediaPlayback();
682 // We must call clearRareData() here since a Document class inherits TreeScope
683 // as well as Node. See a comment on TreeScope.h for the reason.
687 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_listsInvalidatedAtDocument.isEmpty());
688 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_collectionsInvalidatedAtDocument.isEmpty());
689 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_svgUseElements.isEmpty());
691 for (unsigned count : m_nodeListAndCollectionCounts)
692 ASSERT_UNUSED(count, !count);
695 void Document::removedLastRef()
697 ASSERT(!m_deletionHasBegun);
698 if (m_referencingNodeCount) {
699 // Node::removedLastRef doesn't set refCount() to zero because it's not observable.
700 // But we need to remember that our refCount reached zero in subsequent calls to decrementReferencingNodeCount().
701 m_refCountAndParentBit = 0;
703 // If removing a child removes the last node reference, we don't want the scope to be destroyed
704 // until after removeDetachedChildren returns, so we protect ourselves.
705 incrementReferencingNodeCount();
707 RELEASE_ASSERT(!hasLivingRenderTree());
708 // We must make sure not to be retaining any of our children through
709 // these extra pointers or we will create a reference cycle.
710 m_focusedElement = nullptr;
711 m_hoveredElement = nullptr;
712 m_activeElement = nullptr;
713 m_titleElement = nullptr;
714 m_documentElement = nullptr;
715 m_focusNavigationStartingNode = nullptr;
716 m_userActionElements.clear();
717 #if ENABLE(FULLSCREEN_API)
718 m_fullscreenManager->clear();
720 m_associatedFormControls.clear();
722 m_fontSelector->clearDocument();
723 m_fontSelector->unregisterForInvalidationCallbacks(*this);
727 // removeDetachedChildren() doesn't always unregister IDs,
728 // so tear down scope information up front to avoid having
729 // stale references in the map.
731 destroyTreeScopeData();
732 removeDetachedChildren();
733 m_formController = nullptr;
737 m_cssCanvasElements.clear();
742 // We need to do this right now since selfOnlyDeref() can delete this.
743 m_inRemovedLastRefFunction = false;
745 decrementReferencingNodeCount();
748 m_inRemovedLastRefFunction = false;
749 m_deletionHasBegun = true;
755 void Document::commonTeardown()
758 accessSVGExtensions().pauseAnimations();
760 clearScriptedAnimationController();
763 Element* Document::elementForAccessKey(const String& key)
767 if (!m_accessKeyCache)
768 buildAccessKeyCache();
769 return m_accessKeyCache->get(key);
772 void Document::buildAccessKeyCache()
774 m_accessKeyCache = makeUnique<HashMap<String, Element*, ASCIICaseInsensitiveHash>>([this] {
775 HashMap<String, Element*, ASCIICaseInsensitiveHash> map;
776 for (auto& node : composedTreeDescendants(*this)) {
777 if (!is<Element>(node))
779 auto& element = downcast<Element>(node);
780 auto& key = element.attributeWithoutSynchronization(accesskeyAttr);
783 map.add(key, &element);
789 void Document::invalidateAccessKeyCacheSlowCase()
791 m_accessKeyCache = nullptr;
794 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
796 if (selectorString.isEmpty())
797 return Exception { SyntaxError };
798 if (!m_selectorQueryCache)
799 m_selectorQueryCache = makeUnique<SelectorQueryCache>();
800 return m_selectorQueryCache->add(selectorString, *this);
803 void Document::clearSelectorQueryCache()
805 m_selectorQueryCache = nullptr;
808 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
810 // Do not override existing referrer policy with the "empty string" one as the "empty string" means we should use
811 // the policy defined elsewhere.
812 if (m_referrerPolicy && referrerPolicy == ReferrerPolicy::EmptyString)
815 m_referrerPolicy = referrerPolicy;
818 MediaQueryMatcher& Document::mediaQueryMatcher()
820 if (!m_mediaQueryMatcher)
821 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
822 return *m_mediaQueryMatcher;
825 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
827 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
829 bool wasInQuirksMode = inQuirksMode();
830 m_compatibilityMode = mode;
832 clearSelectorQueryCache();
834 if (inQuirksMode() != wasInQuirksMode) {
835 // All user stylesheets have to reparse using the different mode.
836 extensionStyleSheets().clearPageUserSheet();
837 extensionStyleSheets().invalidateInjectedStyleSheetCache();
841 String Document::compatMode() const
843 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
846 void Document::resetLinkColor()
848 m_linkColor = StyleColor::colorFromKeyword(CSSValueWebkitLink, styleColorOptions(nullptr));
851 void Document::resetVisitedLinkColor()
853 m_visitedLinkColor = StyleColor::colorFromKeyword(CSSValueWebkitLink, styleColorOptions(nullptr) | StyleColor::Options::ForVisitedLink);
856 void Document::resetActiveLinkColor()
858 m_activeLinkColor = StyleColor::colorFromKeyword(CSSValueWebkitActivelink, styleColorOptions(nullptr));
861 DOMImplementation& Document::implementation()
863 if (!m_implementation)
864 m_implementation = makeUnique<DOMImplementation>(*this);
865 return *m_implementation;
868 bool Document::hasManifest() const
870 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
873 DocumentType* Document::doctype() const
875 for (Node* node = firstChild(); node; node = node->nextSibling()) {
876 if (is<DocumentType>(node))
877 return downcast<DocumentType>(node);
882 void Document::childrenChanged(const ChildChange& change)
884 ContainerNode::childrenChanged(change);
886 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
887 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
888 // otherwise, we need to detect the doc type changes before updating the viewport.
889 if (Page* page = this->page())
890 page->chrome().didReceiveDocType(*frame());
892 Element* newDocumentElement = childrenOfType<Element>(*this).first();
893 if (newDocumentElement == m_documentElement)
895 m_documentElement = newDocumentElement;
896 // The root style used for media query matching depends on the document element.
897 styleScope().clearResolver();
900 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
902 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled()
903 || Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
904 return HTMLUnknownElement::create(name, document);
906 auto element = HTMLElement::create(name, document);
907 element->setIsCustomElementUpgradeCandidate();
911 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const AtomString& localName)
913 return createUpgradeCandidateElement(document, QualifiedName { nullAtom(), localName, xhtmlNamespaceURI });
916 static inline bool isValidHTMLElementName(const AtomString& localName)
918 return Document::isValidName(localName);
921 static inline bool isValidHTMLElementName(const QualifiedName& name)
923 return Document::isValidName(name.localName());
926 template<typename NameType>
927 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const NameType& name)
929 auto element = HTMLElementFactory::createKnownElement(name, document);
931 return Ref<Element> { element.releaseNonNull() };
933 if (auto* window = document.domWindow()) {
934 auto* registry = window->customElementRegistry();
935 if (UNLIKELY(registry)) {
936 if (auto* elementInterface = registry->findInterface(name))
937 return elementInterface->constructElementWithFallback(document, name);
941 if (UNLIKELY(!isValidHTMLElementName(name)))
942 return Exception { InvalidCharacterError };
944 return Ref<Element> { createUpgradeCandidateElement(document, name) };
947 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomString& name)
949 if (isHTMLDocument())
950 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
952 if (isXHTMLDocument())
953 return createHTMLElementWithNameValidation(*this, name);
955 if (!isValidName(name))
956 return Exception { InvalidCharacterError };
958 return createElement(QualifiedName(nullAtom(), name, nullAtom()), false);
961 Ref<DocumentFragment> Document::createDocumentFragment()
963 return DocumentFragment::create(document());
966 Ref<Text> Document::createTextNode(const String& data)
968 return Text::create(*this, data);
971 Ref<Comment> Document::createComment(const String& data)
973 return Comment::create(*this, data);
976 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
978 if (isHTMLDocument())
979 return Exception { NotSupportedError };
980 return CDATASection::create(*this, data);
983 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
985 if (!isValidName(target))
986 return Exception { InvalidCharacterError };
988 if (data.contains("?>"))
989 return Exception { InvalidCharacterError };
991 return ProcessingInstruction::create(*this, target, data);
994 Ref<Text> Document::createEditingTextNode(const String& text)
996 return Text::createEditingText(*this, text);
999 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
1001 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
1002 return propertySet->ensureCSSStyleDeclaration();
1005 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
1007 switch (nodeToImport.nodeType()) {
1008 case DOCUMENT_FRAGMENT_NODE:
1009 if (nodeToImport.isShadowRoot())
1014 case CDATA_SECTION_NODE:
1015 case PROCESSING_INSTRUCTION_NODE:
1017 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
1019 case ATTRIBUTE_NODE: {
1020 auto& attribute = downcast<Attr>(nodeToImport);
1021 return Ref<Node> { Attr::create(*this, attribute.qualifiedName(), attribute.value()) };
1023 case DOCUMENT_NODE: // Can't import a document into another document.
1024 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
1028 return Exception { NotSupportedError };
1032 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
1034 EventQueueScope scope;
1036 switch (source.nodeType()) {
1038 return Exception { NotSupportedError };
1039 case ATTRIBUTE_NODE: {
1040 auto& attr = downcast<Attr>(source);
1041 if (auto* element = attr.ownerElement()) {
1042 auto result = element->removeAttributeNode(attr);
1043 if (result.hasException())
1044 return result.releaseException();
1049 if (source.isShadowRoot()) {
1050 // ShadowRoot cannot disconnect itself from the host node.
1051 return Exception { HierarchyRequestError };
1053 if (is<HTMLFrameOwnerElement>(source)) {
1054 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
1055 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
1056 return Exception { HierarchyRequestError };
1058 auto result = source.remove();
1059 if (result.hasException())
1060 return result.releaseException();
1061 RELEASE_ASSERT(!source.isConnected());
1062 RELEASE_ASSERT(!source.parentNode());
1065 source.setTreeScopeRecursively(*this);
1067 return Ref<Node> { source };
1070 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1072 // These checks are from DOM Core Level 2, createElementNS
1073 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1074 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1076 if (qName.prefix() == xmlAtom() && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1079 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1080 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1081 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1082 if (qName.prefix() == xmlnsAtom() || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom()))
1083 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1084 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1087 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1089 return hasValidNamespaceForElements(qName);
1092 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1094 if (auto* window = document.domWindow()) {
1095 auto* registry = window->customElementRegistry();
1096 if (UNLIKELY(registry)) {
1097 if (auto* elementInterface = registry->findInterface(name)) {
1098 auto element = HTMLElement::create(name, document);
1099 element->enqueueToUpgrade(*elementInterface);
1104 // FIXME: Should we also check the equality of prefix between the custom element and name?
1105 return createUpgradeCandidateElement(document, name);
1108 // FIXME: This should really be in a possible ElementFactory class.
1109 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1111 RefPtr<Element> element;
1113 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1114 if (name.namespaceURI() == xhtmlNamespaceURI) {
1115 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1116 if (UNLIKELY(!element))
1117 element = createFallbackHTMLElement(*this, name);
1118 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1119 element = SVGElementFactory::createElement(name, *this, createdByParser);
1121 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1122 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1126 m_sawElementsInKnownNamespaces = true;
1128 element = Element::create(name, document());
1130 // <image> uses imgTag so we need a special rule.
1131 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1133 return element.releaseNonNull();
1136 // https://html.spec.whatwg.org/#valid-custom-element-name
1138 struct UnicodeCodePointRange {
1143 #if !ASSERT_DISABLED
1145 static inline bool operator<(const UnicodeCodePointRange& a, const UnicodeCodePointRange& b)
1147 ASSERT(a.minimum <= a.maximum);
1148 ASSERT(b.minimum <= b.maximum);
1149 return a.maximum < b.minimum;
1154 static inline bool operator<(const UnicodeCodePointRange& a, UChar32 b)
1156 ASSERT(a.minimum <= a.maximum);
1157 return a.maximum < b;
1160 static inline bool operator<(UChar32 a, const UnicodeCodePointRange& b)
1162 ASSERT(b.minimum <= b.maximum);
1163 return a < b.minimum;
1166 static inline bool isPotentialCustomElementNameCharacter(UChar32 character)
1168 static const UnicodeCodePointRange ranges[] = {
1185 { 0x10000, 0xEFFFF },
1188 ASSERT(std::is_sorted(std::begin(ranges), std::end(ranges)));
1189 return std::binary_search(std::begin(ranges), std::end(ranges), character);
1192 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomString& localName)
1194 if (!isASCIILower(localName[0]))
1195 return CustomElementNameValidationStatus::FirstCharacterIsNotLowercaseASCIILetter;
1197 bool containsHyphen = false;
1198 for (auto character : StringView(localName).codePoints()) {
1199 if (isASCIIUpper(character))
1200 return CustomElementNameValidationStatus::ContainsUppercaseASCIILetter;
1201 if (!isPotentialCustomElementNameCharacter(character))
1202 return CustomElementNameValidationStatus::ContainsDisallowedCharacter;
1203 if (character == '-')
1204 containsHyphen = true;
1207 if (!containsHyphen)
1208 return CustomElementNameValidationStatus::ContainsNoHyphen;
1211 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag->localName();
1213 static NeverDestroyed<const AtomString> annotationXmlLocalName("annotation-xml", AtomString::ConstructFromLiteral);
1216 if (localName == SVGNames::color_profileTag->localName()
1217 || localName == SVGNames::font_faceTag->localName()
1218 || localName == SVGNames::font_face_formatTag->localName()
1219 || localName == SVGNames::font_face_nameTag->localName()
1220 || localName == SVGNames::font_face_srcTag->localName()
1221 || localName == SVGNames::font_face_uriTag->localName()
1222 || localName == SVGNames::missing_glyphTag->localName()
1223 || localName == annotationXmlLocalName)
1224 return CustomElementNameValidationStatus::ConflictsWithStandardElementName;
1226 return CustomElementNameValidationStatus::Valid;
1229 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomString& namespaceURI, const String& qualifiedName)
1231 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1232 if (parseResult.hasException())
1233 return parseResult.releaseException();
1234 QualifiedName parsedName { parseResult.releaseReturnValue() };
1235 if (!hasValidNamespaceForElements(parsedName))
1236 return Exception { NamespaceError };
1238 if (parsedName.namespaceURI() == xhtmlNamespaceURI)
1239 return createHTMLElementWithNameValidation(*this, parsedName);
1241 return createElement(parsedName, false);
1244 void Document::setReadyState(ReadyState readyState)
1246 if (readyState == m_readyState)
1249 switch (readyState) {
1251 if (!m_documentTiming.domLoading)
1252 m_documentTiming.domLoading = MonotonicTime::now();
1255 if (!m_documentTiming.domInteractive)
1256 m_documentTiming.domInteractive = MonotonicTime::now();
1259 if (!m_documentTiming.domComplete)
1260 m_documentTiming.domComplete = MonotonicTime::now();
1264 m_readyState = readyState;
1265 dispatchEvent(Event::create(eventNames().readystatechangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
1267 if (settings().suppressesIncrementalRendering())
1268 setVisualUpdatesAllowed(readyState);
1271 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1273 ASSERT(settings().suppressesIncrementalRendering());
1274 switch (readyState) {
1276 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1277 ASSERT(m_visualUpdatesAllowed);
1278 setVisualUpdatesAllowed(false);
1281 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1284 if (m_visualUpdatesSuppressionTimer.isActive()) {
1285 ASSERT(!m_visualUpdatesAllowed);
1287 if (view() && !view()->visualUpdatesAllowedByClient())
1290 setVisualUpdatesAllowed(true);
1292 ASSERT(m_visualUpdatesAllowed);
1297 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1299 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1302 m_visualUpdatesAllowed = visualUpdatesAllowed;
1304 if (visualUpdatesAllowed)
1305 m_visualUpdatesSuppressionTimer.stop();
1307 m_visualUpdatesSuppressionTimer.startOneShot(1_s * settings().incrementalRenderingSuppressionTimeoutInSeconds());
1309 if (!visualUpdatesAllowed)
1312 RefPtr<FrameView> frameView = view();
1313 bool needsLayout = frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout());
1317 if (Page* page = this->page()) {
1318 if (frame()->isMainFrame()) {
1319 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1320 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1321 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1326 frameView->updateCompositingLayersAfterLayout();
1328 if (RenderView* renderView = this->renderView())
1329 renderView->repaintViewAndCompositedLayers();
1331 if (Frame* frame = this->frame())
1332 frame->loader().forcePageTransitionIfNeeded();
1335 void Document::visualUpdatesSuppressionTimerFired()
1337 ASSERT(!m_visualUpdatesAllowed);
1339 // If the client is extending the visual update suppression period explicitly, the
1340 // watchdog should not re-enable visual updates itself, but should wait for the client.
1341 if (view() && !view()->visualUpdatesAllowedByClient())
1344 setVisualUpdatesAllowed(true);
1347 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1349 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1350 // both of which we can determine by looking at the timer.
1352 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1353 setVisualUpdatesAllowed(true);
1356 String Document::characterSetWithUTF8Fallback() const
1358 AtomString name = encoding();
1361 return UTF8Encoding().domName();
1364 String Document::defaultCharsetForLegacyBindings() const
1367 UTF8Encoding().domName();
1368 return settings().defaultTextEncodingName();
1371 void Document::setCharset(const String& charset)
1375 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1378 void Document::setContentLanguage(const String& language)
1380 if (m_contentLanguage == language)
1382 m_contentLanguage = language;
1384 // Recalculate style so language is used when selecting the initial font.
1385 m_styleScope->didChangeStyleSheetEnvironment();
1388 ExceptionOr<void> Document::setXMLVersion(const String& version)
1390 if (!XMLDocumentParser::supportsXMLVersion(version))
1391 return Exception { NotSupportedError };
1393 m_xmlVersion = version;
1397 void Document::setXMLStandalone(bool standalone)
1399 m_xmlStandalone = standalone ? StandaloneStatus::Standalone : StandaloneStatus::NotStandalone;
1402 void Document::setDocumentURI(const String& uri)
1404 // This property is read-only from JavaScript, but writable from Objective-C.
1405 m_documentURI = uri;
1409 void Document::setContent(const String& content)
1412 // FIXME: This should probably use insert(), but that's (intentionally)
1413 // not implemented for the XML parser as it's normally synonymous with
1414 // document.write(). append() will end up yielding, but close() will
1415 // pump the tokenizer syncrhonously and finish the parse.
1416 m_parser->append(content.impl());
1420 String Document::suggestedMIMEType() const
1422 if (isXHTMLDocument())
1423 return "application/xhtml+xml"_s;
1424 if (isSVGDocument())
1425 return "image/svg+xml"_s;
1426 if (xmlStandalone())
1427 return "text/xml"_s;
1428 if (isHTMLDocument())
1429 return "text/html"_s;
1430 if (DocumentLoader* loader = this->loader())
1431 return loader->responseMIMEType();
1435 void Document::overrideMIMEType(const String& mimeType)
1437 m_overriddenMIMEType = mimeType;
1440 String Document::contentType() const
1442 if (!m_overriddenMIMEType.isNull())
1443 return m_overriddenMIMEType;
1445 if (DocumentLoader* documentLoader = loader())
1446 return documentLoader->currentContentType();
1448 String mimeType = suggestedMIMEType();
1449 if (!mimeType.isNull())
1452 return "application/xml"_s;
1455 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1457 return caretRangeFromPoint(LayoutPoint(x, y));
1460 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1462 if (!hasLivingRenderTree())
1465 LayoutPoint localPoint;
1466 Node* node = nodeFromPoint(clientPoint, &localPoint);
1470 RenderObject* renderer = node->renderer();
1473 Position rangeCompliantPosition = renderer->positionForPoint(localPoint).parentAnchoredEquivalent();
1474 if (rangeCompliantPosition.isNull())
1477 unsigned offset = rangeCompliantPosition.offsetInContainerNode();
1478 node = &retargetToScope(*rangeCompliantPosition.containerNode());
1479 if (node != rangeCompliantPosition.containerNode())
1482 return Range::create(*this, node, offset, node, offset);
1485 bool Document::isBodyPotentiallyScrollable(HTMLBodyElement& body)
1487 // See https://www.w3.org/TR/cssom-view-1/#potentially-scrollable.
1488 // An element is potentially scrollable if all of the following conditions are true:
1489 // - The element has an associated CSS layout box.
1490 // - The element is not the HTML body element, or it is and the root element's used value of the
1491 // overflow-x or overflow-y properties is not visible.
1492 // - The element's used value of the overflow-x or overflow-y properties is not visible.
1494 // FIXME: We should use RenderObject::hasOverflowClip() instead of Element::computedStyle() but
1495 // the used values are currently not correctly updated. See https://webkit.org/b/182292.
1496 return body.renderer()
1497 && documentElement()->computedStyle()
1498 && !documentElement()->computedStyle()->isOverflowVisible()
1499 && body.computedStyle()
1500 && !body.computedStyle()->isOverflowVisible();
1503 Element* Document::scrollingElementForAPI()
1505 if (inQuirksMode() && settings().CSSOMViewScrollingAPIEnabled())
1506 updateLayoutIgnorePendingStylesheets();
1507 return scrollingElement();
1510 Element* Document::scrollingElement()
1512 if (settings().CSSOMViewScrollingAPIEnabled()) {
1513 // See https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement.
1514 // The scrollingElement attribute, on getting, must run these steps:
1515 // 1. If the Document is in quirks mode, follow these substeps:
1516 if (inQuirksMode()) {
1517 auto* firstBody = body();
1518 // 1. If the HTML body element exists, and it is not potentially scrollable, return the
1519 // HTML body element and abort these steps.
1520 if (firstBody && !isBodyPotentiallyScrollable(*firstBody))
1523 // 2. Return null and abort these steps.
1527 // 2. If there is a root element, return the root element and abort these steps.
1529 return documentElement();
1535 static String canonicalizedTitle(Document& document, const String& title)
1537 // Collapse runs of HTML spaces into single space characters.
1538 // Strip leading and trailing spaces.
1539 // Replace backslashes with currency symbols.
1541 StringBuilder builder;
1543 auto* decoder = document.decoder();
1544 auto backslashAsCurrencySymbol = decoder ? decoder->encoding().backslashAsCurrencySymbol() : '\\';
1546 bool previousCharacterWasHTMLSpace = false;
1547 for (auto character : StringView { title }.codeUnits()) {
1548 if (isHTMLSpace(character))
1549 previousCharacterWasHTMLSpace = true;
1551 if (character == '\\')
1552 character = backslashAsCurrencySymbol;
1553 if (previousCharacterWasHTMLSpace && !builder.isEmpty())
1554 builder.append(' ');
1555 builder.append(character);
1556 previousCharacterWasHTMLSpace = false;
1560 return builder == title ? title : builder.toString();
1563 void Document::updateTitle(const StringWithDirection& title)
1565 if (m_rawTitle == title)
1570 m_title.string = canonicalizedTitle(*this, title.string);
1571 m_title.direction = title.direction;
1573 if (auto* loader = this->loader())
1574 loader->setTitle(m_title);
1577 void Document::updateTitleFromTitleElement()
1579 if (!m_titleElement) {
1584 if (is<HTMLTitleElement>(*m_titleElement))
1585 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1586 else if (is<SVGTitleElement>(*m_titleElement)) {
1587 // FIXME: Does the SVG title element have a text direction?
1588 updateTitle({ downcast<SVGTitleElement>(*m_titleElement).textContent(), TextDirection::LTR });
1592 void Document::setTitle(const String& title)
1594 auto* element = documentElement();
1595 if (is<SVGSVGElement>(element)) {
1596 if (!m_titleElement) {
1597 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1598 element->insertBefore(*m_titleElement, element->firstChild());
1600 m_titleElement->setTextContent(title);
1601 } else if (is<HTMLElement>(element)) {
1602 if (!m_titleElement) {
1603 auto* headElement = head();
1606 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1607 headElement->appendChild(*m_titleElement);
1609 m_titleElement->setTextContent(title);
1613 template<typename> struct TitleTraits;
1615 template<> struct TitleTraits<HTMLTitleElement> {
1616 static bool isInEligibleLocation(HTMLTitleElement& element) { return element.isConnected() && !element.isInShadowTree(); }
1617 static HTMLTitleElement* findTitleElement(Document& document) { return descendantsOfType<HTMLTitleElement>(document).first(); }
1620 template<> struct TitleTraits<SVGTitleElement> {
1621 static bool isInEligibleLocation(SVGTitleElement& element) { return element.parentNode() == element.document().documentElement(); }
1622 static SVGTitleElement* findTitleElement(Document& document) { return childrenOfType<SVGTitleElement>(*document.documentElement()).first(); }
1625 template<typename TitleElement> Element* selectNewTitleElement(Document& document, Element* oldTitleElement, Element& changingTitleElement)
1627 using Traits = TitleTraits<TitleElement>;
1629 if (!is<TitleElement>(changingTitleElement)) {
1630 ASSERT(oldTitleElement == Traits::findTitleElement(document));
1631 return oldTitleElement;
1634 if (oldTitleElement)
1635 return Traits::findTitleElement(document);
1637 // Optimized common case: We have no title element yet.
1638 // We can figure out which title element should be used without searching.
1639 bool isEligible = Traits::isInEligibleLocation(downcast<TitleElement>(changingTitleElement));
1640 auto* newTitleElement = isEligible ? &changingTitleElement : nullptr;
1641 ASSERT(newTitleElement == Traits::findTitleElement(document));
1642 return newTitleElement;
1645 void Document::updateTitleElement(Element& changingTitleElement)
1647 // Most documents use HTML title rules.
1648 // Documents with SVG document elements use SVG title rules.
1649 auto selectTitleElement = is<SVGSVGElement>(documentElement())
1650 ? selectNewTitleElement<SVGTitleElement> : selectNewTitleElement<HTMLTitleElement>;
1651 auto newTitleElement = selectTitleElement(*this, m_titleElement.get(), changingTitleElement);
1652 if (m_titleElement == newTitleElement)
1654 m_titleElement = newTitleElement;
1655 updateTitleFromTitleElement();
1658 void Document::titleElementAdded(Element& titleElement)
1660 if (m_titleElement == &titleElement)
1663 updateTitleElement(titleElement);
1666 void Document::titleElementRemoved(Element& titleElement)
1668 if (m_titleElement != &titleElement)
1671 updateTitleElement(titleElement);
1674 void Document::titleElementTextChanged(Element& titleElement)
1676 if (m_titleElement != &titleElement)
1679 updateTitleFromTitleElement();
1682 void Document::registerForVisibilityStateChangedCallbacks(VisibilityChangeClient& client)
1684 m_visibilityStateCallbackClients.add(&client);
1687 void Document::unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient& client)
1689 m_visibilityStateCallbackClients.remove(&client);
1692 void Document::visibilityStateChanged()
1694 enqueueDocumentEvent(Event::create(eventNames().visibilitychangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
1695 for (auto* client : m_visibilityStateCallbackClients)
1696 client->visibilityStateChanged();
1698 notifyMediaCaptureOfVisibilityChanged();
1701 VisibilityState Document::visibilityState() const
1703 // The visibility of the document is inherited from the visibility of the
1704 // page. If there is no page associated with the document, we will assume
1705 // that the page is hidden, as specified by the spec:
1706 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1707 if (!m_frame || !m_frame->page())
1708 return VisibilityState::Hidden;
1709 return m_frame->page()->visibilityState();
1712 bool Document::hidden() const
1714 return visibilityState() != VisibilityState::Visible;
1719 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1721 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1724 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1726 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1729 void Document::allowsMediaDocumentInlinePlaybackChanged()
1731 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1732 element->allowsMediaDocumentInlinePlaybackChanged();
1735 void Document::stopAllMediaPlayback()
1737 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1738 platformMediaSessionManager->stopAllMediaPlaybackForDocument(*this);
1741 void Document::suspendAllMediaPlayback()
1743 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1744 platformMediaSessionManager->suspendAllMediaPlaybackForDocument(*this);
1747 void Document::resumeAllMediaPlayback()
1749 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1750 platformMediaSessionManager->resumeAllMediaPlaybackForDocument(*this);
1753 void Document::suspendAllMediaBuffering()
1755 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1756 platformMediaSessionManager->suspendAllMediaBufferingForDocument(*this);
1759 void Document::resumeAllMediaBuffering()
1761 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1762 platformMediaSessionManager->resumeAllMediaBufferingForDocument(*this);
1766 String Document::nodeName() const
1768 return "#document"_s;
1771 Node::NodeType Document::nodeType() const
1773 return DOCUMENT_NODE;
1776 FormController& Document::formController()
1778 if (!m_formController)
1779 m_formController = makeUnique<FormController>();
1780 return *m_formController;
1783 Vector<String> Document::formElementsState() const
1785 if (!m_formController)
1786 return Vector<String>();
1787 return m_formController->formElementsState();
1790 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1792 if (!stateVector.size() && !m_formController)
1794 formController().setStateForNewFormElements(stateVector);
1797 FrameView* Document::view() const
1799 return m_frame ? m_frame->view() : nullptr;
1802 Page* Document::page() const
1804 return m_frame ? m_frame->page() : nullptr;
1807 Ref<Range> Document::createRange()
1809 return Range::create(*this);
1812 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1814 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1817 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1819 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1822 void Document::scheduleFullStyleRebuild()
1824 m_needsFullStyleRebuild = true;
1825 scheduleStyleRecalc();
1828 void Document::scheduleStyleRecalc()
1830 ASSERT(!m_renderView || !inHitTesting());
1832 if (m_styleRecalcTimer.isActive() || backForwardCacheState() != NotInBackForwardCache)
1835 ASSERT(childNeedsStyleRecalc() || m_needsFullStyleRebuild);
1836 auto shouldThrottleStyleRecalc = [&] {
1837 if (!view() || !view()->isVisuallyNonEmpty())
1839 if (!page() || !page()->chrome().client().layerFlushThrottlingIsActive())
1844 if (shouldThrottleStyleRecalc())
1847 m_styleRecalcTimer.startOneShot(0_s);
1849 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1852 void Document::unscheduleStyleRecalc()
1854 ASSERT(!childNeedsStyleRecalc());
1856 m_styleRecalcTimer.stop();
1857 m_needsFullStyleRebuild = false;
1860 bool Document::hasPendingStyleRecalc() const
1862 return needsStyleRecalc() && !m_inStyleRecalc;
1865 bool Document::hasPendingFullStyleRebuild() const
1867 return hasPendingStyleRecalc() && m_needsFullStyleRebuild;
1870 void Document::resolveStyle(ResolveStyleType type)
1872 ASSERT(!view() || !view()->isPainting());
1874 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1878 FrameView& frameView = m_renderView->frameView();
1879 Ref<FrameView> protect(frameView);
1880 if (frameView.isPainting())
1883 if (m_inStyleRecalc)
1884 return; // Guard against re-entrancy. -dwh
1886 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1888 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1889 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1891 // FIXME: Do this update per tree scope.
1893 auto elements = copyToVectorOf<RefPtr<SVGUseElement>>(m_svgUseElements);
1894 // We can't clear m_svgUseElements here because updateShadowTree may end up executing arbitrary scripts
1895 // which may insert new SVG use elements or remove existing ones inside sync IPC via ImageLoader::updateFromElement.
1896 for (auto& element : elements)
1897 element->updateShadowTree();
1900 // FIXME: We should update style on our ancestor chain before proceeding, however doing so at
1901 // the time this comment was originally written caused several tests to crash.
1904 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
1905 styleScope().flushPendingUpdate();
1906 frameView.willRecalcStyle();
1909 InspectorInstrumentation::willRecalculateStyle(*this);
1911 bool updatedCompositingLayers = false;
1913 Style::PostResolutionCallbackDisabler disabler(*this);
1914 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1915 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
1917 m_inStyleRecalc = true;
1919 if (m_needsFullStyleRebuild)
1920 type = ResolveStyleType::Rebuild;
1922 if (type == ResolveStyleType::Rebuild) {
1923 // This may get set again during style resolve.
1924 m_hasNodesWithNonFinalStyle = false;
1925 m_hasNodesWithMissingStyle = false;
1927 auto documentStyle = Style::resolveForDocument(*this);
1929 // Inserting the pictograph font at the end of the font fallback list is done by the
1930 // font selector, so set a font selector if needed.
1931 if (settings().fontFallbackPrefersPictographs())
1932 documentStyle.fontCascade().update(&fontSelector());
1934 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
1935 if (documentChange != Style::NoChange)
1936 renderView()->setStyle(WTFMove(documentStyle));
1938 if (auto* documentElement = this->documentElement())
1939 documentElement->invalidateStyleForSubtree();
1942 Style::TreeResolver resolver(*this);
1943 auto styleUpdate = resolver.resolve();
1945 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
1948 clearChildNeedsStyleRecalc();
1949 unscheduleStyleRecalc();
1951 m_inStyleRecalc = false;
1954 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1956 RenderTreeUpdater updater(*this);
1957 updater.commit(WTFMove(styleUpdate));
1959 frameView.styleDidChange();
1962 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1964 if (m_renderView->needsLayout())
1965 frameView.layoutContext().scheduleLayout();
1967 // Usually this is handled by post-layout.
1968 if (!frameView.needsLayout())
1969 frameView.frame().selection().scheduleAppearanceUpdateAfterStyleChange();
1971 // As a result of the style recalculation, the currently hovered element might have been
1972 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1973 // to check if any other elements ended up under the mouse pointer due to re-layout.
1974 if (m_hoveredElement && !m_hoveredElement->renderer())
1975 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1977 ++m_styleRecalcCount;
1978 // FIXME: Assert ASSERT(!needsStyleRecalc()) here. Do we still have some cases where it's not true?
1981 InspectorInstrumentation::didRecalculateStyle(*this);
1983 // Some animated images may now be inside the viewport due to style recalc,
1984 // resume them if necessary if there is no layout pending. Otherwise, we'll
1985 // check if they need to be resumed after layout.
1986 if (updatedCompositingLayers && !frameView.needsLayout())
1987 frameView.viewportContentsChanged();
1989 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
1990 frameView.scrollToFragment(m_url);
1993 void Document::updateTextRenderer(Text& text, unsigned offsetOfReplacedText, unsigned lengthOfReplacedText)
1995 ASSERT(!m_inRenderTreeUpdate);
1996 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1998 auto textUpdate = makeUnique<Style::Update>(*this);
1999 textUpdate->addText(text, { offsetOfReplacedText, lengthOfReplacedText, WTF::nullopt });
2001 RenderTreeUpdater renderTreeUpdater(*this);
2002 renderTreeUpdater.commit(WTFMove(textUpdate));
2005 bool Document::needsStyleRecalc() const
2007 if (backForwardCacheState() != NotInBackForwardCache)
2010 if (m_needsFullStyleRebuild)
2013 if (childNeedsStyleRecalc())
2016 if (styleScope().hasPendingUpdate())
2019 // Ensure this happens eventually as it is currently in resolveStyle. This can be removed if the code moves.
2020 if (m_gotoAnchorNeededAfterStylesheetsLoad && !styleScope().hasPendingSheets())
2026 static bool isSafeToUpdateStyleOrLayout(const Document& document)
2028 bool isSafeToExecuteScript = ScriptDisallowedScope::InMainThread::isScriptAllowed();
2029 auto* frameView = document.view();
2030 bool isInFrameFlattening = frameView && frameView->isInChildFrameWithFrameFlattening();
2031 return isSafeToExecuteScript || isInFrameFlattening || !isInWebProcess();
2034 bool Document::updateStyleIfNeeded()
2036 RefPtr<FrameView> frameView = view();
2038 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
2039 ASSERT(isMainThread());
2040 ASSERT(!frameView || !frameView->isPainting());
2042 if (!frameView || frameView->layoutContext().isInRenderTreeLayout())
2045 styleScope().flushPendingUpdate();
2047 if (!needsStyleRecalc())
2051 #if PLATFORM(IOS_FAMILY)
2052 ContentChangeObserver::StyleRecalcScope observingScope(*this);
2054 // The early exit above for !needsStyleRecalc() is needed when updateWidgetPositions() is called in runOrScheduleAsynchronousTasks().
2055 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(*this));
2060 void Document::updateLayout()
2062 ASSERT(isMainThread());
2064 RefPtr<FrameView> frameView = view();
2065 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
2066 // View layout should not be re-entrant.
2067 ASSERT_NOT_REACHED();
2070 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(*this));
2072 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2074 if (HTMLFrameOwnerElement* owner = ownerElement())
2075 owner->document().updateLayout();
2077 updateStyleIfNeeded();
2079 StackStats::LayoutCheckPoint layoutCheckPoint;
2081 // Only do a layout if changes have occurred that make it necessary.
2082 if (frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
2083 frameView->layoutContext().layout();
2086 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
2088 bool oldIgnore = m_ignorePendingStylesheets;
2090 if (!haveStylesheetsLoaded()) {
2091 m_ignorePendingStylesheets = true;
2092 // FIXME: This should just invalidate elements with missing styles.
2093 if (m_hasNodesWithMissingStyle)
2094 scheduleFullStyleRebuild();
2099 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
2100 view()->flushAnyPendingPostLayoutTasks();
2102 m_ignorePendingStylesheets = oldIgnore;
2105 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle, PseudoId pseudoElementSpecifier)
2107 ASSERT(&element.document() == this);
2108 ASSERT(!element.isPseudoElement() || pseudoElementSpecifier == PseudoId::None);
2109 ASSERT(pseudoElementSpecifier == PseudoId::None || parentStyle);
2111 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
2112 Style::PostResolutionCallbackDisabler disabler(*this, Style::PostResolutionCallbackDisabler::DrainCallbacks::No);
2114 SetForScope<bool> change(m_ignorePendingStylesheets, true);
2115 auto& resolver = element.styleResolver();
2117 if (pseudoElementSpecifier != PseudoId::None)
2118 return resolver.pseudoStyleForElement(element, PseudoStyleRequest(pseudoElementSpecifier), *parentStyle);
2120 auto elementStyle = resolver.styleForElement(element, parentStyle);
2121 if (elementStyle.relations) {
2122 Style::Update emptyUpdate(*this);
2123 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
2126 return WTFMove(elementStyle.renderStyle);
2129 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2131 ASSERT(isMainThread());
2133 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2134 if (!haveStylesheetsLoaded()) {
2135 updateLayoutIgnorePendingStylesheets();
2139 // Check for re-entrancy and assert (same code that is in updateLayout()).
2140 RefPtr<FrameView> frameView = view();
2141 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
2142 // View layout should not be re-entrant.
2143 ASSERT_NOT_REACHED();
2147 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2149 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2151 bool requireFullLayout = false;
2152 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2153 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2154 requireFullLayout = true;
2157 updateStyleIfNeeded();
2159 RenderObject* renderer = element.renderer();
2160 if (!renderer || renderer->needsLayout()) {
2161 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2162 requireFullLayout = true;
2165 // Turn off this optimization for input elements with shadow content.
2166 if (is<HTMLInputElement>(element))
2167 requireFullLayout = true;
2169 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2170 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2171 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2172 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2174 if (!requireFullLayout) {
2175 RenderBox* previousBox = nullptr;
2176 RenderBox* currentBox = nullptr;
2178 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2179 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2181 // Require the entire container chain to be boxes.
2182 if (!is<RenderBox>(currRenderer)) {
2183 requireFullLayout = true;
2187 previousBox = currentBox;
2188 currentBox = downcast<RenderBox>(currRenderer);
2190 // If a box needs layout for itself or if a box has changed children and sizes its width to
2191 // its content, then require a full layout.
2192 if (currentBox->selfNeedsLayout() ||
2193 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2194 requireFullLayout = true;
2198 // If a block contains floats and the child's height isn't specified, then
2199 // give up also, since our height could end up being influenced by the floats.
2200 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2201 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2202 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2203 requireFullLayout = true;
2208 if (!currentBox->isRenderBlockFlow() || currentBox->enclosingFragmentedFlow() || currentBox->isWritingModeRoot()) {
2209 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2210 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2211 // Disallow columns from having the optimization.
2212 // Give up if the writing mode changes at all in the containing block chain.
2213 requireFullLayout = true;
2217 if (currRenderer == frameView->layoutContext().subtreeLayoutRoot())
2222 StackStats::LayoutCheckPoint layoutCheckPoint;
2224 // Only do a layout if changes have occurred that make it necessary.
2225 if (requireFullLayout && frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
2226 frameView->layoutContext().layout();
2228 return requireFullLayout;
2231 bool Document::isPageBoxVisible(int pageIndex)
2233 updateStyleIfNeeded();
2234 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2235 return pageStyle->visibility() != Visibility::Hidden; // display property doesn't apply to @page.
2238 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2240 updateStyleIfNeeded();
2241 auto style = styleScope().resolver().styleForPage(pageIndex);
2243 int width = pageSize.width();
2244 int height = pageSize.height();
2245 switch (style->pageSizeType()) {
2246 case PAGE_SIZE_AUTO:
2248 case PAGE_SIZE_AUTO_LANDSCAPE:
2250 std::swap(width, height);
2252 case PAGE_SIZE_AUTO_PORTRAIT:
2254 std::swap(width, height);
2256 case PAGE_SIZE_RESOLVED: {
2257 auto& size = style->pageSize();
2258 ASSERT(size.width.isFixed());
2259 ASSERT(size.height.isFixed());
2260 width = valueForLength(size.width, 0);
2261 height = valueForLength(size.height, 0);
2265 ASSERT_NOT_REACHED();
2267 pageSize = IntSize(width, height);
2269 // The percentage is calculated with respect to the width even for margin top and bottom.
2270 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2271 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2272 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2273 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2274 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2277 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2279 if (!m_userAgentShadowTreeStyleResolver)
2280 m_userAgentShadowTreeStyleResolver = makeUnique<StyleResolver>(*this);
2281 return *m_userAgentShadowTreeStyleResolver;
2284 void Document::fontsNeedUpdate(FontSelector&)
2286 invalidateMatchedPropertiesCacheAndForceStyleRecalc();
2289 void Document::invalidateMatchedPropertiesCacheAndForceStyleRecalc()
2291 if (auto* resolver = styleScope().resolverIfExists())
2292 resolver->invalidateMatchedPropertiesCache();
2293 if (backForwardCacheState() != NotInBackForwardCache || !renderView())
2295 scheduleFullStyleRebuild();
2298 void Document::didClearStyleResolver()
2300 m_userAgentShadowTreeStyleResolver = nullptr;
2303 void Document::setIsResolvingTreeStyle(bool value)
2305 RELEASE_ASSERT(value != m_isResolvingTreeStyle);
2306 m_isResolvingTreeStyle = value;
2309 void Document::createRenderTree()
2311 ASSERT(!renderView());
2312 ASSERT(m_backForwardCacheState != InBackForwardCache);
2313 ASSERT(!m_axObjectCache || this != &topDocument());
2315 if (m_isNonRenderedPlaceholder)
2318 // FIXME: It would be better if we could pass the resolved document style directly here.
2319 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2320 Node::setRenderer(m_renderView.get());
2322 renderView()->setIsInWindow(true);
2324 resolveStyle(ResolveStyleType::Rebuild);
2327 void Document::didBecomeCurrentDocumentInFrame()
2329 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2330 // If so, then m_frame could become 0, and we need to do something about that.
2332 m_frame->script().updateDocument();
2334 if (!hasLivingRenderTree())
2337 dispatchDisabledAdaptationsDidChangeForMainFrame();
2338 updateViewportArguments();
2340 // FIXME: Doing this only for the main frame is insufficient.
2341 // Changing a subframe can also change the wheel event handler count.
2342 // FIXME: Doing this only when a document goes into the frame is insufficient.
2343 // Removing a document can also change the wheel event handler count.
2344 // FIXME: Doing this every time is a waste. If the current document and its
2345 // subframes' documents have no wheel event handlers, then the count did not change,
2346 // unless the documents they are replacing had wheel event handlers.
2347 if (page() && m_frame->isMainFrame())
2348 wheelEventHandlersChanged();
2350 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2351 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2352 // back/forward cache, or simply newly created).
2353 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2354 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
2355 if (auto* timeline = existingTimeline())
2356 timeline->suspendAnimations();
2358 m_frame->animation().suspendAnimationsForDocument(this);
2359 suspendScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
2361 resumeScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
2362 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
2363 if (auto* timeline = existingTimeline())
2364 timeline->resumeAnimations();
2366 m_frame->animation().resumeAnimationsForDocument(this);
2370 void Document::frameDestroyed()
2372 // detachFromFrame() must be called before destroying the Frame.
2373 RELEASE_ASSERT(!m_frame);
2375 if (auto* window = domWindow())
2376 window->frameDestroyed();
2378 FrameDestructionObserver::frameDestroyed();
2381 void Document::willDetachPage()
2383 FrameDestructionObserver::willDetachPage();
2384 #if PLATFORM(IOS_FAMILY)
2385 contentChangeObserver().willDetachPage();
2387 if (domWindow() && frame())
2388 InspectorInstrumentation::frameWindowDiscarded(*frame(), domWindow());
2391 void Document::attachToCachedFrame(CachedFrameBase& cachedFrame)
2393 RELEASE_ASSERT(cachedFrame.document() == this);
2394 ASSERT(cachedFrame.view());
2395 ASSERT(m_backForwardCacheState == Document::InBackForwardCache);
2396 observeFrame(&cachedFrame.view()->frame());
2399 void Document::detachFromCachedFrame(CachedFrameBase& cachedFrame)
2401 ASSERT_UNUSED(cachedFrame, cachedFrame.view());
2402 RELEASE_ASSERT(cachedFrame.document() == this);
2403 ASSERT(m_frame == &cachedFrame.view()->frame());
2404 ASSERT(m_backForwardCacheState == Document::InBackForwardCache);
2408 void Document::destroyRenderTree()
2410 ASSERT(hasLivingRenderTree());
2412 ASSERT(frame()->document() == this);
2415 // Prevent Widget tree changes from committing until the RenderView is dead and gone.
2416 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2418 SetForScope<bool> change(m_renderTreeBeingDestroyed, true);
2420 if (this == &topDocument())
2421 clearAXObjectCache();
2423 documentWillBecomeInactive();
2426 view()->willDestroyRenderTree();
2428 if (m_documentElement)
2429 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2431 clearChildNeedsStyleRecalc();
2433 unscheduleStyleRecalc();
2435 // FIXME: RenderObject::view() uses m_renderView and we can't null it before destruction is completed
2437 RenderTreeBuilder builder(*m_renderView);
2438 // FIXME: This is a workaround for leftover content (see webkit.org/b/182547).
2439 while (m_renderView->firstChild())
2440 builder.destroy(*m_renderView->firstChild());
2441 m_renderView->destroy();
2443 m_renderView.release();
2445 Node::setRenderer(nullptr);
2447 #if ENABLE(TEXT_AUTOSIZING)
2448 m_textAutoSizing = nullptr;
2452 view()->didDestroyRenderTree();
2455 void Document::prepareForDestruction()
2457 if (m_hasPreparedForDestruction)
2461 m_frame->animation().detachFromDocument(this);
2464 // FIXME: This should be moved to Modules/mediastream.
2465 if (LibWebRTCProvider::webRTCAvailable()) {
2466 if (auto* page = this->page())
2467 page->libWebRTCProvider().unregisterMDNSNames(identifier().toUInt64());
2471 #if ENABLE(SERVICE_WORKER)
2472 setActiveServiceWorker(nullptr);
2473 setServiceWorkerConnection(nullptr);
2476 #if ENABLE(IOS_TOUCH_EVENTS)
2477 clearTouchEventHandlersAndListeners();
2480 m_undoManager->removeAllItems();
2482 m_textManipulationController = nullptr; // Free nodes kept alive by TextManipulationController.
2484 #if ENABLE(ACCESSIBILITY)
2485 if (this != &topDocument()) {
2486 // Let the ax cache know that this subframe goes out of scope.
2487 if (auto* cache = existingAXObjectCache())
2488 cache->prepareForDocumentDestruction(*this);
2493 NavigationDisabler navigationDisabler(m_frame);
2494 disconnectDescendantFrames();
2496 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!m_frame || !m_frame->tree().childCount());
2498 if (m_domWindow && m_frame)
2499 m_domWindow->willDetachDocumentFromFrame();
2501 styleScope().clearResolver();
2503 if (hasLivingRenderTree())
2504 destroyRenderTree();
2506 if (is<PluginDocument>(*this))
2507 downcast<PluginDocument>(*this).detachFromPluginElement();
2509 #if ENABLE(POINTER_LOCK)
2511 page()->pointerLockController().documentDetached(*this);
2514 if (auto* page = this->page()) {
2515 if (auto* validationMessageClient = page->validationMessageClient())
2516 validationMessageClient->documentDetached(*this);
2519 InspectorInstrumentation::documentDetached(*this);
2521 stopActiveDOMObjects();
2522 m_eventQueue.close();
2523 #if ENABLE(FULLSCREEN_API)
2524 m_fullscreenManager->emptyEventQueue();
2529 #if ENABLE(TOUCH_EVENTS)
2530 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2531 parentDocument()->didRemoveEventTargetNode(*this);
2534 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2535 parentDocument()->didRemoveEventTargetNode(*this);
2537 if (m_mediaQueryMatcher)
2538 m_mediaQueryMatcher->documentDestroyed();
2540 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2541 if (!m_clientToIDMap.isEmpty() && page()) {
2542 for (auto* client : copyToVector(m_clientToIDMap.keys()))
2543 removePlaybackTargetPickerClient(*client);
2547 m_cachedResourceLoader->stopUnusedPreloadsTimer();
2549 if (page() && m_mediaState != MediaProducer::IsNotPlaying) {
2550 m_mediaState = MediaProducer::IsNotPlaying;
2551 page()->updateIsPlayingMedia(HTMLMediaElementInvalidID);
2557 m_timeline->detachFromDocument();
2558 m_timeline = nullptr;
2561 #if ENABLE(CSS_PAINTING_API)
2562 for (auto& scope : m_paintWorkletGlobalScopes.values())
2563 scope->prepareForDestruction();
2564 m_paintWorkletGlobalScopes.clear();
2567 m_hasPreparedForDestruction = true;
2569 // Note that m_backForwardCacheState can be Document::AboutToEnterBackForwardCache if our frame
2570 // was removed in an onpagehide event handler fired when the top-level frame is
2571 // about to enter the back/forward cache.
2572 RELEASE_ASSERT(m_backForwardCacheState != Document::InBackForwardCache);
2575 void Document::removeAllEventListeners()
2577 EventTarget::removeAllEventListeners();
2580 m_domWindow->removeAllEventListeners();
2582 #if ENABLE(IOS_TOUCH_EVENTS)
2583 clearTouchEventHandlersAndListeners();
2585 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2586 node->removeAllEventListeners();
2588 #if ENABLE(TOUCH_EVENTS)
2589 m_touchEventTargets = nullptr;
2591 m_wheelEventTargets = nullptr;
2594 void Document::suspendDeviceMotionAndOrientationUpdates()
2596 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2598 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2599 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
2600 if (m_deviceMotionController)
2601 m_deviceMotionController->suspendUpdates();
2602 if (m_deviceOrientationController)
2603 m_deviceOrientationController->suspendUpdates();
2607 void Document::resumeDeviceMotionAndOrientationUpdates()
2609 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2611 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2612 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
2613 if (m_deviceMotionController)
2614 m_deviceMotionController->resumeUpdates();
2615 if (m_deviceOrientationController)
2616 m_deviceOrientationController->resumeUpdates();
2620 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2622 // Bypass this policy when the world is known, and it not the normal world.
2623 JSC::VM& vm = commonVM();
2624 auto& callFrame = *vm.topCallFrame;
2625 return &callFrame != JSC::CallFrame::noCaller() && !currentWorld(*callFrame.lexicalGlobalObject(vm)).isNormal();
2628 void Document::platformSuspendOrStopActiveDOMObjects()
2630 #if PLATFORM(IOS_FAMILY)
2631 contentChangeObserver().didSuspendActiveDOMObjects();
2635 void Document::suspendActiveDOMObjects(ReasonForSuspension why)
2637 ScriptExecutionContext::suspendActiveDOMObjects(why);
2638 suspendDeviceMotionAndOrientationUpdates();
2639 platformSuspendOrStopActiveDOMObjects();
2642 void Document::resumeActiveDOMObjects(ReasonForSuspension why)
2644 ScriptExecutionContext::resumeActiveDOMObjects(why);
2645 resumeDeviceMotionAndOrientationUpdates();
2646 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2649 void Document::stopActiveDOMObjects()
2651 ScriptExecutionContext::stopActiveDOMObjects();
2652 platformSuspendOrStopActiveDOMObjects();
2655 void Document::clearAXObjectCache()
2657 ASSERT(&topDocument() == this);
2658 // Clear the cache member variable before calling delete because attempts
2659 // are made to access it during destruction.
2660 m_axObjectCache = nullptr;
2663 AXObjectCache* Document::existingAXObjectCacheSlow() const
2665 ASSERT(hasEverCreatedAnAXObjectCache);
2666 return topDocument().m_axObjectCache.get();
2669 AXObjectCache* Document::axObjectCache() const
2671 if (!AXObjectCache::accessibilityEnabled())
2674 // The only document that actually has a AXObjectCache is the top-level
2675 // document. This is because we need to be able to get from any WebCoreAXObject
2676 // to any other WebCoreAXObject on the same page. Using a single cache allows
2677 // lookups across nested webareas (i.e. multiple documents).
2678 Document& topDocument = this->topDocument();
2680 // If the document has already been detached, do not make a new axObjectCache.
2681 if (!topDocument.hasLivingRenderTree())
2684 ASSERT(&topDocument == this || !m_axObjectCache);
2685 if (!topDocument.m_axObjectCache) {
2686 topDocument.m_axObjectCache = makeUnique<AXObjectCache>(topDocument);
2687 hasEverCreatedAnAXObjectCache = true;
2689 return topDocument.m_axObjectCache.get();
2692 void Document::setVisuallyOrdered()
2694 m_visuallyOrdered = true;
2696 renderView()->mutableStyle().setRTLOrdering(Order::Visual);
2699 Ref<DocumentParser> Document::createParser()
2701 // FIXME: this should probably pass the frame instead
2702 return XMLDocumentParser::create(*this, view());
2705 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2707 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2710 ExceptionOr<RefPtr<WindowProxy>> Document::openForBindings(DOMWindow& activeWindow, DOMWindow& firstWindow, const String& url, const AtomString& name, const String& features)
2713 return Exception { InvalidAccessError };
2715 return m_domWindow->open(activeWindow, firstWindow, url, name, features);
2718 ExceptionOr<Document&> Document::openForBindings(Document* responsibleDocument, const String&, const String&)
2720 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
2721 return Exception { InvalidStateError };
2723 auto result = open(responsibleDocument);
2724 if (UNLIKELY(result.hasException()))
2725 return result.releaseException();
2730 ExceptionOr<void> Document::open(Document* responsibleDocument)
2732 if (responsibleDocument && !responsibleDocument->securityOrigin().isSameOriginAs(securityOrigin()))
2733 return Exception { SecurityError };
2735 if (m_ignoreOpensDuringUnloadCount)
2738 if (m_activeParserWasAborted)
2742 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2743 if (parser->isParsing()) {
2744 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2745 if (parser->isExecutingScript())
2748 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2753 if (m_frame->loader().policyChecker().delegateIsDecidingNavigationPolicy())
2754 m_frame->loader().policyChecker().stopCheck();
2755 if (m_frame && m_frame->loader().state() == FrameStateProvisional)
2756 m_frame->loader().stopAllLoaders();
2759 removeAllEventListeners();
2761 if (responsibleDocument && isFullyActive()) {
2762 auto newURL = responsibleDocument->url();
2763 if (responsibleDocument != this)
2764 newURL.removeFragmentIdentifier();
2766 auto newCookieURL = responsibleDocument->cookieURL();
2767 if (responsibleDocument != this)
2768 newCookieURL.removeFragmentIdentifier();
2769 setCookieURL(newCookieURL);
2770 setSecurityOriginPolicy(responsibleDocument->securityOriginPolicy());
2774 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2775 parser->setWasCreatedByScript(true);
2778 m_frame->loader().didExplicitOpen();
2783 // https://html.spec.whatwg.org/#fully-active
2784 bool Document::isFullyActive() const
2786 auto* frame = this->frame();
2787 if (!frame || frame->document() != this)
2790 if (frame->isMainFrame())
2793 auto* parentFrame = frame->tree().parent();
2794 return parentFrame && parentFrame->document() && parentFrame->document()->isFullyActive();
2797 void Document::detachParser()
2805 void Document::cancelParsing()
2810 if (m_parser->processingData())
2811 m_activeParserWasAborted = true;
2813 // We have to clear the parser to avoid possibly triggering
2814 // the onload handler when closing as a side effect of a cancel-style
2815 // change, such as opening a new document or closing the window while
2821 void Document::implicitOpen()
2825 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2828 m_parser = createParser();
2830 if (hasActiveParserYieldToken())
2831 m_parser->didBeginYieldingParser();
2834 setReadyState(Loading);
2837 HTMLBodyElement* Document::body() const
2839 auto* element = documentElement();
2840 if (!is<HTMLHtmlElement>(element))
2842 return childrenOfType<HTMLBodyElement>(*element).first();
2845 HTMLElement* Document::bodyOrFrameset() const
2847 // Return the first body or frameset child of the html element.
2848 auto* element = documentElement();
2849 if (!is<HTMLHtmlElement>(element))
2851 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2852 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2858 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2860 if (!is<HTMLBodyElement>(newBody) && !is<HTMLFrameSetElement>(newBody))
2861 return Exception { HierarchyRequestError };
2863 auto* currentBody = bodyOrFrameset();
2864 if (newBody == currentBody)
2867 if (!m_documentElement)
2868 return Exception { HierarchyRequestError };
2871 return m_documentElement->replaceChild(*newBody, *currentBody);
2872 return m_documentElement->appendChild(*newBody);
2875 Location* Document::location() const
2877 auto* window = domWindow();
2878 return window ? &window->location() : nullptr;
2881 HTMLHeadElement* Document::head()
2883 if (auto element = documentElement())
2884 return childrenOfType<HTMLHeadElement>(*element).first();
2888 ExceptionOr<void> Document::closeForBindings()
2890 // FIXME: We should follow the specification more closely:
2891 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2893 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
2894 return Exception { InvalidStateError };
2900 void Document::close()
2902 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2908 void Document::explicitClose()
2910 if (RefPtr<DocumentParser> parser = m_parser)
2914 // Because we have no frame, we don't know if all loading has completed,
2915 // so we just call implicitClose() immediately. FIXME: This might fire
2916 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2924 void Document::implicitClose()
2926 RELEASE_ASSERT(!m_inStyleRecalc);
2927 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2928 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2933 // Call to dispatchWindowLoadEvent can blow us from underneath.
2934 Ref<Document> protectedThis(*this);
2936 m_processingLoadEvent = true;
2938 ScriptableDocumentParser* parser = scriptableDocumentParser();
2939 m_wellFormed = parser && parser->wellFormed();
2941 // We have to clear the parser, in case someone document.write()s from the
2942 // onLoad event handler, as in Radar 3206524.
2945 // FIXME: We kick off the icon loader when the Document is done parsing.
2946 // There are earlier opportunities we could start it:
2947 // -When the <head> finishes parsing
2948 // -When any new HTMLLinkElement is inserted into the document
2949 // But those add a dynamic component to the favicon that has UI
2950 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2951 RefPtr<Frame> f = frame();
2954 // Apply XSL transforms before load events so that event handlers can access the transformed DOM tree.
2955 applyPendingXSLTransformsNowIfScheduled();
2958 if (auto* documentLoader = loader())
2959 documentLoader->startIconLoading();
2961 f->animation().startAnimationsIfNotSuspended(this);
2963 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2964 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2965 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2966 ImageLoader::dispatchPendingBeforeLoadEvents();
2967 ImageLoader::dispatchPendingLoadEvents();
2968 ImageLoader::dispatchPendingErrorEvents();
2969 HTMLLinkElement::dispatchPendingLoadEvents();
2970 HTMLStyleElement::dispatchPendingLoadEvents();
2972 if (svgExtensions())
2973 accessSVGExtensions().dispatchLoadEventToOutermostSVGElements();
2976 dispatchWindowLoadEvent();
2977 dispatchPageshowEvent(PageshowEventNotPersisted);
2978 if (m_pendingStateObject)
2979 dispatchPopstateEvent(WTFMove(m_pendingStateObject));
2982 f->loader().dispatchOnloadEvents();
2984 // An event handler may have removed the frame
2986 m_processingLoadEvent = false;
2990 // Make sure both the initial layout and reflow happen after the onload
2991 // fires. This will improve onload scores, and other browsers do it.
2992 // If they wanna cheat, we can too. -dwh
2994 if (frame()->navigationScheduler().locationChangePending() && timeSinceDocumentCreation() < settings().layoutInterval()) {
2995 // Just bail out. Before or during the onload we were shifted to another page.
2996 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2997 m_processingLoadEvent = false;
2998 view()->layoutContext().unscheduleLayout();
3002 frame()->loader().checkCallImplicitClose();
3004 // We used to force a synchronous display and flush here. This really isn't
3005 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
3006 // (if your platform is syncing flushes and limiting them to 60fps).
3007 m_overMinimumLayoutThreshold = true;
3008 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
3009 updateStyleIfNeeded();
3011 // Always do a layout after loading if needed.
3012 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
3013 view()->layoutContext().layout();
3016 m_processingLoadEvent = false;
3018 if (auto* fontFaceSet = fontSelector().optionalFontFaceSet())
3019 fontFaceSet->didFirstLayout();
3021 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK)
3022 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
3023 // The AX cache may have been cleared at this point, but we need to make sure it contains an
3024 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
3025 // exists in the cache (we ignore the return value because we don't need it here). This is
3026 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
3028 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
3029 // catch new AND page history loads, and that uses AXLoadComplete
3031 axObjectCache()->getOrCreate(renderView());
3032 if (this == &topDocument())
3033 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
3035 // AXLoadComplete can only be posted on the top document, so if it's a document
3036 // in an iframe that just finished loading, post AXLayoutComplete instead.
3037 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
3042 if (svgExtensions())
3043 accessSVGExtensions().startAnimations();
3046 void Document::setParsing(bool b)
3050 if (m_bParsing && !m_sharedObjectPool)
3051 m_sharedObjectPool = makeUnique<DocumentSharedObjectPool>();
3053 if (!m_bParsing && view() && !view()->needsLayout())
3054 view()->fireLayoutRelatedMilestonesIfNeeded();
3057 bool Document::shouldScheduleLayout()
3059 if (!documentElement())
3061 if (!is<HTMLHtmlElement>(*documentElement()))
3063 if (!bodyOrFrameset())
3065 if (styleScope().hasPendingSheetsBeforeBody())
3067 if (page() && page()->chrome().client().layerFlushThrottlingIsActive() && view() && view()->isVisuallyNonEmpty())
3073 bool Document::isLayoutTimerActive()
3075 return view() && view()->layoutContext().isLayoutPending() && !minimumLayoutDelay();
3078 Seconds Document::minimumLayoutDelay()
3080 if (m_overMinimumLayoutThreshold)
3083 auto elapsed = timeSinceDocumentCreation();
3084 m_overMinimumLayoutThreshold = elapsed > settings().layoutInterval();
3086 // We'll want to schedule the timer to fire at the minimum layout threshold.
3087 return std::max(0_s, settings().layoutInterval() - elapsed);
3090 Seconds Document::timeSinceDocumentCreation() const
3092 return MonotonicTime::now() - m_documentCreationTime;
3095 ExceptionOr<void> Document::write(Document* responsibleDocument, SegmentedString&& text)
3097 if (m_activeParserWasAborted)
3100 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
3102 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
3103 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
3105 if (m_writeRecursionIsTooDeep)
3108 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
3109 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
3112 if (!hasInsertionPoint) {
3113 auto result = open(responsibleDocument);
3114 if (UNLIKELY(result.hasException()))
3115 return result.releaseException();
3119 m_parser->insert(WTFMove(text));
3123 ExceptionOr<void> Document::write(Document* responsibleDocument, Vector<String>&& strings)
3125 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
3126 return Exception { InvalidStateError };
3128 SegmentedString text;
3129 for (auto& string : strings)
3130 text.append(WTFMove(string));
3132 return write(responsibleDocument, WTFMove(text));
3135 ExceptionOr<void> Document::writeln(Document* responsibleDocument, Vector<String>&& strings)
3137 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
3138 return Exception { InvalidStateError };
3140 SegmentedString text;
3141 for (auto& string : strings)
3142 text.append(WTFMove(string));
3144 text.append("\n"_s);
3145 return write(responsibleDocument, WTFMove(text));
3148 Seconds Document::minimumDOMTimerInterval() const
3150 auto* page = this->page();
3152 return ScriptExecutionContext::minimumDOMTimerInterval();
3153 return page->settings().minimumDOMTimerInterval();
3156 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
3158 if (m_isTimerThrottlingEnabled == shouldThrottle)
3161 m_isTimerThrottlingEnabled = shouldThrottle;
3162 didChangeTimerAlignmentInterval();
3165 Seconds Document::domTimerAlignmentInterval(bool hasReachedMaxNestingLevel) const
3167 auto alignmentInterval = ScriptExecutionContext::domTimerAlignmentInterval(hasReachedMaxNestingLevel);
3168 if (!hasReachedMaxNestingLevel)
3169 return alignmentInterval;
3171 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
3172 if (m_isTimerThrottlingEnabled)
3173 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
3175 if (Page* page = this->page())
3176 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
3178 if (!topOrigin().canAccess(securityOrigin()) && !hasHadUserInteraction())
3179 alignmentInterval = std::max(alignmentInterval, DOMTimer::nonInteractedCrossOriginFrameAlignmentInterval());
3181 return alignmentInterval;
3184 EventTarget* Document::errorEventTarget()
3186 return m_domWindow.get();
3189 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
3191 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
3194 void Document::setURL(const URL& url)
3196 const URL& newURL = url.isEmpty() ? WTF::blankURL() : url;
3197 if (newURL == m_url)
3201 m_documentURI = m_url.string();
3205 void Document::updateBaseURL()
3207 URL oldBaseURL = m_baseURL;
3208 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
3209 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
3210 // from the Document interface otherwise.
3211 if (!m_baseElementURL.isEmpty())
3212 m_baseURL = m_baseElementURL;
3213 else if (!m_baseURLOverride.isEmpty())
3214 m_baseURL = m_baseURLOverride;
3216 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
3217 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
3218 // and DOM 3 Core does not specify how it should be resolved.
3219 m_baseURL = URL({ }, documentURI());
3222 clearSelectorQueryCache();
3224 if (!m_baseURL.isValid())
3228 void Document::setBaseURLOverride(const URL& url)
3230 m_baseURLOverride = url;
3234 void Document::processBaseElement()
3236 // Find the first href attribute in a base element and the first target attribute in a base element.
3237 const AtomString* href = nullptr;
3238 const AtomString* target = nullptr;
3239 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3240 for (auto& base : baseDescendants) {
3242 const AtomString& value = base.attributeWithoutSynchronization(hrefAttr);
3243 if (!value.isNull()) {
3250 const AtomString& value = base.attributeWithoutSynchronization(targetAttr);
3251 if (!value.isNull()) {
3259 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3262 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3263 if (!strippedHref.isEmpty())
3264 baseElementURL = URL(url(), strippedHref);
3266 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3267 m_baseElementURL = baseElementURL;
3271 m_baseTarget = target ? *target : nullAtom();
3274 String Document::userAgent(const URL& url) const
3276 return frame() ? frame()->loader().userAgent(url) : String();
3279 void Document::disableEval(const String& errorMessage)
3284 frame()->script().disableEval(errorMessage);
3287 void Document::disableWebAssembly(const String& errorMessage)
3292 frame()->script().disableWebAssembly(errorMessage);
3295 #if ENABLE(INDEXED_DATABASE)
3296 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
3298 if (!m_idbConnectionProxy) {
3299 Page* currentPage = page();
3302 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
3304 return m_idbConnectionProxy.get();
3308 SocketProvider* Document::socketProvider()
3310 return m_socketProvider.get();
3313 bool Document::canNavigate(Frame* targetFrame, const URL& destinationURL)
3318 // FIXME: We shouldn't call this function without a target frame, but
3319 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3320 // returning true when supplied with a 0 targetFrame.
3324 if (!canNavigateInternal(*targetFrame))
3327 if (isNavigationBlockedByThirdPartyIFrameRedirectBlocking(*targetFrame, destinationURL)) {
3328 printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation of the top-level window is cross-origin and the user has never interacted with the frame."_s);
3335 bool Document::canNavigateInternal(Frame& targetFrame)
3339 // Cases (i), (ii) and (iii) pass the tests from the specifications but might not pass the "security origin" tests.
3341 // i. A frame can navigate its top ancestor when its 'allow-top-navigation' flag is set (sometimes known as 'frame-busting').
3342 if (!isSandboxed(SandboxTopNavigation) && &targetFrame == &m_frame->tree().top())
3345 // 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.
3346 if (!isSandboxed(SandboxTopNavigationByUserActivation) && UserGestureIndicator::processingUserGesture() && &targetFrame == &m_frame->tree().top())
3349 // iii. A sandboxed frame can always navigate its descendants.
3350 if (isSandboxed(SandboxNavigation) && targetFrame.tree().isDescendantOf(m_frame))
3353 // From https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate.
3354 // 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
3355 // flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.
3356 if (m_frame != &targetFrame && isSandboxed(SandboxNavigation) && targetFrame.tree().parent() && !targetFrame.tree().isDescendantOf(m_frame)) {
3357 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."_s);
3361 // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
3362 if (m_frame != &targetFrame && &targetFrame == &m_frame->tree().top()) {
3363 bool triggeredByUserActivation = UserGestureIndicator::processingUserGesture();
3364 // 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.
3365 if (triggeredByUserActivation && isSandboxed(SandboxTopNavigationByUserActivation)) {
3366 printNavigationErrorMessage(targetFrame, url(), "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."_s);
3369 // 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.
3370 if (!triggeredByUserActivation && isSandboxed(SandboxTopNavigation)) {
3371 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set."_s);
3376 // 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
3377 // sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.
3378 if (!targetFrame.tree().parent() && m_frame != &targetFrame && &targetFrame != &m_frame->tree().top() && isSandboxed(SandboxNavigation) && targetFrame.loader().opener() != m_frame) {
3379 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is sandboxed, and is not allowed to navigate this popup."_s);
3383 // 4. Otherwise, terminate positively!
3385 // This is the normal case. A document can navigate its descendant frames,
3386 // or, more generally, a document can navigate a frame if the document is
3387 // in the same origin as any of that frame's ancestors (in the frame
3390 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3391 // historical information about this security check.
3392 if (canAccessAncestor(securityOrigin(), &targetFrame))
3395 // Top-level frames are easier to navigate than other frames because they
3396 // display their URLs in the address bar (in most browsers). However, there
3397 // are still some restrictions on navigation to avoid nuisance attacks.
3398 // Specifically, a document can navigate a top-level frame if that frame
3399 // opened the document or if the document is the same-origin with any of
3400 // the top-level frame's opener's ancestors (in the frame hierarchy).
3402 // In both of these cases, the document performing the navigation is in
3403 // some way related to the frame being navigate (e.g., by the "opener"
3404 // and/or "parent" relation). Requiring some sort of relation prevents a
3405 // document from navigating arbitrary, unrelated top-level frames.
3406 if (!targetFrame.tree().parent()) {
3407 if (&targetFrame == m_frame->loader().opener())
3410 if (canAccessAncestor(securityOrigin(), targetFrame.loader().opener()))
3414 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3418 // Prevent cross-site top-level redirects from third-party iframes unless the user has ever interacted with the frame.
3419 bool Document::isNavigationBlockedByThirdPartyIFrameRedirectBlocking(Frame& targetFrame, const URL& destinationURL)
3421 if (!settings().thirdPartyIframeRedirectBlockingEnabled())
3424 // Only prevent top frame navigations by subframes.
3425 if (m_frame == &targetFrame || &targetFrame != &m_frame->tree().top())
3428 // Only prevent navigations by subframes that the user has not interacted with.
3429 if (m_frame->hasHadUserInteraction())
3432 // Only prevent navigations by unsandboxed iframes. Such navigations by unsandboxed iframes would have already been blocked unless
3433 // "allow-top-navigation" / "allow-top-navigation-by-user-activation" was explicitly specified.
3434 if (sandboxFlags() != SandboxNone)
3437 // Only prevent navigations by third-party iframes.
3438 if (canAccessAncestor(securityOrigin(), &targetFrame))
3441 // Only prevent cross-site navigations.
3442 auto* targetDocument = targetFrame.document();
3443 if (targetDocument && (targetDocument->securityOrigin().canAccess(SecurityOrigin::create(destinationURL)) || areRegistrableDomainsEqual(targetDocument->url(), destinationURL)))
3449 void Document::didRemoveAllPendingStylesheet()
3451 if (auto* parser = scriptableDocumentParser())
3452 parser->executeScriptsWaitingForStylesheetsSoon();
3455 bool Document::usesStyleBasedEditability() const
3457 if (m_hasElementUsingStyleBasedEditability)
3460 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3461 ASSERT(!m_inStyleRecalc);
3463 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3464 styleScope.flushPendingUpdate();
3465 return styleScope.usesStyleBasedEditability();
3468 void Document::setHasElementUsingStyleBasedEditability()
3470 m_hasElementUsingStyleBasedEditability = true;
3473 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3475 ASSERT(!equiv.isNull());
3476 ASSERT(!content.isNull());
3478 HttpEquivPolicy policy = httpEquivPolicy();
3479 if (policy != HttpEquivPolicy::Enabled) {
3482 case HttpEquivPolicy::Enabled:
3483 ASSERT_NOT_REACHED();
3485 case HttpEquivPolicy::DisabledBySettings:
3486 reason = "by the embedder.";
3488 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3489 reason = "for documents with Content-Disposition: attachment.";
3492 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3493 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3497 Frame* frame = this->frame();
3498 auto* documentLoader = frame ? frame->loader().documentLoader() : nullptr;
3499 auto httpStatusCode = documentLoader ? documentLoader->response().httpStatusCode() : 0;
3501 HTTPHeaderName headerName;
3502 if (!findHTTPHeaderName(equiv, headerName))
3505 switch (headerName) {
3506 case HTTPHeaderName::DefaultStyle:
3507 // The preferred style set has been overridden as per section
3508 // 14.3.2 of the HTML4.0 specification. We need to update the
3509 // sheet used variable and then update our style selector.
3510 // For more info, see the test at:
3511 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3513 styleScope().setPreferredStylesheetSetName(content);
3516 case HTTPHeaderName::Refresh: {
3519 if (frame && parseMetaHTTPEquivRefresh(content, delay, urlString)) {
3521 if (urlString.isEmpty())
3522 completedURL = m_url;
3524 completedURL = completeURL(urlString);
3525 if (!WTF::protocolIsJavaScript(completedURL))
3526 frame->navigationScheduler().scheduleRedirect(*this, delay, completedURL);
3528 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3529 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3536 case HTTPHeaderName::SetCookie:
3537 if (isHTMLDocument())
3538 addConsoleMessage(MessageSource::Security, MessageLevel::Error, "The Set-Cookie meta tag is obsolete and was ignored. Use the HTTP header Set-Cookie or document.cookie instead."_s);
3541 case HTTPHeaderName::ContentLanguage:
3542 setContentLanguage(content);
3545 case HTTPHeaderName::XDNSPrefetchControl:
3546 parseDNSPrefetchControlHeader(content);
3549 case HTTPHeaderName::XFrameOptions:
3551 FrameLoader& frameLoader = frame->loader();
3552 unsigned long requestIdentifier = 0;
3553 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3554 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3556 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.";
3557 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3561 case HTTPHeaderName::ContentSecurityPolicy:
3562 if (isInDocumentHead)
3563 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::Enforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta, referrer(), httpStatusCode);
3566 case HTTPHeaderName::XWebKitCSP:
3567 if (isInDocumentHead)
3568 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::PrefixedEnforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta, referrer(), httpStatusCode);
3576 void Document::processDisabledAdaptations(const String& disabledAdaptationsString)
3578 auto disabledAdaptations = parseDisabledAdaptations(disabledAdaptationsString);
3579 if (m_disabledAdaptations == disabledAdaptations)
3582 m_disabledAdaptations = disabledAdaptations;
3583 dispatchDisabledAdaptationsDidChangeForMainFrame();
3586 void Document::dispatchDisabledAdaptationsDidChangeForMainFrame()
3588 if (!frame()->isMainFrame())
3594 page()->chrome().dispatchDisabledAdaptationsDidChange(m_disabledAdaptations);
3597 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3599 ASSERT(!features.isNull());
3601 LOG_WITH_STREAM(Viewports, stream << "Document::processViewport " << features);
3603 if (origin < m_viewportArguments.type)
3606 m_viewportArguments = ViewportArguments(origin);
3608 LOG_WITH_STREAM(Viewports, stream << " resolved to " << m_viewportArguments);
3610 processFeaturesString(features, FeatureMode::Viewport, [this](StringView key, StringView value) {
3611 setViewportFeature(m_viewportArguments, *this, key, value);
3614 updateViewportArguments();
3617 ViewportArguments Document::viewportArguments() const
3619 auto* page = this->page();
3621 return m_viewportArguments;
3622 return page->overrideViewportArguments().valueOr(m_viewportArguments);
3625 void Document::updateViewportArguments()
3627 if (page() && frame()->isMainFrame()) {
3629 m_didDispatchViewportPropertiesChanged = true;
3631 page()->chrome().dispatchViewportPropertiesDidChange(viewportArguments());
3632 page()->chrome().didReceiveDocType(*frame());
3636 #if ENABLE(DARK_MODE_CSS)
3637 static void processColorSchemeString(StringView colorScheme, const WTF::Function<void(StringView key)>& callback)
3639 unsigned length = colorScheme.length();
3640 for (unsigned i = 0; i < length; ) {
3641 // Skip to first non-separator.
3642 while (i < length && isHTMLSpace(colorScheme[i]))
3644 unsigned keyBegin = i;