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-2015 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 "AnimationController.h"
34 #include "AuthorStyleSheets.h"
35 #include "CDATASection.h"
36 #include "CSSFontSelector.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedResourceLoader.h"
42 #include "ChromeClient.h"
44 #include "CompositionEvent.h"
45 #include "ContentSecurityPolicy.h"
46 #include "CookieJar.h"
47 #include "CustomElementDefinitions.h"
48 #include "CustomEvent.h"
49 #include "DOMImplementation.h"
50 #include "DOMNamedFlowCollection.h"
51 #include "DOMWindow.h"
52 #include "DateComponents.h"
53 #include "DebugPageOverlays.h"
54 #include "Dictionary.h"
55 #include "DocumentLoader.h"
56 #include "DocumentMarkerController.h"
57 #include "DocumentSharedObjectPool.h"
58 #include "DocumentType.h"
60 #include "ElementIterator.h"
61 #include "EntityReference.h"
62 #include "EventHandler.h"
63 #include "ExtensionStyleSheets.h"
64 #include "FocusController.h"
65 #include "FontFaceSet.h"
66 #include "FormController.h"
67 #include "FrameLoader.h"
68 #include "FrameLoaderClient.h"
69 #include "FrameView.h"
70 #include "GenericCachedHTMLCollection.h"
71 #include "HTMLAllCollection.h"
72 #include "HTMLAnchorElement.h"
73 #include "HTMLBaseElement.h"
74 #include "HTMLBodyElement.h"
75 #include "HTMLCanvasElement.h"
76 #include "HTMLDocument.h"
77 #include "HTMLElementFactory.h"
78 #include "HTMLFormControlElement.h"
79 #include "HTMLFrameOwnerElement.h"
80 #include "HTMLFrameSetElement.h"
81 #include "HTMLHeadElement.h"
82 #include "HTMLIFrameElement.h"
83 #include "HTMLImageElement.h"
84 #include "HTMLLinkElement.h"
85 #include "HTMLMediaElement.h"
86 #include "HTMLNameCollection.h"
87 #include "HTMLParserIdioms.h"
88 #include "HTMLPictureElement.h"
89 #include "HTMLPlugInElement.h"
90 #include "HTMLScriptElement.h"
91 #include "HTMLStyleElement.h"
92 #include "HTMLTitleElement.h"
93 #include "HTMLUnknownElement.h"
94 #include "HTTPHeaderNames.h"
95 #include "HTTPParsers.h"
96 #include "HashChangeEvent.h"
98 #include "HitTestResult.h"
99 #include "IconController.h"
100 #include "ImageLoader.h"
101 #include "InspectorInstrumentation.h"
102 #include "JSLazyEventListener.h"
103 #include "JSModuleLoader.h"
104 #include "KeyboardEvent.h"
105 #include "Language.h"
106 #include "LifecycleCallbackQueue.h"
107 #include "LoaderStrategy.h"
109 #include "MainFrame.h"
110 #include "MediaCanStartListener.h"
111 #include "MediaProducer.h"
112 #include "MediaQueryList.h"
113 #include "MediaQueryMatcher.h"
114 #include "MessageEvent.h"
115 #include "MouseEventWithHitTestResults.h"
116 #include "MutationEvent.h"
117 #include "NameNodeList.h"
118 #include "NestingLevelIncrementer.h"
119 #include "NodeIterator.h"
120 #include "NodeRareData.h"
121 #include "NodeWithIndex.h"
122 #include "OverflowEvent.h"
123 #include "PageConsoleClient.h"
124 #include "PageGroup.h"
125 #include "PageTransitionEvent.h"
126 #include "PlatformLocale.h"
127 #include "PlatformMediaSessionManager.h"
128 #include "PlatformStrategies.h"
129 #include "PlugInsResources.h"
130 #include "PluginDocument.h"
131 #include "PointerLockController.h"
132 #include "PopStateEvent.h"
133 #include "ProcessingInstruction.h"
134 #include "RenderChildIterator.h"
135 #include "RenderLayerCompositor.h"
136 #include "RenderView.h"
137 #include "RenderWidget.h"
138 #include "ResourceLoadObserver.h"
139 #include "RuntimeEnabledFeatures.h"
140 #include "SVGDocumentExtensions.h"
141 #include "SVGElement.h"
142 #include "SVGElementFactory.h"
143 #include "SVGNames.h"
144 #include "SVGTitleElement.h"
145 #include "SVGZoomEvent.h"
146 #include "SchemeRegistry.h"
147 #include "ScopedEventQueue.h"
148 #include "ScriptController.h"
149 #include "ScriptRunner.h"
150 #include "ScriptSourceCode.h"
151 #include "ScrollingCoordinator.h"
152 #include "SecurityOrigin.h"
153 #include "SecurityOriginPolicy.h"
154 #include "SecurityPolicy.h"
155 #include "SegmentedString.h"
156 #include "SelectorQuery.h"
157 #include "Settings.h"
158 #include "ShadowRoot.h"
159 #include "StorageEvent.h"
160 #include "StyleProperties.h"
161 #include "StyleResolveForDocument.h"
162 #include "StyleResolver.h"
163 #include "StyleSheetContents.h"
164 #include "StyleSheetList.h"
165 #include "StyleTreeResolver.h"
166 #include "SubresourceLoader.h"
167 #include "TextEvent.h"
168 #include "TextNodeTraversal.h"
169 #include "TransformSource.h"
170 #include "TreeWalker.h"
171 #include "VisitedLinkState.h"
172 #include "WheelEvent.h"
173 #include "WindowFeatures.h"
174 #include "XMLDocument.h"
175 #include "XMLDocumentParser.h"
176 #include "XMLNSNames.h"
177 #include "XMLNames.h"
178 #include "XPathEvaluator.h"
179 #include "XPathExpression.h"
180 #include "XPathNSResolver.h"
181 #include "XPathResult.h"
182 #include "htmlediting.h"
183 #include <JavaScriptCore/Profile.h>
185 #include <inspector/ScriptCallStack.h>
186 #include <wtf/CurrentTime.h>
187 #include <wtf/NeverDestroyed.h>
188 #include <wtf/SystemTracing.h>
189 #include <wtf/TemporaryChange.h>
190 #include <wtf/text/StringBuffer.h>
191 #include <yarr/RegularExpression.h>
193 #if ENABLE(DEVICE_ORIENTATION)
194 #include "DeviceMotionEvent.h"
195 #include "DeviceOrientationEvent.h"
198 #if ENABLE(FULLSCREEN_API)
199 #include "RenderFullScreen.h"
203 #include "CSSFontSelector.h"
204 #include "DeviceMotionClientIOS.h"
205 #include "DeviceMotionController.h"
206 #include "DeviceOrientationClientIOS.h"
207 #include "DeviceOrientationController.h"
208 #include "Geolocation.h"
209 #include "Navigator.h"
210 #include "NavigatorGeolocation.h"
211 #include "WKContentObservation.h"
212 #include "WebCoreSystemInterface.h"
215 #if ENABLE(IOS_GESTURE_EVENTS)
216 #include "GestureEvent.h"
219 #if ENABLE(IOS_TEXT_AUTOSIZING)
220 #include "TextAutoSizing.h"
224 #include "MathMLElement.h"
225 #include "MathMLElementFactory.h"
226 #include "MathMLNames.h"
229 #if ENABLE(MEDIA_SESSION)
230 #include "MediaSession.h"
233 #if ENABLE(REQUEST_ANIMATION_FRAME)
234 #include "RequestAnimationFrameCallback.h"
235 #include "ScriptedAnimationController.h"
238 #if ENABLE(TEXT_AUTOSIZING)
239 #include "TextAutosizer.h"
242 #if ENABLE(TOUCH_EVENTS)
243 #include "TouchEvent.h"
244 #include "TouchList.h"
247 #if ENABLE(VIDEO_TRACK)
248 #include "CaptionUserPreferences.h"
251 #if ENABLE(WEB_REPLAY)
252 #include "WebReplayInputs.h"
253 #include <replay/EmptyInputCursor.h>
254 #include <replay/InputCursor.h>
257 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
258 #include "MediaPlaybackTargetClient.h"
262 #include "XSLTProcessor.h"
266 using namespace Unicode;
270 using namespace HTMLNames;
272 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
274 static const unsigned cMaxWriteRecursionDepth = 21;
276 // DOM Level 2 says (letters added):
278 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
279 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
280 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
281 // 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.
282 // 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.
283 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
284 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
285 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
286 // i) Characters ':' and '_' are allowed as name-start characters.
287 // j) Characters '-' and '.' are allowed as name characters.
289 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
291 static inline bool isValidNameStart(UChar32 c)
294 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
298 if (c == ':' || c == '_')
301 // rules (a) and (f) above
302 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)))
306 if (c >= 0xF900 && c < 0xFFFE)
310 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
311 if (type == U_DT_FONT || type == U_DT_COMPAT)
317 static inline bool isValidNamePart(UChar32 c)
319 // rules (a), (e), and (i) above
320 if (isValidNameStart(c))
323 // rules (g) and (h) above
324 if (c == 0x00B7 || c == 0x0387)
328 if (c == '-' || c == '.')
331 // rules (b) and (f) above
332 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
336 if (c >= 0xF900 && c < 0xFFFE)
340 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
341 if (type == U_DT_FONT || type == U_DT_COMPAT)
347 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
349 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
351 // If a Document has the address "about:blank"
352 // The origin of the Document is the origin it was assigned when its browsing context was created.
354 // Note: We generalize this to all "blank" URLs and invalid URLs because we
355 // treat all of these URLs as about:blank.
357 return url.isEmpty() || url.isBlankURL();
360 static Widget* widgetForElement(Element* focusedElement)
364 auto* renderer = focusedElement->renderer();
365 if (!is<RenderWidget>(renderer))
367 return downcast<RenderWidget>(*renderer).widget();
370 static bool acceptsEditingFocus(Node* node)
373 ASSERT(node->hasEditableStyle());
375 Node* root = node->rootEditableElement();
376 Frame* frame = node->document().frame();
380 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
383 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
385 // targetFrame can be 0 when we're trying to navigate a top-level frame
386 // that has a 0 opener.
390 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
391 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
392 Document* ancestorDocument = ancestorFrame->document();
393 // FIXME: Should be an ASSERT? Frames should alway have documents.
394 if (!ancestorDocument)
397 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
398 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
401 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
402 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
403 // something more general instead?
404 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
411 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
413 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
415 // FIXME: should we print to the console of the document performing the navigation instead?
416 frame->document()->domWindow()->printErrorMessage(message);
419 uint64_t Document::s_globalTreeVersion = 0;
421 #if ENABLE(IOS_TEXT_AUTOSIZING)
422 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
424 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
427 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
429 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
433 HashSet<Document*>& Document::allDocuments()
435 static NeverDestroyed<HashSet<Document*>> documents;
439 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
440 : ContainerNode(*this, CreateDocument)
442 #if ENABLE(IOS_TOUCH_EVENTS)
443 , m_handlingTouchEvent(false)
444 , m_touchEventRegionsDirty(false)
445 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
447 , m_referencingNodeCount(0)
448 , m_didCalculateStyleResolver(false)
449 , m_hasNodesWithPlaceholderStyle(false)
450 , m_needsNotifyRemoveAllPendingStylesheet(false)
451 , m_ignorePendingStylesheets(false)
452 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
454 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
455 , m_activeParserCount(0)
456 , m_wellFormed(false)
458 , m_paginatedForScreen(false)
459 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
460 , m_compatibilityModeLocked(false)
461 , m_textColor(Color::black)
462 , m_domTreeVersion(++s_globalTreeVersion)
464 , m_mutationObserverTypes(0)
465 , m_authorStyleSheets(std::make_unique<AuthorStyleSheets>(*this))
466 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
467 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
468 , m_visuallyOrdered(false)
469 , m_readyState(Complete)
471 , m_optimizedStyleSheetUpdateTimer(*this, &Document::optimizedStyleSheetUpdateTimerFired)
472 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
473 , m_pendingStyleRecalcShouldForce(false)
474 , m_inStyleRecalc(false)
475 , m_closeAfterStyleRecalc(false)
476 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
477 , m_frameElementsShouldIgnoreScrolling(false)
478 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
479 , m_markers(std::make_unique<DocumentMarkerController>(*this))
480 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
481 , m_cssTarget(nullptr)
482 , m_processingLoadEvent(false)
483 , m_loadEventFinished(false)
484 , m_startTime(std::chrono::steady_clock::now())
485 , m_overMinimumLayoutThreshold(false)
486 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
487 , m_moduleLoader(std::make_unique<JSModuleLoader>(*this))
488 , m_xmlVersion(ASCIILiteral("1.0"))
489 , m_xmlStandalone(StandaloneUnspecified)
490 , m_hasXMLDeclaration(false)
491 , m_designMode(inherit)
493 , m_inInvalidateNodeListAndCollectionCaches(false)
495 #if ENABLE(DASHBOARD_SUPPORT)
496 , m_hasAnnotatedRegions(false)
497 , m_annotatedRegionsDirty(false)
499 , m_createRenderers(true)
500 , m_inPageCache(false)
501 , m_accessKeyMapValid(false)
502 , m_documentClasses(documentClasses)
503 , m_isSynthesized(constructionFlags & Synthesized)
504 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
505 , m_sawElementsInKnownNamespaces(false)
506 , m_isSrcdocDocument(false)
507 , m_eventQueue(*this)
508 , m_weakFactory(this)
509 #if ENABLE(FULLSCREEN_API)
510 , m_areKeysEnabledInFullScreen(0)
511 , m_fullScreenRenderer(nullptr)
512 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
513 , m_isAnimatingFullScreen(false)
515 , m_loadEventDelayCount(0)
516 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
517 , m_referrerPolicy(ReferrerPolicyDefault)
518 , m_writeRecursionIsTooDeep(false)
519 , m_writeRecursionDepth(0)
520 , m_lastHandledUserGestureTimestamp(0)
522 #if ENABLE(DEVICE_ORIENTATION)
523 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
524 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
525 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
526 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
529 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
530 , m_isTelephoneNumberParsingAllowed(true)
532 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
533 , m_scheduledTasksAreSuspended(false)
534 , m_visualUpdatesAllowed(true)
535 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
536 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
538 , m_didDispatchViewportPropertiesChanged(false)
540 #if ENABLE(TEMPLATE_ELEMENT)
541 , m_templateDocumentHost(nullptr)
543 #if ENABLE(WEB_REPLAY)
544 , m_inputCursor(EmptyInputCursor::create())
546 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
547 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
548 , m_disabledFieldsetElementsCount(0)
549 , m_hasInjectedPlugInsScript(false)
550 , m_renderTreeBeingDestroyed(false)
551 , m_hasPreparedForDestruction(false)
552 , m_hasStyleWithViewportUnits(false)
554 allDocuments().add(this);
556 // We depend on the url getting immediately set in subframes, but we
557 // also depend on the url NOT getting immediately set in opened windows.
558 // See fast/dom/early-frame-url.html
559 // and fast/dom/location-new-window-no-crash.html, respectively.
560 // FIXME: Can/should we unify this behavior?
561 if ((frame && frame->ownerElement()) || !url.isEmpty())
564 m_cachedResourceLoader->setDocument(this);
566 #if ENABLE(TEXT_AUTOSIZING)
567 m_textAutosizer = std::make_unique<TextAutosizer>(this);
571 resetVisitedLinkColor();
572 resetActiveLinkColor();
574 initSecurityContext();
577 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
578 nodeListAndCollectionCount = 0;
581 #if ENABLE(FULLSCREEN_API)
582 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
587 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
589 } while ((owner = owner->document().ownerElement()));
594 Ref<Document> Document::create(ScriptExecutionContext& context)
596 Ref<Document> document = adoptRef(*new Document(nullptr, URL()));
597 document->setSecurityOriginPolicy(context.securityOriginPolicy());
602 Document::~Document()
604 allDocuments().remove(this);
606 ASSERT(!renderView());
607 ASSERT(!m_inPageCache);
608 ASSERT(m_ranges.isEmpty());
609 ASSERT(!m_parentTreeScope);
610 ASSERT(!m_disabledFieldsetElementsCount);
612 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
613 m_deviceMotionClient->deviceMotionControllerDestroyed();
614 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
617 #if ENABLE(TEMPLATE_ELEMENT)
618 if (m_templateDocument)
619 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
622 // FIXME: Should we reset m_domWindow when we detach from the Frame?
624 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
626 m_scriptRunner = nullptr;
627 m_moduleLoader = nullptr;
629 removeAllEventListeners();
631 // Currently we believe that Document can never outlive the parser.
632 // Although the Document may be replaced synchronously, DocumentParsers
633 // generally keep at least one reference to an Element which would in turn
634 // has a reference to the Document. If you hit this ASSERT, then that
635 // assumption is wrong. DocumentParser::detach() should ensure that even
636 // if the DocumentParser outlives the Document it won't cause badness.
637 ASSERT(!m_parser || m_parser->refCount() == 1);
640 if (this == &topDocument())
641 clearAXObjectCache();
645 if (m_styleSheetList)
646 m_styleSheetList->detachFromDocument();
649 m_elementSheet->detachFromDocument();
650 extensionStyleSheets().detachFromDocument();
652 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
654 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
655 // load the initial empty document and the SVGDocument with the same DocumentLoader).
656 if (m_cachedResourceLoader->document() == this)
657 m_cachedResourceLoader->setDocument(nullptr);
660 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
661 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
664 // We must call clearRareData() here since a Document class inherits TreeScope
665 // as well as Node. See a comment on TreeScope.h for the reason.
669 ASSERT(!m_listsInvalidatedAtDocument.size());
670 ASSERT(!m_collectionsInvalidatedAtDocument.size());
672 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
673 ASSERT(!m_nodeListAndCollectionCounts[i]);
676 void Document::removedLastRef()
678 ASSERT(!m_deletionHasBegun);
679 if (m_referencingNodeCount) {
680 // If removing a child removes the last node reference, we don't want the scope to be destroyed
681 // until after removeDetachedChildren returns, so we protect ourselves.
682 incrementReferencingNodeCount();
684 // We must make sure not to be retaining any of our children through
685 // these extra pointers or we will create a reference cycle.
686 m_focusedElement = nullptr;
687 m_hoveredElement = nullptr;
688 m_activeElement = nullptr;
689 m_titleElement = nullptr;
690 m_documentElement = nullptr;
691 m_userActionElements.documentDidRemoveLastRef();
692 #if ENABLE(FULLSCREEN_API)
693 m_fullScreenElement = nullptr;
694 m_fullScreenElementStack.clear();
699 // removeDetachedChildren() doesn't always unregister IDs,
700 // so tear down scope information up front to avoid having
701 // stale references in the map.
703 destroyTreeScopeData();
704 removeDetachedChildren();
705 m_formController = nullptr;
709 m_cssCanvasElements.clear();
714 // We need to do this right now since selfOnlyDeref() can delete this.
715 m_inRemovedLastRefFunction = false;
717 decrementReferencingNodeCount();
720 m_inRemovedLastRefFunction = false;
721 m_deletionHasBegun = true;
727 void Document::commonTeardown()
730 accessSVGExtensions().pauseAnimations();
732 #if ENABLE(REQUEST_ANIMATION_FRAME)
733 clearScriptedAnimationController();
737 Element* Document::getElementByAccessKey(const String& key)
741 if (!m_accessKeyMapValid) {
742 buildAccessKeyMap(this);
743 m_accessKeyMapValid = true;
745 return m_elementsByAccessKey.get(key.impl());
748 void Document::buildAccessKeyMap(TreeScope* scope)
751 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
752 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
753 if (!accessKey.isEmpty())
754 m_elementsByAccessKey.set(accessKey.impl(), &element);
756 if (ShadowRoot* root = element.shadowRoot())
757 buildAccessKeyMap(root);
761 void Document::invalidateAccessKeyMap()
763 m_accessKeyMapValid = false;
764 m_elementsByAccessKey.clear();
767 void Document::addImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
769 return m_imagesByUsemap.add(name, element, *this);
772 void Document::removeImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
774 return m_imagesByUsemap.remove(name, element);
777 HTMLImageElement* Document::imageElementByCaseFoldedUsemap(const AtomicStringImpl& name) const
779 return m_imagesByUsemap.getElementByCaseFoldedUsemap(name, *this);
782 SelectorQuery* Document::selectorQueryForString(const String& selectorString, ExceptionCode& ec)
784 if (selectorString.isEmpty()) {
789 if (!m_selectorQueryCache)
790 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
791 return m_selectorQueryCache->add(selectorString, *this, ec);
794 void Document::clearSelectorQueryCache()
796 m_selectorQueryCache = nullptr;
799 MediaQueryMatcher& Document::mediaQueryMatcher()
801 if (!m_mediaQueryMatcher)
802 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
803 return *m_mediaQueryMatcher;
806 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
808 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
810 bool wasInQuirksMode = inQuirksMode();
811 m_compatibilityMode = mode;
813 clearSelectorQueryCache();
815 if (inQuirksMode() != wasInQuirksMode) {
816 // All user stylesheets have to reparse using the different mode.
817 extensionStyleSheets().clearPageUserSheet();
818 extensionStyleSheets().invalidateInjectedStyleSheetCache();
822 String Document::compatMode() const
824 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
827 void Document::resetLinkColor()
829 m_linkColor = Color(0, 0, 238);
832 void Document::resetVisitedLinkColor()
834 m_visitedLinkColor = Color(85, 26, 139);
837 void Document::resetActiveLinkColor()
839 m_activeLinkColor.setNamedColor("red");
842 DOMImplementation& Document::implementation()
844 if (!m_implementation)
845 m_implementation = std::make_unique<DOMImplementation>(*this);
846 return *m_implementation;
849 bool Document::hasManifest() const
851 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->fastHasAttribute(manifestAttr);
854 DocumentType* Document::doctype() const
856 for (Node* node = firstChild(); node; node = node->nextSibling()) {
857 if (node->isDocumentTypeNode())
858 return static_cast<DocumentType*>(node);
863 void Document::childrenChanged(const ChildChange& change)
865 ContainerNode::childrenChanged(change);
868 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
869 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
870 // otherwise, we need to detect the doc type changes before updating the viewport.
871 if (Page* page = this->page())
872 page->chrome().didReceiveDocType(frame());
875 Element* newDocumentElement = childrenOfType<Element>(*this).first();
876 if (newDocumentElement == m_documentElement)
878 m_documentElement = newDocumentElement;
879 // The root style used for media query matching depends on the document element.
880 clearStyleResolver();
883 static RefPtr<Element> createHTMLElementWithNameValidation(Document& document, const AtomicString& localName, ExceptionCode& ec)
885 RefPtr<HTMLElement> element = HTMLElementFactory::createKnownElement(localName, document);
889 #if ENABLE(CUSTOM_ELEMENTS)
890 auto* definitions = document.customElementDefinitions();
891 if (UNLIKELY(definitions)) {
892 if (auto* interface = definitions->findInterface(localName))
893 return interface->constructElement(localName, JSCustomElementInterface::ShouldClearException::DoNotClear);
897 if (UNLIKELY(!Document::isValidName(localName))) {
898 ec = INVALID_CHARACTER_ERR;
902 return HTMLUnknownElement::create(QualifiedName(nullAtom, localName, xhtmlNamespaceURI), document);
905 RefPtr<Element> Document::createElementForBindings(const AtomicString& name, ExceptionCode& ec)
907 if (isHTMLDocument())
908 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase(), ec);
910 if (isXHTMLDocument())
911 return createHTMLElementWithNameValidation(*this, name, ec);
913 if (!isValidName(name)) {
914 ec = INVALID_CHARACTER_ERR;
918 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
921 Ref<DocumentFragment> Document::createDocumentFragment()
923 return DocumentFragment::create(document());
926 Ref<Text> Document::createTextNode(const String& data)
928 return Text::create(*this, data);
931 Ref<Comment> Document::createComment(const String& data)
933 return Comment::create(*this, data);
936 RefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
938 if (isHTMLDocument()) {
939 ec = NOT_SUPPORTED_ERR;
942 return CDATASection::create(*this, data);
945 RefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
947 if (!isValidName(target)) {
948 ec = INVALID_CHARACTER_ERR;
952 if (data.contains("?>")) {
953 ec = INVALID_CHARACTER_ERR;
957 return ProcessingInstruction::create(*this, target, data);
960 RefPtr<EntityReference> Document::createEntityReference(const String&, ExceptionCode& ec)
962 ec = NOT_SUPPORTED_ERR;
966 Ref<Text> Document::createEditingTextNode(const String& text)
968 return Text::createEditingText(*this, text);
971 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
973 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
974 return *propertySet->ensureCSSStyleDeclaration();
977 RefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
980 ec = NOT_SUPPORTED_ERR;
984 switch (importedNode->nodeType()) {
985 case DOCUMENT_FRAGMENT_NODE:
986 if (importedNode->isShadowRoot())
991 case CDATA_SECTION_NODE:
992 case PROCESSING_INSTRUCTION_NODE:
994 return importedNode->cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
997 // FIXME: This will "Attr::normalize" child nodes of Attr.
998 return Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(*importedNode).name(), nullAtom), downcast<Attr>(*importedNode).value());
1000 case DOCUMENT_NODE: // Can't import a document into another document.
1001 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
1005 ec = NOT_SUPPORTED_ERR;
1010 RefPtr<Node> Document::adoptNode(Node* source, ExceptionCode& ec)
1013 ec = NOT_SUPPORTED_ERR;
1017 EventQueueScope scope;
1019 switch (source->nodeType()) {
1021 ec = NOT_SUPPORTED_ERR;
1023 case ATTRIBUTE_NODE: {
1024 Attr& attr = downcast<Attr>(*source);
1025 if (attr.ownerElement())
1026 attr.ownerElement()->removeAttributeNode(&attr, ec);
1030 if (source->isShadowRoot()) {
1031 // ShadowRoot cannot disconnect itself from the host node.
1032 ec = HIERARCHY_REQUEST_ERR;
1035 if (is<HTMLFrameOwnerElement>(*source)) {
1036 HTMLFrameOwnerElement& frameOwnerElement = downcast<HTMLFrameOwnerElement>(*source);
1037 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1038 ec = HIERARCHY_REQUEST_ERR;
1042 if (source->parentNode()) {
1043 source->parentNode()->removeChild(*source, ec);
1049 adoptIfNeeded(source);
1054 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1056 // These checks are from DOM Core Level 2, createElementNS
1057 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1058 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1060 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1063 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1064 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1065 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1066 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1067 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1068 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1071 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1073 return hasValidNamespaceForElements(qName);
1076 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1078 #if ENABLE(CUSTOM_ELEMENTS)
1079 auto* definitions = document.customElementDefinitions();
1080 if (UNLIKELY(definitions)) {
1081 if (auto* interface = definitions->findInterface(name)) {
1082 Ref<HTMLElement> element = HTMLElement::create(name, document);
1083 element->setIsCustomElement(); // Pre-upgrade element is still considered a custom element.
1084 LifecycleCallbackQueue::enqueueElementUpgrade(element.get(), *interface);
1089 return HTMLUnknownElement::create(name, document);
1092 // FIXME: This should really be in a possible ElementFactory class.
1093 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1095 RefPtr<Element> element;
1097 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1098 if (name.namespaceURI() == xhtmlNamespaceURI) {
1099 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1100 if (UNLIKELY(!element))
1101 element = createFallbackHTMLElement(*this, name);
1102 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1103 element = SVGElementFactory::createElement(name, *this, createdByParser);
1105 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1106 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1110 m_sawElementsInKnownNamespaces = true;
1112 element = Element::create(name, document());
1114 // <image> uses imgTag so we need a special rule.
1115 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1117 return element.releaseNonNull();
1120 bool Document::cssRegionsEnabled() const
1122 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1125 bool Document::cssCompositingEnabled() const
1127 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1130 #if ENABLE(CSS_REGIONS)
1132 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1134 if (!cssRegionsEnabled() || !renderView())
1137 updateStyleIfNeeded();
1139 return namedFlows().createCSSOMSnapshot();
1144 NamedFlowCollection& Document::namedFlows()
1147 m_namedFlows = NamedFlowCollection::create(this);
1149 return *m_namedFlows;
1152 RefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1154 String prefix, localName;
1155 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1158 QualifiedName qName(prefix, localName, namespaceURI);
1159 if (!hasValidNamespaceForElements(qName)) {
1164 return createElement(qName, false);
1167 String Document::readyState() const
1169 static NeverDestroyed<const String> loading(ASCIILiteral("loading"));
1170 static NeverDestroyed<const String> interactive(ASCIILiteral("interactive"));
1171 static NeverDestroyed<const String> complete(ASCIILiteral("complete"));
1173 switch (m_readyState) {
1182 ASSERT_NOT_REACHED();
1186 void Document::setReadyState(ReadyState readyState)
1188 if (readyState == m_readyState)
1191 #if ENABLE(WEB_TIMING)
1192 switch (readyState) {
1194 if (!m_documentTiming.domLoading)
1195 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1198 if (!m_documentTiming.domInteractive)
1199 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1202 if (!m_documentTiming.domComplete)
1203 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1208 m_readyState = readyState;
1209 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1211 if (settings() && settings()->suppressesIncrementalRendering())
1212 setVisualUpdatesAllowed(readyState);
1215 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1217 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1218 switch (readyState) {
1220 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1221 ASSERT(m_visualUpdatesAllowed);
1222 setVisualUpdatesAllowed(false);
1225 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1228 if (m_visualUpdatesSuppressionTimer.isActive()) {
1229 ASSERT(!m_visualUpdatesAllowed);
1231 if (!view()->visualUpdatesAllowedByClient())
1234 setVisualUpdatesAllowed(true);
1236 ASSERT(m_visualUpdatesAllowed);
1241 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1243 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1246 m_visualUpdatesAllowed = visualUpdatesAllowed;
1248 if (visualUpdatesAllowed)
1249 m_visualUpdatesSuppressionTimer.stop();
1251 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1253 if (!visualUpdatesAllowed)
1256 FrameView* frameView = view();
1257 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1261 if (Page* page = this->page()) {
1262 if (frame()->isMainFrame()) {
1263 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1264 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1265 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1270 view()->updateCompositingLayersAfterLayout();
1272 if (RenderView* renderView = this->renderView())
1273 renderView->repaintViewAndCompositedLayers();
1275 if (Frame* frame = this->frame())
1276 frame->loader().forcePageTransitionIfNeeded();
1279 void Document::visualUpdatesSuppressionTimerFired()
1281 ASSERT(!m_visualUpdatesAllowed);
1283 // If the client is extending the visual update suppression period explicitly, the
1284 // watchdog should not re-enable visual updates itself, but should wait for the client.
1285 if (!view()->visualUpdatesAllowedByClient())
1288 setVisualUpdatesAllowed(true);
1291 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1293 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1294 // both of which we can determine by looking at the timer.
1296 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1297 setVisualUpdatesAllowed(true);
1300 String Document::characterSetWithUTF8Fallback() const
1302 AtomicString name = encoding();
1305 return UTF8Encoding().domName();
1308 String Document::defaultCharset() const
1310 if (Settings* settings = this->settings())
1311 return settings->defaultTextEncodingName();
1312 return UTF8Encoding().domName();
1315 void Document::setCharset(const String& charset)
1319 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1322 void Document::setContentLanguage(const String& language)
1324 if (m_contentLanguage == language)
1326 m_contentLanguage = language;
1328 // Recalculate style so language is used when selecting the initial font.
1329 styleResolverChanged(DeferRecalcStyle);
1332 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1334 if (!implementation().hasFeature("XML", String())) {
1335 ec = NOT_SUPPORTED_ERR;
1339 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1340 ec = NOT_SUPPORTED_ERR;
1344 m_xmlVersion = version;
1347 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1349 if (!implementation().hasFeature("XML", String())) {
1350 ec = NOT_SUPPORTED_ERR;
1354 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1357 void Document::setDocumentURI(const String& uri)
1359 // This property is read-only from JavaScript, but writable from Objective-C.
1360 m_documentURI = uri;
1364 void Document::setContent(const String& content)
1367 // FIXME: This should probably use insert(), but that's (intentionally)
1368 // not implemented for the XML parser as it's normally synonymous with
1369 // document.write(). append() will end up yielding, but close() will
1370 // pump the tokenizer syncrhonously and finish the parse.
1371 m_parser->append(content.impl());
1375 String Document::suggestedMIMEType() const
1377 if (isXHTMLDocument())
1378 return ASCIILiteral("application/xhtml+xml");
1379 if (isSVGDocument())
1380 return ASCIILiteral("image/svg+xml");
1381 if (xmlStandalone())
1382 return ASCIILiteral("text/xml");
1383 if (isHTMLDocument())
1384 return ASCIILiteral("text/html");
1385 if (DocumentLoader* loader = this->loader())
1386 return loader->responseMIMEType();
1390 void Document::overrideMIMEType(const String& mimeType)
1392 m_overriddenMIMEType = mimeType;
1395 String Document::contentType() const
1397 if (!m_overriddenMIMEType.isNull())
1398 return m_overriddenMIMEType;
1400 if (DocumentLoader* documentLoader = loader())
1401 return documentLoader->currentContentType();
1403 String mimeType = suggestedMIMEType();
1404 if (!mimeType.isNull())
1407 return ASCIILiteral("application/xml");
1410 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1412 if (!frame() || !view())
1415 Frame& frame = *this->frame();
1417 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1419 LayoutPoint contentsPoint = clientPoint;
1420 contentsPoint.scale(scaleFactor, scaleFactor);
1421 contentsPoint.moveBy(view()->contentsScrollPosition());
1423 LayoutRect visibleRect;
1425 visibleRect = view()->unobscuredContentRect();
1427 visibleRect = view()->visibleContentRect();
1429 if (!visibleRect.contains(contentsPoint))
1432 HitTestResult result(contentsPoint);
1433 renderView()->hitTest(HitTestRequest(), result);
1436 *localPoint = result.localPoint();
1438 return result.innerNode();
1441 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1443 if (!hasLivingRenderTree())
1446 Node* node = nodeFromPoint(clientPoint);
1447 while (node && !is<Element>(*node))
1448 node = node->parentNode();
1451 node = ancestorInThisScope(node);
1453 return downcast<Element>(node);
1456 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1458 return caretRangeFromPoint(LayoutPoint(x, y));
1461 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1463 if (!hasLivingRenderTree())
1466 LayoutPoint localPoint;
1467 Node* node = nodeFromPoint(clientPoint, &localPoint);
1471 Node* shadowAncestorNode = ancestorInThisScope(node);
1472 if (shadowAncestorNode != node) {
1473 unsigned offset = shadowAncestorNode->computeNodeIndex();
1474 ContainerNode* container = shadowAncestorNode->parentNode();
1475 return Range::create(*this, container, offset, container, offset);
1478 RenderObject* renderer = node->renderer();
1481 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1482 if (visiblePosition.isNull())
1485 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1486 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1489 Element* Document::scrollingElement()
1491 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1492 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1498 * Performs three operations:
1499 * 1. Convert control characters to spaces
1500 * 2. Trim leading and trailing spaces
1501 * 3. Collapse internal whitespace.
1503 template <typename CharacterType>
1504 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1506 const String& title = titleWithDirection.string();
1507 const CharacterType* characters = title.characters<CharacterType>();
1508 unsigned length = title.length();
1511 StringBuffer<CharacterType> buffer(length);
1512 unsigned builderIndex = 0;
1514 // Skip leading spaces and leading characters that would convert to spaces
1515 for (i = 0; i < length; ++i) {
1516 CharacterType c = characters[i];
1517 if (!(c <= 0x20 || c == 0x7F))
1522 return StringWithDirection();
1524 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1525 bool previousCharWasWS = false;
1526 for (; i < length; ++i) {
1527 CharacterType c = characters[i];
1528 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1529 if (previousCharWasWS)
1531 buffer[builderIndex++] = ' ';
1532 previousCharWasWS = true;
1534 buffer[builderIndex++] = c;
1535 previousCharWasWS = false;
1539 // Strip trailing spaces
1540 while (builderIndex > 0) {
1542 if (buffer[builderIndex] != ' ')
1546 if (!builderIndex && buffer[builderIndex] == ' ')
1547 return StringWithDirection();
1549 buffer.shrink(builderIndex + 1);
1551 // Replace the backslashes with currency symbols if the encoding requires it.
1552 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1554 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1557 void Document::updateTitle(const StringWithDirection& title)
1559 if (m_rawTitle == title)
1564 if (m_rawTitle.string().isEmpty())
1565 m_title = StringWithDirection();
1567 if (m_rawTitle.string().is8Bit())
1568 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1570 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1572 if (DocumentLoader* loader = this->loader())
1573 loader->setTitle(m_title);
1576 void Document::updateTitleFromTitleElement()
1578 if (!m_titleElement) {
1579 updateTitle(StringWithDirection());
1583 if (is<HTMLTitleElement>(*m_titleElement))
1584 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1585 else if (is<SVGTitleElement>(*m_titleElement)) {
1586 // FIXME: does SVG have a title text direction?
1587 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1591 void Document::setTitle(const String& title)
1593 if (!isHTMLDocument() && !isXHTMLDocument())
1594 m_titleElement = nullptr;
1595 else if (!m_titleElement) {
1596 auto* headElement = head();
1599 m_titleElement = createElement(titleTag, false);
1600 headElement->appendChild(*m_titleElement, ASSERT_NO_EXCEPTION);
1603 // The DOM API has no method of specifying direction, so assume LTR.
1604 updateTitle(StringWithDirection(title, LTR));
1606 if (is<HTMLTitleElement>(m_titleElement.get()))
1607 downcast<HTMLTitleElement>(*m_titleElement).setText(title);
1610 void Document::updateTitleElement(Element* newTitleElement)
1612 // Only allow the first title element in tree order to change the title -- others have no effect.
1613 if (m_titleElement) {
1614 if (isHTMLDocument() || isXHTMLDocument())
1615 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1616 else if (isSVGDocument())
1617 m_titleElement = descendantsOfType<SVGTitleElement>(*this).first();
1619 m_titleElement = newTitleElement;
1621 updateTitleFromTitleElement();
1624 void Document::titleElementAdded(Element& titleElement)
1626 if (m_titleElement == &titleElement)
1629 updateTitleElement(&titleElement);
1632 void Document::titleElementRemoved(Element& titleElement)
1634 if (m_titleElement != &titleElement)
1637 updateTitleElement(nullptr);
1640 void Document::titleElementTextChanged(Element& titleElement)
1642 if (m_titleElement != &titleElement)
1645 updateTitleFromTitleElement();
1648 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1650 m_visibilityStateCallbackElements.add(element);
1653 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1655 m_visibilityStateCallbackElements.remove(element);
1658 void Document::visibilityStateChanged()
1660 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1661 for (auto* element : m_visibilityStateCallbackElements)
1662 element->visibilityStateChanged();
1665 PageVisibilityState Document::pageVisibilityState() const
1667 // The visibility of the document is inherited from the visibility of the
1668 // page. If there is no page associated with the document, we will assume
1669 // that the page is hidden, as specified by the spec:
1670 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1671 if (!m_frame || !m_frame->page())
1672 return PageVisibilityStateHidden;
1673 return m_frame->page()->visibilityState();
1676 String Document::visibilityState() const
1678 return pageVisibilityStateString(pageVisibilityState());
1681 bool Document::hidden() const
1683 return pageVisibilityState() != PageVisibilityStateVisible;
1688 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1690 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1693 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1695 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1698 void Document::allowsMediaDocumentInlinePlaybackChanged()
1700 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1701 element->allowsMediaDocumentInlinePlaybackChanged();
1705 String Document::nodeName() const
1710 Node::NodeType Document::nodeType() const
1712 return DOCUMENT_NODE;
1715 FormController& Document::formController()
1717 if (!m_formController)
1718 m_formController = std::make_unique<FormController>();
1719 return *m_formController;
1722 Vector<String> Document::formElementsState() const
1724 if (!m_formController)
1725 return Vector<String>();
1726 return m_formController->formElementsState();
1729 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1731 if (!stateVector.size() && !m_formController)
1733 formController().setStateForNewFormElements(stateVector);
1736 FrameView* Document::view() const
1738 return m_frame ? m_frame->view() : nullptr;
1741 Page* Document::page() const
1743 return m_frame ? m_frame->page() : nullptr;
1746 Settings* Document::settings() const
1748 return m_frame ? &m_frame->settings() : nullptr;
1751 Ref<Range> Document::createRange()
1753 return Range::create(*this);
1756 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1758 return createNodeIterator(root, whatToShow, WTFMove(filter), ec);
1761 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1767 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1770 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1772 return createNodeIterator(root, whatToShow, nullptr, ec);
1775 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionCode& ec)
1777 return createNodeIterator(root, 0xFFFFFFFF, nullptr, ec);
1780 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1782 return createTreeWalker(root, whatToShow, WTFMove(filter), ec);
1785 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1791 return TreeWalker::create(*root, whatToShow, WTFMove(filter));
1794 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1796 return createTreeWalker(root, whatToShow, nullptr, ec);
1799 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionCode& ec)
1801 return createTreeWalker(root, 0xFFFFFFFF, nullptr, ec);
1804 void Document::scheduleForcedStyleRecalc()
1806 m_pendingStyleRecalcShouldForce = true;
1807 scheduleStyleRecalc();
1810 void Document::scheduleStyleRecalc()
1812 if (m_styleRecalcTimer.isActive() || inPageCache())
1815 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1817 // FIXME: Why on earth is this here? This is clearly misplaced.
1818 invalidateAccessKeyMap();
1820 m_styleRecalcTimer.startOneShot(0);
1822 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1825 void Document::unscheduleStyleRecalc()
1827 ASSERT(!childNeedsStyleRecalc());
1829 m_styleRecalcTimer.stop();
1830 m_pendingStyleRecalcShouldForce = false;
1833 bool Document::hasPendingStyleRecalc() const
1835 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1838 bool Document::hasPendingForcedStyleRecalc() const
1840 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1843 void Document::recalcStyle(Style::Change change)
1845 ASSERT(!view() || !view()->isPainting());
1847 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1851 FrameView& frameView = m_renderView->frameView();
1852 Ref<FrameView> protect(frameView);
1853 if (frameView.isPainting())
1856 if (m_inStyleRecalc)
1857 return; // Guard against re-entrancy. -dwh
1859 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1861 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1862 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1864 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1865 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1866 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1867 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1868 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1869 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1871 authorStyleSheets().flushPendingUpdates();
1873 frameView.willRecalcStyle();
1875 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1877 // FIXME: We never reset this flags.
1878 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1879 authorStyleSheets().setUsesRemUnit(true);
1880 // We don't call setUsesStyleBasedEditability here because the whole point of the flag is to avoid style recalc.
1881 // i.e. updating the flag here would be too late.
1883 m_inStyleRecalc = true;
1884 bool updatedCompositingLayers = false;
1886 Style::PostResolutionCallbackDisabler disabler(*this);
1887 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1889 if (m_pendingStyleRecalcShouldForce)
1890 change = Style::Force;
1892 if (change == Style::Force) {
1893 // This may get set again during style resolve.
1894 m_hasNodesWithPlaceholderStyle = false;
1896 auto documentStyle = Style::resolveForDocument(*this);
1898 // Inserting the pictograph font at the end of the font fallback list is done by the
1899 // font selector, so set a font selector if needed.
1900 if (Settings* settings = this->settings()) {
1901 if (settings->fontFallbackPrefersPictographs())
1902 documentStyle.get().fontCascade().update(&fontSelector());
1905 auto documentChange = Style::determineChange(documentStyle.get(), m_renderView->style());
1906 if (documentChange != Style::NoChange)
1907 renderView()->setStyle(WTFMove(documentStyle));
1910 Style::TreeResolver resolver(*this);
1911 resolver.resolve(change);
1913 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1915 clearNeedsStyleRecalc();
1916 clearChildNeedsStyleRecalc();
1917 unscheduleStyleRecalc();
1919 m_inStyleRecalc = false;
1922 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1923 if (m_closeAfterStyleRecalc) {
1924 m_closeAfterStyleRecalc = false;
1928 ++m_styleRecalcCount;
1930 InspectorInstrumentation::didRecalculateStyle(cookie);
1932 // Some animated images may now be inside the viewport due to style recalc,
1933 // resume them if necessary if there is no layout pending. Otherwise, we'll
1934 // check if they need to be resumed after layout.
1935 if (updatedCompositingLayers && !frameView.needsLayout())
1936 frameView.viewportContentsChanged();
1938 if (!frameView.needsLayout())
1939 frameView.frame().selection().updateAppearanceAfterLayout();
1941 // As a result of the style recalculation, the currently hovered element might have been
1942 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1943 // to check if any other elements ended up under the mouse pointer due to re-layout.
1944 if (m_hoveredElement && !m_hoveredElement->renderer())
1945 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1948 void Document::updateStyleIfNeeded()
1950 ASSERT(isMainThread());
1951 ASSERT(!view() || !view()->isPainting());
1953 if (!view() || view()->isInLayout())
1956 if (m_optimizedStyleSheetUpdateTimer.isActive())
1957 styleResolverChanged(RecalcStyleIfNeeded);
1959 if (!needsStyleRecalc())
1962 recalcStyle(Style::NoChange);
1965 void Document::updateLayout()
1967 ASSERT(isMainThread());
1969 FrameView* frameView = view();
1970 if (frameView && frameView->isInLayout()) {
1971 // View layout should not be re-entrant.
1972 ASSERT_NOT_REACHED();
1976 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1978 if (HTMLFrameOwnerElement* owner = ownerElement())
1979 owner->document().updateLayout();
1981 updateStyleIfNeeded();
1983 StackStats::LayoutCheckPoint layoutCheckPoint;
1985 // Only do a layout if changes have occurred that make it necessary.
1986 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1987 frameView->layout();
1990 // FIXME: This is a bad idea and needs to be removed eventually.
1991 // Other browsers load stylesheets before they continue parsing the web page.
1992 // Since we don't, we can run JavaScript code that needs answers before the
1993 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1994 // lets us get reasonable answers. The long term solution to this problem is
1995 // to instead suspend JavaScript execution.
1996 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1998 bool oldIgnore = m_ignorePendingStylesheets;
2000 if (!haveStylesheetsLoaded()) {
2001 m_ignorePendingStylesheets = true;
2002 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
2003 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
2004 // with accurate style information. (Our suppression involves blanking the whole page at the
2005 // moment. If it were more refined, we might be able to do something better.)
2006 // It's worth noting though that this entire method is a hack, since what we really want to do is
2007 // suspend JS instead of doing a layout with inaccurate information.
2008 HTMLElement* bodyElement = bodyOrFrameset();
2009 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
2010 m_pendingSheetLayout = DidLayoutWithPendingSheets;
2011 styleResolverChanged(RecalcStyleImmediately);
2012 } else if (m_hasNodesWithPlaceholderStyle)
2013 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
2014 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
2015 // but here we need up-to-date style immediately.
2016 recalcStyle(Style::Force);
2021 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
2022 view()->flushAnyPendingPostLayoutTasks();
2024 m_ignorePendingStylesheets = oldIgnore;
2027 Ref<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, RenderStyle* parentStyle)
2029 ASSERT(&element.document() == this);
2031 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
2032 ResourceLoadSuspender suspender;
2034 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
2035 auto elementStyle = element.resolveStyle(parentStyle);
2037 Style::commitRelationsToDocument(WTFMove(elementStyle.relations));
2039 return WTFMove(elementStyle.renderStyle);
2042 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2044 ASSERT(isMainThread());
2046 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2047 if (!haveStylesheetsLoaded()) {
2048 updateLayoutIgnorePendingStylesheets();
2052 // Check for re-entrancy and assert (same code that is in updateLayout()).
2053 FrameView* frameView = view();
2054 if (frameView && frameView->isInLayout()) {
2055 // View layout should not be re-entrant.
2056 ASSERT_NOT_REACHED();
2060 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2062 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2064 bool requireFullLayout = false;
2065 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2066 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2067 requireFullLayout = true;
2070 updateStyleIfNeeded();
2072 RenderObject* renderer = element.renderer();
2073 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2074 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2075 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2076 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2077 requireFullLayout = true;
2080 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2081 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2082 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2083 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2085 if (!requireFullLayout) {
2086 RenderBox* previousBox = nullptr;
2087 RenderBox* currentBox = nullptr;
2089 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2090 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2092 // Require the entire container chain to be boxes.
2093 if (!is<RenderBox>(currRenderer)) {
2094 requireFullLayout = true;
2098 previousBox = currentBox;
2099 currentBox = downcast<RenderBox>(currRenderer);
2101 // If a box needs layout for itself or if a box has changed children and sizes its width to
2102 // its content, then require a full layout.
2103 if (currentBox->selfNeedsLayout() ||
2104 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2105 requireFullLayout = true;
2109 // If a block contains floats and the child's height isn't specified, then
2110 // give up also, since our height could end up being influenced by the floats.
2111 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2112 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2113 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2114 requireFullLayout = true;
2119 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2120 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2121 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2122 // Disallow regions/columns from having the optimization.
2123 // Give up if the writing mode changes at all in the containing block chain.
2124 requireFullLayout = true;
2128 if (currRenderer == frameView->layoutRoot())
2133 StackStats::LayoutCheckPoint layoutCheckPoint;
2135 // Only do a layout if changes have occurred that make it necessary.
2136 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2137 frameView->layout();
2139 return requireFullLayout;
2142 bool Document::isPageBoxVisible(int pageIndex)
2144 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
2145 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2148 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2150 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
2152 int width = pageSize.width();
2153 int height = pageSize.height();
2154 switch (style->pageSizeType()) {
2155 case PAGE_SIZE_AUTO:
2157 case PAGE_SIZE_AUTO_LANDSCAPE:
2159 std::swap(width, height);
2161 case PAGE_SIZE_AUTO_PORTRAIT:
2163 std::swap(width, height);
2165 case PAGE_SIZE_RESOLVED: {
2166 LengthSize size = style->pageSize();
2167 ASSERT(size.width().isFixed());
2168 ASSERT(size.height().isFixed());
2169 width = valueForLength(size.width(), 0);
2170 height = valueForLength(size.height(), 0);
2174 ASSERT_NOT_REACHED();
2176 pageSize = IntSize(width, height);
2178 // The percentage is calculated with respect to the width even for margin top and bottom.
2179 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2180 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2181 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2182 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2183 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2186 void Document::createStyleResolver()
2188 m_styleResolver = std::make_unique<StyleResolver>(*this);
2189 m_styleResolver->appendAuthorStyleSheets(authorStyleSheets().activeStyleSheets());
2192 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2194 if (!m_userAgentShadowTreeStyleResolver) {
2195 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2197 // FIXME: Filter out shadow pseudo elements we don't want to expose to authors.
2198 auto& documentAuthorStyle = *ensureStyleResolver().ruleSets().authorStyle();
2199 if (documentAuthorStyle.hasShadowPseudoElementRules())
2200 m_userAgentShadowTreeStyleResolver->ruleSets().authorStyle()->copyShadowPseudoElementRulesFrom(documentAuthorStyle);
2203 return *m_userAgentShadowTreeStyleResolver;
2206 void Document::fontsNeedUpdate(FontSelector&)
2208 if (m_styleResolver)
2209 m_styleResolver->invalidateMatchedPropertiesCache();
2210 if (inPageCache() || !renderView())
2212 scheduleForcedStyleRecalc();
2215 CSSFontSelector& Document::fontSelector()
2217 if (!m_fontSelector) {
2218 m_fontSelector = CSSFontSelector::create(*this);
2219 m_fontSelector->registerForInvalidationCallbacks(*this);
2221 return *m_fontSelector;
2224 void Document::clearStyleResolver()
2226 m_styleResolver = nullptr;
2227 m_userAgentShadowTreeStyleResolver = nullptr;
2229 // FIXME: It would be better if the FontSelector could survive this operation.
2230 if (m_fontSelector) {
2231 m_fontSelector->clearDocument();
2232 m_fontSelector->unregisterForInvalidationCallbacks(*this);
2233 m_fontSelector = nullptr;
2237 void Document::createRenderTree()
2239 ASSERT(!renderView());
2240 ASSERT(!m_inPageCache);
2241 ASSERT(!m_axObjectCache || this != &topDocument());
2243 if (m_isNonRenderedPlaceholder)
2246 // FIXME: It would be better if we could pass the resolved document style directly here.
2247 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2248 Node::setRenderer(m_renderView.get());
2250 renderView()->setIsInWindow(true);
2252 recalcStyle(Style::Force);
2255 void Document::didBecomeCurrentDocumentInFrame()
2257 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2258 // If so, then m_frame could become 0, and we need to do something about that.
2260 m_frame->script().updateDocument();
2262 if (!hasLivingRenderTree())
2265 updateViewportArguments();
2267 // FIXME: Doing this only for the main frame is insufficient.
2268 // Changing a subframe can also change the wheel event handler count.
2269 // FIXME: Doing this only when a document goes into the frame is insufficient.
2270 // Removing a document can also change the wheel event handler count.
2271 // FIXME: Doing this every time is a waste. If the current document and its
2272 // subframes' documents have no wheel event handlers, then the count did not change,
2273 // unless the documents they are replacing had wheel event handlers.
2274 if (page() && m_frame->isMainFrame())
2275 wheelEventHandlersChanged();
2277 #if ENABLE(TOUCH_EVENTS)
2278 // FIXME: Doing this only for the main frame is insufficient.
2279 // A subframe could have touch event handlers.
2280 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2281 page()->chrome().client().needTouchEvents(true);
2284 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2285 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2286 // page cache, or simply newly created).
2287 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2288 m_frame->animation().suspendAnimationsForDocument(this);
2289 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2291 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2292 m_frame->animation().resumeAnimationsForDocument(this);
2296 void Document::disconnectFromFrame()
2301 void Document::destroyRenderTree()
2303 ASSERT(hasLivingRenderTree());
2304 ASSERT(!m_inPageCache);
2306 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2308 if (this == &topDocument())
2309 clearAXObjectCache();
2311 documentWillBecomeInactive();
2313 if (FrameView* frameView = view())
2314 frameView->detachCustomScrollbars();
2316 #if ENABLE(FULLSCREEN_API)
2317 if (m_fullScreenRenderer)
2318 setFullScreenRenderer(nullptr);
2321 m_hoveredElement = nullptr;
2322 m_focusedElement = nullptr;
2323 m_activeElement = nullptr;
2325 if (m_documentElement)
2326 Style::detachRenderTree(*m_documentElement);
2328 clearChildNeedsStyleRecalc();
2330 unscheduleStyleRecalc();
2332 m_renderView = nullptr;
2333 Node::setRenderer(nullptr);
2335 #if ENABLE(IOS_TEXT_AUTOSIZING)
2336 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2337 m_textAutoSizedNodes.clear();
2341 void Document::prepareForDestruction()
2343 if (m_hasPreparedForDestruction)
2346 #if ENABLE(IOS_TOUCH_EVENTS)
2347 clearTouchEventListeners();
2350 #if HAVE(ACCESSIBILITY)
2351 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2352 if (this != &topDocument()) {
2353 if (AXObjectCache* cache = existingAXObjectCache())
2354 cache->clearTextMarkerNodesInUse(this);
2358 disconnectDescendantFrames();
2359 if (m_domWindow && m_frame)
2360 m_domWindow->willDetachDocumentFromFrame();
2362 if (hasLivingRenderTree())
2363 destroyRenderTree();
2365 if (is<PluginDocument>(*this))
2366 downcast<PluginDocument>(*this).detachFromPluginElement();
2368 #if ENABLE(POINTER_LOCK)
2370 page()->pointerLockController().documentDetached(this);
2373 InspectorInstrumentation::documentDetached(*this);
2375 stopActiveDOMObjects();
2376 m_eventQueue.close();
2377 #if ENABLE(FULLSCREEN_API)
2378 m_fullScreenChangeEventTargetQueue.clear();
2379 m_fullScreenErrorEventTargetQueue.clear();
2384 #if ENABLE(TOUCH_EVENTS)
2385 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2386 parentDocument()->didRemoveEventTargetNode(*this);
2389 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2390 parentDocument()->didRemoveEventTargetNode(*this);
2392 if (m_mediaQueryMatcher)
2393 m_mediaQueryMatcher->documentDestroyed();
2395 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2396 if (!m_clientToIDMap.isEmpty() && page()) {
2397 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2398 copyKeysToVector(m_clientToIDMap, clients);
2399 for (auto* client : clients)
2400 removePlaybackTargetPickerClient(*client);
2404 disconnectFromFrame();
2406 m_hasPreparedForDestruction = true;
2409 void Document::removeAllEventListeners()
2411 EventTarget::removeAllEventListeners();
2414 m_domWindow->removeAllEventListeners();
2415 #if ENABLE(IOS_TOUCH_EVENTS)
2416 clearTouchEventListeners();
2418 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2419 node->removeAllEventListeners();
2422 void Document::suspendDeviceMotionAndOrientationUpdates()
2424 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2426 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2427 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2428 if (m_deviceMotionController)
2429 m_deviceMotionController->suspendUpdates();
2430 if (m_deviceOrientationController)
2431 m_deviceOrientationController->suspendUpdates();
2435 void Document::resumeDeviceMotionAndOrientationUpdates()
2437 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2439 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2440 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2441 if (m_deviceMotionController)
2442 m_deviceMotionController->resumeUpdates();
2443 if (m_deviceOrientationController)
2444 m_deviceOrientationController->resumeUpdates();
2448 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2450 JSC::CallFrame* callFrame = JSDOMWindow::commonVM().topCallFrame;
2451 if (callFrame == JSC::CallFrame::noCaller())
2453 DOMWrapperWorld& domWrapperWorld = currentWorld(callFrame);
2454 if (domWrapperWorld.isNormal())
2459 void Document::platformSuspendOrStopActiveDOMObjects()
2462 if (WebThreadCountOfObservedContentModifiers() > 0) {
2463 Frame* frame = this->frame();
2464 if (Page* page = frame ? frame->page() : nullptr)
2465 page->chrome().client().clearContentChangeObservers(frame);
2470 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2472 ScriptExecutionContext::suspendActiveDOMObjects(why);
2473 suspendDeviceMotionAndOrientationUpdates();
2474 platformSuspendOrStopActiveDOMObjects();
2477 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2479 ScriptExecutionContext::resumeActiveDOMObjects(why);
2480 resumeDeviceMotionAndOrientationUpdates();
2481 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2484 void Document::stopActiveDOMObjects()
2486 ScriptExecutionContext::stopActiveDOMObjects();
2487 platformSuspendOrStopActiveDOMObjects();
2490 void Document::clearAXObjectCache()
2492 ASSERT(&topDocument() == this);
2493 // Clear the cache member variable before calling delete because attempts
2494 // are made to access it during destruction.
2495 m_axObjectCache = nullptr;
2498 AXObjectCache* Document::existingAXObjectCache() const
2500 Document& topDocument = this->topDocument();
2501 if (!topDocument.hasLivingRenderTree())
2503 return topDocument.m_axObjectCache.get();
2506 AXObjectCache* Document::axObjectCache() const
2508 if (!AXObjectCache::accessibilityEnabled())
2511 // The only document that actually has a AXObjectCache is the top-level
2512 // document. This is because we need to be able to get from any WebCoreAXObject
2513 // to any other WebCoreAXObject on the same page. Using a single cache allows
2514 // lookups across nested webareas (i.e. multiple documents).
2515 Document& topDocument = this->topDocument();
2517 // If the document has already been detached, do not make a new axObjectCache.
2518 if (!topDocument.hasLivingRenderTree())
2521 ASSERT(&topDocument == this || !m_axObjectCache);
2522 if (!topDocument.m_axObjectCache)
2523 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2524 return topDocument.m_axObjectCache.get();
2527 void Document::setVisuallyOrdered()
2529 m_visuallyOrdered = true;
2531 renderView()->style().setRTLOrdering(VisualOrder);
2534 Ref<DocumentParser> Document::createParser()
2536 // FIXME: this should probably pass the frame instead
2537 return XMLDocumentParser::create(*this, view());
2540 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2542 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2545 void Document::open(Document* ownerDocument)
2547 if (m_ignoreOpensDuringUnloadCount)
2550 if (ownerDocument) {
2551 setURL(ownerDocument->url());
2552 setCookieURL(ownerDocument->cookieURL());
2553 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2557 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2558 if (parser->isParsing()) {
2559 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2560 if (parser->isExecutingScript())
2563 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2568 if (m_frame->loader().state() == FrameStateProvisional)
2569 m_frame->loader().stopAllLoaders();
2572 removeAllEventListeners();
2574 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2575 parser->setWasCreatedByScript(true);
2578 m_frame->loader().didExplicitOpen();
2581 void Document::detachParser()
2589 void Document::cancelParsing()
2594 // We have to clear the parser to avoid possibly triggering
2595 // the onload handler when closing as a side effect of a cancel-style
2596 // change, such as opening a new document or closing the window while
2602 void Document::implicitOpen()
2608 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2610 m_parser = createParser();
2612 setReadyState(Loading);
2615 HTMLBodyElement* Document::body() const
2617 auto* element = documentElement();
2620 return childrenOfType<HTMLBodyElement>(*element).first();
2623 HTMLElement* Document::bodyOrFrameset() const
2625 // Return the first body or frameset child of the html element.
2626 auto* element = documentElement();
2629 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2630 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2636 void Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody, ExceptionCode& ec)
2638 // FIXME: This does not support setting a <frameset> Element, only a <body>. This does
2639 // not match the HTML specification:
2640 // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
2641 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2642 ec = HIERARCHY_REQUEST_ERR;
2646 if (&newBody->document() != this) {
2648 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2652 newBody = downcast<HTMLElement>(node.get());
2655 if (auto* body = bodyOrFrameset())
2656 documentElement()->replaceChild(newBody.releaseNonNull(), *body, ec);
2658 documentElement()->appendChild(newBody.releaseNonNull(), ec);
2661 Location* Document::location() const
2663 auto* window = domWindow();
2667 return window->location();
2670 HTMLHeadElement* Document::head()
2672 if (auto element = documentElement())
2673 return childrenOfType<HTMLHeadElement>(*element).first();
2677 void Document::close()
2679 // FIXME: We should follow the specification more closely:
2680 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2682 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2688 void Document::explicitClose()
2690 if (RefPtr<DocumentParser> parser = m_parser)
2694 // Because we have no frame, we don't know if all loading has completed,
2695 // so we just call implicitClose() immediately. FIXME: This might fire
2696 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2701 m_frame->loader().checkCompleted();
2704 void Document::implicitClose()
2706 // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
2707 if (m_inStyleRecalc) {
2708 m_closeAfterStyleRecalc = true;
2712 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2713 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2718 // Call to dispatchWindowLoadEvent can blow us from underneath.
2719 Ref<Document> protect(*this);
2721 m_processingLoadEvent = true;
2723 ScriptableDocumentParser* parser = scriptableDocumentParser();
2724 m_wellFormed = parser && parser->wellFormed();
2726 // We have to clear the parser, in case someone document.write()s from the
2727 // onLoad event handler, as in Radar 3206524.
2730 // FIXME: We kick off the icon loader when the Document is done parsing.
2731 // There are earlier opportunities we could start it:
2732 // -When the <head> finishes parsing
2733 // -When any new HTMLLinkElement is inserted into the document
2734 // But those add a dynamic component to the favicon that has UI
2735 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2738 f->loader().icon().startLoader();
2739 f->animation().startAnimationsIfNotSuspended(this);
2741 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2742 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2743 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2744 ImageLoader::dispatchPendingBeforeLoadEvents();
2745 ImageLoader::dispatchPendingLoadEvents();
2746 ImageLoader::dispatchPendingErrorEvents();
2747 HTMLLinkElement::dispatchPendingLoadEvents();
2748 HTMLStyleElement::dispatchPendingLoadEvents();
2751 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2752 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2753 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2754 if (svgExtensions())
2755 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2757 dispatchWindowLoadEvent();
2758 enqueuePageshowEvent(PageshowEventNotPersisted);
2759 if (m_pendingStateObject)
2760 enqueuePopstateEvent(WTFMove(m_pendingStateObject));
2763 f->loader().dispatchOnloadEvents();
2764 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2765 if (!ownerElement())
2766 printf("onload fired at %lld\n", elapsedTime().count());
2769 // An event handler may have removed the frame
2771 m_processingLoadEvent = false;
2775 // Make sure both the initial layout and reflow happen after the onload
2776 // fires. This will improve onload scores, and other browsers do it.
2777 // If they wanna cheat, we can too. -dwh
2779 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2780 // Just bail out. Before or during the onload we were shifted to another page.
2781 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2782 m_processingLoadEvent = false;
2783 view()->unscheduleRelayout();
2787 frame()->loader().checkCallImplicitClose();
2789 // We used to force a synchronous display and flush here. This really isn't
2790 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2791 // (if your platform is syncing flushes and limiting them to 60fps).
2792 m_overMinimumLayoutThreshold = true;
2793 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2794 updateStyleIfNeeded();
2796 // Always do a layout after loading if needed.
2797 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2801 m_processingLoadEvent = false;
2803 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2804 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2805 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2806 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2807 // exists in the cache (we ignore the return value because we don't need it here). This is
2808 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2810 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2811 // catch new AND page history loads, and that uses AXLoadComplete
2813 axObjectCache()->getOrCreate(renderView());
2814 if (this == &topDocument())
2815 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2817 // AXLoadComplete can only be posted on the top document, so if it's a document
2818 // in an iframe that just finished loading, post AXLayoutComplete instead.
2819 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2824 if (svgExtensions())
2825 accessSVGExtensions().startAnimations();
2828 void Document::setParsing(bool b)
2832 if (m_bParsing && !m_sharedObjectPool)
2833 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2835 if (!m_bParsing && view() && !view()->needsLayout())
2836 view()->fireLayoutRelatedMilestonesIfNeeded();
2838 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2839 if (!ownerElement() && !m_bParsing)
2840 printf("Parsing finished at %lld\n", elapsedTime().count());
2844 bool Document::shouldScheduleLayout()
2846 // This function will only be called when FrameView thinks a layout is needed.
2847 // This enforces a couple extra rules.
2849 // (a) Only schedule a layout once the stylesheets are loaded.
2850 // (b) Only schedule layout once we have a body element.
2852 return (haveStylesheetsLoaded() && bodyOrFrameset())
2853 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2856 bool Document::isLayoutTimerActive()
2858 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2861 std::chrono::milliseconds Document::minimumLayoutDelay()
2863 if (m_overMinimumLayoutThreshold)
2864 return std::chrono::milliseconds(0);
2866 std::chrono::milliseconds elapsed = elapsedTime();
2867 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2869 // We'll want to schedule the timer to fire at the minimum layout threshold.
2870 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2873 std::chrono::milliseconds Document::elapsedTime() const
2875 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2877 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2880 void Document::write(const SegmentedString& text, Document* ownerDocument)
2882 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2884 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2885 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2887 if (m_writeRecursionIsTooDeep)
2890 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2891 if (!ownerElement())
2892 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2895 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2896 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2899 if (!hasInsertionPoint)
2900 open(ownerDocument);
2903 m_parser->insert(text);
2905 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2906 if (!ownerElement())
2907 printf("Ending a document.write at %lld\n", elapsedTime().count());
2911 void Document::write(const String& text, Document* ownerDocument)
2913 write(SegmentedString(text), ownerDocument);
2916 void Document::writeln(const String& text, Document* ownerDocument)
2918 write(text, ownerDocument);
2919 write("\n", ownerDocument);
2922 std::chrono::milliseconds Document::minimumTimerInterval() const
2924 auto* page = this->page();
2926 return ScriptExecutionContext::minimumTimerInterval();
2927 return page->settings().minimumDOMTimerInterval();
2930 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2932 if (m_isTimerThrottlingEnabled == shouldThrottle)
2935 m_isTimerThrottlingEnabled = shouldThrottle;
2936 didChangeTimerAlignmentInterval();
2939 std::chrono::milliseconds Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2941 auto alignmentInterval = ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2943 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2944 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2945 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
2947 if (Page* page = this->page())
2948 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
2950 return alignmentInterval;
2953 EventTarget* Document::errorEventTarget()
2955 return m_domWindow.get();
2958 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2960 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2963 void Document::setURL(const URL& url)
2965 const URL& newURL = url.isEmpty() ? blankURL() : url;
2966 if (newURL == m_url)
2970 m_documentURI = m_url.string();
2974 void Document::updateBaseURL()
2976 URL oldBaseURL = m_baseURL;
2977 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2978 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2979 // from the Document interface otherwise.
2980 if (!m_baseElementURL.isEmpty())
2981 m_baseURL = m_baseElementURL;
2982 else if (!m_baseURLOverride.isEmpty())
2983 m_baseURL = m_baseURLOverride;
2985 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2986 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2987 // and DOM 3 Core does not specify how it should be resolved.
2988 m_baseURL = URL(ParsedURLString, documentURI());
2991 clearSelectorQueryCache();
2993 if (!m_baseURL.isValid())
2996 if (m_elementSheet) {
2997 // Element sheet is silly. It never contains anything.
2998 ASSERT(!m_elementSheet->contents().ruleCount());
2999 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
3000 bool usesStyleBasedEditability = m_elementSheet->contents().usesStyleBasedEditability();
3001 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
3002 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
3004 m_elementSheet->contents().parserSetUsesRemUnits();
3005 if (usesStyleBasedEditability)
3006 m_elementSheet->contents().parserSetUsesStyleBasedEditability();
3009 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
3010 // Base URL change changes any relative visited links.
3011 // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
3012 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
3013 anchor.invalidateCachedVisitedLinkHash();
3017 void Document::setBaseURLOverride(const URL& url)
3019 m_baseURLOverride = url;
3023 void Document::processBaseElement()
3025 // Find the first href attribute in a base element and the first target attribute in a base element.
3026 const AtomicString* href = nullptr;
3027 const AtomicString* target = nullptr;
3028 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3029 for (auto& base : baseDescendants) {
3031 const AtomicString& value = base.fastGetAttribute(hrefAttr);
3032 if (!value.isNull()) {
3039 const AtomicString& value = base.fastGetAttribute(targetAttr);
3040 if (!value.isNull()) {
3048 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3051 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3052 if (!strippedHref.isEmpty())
3053 baseElementURL = URL(url(), strippedHref);
3055 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3056 m_baseElementURL = baseElementURL;
3060 m_baseTarget = target ? *target : nullAtom;
3063 String Document::userAgent(const URL& url) const
3065 return frame() ? frame()->loader().userAgent(url) : String();
3068 void Document::disableEval(const String& errorMessage)
3073 frame()->script().disableEval(errorMessage);
3076 bool Document::canNavigate(Frame* targetFrame)
3081 // FIXME: We shouldn't call this function without a target frame, but
3082 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3083 // returning true when supplied with a 0 targetFrame.
3087 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
3088 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3091 if (isSandboxed(SandboxNavigation)) {
3092 if (targetFrame->tree().isDescendantOf(m_frame))
3095 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
3096 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3097 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
3099 printNavigationErrorMessage(targetFrame, url(), reason);
3103 // This is the normal case. A document can navigate its decendant frames,
3104 // or, more generally, a document can navigate a frame if the document is
3105 // in the same origin as any of that frame's ancestors (in the frame
3108 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3109 // historical information about this security check.
3110 if (canAccessAncestor(securityOrigin(), targetFrame))
3113 // Top-level frames are easier to navigate than other frames because they
3114 // display their URLs in the address bar (in most browsers). However, there
3115 // are still some restrictions on navigation to avoid nuisance attacks.
3116 // Specifically, a document can navigate a top-level frame if that frame
3117 // opened the document or if the document is the same-origin with any of
3118 // the top-level frame's opener's ancestors (in the frame hierarchy).
3120 // In both of these cases, the document performing the navigation is in
3121 // some way related to the frame being navigate (e.g., by the "opener"
3122 // and/or "parent" relation). Requiring some sort of relation prevents a
3123 // document from navigating arbitrary, unrelated top-level frames.
3124 if (!targetFrame->tree().parent()) {
3125 if (targetFrame == m_frame->loader().opener())
3128 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3132 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3136 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3138 Frame* currentFrame = m_frame;
3142 Frame* ancestorFrame = currentFrame->tree().parent();
3144 while (ancestorFrame) {
3145 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3146 return currentFrame;
3147 currentFrame = ancestorFrame;
3148 ancestorFrame = ancestorFrame->tree().parent();
3153 void Document::didRemoveAllPendingStylesheet()
3155 m_needsNotifyRemoveAllPendingStylesheet = false;
3157 styleResolverChanged(DeferRecalcStyleIfNeeded);
3159 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3160 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3162 renderView()->repaintViewAndCompositedLayers();
3165 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3166 parser->executeScriptsWaitingForStylesheets();
3168 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3169 view()->scrollToFragment(m_url);
3172 CSSStyleSheet& Document::elementSheet()
3174 if (!m_elementSheet)
3175 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
3176 return *m_elementSheet;
3179 bool Document::usesStyleBasedEditability() const
3181 if (m_elementSheet && m_elementSheet->contents().usesStyleBasedEditability())
3184 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3185 ASSERT(!m_inStyleRecalc);
3187 auto& authorSheets = const_cast<AuthorStyleSheets&>(authorStyleSheets());
3188 authorSheets.flushPendingUpdates();
3189 return authorSheets.usesStyleBasedEditability();
3192 void Document::processHttpEquiv(const String& equiv, const String& content)
3194 ASSERT(!equiv.isNull() && !content.isNull());
3196 HttpEquivPolicy policy = httpEquivPolicy();
3197 if (policy != HttpEquivPolicy::Enabled) {
3200 case HttpEquivPolicy::Enabled:
3201 ASSERT_NOT_REACHED();
3203 case HttpEquivPolicy::DisabledBySettings:
3204 reason = "by the embedder.";
3206 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3207 reason = "for documents with Content-Disposition: attachment.";
3210 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3211 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3215 Frame* frame = this->frame();
3217 HTTPHeaderName headerName;
3218 if (!findHTTPHeaderName(equiv, headerName))
3221 switch (headerName) {
3222 case HTTPHeaderName::DefaultStyle:
3223 // The preferred style set has been overridden as per section
3224 // 14.3.2 of the HTML4.0 specification. We need to update the
3225 // sheet used variable and then update our style selector.
3226 // For more info, see the test at:
3227 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3229 authorStyleSheets().setSelectedStylesheetSetName(content);
3230 authorStyleSheets().setPreferredStylesheetSetName(content);
3231 styleResolverChanged(DeferRecalcStyle);
3234 case HTTPHeaderName::Refresh: {
3237 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
3239 if (urlString.isEmpty())
3240 completedURL = m_url;
3242 completedURL = completeURL(urlString);
3243 if (!protocolIsJavaScript(completedURL))
3244 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3246 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3247 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3254 case HTTPHeaderName::SetCookie:
3255 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3256 if (is<HTMLDocument>(*this)) {
3257 // Exception (for sandboxed documents) ignored.
3258 downcast<HTMLDocument>(*this).setCookie(content, IGNORE_EXCEPTION);
3262 case HTTPHeaderName::ContentLanguage:
3263 setContentLanguage(content);
3266 case HTTPHeaderName::XDNSPrefetchControl:
3267 parseDNSPrefetchControlHeader(content);
3270 case HTTPHeaderName::XFrameOptions:
3272 FrameLoader& frameLoader = frame->loader();
3273 unsigned long requestIdentifier = 0;
3274 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3275 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3276 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3277 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3278 frameLoader.stopAllLoaders();
3279 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3280 // intent, we must navigate away from the possibly partially-rendered document to a location that
3281 // doesn't inherit the parent's SecurityOrigin.
3282 frame->navigationScheduler().scheduleLocationChange(this, securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
3283 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3288 case HTTPHeaderName::ContentSecurityPolicy:
3289 contentSecurityPolicy()->processHTTPEquiv(content, ContentSecurityPolicyHeaderType::Enforce);
3292 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
3293 contentSecurityPolicy()->processHTTPEquiv(content, ContentSecurityPolicyHeaderType::Report);
3296 case HTTPHeaderName::XWebKitCSP:
3297 contentSecurityPolicy()->processHTTPEquiv(content, ContentSecurityPolicyHeaderType::PrefixedEnforce);
3300 case HTTPHeaderName::XWebKitCSPReportOnly:
3301 contentSecurityPolicy()->processHTTPEquiv(content, ContentSecurityPolicyHeaderType::PrefixedReport);
3309 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3311 ASSERT(!features.isNull());
3313 if (origin < m_viewportArguments.type)
3316 m_viewportArguments = ViewportArguments(origin);
3318 processFeaturesString(features, [this](StringView key, StringView value) {
3319 setViewportFeature(m_viewportArguments, *this, key, value);
3322 updateViewportArguments();
3325 void Document::updateViewportArguments()
3327 if (page() && frame()->isMainFrame()) {
3329 m_didDispatchViewportPropertiesChanged = true;
3331 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3333 page()->chrome().didReceiveDocType(frame());
3340 void Document::processFormatDetection(const String& features)
3342 // FIXME: Find a better place for this function.
3343 processFeaturesString(features, [this](StringView key, StringView value) {
3344 if (equalLettersIgnoringASCIICase(key, "telephone") && equalLettersIgnoringASCIICase(value, "no"))
3345 setIsTelephoneNumberParsingAllowed(false);
3349 void Document::processWebAppOrientations()
3351 if (Page* page = this->page())
3352 page->chrome().client().webAppOrientationsUpdated();
3357 void Document::processReferrerPolicy(const String& policy)
3359 ASSERT(!policy.isNull());
3361 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3362 // even if the document has a meta tag saying otherwise.
3363 if (shouldEnforceContentDispositionAttachmentSandbox())
3366 // Note that we're supporting both the standard and legacy keywords for referrer
3367 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3368 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3369 setReferrerPolicy(ReferrerPolicyNever);
3370 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3371 setReferrerPolicy(ReferrerPolicyAlways);
3372 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3373 setReferrerPolicy(ReferrerPolicyOrigin);
3374 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3375 setReferrerPolicy(ReferrerPolicyDefault);
3377 addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, "Failed to set referrer policy: The value '" + policy + "' is not one of 'no-referrer', 'origin', 'no-referrer-when-downgrade', or 'unsafe-url'. Defaulting to 'no-referrer'.");
3378 setReferrerPolicy(ReferrerPolicyNever);
3382 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3384 if (!hasLivingRenderTree())
3385 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3387 HitTestResult result(documentPoint);
3388 renderView()->hitTest(request, result);
3390 if (!request.readOnly())
3391 updateHoverActiveState(request, result.innerElement());
3393 return MouseEventWithHitTestResults(event, result);
3396 // DOM Section 1.1.1
3397 bool Document::childTypeAllowed(NodeType type) const
3400 case ATTRIBUTE_NODE:
3401 case CDATA_SECTION_NODE:
3402 case DOCUMENT_FRAGMENT_NODE:
3407 case PROCESSING_INSTRUCTION_NODE:
3409 case DOCUMENT_TYPE_NODE:
3411 // Documents may contain no more than one of each of these.
3412 // (One Element and one DocumentType.)
3413 for (Node* c = firstChild(); c; c = c->nextSibling())
3414 if (c->nodeType() == type)
3421 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3423 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3426 switch (newChild.nodeType()) {
3427 case ATTRIBUTE_NODE:
3428 case CDATA_SECTION_NODE:
3433 case PROCESSING_INSTRUCTION_NODE:
3435 case DOCUMENT_FRAGMENT_NODE: {
3436 bool hasSeenElementChild = false;
3437 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3438 if (is<Element>(*node)) {
3439 if (hasSeenElementChild)
3441 hasSeenElementChild = true;
3443 if (!canAcceptChild(*node, refChild, operation))
3448 case DOCUMENT_TYPE_NODE: {
3449 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3450 if (operation == AcceptChildOperation::Replace) {
3451 // parent has a doctype child that is not child, or an element is preceding child.
3452 if (existingDocType && existingDocType != refChild)
3454 if (refChild->previousElementSibling())
3457 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3458 if (existingDocType)
3460 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3465 case ELEMENT_NODE: {
3466 auto* existingElementChild = firstElementChild();
3467 if (operation == AcceptChildOperation::Replace) {
3468 if (existingElementChild && existingElementChild != refChild)
3470 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3471 if (is<DocumentType>(*child))
3475 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3476 if (existingElementChild)
3478 for (auto* child = refChild; child; child = child->nextSibling()) {
3479 if (is<DocumentType>(*child))
3489 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3491 Ref<Document> clone = cloneDocumentWithoutChildren();
3492 clone->cloneDataFromDocument(*this);
3494 case CloningOperation::OnlySelf:
3495 case CloningOperation::SelfWithTemplateContent:
3497 case CloningOperation::Everything:
3498 cloneChildNodes(clone);
3501 return WTFMove(clone);
3504 Ref<Document> Document::cloneDocumentWithoutChildren() const
3506 if (isXMLDocument()) {
3507 if (isXHTMLDocument())
3508 return XMLDocument::createXHTML(nullptr, url());
3509 return XMLDocument::create(nullptr, url());
3511 return create(nullptr, url());
3514 void Document::cloneDataFromDocument(const Document& other)
3516 ASSERT(m_url == other.url());
3517 m_baseURL = other.baseURL();
3518 m_baseURLOverride = other.baseURLOverride();
3519 m_documentURI = other.documentURI();
3521 setCompatibilityMode(other.m_compatibilityMode);
3522 setSecurityOriginPolicy(other.securityOriginPolicy());
3523 overrideMIMEType(other.contentType());
3524 setDecoder(other.decoder());
3527 StyleSheetList& Document::styleSheets()
3529 if (!m_styleSheetList)
3530 m_styleSheetList = StyleSheetList::create(this);
3531 return *m_styleSheetList;
3534 String Document::preferredStylesheetSet() const
3536 return authorStyleSheets().preferredStylesheetSetName();
3539 String Document::selectedStylesheetSet() const
3541 return authorStyleSheets().selectedStylesheetSetName();
3544 void Document::setSelectedStylesheetSet(const String& aString)
3546 authorStyleSheets().setSelectedStylesheetSetName(aString);
3547 styleResolverChanged(DeferRecalcStyle);
3550 void Document::evaluateMediaQueryList()
3552 if (m_mediaQueryMatcher)
3553 m_mediaQueryMatcher->styleResolverChanged();
3555 checkViewportDependentPictures();
3558 void Document::checkViewportDependentPictures()
3560 Vector<HTMLPictureElement*, 16> changedPictures;
3561 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3562 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3563 if ((*it)->viewportChangeAffectedPicture())
3564 changedPictures.append(*it);
3566 for (auto* picture : changedPictures)
3567 picture->sourcesChanged();
3570 void Document::optimizedStyleSheetUpdateTimerFired()
3572 styleResolverChanged(RecalcStyleIfNeeded);
3575 void Document::scheduleOptimizedStyleSheetUpdate()
3577 if (m_optimizedStyleSheetUpdateTimer.isActive())
3579 authorStyleSheets().setPendingUpdateType(AuthorStyleSheets::OptimizedUpdate);
3580 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3583 void Document::updateViewportUnitsOnResize()
3585 if (!hasStyleWithViewportUnits())
3588 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3590 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3591 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3592 auto* renderer = element->renderer();
3593 if (renderer && renderer->style().hasViewportUnits())
3594 element->setNeedsStyleRecalc(InlineStyleChange);
3598 void Document::addAudioProducer(MediaProducer* audioProducer)
3600 m_audioProducers.add(audioProducer);
3601 updateIsPlayingMedia();
3604 void Document::removeAudioProducer(MediaProducer* audioProducer)
3606 m_audioProducers.remove(audioProducer);
3607 updateIsPlayingMedia();
3610 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3612 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3613 for (auto* audioProducer : m_audioProducers)
3614 state |= audioProducer->mediaState();
3616 #if ENABLE(MEDIA_SESSION)
3617 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3618 if (sourceElement->isPlaying())
3619 state |= MediaProducer::IsSourceElementPlaying;
3621 if (auto* session = sourceElement->session()) {
3622 if (auto* controls = session->controls()) {
3623 if (controls->previousTrackEnabled())
3624 state |= MediaProducer::IsPreviousTrackControlEnabled;
3625 if (controls->nextTrackEnabled())
3626 state |= MediaProducer::IsNextTrackControlEnabled;
3632 if (state == m_mediaState)
3635 m_mediaState = state;
3638 page()->updateIsPlayingMedia(sourceElementID);
3641 void Document::pageMutedStateDidChange()
3643 for (auto* audioProducer : m_audioProducers)
3644 audioProducer->pageMutedStateDidChange();
3647 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3649 if (m_optimizedStyleSheetUpdateTimer.isActive())
3650 m_optimizedStyleSheetUpdateTimer.stop();
3652 // Don't bother updating, since we haven't loaded all our style info yet
3653 // and haven't calculated the style selector for the first time.
3654 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {