2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004-2015 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
32 #include "AnimationController.h"
34 #include "AuthorStyleSheets.h"
35 #include "CDATASection.h"
36 #include "CSSFontSelector.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedResourceLoader.h"
42 #include "ChromeClient.h"
44 #include "CompositionEvent.h"
45 #include "ContentSecurityPolicy.h"
46 #include "CookieJar.h"
47 #include "CustomEvent.h"
48 #include "DOMImplementation.h"
49 #include "DOMNamedFlowCollection.h"
50 #include "DOMWindow.h"
51 #include "DateComponents.h"
52 #include "DebugPageOverlays.h"
53 #include "Dictionary.h"
54 #include "DocumentLoader.h"
55 #include "DocumentMarkerController.h"
56 #include "DocumentSharedObjectPool.h"
57 #include "DocumentType.h"
59 #include "ElementIterator.h"
60 #include "EntityReference.h"
61 #include "EventHandler.h"
62 #include "ExtensionStyleSheets.h"
63 #include "FocusController.h"
64 #include "FontLoader.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 "HTMLIFrameElement.h"
82 #include "HTMLImageElement.h"
83 #include "HTMLLinkElement.h"
84 #include "HTMLMediaElement.h"
85 #include "HTMLNameCollection.h"
86 #include "HTMLParserIdioms.h"
87 #include "HTMLPictureElement.h"
88 #include "HTMLPlugInElement.h"
89 #include "HTMLScriptElement.h"
90 #include "HTMLStyleElement.h"
91 #include "HTMLTitleElement.h"
92 #include "HTTPHeaderNames.h"
93 #include "HTTPParsers.h"
94 #include "HashChangeEvent.h"
96 #include "HitTestResult.h"
97 #include "IconController.h"
98 #include "ImageLoader.h"
99 #include "InspectorInstrumentation.h"
100 #include "JSLazyEventListener.h"
101 #include "JSModuleLoader.h"
102 #include "KeyboardEvent.h"
103 #include "Language.h"
104 #include "LoaderStrategy.h"
106 #include "MainFrame.h"
107 #include "MediaCanStartListener.h"
108 #include "MediaProducer.h"
109 #include "MediaQueryList.h"
110 #include "MediaQueryMatcher.h"
111 #include "MessageEvent.h"
112 #include "MouseEventWithHitTestResults.h"
113 #include "MutationEvent.h"
114 #include "NameNodeList.h"
115 #include "NestingLevelIncrementer.h"
116 #include "NodeIterator.h"
117 #include "NodeRareData.h"
118 #include "NodeWithIndex.h"
119 #include "OverflowEvent.h"
120 #include "PageConsoleClient.h"
121 #include "PageGroup.h"
122 #include "PageTransitionEvent.h"
123 #include "PlatformLocale.h"
124 #include "PlatformMediaSessionManager.h"
125 #include "PlatformStrategies.h"
126 #include "PlugInsResources.h"
127 #include "PluginDocument.h"
128 #include "PointerLockController.h"
129 #include "PopStateEvent.h"
130 #include "ProcessingInstruction.h"
131 #include "RenderChildIterator.h"
132 #include "RenderLayerCompositor.h"
133 #include "RenderView.h"
134 #include "RenderWidget.h"
135 #include "RuntimeEnabledFeatures.h"
136 #include "SVGDocumentExtensions.h"
137 #include "SVGElement.h"
138 #include "SVGElementFactory.h"
139 #include "SVGNames.h"
140 #include "SVGTitleElement.h"
141 #include "SVGZoomEvent.h"
142 #include "SchemeRegistry.h"
143 #include "ScopedEventQueue.h"
144 #include "ScriptController.h"
145 #include "ScriptRunner.h"
146 #include "ScriptSourceCode.h"
147 #include "ScrollingCoordinator.h"
148 #include "SecurityOrigin.h"
149 #include "SecurityOriginPolicy.h"
150 #include "SecurityPolicy.h"
151 #include "SegmentedString.h"
152 #include "SelectorQuery.h"
153 #include "Settings.h"
154 #include "ShadowRoot.h"
155 #include "StorageEvent.h"
156 #include "StyleProperties.h"
157 #include "StyleResolver.h"
158 #include "StyleSheetContents.h"
159 #include "StyleSheetList.h"
160 #include "SubresourceLoader.h"
161 #include "TextEvent.h"
162 #include "TextNodeTraversal.h"
163 #include "TransformSource.h"
164 #include "TreeWalker.h"
165 #include "VisitedLinkState.h"
166 #include "WheelEvent.h"
167 #include "XMLDocumentParser.h"
168 #include "XMLNSNames.h"
169 #include "XMLNames.h"
170 #include "XPathEvaluator.h"
171 #include "XPathExpression.h"
172 #include "XPathNSResolver.h"
173 #include "XPathResult.h"
174 #include "htmlediting.h"
175 #include <JavaScriptCore/Profile.h>
177 #include <inspector/ScriptCallStack.h>
178 #include <wtf/CurrentTime.h>
179 #include <wtf/TemporaryChange.h>
180 #include <wtf/text/StringBuffer.h>
181 #include <yarr/RegularExpression.h>
184 #include "DOMSecurityPolicy.h"
187 #if ENABLE(DEVICE_ORIENTATION)
188 #include "DeviceMotionEvent.h"
189 #include "DeviceOrientationEvent.h"
192 #if ENABLE(FULLSCREEN_API)
193 #include "RenderFullScreen.h"
197 #include "CSSFontSelector.h"
198 #include "DeviceMotionClientIOS.h"
199 #include "DeviceMotionController.h"
200 #include "DeviceOrientationClientIOS.h"
201 #include "DeviceOrientationController.h"
202 #include "Geolocation.h"
203 #include "Navigator.h"
204 #include "NavigatorGeolocation.h"
205 #include "WKContentObservation.h"
206 #include "WebCoreSystemInterface.h"
209 #if ENABLE(IOS_GESTURE_EVENTS)
210 #include "GestureEvent.h"
213 #if ENABLE(IOS_TEXT_AUTOSIZING)
214 #include "TextAutoSizing.h"
218 #include "MathMLElement.h"
219 #include "MathMLElementFactory.h"
220 #include "MathMLNames.h"
223 #if ENABLE(MEDIA_SESSION)
224 #include "MediaSession.h"
227 #if ENABLE(REQUEST_ANIMATION_FRAME)
228 #include "RequestAnimationFrameCallback.h"
229 #include "ScriptedAnimationController.h"
232 #if ENABLE(TEXT_AUTOSIZING)
233 #include "TextAutosizer.h"
236 #if ENABLE(TOUCH_EVENTS)
237 #include "TouchEvent.h"
238 #include "TouchList.h"
241 #if ENABLE(VIDEO_TRACK)
242 #include "CaptionUserPreferences.h"
245 #if ENABLE(WEB_REPLAY)
246 #include "WebReplayInputs.h"
247 #include <replay/EmptyInputCursor.h>
248 #include <replay/InputCursor.h>
251 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
252 #include "MediaPlaybackTargetClient.h"
256 #include "XSLTProcessor.h"
260 using namespace Unicode;
264 using namespace HTMLNames;
266 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
268 static const unsigned cMaxWriteRecursionDepth = 21;
270 // DOM Level 2 says (letters added):
272 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
273 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
274 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
275 // 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.
276 // 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.
277 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
278 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
279 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
280 // i) Characters ':' and '_' are allowed as name-start characters.
281 // j) Characters '-' and '.' are allowed as name characters.
283 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
285 static inline bool isValidNameStart(UChar32 c)
288 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
292 if (c == ':' || c == '_')
295 // rules (a) and (f) above
296 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)))
300 if (c >= 0xF900 && c < 0xFFFE)
304 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
305 if (type == U_DT_FONT || type == U_DT_COMPAT)
311 static inline bool isValidNamePart(UChar32 c)
313 // rules (a), (e), and (i) above
314 if (isValidNameStart(c))
317 // rules (g) and (h) above
318 if (c == 0x00B7 || c == 0x0387)
322 if (c == '-' || c == '.')
325 // rules (b) and (f) above
326 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
330 if (c >= 0xF900 && c < 0xFFFE)
334 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
335 if (type == U_DT_FONT || type == U_DT_COMPAT)
341 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
343 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
345 // If a Document has the address "about:blank"
346 // The origin of the Document is the origin it was assigned when its browsing context was created.
348 // Note: We generalize this to all "blank" URLs and invalid URLs because we
349 // treat all of these URLs as about:blank.
351 return url.isEmpty() || url.isBlankURL();
354 static Widget* widgetForElement(Element* focusedElement)
358 auto* renderer = focusedElement->renderer();
359 if (!is<RenderWidget>(renderer))
361 return downcast<RenderWidget>(*renderer).widget();
364 static bool acceptsEditingFocus(Node* node)
367 ASSERT(node->hasEditableStyle());
369 Node* root = node->rootEditableElement();
370 Frame* frame = node->document().frame();
374 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
377 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
379 // targetFrame can be 0 when we're trying to navigate a top-level frame
380 // that has a 0 opener.
384 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
385 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
386 Document* ancestorDocument = ancestorFrame->document();
387 // FIXME: Should be an ASSERT? Frames should alway have documents.
388 if (!ancestorDocument)
391 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
392 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
395 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
396 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
397 // something more general instead?
398 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
405 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
407 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
409 // FIXME: should we print to the console of the document performing the navigation instead?
410 frame->document()->domWindow()->printErrorMessage(message);
413 uint64_t Document::s_globalTreeVersion = 0;
415 #if ENABLE(IOS_TEXT_AUTOSIZING)
416 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
418 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
421 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
423 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
427 HashSet<Document*>& Document::allDocuments()
429 static NeverDestroyed<HashSet<Document*>> documents;
433 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
434 : ContainerNode(*this, CreateDocument)
436 #if ENABLE(IOS_TOUCH_EVENTS)
437 , m_handlingTouchEvent(false)
438 , m_touchEventRegionsDirty(false)
439 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
441 , m_referencingNodeCount(0)
442 , m_didCalculateStyleResolver(false)
443 , m_hasNodesWithPlaceholderStyle(false)
444 , m_needsNotifyRemoveAllPendingStylesheet(false)
445 , m_ignorePendingStylesheets(false)
446 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
448 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
449 , m_activeParserCount(0)
450 , m_wellFormed(false)
452 , m_paginatedForScreen(false)
453 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
454 , m_compatibilityModeLocked(false)
455 , m_textColor(Color::black)
456 , m_domTreeVersion(++s_globalTreeVersion)
458 , m_mutationObserverTypes(0)
459 , m_authorStyleSheets(std::make_unique<AuthorStyleSheets>(*this))
460 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
461 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
462 , m_visuallyOrdered(false)
463 , m_readyState(Complete)
465 , m_optimizedStyleSheetUpdateTimer(*this, &Document::optimizedStyleSheetUpdateTimerFired)
466 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
467 , m_pendingStyleRecalcShouldForce(false)
468 , m_inStyleRecalc(false)
469 , m_closeAfterStyleRecalc(false)
470 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
471 , m_frameElementsShouldIgnoreScrolling(false)
472 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
473 , m_ignoreDestructiveWriteCount(0)
474 , m_markers(std::make_unique<DocumentMarkerController>(*this))
475 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
476 , m_cssTarget(nullptr)
477 , m_processingLoadEvent(false)
478 , m_loadEventFinished(false)
479 , m_startTime(std::chrono::steady_clock::now())
480 , m_overMinimumLayoutThreshold(false)
481 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
482 , m_moduleLoader(std::make_unique<JSModuleLoader>(*this))
483 , m_xmlVersion(ASCIILiteral("1.0"))
484 , m_xmlStandalone(StandaloneUnspecified)
485 , m_hasXMLDeclaration(false)
486 , m_designMode(inherit)
488 , m_inInvalidateNodeListAndCollectionCaches(false)
490 #if ENABLE(DASHBOARD_SUPPORT)
491 , m_hasAnnotatedRegions(false)
492 , m_annotatedRegionsDirty(false)
494 , m_createRenderers(true)
495 , m_inPageCache(false)
496 , m_accessKeyMapValid(false)
497 , m_documentClasses(documentClasses)
498 , m_isSynthesized(constructionFlags & Synthesized)
499 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
500 , m_sawElementsInKnownNamespaces(false)
501 , m_isSrcdocDocument(false)
502 , m_eventQueue(*this)
503 , m_weakFactory(this)
504 #if ENABLE(FULLSCREEN_API)
505 , m_areKeysEnabledInFullScreen(0)
506 , m_fullScreenRenderer(nullptr)
507 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
508 , m_isAnimatingFullScreen(false)
510 , m_loadEventDelayCount(0)
511 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
512 , m_referrerPolicy(ReferrerPolicyDefault)
513 , m_directionSetOnDocumentElement(false)
514 , m_writingModeSetOnDocumentElement(false)
515 , m_writeRecursionIsTooDeep(false)
516 , m_writeRecursionDepth(0)
517 , m_lastHandledUserGestureTimestamp(0)
519 #if ENABLE(DEVICE_ORIENTATION)
520 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
521 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
522 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
523 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
526 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
527 , m_isTelephoneNumberParsingAllowed(true)
529 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
530 , m_scheduledTasksAreSuspended(false)
531 , m_visualUpdatesAllowed(true)
532 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
533 , m_sharedObjectPoolClearTimer(*this, &Document::sharedObjectPoolClearTimerFired)
535 , m_didDispatchViewportPropertiesChanged(false)
537 #if ENABLE(TEMPLATE_ELEMENT)
538 , m_templateDocumentHost(nullptr)
540 #if ENABLE(WEB_REPLAY)
541 , m_inputCursor(EmptyInputCursor::create())
543 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
544 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
545 , m_disabledFieldsetElementsCount(0)
546 , m_hasInjectedPlugInsScript(false)
547 , m_renderTreeBeingDestroyed(false)
548 , m_hasPreparedForDestruction(false)
549 , m_hasStyleWithViewportUnits(false)
551 allDocuments().add(this);
553 // We depend on the url getting immediately set in subframes, but we
554 // also depend on the url NOT getting immediately set in opened windows.
555 // See fast/dom/early-frame-url.html
556 // and fast/dom/location-new-window-no-crash.html, respectively.
557 // FIXME: Can/should we unify this behavior?
558 if ((frame && frame->ownerElement()) || !url.isEmpty())
561 m_cachedResourceLoader->setDocument(this);
563 #if ENABLE(TEXT_AUTOSIZING)
564 m_textAutosizer = std::make_unique<TextAutosizer>(this);
568 resetVisitedLinkColor();
569 resetActiveLinkColor();
571 initSecurityContext();
574 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
575 nodeListAndCollectionCount = 0;
578 #if ENABLE(FULLSCREEN_API)
579 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
584 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
586 } while ((owner = owner->document().ownerElement()));
591 Ref<Document> Document::create(ScriptExecutionContext& context)
593 Ref<Document> document = adoptRef(*new Document(nullptr, URL()));
594 document->setSecurityOriginPolicy(context.securityOriginPolicy());
599 Document::~Document()
601 allDocuments().remove(this);
603 ASSERT(!renderView());
604 ASSERT(!m_inPageCache);
605 ASSERT(m_ranges.isEmpty());
606 ASSERT(!m_parentTreeScope);
607 ASSERT(!m_disabledFieldsetElementsCount);
609 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
610 m_deviceMotionClient->deviceMotionControllerDestroyed();
611 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
614 #if ENABLE(TEMPLATE_ELEMENT)
615 if (m_templateDocument)
616 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
619 // FIXME: Should we reset m_domWindow when we detach from the Frame?
621 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
623 m_scriptRunner = nullptr;
624 m_moduleLoader = nullptr;
626 removeAllEventListeners();
628 // Currently we believe that Document can never outlive the parser.
629 // Although the Document may be replaced synchronously, DocumentParsers
630 // generally keep at least one reference to an Element which would in turn
631 // has a reference to the Document. If you hit this ASSERT, then that
632 // assumption is wrong. DocumentParser::detach() should ensure that even
633 // if the DocumentParser outlives the Document it won't cause badness.
634 ASSERT(!m_parser || m_parser->refCount() == 1);
637 if (this == &topDocument())
638 clearAXObjectCache();
642 if (m_styleSheetList)
643 m_styleSheetList->detachFromDocument();
646 m_elementSheet->detachFromDocument();
647 extensionStyleSheets().detachFromDocument();
649 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
651 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
652 // load the initial empty document and the SVGDocument with the same DocumentLoader).
653 if (m_cachedResourceLoader->document() == this)
654 m_cachedResourceLoader->setDocument(nullptr);
657 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
658 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
661 // We must call clearRareData() here since a Document class inherits TreeScope
662 // as well as Node. See a comment on TreeScope.h for the reason.
666 ASSERT(!m_listsInvalidatedAtDocument.size());
667 ASSERT(!m_collectionsInvalidatedAtDocument.size());
669 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
670 ASSERT(!m_nodeListAndCollectionCounts[i]);
673 void Document::removedLastRef()
675 ASSERT(!m_deletionHasBegun);
676 if (m_referencingNodeCount) {
677 // If removing a child removes the last node reference, we don't want the scope to be destroyed
678 // until after removeDetachedChildren returns, so we protect ourselves.
679 incrementReferencingNodeCount();
681 // We must make sure not to be retaining any of our children through
682 // these extra pointers or we will create a reference cycle.
683 m_focusedElement = nullptr;
684 m_hoveredElement = nullptr;
685 m_activeElement = nullptr;
686 m_titleElement = nullptr;
687 m_documentElement = nullptr;
688 m_userActionElements.documentDidRemoveLastRef();
689 #if ENABLE(FULLSCREEN_API)
690 m_fullScreenElement = nullptr;
691 m_fullScreenElementStack.clear();
696 // removeDetachedChildren() doesn't always unregister IDs,
697 // so tear down scope information up front to avoid having
698 // stale references in the map.
700 destroyTreeScopeData();
701 removeDetachedChildren();
702 m_formController = nullptr;
706 m_cssCanvasElements.clear();
711 // We need to do this right now since selfOnlyDeref() can delete this.
712 m_inRemovedLastRefFunction = false;
714 decrementReferencingNodeCount();
717 m_inRemovedLastRefFunction = false;
718 m_deletionHasBegun = true;
724 void Document::commonTeardown()
727 accessSVGExtensions().pauseAnimations();
729 #if ENABLE(REQUEST_ANIMATION_FRAME)
730 clearScriptedAnimationController();
734 Element* Document::getElementByAccessKey(const String& key)
738 if (!m_accessKeyMapValid) {
739 buildAccessKeyMap(this);
740 m_accessKeyMapValid = true;
742 return m_elementsByAccessKey.get(key.impl());
745 void Document::buildAccessKeyMap(TreeScope* scope)
748 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
749 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
750 if (!accessKey.isEmpty())
751 m_elementsByAccessKey.set(accessKey.impl(), &element);
753 if (ShadowRoot* root = element.shadowRoot())
754 buildAccessKeyMap(root);
758 void Document::invalidateAccessKeyMap()
760 m_accessKeyMapValid = false;
761 m_elementsByAccessKey.clear();
764 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
766 return m_imagesByUsemap.add(name, element, *this);
769 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
771 return m_imagesByUsemap.remove(name, element);
774 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
776 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
779 SelectorQuery* Document::selectorQueryForString(const String& selectorString, ExceptionCode& ec)
781 if (selectorString.isEmpty()) {
786 if (!m_selectorQueryCache)
787 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
788 return m_selectorQueryCache->add(selectorString, *this, ec);
791 void Document::clearSelectorQueryCache()
793 m_selectorQueryCache = nullptr;
796 MediaQueryMatcher& Document::mediaQueryMatcher()
798 if (!m_mediaQueryMatcher)
799 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
800 return *m_mediaQueryMatcher;
803 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
805 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
807 bool wasInQuirksMode = inQuirksMode();
808 m_compatibilityMode = mode;
810 clearSelectorQueryCache();
812 if (inQuirksMode() != wasInQuirksMode) {
813 // All user stylesheets have to reparse using the different mode.
814 extensionStyleSheets().clearPageUserSheet();
815 extensionStyleSheets().invalidateInjectedStyleSheetCache();
819 String Document::compatMode() const
821 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
824 void Document::resetLinkColor()
826 m_linkColor = Color(0, 0, 238);
829 void Document::resetVisitedLinkColor()
831 m_visitedLinkColor = Color(85, 26, 139);
834 void Document::resetActiveLinkColor()
836 m_activeLinkColor.setNamedColor("red");
839 DOMImplementation& Document::implementation()
841 if (!m_implementation)
842 m_implementation = std::make_unique<DOMImplementation>(*this);
843 return *m_implementation;
846 bool Document::hasManifest() const
848 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->fastHasAttribute(manifestAttr);
851 DocumentType* Document::doctype() const
853 for (Node* node = firstChild(); node; node = node->nextSibling()) {
854 if (node->isDocumentTypeNode())
855 return static_cast<DocumentType*>(node);
860 void Document::childrenChanged(const ChildChange& change)
862 ContainerNode::childrenChanged(change);
865 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
866 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
867 // otherwise, we need to detect the doc type changes before updating the viewport.
868 if (Page* page = this->page())
869 page->chrome().didReceiveDocType(frame());
872 Element* newDocumentElement = childrenOfType<Element>(*this).first();
873 if (newDocumentElement == m_documentElement)
875 m_documentElement = newDocumentElement;
876 // The root style used for media query matching depends on the document element.
877 clearStyleResolver();
880 RefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
882 if (!isValidName(name)) {
883 ec = INVALID_CHARACTER_ERR;
887 if (isXHTMLDocument())
888 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
890 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
893 Ref<DocumentFragment> Document::createDocumentFragment()
895 return DocumentFragment::create(document());
898 Ref<Text> Document::createTextNode(const String& data)
900 return Text::create(*this, data);
903 Ref<Comment> Document::createComment(const String& data)
905 return Comment::create(*this, data);
908 RefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
910 if (isHTMLDocument()) {
911 ec = NOT_SUPPORTED_ERR;
914 return CDATASection::create(*this, data);
917 RefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
919 if (!isValidName(target)) {
920 ec = INVALID_CHARACTER_ERR;
924 if (data.contains("?>")) {
925 ec = INVALID_CHARACTER_ERR;
929 return ProcessingInstruction::create(*this, target, data);
932 RefPtr<EntityReference> Document::createEntityReference(const String&, ExceptionCode& ec)
934 ec = NOT_SUPPORTED_ERR;
938 Ref<Text> Document::createEditingTextNode(const String& text)
940 return Text::createEditingText(*this, text);
943 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
945 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
946 return *propertySet->ensureCSSStyleDeclaration();
949 RefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
952 ec = NOT_SUPPORTED_ERR;
956 switch (importedNode->nodeType()) {
959 case CDATA_SECTION_NODE:
960 case PROCESSING_INSTRUCTION_NODE:
962 case DOCUMENT_FRAGMENT_NODE:
963 return importedNode->cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
966 // FIXME: This will "Attr::normalize" child nodes of Attr.
967 return Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(*importedNode).name(), nullAtom), downcast<Attr>(*importedNode).value());
969 case DOCUMENT_NODE: // Can't import a document into another document.
970 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
974 ec = NOT_SUPPORTED_ERR;
979 RefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
982 ec = NOT_SUPPORTED_ERR;
986 EventQueueScope scope;
988 switch (source->nodeType()) {
990 ec = NOT_SUPPORTED_ERR;
992 case ATTRIBUTE_NODE: {
993 Attr& attr = downcast<Attr>(*source);
994 if (attr.ownerElement())
995 attr.ownerElement()->removeAttributeNode(&attr, ec);
999 if (source->isShadowRoot()) {
1000 // ShadowRoot cannot disconnect itself from the host node.
1001 ec = HIERARCHY_REQUEST_ERR;
1004 if (is<HTMLFrameOwnerElement>(*source)) {
1005 HTMLFrameOwnerElement& frameOwnerElement = downcast<HTMLFrameOwnerElement>(*source);
1006 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1007 ec = HIERARCHY_REQUEST_ERR;
1011 if (source->parentNode()) {
1012 source->parentNode()->removeChild(*source, ec);
1018 adoptIfNeeded(source.get());
1023 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1025 // These checks are from DOM Core Level 2, createElementNS
1026 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1027 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1029 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1032 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1033 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1034 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1035 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1036 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1037 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1040 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1042 return hasValidNamespaceForElements(qName);
1045 // FIXME: This should really be in a possible ElementFactory class.
1046 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1048 RefPtr<Element> element;
1050 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1051 if (name.namespaceURI() == xhtmlNamespaceURI)
1052 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1053 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1054 element = SVGElementFactory::createElement(name, *this, createdByParser);
1056 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1057 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1061 m_sawElementsInKnownNamespaces = true;
1063 element = Element::create(name, document());
1065 // <image> uses imgTag so we need a special rule.
1066 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1068 return element.releaseNonNull();
1071 bool Document::cssRegionsEnabled() const
1073 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1076 bool Document::cssCompositingEnabled() const
1078 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1081 #if ENABLE(CSS_REGIONS)
1083 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1085 if (!cssRegionsEnabled() || !renderView())
1088 updateStyleIfNeeded();
1090 return namedFlows().createCSSOMSnapshot();
1095 NamedFlowCollection& Document::namedFlows()
1098 m_namedFlows = NamedFlowCollection::create(this);
1100 return *m_namedFlows;
1103 RefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1105 String prefix, localName;
1106 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1109 QualifiedName qName(prefix, localName, namespaceURI);
1110 if (!hasValidNamespaceForElements(qName)) {
1115 return createElement(qName, false);
1118 String Document::readyState() const
1120 DEPRECATED_DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1121 DEPRECATED_DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1122 DEPRECATED_DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1124 switch (m_readyState) {
1133 ASSERT_NOT_REACHED();
1137 void Document::setReadyState(ReadyState readyState)
1139 if (readyState == m_readyState)
1142 #if ENABLE(WEB_TIMING)
1143 switch (readyState) {
1145 if (!m_documentTiming.domLoading)
1146 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1149 if (!m_documentTiming.domInteractive)
1150 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1153 if (!m_documentTiming.domComplete)
1154 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1159 m_readyState = readyState;
1160 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1162 if (settings() && settings()->suppressesIncrementalRendering())
1163 setVisualUpdatesAllowed(readyState);
1166 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1168 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1169 switch (readyState) {
1171 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1172 ASSERT(m_visualUpdatesAllowed);
1173 setVisualUpdatesAllowed(false);
1176 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1179 if (m_visualUpdatesSuppressionTimer.isActive()) {
1180 ASSERT(!m_visualUpdatesAllowed);
1182 if (!view()->visualUpdatesAllowedByClient())
1185 setVisualUpdatesAllowed(true);
1187 ASSERT(m_visualUpdatesAllowed);
1192 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1194 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1197 m_visualUpdatesAllowed = visualUpdatesAllowed;
1199 if (visualUpdatesAllowed)
1200 m_visualUpdatesSuppressionTimer.stop();
1202 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1204 if (!visualUpdatesAllowed)
1207 FrameView* frameView = view();
1208 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1212 if (Page* page = this->page()) {
1213 if (frame()->isMainFrame()) {
1214 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1215 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1216 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1221 view()->updateCompositingLayersAfterLayout();
1223 if (RenderView* renderView = this->renderView())
1224 renderView->repaintViewAndCompositedLayers();
1226 if (Frame* frame = this->frame())
1227 frame->loader().forcePageTransitionIfNeeded();
1230 void Document::visualUpdatesSuppressionTimerFired()
1232 ASSERT(!m_visualUpdatesAllowed);
1234 // If the client is extending the visual update suppression period explicitly, the
1235 // watchdog should not re-enable visual updates itself, but should wait for the client.
1236 if (!view()->visualUpdatesAllowedByClient())
1239 setVisualUpdatesAllowed(true);
1242 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1244 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1245 // both of which we can determine by looking at the timer.
1247 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1248 setVisualUpdatesAllowed(true);
1251 String Document::characterSetWithUTF8Fallback() const
1253 AtomicString name = encoding();
1256 return UTF8Encoding().domName();
1259 String Document::defaultCharset() const
1261 if (Settings* settings = this->settings())
1262 return settings->defaultTextEncodingName();
1266 void Document::setCharset(const String& charset)
1270 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1273 void Document::setContentLanguage(const String& language)
1275 if (m_contentLanguage == language)
1277 m_contentLanguage = language;
1279 // Recalculate style so language is used when selecting the initial font.
1280 styleResolverChanged(DeferRecalcStyle);
1283 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1285 if (!implementation().hasFeature("XML", String())) {
1286 ec = NOT_SUPPORTED_ERR;
1290 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1291 ec = NOT_SUPPORTED_ERR;
1295 m_xmlVersion = version;
1298 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1300 if (!implementation().hasFeature("XML", String())) {
1301 ec = NOT_SUPPORTED_ERR;
1305 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1308 void Document::setDocumentURI(const String& uri)
1310 // This property is read-only from JavaScript, but writable from Objective-C.
1311 m_documentURI = uri;
1315 void Document::setContent(const String& content)
1318 // FIXME: This should probably use insert(), but that's (intentionally)
1319 // not implemented for the XML parser as it's normally synonymous with
1320 // document.write(). append() will end up yielding, but close() will
1321 // pump the tokenizer syncrhonously and finish the parse.
1322 m_parser->append(content.impl());
1326 String Document::suggestedMIMEType() const
1328 if (isXHTMLDocument())
1329 return ASCIILiteral("application/xhtml+xml");
1330 if (isSVGDocument())
1331 return ASCIILiteral("image/svg+xml");
1332 if (xmlStandalone())
1333 return ASCIILiteral("text/xml");
1334 if (isHTMLDocument())
1335 return ASCIILiteral("text/html");
1336 if (DocumentLoader* loader = this->loader())
1337 return loader->responseMIMEType();
1341 void Document::overrideMIMEType(const String& mimeType)
1343 m_overriddenMIMEType = mimeType;
1346 String Document::contentType() const
1348 if (!m_overriddenMIMEType.isNull())
1349 return m_overriddenMIMEType;
1351 if (DocumentLoader* documentLoader = loader())
1352 return documentLoader->currentContentType();
1354 String mimeType = suggestedMIMEType();
1355 if (!mimeType.isNull())
1358 return ASCIILiteral("application/xml");
1361 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1363 if (!frame() || !view())
1366 Frame& frame = *this->frame();
1368 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1370 LayoutPoint contentsPoint = clientPoint;
1371 contentsPoint.scale(scaleFactor, scaleFactor);
1372 contentsPoint.moveBy(view()->contentsScrollPosition());
1374 LayoutRect visibleRect;
1376 visibleRect = view()->unobscuredContentRect();
1378 visibleRect = view()->visibleContentRect();
1380 if (!visibleRect.contains(contentsPoint))
1383 HitTestResult result(contentsPoint);
1384 renderView()->hitTest(HitTestRequest(), result);
1387 *localPoint = result.localPoint();
1389 return result.innerNode();
1392 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1394 if (!hasLivingRenderTree())
1397 Node* node = nodeFromPoint(clientPoint);
1398 while (node && !is<Element>(*node))
1399 node = node->parentNode();
1402 node = ancestorInThisScope(node);
1404 return downcast<Element>(node);
1407 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1409 return caretRangeFromPoint(LayoutPoint(x, y));
1412 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1414 if (!hasLivingRenderTree())
1417 LayoutPoint localPoint;
1418 Node* node = nodeFromPoint(clientPoint, &localPoint);
1422 Node* shadowAncestorNode = ancestorInThisScope(node);
1423 if (shadowAncestorNode != node) {
1424 unsigned offset = shadowAncestorNode->computeNodeIndex();
1425 ContainerNode* container = shadowAncestorNode->parentNode();
1426 return Range::create(*this, container, offset, container, offset);
1429 RenderObject* renderer = node->renderer();
1432 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1433 if (visiblePosition.isNull())
1436 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1437 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1440 Element* Document::scrollingElement()
1442 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1443 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1449 * Performs three operations:
1450 * 1. Convert control characters to spaces
1451 * 2. Trim leading and trailing spaces
1452 * 3. Collapse internal whitespace.
1454 template <typename CharacterType>
1455 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1457 const String& title = titleWithDirection.string();
1458 const CharacterType* characters = title.characters<CharacterType>();
1459 unsigned length = title.length();
1462 StringBuffer<CharacterType> buffer(length);
1463 unsigned builderIndex = 0;
1465 // Skip leading spaces and leading characters that would convert to spaces
1466 for (i = 0; i < length; ++i) {
1467 CharacterType c = characters[i];
1468 if (!(c <= 0x20 || c == 0x7F))
1473 return StringWithDirection();
1475 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1476 bool previousCharWasWS = false;
1477 for (; i < length; ++i) {
1478 CharacterType c = characters[i];
1479 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1480 if (previousCharWasWS)
1482 buffer[builderIndex++] = ' ';
1483 previousCharWasWS = true;
1485 buffer[builderIndex++] = c;
1486 previousCharWasWS = false;
1490 // Strip trailing spaces
1491 while (builderIndex > 0) {
1493 if (buffer[builderIndex] != ' ')
1497 if (!builderIndex && buffer[builderIndex] == ' ')
1498 return StringWithDirection();
1500 buffer.shrink(builderIndex + 1);
1502 // Replace the backslashes with currency symbols if the encoding requires it.
1503 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1505 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1508 void Document::updateTitle(const StringWithDirection& title)
1510 if (m_rawTitle == title)
1515 if (m_rawTitle.string().isEmpty())
1516 m_title = StringWithDirection();
1518 if (m_rawTitle.string().is8Bit())
1519 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1521 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1523 if (DocumentLoader* loader = this->loader())
1524 loader->setTitle(m_title);
1527 void Document::updateTitleFromTitleElement()
1529 if (!m_titleElement) {
1530 updateTitle(StringWithDirection());
1534 if (is<HTMLTitleElement>(*m_titleElement))
1535 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1536 else if (is<SVGTitleElement>(*m_titleElement)) {
1537 // FIXME: does SVG have a title text direction?
1538 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1542 void Document::setTitle(const String& title)
1544 if (!isHTMLDocument() && !isXHTMLDocument())
1545 m_titleElement = nullptr;
1546 else if (!m_titleElement) {
1547 auto* headElement = head();
1550 m_titleElement = createElement(titleTag, false);
1551 headElement->appendChild(*m_titleElement, ASSERT_NO_EXCEPTION);
1554 // The DOM API has no method of specifying direction, so assume LTR.
1555 updateTitle(StringWithDirection(title, LTR));
1557 if (is<HTMLTitleElement>(m_titleElement.get()))
1558 downcast<HTMLTitleElement>(*m_titleElement).setText(title);
1561 void Document::updateTitleElement(Element* newTitleElement)
1563 // Only allow the first title element in tree order to change the title -- others have no effect.
1564 if (m_titleElement) {
1565 if (isHTMLDocument() || isXHTMLDocument())
1566 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1567 else if (isSVGDocument())
1568 m_titleElement = descendantsOfType<SVGTitleElement>(*this).first();
1570 m_titleElement = newTitleElement;
1572 updateTitleFromTitleElement();
1575 void Document::titleElementAdded(Element& titleElement)
1577 if (m_titleElement == &titleElement)
1580 updateTitleElement(&titleElement);
1583 void Document::titleElementRemoved(Element& titleElement)
1585 if (m_titleElement != &titleElement)
1588 updateTitleElement(nullptr);
1591 void Document::titleElementTextChanged(Element& titleElement)
1593 if (m_titleElement != &titleElement)
1596 updateTitleFromTitleElement();
1599 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1601 m_visibilityStateCallbackElements.add(element);
1604 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1606 m_visibilityStateCallbackElements.remove(element);
1609 void Document::visibilityStateChanged()
1611 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1612 for (auto* element : m_visibilityStateCallbackElements)
1613 element->visibilityStateChanged();
1616 PageVisibilityState Document::pageVisibilityState() const
1618 // The visibility of the document is inherited from the visibility of the
1619 // page. If there is no page associated with the document, we will assume
1620 // that the page is hidden, as specified by the spec:
1621 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1622 if (!m_frame || !m_frame->page())
1623 return PageVisibilityStateHidden;
1624 return m_frame->page()->visibilityState();
1627 String Document::visibilityState() const
1629 return pageVisibilityStateString(pageVisibilityState());
1632 bool Document::hidden() const
1634 return pageVisibilityState() != PageVisibilityStateVisible;
1639 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1641 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1644 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1646 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1649 void Document::allowsMediaDocumentInlinePlaybackChanged()
1651 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1652 element->allowsMediaDocumentInlinePlaybackChanged();
1656 #if ENABLE(CSP_NEXT)
1657 DOMSecurityPolicy& Document::securityPolicy()
1659 if (!m_domSecurityPolicy)
1660 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1661 return *m_domSecurityPolicy;
1665 String Document::nodeName() const
1670 Node::NodeType Document::nodeType() const
1672 return DOCUMENT_NODE;
1675 FormController& Document::formController()
1677 if (!m_formController)
1678 m_formController = std::make_unique<FormController>();
1679 return *m_formController;
1682 Vector<String> Document::formElementsState() const
1684 if (!m_formController)
1685 return Vector<String>();
1686 return m_formController->formElementsState();
1689 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1691 if (!stateVector.size() && !m_formController)
1693 formController().setStateForNewFormElements(stateVector);
1696 FrameView* Document::view() const
1698 return m_frame ? m_frame->view() : nullptr;
1701 Page* Document::page() const
1703 return m_frame ? m_frame->page() : nullptr;
1706 Settings* Document::settings() const
1708 return m_frame ? &m_frame->settings() : nullptr;
1711 Ref<Range> Document::createRange()
1713 return Range::create(*this);
1716 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1718 return createNodeIterator(root, whatToShow, WTF::move(filter), ec);
1721 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1727 return NodeIterator::create(root, whatToShow, WTF::move(filter));
1730 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1732 return createNodeIterator(root, whatToShow, nullptr, ec);
1735 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionCode& ec)
1737 return createNodeIterator(root, 0xFFFFFFFF, nullptr, ec);
1740 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1742 return createTreeWalker(root, whatToShow, WTF::move(filter), ec);
1745 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1751 return TreeWalker::create(root, whatToShow, WTF::move(filter));
1754 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1756 return createTreeWalker(root, whatToShow, nullptr, ec);
1759 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionCode& ec)
1761 return createTreeWalker(root, 0xFFFFFFFF, nullptr, ec);
1764 void Document::scheduleForcedStyleRecalc()
1766 m_pendingStyleRecalcShouldForce = true;
1767 scheduleStyleRecalc();
1770 void Document::scheduleStyleRecalc()
1772 if (m_styleRecalcTimer.isActive() || inPageCache())
1775 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1777 // FIXME: Why on earth is this here? This is clearly misplaced.
1778 invalidateAccessKeyMap();
1780 m_styleRecalcTimer.startOneShot(0);
1782 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1785 void Document::unscheduleStyleRecalc()
1787 ASSERT(!childNeedsStyleRecalc());
1789 m_styleRecalcTimer.stop();
1790 m_pendingStyleRecalcShouldForce = false;
1793 bool Document::hasPendingStyleRecalc() const
1795 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1798 bool Document::hasPendingForcedStyleRecalc() const
1800 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1803 void Document::recalcStyle(Style::Change change)
1805 ASSERT(!view() || !view()->isPainting());
1807 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1811 FrameView& frameView = m_renderView->frameView();
1812 Ref<FrameView> protect(frameView);
1813 if (frameView.isPainting())
1816 if (m_inStyleRecalc)
1817 return; // Guard against re-entrancy. -dwh
1819 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1820 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1822 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1823 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1824 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1825 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1826 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1827 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1829 authorStyleSheets().flushPendingUpdates();
1831 frameView.willRecalcStyle();
1833 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1835 // FIXME: We never reset this flags.
1836 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1837 authorStyleSheets().setUsesRemUnit(true);
1838 // We don't call setUsesStyleBasedEditability here because the whole point of the flag is to avoid style recalc.
1839 // i.e. updating the flag here would be too late.
1841 m_inStyleRecalc = true;
1842 bool updatedCompositingLayers = false;
1844 Style::PostResolutionCallbackDisabler disabler(*this);
1845 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1847 if (m_pendingStyleRecalcShouldForce)
1848 change = Style::Force;
1850 if (change == Style::Force) {
1851 // This may get set again during style resolve.
1852 m_hasNodesWithPlaceholderStyle = false;
1855 Style::resolveTree(*this, change);
1857 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1859 clearNeedsStyleRecalc();
1860 clearChildNeedsStyleRecalc();
1861 unscheduleStyleRecalc();
1863 m_inStyleRecalc = false;
1866 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1867 if (m_closeAfterStyleRecalc) {
1868 m_closeAfterStyleRecalc = false;
1872 ++m_styleRecalcCount;
1874 InspectorInstrumentation::didRecalculateStyle(cookie);
1876 // Some animated images may now be inside the viewport due to style recalc,
1877 // resume them if necessary if there is no layout pending. Otherwise, we'll
1878 // check if they need to be resumed after layout.
1879 if (updatedCompositingLayers && !frameView.needsLayout())
1880 frameView.viewportContentsChanged();
1882 if (!frameView.needsLayout())
1883 frameView.frame().selection().updateAppearanceAfterLayout();
1885 // As a result of the style recalculation, the currently hovered element might have been
1886 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1887 // to check if any other elements ended up under the mouse pointer due to re-layout.
1888 if (m_hoveredElement && !m_hoveredElement->renderer())
1889 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1892 void Document::updateStyleIfNeeded()
1894 ASSERT(isMainThread());
1895 ASSERT(!view() || !view()->isPainting());
1897 if (!view() || view()->isInLayout())
1900 if (m_optimizedStyleSheetUpdateTimer.isActive())
1901 styleResolverChanged(RecalcStyleIfNeeded);
1903 if (!needsStyleRecalc())
1906 recalcStyle(Style::NoChange);
1909 void Document::updateLayout()
1911 ASSERT(isMainThread());
1913 FrameView* frameView = view();
1914 if (frameView && frameView->isInLayout()) {
1915 // View layout should not be re-entrant.
1916 ASSERT_NOT_REACHED();
1920 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1922 if (HTMLFrameOwnerElement* owner = ownerElement())
1923 owner->document().updateLayout();
1925 updateStyleIfNeeded();
1927 StackStats::LayoutCheckPoint layoutCheckPoint;
1929 // Only do a layout if changes have occurred that make it necessary.
1930 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1931 frameView->layout();
1934 // FIXME: This is a bad idea and needs to be removed eventually.
1935 // Other browsers load stylesheets before they continue parsing the web page.
1936 // Since we don't, we can run JavaScript code that needs answers before the
1937 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1938 // lets us get reasonable answers. The long term solution to this problem is
1939 // to instead suspend JavaScript execution.
1940 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1942 bool oldIgnore = m_ignorePendingStylesheets;
1944 if (!haveStylesheetsLoaded()) {
1945 m_ignorePendingStylesheets = true;
1946 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1947 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1948 // with accurate style information. (Our suppression involves blanking the whole page at the
1949 // moment. If it were more refined, we might be able to do something better.)
1950 // It's worth noting though that this entire method is a hack, since what we really want to do is
1951 // suspend JS instead of doing a layout with inaccurate information.
1952 HTMLElement* bodyElement = bodyOrFrameset();
1953 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1954 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1955 styleResolverChanged(RecalcStyleImmediately);
1956 } else if (m_hasNodesWithPlaceholderStyle)
1957 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1958 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1959 // but here we need up-to-date style immediately.
1960 recalcStyle(Style::Force);
1965 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1966 view()->flushAnyPendingPostLayoutTasks();
1968 m_ignorePendingStylesheets = oldIgnore;
1971 Ref<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, RenderStyle* parentStyle)
1973 ASSERT(&element.document() == this);
1975 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1976 ResourceLoadSuspender suspender;
1978 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
1979 return element.resolveStyle(parentStyle);
1982 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
1984 ASSERT(isMainThread());
1986 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
1987 if (!haveStylesheetsLoaded()) {
1988 updateLayoutIgnorePendingStylesheets();
1992 // Check for re-entrancy and assert (same code that is in updateLayout()).
1993 FrameView* frameView = view();
1994 if (frameView && frameView->isInLayout()) {
1995 // View layout should not be re-entrant.
1996 ASSERT_NOT_REACHED();
2000 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2002 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2004 bool requireFullLayout = false;
2005 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2006 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2007 requireFullLayout = true;
2010 updateStyleIfNeeded();
2012 RenderObject* renderer = element.renderer();
2013 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2014 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2015 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2016 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2017 requireFullLayout = true;
2020 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2021 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2022 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2023 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2025 if (!requireFullLayout) {
2026 RenderBox* previousBox = nullptr;
2027 RenderBox* currentBox = nullptr;
2029 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2030 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2032 // Require the entire container chain to be boxes.
2033 if (!is<RenderBox>(currRenderer)) {
2034 requireFullLayout = true;
2038 previousBox = currentBox;
2039 currentBox = downcast<RenderBox>(currRenderer);
2041 // If a box needs layout for itself or if a box has changed children and sizes its width to
2042 // its content, then require a full layout.
2043 if (currentBox->selfNeedsLayout() ||
2044 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2045 requireFullLayout = true;
2049 // If a block contains floats and the child's height isn't specified, then
2050 // give up also, since our height could end up being influenced by the floats.
2051 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2052 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2053 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2054 requireFullLayout = true;
2059 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2060 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2061 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2062 // Disallow regions/columns from having the optimization.
2063 // Give up if the writing mode changes at all in the containing block chain.
2064 requireFullLayout = true;
2068 if (currRenderer == frameView->layoutRoot())
2073 StackStats::LayoutCheckPoint layoutCheckPoint;
2075 // Only do a layout if changes have occurred that make it necessary.
2076 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2077 frameView->layout();
2079 return requireFullLayout;
2082 bool Document::isPageBoxVisible(int pageIndex)
2084 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
2085 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2088 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2090 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
2092 int width = pageSize.width();
2093 int height = pageSize.height();
2094 switch (style->pageSizeType()) {
2095 case PAGE_SIZE_AUTO:
2097 case PAGE_SIZE_AUTO_LANDSCAPE:
2099 std::swap(width, height);
2101 case PAGE_SIZE_AUTO_PORTRAIT:
2103 std::swap(width, height);
2105 case PAGE_SIZE_RESOLVED: {
2106 LengthSize size = style->pageSize();
2107 ASSERT(size.width().isFixed());
2108 ASSERT(size.height().isFixed());
2109 width = valueForLength(size.width(), 0);
2110 height = valueForLength(size.height(), 0);
2114 ASSERT_NOT_REACHED();
2116 pageSize = IntSize(width, height);
2118 // The percentage is calculated with respect to the width even for margin top and bottom.
2119 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2120 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2121 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2122 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2123 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2126 void Document::createStyleResolver()
2128 m_styleResolver = std::make_unique<StyleResolver>(*this);
2129 m_styleResolver->appendAuthorStyleSheets(authorStyleSheets().activeStyleSheets());
2132 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2134 if (!m_userAgentShadowTreeStyleResolver) {
2135 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2137 // FIXME: Filter out shadow pseudo elements we don't want to expose to authors.
2138 auto& documentAuthorStyle = *ensureStyleResolver().ruleSets().authorStyle();
2139 if (documentAuthorStyle.hasShadowPseudoElementRules())
2140 m_userAgentShadowTreeStyleResolver->ruleSets().authorStyle()->copyShadowPseudoElementRulesFrom(documentAuthorStyle);
2143 return *m_userAgentShadowTreeStyleResolver;
2146 void Document::fontsNeedUpdate(FontSelector&)
2148 if (m_styleResolver)
2149 m_styleResolver->invalidateMatchedPropertiesCache();
2150 if (inPageCache() || !renderView())
2152 scheduleForcedStyleRecalc();
2155 CSSFontSelector& Document::fontSelector()
2157 if (!m_fontSelector) {
2158 m_fontSelector = CSSFontSelector::create(*this);
2159 m_fontSelector->registerForInvalidationCallbacks(*this);
2161 return *m_fontSelector;
2164 void Document::clearStyleResolver()
2166 m_styleResolver = nullptr;
2167 m_userAgentShadowTreeStyleResolver = nullptr;
2169 // FIXME: It would be better if the FontSelector could survive this operation.
2170 if (m_fontSelector) {
2171 m_fontSelector->clearDocument();
2172 m_fontSelector->unregisterForInvalidationCallbacks(*this);
2173 m_fontSelector = nullptr;
2177 void Document::createRenderTree()
2179 ASSERT(!renderView());
2180 ASSERT(!m_inPageCache);
2181 ASSERT(!m_axObjectCache || this != &topDocument());
2183 if (m_isNonRenderedPlaceholder)
2186 // FIXME: It would be better if we could pass the resolved document style directly here.
2187 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2188 Node::setRenderer(m_renderView.get());
2190 renderView()->setIsInWindow(true);
2192 recalcStyle(Style::Force);
2195 void Document::didBecomeCurrentDocumentInFrame()
2197 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2198 // If so, then m_frame could become 0, and we need to do something about that.
2200 m_frame->script().updateDocument();
2202 if (!hasLivingRenderTree())
2205 updateViewportArguments();
2207 // FIXME: Doing this only for the main frame is insufficient.
2208 // Changing a subframe can also change the wheel event handler count.
2209 // FIXME: Doing this only when a document goes into the frame is insufficient.
2210 // Removing a document can also change the wheel event handler count.
2211 // FIXME: Doing this every time is a waste. If the current document and its
2212 // subframes' documents have no wheel event handlers, then the count did not change,
2213 // unless the documents they are replacing had wheel event handlers.
2214 if (page() && m_frame->isMainFrame())
2215 wheelEventHandlersChanged();
2217 #if ENABLE(TOUCH_EVENTS)
2218 // FIXME: Doing this only for the main frame is insufficient.
2219 // A subframe could have touch event handlers.
2220 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2221 page()->chrome().client().needTouchEvents(true);
2224 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2225 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2226 // page cache, or simply newly created).
2227 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2228 m_frame->animation().suspendAnimationsForDocument(this);
2229 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2231 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2232 m_frame->animation().resumeAnimationsForDocument(this);
2236 void Document::disconnectFromFrame()
2241 void Document::destroyRenderTree()
2243 ASSERT(hasLivingRenderTree());
2244 ASSERT(!m_inPageCache);
2246 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2248 if (this == &topDocument())
2249 clearAXObjectCache();
2251 documentWillBecomeInactive();
2253 if (FrameView* frameView = view())
2254 frameView->detachCustomScrollbars();
2256 #if ENABLE(FULLSCREEN_API)
2257 if (m_fullScreenRenderer)
2258 setFullScreenRenderer(nullptr);
2261 m_hoveredElement = nullptr;
2262 m_focusedElement = nullptr;
2263 m_activeElement = nullptr;
2265 if (m_documentElement)
2266 Style::detachRenderTree(*m_documentElement);
2268 clearChildNeedsStyleRecalc();
2270 unscheduleStyleRecalc();
2272 m_renderView = nullptr;
2273 Node::setRenderer(nullptr);
2275 #if ENABLE(IOS_TEXT_AUTOSIZING)
2276 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2277 m_textAutoSizedNodes.clear();
2281 void Document::prepareForDestruction()
2283 if (m_hasPreparedForDestruction)
2286 #if ENABLE(IOS_TOUCH_EVENTS)
2287 clearTouchEventListeners();
2290 #if HAVE(ACCESSIBILITY)
2291 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2292 if (this != &topDocument()) {
2293 if (AXObjectCache* cache = existingAXObjectCache())
2294 cache->clearTextMarkerNodesInUse(this);
2298 disconnectDescendantFrames();
2299 if (m_domWindow && m_frame)
2300 m_domWindow->willDetachDocumentFromFrame();
2302 if (hasLivingRenderTree())
2303 destroyRenderTree();
2305 if (is<PluginDocument>(*this))
2306 downcast<PluginDocument>(*this).detachFromPluginElement();
2308 #if ENABLE(POINTER_LOCK)
2310 page()->pointerLockController().documentDetached(this);
2313 InspectorInstrumentation::documentDetached(*this);
2315 stopActiveDOMObjects();
2316 m_eventQueue.close();
2317 #if ENABLE(FULLSCREEN_API)
2318 m_fullScreenChangeEventTargetQueue.clear();
2319 m_fullScreenErrorEventTargetQueue.clear();
2324 #if ENABLE(TOUCH_EVENTS)
2325 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2326 parentDocument()->didRemoveEventTargetNode(*this);
2329 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2330 parentDocument()->didRemoveEventTargetNode(*this);
2332 if (m_mediaQueryMatcher)
2333 m_mediaQueryMatcher->documentDestroyed();
2335 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2336 if (!m_clientToIDMap.isEmpty() && page()) {
2337 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2338 copyKeysToVector(m_clientToIDMap, clients);
2339 for (auto* client : clients)
2340 removePlaybackTargetPickerClient(*client);
2344 disconnectFromFrame();
2346 m_hasPreparedForDestruction = true;
2349 void Document::removeAllEventListeners()
2351 EventTarget::removeAllEventListeners();
2354 m_domWindow->removeAllEventListeners();
2355 #if ENABLE(IOS_TOUCH_EVENTS)
2356 clearTouchEventListeners();
2358 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2359 node->removeAllEventListeners();
2362 void Document::suspendDeviceMotionAndOrientationUpdates()
2364 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2366 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2367 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2368 if (m_deviceMotionController)
2369 m_deviceMotionController->suspendUpdates();
2370 if (m_deviceOrientationController)
2371 m_deviceOrientationController->suspendUpdates();
2375 void Document::resumeDeviceMotionAndOrientationUpdates()
2377 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2379 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2380 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2381 if (m_deviceMotionController)
2382 m_deviceMotionController->resumeUpdates();
2383 if (m_deviceOrientationController)
2384 m_deviceOrientationController->resumeUpdates();
2388 void Document::platformSuspendOrStopActiveDOMObjects()
2391 if (WebThreadCountOfObservedContentModifiers() > 0) {
2392 Frame* frame = this->frame();
2393 if (Page* page = frame ? frame->page() : nullptr)
2394 page->chrome().client().clearContentChangeObservers(frame);
2399 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2401 ScriptExecutionContext::suspendActiveDOMObjects(why);
2402 suspendDeviceMotionAndOrientationUpdates();
2403 platformSuspendOrStopActiveDOMObjects();
2406 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2408 ScriptExecutionContext::resumeActiveDOMObjects(why);
2409 resumeDeviceMotionAndOrientationUpdates();
2410 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2413 void Document::stopActiveDOMObjects()
2415 ScriptExecutionContext::stopActiveDOMObjects();
2416 platformSuspendOrStopActiveDOMObjects();
2419 void Document::clearAXObjectCache()
2421 ASSERT(&topDocument() == this);
2422 // Clear the cache member variable before calling delete because attempts
2423 // are made to access it during destruction.
2424 m_axObjectCache = nullptr;
2427 AXObjectCache* Document::existingAXObjectCache() const
2429 Document& topDocument = this->topDocument();
2430 if (!topDocument.hasLivingRenderTree())
2432 return topDocument.m_axObjectCache.get();
2435 AXObjectCache* Document::axObjectCache() const
2437 if (!AXObjectCache::accessibilityEnabled())
2440 // The only document that actually has a AXObjectCache is the top-level
2441 // document. This is because we need to be able to get from any WebCoreAXObject
2442 // to any other WebCoreAXObject on the same page. Using a single cache allows
2443 // lookups across nested webareas (i.e. multiple documents).
2444 Document& topDocument = this->topDocument();
2446 // If the document has already been detached, do not make a new axObjectCache.
2447 if (!topDocument.hasLivingRenderTree())
2450 ASSERT(&topDocument == this || !m_axObjectCache);
2451 if (!topDocument.m_axObjectCache)
2452 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2453 return topDocument.m_axObjectCache.get();
2456 void Document::setVisuallyOrdered()
2458 m_visuallyOrdered = true;
2460 renderView()->style().setRTLOrdering(VisualOrder);
2463 Ref<DocumentParser> Document::createParser()
2465 // FIXME: this should probably pass the frame instead
2466 return XMLDocumentParser::create(*this, view());
2469 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2471 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2474 void Document::open(Document* ownerDocument)
2476 if (ownerDocument) {
2477 setURL(ownerDocument->url());
2478 setCookieURL(ownerDocument->cookieURL());
2479 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2483 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2484 if (parser->isParsing()) {
2485 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2486 if (parser->isExecutingScript())
2489 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2494 if (m_frame->loader().state() == FrameStateProvisional)
2495 m_frame->loader().stopAllLoaders();
2498 removeAllEventListeners();
2500 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2501 parser->setWasCreatedByScript(true);
2504 m_frame->loader().didExplicitOpen();
2507 void Document::detachParser()
2515 void Document::cancelParsing()
2520 // We have to clear the parser to avoid possibly triggering
2521 // the onload handler when closing as a side effect of a cancel-style
2522 // change, such as opening a new document or closing the window while
2528 void Document::implicitOpen()
2534 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2536 m_parser = createParser();
2538 setReadyState(Loading);
2541 HTMLBodyElement* Document::body() const
2543 auto* element = documentElement();
2546 return childrenOfType<HTMLBodyElement>(*element).first();
2549 HTMLElement* Document::bodyOrFrameset() const
2551 // Return the first body or frameset child of the html element.
2552 auto* element = documentElement();
2555 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2556 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2562 void Document::setBodyOrFrameset(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2564 RefPtr<HTMLElement> newBody = prpNewBody;
2566 // FIXME: This does not support setting a <frameset> Element, only a <body>. This does
2567 // not match the HTML specification:
2568 // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
2569 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2570 ec = HIERARCHY_REQUEST_ERR;
2574 if (&newBody->document() != this) {
2576 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2580 newBody = downcast<HTMLElement>(node.get());
2583 if (auto* body = bodyOrFrameset())
2584 documentElement()->replaceChild(newBody.releaseNonNull(), *body, ec);
2586 documentElement()->appendChild(newBody.releaseNonNull(), ec);
2589 Location* Document::location() const
2591 auto* window = domWindow();
2595 return window->location();
2598 HTMLHeadElement* Document::head()
2600 if (auto element = documentElement())
2601 return childrenOfType<HTMLHeadElement>(*element).first();
2605 void Document::close()
2607 // FIXME: We should follow the specification more closely:
2608 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2610 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2616 void Document::explicitClose()
2618 if (RefPtr<DocumentParser> parser = m_parser)
2622 // Because we have no frame, we don't know if all loading has completed,
2623 // so we just call implicitClose() immediately. FIXME: This might fire
2624 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2629 m_frame->loader().checkCompleted();
2632 void Document::implicitClose()
2634 // 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.
2635 if (m_inStyleRecalc) {
2636 m_closeAfterStyleRecalc = true;
2640 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2641 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2646 // Call to dispatchWindowLoadEvent can blow us from underneath.
2647 Ref<Document> protect(*this);
2649 m_processingLoadEvent = true;
2651 ScriptableDocumentParser* parser = scriptableDocumentParser();
2652 m_wellFormed = parser && parser->wellFormed();
2654 // We have to clear the parser, in case someone document.write()s from the
2655 // onLoad event handler, as in Radar 3206524.
2658 // FIXME: We kick off the icon loader when the Document is done parsing.
2659 // There are earlier opportunities we could start it:
2660 // -When the <head> finishes parsing
2661 // -When any new HTMLLinkElement is inserted into the document
2662 // But those add a dynamic component to the favicon that has UI
2663 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2666 f->loader().icon().startLoader();
2667 f->animation().startAnimationsIfNotSuspended(this);
2669 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2670 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2671 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2672 ImageLoader::dispatchPendingBeforeLoadEvents();
2673 ImageLoader::dispatchPendingLoadEvents();
2674 ImageLoader::dispatchPendingErrorEvents();
2675 HTMLLinkElement::dispatchPendingLoadEvents();
2676 HTMLStyleElement::dispatchPendingLoadEvents();
2679 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2680 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2681 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2682 if (svgExtensions())
2683 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2685 dispatchWindowLoadEvent();
2686 enqueuePageshowEvent(PageshowEventNotPersisted);
2687 if (m_pendingStateObject)
2688 enqueuePopstateEvent(m_pendingStateObject.release());
2691 f->loader().dispatchOnloadEvents();
2692 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2693 if (!ownerElement())
2694 printf("onload fired at %lld\n", elapsedTime().count());
2697 // An event handler may have removed the frame
2699 m_processingLoadEvent = false;
2703 // Make sure both the initial layout and reflow happen after the onload
2704 // fires. This will improve onload scores, and other browsers do it.
2705 // If they wanna cheat, we can too. -dwh
2707 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2708 // Just bail out. Before or during the onload we were shifted to another page.
2709 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2710 m_processingLoadEvent = false;
2711 view()->unscheduleRelayout();
2715 frame()->loader().checkCallImplicitClose();
2717 // We used to force a synchronous display and flush here. This really isn't
2718 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2719 // (if your platform is syncing flushes and limiting them to 60fps).
2720 m_overMinimumLayoutThreshold = true;
2721 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2722 updateStyleIfNeeded();
2724 // Always do a layout after loading if needed.
2725 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2729 m_processingLoadEvent = false;
2731 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2732 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2733 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2734 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2735 // exists in the cache (we ignore the return value because we don't need it here). This is
2736 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2738 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2739 // catch new AND page history loads, and that uses AXLoadComplete
2741 axObjectCache()->getOrCreate(renderView());
2742 if (this == &topDocument())
2743 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2745 // AXLoadComplete can only be posted on the top document, so if it's a document
2746 // in an iframe that just finished loading, post AXLayoutComplete instead.
2747 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2752 if (svgExtensions())
2753 accessSVGExtensions().startAnimations();
2756 void Document::setParsing(bool b)
2760 if (m_bParsing && !m_sharedObjectPool)
2761 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2763 if (!m_bParsing && view() && !view()->needsLayout())
2764 view()->fireLayoutRelatedMilestonesIfNeeded();
2766 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2767 if (!ownerElement() && !m_bParsing)
2768 printf("Parsing finished at %lld\n", elapsedTime().count());
2772 bool Document::shouldScheduleLayout()
2774 // This function will only be called when FrameView thinks a layout is needed.
2775 // This enforces a couple extra rules.
2777 // (a) Only schedule a layout once the stylesheets are loaded.
2778 // (b) Only schedule layout once we have a body element.
2780 return (haveStylesheetsLoaded() && bodyOrFrameset())
2781 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2784 bool Document::isLayoutTimerActive()
2786 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2789 std::chrono::milliseconds Document::minimumLayoutDelay()
2791 if (m_overMinimumLayoutThreshold)
2792 return std::chrono::milliseconds(0);
2794 std::chrono::milliseconds elapsed = elapsedTime();
2795 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2797 // We'll want to schedule the timer to fire at the minimum layout threshold.
2798 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2801 std::chrono::milliseconds Document::elapsedTime() const
2803 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2805 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2808 void Document::write(const SegmentedString& text, Document* ownerDocument)
2810 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2812 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2813 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2815 if (m_writeRecursionIsTooDeep)
2818 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2819 if (!ownerElement())
2820 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2823 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2824 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2827 if (!hasInsertionPoint)
2828 open(ownerDocument);
2831 m_parser->insert(text);
2833 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2834 if (!ownerElement())
2835 printf("Ending a document.write at %lld\n", elapsedTime().count());
2839 void Document::write(const String& text, Document* ownerDocument)
2841 write(SegmentedString(text), ownerDocument);
2844 void Document::writeln(const String& text, Document* ownerDocument)
2846 write(text, ownerDocument);
2847 write("\n", ownerDocument);
2850 double Document::minimumTimerInterval() const
2852 Page* page = this->page();
2854 return ScriptExecutionContext::minimumTimerInterval();
2855 return page->settings().minimumDOMTimerInterval();
2858 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2860 if (m_isTimerThrottlingEnabled == shouldThrottle)
2863 m_isTimerThrottlingEnabled = shouldThrottle;
2864 didChangeTimerAlignmentInterval();
2867 double Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2869 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2870 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2871 return DOMTimer::hiddenPageAlignmentInterval();
2873 Page* page = this->page();
2875 return ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2876 return page->settings().domTimerAlignmentInterval();
2879 EventTarget* Document::errorEventTarget()
2881 return m_domWindow.get();
2884 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2886 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTF::move(callStack));
2889 void Document::setURL(const URL& url)
2891 const URL& newURL = url.isEmpty() ? blankURL() : url;
2892 if (newURL == m_url)
2896 m_documentURI = m_url.string();
2900 void Document::updateBaseURL()
2902 URL oldBaseURL = m_baseURL;
2903 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2904 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2905 // from the Document interface otherwise.
2906 if (!m_baseElementURL.isEmpty())
2907 m_baseURL = m_baseElementURL;
2908 else if (!m_baseURLOverride.isEmpty())
2909 m_baseURL = m_baseURLOverride;
2911 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2912 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2913 // and DOM 3 Core does not specify how it should be resolved.
2914 m_baseURL = URL(ParsedURLString, documentURI());
2917 clearSelectorQueryCache();
2919 if (!m_baseURL.isValid())
2922 if (m_elementSheet) {
2923 // Element sheet is silly. It never contains anything.
2924 ASSERT(!m_elementSheet->contents().ruleCount());
2925 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2926 bool usesStyleBasedEditability = m_elementSheet->contents().usesStyleBasedEditability();
2927 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2928 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2930 m_elementSheet->contents().parserSetUsesRemUnits();
2931 if (usesStyleBasedEditability)
2932 m_elementSheet->contents().parserSetUsesStyleBasedEditability();
2935 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2936 // Base URL change changes any relative visited links.
2937 // 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.
2938 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2939 anchor.invalidateCachedVisitedLinkHash();
2943 void Document::setBaseURLOverride(const URL& url)
2945 m_baseURLOverride = url;
2949 void Document::processBaseElement()
2951 // Find the first href attribute in a base element and the first target attribute in a base element.
2952 const AtomicString* href = nullptr;
2953 const AtomicString* target = nullptr;
2954 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2955 for (auto& base : baseDescendants) {
2957 const AtomicString& value = base.fastGetAttribute(hrefAttr);
2958 if (!value.isNull()) {
2965 const AtomicString& value = base.fastGetAttribute(targetAttr);
2966 if (!value.isNull()) {
2974 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2977 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2978 if (!strippedHref.isEmpty())
2979 baseElementURL = URL(url(), strippedHref);
2981 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2982 m_baseElementURL = baseElementURL;
2986 m_baseTarget = target ? *target : nullAtom;
2989 String Document::userAgent(const URL& url) const
2991 return frame() ? frame()->loader().userAgent(url) : String();
2994 void Document::disableEval(const String& errorMessage)
2999 frame()->script().disableEval(errorMessage);
3002 bool Document::canNavigate(Frame* targetFrame)
3007 // FIXME: We shouldn't call this function without a target frame, but
3008 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3009 // returning true when supplied with a 0 targetFrame.
3013 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
3014 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3017 if (isSandboxed(SandboxNavigation)) {
3018 if (targetFrame->tree().isDescendantOf(m_frame))
3021 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
3022 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3023 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
3025 printNavigationErrorMessage(targetFrame, url(), reason);
3029 // This is the normal case. A document can navigate its decendant frames,
3030 // or, more generally, a document can navigate a frame if the document is
3031 // in the same origin as any of that frame's ancestors (in the frame
3034 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3035 // historical information about this security check.
3036 if (canAccessAncestor(securityOrigin(), targetFrame))
3039 // Top-level frames are easier to navigate than other frames because they
3040 // display their URLs in the address bar (in most browsers). However, there
3041 // are still some restrictions on navigation to avoid nuisance attacks.
3042 // Specifically, a document can navigate a top-level frame if that frame
3043 // opened the document or if the document is the same-origin with any of
3044 // the top-level frame's opener's ancestors (in the frame hierarchy).
3046 // In both of these cases, the document performing the navigation is in
3047 // some way related to the frame being navigate (e.g., by the "opener"
3048 // and/or "parent" relation). Requiring some sort of relation prevents a
3049 // document from navigating arbitrary, unrelated top-level frames.
3050 if (!targetFrame->tree().parent()) {
3051 if (targetFrame == m_frame->loader().opener())
3054 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3058 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3062 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3064 Frame* currentFrame = m_frame;
3068 Frame* ancestorFrame = currentFrame->tree().parent();
3070 while (ancestorFrame) {
3071 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3072 return currentFrame;
3073 currentFrame = ancestorFrame;
3074 ancestorFrame = ancestorFrame->tree().parent();
3079 void Document::didRemoveAllPendingStylesheet()
3081 m_needsNotifyRemoveAllPendingStylesheet = false;
3083 styleResolverChanged(DeferRecalcStyleIfNeeded);
3085 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3086 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3088 renderView()->repaintViewAndCompositedLayers();
3091 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3092 parser->executeScriptsWaitingForStylesheets();
3094 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3095 view()->scrollToFragment(m_url);
3098 CSSStyleSheet& Document::elementSheet()
3100 if (!m_elementSheet)
3101 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
3102 return *m_elementSheet;
3105 bool Document::usesStyleBasedEditability() const
3107 if (m_elementSheet && m_elementSheet->contents().usesStyleBasedEditability())
3110 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3111 ASSERT(!m_inStyleRecalc);
3113 auto& authorSheets = const_cast<AuthorStyleSheets&>(authorStyleSheets());
3114 authorSheets.flushPendingUpdates();
3115 return authorSheets.usesStyleBasedEditability();
3118 void Document::processHttpEquiv(const String& equiv, const String& content)
3120 ASSERT(!equiv.isNull() && !content.isNull());
3122 HttpEquivPolicy policy = httpEquivPolicy();
3123 if (policy != HttpEquivPolicy::Enabled) {
3126 case HttpEquivPolicy::Enabled:
3127 ASSERT_NOT_REACHED();
3129 case HttpEquivPolicy::DisabledBySettings:
3130 reason = "by the embedder.";
3132 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3133 reason = "for documents with Content-Disposition: attachment.";
3136 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3137 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3141 Frame* frame = this->frame();
3143 HTTPHeaderName headerName;
3144 if (!findHTTPHeaderName(equiv, headerName))
3147 switch (headerName) {
3148 case HTTPHeaderName::DefaultStyle:
3149 // The preferred style set has been overridden as per section
3150 // 14.3.2 of the HTML4.0 specification. We need to update the
3151 // sheet used variable and then update our style selector.
3152 // For more info, see the test at:
3153 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3155 authorStyleSheets().setSelectedStylesheetSetName(content);
3156 authorStyleSheets().setPreferredStylesheetSetName(content);
3157 styleResolverChanged(DeferRecalcStyle);
3160 case HTTPHeaderName::Refresh: {
3163 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
3165 if (urlString.isEmpty())
3166 completedURL = m_url;
3168 completedURL = completeURL(urlString);
3169 if (!protocolIsJavaScript(completedURL))
3170 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3172 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3173 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3180 case HTTPHeaderName::SetCookie:
3181 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3182 if (is<HTMLDocument>(*this)) {
3183 // Exception (for sandboxed documents) ignored.
3184 downcast<HTMLDocument>(*this).setCookie(content, IGNORE_EXCEPTION);
3188 case HTTPHeaderName::ContentLanguage:
3189 setContentLanguage(content);
3192 case HTTPHeaderName::XDNSPrefetchControl:
3193 parseDNSPrefetchControlHeader(content);
3196 case HTTPHeaderName::XFrameOptions:
3198 FrameLoader& frameLoader = frame->loader();
3199 unsigned long requestIdentifier = 0;
3200 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3201 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3202 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3203 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3204 frameLoader.stopAllLoaders();
3205 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3206 // intent, we must navigate away from the possibly partially-rendered document to a location that
3207 // doesn't inherit the parent's SecurityOrigin.
3208 frame->navigationScheduler().scheduleLocationChange(this, securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
3209 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3214 case HTTPHeaderName::ContentSecurityPolicy:
3215 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
3218 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
3219 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
3222 case HTTPHeaderName::XWebKitCSP:
3223 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
3226 case HTTPHeaderName::XWebKitCSPReportOnly:
3227 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
3235 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3236 static bool isSeparator(UChar c)
3238 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3241 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3243 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3244 unsigned keyBegin, keyEnd;
3245 unsigned valueBegin, valueEnd;
3247 String buffer = features.lower();
3248 unsigned length = buffer.length();
3249 for (unsigned i = 0; i < length; ) {
3250 // skip to first non-separator, but don't skip past the end of the string
3251 while (isSeparator(buffer[i])) {
3258 // skip to first separator
3259 while (!isSeparator(buffer[i]))
3263 // skip to first '=', but don't skip past a ',' or the end of the string
3264 while (buffer[i] != '=') {
3265 if (buffer[i] == ',' || i >= length)
3270 // skip to first non-separator, but don't skip past a ',' or the end of the string
3271 while (isSeparator(buffer[i])) {
3272 if (buffer[i] == ',' || i >= length)
3278 // skip to first separator
3279 while (!isSeparator(buffer[i]))
3283 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
3285 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3286 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3287 callback(keyString, valueString, this, data);
3291 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3293 ASSERT(!features.isNull());
3295 if (origin < m_viewportArguments.type)
3298 m_viewportArguments = ViewportArguments(origin);
3299 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3301 updateViewportArguments();
3304 void Document::updateViewportArguments()
3306 if (page() && frame()->isMainFrame()) {
3308 m_didDispatchViewportPropertiesChanged = true;
3310 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3312 page()->chrome().didReceiveDocType(frame());
3318 // FIXME: Find a better place for this functionality.
3319 void setParserFeature(const String& key, const String& value, Document* document, void*)
3321 if (key == "telephone" && equalIgnoringCase(value, "no"))
3322 document->setIsTelephoneNumberParsingAllowed(false);
3325 void Document::processFormatDetection(const String& features)
3327 ASSERT(!features.isNull());
3328 processArguments(features, nullptr, &setParserFeature);
3331 void Document::processWebAppOrientations()
3333 if (Page* page = this->page())
3334 page->chrome().client().webAppOrientationsUpdated();
3338 void Document::processReferrerPolicy(const String& policy)
3340 ASSERT(!policy.isNull());
3342 // Note that we're supporting both the standard and legacy keywords for referrer
3343 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3344 if (equalIgnoringCase(policy, "no-referrer") || equalIgnoringCase(policy, "never"))
3345 setReferrerPolicy(ReferrerPolicyNever);
3346 else if (equalIgnoringCase(policy, "unsafe-url") || equalIgnoringCase(policy, "always"))
3347 setReferrerPolicy(ReferrerPolicyAlways);
3348 else if (equalIgnoringCase(policy, "origin"))
3349 setReferrerPolicy(ReferrerPolicyOrigin);
3350 else if (equalIgnoringCase(policy, "no-referrer-when-downgrade") || equalIgnoringCase(policy, "default"))
3351 setReferrerPolicy(ReferrerPolicyDefault);
3353 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'.");
3354 setReferrerPolicy(ReferrerPolicyNever);
3358 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3360 if (!hasLivingRenderTree())
3361 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3363 HitTestResult result(documentPoint);
3364 renderView()->hitTest(request, result);
3366 if (!request.readOnly())
3367 updateHoverActiveState(request, result.innerElement());
3369 return MouseEventWithHitTestResults(event, result);
3372 // DOM Section 1.1.1
3373 bool Document::childTypeAllowed(NodeType type) const
3376 case ATTRIBUTE_NODE:
3377 case CDATA_SECTION_NODE:
3378 case DOCUMENT_FRAGMENT_NODE:
3383 case PROCESSING_INSTRUCTION_NODE:
3385 case DOCUMENT_TYPE_NODE:
3387 // Documents may contain no more than one of each of these.
3388 // (One Element and one DocumentType.)
3389 for (Node* c = firstChild(); c; c = c->nextSibling())
3390 if (c->nodeType() == type)
3397 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3399 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3402 switch (newChild.nodeType()) {
3403 case ATTRIBUTE_NODE:
3404 case CDATA_SECTION_NODE:
3409 case PROCESSING_INSTRUCTION_NODE:
3411 case DOCUMENT_FRAGMENT_NODE: {
3412 bool hasSeenElementChild = false;
3413 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3414 if (is<Element>(*node)) {
3415 if (hasSeenElementChild)
3417 hasSeenElementChild = true;
3419 if (!canAcceptChild(*node, refChild, operation))
3424 case DOCUMENT_TYPE_NODE: {
3425 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3426 if (operation == AcceptChildOperation::Replace) {
3427 // parent has a doctype child that is not child, or an element is preceding child.
3428 if (existingDocType && existingDocType != refChild)
3430 if (refChild->previousElementSibling())
3433 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3434 if (existingDocType)
3436 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3441 case ELEMENT_NODE: {
3442 auto* existingElementChild = firstElementChild();
3443 if (operation == AcceptChildOperation::Replace) {
3444 if (existingElementChild && existingElementChild != refChild)
3446 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3447 if (is<DocumentType>(*child))
3451 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3452 if (existingElementChild)
3454 for (auto* child = refChild; child; child = child->nextSibling()) {
3455 if (is<DocumentType>(*child))
3465 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3467 Ref<Document> clone = cloneDocumentWithoutChildren();
3468 clone->cloneDataFromDocument(*this);
3470 case CloningOperation::OnlySelf:
3471 case CloningOperation::SelfWithTemplateContent:
3473 case CloningOperation::Everything:
3474 cloneChildNodes(clone);
3477 return WTF::move(clone);
3480 Ref<Document> Document::cloneDocumentWithoutChildren() const
3482 return isXHTMLDocument() ? createXHTML(nullptr, url()) : create(nullptr, url());
3485 void Document::cloneDataFromDocument(const Document& other)
3487 ASSERT(m_url == other.url());
3488 m_baseURL = other.baseURL();
3489 m_baseURLOverride = other.baseURLOverride();
3490 m_documentURI = other.documentURI();
3492 setCompatibilityMode(other.m_compatibilityMode);
3493 setSecurityOriginPolicy(other.securityOriginPolicy());
3494 overrideMIMEType(other.contentType());
3495 setDecoder(other.decoder());
3498 StyleSheetList& Document::styleSheets()
3500 if (!m_styleSheetList)
3501 m_styleSheetList = StyleSheetList::create(this);
3502 return *m_styleSheetList;
3505 String Document::preferredStylesheetSet() const
3507 return authorStyleSheets().preferredStylesheetSetName();
3510 String Document::selectedStylesheetSet() const
3512 return authorStyleSheets().selectedStylesheetSetName();
3515 void Document::setSelectedStylesheetSet(const String& aString)
3517 authorStyleSheets().setSelectedStylesheetSetName(aString);
3518 styleResolverChanged(DeferRecalcStyle);
3521 void Document::evaluateMediaQueryList()
3523 if (m_mediaQueryMatcher)
3524 m_mediaQueryMatcher->styleResolverChanged();
3526 checkViewportDependentPictures();
3529 void Document::checkViewportDependentPictures()
3531 Vector<HTMLPictureElement*, 16> changedPictures;
3532 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3533 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3534 if ((*it)->viewportChangeAffectedPicture())
3535 changedPictures.append(*it);
3537 for (auto* picture : changedPictures)
3538 picture->sourcesChanged();
3541 void Document::optimizedStyleSheetUpdateTimerFired()
3543 styleResolverChanged(RecalcStyleIfNeeded);
3546 void Document::scheduleOptimizedStyleSheetUpdate()
3548 if (m_optimizedStyleSheetUpdateTimer.isActive())
3550 authorStyleSheets().setPendingUpdateType(AuthorStyleSheets::OptimizedUpdate);
3551 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3554 void Document::updateViewportUnitsOnResize()
3556 if (!hasStyleWithViewportUnits())
3559 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3561 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3562 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3563 auto* renderer = element->renderer();
3564 if (renderer && renderer->style().hasViewportUnits())
3565 element->setNeedsStyleRecalc(InlineStyleChange);
3569 void Document::addAudioProducer(MediaProducer* audioProducer)
3571 m_audioProducers.add(audioProducer);
3572 updateIsPlayingMedia();
3575 void Document::removeAudioProducer(MediaProducer* audioProducer)
3577 m_audioProducers.remove(audioProducer);
3578 updateIsPlayingMedia();
3581 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3583 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3584 for (auto* audioProducer : m_audioProducers)
3585 state |= audioProducer->mediaState();
3587 #if ENABLE(MEDIA_SESSION)
3588 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3589 if (sourceElement->isPlaying())
3590 state |= MediaProducer::IsSourceElementPlaying;
3592 if (auto* session = sourceElement->session()) {
3593 if (auto* controls = session->controls()) {
3594 if (controls->previousTrackEnabled())
3595 state |= MediaProducer::IsPreviousTrackControlEnabled;
3596 if (controls->nextTrackEnabled())
3597 state |= MediaProducer::IsNextTrackControlEnabled;
3603 if (state == m_mediaState)
3606 m_mediaState = state;
3609 page()->updateIsPlayingMedia(sourceElementID);
3612 void Document::pageMutedStateDidChange()
3614 for (auto* audioProducer : m_audioProducers)
3615 audioProducer->pageMutedStateDidChange();
3618 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3620 if (m_optimizedStyleSheetUpdateTimer.isActive())
3621 m_optimizedStyleSheetUpdateTimer.stop();
3623 // Don't bother updating, since we haven't loaded all our style info yet
3624 // and haven't calculated the style selector for the first time.
3625 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3626 m_styleResolver = nullptr;
3629 m_didCalculateStyleResolver = true;
3631 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3632 if (!ownerElement())
3633 printf("Beginning update of style selector at time %lld.\n", elapsedTime().count());
3636 auto styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3637 ? AuthorStyleSheets::OptimizedUpdate
3638 : AuthorStyleSheets::FullUpdate;
3639 bool stylesheetChangeRequiresStyleRecalc = authorStyleSheets().updateActiveStyleSheets(styleSheetUpdate);
3641 if (updateFlag == DeferRecalcStyle) {
3642 scheduleForcedStyleRecalc();
3646 if (updateFlag == DeferRecalcStyleIfNeeded) {
3647 if (stylesheetChangeRequiresStyleRecalc)
3648 scheduleForcedStyleRecalc();
3652 if (!stylesheetChangeRequiresStyleRecalc)
3655 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3656 // make sure animations get the correct update time
3658 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
3659 recalcStyle(Style::Force);
3662 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3663 if (!ownerElement())
3664 printf("Finished update of style selector at time %lld\n", elapsedTime().count());
3668 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3670 view()->scheduleRelayout();
3673 evaluateMediaQueryList();
3676 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3678 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3681 Element* focusedElement = node->treeScope().focusedElement();
3682 if (!focusedElement)
3685 bool nodeInSubtree = false;
3686 if (amongChildrenOnly)
3687 nodeInSubtree = focusedElement->isDescendantOf(node);
3689 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3692 setFocusedElement(nullptr);
3695 void Document::hoveredElementDidDetach(Element* element)
3697 if (!m_hoveredElement || element != m_hoveredElement)
3700 m_hoveredElement = element->parentElement();
3701 while (m_hoveredElement && !m_hoveredElement->renderer())
3702 m_hoveredElement = m_hoveredElement->parentElement();
3704 frame()->eventHandler().scheduleHoverStateUpdate();
3707 void Document::elementInActiveChainDidDetach(Element* element)
3709 if (!m_activeElement || element != m_activeElement)
3712 m_activeElement = element->parentElement();
3713 while (m_activeElement && !m_activeElement->renderer())
3714 m_activeElement = m_activeElement->parentElement();
3717 #if ENABLE(DASHBOARD_SUPPORT)
3718 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3720 return m_annotatedRegions;
3723 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3725 m_annotatedRegions = regions;
3726 setAnnotatedRegionsDirty(false);
3730 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
3732 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3734 // Make sure newFocusedElement is actually in this document
3735 if (newFocusedElement && (&newFocusedElement->document() != this))
3738 if (m_focusedElement == newFocusedElement)
3744 bool focusChangeBlocked = false;
3745 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3747 // Remove focus from the existing focus node (if any)
3748 if (oldFocusedElement) {
3749 if (oldFocusedElement->active())
3750 oldFocusedElement->setActive(false);
3752 oldFocusedElement->setFocus(false);
3754 // Dispatch a change event for form control elements that have been edited.
3755 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3756 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3757 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3758 formControlElement.dispatchFormControlChangeEvent();
3761 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3762 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3764 if (m_focusedElement) {
3765 // handler shifted focus
3766 focusChangeBlocked = true;
3767 newFocusedElement = nullptr;
3770 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3771 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3772 // on it, probably when <rdar://problem/8503958> is resolved.
3773 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3775 if (m_focusedElement) {
3776 // handler shifted focus
3777 focusChangeBlocked = true;
3778 newFocusedElement = nullptr;
3781 if (oldFocusedElement->isRootEditableElement())
3782 frame()->editor().didEndEditing();
3785 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3786 oldWidget->setFocus(false);
3788 view()->setFocus(false);
3792 if (newFocusedElement && newFocusedElement->isFocusable()) {
3793 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3794 // delegate blocks focus change
3795 focusChangeBlocked = true;
3796 goto SetFocusedNodeDone;
3798 // Set focus on the new node
3799 m_focusedElement = newFocusedElement;
3801 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3802 m_focusedElement->dispatchFocusEvent(oldFocusedElement.copyRef(), direction);
3804 if (m_focusedElement != newFocusedElement) {
3805 // handler shifted focus
3806 focusChangeBlocked = true;
3807 goto SetFocusedNodeDone;
3810 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.copyRef()); // DOM level 3 bubbling focus event.
3812 if (m_focusedElement != newFocusedElement) {
3813 // handler shifted focus
3814 focusChangeBlocked = true;
3815 goto SetFocusedNodeDone;
3818 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3819 // on it, probably when <rdar://problem/8503958> is m.
3820 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement.copyRef()); // DOM level 2 for compatibility.
3822 if (m_focusedElement != newFocusedElement) {
3823 // handler shifted focus
3824 focusChangeBlocked = true;
3825 goto SetFocusedNodeDone;
3828 m_focusedElement->setFocus(true);
3830 if (m_focusedElement->isRootEditableElement())
3831 frame()->editor().didBeginEditing();
3833 // eww, I suck. set the qt focus correctly
3834 // ### find a better place in the code for this
3836 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3838 // Make sure a widget has the right size before giving it focus.
3839 // Otherwise, we are testing edge cases of the Widget code.
3840 // Specifically, in WebCore this does not work well for text fields.
3842 // Re-get the widget in case updating the layout changed things.
3843 focusWidget = widgetForElement(m_focusedElement.get());
3846 focusWidget->setFocus(true);
3848 view()->setFocus(true);
3852 if (!focusChangeBlocked && m_focusedElement) {
3853 // Create the AXObject cache in a focus change because GTK relies on it.
3854 if (AXObjectCache* cache = axObjectCache())
3855 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3858 if (!focusChangeBlocked && page())
3859 page()->chrome().focusedElementChanged(m_focusedElement.get());
3862 updateStyleIfNeeded();
3863 return !focusChangeBlocked;
3866 void Document::setCSSTarget(Element* n)
3869 m_cssTarget->setNeedsStyleRecalc();
3872 n->setNeedsStyleRecalc();
3875 void Document::registerNodeListForInvalidation(LiveNodeList& list)
3877 m_nodeListAndCollectionCounts[list.invalidationType()]++;
3878 if (!list.isRootedAtDocument())
3880 ASSERT(!list.isRegisteredForInvalidationAtDocument());
3881 list.setRegisteredForInvalidationAtDocument(true);
3882 m_listsInvalidatedAtDocument.add(&list);
3885 void Document::unregisterNodeListForInvalidation(LiveNodeList& list)
3887 m_nodeListAndCollectionCounts[list.invalidationType()]--;
3888 if (!list.isRegisteredForInvalidationAtDocument())
3891 list.setRegisteredForInvalidationAtDocument(false);
3892 ASSERT(m_inInvalidateNodeListAndCollectionCaches
3893 ? m_listsInvalidatedAtDocument.isEmpty()
3894 : m_listsInvalidatedAtDocument.contains(&list));
3895 m_listsInvalidatedAtDocument.remove(&list);
3898 void Document::registerCollection(HTMLCollection& collection)
3900 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
3901 if (collection.isRootedAtDocument())
3902 m_collectionsInvalidatedAtDocument.add(&collection);
3905 void Document::unregisterCollection(HTMLCollection& collection)
3907 ASSERT(m_nodeListAndCollectionCounts[collection.invalidationType()]);
3908 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
3909 if (!collection.isRootedAtDocument())
3912 m_collectionsInvalidatedAtDocument.remove(&collection);
3915 void Document::collectionCachedIdNameMap(const HTMLCollection& collection)
3917 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3918 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
3921 void Document::collectionWillClearIdNameMap(const HTMLCollection& collection)
3923 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3924 ASSERT(m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]);
3925 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
3928 void Document::attachNodeIterator(NodeIterator* ni)
3930 m_nodeIterators.add(ni);
3933 void Document::detachNodeIterator(NodeIterator* ni)
3935 // The node iterator can be detached without having been attached if its root node didn't have a document
3936 // when the iterator was created, but has it now.
3937 m_nodeIterators.remove(ni);
3940 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3942 Vector<NodeIterator*> nodeIterators;
3943 copyToVector(m_nodeIterators, nodeIterators);
3944 for (auto* it : nodeIterators) {
3945 if (it->root() == node) {
3946 detachNodeIterator(it);
3947 newDocument->attachNodeIterator(it);
3952 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
3954 for (auto* range : m_ranges)
3955 range->nodeChildrenChanged(container);
3958 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3960 for (auto* range : m_ranges)
3961 range->nodeChildrenWillBeRemoved(container);
3963 for (auto* it : m_nodeIterators) {
3964 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3965 it->nodeWillBeRemoved(*n);
3968 if (Frame* frame = this->frame()) {
3969 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3970 frame->eventHandler().nodeWillBeRemoved(*n);
3971 frame->selection().nodeWillBeRemoved(*n);
3972 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3976 if (m_markers->hasMarkers()) {
3977 for (Text* textNode = TextNodeTraversal::firstChild(container); textNode; textNode = TextNodeTraversal::nextSibling(*textNode))
3978 m_markers->removeMarkers(textNode);
3982 void Document::nodeWillBeRemoved(Node& n)
3984 for (auto* it : m_nodeIterators)
3985 it->nodeWillBeRemoved(n);
3987 for (auto* range : m_ranges)
3988 range->nodeWillBeRemoved(n);
3990 if (Frame* frame = this->frame()) {
3991 frame->eventHandler().nodeWillBeRemoved(n);
3992 frame->selection().nodeWillBeRemoved(n);
3993 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3997 m_markers->removeMarkers(&n);
4000 void Document::textInserted(Node* text, unsigned offset, unsigned length)
4002 if (!m_ranges.isEmpty()) {
4003 for (auto* range : m_ranges)
4004 range->textInserted(text, offset, length);
4007 // Update the markers for spelling and grammar checking.
4008 m_markers->shiftMarkers(text, offset, length);
4011 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
4013 if (!m_ranges.isEmpty()) {
4014 for (auto* range : m_ranges)
4015 range->textRemoved(text, offset, length);
4018 // Update the markers for spelling and grammar checking.
4019 m_markers->removeMarkers(text, offset, length);
4020 m_markers->shiftMarkers(text, offset + length, 0 - length);
4023 void Document::textNodesMerged(Text* oldNode, unsigned offset)
4025 if (!m_ranges.isEmpty()) {
4026 NodeWithIndex oldNodeWithIndex(oldNode);
4027 for (auto* range : m_ranges)
4028 range->textNodesMerged(oldNodeWithIndex, offset);
4031 // FIXME: This should update markers for spelling and grammar checking.
4034 void Document::textNodeSplit(Text* oldNode)
4036 for (auto* range : m_ranges)
4037 range->textNodeSplit(oldNode);
4039 // FIXME: This should update markers for spelling and grammar checking.
4042 void Document::createDOMWindow()
4045 ASSERT(!m_domWindow);
4047 m_domWindow = DOMWindow::create(this);
4049 ASSERT(m_domWindow->document() == this);
4050 ASSERT(m_domWindow->frame() == m_frame);
4053 void Document::takeDOMWindowFrom(Document* document)
4056 ASSERT(!m_domWindow);
4057 ASSERT(document->m_domWindow);
4058 // A valid DOMWindow is needed by CachedFrame for its documents.
4059 ASSERT(!document->inPageCache());
4061 m_domWindow = document->m_domWindow.release();
4062 m_domWindow->didSecureTransitionTo(this);
4064 ASSERT(m_domWindow->document() == this);
4065 ASSERT(m_domWindow->frame() == m_frame);
4068 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
4072 m_domWindow->setAttributeEventListener(eventType, listener);
4075 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
4079 setWindowAttributeEventListener(eventType, JSLazyEventListener::createForDOMWindow(*m_frame, attributeName, attributeValue));
4082 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
4086 return m_domWindow->getAttributeEventListener(eventType);
4089 void Document::dispatchWindowEvent(Event& event, EventTarget* target)
4091 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4094 m_domWindow->dispatchEvent(event, target);
4097 void Document::dispatchWindowLoadEvent()
4099 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4102 m_domWindow->dispatchLoadEvent();
4103 m_loadEventFinished = true;
4104 m_cachedResourceLoader->documentDidFinishLoadEvent();
4107 void Document::enqueueWindowEvent(Ref<Event>&& event)
4109 event->setTarget(m_domWindow.get());
4110 m_eventQueue.enqueueEvent(WTF::move(event));
4113 void Document::enqueueDocumentEvent(Ref<Event>&& event)
4115 event->setTarget(this);
4116 m_eventQueue.enqueueEvent(WTF::move(event));
4119 void Document::enqueueOverflowEvent(Ref<Event>&& event)
4121 m_eventQueue.enqueueEvent(WTF::move(event));
4124 RefPtr<Event> Document::createEvent(const String& type, ExceptionCode& ec)
4126 // Please do *not* add new event classes to this function unless they are
4127 // required for compatibility of some actual legacy web content.
4129 // This mechanism is superceded by use of event constructors.
4130 // That is what we should use for any new event classes.
4132 // The following strings are the ones from the DOM specification
4133 // <https://dom.spec.whatwg.org/#dom-document-createevent>.
4135 if (equalIgnoringASCIICase(type, "customevent"))
4136 return CustomEvent::create();
4137 if (equalIgnoringASCIICase(type, "event") || equalIgnoringASCIICase(type, "events") || equalIgnoringASCIICase(type, "htmlevents"))
4138 return Event::create();
4139 if (equalIgnoringASCIICase(type, "keyboardevent") || equalIgnoringASCIICase(type, "keyboardevents"))
4140 return KeyboardEvent::create();
4141 if (equalIgnoringASCIICase(type, "messageevent"))
4142 return MessageEvent::create();
4143 if (equalIgnoringASCIICase(type, "mouseevent") || equalIgnoringASCIICase(type, "mouseevents"))
4144 return MouseEvent::create();
4145 if (equalIgnoringASCIICase(type, "uievent") || equalIgnoringASCIICase(type, "uievents"))
4146 return UIEvent::create();
4148 #if ENABLE(TOUCH_EVENTS)
4149 if (equalIgnoringASCIICase(type, "touchevent"))
4150 return TouchEvent::create();
4153 // The following string comes from the SVG specifications
4154 // <http://www.w3.org/TR/SVG/script.html#InterfaceSVGZoomEvent>
4155 // <http://www.w3.org/TR/SVG2/interact.html#InterfaceSVGZoomEvent>.
4156 // However, since there is no provision for initializing the event once it is created,
4157 // there is no practical value in this feature.
4159 if (equalIgnoringASCIICase(type, "svgzoomevents"))
4160 return SVGZoomEvent::create();
4162 // The following strings are for event classes where WebKit supplies an init function.
4163 // These strings are not part of the DOM specification and we would like to eliminate them.
4164 // However, we currently include these because we have concerns about backward compatibility.
4166 // FIXME: For each of the strings below, prove there is no content depending on it and remove
4167 // both the string and the corresponding init function for that class.
4169 if (equalIgnoringASCIICase(type, "compositionevent"))
4170 return CompositionEvent::create();
4171 if (equalIgnoringASCIICase(type, "hashchangeevent"))
4172 return HashChangeEvent::create();
4173 if (equalIgnoringASCIICase(type, "mutationevent") || equalIgnoringASCIICase(type, "mutationevents"))
4174 return MutationEvent::create();
4175 if (equalIgnoringASCIICase(type, "overflowevent"))
4176 return OverflowEvent::create();
4177 if (equalIgnoringASCIICase(type, "storageevent"))
4178 return StorageEvent::create();
4179 if (equalIgnoringASCIICase(type, "textevent"))
4180 return TextEvent::create();
4181 if (equalIgnoringASCIICase(type, "wheelevent"))
4182 return WheelEvent::create();
4184 #if ENABLE(DEVICE_ORIENTATION)
4185 if (equalIgnoringASCIICase(type, "devicemotionevent"))
4186 return DeviceMotionEvent::create();
4187 if (equalIgnoringASCIICase(type, "deviceorientationevent"))
4188 return DeviceOrientationEvent::create();
4191 ec = NOT_SUPPORTED_ERR;
4195 bool Document::hasListenerTypeForEventType(PlatformEvent::Type eventType) const
4197 switch (eventType) {
4198 case PlatformEvent::MouseForceChanged:
4199 return m_listenerTypes & Document::FORCECHANGED_LISTENER;
4200 case PlatformEvent::MouseForceDown:
4201 return m_listenerTypes & Document::FORCEDOWN_LISTENER;
4202 case PlatformEvent::MouseForceUp:
4203 return m_listenerTypes & Document::FORCEUP_LISTENER;
4204 case PlatformEvent::MouseScroll:
4205 return m_listenerTypes & Document::SCROLL_LISTENER;
4211 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
4213 if (eventType == eventNames().DOMSubtreeModifiedEvent)
4214 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
4215 else if (eventType == eventNames().DOMNodeInsertedEvent)
4216 addListenerType(DOMNODEINSERTED_LISTENER);
4217 else if (eventType == eventNames().DOMNodeRemovedEvent)
4218 addListenerType(DOMNODEREMOVED_LISTENER);
4219 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
4220 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
4221 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
4222 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
4223 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
4224 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
4225 else if (eventType == eventNames().overflowchangedEvent)
4226 addListenerType(OVERFLOWCHANGED_LISTENER);
4227 else if (eventType == eventNames().webkitAnimationStartEvent || eventType == eventNames().animationstartEvent)
4228 addListenerType(ANIMATIONSTART_LISTENER);
4229 else if (eventType == eventNames().webkitAnimationEndEvent || eventType == eventNames().animationendEvent)
4230 addListenerType(ANIMATIONEND_LISTENER);
4231 else if (eventType == eventNames().webkitAnimationIterationEvent || eventType == eventNames().animationiterationEvent)
4232 addListenerType(ANIMATIONITERATION_LISTENER);
4233 else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
4234 addListenerType(TRANSITIONEND_LISTENER);
4235 else if (eventType == eventNames().beforeloadEvent)
4236 addListenerType(BEFORELOAD_LISTENER);
4237 else if (eventType == eventNames().scrollEvent)
4238 addListenerType(SCROLL_LISTENER);
4239 else if (eventType == eventNames().webkitmouseforcewillbeginEvent)
4240 addListenerType(FORCEWILLBEGIN_LISTENER);
4241 else if (eventType == eventNames().webkitmouseforcechangedEvent)
4242 addListenerType(FORCECHANGED_LISTENER);
4243 else if (eventType == eventNames().webkitmouseforcedownEvent)
4244 addListenerType(FORCEDOWN_LISTENER);
4245 else if (eventType == eventNames().webkitmouseforceupEvent)
4246 addListenerType(FORCEUP_LISTENER);
4249 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
4254 HTMLFrameOwnerElement* Document::ownerElement() const
4258 return frame()->ownerElement();
4261 String Document::cookie(ExceptionCode& ec)
4263 if (page() && !page()->settings().cookieEnabled())
4266 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4267 // INVALID_STATE_ERR exception on getting if the Document has no
4268 // browsing context.
4270 if (!securityOrigin()->canAccessCookies()) {
4275 URL cookieURL = this->cookieURL();
4276 if (cookieURL.isEmpty())
4279 if (!isDOMCookieCacheValid())
4280 setCachedDOMCookies(cookies(this, cookieURL));
4282 return cachedDOMCookies();
4285 void Document::setCookie(const String& value, ExceptionCode& ec)
4287 if (page() && !page()->settings().cookieEnabled())
4290 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4291 // INVALID_STATE_ERR exception on setting if the Document has no
4292 // browsing context.
4294 if (!securityOrigin()->canAccessCookies()) {
4299 URL cookieURL = this->cookieURL();
4300 if (cookieURL.isEmpty())
4303 invalidateDOMCookieCache();
4304 setCookies(this, cookieURL, value);
4307 String Document::referrer() const
4310 return frame()->loader().referrer();
4314 String Document::origin() const
4316 return securityOrigin()->databaseIdentifier();