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-2016 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 "CDATASection.h"
35 #include "CSSFontSelector.h"
36 #include "CSSStyleDeclaration.h"
37 #include "CSSStyleSheet.h"
38 #include "CachedCSSStyleSheet.h"
39 #include "CachedResourceLoader.h"
41 #include "ChromeClient.h"
43 #include "CompositionEvent.h"
44 #include "ContentSecurityPolicy.h"
45 #include "CookieJar.h"
46 #include "CustomElementReactionQueue.h"
47 #include "CustomElementRegistry.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 "EventHandler.h"
62 #include "ExtensionStyleSheets.h"
63 #include "FocusController.h"
64 #include "FontFaceSet.h"
65 #include "FormController.h"
66 #include "FrameLoader.h"
67 #include "FrameLoaderClient.h"
68 #include "FrameView.h"
69 #include "GenericCachedHTMLCollection.h"
70 #include "HTMLAllCollection.h"
71 #include "HTMLAnchorElement.h"
72 #include "HTMLBaseElement.h"
73 #include "HTMLBodyElement.h"
74 #include "HTMLCanvasElement.h"
75 #include "HTMLDocument.h"
76 #include "HTMLElementFactory.h"
77 #include "HTMLFormControlElement.h"
78 #include "HTMLFrameOwnerElement.h"
79 #include "HTMLFrameSetElement.h"
80 #include "HTMLHeadElement.h"
81 #include "HTMLHtmlElement.h"
82 #include "HTMLImageElement.h"
83 #include "HTMLInputElement.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 "JSCustomElementInterface.h"
103 #include "JSLazyEventListener.h"
104 #include "KeyboardEvent.h"
105 #include "Language.h"
106 #include "LoaderStrategy.h"
108 #include "MainFrame.h"
109 #include "MediaCanStartListener.h"
110 #include "MediaProducer.h"
111 #include "MediaQueryList.h"
112 #include "MediaQueryMatcher.h"
113 #include "MessageEvent.h"
114 #include "MouseEventWithHitTestResults.h"
115 #include "MutationEvent.h"
116 #include "NameNodeList.h"
117 #include "NestingLevelIncrementer.h"
118 #include "NoEventDispatchAssertion.h"
119 #include "NodeIterator.h"
120 #include "NodeRareData.h"
121 #include "NodeWithIndex.h"
122 #include "OriginAccessEntry.h"
123 #include "OverflowEvent.h"
124 #include "PageConsoleClient.h"
125 #include "PageGroup.h"
126 #include "PageTransitionEvent.h"
127 #include "PlatformLocale.h"
128 #include "PlatformMediaSessionManager.h"
129 #include "PlatformScreen.h"
130 #include "PlatformStrategies.h"
131 #include "PlugInsResources.h"
132 #include "PluginDocument.h"
133 #include "PointerLockController.h"
134 #include "PopStateEvent.h"
135 #include "ProcessingInstruction.h"
136 #include "RenderChildIterator.h"
137 #include "RenderLayerCompositor.h"
138 #include "RenderTreeUpdater.h"
139 #include "RenderView.h"
140 #include "RenderWidget.h"
141 #include "ResourceLoadObserver.h"
142 #include "RuntimeEnabledFeatures.h"
143 #include "SVGDocumentExtensions.h"
144 #include "SVGElement.h"
145 #include "SVGElementFactory.h"
146 #include "SVGNames.h"
147 #include "SVGSVGElement.h"
148 #include "SVGTitleElement.h"
149 #include "SVGZoomEvent.h"
150 #include "SchemeRegistry.h"
151 #include "ScopedEventQueue.h"
152 #include "ScriptController.h"
153 #include "ScriptModuleLoader.h"
154 #include "ScriptRunner.h"
155 #include "ScriptSourceCode.h"
156 #include "ScrollingCoordinator.h"
157 #include "SecurityOrigin.h"
158 #include "SecurityOriginPolicy.h"
159 #include "SecurityPolicy.h"
160 #include "SegmentedString.h"
161 #include "SelectorQuery.h"
162 #include "Settings.h"
163 #include "ShadowRoot.h"
164 #include "SocketProvider.h"
165 #include "StorageEvent.h"
166 #include "StyleProperties.h"
167 #include "StyleResolveForDocument.h"
168 #include "StyleResolver.h"
169 #include "StyleScope.h"
170 #include "StyleSheetContents.h"
171 #include "StyleSheetList.h"
172 #include "StyleTreeResolver.h"
173 #include "SubresourceLoader.h"
174 #include "TextAutoSizing.h"
175 #include "TextEvent.h"
176 #include "TextNodeTraversal.h"
177 #include "TransformSource.h"
178 #include "TreeWalker.h"
179 #include "VisitedLinkState.h"
180 #include "WheelEvent.h"
181 #include "WindowFeatures.h"
182 #include "XMLDocument.h"
183 #include "XMLDocumentParser.h"
184 #include "XMLNSNames.h"
185 #include "XMLNames.h"
186 #include "XPathEvaluator.h"
187 #include "XPathExpression.h"
188 #include "XPathNSResolver.h"
189 #include "XPathResult.h"
190 #include "htmlediting.h"
192 #include <inspector/ScriptCallStack.h>
193 #include <wtf/CurrentTime.h>
194 #include <wtf/NeverDestroyed.h>
195 #include <wtf/SetForScope.h>
196 #include <wtf/SystemTracing.h>
197 #include <wtf/text/StringBuffer.h>
198 #include <yarr/RegularExpression.h>
200 #if ENABLE(DEVICE_ORIENTATION)
201 #include "DeviceMotionEvent.h"
202 #include "DeviceOrientationEvent.h"
205 #if ENABLE(FULLSCREEN_API)
206 #include "RenderFullScreen.h"
209 #if ENABLE(INDEXED_DATABASE)
210 #include "IDBConnectionProxy.h"
211 #include "IDBOpenDBRequest.h"
215 #include "CSSFontSelector.h"
216 #include "DeviceMotionClientIOS.h"
217 #include "DeviceMotionController.h"
218 #include "DeviceOrientationClientIOS.h"
219 #include "DeviceOrientationController.h"
220 #include "Geolocation.h"
221 #include "Navigator.h"
222 #include "NavigatorGeolocation.h"
223 #include "WKContentObservation.h"
224 #include "WebCoreSystemInterface.h"
227 #if ENABLE(IOS_GESTURE_EVENTS)
228 #include "GestureEvent.h"
232 #include "MathMLElement.h"
233 #include "MathMLElementFactory.h"
234 #include "MathMLNames.h"
237 #if ENABLE(MEDIA_SESSION)
238 #include "MediaSession.h"
241 #if ENABLE(REQUEST_ANIMATION_FRAME)
242 #include "RequestAnimationFrameCallback.h"
243 #include "ScriptedAnimationController.h"
246 #if ENABLE(TOUCH_EVENTS)
247 #include "TouchEvent.h"
248 #include "TouchList.h"
251 #if ENABLE(VIDEO_TRACK)
252 #include "CaptionUserPreferences.h"
255 #if ENABLE(WEB_REPLAY)
256 #include "WebReplayInputs.h"
257 #include <replay/EmptyInputCursor.h>
258 #include <replay/InputCursor.h>
261 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
262 #include "MediaPlaybackTargetClient.h"
266 #include "XSLTProcessor.h"
270 using namespace Unicode;
274 using namespace HTMLNames;
276 static const unsigned cMaxWriteRecursionDepth = 21;
278 // DOM Level 2 says (letters added):
280 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
281 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
282 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
283 // 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.
284 // 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.
285 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
286 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
287 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
288 // i) Characters ':' and '_' are allowed as name-start characters.
289 // j) Characters '-' and '.' are allowed as name characters.
291 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
293 static inline bool isValidNameStart(UChar32 c)
296 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
300 if (c == ':' || c == '_')
303 // rules (a) and (f) above
304 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)))
308 if (c >= 0xF900 && c < 0xFFFE)
312 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
313 if (type == U_DT_FONT || type == U_DT_COMPAT)
319 static inline bool isValidNamePart(UChar32 c)
321 // rules (a), (e), and (i) above
322 if (isValidNameStart(c))
325 // rules (g) and (h) above
326 if (c == 0x00B7 || c == 0x0387)
330 if (c == '-' || c == '.')
333 // rules (b) and (f) above
334 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
338 if (c >= 0xF900 && c < 0xFFFE)
342 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
343 if (type == U_DT_FONT || type == U_DT_COMPAT)
349 static Widget* widgetForElement(Element* focusedElement)
353 auto* renderer = focusedElement->renderer();
354 if (!is<RenderWidget>(renderer))
356 return downcast<RenderWidget>(*renderer).widget();
359 static bool acceptsEditingFocus(Node* node)
362 ASSERT(node->hasEditableStyle());
364 Node* root = node->rootEditableElement();
365 Frame* frame = node->document().frame();
369 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
372 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
374 // targetFrame can be 0 when we're trying to navigate a top-level frame
375 // that has a 0 opener.
379 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
380 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
381 Document* ancestorDocument = ancestorFrame->document();
382 // FIXME: Should be an ASSERT? Frames should alway have documents.
383 if (!ancestorDocument)
386 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
387 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
390 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
391 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
392 // something more general instead?
393 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
400 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
402 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
404 // FIXME: should we print to the console of the document performing the navigation instead?
405 frame->document()->domWindow()->printErrorMessage(message);
408 #if ENABLE(TEXT_AUTOSIZING)
410 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
412 new (NotNull, &slot) TextAutoSizingKey(TextAutoSizingKey::Deleted);
415 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
417 return value.isDeleted();
422 uint64_t Document::s_globalTreeVersion = 0;
424 HashSet<Document*>& Document::allDocuments()
426 static NeverDestroyed<HashSet<Document*>> documents;
430 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
431 : ContainerNode(*this, CreateDocument)
433 #if ENABLE(IOS_TOUCH_EVENTS)
434 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
436 , m_referencingNodeCount(0)
437 , m_hasNodesWithPlaceholderStyle(false)
438 , m_needsNotifyRemoveAllPendingStylesheet(false)
439 , m_ignorePendingStylesheets(false)
440 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
442 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
443 , m_activeParserCount(0)
444 , m_wellFormed(false)
446 , m_paginatedForScreen(false)
447 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
448 , m_compatibilityModeLocked(false)
449 , m_textColor(Color::black)
450 , m_domTreeVersion(++s_globalTreeVersion)
452 , m_mutationObserverTypes(0)
453 , m_styleScope(std::make_unique<Style::Scope>(*this))
454 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
455 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
456 , m_visuallyOrdered(false)
457 , m_readyState(Complete)
459 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
460 , m_pendingStyleRecalcShouldForce(false)
461 , m_inStyleRecalc(false)
462 , m_closeAfterStyleRecalc(false)
463 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
464 , m_frameElementsShouldIgnoreScrolling(false)
465 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
466 , m_markers(std::make_unique<DocumentMarkerController>(*this))
467 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
468 , m_cssTarget(nullptr)
469 , m_processingLoadEvent(false)
470 , m_loadEventFinished(false)
471 , m_documentCreationTime(MonotonicTime::now())
472 , m_overMinimumLayoutThreshold(false)
473 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
474 , m_moduleLoader(std::make_unique<ScriptModuleLoader>(*this))
475 , m_xmlVersion(ASCIILiteral("1.0"))
476 , m_xmlStandalone(StandaloneUnspecified)
477 , m_hasXMLDeclaration(false)
478 , m_designMode(inherit)
479 #if ENABLE(DASHBOARD_SUPPORT)
480 , m_hasAnnotatedRegions(false)
481 , m_annotatedRegionsDirty(false)
483 , m_createRenderers(true)
484 , m_accessKeyMapValid(false)
485 , m_documentClasses(documentClasses)
486 , m_isSynthesized(constructionFlags & Synthesized)
487 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
488 , m_sawElementsInKnownNamespaces(false)
489 , m_isSrcdocDocument(false)
490 , m_eventQueue(*this)
491 , m_weakFactory(this)
492 #if ENABLE(FULLSCREEN_API)
493 , m_areKeysEnabledInFullScreen(0)
494 , m_fullScreenRenderer(nullptr)
495 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
496 , m_isAnimatingFullScreen(false)
498 , m_loadEventDelayCount(0)
499 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
500 , m_referrerPolicy(ReferrerPolicy::Default)
501 , m_writeRecursionIsTooDeep(false)
502 , m_writeRecursionDepth(0)
503 , m_lastHandledUserGestureTimestamp(0)
505 #if ENABLE(DEVICE_ORIENTATION)
506 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
507 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
508 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
509 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
512 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
513 , m_isTelephoneNumberParsingAllowed(true)
515 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
516 , m_scheduledTasksAreSuspended(false)
517 , m_visualUpdatesAllowed(true)
518 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
519 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
521 , m_didDispatchViewportPropertiesChanged(false)
523 , m_templateDocumentHost(nullptr)
524 , m_fontSelector(CSSFontSelector::create(*this))
525 #if ENABLE(WEB_REPLAY)
526 , m_inputCursor(EmptyInputCursor::create())
528 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
529 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
530 , m_disabledFieldsetElementsCount(0)
531 , m_hasInjectedPlugInsScript(false)
532 , m_hasStyleWithViewportUnits(false)
533 #if ENABLE(WEB_SOCKETS)
534 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
537 allDocuments().add(this);
539 // We depend on the url getting immediately set in subframes, but we
540 // also depend on the url NOT getting immediately set in opened windows.
541 // See fast/dom/early-frame-url.html
542 // and fast/dom/location-new-window-no-crash.html, respectively.
543 // FIXME: Can/should we unify this behavior?
544 if ((frame && frame->ownerElement()) || !url.isEmpty())
547 m_cachedResourceLoader->setDocument(this);
550 resetVisitedLinkColor();
551 resetActiveLinkColor();
553 initSecurityContext();
556 m_fontSelector->registerForInvalidationCallbacks(*this);
558 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
559 nodeListAndCollectionCount = 0;
562 #if ENABLE(FULLSCREEN_API)
564 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
569 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
571 } while ((owner = owner->document().ownerElement()));
577 Ref<Document> Document::create(Document& contextDocument)
579 auto document = adoptRef(*new Document(nullptr, URL()));
580 document->setContextDocument(contextDocument);
581 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
585 Document::~Document()
587 allDocuments().remove(this);
589 ASSERT(!renderView());
590 ASSERT(m_pageCacheState != InPageCache);
591 ASSERT(m_ranges.isEmpty());
592 ASSERT(!m_parentTreeScope);
593 ASSERT(!m_disabledFieldsetElementsCount);
594 ASSERT(m_inDocumentShadowRoots.isEmpty());
596 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
597 m_deviceMotionClient->deviceMotionControllerDestroyed();
598 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
601 if (m_templateDocument)
602 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
604 // FIXME: Should we reset m_domWindow when we detach from the Frame?
606 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
608 m_scriptRunner = nullptr;
609 m_moduleLoader = nullptr;
611 removeAllEventListeners();
613 // Currently we believe that Document can never outlive the parser.
614 // Although the Document may be replaced synchronously, DocumentParsers
615 // generally keep at least one reference to an Element which would in turn
616 // has a reference to the Document. If you hit this ASSERT, then that
617 // assumption is wrong. DocumentParser::detach() should ensure that even
618 // if the DocumentParser outlives the Document it won't cause badness.
619 ASSERT(!m_parser || m_parser->refCount() == 1);
622 if (this == &topDocument())
623 clearAXObjectCache();
627 if (m_styleSheetList)
628 m_styleSheetList->detachFromDocument();
630 extensionStyleSheets().detachFromDocument();
632 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
633 m_fontSelector->clearDocument();
634 m_fontSelector->unregisterForInvalidationCallbacks(*this);
636 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
637 // load the initial empty document and the SVGDocument with the same DocumentLoader).
638 if (m_cachedResourceLoader->document() == this)
639 m_cachedResourceLoader->setDocument(nullptr);
642 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
643 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
646 // We must call clearRareData() here since a Document class inherits TreeScope
647 // as well as Node. See a comment on TreeScope.h for the reason.
651 ASSERT(!m_listsInvalidatedAtDocument.size());
652 ASSERT(!m_collectionsInvalidatedAtDocument.size());
654 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
655 ASSERT(!m_nodeListAndCollectionCounts[i]);
658 void Document::removedLastRef()
660 ASSERT(!m_deletionHasBegun);
661 if (m_referencingNodeCount) {
662 // If removing a child removes the last node reference, we don't want the scope to be destroyed
663 // until after removeDetachedChildren returns, so we protect ourselves.
664 incrementReferencingNodeCount();
666 RELEASE_ASSERT(!hasLivingRenderTree());
667 // We must make sure not to be retaining any of our children through
668 // these extra pointers or we will create a reference cycle.
669 m_focusedElement = nullptr;
670 m_hoveredElement = nullptr;
671 m_activeElement = nullptr;
672 m_titleElement = nullptr;
673 m_documentElement = nullptr;
674 m_focusNavigationStartingNode = nullptr;
675 m_userActionElements.documentDidRemoveLastRef();
676 #if ENABLE(FULLSCREEN_API)
677 m_fullScreenElement = nullptr;
678 m_fullScreenElementStack.clear();
683 // removeDetachedChildren() doesn't always unregister IDs,
684 // so tear down scope information up front to avoid having
685 // stale references in the map.
687 destroyTreeScopeData();
688 removeDetachedChildren();
689 m_formController = nullptr;
693 m_cssCanvasElements.clear();
698 // We need to do this right now since selfOnlyDeref() can delete this.
699 m_inRemovedLastRefFunction = false;
701 decrementReferencingNodeCount();
704 m_inRemovedLastRefFunction = false;
705 m_deletionHasBegun = true;
711 void Document::commonTeardown()
714 accessSVGExtensions().pauseAnimations();
716 #if ENABLE(REQUEST_ANIMATION_FRAME)
717 clearScriptedAnimationController();
721 Element* Document::getElementByAccessKey(const String& key)
725 if (!m_accessKeyMapValid) {
726 buildAccessKeyMap(this);
727 m_accessKeyMapValid = true;
729 return m_elementsByAccessKey.get(key.impl());
732 void Document::buildAccessKeyMap(TreeScope* scope)
735 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
736 const AtomicString& accessKey = element.attributeWithoutSynchronization(accesskeyAttr);
737 if (!accessKey.isEmpty())
738 m_elementsByAccessKey.set(accessKey.impl(), &element);
740 if (ShadowRoot* root = element.shadowRoot())
741 buildAccessKeyMap(root);
745 void Document::invalidateAccessKeyMap()
747 m_accessKeyMapValid = false;
748 m_elementsByAccessKey.clear();
751 void Document::addImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
753 return m_imagesByUsemap.add(name, element, *this);
756 void Document::removeImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
758 return m_imagesByUsemap.remove(name, element);
761 HTMLImageElement* Document::imageElementByCaseFoldedUsemap(const AtomicStringImpl& name) const
763 return m_imagesByUsemap.getElementByCaseFoldedUsemap(name, *this);
766 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
768 if (selectorString.isEmpty())
769 return Exception { SYNTAX_ERR };
770 if (!m_selectorQueryCache)
771 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
772 return m_selectorQueryCache->add(selectorString, *this);
775 void Document::clearSelectorQueryCache()
777 m_selectorQueryCache = nullptr;
780 MediaQueryMatcher& Document::mediaQueryMatcher()
782 if (!m_mediaQueryMatcher)
783 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
784 return *m_mediaQueryMatcher;
787 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
789 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
791 bool wasInQuirksMode = inQuirksMode();
792 m_compatibilityMode = mode;
794 clearSelectorQueryCache();
796 if (inQuirksMode() != wasInQuirksMode) {
797 // All user stylesheets have to reparse using the different mode.
798 extensionStyleSheets().clearPageUserSheet();
799 extensionStyleSheets().invalidateInjectedStyleSheetCache();
803 String Document::compatMode() const
805 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
808 void Document::resetLinkColor()
810 m_linkColor = Color(0, 0, 238);
813 void Document::resetVisitedLinkColor()
815 m_visitedLinkColor = Color(85, 26, 139);
818 void Document::resetActiveLinkColor()
820 m_activeLinkColor = Color(255, 0, 0);
823 DOMImplementation& Document::implementation()
825 if (!m_implementation)
826 m_implementation = std::make_unique<DOMImplementation>(*this);
827 return *m_implementation;
830 bool Document::hasManifest() const
832 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
835 DocumentType* Document::doctype() const
837 for (Node* node = firstChild(); node; node = node->nextSibling()) {
838 if (node->isDocumentTypeNode())
839 return static_cast<DocumentType*>(node);
844 void Document::childrenChanged(const ChildChange& change)
846 ContainerNode::childrenChanged(change);
849 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
850 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
851 // otherwise, we need to detect the doc type changes before updating the viewport.
852 if (Page* page = this->page())
853 page->chrome().didReceiveDocType(frame());
856 Element* newDocumentElement = childrenOfType<Element>(*this).first();
857 if (newDocumentElement == m_documentElement)
859 m_documentElement = newDocumentElement;
860 // The root style used for media query matching depends on the document element.
861 styleScope().clearResolver();
864 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
866 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled()
867 || Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
868 return HTMLUnknownElement::create(name, document);
870 auto element = HTMLElement::create(name, document);
871 element->setIsCustomElementUpgradeCandidate();
875 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const AtomicString& localName)
877 return createUpgradeCandidateElement(document, QualifiedName { nullAtom, localName, xhtmlNamespaceURI });
880 static inline bool isValidHTMLElementName(const AtomicString& localName)
882 return Document::isValidName(localName);
885 static inline bool isValidHTMLElementName(const QualifiedName& name)
887 return Document::isValidName(name.localName());
890 template<typename NameType>
891 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const NameType& name)
893 auto element = HTMLElementFactory::createKnownElement(name, document);
895 return Ref<Element> { element.releaseNonNull() };
897 if (auto* window = document.domWindow()) {
898 auto* registry = window->customElementRegistry();
899 if (UNLIKELY(registry)) {
900 if (auto* elementInterface = registry->findInterface(name))
901 return elementInterface->constructElementWithFallback(document, name);
905 if (UNLIKELY(!isValidHTMLElementName(name)))
906 return Exception { INVALID_CHARACTER_ERR };
908 return Ref<Element> { createUpgradeCandidateElement(document, name) };
911 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomicString& name)
913 if (isHTMLDocument())
914 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
916 if (isXHTMLDocument())
917 return createHTMLElementWithNameValidation(*this, name);
919 if (!isValidName(name))
920 return Exception { INVALID_CHARACTER_ERR };
922 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
925 Ref<DocumentFragment> Document::createDocumentFragment()
927 return DocumentFragment::create(document());
930 Ref<Text> Document::createTextNode(const String& data)
932 return Text::create(*this, data);
935 Ref<Comment> Document::createComment(const String& data)
937 return Comment::create(*this, data);
940 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
942 if (isHTMLDocument())
943 return Exception { NOT_SUPPORTED_ERR };
944 return CDATASection::create(*this, data);
947 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
949 if (!isValidName(target))
950 return Exception { INVALID_CHARACTER_ERR };
952 if (data.contains("?>"))
953 return Exception { INVALID_CHARACTER_ERR };
955 return ProcessingInstruction::create(*this, target, data);
958 Ref<Text> Document::createEditingTextNode(const String& text)
960 return Text::createEditingText(*this, text);
963 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
965 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
966 return *propertySet->ensureCSSStyleDeclaration();
969 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
971 switch (nodeToImport.nodeType()) {
972 case DOCUMENT_FRAGMENT_NODE:
973 if (nodeToImport.isShadowRoot())
978 case CDATA_SECTION_NODE:
979 case PROCESSING_INSTRUCTION_NODE:
981 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
984 // FIXME: This will "Attr::normalize" child nodes of Attr.
985 return Ref<Node> { Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(nodeToImport).name(), nullAtom), downcast<Attr>(nodeToImport).value()) };
987 case DOCUMENT_NODE: // Can't import a document into another document.
988 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
992 return Exception { NOT_SUPPORTED_ERR };
996 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
998 EventQueueScope scope;
1000 switch (source.nodeType()) {
1002 return Exception { NOT_SUPPORTED_ERR };
1003 case ATTRIBUTE_NODE: {
1004 auto& attr = downcast<Attr>(source);
1005 if (auto* element = attr.ownerElement()) {
1006 auto result = element->removeAttributeNode(attr);
1007 if (result.hasException())
1008 return result.releaseException();
1013 if (source.isShadowRoot()) {
1014 // ShadowRoot cannot disconnect itself from the host node.
1015 return Exception { HIERARCHY_REQUEST_ERR };
1017 if (is<HTMLFrameOwnerElement>(source)) {
1018 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
1019 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
1020 return Exception { HIERARCHY_REQUEST_ERR };
1022 auto result = source.remove();
1023 if (result.hasException())
1024 return result.releaseException();
1027 adoptIfNeeded(source);
1029 return Ref<Node> { source };
1032 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1034 // These checks are from DOM Core Level 2, createElementNS
1035 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1036 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1038 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1041 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1042 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1043 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1044 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1045 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1046 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1049 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1051 return hasValidNamespaceForElements(qName);
1054 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1056 if (auto* window = document.domWindow()) {
1057 auto* registry = window->customElementRegistry();
1058 if (UNLIKELY(registry)) {
1059 if (auto* elementInterface = registry->findInterface(name)) {
1060 auto element = HTMLElement::create(name, document);
1061 element->enqueueToUpgrade(*elementInterface);
1066 // FIXME: Should we also check the equality of prefix between the custom element and name?
1067 return createUpgradeCandidateElement(document, name);
1070 // FIXME: This should really be in a possible ElementFactory class.
1071 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1073 RefPtr<Element> element;
1075 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1076 if (name.namespaceURI() == xhtmlNamespaceURI) {
1077 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1078 if (UNLIKELY(!element))
1079 element = createFallbackHTMLElement(*this, name);
1080 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1081 element = SVGElementFactory::createElement(name, *this, createdByParser);
1083 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1084 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1088 m_sawElementsInKnownNamespaces = true;
1090 element = Element::create(name, document());
1092 // <image> uses imgTag so we need a special rule.
1093 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1095 return element.releaseNonNull();
1098 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomicString& localName)
1100 bool containsHyphen = false;
1101 for (auto character : StringView(localName).codeUnits()) {
1102 if (isASCIIUpper(character))
1103 return CustomElementNameValidationStatus::ContainsUpperCase;
1104 if (character == '-')
1105 containsHyphen = true;
1108 if (!containsHyphen)
1109 return CustomElementNameValidationStatus::NoHyphen;
1112 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag.localName();
1114 static NeverDestroyed<const AtomicString> annotationXmlLocalName("annotation-xml", AtomicString::ConstructFromLiteral);
1117 if (localName == SVGNames::color_profileTag.localName()
1118 || localName == SVGNames::font_faceTag.localName()
1119 || localName == SVGNames::font_face_formatTag.localName()
1120 || localName == SVGNames::font_face_nameTag.localName()
1121 || localName == SVGNames::font_face_srcTag.localName()
1122 || localName == SVGNames::font_face_uriTag.localName()
1123 || localName == SVGNames::missing_glyphTag.localName()
1124 || localName == annotationXmlLocalName)
1125 return CustomElementNameValidationStatus::ConflictsWithBuiltinNames;
1127 return CustomElementNameValidationStatus::Valid;
1130 #if ENABLE(CSS_GRID_LAYOUT)
1132 bool Document::isCSSGridLayoutEnabled() const
1134 return RuntimeEnabledFeatures::sharedFeatures().isCSSGridLayoutEnabled();
1139 #if ENABLE(CSS_REGIONS)
1141 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1146 updateStyleIfNeeded();
1148 return namedFlows().createCSSOMSnapshot();
1153 NamedFlowCollection& Document::namedFlows()
1156 m_namedFlows = NamedFlowCollection::create(this);
1158 return *m_namedFlows;
1161 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName)
1163 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1164 if (parseResult.hasException())
1165 return parseResult.releaseException();
1166 QualifiedName parsedName { parseResult.releaseReturnValue() };
1167 if (!hasValidNamespaceForElements(parsedName))
1168 return Exception { NAMESPACE_ERR };
1170 if (parsedName.namespaceURI() == xhtmlNamespaceURI)
1171 return createHTMLElementWithNameValidation(*this, parsedName);
1173 return createElement(parsedName, false);
1176 String Document::readyState() const
1178 static NeverDestroyed<const String> loading(ASCIILiteral("loading"));
1179 static NeverDestroyed<const String> interactive(ASCIILiteral("interactive"));
1180 static NeverDestroyed<const String> complete(ASCIILiteral("complete"));
1182 switch (m_readyState) {
1191 ASSERT_NOT_REACHED();
1195 void Document::setReadyState(ReadyState readyState)
1197 if (readyState == m_readyState)
1200 #if ENABLE(WEB_TIMING)
1201 switch (readyState) {
1203 if (!m_documentTiming.domLoading)
1204 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1207 if (!m_documentTiming.domInteractive)
1208 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1211 if (!m_documentTiming.domComplete)
1212 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1217 m_readyState = readyState;
1218 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1220 if (settings() && settings()->suppressesIncrementalRendering())
1221 setVisualUpdatesAllowed(readyState);
1224 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1226 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1227 switch (readyState) {
1229 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1230 ASSERT(m_visualUpdatesAllowed);
1231 setVisualUpdatesAllowed(false);
1234 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1237 if (m_visualUpdatesSuppressionTimer.isActive()) {
1238 ASSERT(!m_visualUpdatesAllowed);
1240 if (!view()->visualUpdatesAllowedByClient())
1243 setVisualUpdatesAllowed(true);
1245 ASSERT(m_visualUpdatesAllowed);
1250 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1252 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1255 m_visualUpdatesAllowed = visualUpdatesAllowed;
1257 if (visualUpdatesAllowed)
1258 m_visualUpdatesSuppressionTimer.stop();
1260 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1262 if (!visualUpdatesAllowed)
1265 FrameView* frameView = view();
1266 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1270 if (Page* page = this->page()) {
1271 if (frame()->isMainFrame()) {
1272 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1273 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1274 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1279 view()->updateCompositingLayersAfterLayout();
1281 if (RenderView* renderView = this->renderView())
1282 renderView->repaintViewAndCompositedLayers();
1284 if (Frame* frame = this->frame())
1285 frame->loader().forcePageTransitionIfNeeded();
1288 void Document::visualUpdatesSuppressionTimerFired()
1290 ASSERT(!m_visualUpdatesAllowed);
1292 // If the client is extending the visual update suppression period explicitly, the
1293 // watchdog should not re-enable visual updates itself, but should wait for the client.
1294 if (!view()->visualUpdatesAllowedByClient())
1297 setVisualUpdatesAllowed(true);
1300 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1302 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1303 // both of which we can determine by looking at the timer.
1305 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1306 setVisualUpdatesAllowed(true);
1309 String Document::characterSetWithUTF8Fallback() const
1311 AtomicString name = encoding();
1314 return UTF8Encoding().domName();
1317 String Document::defaultCharsetForLegacyBindings() const
1319 if (Settings* settings = this->settings())
1320 return settings->defaultTextEncodingName();
1321 return UTF8Encoding().domName();
1324 void Document::setCharset(const String& charset)
1328 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1331 void Document::setContentLanguage(const String& language)
1333 if (m_contentLanguage == language)
1335 m_contentLanguage = language;
1337 // Recalculate style so language is used when selecting the initial font.
1338 m_styleScope->didChangeStyleSheetEnvironment();
1341 ExceptionOr<void> Document::setXMLVersion(const String& version)
1343 if (!XMLDocumentParser::supportsXMLVersion(version))
1344 return Exception { NOT_SUPPORTED_ERR };
1346 m_xmlVersion = version;
1350 void Document::setXMLStandalone(bool standalone)
1352 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1355 void Document::setDocumentURI(const String& uri)
1357 // This property is read-only from JavaScript, but writable from Objective-C.
1358 m_documentURI = uri;
1362 void Document::setContent(const String& content)
1365 // FIXME: This should probably use insert(), but that's (intentionally)
1366 // not implemented for the XML parser as it's normally synonymous with
1367 // document.write(). append() will end up yielding, but close() will
1368 // pump the tokenizer syncrhonously and finish the parse.
1369 m_parser->append(content.impl());
1373 String Document::suggestedMIMEType() const
1375 if (isXHTMLDocument())
1376 return ASCIILiteral("application/xhtml+xml");
1377 if (isSVGDocument())
1378 return ASCIILiteral("image/svg+xml");
1379 if (xmlStandalone())
1380 return ASCIILiteral("text/xml");
1381 if (isHTMLDocument())
1382 return ASCIILiteral("text/html");
1383 if (DocumentLoader* loader = this->loader())
1384 return loader->responseMIMEType();
1388 void Document::overrideMIMEType(const String& mimeType)
1390 m_overriddenMIMEType = mimeType;
1393 String Document::contentType() const
1395 if (!m_overriddenMIMEType.isNull())
1396 return m_overriddenMIMEType;
1398 if (DocumentLoader* documentLoader = loader())
1399 return documentLoader->currentContentType();
1401 String mimeType = suggestedMIMEType();
1402 if (!mimeType.isNull())
1405 return ASCIILiteral("application/xml");
1408 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1410 return caretRangeFromPoint(LayoutPoint(x, y));
1413 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1415 if (!hasLivingRenderTree())
1418 LayoutPoint localPoint;
1419 Node* node = nodeFromPoint(clientPoint, &localPoint);
1423 Node* shadowAncestorNode = ancestorInThisScope(node);
1424 if (shadowAncestorNode != node) {
1425 unsigned offset = shadowAncestorNode->computeNodeIndex();
1426 ContainerNode* container = shadowAncestorNode->parentNode();
1427 return Range::create(*this, container, offset, container, offset);
1430 RenderObject* renderer = node->renderer();
1433 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1434 if (visiblePosition.isNull())
1437 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1438 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1441 Element* Document::scrollingElement()
1443 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1444 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1450 * Performs three operations:
1451 * 1. Convert control characters to spaces
1452 * 2. Trim leading and trailing spaces
1453 * 3. Collapse internal whitespace.
1455 template <typename CharacterType>
1456 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1458 const String& title = titleWithDirection.string();
1459 const CharacterType* characters = title.characters<CharacterType>();
1460 unsigned length = title.length();
1463 StringBuffer<CharacterType> buffer(length);
1464 unsigned builderIndex = 0;
1466 // Skip leading spaces and leading characters that would convert to spaces
1467 for (i = 0; i < length; ++i) {
1468 CharacterType c = characters[i];
1469 if (isNotHTMLSpace(c))
1474 return StringWithDirection();
1476 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1477 bool previousCharWasWS = false;
1478 for (; i < length; ++i) {
1479 CharacterType c = characters[i];
1480 if (isHTMLSpace(c)) {
1481 if (previousCharWasWS)
1483 buffer[builderIndex++] = ' ';
1484 previousCharWasWS = true;
1486 buffer[builderIndex++] = c;
1487 previousCharWasWS = false;
1491 // Strip trailing spaces
1492 while (builderIndex > 0) {
1494 if (buffer[builderIndex] != ' ')
1498 if (!builderIndex && buffer[builderIndex] == ' ')
1499 return StringWithDirection();
1501 buffer.shrink(builderIndex + 1);
1503 // Replace the backslashes with currency symbols if the encoding requires it.
1504 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1506 return StringWithDirection(String::adopt(WTFMove(buffer)), titleWithDirection.direction());
1509 void Document::updateTitle(const StringWithDirection& title)
1511 if (m_rawTitle == title)
1516 if (m_rawTitle.string().isEmpty())
1517 m_title = StringWithDirection();
1519 if (m_rawTitle.string().is8Bit())
1520 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1522 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1524 if (DocumentLoader* loader = this->loader())
1525 loader->setTitle(m_title);
1528 void Document::updateTitleFromTitleElement()
1530 if (!m_titleElement) {
1531 updateTitle(StringWithDirection());
1535 if (is<HTMLTitleElement>(*m_titleElement))
1536 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1537 else if (is<SVGTitleElement>(*m_titleElement)) {
1538 // FIXME: does SVG have a title text direction?
1539 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1543 void Document::setTitle(const String& title)
1545 if (!m_titleElement) {
1546 if (isHTMLDocument() || isXHTMLDocument()) {
1547 auto* headElement = head();
1550 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1551 headElement->appendChild(*m_titleElement);
1552 } else if (isSVGDocument()) {
1553 auto* element = documentElement();
1554 if (!is<SVGSVGElement>(element))
1556 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1557 element->insertBefore(*m_titleElement, element->firstChild());
1559 } else if (!isHTMLDocument() && !isXHTMLDocument() && !isSVGDocument())
1560 m_titleElement = nullptr;
1562 // The DOM API has no method of specifying direction, so assume LTR.
1563 updateTitle(StringWithDirection(title, LTR));
1565 if (is<HTMLTitleElement>(m_titleElement.get()))
1566 downcast<HTMLTitleElement>(*m_titleElement).setTextContent(title);
1567 else if (is<SVGTitleElement>(m_titleElement.get()))
1568 downcast<SVGTitleElement>(*m_titleElement).setTextContent(title);
1571 void Document::updateTitleElement(Element* newTitleElement)
1573 if (is<SVGSVGElement>(documentElement()))
1574 m_titleElement = childrenOfType<SVGTitleElement>(*documentElement()).first();
1576 if (m_titleElement) {
1577 if (isHTMLDocument() || isXHTMLDocument())
1578 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1580 m_titleElement = newTitleElement;
1583 updateTitleFromTitleElement();
1586 void Document::titleElementAdded(Element& titleElement)
1588 if (m_titleElement == &titleElement)
1591 updateTitleElement(&titleElement);
1594 void Document::titleElementRemoved(Element& titleElement)
1596 if (m_titleElement != &titleElement)
1599 updateTitleElement(nullptr);
1602 void Document::titleElementTextChanged(Element& titleElement)
1604 if (m_titleElement != &titleElement)
1607 updateTitleFromTitleElement();
1610 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1612 m_visibilityStateCallbackElements.add(element);
1615 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1617 m_visibilityStateCallbackElements.remove(element);
1620 void Document::visibilityStateChanged()
1622 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1623 for (auto* element : m_visibilityStateCallbackElements)
1624 element->visibilityStateChanged();
1627 PageVisibilityState Document::pageVisibilityState() const
1629 // The visibility of the document is inherited from the visibility of the
1630 // page. If there is no page associated with the document, we will assume
1631 // that the page is hidden, as specified by the spec:
1632 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1633 if (!m_frame || !m_frame->page())
1634 return PageVisibilityStateHidden;
1635 return m_frame->page()->visibilityState();
1638 String Document::visibilityState() const
1640 return pageVisibilityStateString(pageVisibilityState());
1643 bool Document::hidden() const
1645 return pageVisibilityState() != PageVisibilityStateVisible;
1650 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1652 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1655 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1657 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1660 void Document::allowsMediaDocumentInlinePlaybackChanged()
1662 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1663 element->allowsMediaDocumentInlinePlaybackChanged();
1668 String Document::nodeName() const
1670 return ASCIILiteral("#document");
1673 Node::NodeType Document::nodeType() const
1675 return DOCUMENT_NODE;
1678 FormController& Document::formController()
1680 if (!m_formController)
1681 m_formController = std::make_unique<FormController>();
1682 return *m_formController;
1685 Vector<String> Document::formElementsState() const
1687 if (!m_formController)
1688 return Vector<String>();
1689 return m_formController->formElementsState();
1692 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1694 if (!stateVector.size() && !m_formController)
1696 formController().setStateForNewFormElements(stateVector);
1699 FrameView* Document::view() const
1701 return m_frame ? m_frame->view() : nullptr;
1704 Page* Document::page() const
1706 return m_frame ? m_frame->page() : nullptr;
1709 Settings* Document::settings() const
1711 return m_frame ? &m_frame->settings() : nullptr;
1714 Ref<Range> Document::createRange()
1716 return Range::create(*this);
1719 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1721 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1724 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1726 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1729 void Document::scheduleForcedStyleRecalc()
1731 m_pendingStyleRecalcShouldForce = true;
1732 scheduleStyleRecalc();
1735 void Document::scheduleStyleRecalc()
1737 ASSERT(!m_renderView || !m_renderView->inHitTesting());
1739 if (m_styleRecalcTimer.isActive() || pageCacheState() != NotInPageCache)
1742 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1744 // FIXME: Why on earth is this here? This is clearly misplaced.
1745 invalidateAccessKeyMap();
1747 m_styleRecalcTimer.startOneShot(0);
1749 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1752 void Document::unscheduleStyleRecalc()
1754 ASSERT(!childNeedsStyleRecalc());
1756 m_styleRecalcTimer.stop();
1757 m_pendingStyleRecalcShouldForce = false;
1760 bool Document::hasPendingStyleRecalc() const
1762 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1765 bool Document::hasPendingForcedStyleRecalc() const
1767 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1770 void Document::recalcStyle(Style::Change change)
1772 ASSERT(!view() || !view()->isPainting());
1774 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1778 FrameView& frameView = m_renderView->frameView();
1779 Ref<FrameView> protect(frameView);
1780 if (frameView.isPainting())
1783 if (m_inStyleRecalc)
1784 return; // Guard against re-entrancy. -dwh
1786 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1788 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1789 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1791 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1792 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1793 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1794 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1795 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1796 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1798 styleScope().flushPendingUpdate();
1800 frameView.willRecalcStyle();
1802 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1804 m_inStyleRecalc = true;
1805 bool updatedCompositingLayers = false;
1807 Style::PostResolutionCallbackDisabler disabler(*this);
1808 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1810 if (m_pendingStyleRecalcShouldForce)
1811 change = Style::Force;
1813 if (change == Style::Force) {
1814 // This may get set again during style resolve.
1815 m_hasNodesWithPlaceholderStyle = false;
1817 auto documentStyle = Style::resolveForDocument(*this);
1819 // Inserting the pictograph font at the end of the font fallback list is done by the
1820 // font selector, so set a font selector if needed.
1821 if (Settings* settings = this->settings()) {
1822 if (settings->fontFallbackPrefersPictographs())
1823 documentStyle.fontCascade().update(&fontSelector());
1826 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
1827 if (documentChange != Style::NoChange)
1828 renderView()->setStyle(WTFMove(documentStyle));
1831 Style::TreeResolver resolver(*this);
1832 auto styleUpdate = resolver.resolve(change);
1834 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
1837 clearChildNeedsStyleRecalc();
1838 unscheduleStyleRecalc();
1840 m_inStyleRecalc = false;
1843 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1845 RenderTreeUpdater updater(*this);
1846 updater.commit(WTFMove(styleUpdate));
1849 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1852 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1853 if (m_closeAfterStyleRecalc) {
1854 m_closeAfterStyleRecalc = false;
1858 ++m_styleRecalcCount;
1860 InspectorInstrumentation::didRecalculateStyle(cookie);
1862 // Some animated images may now be inside the viewport due to style recalc,
1863 // resume them if necessary if there is no layout pending. Otherwise, we'll
1864 // check if they need to be resumed after layout.
1865 if (updatedCompositingLayers && !frameView.needsLayout())
1866 frameView.viewportContentsChanged();
1868 if (!frameView.needsLayout())
1869 frameView.frame().selection().updateAppearanceAfterLayout();
1871 // As a result of the style recalculation, the currently hovered element might have been
1872 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1873 // to check if any other elements ended up under the mouse pointer due to re-layout.
1874 if (m_hoveredElement && !m_hoveredElement->renderer())
1875 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1878 bool Document::needsStyleRecalc() const
1880 if (pageCacheState() != NotInPageCache)
1883 return m_pendingStyleRecalcShouldForce || childNeedsStyleRecalc() || styleScope().hasPendingUpdate();
1886 void Document::updateStyleIfNeeded()
1888 ASSERT(isMainThread());
1889 ASSERT(!view() || !view()->isPainting());
1891 if (!view() || view()->isInRenderTreeLayout())
1894 styleScope().flushPendingUpdate();
1896 if (!needsStyleRecalc())
1902 void Document::updateLayout()
1904 ASSERT(isMainThread());
1906 FrameView* frameView = view();
1907 if (frameView && frameView->isInRenderTreeLayout()) {
1908 // View layout should not be re-entrant.
1909 ASSERT_NOT_REACHED();
1913 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1915 if (HTMLFrameOwnerElement* owner = ownerElement())
1916 owner->document().updateLayout();
1918 updateStyleIfNeeded();
1920 StackStats::LayoutCheckPoint layoutCheckPoint;
1922 // Only do a layout if changes have occurred that make it necessary.
1923 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1924 frameView->layout();
1927 // FIXME: This is a bad idea and needs to be removed eventually.
1928 // Other browsers load stylesheets before they continue parsing the web page.
1929 // Since we don't, we can run JavaScript code that needs answers before the
1930 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1931 // lets us get reasonable answers. The long term solution to this problem is
1932 // to instead suspend JavaScript execution.
1933 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1935 bool oldIgnore = m_ignorePendingStylesheets;
1937 if (!haveStylesheetsLoaded()) {
1938 m_ignorePendingStylesheets = true;
1939 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1940 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1941 // with accurate style information. (Our suppression involves blanking the whole page at the
1942 // moment. If it were more refined, we might be able to do something better.)
1943 // It's worth noting though that this entire method is a hack, since what we really want to do is
1944 // suspend JS instead of doing a layout with inaccurate information.
1945 HTMLElement* bodyElement = bodyOrFrameset();
1946 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1947 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1948 styleScope().didChangeActiveStyleSheetCandidates();
1949 recalcStyle(Style::Force);
1950 } else if (m_hasNodesWithPlaceholderStyle)
1951 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1952 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1953 // but here we need up-to-date style immediately.
1954 recalcStyle(Style::Force);
1959 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1960 view()->flushAnyPendingPostLayoutTasks();
1962 m_ignorePendingStylesheets = oldIgnore;
1965 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle)
1967 ASSERT(&element.document() == this);
1969 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1970 Style::PostResolutionCallbackDisabler disabler(*this);
1972 SetForScope<bool> change(m_ignorePendingStylesheets, true);
1973 auto elementStyle = element.resolveStyle(parentStyle);
1975 if (elementStyle.relations) {
1976 Style::Update emptyUpdate(*this);
1977 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
1980 return WTFMove(elementStyle.renderStyle);
1983 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
1985 ASSERT(isMainThread());
1987 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
1988 if (!haveStylesheetsLoaded()) {
1989 updateLayoutIgnorePendingStylesheets();
1993 // Check for re-entrancy and assert (same code that is in updateLayout()).
1994 FrameView* frameView = view();
1995 if (frameView && frameView->isInRenderTreeLayout()) {
1996 // View layout should not be re-entrant.
1997 ASSERT_NOT_REACHED();
2001 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2003 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2005 bool requireFullLayout = false;
2006 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2007 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2008 requireFullLayout = true;
2011 updateStyleIfNeeded();
2013 RenderObject* renderer = element.renderer();
2014 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2015 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2016 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2017 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2018 requireFullLayout = true;
2021 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2022 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2023 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2024 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2026 if (!requireFullLayout) {
2027 RenderBox* previousBox = nullptr;
2028 RenderBox* currentBox = nullptr;
2030 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2031 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2033 // Require the entire container chain to be boxes.
2034 if (!is<RenderBox>(currRenderer)) {
2035 requireFullLayout = true;
2039 previousBox = currentBox;
2040 currentBox = downcast<RenderBox>(currRenderer);
2042 // If a box needs layout for itself or if a box has changed children and sizes its width to
2043 // its content, then require a full layout.
2044 if (currentBox->selfNeedsLayout() ||
2045 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2046 requireFullLayout = true;
2050 // If a block contains floats and the child's height isn't specified, then
2051 // give up also, since our height could end up being influenced by the floats.
2052 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2053 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2054 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2055 requireFullLayout = true;
2060 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2061 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2062 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2063 // Disallow regions/columns from having the optimization.
2064 // Give up if the writing mode changes at all in the containing block chain.
2065 requireFullLayout = true;
2069 if (currRenderer == frameView->layoutRoot())
2074 StackStats::LayoutCheckPoint layoutCheckPoint;
2076 // Only do a layout if changes have occurred that make it necessary.
2077 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2078 frameView->layout();
2080 return requireFullLayout;
2083 bool Document::isPageBoxVisible(int pageIndex)
2085 updateStyleIfNeeded();
2086 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2087 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2090 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2092 updateStyleIfNeeded();
2093 std::unique_ptr<RenderStyle> style = styleScope().resolver().styleForPage(pageIndex);
2095 int width = pageSize.width();
2096 int height = pageSize.height();
2097 switch (style->pageSizeType()) {
2098 case PAGE_SIZE_AUTO:
2100 case PAGE_SIZE_AUTO_LANDSCAPE:
2102 std::swap(width, height);
2104 case PAGE_SIZE_AUTO_PORTRAIT:
2106 std::swap(width, height);
2108 case PAGE_SIZE_RESOLVED: {
2109 LengthSize size = style->pageSize();
2110 ASSERT(size.width().isFixed());
2111 ASSERT(size.height().isFixed());
2112 width = valueForLength(size.width(), 0);
2113 height = valueForLength(size.height(), 0);
2117 ASSERT_NOT_REACHED();
2119 pageSize = IntSize(width, height);
2121 // The percentage is calculated with respect to the width even for margin top and bottom.
2122 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2123 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2124 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2125 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2126 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2129 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2131 if (!m_userAgentShadowTreeStyleResolver)
2132 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2133 return *m_userAgentShadowTreeStyleResolver;
2136 void Document::fontsNeedUpdate(FontSelector&)
2138 if (auto* resolver = styleScope().resolverIfExists())
2139 resolver->invalidateMatchedPropertiesCache();
2140 if (pageCacheState() != NotInPageCache || !renderView())
2142 scheduleForcedStyleRecalc();
2145 void Document::didClearStyleResolver()
2147 m_userAgentShadowTreeStyleResolver = nullptr;
2149 m_fontSelector->buildStarted();
2152 void Document::createRenderTree()
2154 ASSERT(!renderView());
2155 ASSERT(m_pageCacheState != InPageCache);
2156 ASSERT(!m_axObjectCache || this != &topDocument());
2158 if (m_isNonRenderedPlaceholder)
2161 // FIXME: It would be better if we could pass the resolved document style directly here.
2162 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2163 Node::setRenderer(m_renderView.get());
2165 renderView()->setIsInWindow(true);
2167 recalcStyle(Style::Force);
2170 void Document::didBecomeCurrentDocumentInFrame()
2172 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2173 // If so, then m_frame could become 0, and we need to do something about that.
2175 m_frame->script().updateDocument();
2177 if (!hasLivingRenderTree())
2180 updateViewportArguments();
2182 // FIXME: Doing this only for the main frame is insufficient.
2183 // Changing a subframe can also change the wheel event handler count.
2184 // FIXME: Doing this only when a document goes into the frame is insufficient.
2185 // Removing a document can also change the wheel event handler count.
2186 // FIXME: Doing this every time is a waste. If the current document and its
2187 // subframes' documents have no wheel event handlers, then the count did not change,
2188 // unless the documents they are replacing had wheel event handlers.
2189 if (page() && m_frame->isMainFrame())
2190 wheelEventHandlersChanged();
2192 #if ENABLE(TOUCH_EVENTS)
2193 // FIXME: Doing this only for the main frame is insufficient.
2194 // A subframe could have touch event handlers.
2195 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2196 page()->chrome().client().needTouchEvents(true);
2199 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2200 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2201 // page cache, or simply newly created).
2202 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2203 m_frame->animation().suspendAnimationsForDocument(this);
2204 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2206 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2207 m_frame->animation().resumeAnimationsForDocument(this);
2211 void Document::disconnectFromFrame()
2216 void Document::destroyRenderTree()
2218 ASSERT(hasLivingRenderTree());
2219 ASSERT(m_pageCacheState != InPageCache);
2221 SetForScope<bool> change(m_renderTreeBeingDestroyed, true);
2223 if (this == &topDocument())
2224 clearAXObjectCache();
2226 documentWillBecomeInactive();
2228 if (FrameView* frameView = view())
2229 frameView->detachCustomScrollbars();
2231 #if ENABLE(FULLSCREEN_API)
2232 if (m_fullScreenRenderer)
2233 setFullScreenRenderer(nullptr);
2236 m_hoveredElement = nullptr;
2237 m_focusedElement = nullptr;
2238 m_activeElement = nullptr;
2239 m_focusNavigationStartingNode = nullptr;
2241 if (m_documentElement)
2242 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2244 clearChildNeedsStyleRecalc();
2246 unscheduleStyleRecalc();
2248 m_renderView = nullptr;
2249 Node::setRenderer(nullptr);
2251 #if ENABLE(TEXT_AUTOSIZING)
2252 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2253 m_textAutoSizedNodes.clear();
2257 void Document::prepareForDestruction()
2259 if (m_hasPreparedForDestruction)
2262 #if ENABLE(IOS_TOUCH_EVENTS)
2263 clearTouchEventHandlersAndListeners();
2266 #if HAVE(ACCESSIBILITY)
2267 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2268 if (this != &topDocument()) {
2269 if (AXObjectCache* cache = existingAXObjectCache())
2270 cache->clearTextMarkerNodesInUse(this);
2274 disconnectDescendantFrames();
2275 if (m_domWindow && m_frame)
2276 m_domWindow->willDetachDocumentFromFrame();
2278 if (hasLivingRenderTree())
2279 destroyRenderTree();
2281 if (is<PluginDocument>(*this))
2282 downcast<PluginDocument>(*this).detachFromPluginElement();
2284 #if ENABLE(POINTER_LOCK)
2286 page()->pointerLockController().documentDetached(this);
2289 InspectorInstrumentation::documentDetached(*this);
2291 stopActiveDOMObjects();
2292 m_eventQueue.close();
2293 #if ENABLE(FULLSCREEN_API)
2294 m_fullScreenChangeEventTargetQueue.clear();
2295 m_fullScreenErrorEventTargetQueue.clear();
2300 #if ENABLE(TOUCH_EVENTS)
2301 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2302 parentDocument()->didRemoveEventTargetNode(*this);
2305 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2306 parentDocument()->didRemoveEventTargetNode(*this);
2308 if (m_mediaQueryMatcher)
2309 m_mediaQueryMatcher->documentDestroyed();
2311 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2312 if (!m_clientToIDMap.isEmpty() && page()) {
2313 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2314 copyKeysToVector(m_clientToIDMap, clients);
2315 for (auto* client : clients)
2316 removePlaybackTargetPickerClient(*client);
2320 disconnectFromFrame();
2322 m_hasPreparedForDestruction = true;
2325 void Document::removeAllEventListeners()
2327 EventTarget::removeAllEventListeners();
2330 m_domWindow->removeAllEventListeners();
2331 #if ENABLE(IOS_TOUCH_EVENTS)
2332 clearTouchEventHandlersAndListeners();
2334 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2335 node->removeAllEventListeners();
2337 #if ENABLE(TOUCH_EVENTS)
2338 m_touchEventTargets = nullptr;
2340 m_wheelEventTargets = nullptr;
2343 void Document::suspendDeviceMotionAndOrientationUpdates()
2345 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2347 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2348 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2349 if (m_deviceMotionController)
2350 m_deviceMotionController->suspendUpdates();
2351 if (m_deviceOrientationController)
2352 m_deviceOrientationController->suspendUpdates();
2356 void Document::resumeDeviceMotionAndOrientationUpdates()
2358 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2360 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2361 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2362 if (m_deviceMotionController)
2363 m_deviceMotionController->resumeUpdates();
2364 if (m_deviceOrientationController)
2365 m_deviceOrientationController->resumeUpdates();
2369 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2371 JSC::CallFrame* callFrame = JSDOMWindow::commonVM().topCallFrame;
2372 if (callFrame == JSC::CallFrame::noCaller())
2374 DOMWrapperWorld& domWrapperWorld = currentWorld(callFrame);
2375 if (domWrapperWorld.isNormal())
2380 void Document::platformSuspendOrStopActiveDOMObjects()
2383 if (WebThreadCountOfObservedContentModifiers() > 0) {
2384 Frame* frame = this->frame();
2385 if (Page* page = frame ? frame->page() : nullptr)
2386 page->chrome().client().clearContentChangeObservers(frame);
2391 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2393 ScriptExecutionContext::suspendActiveDOMObjects(why);
2394 suspendDeviceMotionAndOrientationUpdates();
2395 platformSuspendOrStopActiveDOMObjects();
2398 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2400 ScriptExecutionContext::resumeActiveDOMObjects(why);
2401 resumeDeviceMotionAndOrientationUpdates();
2402 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2405 void Document::stopActiveDOMObjects()
2407 ScriptExecutionContext::stopActiveDOMObjects();
2408 platformSuspendOrStopActiveDOMObjects();
2411 void Document::clearAXObjectCache()
2413 ASSERT(&topDocument() == this);
2414 // Clear the cache member variable before calling delete because attempts
2415 // are made to access it during destruction.
2416 m_axObjectCache = nullptr;
2419 static bool hasEverCreatedAnAXObjectCache = false;
2421 AXObjectCache* Document::existingAXObjectCache() const
2423 if (!hasEverCreatedAnAXObjectCache)
2426 Document& topDocument = this->topDocument();
2427 if (!topDocument.hasLivingRenderTree())
2429 return topDocument.m_axObjectCache.get();
2432 AXObjectCache* Document::axObjectCache() const
2434 if (!AXObjectCache::accessibilityEnabled())
2437 // The only document that actually has a AXObjectCache is the top-level
2438 // document. This is because we need to be able to get from any WebCoreAXObject
2439 // to any other WebCoreAXObject on the same page. Using a single cache allows
2440 // lookups across nested webareas (i.e. multiple documents).
2441 Document& topDocument = this->topDocument();
2443 // If the document has already been detached, do not make a new axObjectCache.
2444 if (!topDocument.hasLivingRenderTree())
2447 ASSERT(&topDocument == this || !m_axObjectCache);
2448 if (!topDocument.m_axObjectCache) {
2449 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2450 hasEverCreatedAnAXObjectCache = true;
2452 return topDocument.m_axObjectCache.get();
2455 void Document::setVisuallyOrdered()
2457 m_visuallyOrdered = true;
2459 renderView()->mutableStyle().setRTLOrdering(VisualOrder);
2462 Ref<DocumentParser> Document::createParser()
2464 // FIXME: this should probably pass the frame instead
2465 return XMLDocumentParser::create(*this, view());
2468 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2470 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2473 void Document::open(Document* ownerDocument)
2475 if (m_ignoreOpensDuringUnloadCount)
2478 if (ownerDocument) {
2479 setURL(ownerDocument->url());
2480 setCookieURL(ownerDocument->cookieURL());
2481 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2485 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2486 if (parser->isParsing()) {
2487 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2488 if (parser->isExecutingScript())
2491 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2496 if (m_frame->loader().state() == FrameStateProvisional)
2497 m_frame->loader().stopAllLoaders();
2500 removeAllEventListeners();
2502 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2503 parser->setWasCreatedByScript(true);
2506 m_frame->loader().didExplicitOpen();
2509 void Document::detachParser()
2517 void Document::cancelParsing()
2522 // We have to clear the parser to avoid possibly triggering
2523 // the onload handler when closing as a side effect of a cancel-style
2524 // change, such as opening a new document or closing the window while
2530 void Document::implicitOpen()
2534 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2537 m_parser = createParser();
2539 setReadyState(Loading);
2542 HTMLBodyElement* Document::body() const
2544 auto* element = documentElement();
2547 return childrenOfType<HTMLBodyElement>(*element).first();
2550 HTMLElement* Document::bodyOrFrameset() const
2552 // Return the first body or frameset child of the html element.
2553 auto* element = documentElement();
2554 if (!is<HTMLHtmlElement>(element))
2556 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2557 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2563 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2565 if (!is<HTMLBodyElement>(newBody.get()) && !is<HTMLFrameSetElement>(newBody.get()))
2566 return Exception { HIERARCHY_REQUEST_ERR };
2568 auto* currentBody = bodyOrFrameset();
2569 if (newBody == currentBody)
2572 if (!m_documentElement)
2573 return Exception { HIERARCHY_REQUEST_ERR };
2576 return m_documentElement->replaceChild(*newBody, *currentBody);
2577 return m_documentElement->appendChild(*newBody);
2580 Location* Document::location() const
2582 auto* window = domWindow();
2586 return window->location();
2589 HTMLHeadElement* Document::head()
2591 if (auto element = documentElement())
2592 return childrenOfType<HTMLHeadElement>(*element).first();
2596 void Document::close()
2598 // FIXME: We should follow the specification more closely:
2599 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2601 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2607 void Document::explicitClose()
2609 if (RefPtr<DocumentParser> parser = m_parser)
2613 // Because we have no frame, we don't know if all loading has completed,
2614 // so we just call implicitClose() immediately. FIXME: This might fire
2615 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2620 m_frame->loader().checkCompleted();
2623 void Document::implicitClose()
2625 // 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.
2626 if (m_inStyleRecalc) {
2627 m_closeAfterStyleRecalc = true;
2631 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2632 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2637 // Call to dispatchWindowLoadEvent can blow us from underneath.
2638 Ref<Document> protectedThis(*this);
2640 m_processingLoadEvent = true;
2642 ScriptableDocumentParser* parser = scriptableDocumentParser();
2643 m_wellFormed = parser && parser->wellFormed();
2645 // We have to clear the parser, in case someone document.write()s from the
2646 // onLoad event handler, as in Radar 3206524.
2649 // FIXME: We kick off the icon loader when the Document is done parsing.
2650 // There are earlier opportunities we could start it:
2651 // -When the <head> finishes parsing
2652 // -When any new HTMLLinkElement is inserted into the document
2653 // But those add a dynamic component to the favicon that has UI
2654 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2657 if (f->loader().client().useIconLoadingClient()) {
2658 if (auto* documentLoader = loader())
2659 documentLoader->startIconLoading();
2661 f->loader().icon().startLoader();
2663 f->animation().startAnimationsIfNotSuspended(this);
2665 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2666 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2667 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2668 ImageLoader::dispatchPendingBeforeLoadEvents();
2669 ImageLoader::dispatchPendingLoadEvents();
2670 ImageLoader::dispatchPendingErrorEvents();
2671 HTMLLinkElement::dispatchPendingLoadEvents();
2672 HTMLStyleElement::dispatchPendingLoadEvents();
2675 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2676 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2677 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2678 if (svgExtensions())
2679 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2681 dispatchWindowLoadEvent();
2682 enqueuePageshowEvent(PageshowEventNotPersisted);
2683 if (m_pendingStateObject)
2684 enqueuePopstateEvent(WTFMove(m_pendingStateObject));
2687 f->loader().dispatchOnloadEvents();
2689 // An event handler may have removed the frame
2691 m_processingLoadEvent = false;
2695 // Make sure both the initial layout and reflow happen after the onload
2696 // fires. This will improve onload scores, and other browsers do it.
2697 // If they wanna cheat, we can too. -dwh
2699 if (frame()->navigationScheduler().locationChangePending() && timeSinceDocumentCreation() < settings()->layoutInterval()) {
2700 // Just bail out. Before or during the onload we were shifted to another page.
2701 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2702 m_processingLoadEvent = false;
2703 view()->unscheduleRelayout();
2707 frame()->loader().checkCallImplicitClose();
2709 // We used to force a synchronous display and flush here. This really isn't
2710 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2711 // (if your platform is syncing flushes and limiting them to 60fps).
2712 m_overMinimumLayoutThreshold = true;
2713 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2714 updateStyleIfNeeded();
2716 // Always do a layout after loading if needed.
2717 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2721 m_processingLoadEvent = false;
2723 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2724 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2725 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2726 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2727 // exists in the cache (we ignore the return value because we don't need it here). This is
2728 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2730 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2731 // catch new AND page history loads, and that uses AXLoadComplete
2733 axObjectCache()->getOrCreate(renderView());
2734 if (this == &topDocument())
2735 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2737 // AXLoadComplete can only be posted on the top document, so if it's a document
2738 // in an iframe that just finished loading, post AXLayoutComplete instead.
2739 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2744 if (svgExtensions())
2745 accessSVGExtensions().startAnimations();
2748 void Document::setParsing(bool b)
2752 if (m_bParsing && !m_sharedObjectPool)
2753 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2755 if (!m_bParsing && view() && !view()->needsLayout())
2756 view()->fireLayoutRelatedMilestonesIfNeeded();
2759 bool Document::shouldScheduleLayout()
2761 // This function will only be called when FrameView thinks a layout is needed.
2762 // This enforces a couple extra rules.
2764 // (a) Only schedule a layout once the stylesheets are loaded.
2765 // (b) Only schedule layout once we have a body element.
2767 return (haveStylesheetsLoaded() && bodyOrFrameset())
2768 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2771 bool Document::isLayoutTimerActive()
2773 return view() && view()->layoutPending() && !minimumLayoutDelay();
2776 Seconds Document::minimumLayoutDelay()
2778 if (m_overMinimumLayoutThreshold)
2781 auto elapsed = timeSinceDocumentCreation();
2782 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2784 // We'll want to schedule the timer to fire at the minimum layout threshold.
2785 return std::max(0_s, settings()->layoutInterval() - elapsed);
2788 Seconds Document::timeSinceDocumentCreation() const
2790 return MonotonicTime::now() - m_documentCreationTime;
2793 void Document::write(const SegmentedString& text, Document* ownerDocument)
2795 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2797 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2798 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2800 if (m_writeRecursionIsTooDeep)
2803 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2804 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2807 if (!hasInsertionPoint)
2808 open(ownerDocument);
2811 m_parser->insert(text);
2814 void Document::write(const String& text, Document* ownerDocument)
2816 write(SegmentedString(text), ownerDocument);
2819 void Document::writeln(const String& text, Document* ownerDocument)
2821 write(text, ownerDocument);
2822 write("\n", ownerDocument);
2825 std::chrono::milliseconds Document::minimumTimerInterval() const
2827 auto* page = this->page();
2829 return ScriptExecutionContext::minimumTimerInterval();
2830 return page->settings().minimumDOMTimerInterval();
2833 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2835 if (m_isTimerThrottlingEnabled == shouldThrottle)
2838 m_isTimerThrottlingEnabled = shouldThrottle;
2839 didChangeTimerAlignmentInterval();
2842 std::chrono::milliseconds Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2844 auto alignmentInterval = ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2846 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2847 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2848 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
2850 if (Page* page = this->page())
2851 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
2853 return alignmentInterval;
2856 EventTarget* Document::errorEventTarget()
2858 return m_domWindow.get();
2861 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2863 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2866 void Document::setURL(const URL& url)
2868 const URL& newURL = url.isEmpty() ? blankURL() : url;
2869 if (newURL == m_url)
2873 m_documentURI = m_url.string();
2877 void Document::updateBaseURL()
2879 URL oldBaseURL = m_baseURL;
2880 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2881 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2882 // from the Document interface otherwise.
2883 if (!m_baseElementURL.isEmpty())
2884 m_baseURL = m_baseElementURL;
2885 else if (!m_baseURLOverride.isEmpty())
2886 m_baseURL = m_baseURLOverride;
2888 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2889 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2890 // and DOM 3 Core does not specify how it should be resolved.
2891 m_baseURL = URL(ParsedURLString, documentURI());
2894 clearSelectorQueryCache();
2896 if (!m_baseURL.isValid())
2899 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2900 // Base URL change changes any relative visited links.
2901 // 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.
2902 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2903 anchor.invalidateCachedVisitedLinkHash();
2907 void Document::setBaseURLOverride(const URL& url)
2909 m_baseURLOverride = url;
2913 void Document::processBaseElement()
2915 // Find the first href attribute in a base element and the first target attribute in a base element.
2916 const AtomicString* href = nullptr;
2917 const AtomicString* target = nullptr;
2918 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2919 for (auto& base : baseDescendants) {
2921 const AtomicString& value = base.attributeWithoutSynchronization(hrefAttr);
2922 if (!value.isNull()) {
2929 const AtomicString& value = base.attributeWithoutSynchronization(targetAttr);
2930 if (!value.isNull()) {
2938 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2941 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2942 if (!strippedHref.isEmpty())
2943 baseElementURL = URL(url(), strippedHref);
2945 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2946 m_baseElementURL = baseElementURL;
2950 m_baseTarget = target ? *target : nullAtom;
2953 String Document::userAgent(const URL& url) const
2955 return frame() ? frame()->loader().userAgent(url) : String();
2958 void Document::disableEval(const String& errorMessage)
2963 frame()->script().disableEval(errorMessage);
2966 #if ENABLE(INDEXED_DATABASE)
2968 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
2970 if (!m_idbConnectionProxy) {
2971 Page* currentPage = page();
2974 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
2976 return m_idbConnectionProxy.get();
2981 #if ENABLE(WEB_SOCKETS)
2983 SocketProvider* Document::socketProvider()
2985 return m_socketProvider.get();
2990 bool Document::canNavigate(Frame* targetFrame)
2995 // FIXME: We shouldn't call this function without a target frame, but
2996 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2997 // returning true when supplied with a 0 targetFrame.
3001 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
3002 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3005 if (isSandboxed(SandboxNavigation)) {
3006 if (targetFrame->tree().isDescendantOf(m_frame))
3009 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
3010 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3011 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
3013 printNavigationErrorMessage(targetFrame, url(), reason);
3017 // This is the normal case. A document can navigate its decendant frames,
3018 // or, more generally, a document can navigate a frame if the document is
3019 // in the same origin as any of that frame's ancestors (in the frame
3022 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3023 // historical information about this security check.
3024 if (canAccessAncestor(securityOrigin(), targetFrame))
3027 // Top-level frames are easier to navigate than other frames because they
3028 // display their URLs in the address bar (in most browsers). However, there
3029 // are still some restrictions on navigation to avoid nuisance attacks.
3030 // Specifically, a document can navigate a top-level frame if that frame
3031 // opened the document or if the document is the same-origin with any of
3032 // the top-level frame's opener's ancestors (in the frame hierarchy).
3034 // In both of these cases, the document performing the navigation is in
3035 // some way related to the frame being navigate (e.g., by the "opener"
3036 // and/or "parent" relation). Requiring some sort of relation prevents a
3037 // document from navigating arbitrary, unrelated top-level frames.
3038 if (!targetFrame->tree().parent()) {
3039 if (targetFrame == m_frame->loader().opener())
3042 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3046 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3050 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3052 Frame* currentFrame = m_frame;
3056 Frame* ancestorFrame = currentFrame->tree().parent();
3058 while (ancestorFrame) {
3059 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3060 return currentFrame;
3061 currentFrame = ancestorFrame;
3062 ancestorFrame = ancestorFrame->tree().parent();
3067 void Document::didRemoveAllPendingStylesheet()
3069 m_needsNotifyRemoveAllPendingStylesheet = false;
3071 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3072 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3074 renderView()->repaintViewAndCompositedLayers();
3077 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3078 parser->executeScriptsWaitingForStylesheets();
3080 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3081 view()->scrollToFragment(m_url);
3084 bool Document::usesStyleBasedEditability() const
3086 if (m_hasElementUsingStyleBasedEditability)
3089 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3090 ASSERT(!m_inStyleRecalc);
3092 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3093 styleScope.flushPendingUpdate();
3094 return styleScope.usesStyleBasedEditability();
3097 void Document::setHasElementUsingStyleBasedEditability()
3099 m_hasElementUsingStyleBasedEditability = true;
3102 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3104 ASSERT(!equiv.isNull());
3105 ASSERT(!content.isNull());
3107 HttpEquivPolicy policy = httpEquivPolicy();
3108 if (policy != HttpEquivPolicy::Enabled) {
3111 case HttpEquivPolicy::Enabled:
3112 ASSERT_NOT_REACHED();
3114 case HttpEquivPolicy::DisabledBySettings:
3115 reason = "by the embedder.";
3117 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3118 reason = "for documents with Content-Disposition: attachment.";
3121 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3122 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3126 Frame* frame = this->frame();
3128 HTTPHeaderName headerName;
3129 if (!findHTTPHeaderName(equiv, headerName))
3132 switch (headerName) {
3133 case HTTPHeaderName::DefaultStyle:
3134 // The preferred style set has been overridden as per section
3135 // 14.3.2 of the HTML4.0 specification. We need to update the
3136 // sheet used variable and then update our style selector.
3137 // For more info, see the test at:
3138 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3140 styleScope().setSelectedStylesheetSetName(content);
3141 styleScope().setPreferredStylesheetSetName(content);
3144 case HTTPHeaderName::Refresh: {
3147 if (frame && parseMetaHTTPEquivRefresh(content, delay, urlString)) {
3149 if (urlString.isEmpty())
3150 completedURL = m_url;
3152 completedURL = completeURL(urlString);
3153 if (!protocolIsJavaScript(completedURL))
3154 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3156 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3157 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3164 case HTTPHeaderName::SetCookie:
3165 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3166 if (is<HTMLDocument>(*this)) {
3167 // Exception (for sandboxed documents) ignored.
3168 downcast<HTMLDocument>(*this).setCookie(content);
3172 case HTTPHeaderName::ContentLanguage:
3173 setContentLanguage(content);
3176 case HTTPHeaderName::XDNSPrefetchControl:
3177 parseDNSPrefetchControlHeader(content);
3180 case HTTPHeaderName::XFrameOptions:
3182 FrameLoader& frameLoader = frame->loader();
3183 unsigned long requestIdentifier = 0;
3184 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3185 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3187 String message = "The X-Frame-Option '" + content + "' supplied in a <meta> element was ignored. X-Frame-Options may only be provided by an HTTP header sent with the document.";
3188 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3192 case HTTPHeaderName::ContentSecurityPolicy:
3193 if (isInDocumentHead)
3194 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::Enforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3197 case HTTPHeaderName::XWebKitCSP:
3198 if (isInDocumentHead)
3199 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::PrefixedEnforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3207 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3209 ASSERT(!features.isNull());
3211 if (origin < m_viewportArguments.type)
3214 m_viewportArguments = ViewportArguments(origin);
3216 processFeaturesString(features, [this](StringView key, StringView value) {
3217 setViewportFeature(m_viewportArguments, *this, key, value);
3220 updateViewportArguments();
3223 void Document::updateViewportArguments()
3225 if (page() && frame()->isMainFrame()) {
3227 m_didDispatchViewportPropertiesChanged = true;
3229 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3231 page()->chrome().didReceiveDocType(frame());
3238 void Document::processFormatDetection(const String& features)
3240 // FIXME: Find a better place for this function.
3241 processFeaturesString(features, [this](StringView key, StringView value) {
3242 if (equalLettersIgnoringASCIICase(key, "telephone") && equalLettersIgnoringASCIICase(value, "no"))
3243 setIsTelephoneNumberParsingAllowed(false);
3247 void Document::processWebAppOrientations()
3249 if (Page* page = this->page())
3250 page->chrome().client().webAppOrientationsUpdated();
3255 void Document::processReferrerPolicy(const String& policy)
3257 ASSERT(!policy.isNull());
3259 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3260 // even if the document has a meta tag saying otherwise.
3261 if (shouldEnforceContentDispositionAttachmentSandbox())
3265 if (shouldEnforceQuickLookSandbox())
3269 // Note that we're supporting both the standard and legacy keywords for referrer
3270 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3271 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3272 setReferrerPolicy(ReferrerPolicy::Never);
3273 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3274 setReferrerPolicy(ReferrerPolicy::Always);
3275 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3276 setReferrerPolicy(ReferrerPolicy::Origin);
3277 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3278 setReferrerPolicy(ReferrerPolicy::Default);
3280 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'.");
3281 setReferrerPolicy(ReferrerPolicy::Never);
3285 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3287 if (!hasLivingRenderTree())
3288 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3290 HitTestResult result(documentPoint);
3291 renderView()->hitTest(request, result);
3293 if (!request.readOnly())
3294 updateHoverActiveState(request, result.targetElement());
3296 return MouseEventWithHitTestResults(event, result);
3299 // DOM Section 1.1.1
3300 bool Document::childTypeAllowed(NodeType type) const
3303 case ATTRIBUTE_NODE:
3304 case CDATA_SECTION_NODE:
3305 case DOCUMENT_FRAGMENT_NODE:
3310 case PROCESSING_INSTRUCTION_NODE:
3312 case DOCUMENT_TYPE_NODE:
3314 // Documents may contain no more than one of each of these.
3315 // (One Element and one DocumentType.)
3316 for (Node* c = firstChild(); c; c = c->nextSibling())
3317 if (c->nodeType() == type)
3324 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3326 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3329 switch (newChild.nodeType()) {
3330 case ATTRIBUTE_NODE:
3331 case CDATA_SECTION_NODE:
3336 case PROCESSING_INSTRUCTION_NODE:
3338 case DOCUMENT_FRAGMENT_NODE: {
3339 bool hasSeenElementChild = false;
3340 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3341 if (is<Element>(*node)) {
3342 if (hasSeenElementChild)
3344 hasSeenElementChild = true;
3346 if (!canAcceptChild(*node, refChild, operation))
3351 case DOCUMENT_TYPE_NODE: {
3352 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3353 if (operation == AcceptChildOperation::Replace) {
3354 // parent has a doctype child that is not child, or an element is preceding child.
3355 if (existingDocType && existingDocType != refChild)
3357 if (refChild->previousElementSibling())
3360 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3361 if (existingDocType)
3363 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3368 case ELEMENT_NODE: {
3369 auto* existingElementChild = firstElementChild();
3370 if (operation == AcceptChildOperation::Replace) {
3371 if (existingElementChild && existingElementChild != refChild)
3373 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3374 if (is<DocumentType>(*child))
3378 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3379 if (existingElementChild)
3381 for (auto* child = refChild; child; child = child->nextSibling()) {
3382 if (is<DocumentType>(*child))
3392 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3394 Ref<Document> clone = cloneDocumentWithoutChildren();
3395 clone->cloneDataFromDocument(*this);
3397 case CloningOperation::OnlySelf:
3398 case CloningOperation::SelfWithTemplateContent:
3400 case CloningOperation::Everything:
3401 cloneChildNodes(clone);
3404 return WTFMove(clone);
3407 Ref<Document> Document::cloneDocumentWithoutChildren() const
3409 if (isXMLDocument()) {
3410 if (isXHTMLDocument())
3411 return XMLDocument::createXHTML(nullptr, url());
3412 return XMLDocument::create(nullptr, url());
3414 return create(nullptr, url());
3417 void Document::cloneDataFromDocument(const Document& other)
3419 ASSERT(m_url == other.url());
3420 m_baseURL = other.baseURL();
3421 m_baseURLOverride = other.baseURLOverride();
3422 m_documentURI = other.documentURI();
3424 setCompatibilityMode(other.m_compatibilityMode);
3425 setContextDocument(other.contextDocument());
3426 setSecurityOriginPolicy(other.securityOriginPolicy());
3427 overrideMIMEType(other.contentType());
3428 setDecoder(other.decoder());
3431 StyleSheetList& Document::styleSheets()
3433 if (!m_styleSheetList)
3434 m_styleSheetList = StyleSheetList::create(this);
3435 return *m_styleSheetList;
3438 String Document::preferredStylesheetSet() const
3440 return styleScope().preferredStylesheetSetName();
3443 String Document::selectedStylesheetSet() const
3445 return styleScope().selectedStylesheetSetName();
3448 void Document::setSelectedStylesheetSet(const String& aString)
3450 styleScope().setSelectedStylesheetSetName(aString);
3453 void Document::evaluateMediaQueryList()
3455 if (m_mediaQueryMatcher)
3456 m_mediaQueryMatcher->styleResolverChanged();
3458 checkViewportDependentPictures();
3461 void Document::checkViewportDependentPictures()
3463 Vector<HTMLPictureElement*, 16> changedPictures;
3464 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3465 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3466 if ((*it)->viewportChangeAffectedPicture())
3467 changedPictures.append(*it);
3469 for (auto* picture : changedPictures)
3470 picture->sourcesChanged();
3473 void Document::updateViewportUnitsOnResize()
3475 if (!hasStyleWithViewportUnits())
3478 styleScope().resolver().clearCachedPropertiesAffectedByViewportUnits();
3480 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3481 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3482 auto* renderer = element->renderer();
3483 if (renderer && renderer->style().hasViewportUnits())
3484 element->invalidateStyle();
3488 void Document::addAudioProducer(MediaProducer* audioProducer)
3490 m_audioProducers.add(audioProducer);
3491 updateIsPlayingMedia();
3494 void Document::removeAudioProducer(MediaProducer* audioProducer)
3496 m_audioProducers.remove(audioProducer);
3497 updateIsPlayingMedia();
3500 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3502 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3503 for (auto* audioProducer : m_audioProducers)
3504 state |= audioProducer->mediaState();
3506 #if ENABLE(MEDIA_SESSION)
3507 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3508 if (sourceElement->isPlaying())
3509 state |= MediaProducer::IsSourceElementPlaying;
3511 if (auto* session = sourceElement->session()) {
3512 if (auto* controls = session->controls()) {
3513 if (controls->previousTrackEnabled())
3514 state |= MediaProducer::IsPreviousTrackControlEnabled;
3515 if (controls->nextTrackEnabled())
3516 state |= MediaProducer::IsNextTrackControlEnabled;
3522 if (state == m_mediaState)
3525 m_mediaState = state;
3528 page()->updateIsPlayingMedia(sourceElementID);
3531 void Document::pageMutedStateDidChange()
3533 for (auto* audioProducer : m_audioProducers)
3534 audioProducer->pageMutedStateDidChange();
3537 static bool isNodeInSubtree(Node& node, Node& container, bool amongChildrenOnly)
3539 if (amongChildrenOnly)
3540 return node.isDescendantOf(container);
3542 return &node == &container || node.isDescendantOf(container);
3545 void Document::removeFocusedNodeOfSubtree(Node& node, bool amongChildrenOnly)
3547 if (!m_focusedElement || pageCacheState() != NotInPageCache) // If the document is in the page cache, then we don't need to clear out the focused node.
3550 Element* focusedElement = node.treeScope().focusedElement();
3551 if (!focusedElement)
3554 if (isNodeInSubtree(*focusedElement, node, amongChildrenOnly)) {
3555 setFocusedElement(nullptr, FocusDirectionNone, FocusRemovalEventsMode::DoNotDispatch);
3556 // Set the focus navigation starting node to the previous focused element so that
3557 // we can fallback to the siblings or parent node for the next search.
3558 // Also we need to call removeFocusNavigationNodeOfSubtree after this function because
3559 // setFocusedElement(nullptr) will reset m_focusNavigationStartingNode.
3560 setFocusNavigationStartingNode(focusedElement);
3564 void Document::hoveredElementDidDetach(Element* element)
3566 if (!m_hoveredElement || element != m_hoveredElement)
3569 m_hoveredElement = element->parentElement();
3570 while (m_hoveredElement && !m_hoveredElement->renderer())
3571 m_hoveredElement = m_hoveredElement->parentElement();
3573 frame()->eventHandler().scheduleHoverStateUpdate();
3576 void Document::elementInActiveChainDidDetach(Element* element)
3578 if (!m_activeElement || element != m_activeElement)
3581 m_activeElement = element->parentElement();
3582 while (m_activeElement && !m_activeElement->renderer())
3583 m_activeElement = m_activeElement->parentElement();
3586 #if ENABLE(DASHBOARD_SUPPORT)
3588 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3590 return m_annotatedRegions;
3593 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3595 m_annotatedRegions = regions;
3596 setAnnotatedRegionsDirty(false);
3601 bool Document::setFocusedElement(Element* element, FocusDirection direction, FocusRemovalEventsMode eventsMode)
3603 RefPtr<Element> newFocusedElement = element;
3604 // Make sure newFocusedElement is actually in this document
3605 if (newFocusedElement && (&newFocusedElement->document() != this))
3608 if (m_focusedElement == newFocusedElement)
3611 if (pageCacheState() != NotInPageCache)
3614 bool focusChangeBlocked = false;
3615 RefPtr<Element> oldFocusedElement = WTFMove(m_focusedElement);
3617 // Remove focus from the existing focus node (if any)
3618 if (oldFocusedElement) {
3619 oldFocusedElement->setFocus(false);
3620 setFocusNavigationStartingNode(nullptr);
3622 if (eventsMode == FocusRemovalEventsMode::Dispatch) {
3623 // Dispatch a change event for form control elements that have been edited.
3624 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3625 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3626 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3627 formControlElement.dispatchFormControlChangeEvent();
3630 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3631 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3633 if (m_focusedElement) {
3634 // handler shifted focus
3635 focusChangeBlocked = true;
3636 newFocusedElement = nullptr;
3639 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3640 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3641 // on it, probably when <rdar://problem/8503958> is resolved.
3642 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3644 if (m_focusedElement) {
3645 // handler shifted focus
3646 focusChangeBlocked = true;
3647 newFocusedElement = nullptr;