2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004-2015 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
32 #include "AnimationController.h"
34 #include "AuthorStyleSheets.h"
35 #include "CDATASection.h"
36 #include "CSSFontSelector.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedResourceLoader.h"
42 #include "ChromeClient.h"
44 #include "CompositionEvent.h"
45 #include "ContentSecurityPolicy.h"
46 #include "CookieJar.h"
47 #include "CustomElementDefinitions.h"
48 #include "CustomEvent.h"
49 #include "DOMImplementation.h"
50 #include "DOMNamedFlowCollection.h"
51 #include "DOMWindow.h"
52 #include "DateComponents.h"
53 #include "DebugPageOverlays.h"
54 #include "Dictionary.h"
55 #include "DocumentLoader.h"
56 #include "DocumentMarkerController.h"
57 #include "DocumentSharedObjectPool.h"
58 #include "DocumentType.h"
60 #include "ElementIterator.h"
61 #include "EntityReference.h"
62 #include "EventHandler.h"
63 #include "ExtensionStyleSheets.h"
64 #include "FocusController.h"
65 #include "FontLoader.h"
66 #include "FormController.h"
67 #include "FrameLoader.h"
68 #include "FrameLoaderClient.h"
69 #include "FrameView.h"
70 #include "GenericCachedHTMLCollection.h"
71 #include "HTMLAllCollection.h"
72 #include "HTMLAnchorElement.h"
73 #include "HTMLBaseElement.h"
74 #include "HTMLBodyElement.h"
75 #include "HTMLCanvasElement.h"
76 #include "HTMLDocument.h"
77 #include "HTMLElementFactory.h"
78 #include "HTMLFormControlElement.h"
79 #include "HTMLFrameOwnerElement.h"
80 #include "HTMLFrameSetElement.h"
81 #include "HTMLHeadElement.h"
82 #include "HTMLIFrameElement.h"
83 #include "HTMLImageElement.h"
84 #include "HTMLLinkElement.h"
85 #include "HTMLMediaElement.h"
86 #include "HTMLNameCollection.h"
87 #include "HTMLParserIdioms.h"
88 #include "HTMLPictureElement.h"
89 #include "HTMLPlugInElement.h"
90 #include "HTMLScriptElement.h"
91 #include "HTMLStyleElement.h"
92 #include "HTMLTitleElement.h"
93 #include "HTMLUnknownElement.h"
94 #include "HTTPHeaderNames.h"
95 #include "HTTPParsers.h"
96 #include "HashChangeEvent.h"
98 #include "HitTestResult.h"
99 #include "IconController.h"
100 #include "ImageLoader.h"
101 #include "InspectorInstrumentation.h"
102 #include "JSLazyEventListener.h"
103 #include "JSModuleLoader.h"
104 #include "KeyboardEvent.h"
105 #include "Language.h"
106 #include "LoaderStrategy.h"
108 #include "MainFrame.h"
109 #include "MediaCanStartListener.h"
110 #include "MediaProducer.h"
111 #include "MediaQueryList.h"
112 #include "MediaQueryMatcher.h"
113 #include "MessageEvent.h"
114 #include "MouseEventWithHitTestResults.h"
115 #include "MutationEvent.h"
116 #include "NameNodeList.h"
117 #include "NestingLevelIncrementer.h"
118 #include "NodeIterator.h"
119 #include "NodeRareData.h"
120 #include "NodeWithIndex.h"
121 #include "OverflowEvent.h"
122 #include "PageConsoleClient.h"
123 #include "PageGroup.h"
124 #include "PageTransitionEvent.h"
125 #include "PlatformLocale.h"
126 #include "PlatformMediaSessionManager.h"
127 #include "PlatformStrategies.h"
128 #include "PlugInsResources.h"
129 #include "PluginDocument.h"
130 #include "PointerLockController.h"
131 #include "PopStateEvent.h"
132 #include "ProcessingInstruction.h"
133 #include "RenderChildIterator.h"
134 #include "RenderLayerCompositor.h"
135 #include "RenderView.h"
136 #include "RenderWidget.h"
137 #include "RuntimeEnabledFeatures.h"
138 #include "SVGDocumentExtensions.h"
139 #include "SVGElement.h"
140 #include "SVGElementFactory.h"
141 #include "SVGNames.h"
142 #include "SVGTitleElement.h"
143 #include "SVGZoomEvent.h"
144 #include "SchemeRegistry.h"
145 #include "ScopedEventQueue.h"
146 #include "ScriptController.h"
147 #include "ScriptRunner.h"
148 #include "ScriptSourceCode.h"
149 #include "ScrollingCoordinator.h"
150 #include "SecurityOrigin.h"
151 #include "SecurityOriginPolicy.h"
152 #include "SecurityPolicy.h"
153 #include "SegmentedString.h"
154 #include "SelectorQuery.h"
155 #include "Settings.h"
156 #include "ShadowRoot.h"
157 #include "StorageEvent.h"
158 #include "StyleProperties.h"
159 #include "StyleResolveForDocument.h"
160 #include "StyleResolver.h"
161 #include "StyleSheetContents.h"
162 #include "StyleSheetList.h"
163 #include "StyleTreeResolver.h"
164 #include "SubresourceLoader.h"
165 #include "TextEvent.h"
166 #include "TextNodeTraversal.h"
167 #include "TransformSource.h"
168 #include "TreeWalker.h"
169 #include "VisitedLinkState.h"
170 #include "WheelEvent.h"
171 #include "XMLDocument.h"
172 #include "XMLDocumentParser.h"
173 #include "XMLNSNames.h"
174 #include "XMLNames.h"
175 #include "XPathEvaluator.h"
176 #include "XPathExpression.h"
177 #include "XPathNSResolver.h"
178 #include "XPathResult.h"
179 #include "htmlediting.h"
180 #include <JavaScriptCore/Profile.h>
182 #include <inspector/ScriptCallStack.h>
183 #include <wtf/CurrentTime.h>
184 #include <wtf/NeverDestroyed.h>
185 #include <wtf/SystemTracing.h>
186 #include <wtf/TemporaryChange.h>
187 #include <wtf/text/StringBuffer.h>
188 #include <yarr/RegularExpression.h>
191 #include "DOMSecurityPolicy.h"
194 #if ENABLE(DEVICE_ORIENTATION)
195 #include "DeviceMotionEvent.h"
196 #include "DeviceOrientationEvent.h"
199 #if ENABLE(FULLSCREEN_API)
200 #include "RenderFullScreen.h"
204 #include "CSSFontSelector.h"
205 #include "DeviceMotionClientIOS.h"
206 #include "DeviceMotionController.h"
207 #include "DeviceOrientationClientIOS.h"
208 #include "DeviceOrientationController.h"
209 #include "Geolocation.h"
210 #include "Navigator.h"
211 #include "NavigatorGeolocation.h"
212 #include "WKContentObservation.h"
213 #include "WebCoreSystemInterface.h"
216 #if ENABLE(IOS_GESTURE_EVENTS)
217 #include "GestureEvent.h"
220 #if ENABLE(IOS_TEXT_AUTOSIZING)
221 #include "TextAutoSizing.h"
225 #include "MathMLElement.h"
226 #include "MathMLElementFactory.h"
227 #include "MathMLNames.h"
230 #if ENABLE(MEDIA_SESSION)
231 #include "MediaSession.h"
234 #if ENABLE(REQUEST_ANIMATION_FRAME)
235 #include "RequestAnimationFrameCallback.h"
236 #include "ScriptedAnimationController.h"
239 #if ENABLE(TEXT_AUTOSIZING)
240 #include "TextAutosizer.h"
243 #if ENABLE(TOUCH_EVENTS)
244 #include "TouchEvent.h"
245 #include "TouchList.h"
248 #if ENABLE(VIDEO_TRACK)
249 #include "CaptionUserPreferences.h"
252 #if ENABLE(WEB_REPLAY)
253 #include "WebReplayInputs.h"
254 #include <replay/EmptyInputCursor.h>
255 #include <replay/InputCursor.h>
258 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
259 #include "MediaPlaybackTargetClient.h"
263 #include "XSLTProcessor.h"
267 using namespace Unicode;
271 using namespace HTMLNames;
273 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
275 static const unsigned cMaxWriteRecursionDepth = 21;
277 // DOM Level 2 says (letters added):
279 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
280 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
281 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
282 // 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.
283 // 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.
284 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
285 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
286 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
287 // i) Characters ':' and '_' are allowed as name-start characters.
288 // j) Characters '-' and '.' are allowed as name characters.
290 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
292 static inline bool isValidNameStart(UChar32 c)
295 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
299 if (c == ':' || c == '_')
302 // rules (a) and (f) above
303 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)))
307 if (c >= 0xF900 && c < 0xFFFE)
311 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
312 if (type == U_DT_FONT || type == U_DT_COMPAT)
318 static inline bool isValidNamePart(UChar32 c)
320 // rules (a), (e), and (i) above
321 if (isValidNameStart(c))
324 // rules (g) and (h) above
325 if (c == 0x00B7 || c == 0x0387)
329 if (c == '-' || c == '.')
332 // rules (b) and (f) above
333 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
337 if (c >= 0xF900 && c < 0xFFFE)
341 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
342 if (type == U_DT_FONT || type == U_DT_COMPAT)
348 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
350 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
352 // If a Document has the address "about:blank"
353 // The origin of the Document is the origin it was assigned when its browsing context was created.
355 // Note: We generalize this to all "blank" URLs and invalid URLs because we
356 // treat all of these URLs as about:blank.
358 return url.isEmpty() || url.isBlankURL();
361 static Widget* widgetForElement(Element* focusedElement)
365 auto* renderer = focusedElement->renderer();
366 if (!is<RenderWidget>(renderer))
368 return downcast<RenderWidget>(*renderer).widget();
371 static bool acceptsEditingFocus(Node* node)
374 ASSERT(node->hasEditableStyle());
376 Node* root = node->rootEditableElement();
377 Frame* frame = node->document().frame();
381 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
384 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
386 // targetFrame can be 0 when we're trying to navigate a top-level frame
387 // that has a 0 opener.
391 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
392 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
393 Document* ancestorDocument = ancestorFrame->document();
394 // FIXME: Should be an ASSERT? Frames should alway have documents.
395 if (!ancestorDocument)
398 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
399 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
402 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
403 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
404 // something more general instead?
405 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
412 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
414 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
416 // FIXME: should we print to the console of the document performing the navigation instead?
417 frame->document()->domWindow()->printErrorMessage(message);
420 uint64_t Document::s_globalTreeVersion = 0;
422 #if ENABLE(IOS_TEXT_AUTOSIZING)
423 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
425 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
428 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
430 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
434 HashSet<Document*>& Document::allDocuments()
436 static NeverDestroyed<HashSet<Document*>> documents;
440 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
441 : ContainerNode(*this, CreateDocument)
443 #if ENABLE(IOS_TOUCH_EVENTS)
444 , m_handlingTouchEvent(false)
445 , m_touchEventRegionsDirty(false)
446 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
448 , m_referencingNodeCount(0)
449 , m_didCalculateStyleResolver(false)
450 , m_hasNodesWithPlaceholderStyle(false)
451 , m_needsNotifyRemoveAllPendingStylesheet(false)
452 , m_ignorePendingStylesheets(false)
453 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
455 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
456 , m_activeParserCount(0)
457 , m_wellFormed(false)
459 , m_paginatedForScreen(false)
460 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
461 , m_compatibilityModeLocked(false)
462 , m_textColor(Color::black)
463 , m_domTreeVersion(++s_globalTreeVersion)
465 , m_mutationObserverTypes(0)
466 , m_authorStyleSheets(std::make_unique<AuthorStyleSheets>(*this))
467 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
468 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
469 , m_visuallyOrdered(false)
470 , m_readyState(Complete)
472 , m_optimizedStyleSheetUpdateTimer(*this, &Document::optimizedStyleSheetUpdateTimerFired)
473 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
474 , m_pendingStyleRecalcShouldForce(false)
475 , m_inStyleRecalc(false)
476 , m_closeAfterStyleRecalc(false)
477 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
478 , m_frameElementsShouldIgnoreScrolling(false)
479 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
480 , m_markers(std::make_unique<DocumentMarkerController>(*this))
481 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
482 , m_cssTarget(nullptr)
483 , m_processingLoadEvent(false)
484 , m_loadEventFinished(false)
485 , m_startTime(std::chrono::steady_clock::now())
486 , m_overMinimumLayoutThreshold(false)
487 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
488 , m_moduleLoader(std::make_unique<JSModuleLoader>(*this))
489 , m_xmlVersion(ASCIILiteral("1.0"))
490 , m_xmlStandalone(StandaloneUnspecified)
491 , m_hasXMLDeclaration(false)
492 , m_designMode(inherit)
494 , m_inInvalidateNodeListAndCollectionCaches(false)
496 #if ENABLE(DASHBOARD_SUPPORT)
497 , m_hasAnnotatedRegions(false)
498 , m_annotatedRegionsDirty(false)
500 , m_createRenderers(true)
501 , m_inPageCache(false)
502 , m_accessKeyMapValid(false)
503 , m_documentClasses(documentClasses)
504 , m_isSynthesized(constructionFlags & Synthesized)
505 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
506 , m_sawElementsInKnownNamespaces(false)
507 , m_isSrcdocDocument(false)
508 , m_eventQueue(*this)
509 , m_weakFactory(this)
510 #if ENABLE(FULLSCREEN_API)
511 , m_areKeysEnabledInFullScreen(0)
512 , m_fullScreenRenderer(nullptr)
513 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
514 , m_isAnimatingFullScreen(false)
516 , m_loadEventDelayCount(0)
517 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
518 , m_referrerPolicy(ReferrerPolicyDefault)
519 , m_writeRecursionIsTooDeep(false)
520 , m_writeRecursionDepth(0)
521 , m_lastHandledUserGestureTimestamp(0)
523 #if ENABLE(DEVICE_ORIENTATION)
524 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
525 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
526 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
527 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
530 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
531 , m_isTelephoneNumberParsingAllowed(true)
533 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
534 , m_scheduledTasksAreSuspended(false)
535 , m_visualUpdatesAllowed(true)
536 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
537 , m_sharedObjectPoolClearTimer(*this, &Document::sharedObjectPoolClearTimerFired)
539 , m_didDispatchViewportPropertiesChanged(false)
541 #if ENABLE(TEMPLATE_ELEMENT)
542 , m_templateDocumentHost(nullptr)
544 #if ENABLE(WEB_REPLAY)
545 , m_inputCursor(EmptyInputCursor::create())
547 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
548 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
549 , m_disabledFieldsetElementsCount(0)
550 , m_hasInjectedPlugInsScript(false)
551 , m_renderTreeBeingDestroyed(false)
552 , m_hasPreparedForDestruction(false)
553 , m_hasStyleWithViewportUnits(false)
555 allDocuments().add(this);
557 // We depend on the url getting immediately set in subframes, but we
558 // also depend on the url NOT getting immediately set in opened windows.
559 // See fast/dom/early-frame-url.html
560 // and fast/dom/location-new-window-no-crash.html, respectively.
561 // FIXME: Can/should we unify this behavior?
562 if ((frame && frame->ownerElement()) || !url.isEmpty())
565 m_cachedResourceLoader->setDocument(this);
567 #if ENABLE(TEXT_AUTOSIZING)
568 m_textAutosizer = std::make_unique<TextAutosizer>(this);
572 resetVisitedLinkColor();
573 resetActiveLinkColor();
575 initSecurityContext();
578 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
579 nodeListAndCollectionCount = 0;
582 #if ENABLE(FULLSCREEN_API)
583 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
588 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
590 } while ((owner = owner->document().ownerElement()));
595 Ref<Document> Document::create(ScriptExecutionContext& context)
597 Ref<Document> document = adoptRef(*new Document(nullptr, URL()));
598 document->setSecurityOriginPolicy(context.securityOriginPolicy());
603 Document::~Document()
605 allDocuments().remove(this);
607 ASSERT(!renderView());
608 ASSERT(!m_inPageCache);
609 ASSERT(m_ranges.isEmpty());
610 ASSERT(!m_parentTreeScope);
611 ASSERT(!m_disabledFieldsetElementsCount);
613 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
614 m_deviceMotionClient->deviceMotionControllerDestroyed();
615 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
618 #if ENABLE(TEMPLATE_ELEMENT)
619 if (m_templateDocument)
620 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
623 // FIXME: Should we reset m_domWindow when we detach from the Frame?
625 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
627 m_scriptRunner = nullptr;
628 m_moduleLoader = nullptr;
630 removeAllEventListeners();
632 // Currently we believe that Document can never outlive the parser.
633 // Although the Document may be replaced synchronously, DocumentParsers
634 // generally keep at least one reference to an Element which would in turn
635 // has a reference to the Document. If you hit this ASSERT, then that
636 // assumption is wrong. DocumentParser::detach() should ensure that even
637 // if the DocumentParser outlives the Document it won't cause badness.
638 ASSERT(!m_parser || m_parser->refCount() == 1);
641 if (this == &topDocument())
642 clearAXObjectCache();
646 if (m_styleSheetList)
647 m_styleSheetList->detachFromDocument();
650 m_elementSheet->detachFromDocument();
651 extensionStyleSheets().detachFromDocument();
653 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
655 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
656 // load the initial empty document and the SVGDocument with the same DocumentLoader).
657 if (m_cachedResourceLoader->document() == this)
658 m_cachedResourceLoader->setDocument(nullptr);
661 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
662 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
665 // We must call clearRareData() here since a Document class inherits TreeScope
666 // as well as Node. See a comment on TreeScope.h for the reason.
670 ASSERT(!m_listsInvalidatedAtDocument.size());
671 ASSERT(!m_collectionsInvalidatedAtDocument.size());
673 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
674 ASSERT(!m_nodeListAndCollectionCounts[i]);
677 void Document::removedLastRef()
679 ASSERT(!m_deletionHasBegun);
680 if (m_referencingNodeCount) {
681 // If removing a child removes the last node reference, we don't want the scope to be destroyed
682 // until after removeDetachedChildren returns, so we protect ourselves.
683 incrementReferencingNodeCount();
685 // We must make sure not to be retaining any of our children through
686 // these extra pointers or we will create a reference cycle.
687 m_focusedElement = nullptr;
688 m_hoveredElement = nullptr;
689 m_activeElement = nullptr;
690 m_titleElement = nullptr;
691 m_documentElement = nullptr;
692 m_userActionElements.documentDidRemoveLastRef();
693 #if ENABLE(FULLSCREEN_API)
694 m_fullScreenElement = nullptr;
695 m_fullScreenElementStack.clear();
700 // removeDetachedChildren() doesn't always unregister IDs,
701 // so tear down scope information up front to avoid having
702 // stale references in the map.
704 destroyTreeScopeData();
705 removeDetachedChildren();
706 m_formController = nullptr;
710 m_cssCanvasElements.clear();
715 // We need to do this right now since selfOnlyDeref() can delete this.
716 m_inRemovedLastRefFunction = false;
718 decrementReferencingNodeCount();
721 m_inRemovedLastRefFunction = false;
722 m_deletionHasBegun = true;
728 void Document::commonTeardown()
731 accessSVGExtensions().pauseAnimations();
733 #if ENABLE(REQUEST_ANIMATION_FRAME)
734 clearScriptedAnimationController();
738 Element* Document::getElementByAccessKey(const String& key)
742 if (!m_accessKeyMapValid) {
743 buildAccessKeyMap(this);
744 m_accessKeyMapValid = true;
746 return m_elementsByAccessKey.get(key.impl());
749 void Document::buildAccessKeyMap(TreeScope* scope)
752 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
753 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
754 if (!accessKey.isEmpty())
755 m_elementsByAccessKey.set(accessKey.impl(), &element);
757 if (ShadowRoot* root = element.shadowRoot())
758 buildAccessKeyMap(root);
762 void Document::invalidateAccessKeyMap()
764 m_accessKeyMapValid = false;
765 m_elementsByAccessKey.clear();
768 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
770 return m_imagesByUsemap.add(name, element, *this);
773 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
775 return m_imagesByUsemap.remove(name, element);
778 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
780 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
783 SelectorQuery* Document::selectorQueryForString(const String& selectorString, ExceptionCode& ec)
785 if (selectorString.isEmpty()) {
790 if (!m_selectorQueryCache)
791 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
792 return m_selectorQueryCache->add(selectorString, *this, ec);
795 void Document::clearSelectorQueryCache()
797 m_selectorQueryCache = nullptr;
800 MediaQueryMatcher& Document::mediaQueryMatcher()
802 if (!m_mediaQueryMatcher)
803 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
804 return *m_mediaQueryMatcher;
807 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
809 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
811 bool wasInQuirksMode = inQuirksMode();
812 m_compatibilityMode = mode;
814 clearSelectorQueryCache();
816 if (inQuirksMode() != wasInQuirksMode) {
817 // All user stylesheets have to reparse using the different mode.
818 extensionStyleSheets().clearPageUserSheet();
819 extensionStyleSheets().invalidateInjectedStyleSheetCache();
823 String Document::compatMode() const
825 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
828 void Document::resetLinkColor()
830 m_linkColor = Color(0, 0, 238);
833 void Document::resetVisitedLinkColor()
835 m_visitedLinkColor = Color(85, 26, 139);
838 void Document::resetActiveLinkColor()
840 m_activeLinkColor.setNamedColor("red");
843 DOMImplementation& Document::implementation()
845 if (!m_implementation)
846 m_implementation = std::make_unique<DOMImplementation>(*this);
847 return *m_implementation;
850 bool Document::hasManifest() const
852 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->fastHasAttribute(manifestAttr);
855 DocumentType* Document::doctype() const
857 for (Node* node = firstChild(); node; node = node->nextSibling()) {
858 if (node->isDocumentTypeNode())
859 return static_cast<DocumentType*>(node);
864 void Document::childrenChanged(const ChildChange& change)
866 ContainerNode::childrenChanged(change);
869 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
870 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
871 // otherwise, we need to detect the doc type changes before updating the viewport.
872 if (Page* page = this->page())
873 page->chrome().didReceiveDocType(frame());
876 Element* newDocumentElement = childrenOfType<Element>(*this).first();
877 if (newDocumentElement == m_documentElement)
879 m_documentElement = newDocumentElement;
880 // The root style used for media query matching depends on the document element.
881 clearStyleResolver();
884 static RefPtr<Element> createHTMLElementWithNameValidation(Document& document, const QualifiedName qualifiedName, ExceptionCode& ec)
886 RefPtr<HTMLElement> element = HTMLElementFactory::createKnownElement(qualifiedName, document);
890 #if ENABLE(CUSTOM_ELEMENTS)
891 auto* definitions = document.customElementDefinitions();
892 if (UNLIKELY(definitions)) {
893 if (auto* interface = definitions->findInterface(qualifiedName))
894 return interface->constructElement(qualifiedName.localName());
898 if (UNLIKELY(!Document::isValidName(qualifiedName.localName()))) {
899 ec = INVALID_CHARACTER_ERR;
903 return HTMLUnknownElement::create(qualifiedName, document);
906 RefPtr<Element> Document::createElementForBindings(const AtomicString& name, ExceptionCode& ec)
908 if (isHTMLDocument())
909 return createHTMLElementWithNameValidation(*this, QualifiedName(nullAtom, name.convertToASCIILowercase(), xhtmlNamespaceURI), ec);
911 if (isXHTMLDocument())
912 return createHTMLElementWithNameValidation(*this, QualifiedName(nullAtom, name, xhtmlNamespaceURI), ec);
914 if (!isValidName(name)) {
915 ec = INVALID_CHARACTER_ERR;
919 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
922 Ref<DocumentFragment> Document::createDocumentFragment()
924 return DocumentFragment::create(document());
927 Ref<Text> Document::createTextNode(const String& data)
929 return Text::create(*this, data);
932 Ref<Comment> Document::createComment(const String& data)
934 return Comment::create(*this, data);
937 RefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
939 if (isHTMLDocument()) {
940 ec = NOT_SUPPORTED_ERR;
943 return CDATASection::create(*this, data);
946 RefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
948 if (!isValidName(target)) {
949 ec = INVALID_CHARACTER_ERR;
953 if (data.contains("?>")) {
954 ec = INVALID_CHARACTER_ERR;
958 return ProcessingInstruction::create(*this, target, data);
961 RefPtr<EntityReference> Document::createEntityReference(const String&, ExceptionCode& ec)
963 ec = NOT_SUPPORTED_ERR;
967 Ref<Text> Document::createEditingTextNode(const String& text)
969 return Text::createEditingText(*this, text);
972 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
974 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
975 return *propertySet->ensureCSSStyleDeclaration();
978 RefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
981 ec = NOT_SUPPORTED_ERR;
985 switch (importedNode->nodeType()) {
988 case CDATA_SECTION_NODE:
989 case PROCESSING_INSTRUCTION_NODE:
991 case DOCUMENT_FRAGMENT_NODE:
992 return importedNode->cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
995 // FIXME: This will "Attr::normalize" child nodes of Attr.
996 return Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(*importedNode).name(), nullAtom), downcast<Attr>(*importedNode).value());
998 case DOCUMENT_NODE: // Can't import a document into another document.
999 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
1003 ec = NOT_SUPPORTED_ERR;
1008 RefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1011 ec = NOT_SUPPORTED_ERR;
1015 EventQueueScope scope;
1017 switch (source->nodeType()) {
1019 ec = NOT_SUPPORTED_ERR;
1021 case ATTRIBUTE_NODE: {
1022 Attr& attr = downcast<Attr>(*source);
1023 if (attr.ownerElement())
1024 attr.ownerElement()->removeAttributeNode(&attr, ec);
1028 if (source->isShadowRoot()) {
1029 // ShadowRoot cannot disconnect itself from the host node.
1030 ec = HIERARCHY_REQUEST_ERR;
1033 if (is<HTMLFrameOwnerElement>(*source)) {
1034 HTMLFrameOwnerElement& frameOwnerElement = downcast<HTMLFrameOwnerElement>(*source);
1035 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1036 ec = HIERARCHY_REQUEST_ERR;
1040 if (source->parentNode()) {
1041 source->parentNode()->removeChild(*source, ec);
1047 adoptIfNeeded(source.get());
1052 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1054 // These checks are from DOM Core Level 2, createElementNS
1055 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1056 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1058 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1061 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1062 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1063 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1064 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1065 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1066 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1069 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1071 return hasValidNamespaceForElements(qName);
1074 // FIXME: This should really be in a possible ElementFactory class.
1075 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1077 RefPtr<Element> element;
1079 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1080 if (name.namespaceURI() == xhtmlNamespaceURI)
1081 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1082 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1083 element = SVGElementFactory::createElement(name, *this, createdByParser);
1085 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1086 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1090 m_sawElementsInKnownNamespaces = true;
1092 element = Element::create(name, document());
1094 // <image> uses imgTag so we need a special rule.
1095 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1097 return element.releaseNonNull();
1100 bool Document::cssRegionsEnabled() const
1102 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1105 bool Document::cssCompositingEnabled() const
1107 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1110 #if ENABLE(CSS_REGIONS)
1112 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1114 if (!cssRegionsEnabled() || !renderView())
1117 updateStyleIfNeeded();
1119 return namedFlows().createCSSOMSnapshot();
1124 NamedFlowCollection& Document::namedFlows()
1127 m_namedFlows = NamedFlowCollection::create(this);
1129 return *m_namedFlows;
1132 RefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1134 String prefix, localName;
1135 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1138 QualifiedName qName(prefix, localName, namespaceURI);
1139 if (!hasValidNamespaceForElements(qName)) {
1144 return createElement(qName, false);
1147 String Document::readyState() const
1149 static NeverDestroyed<const String> loading(ASCIILiteral("loading"));
1150 static NeverDestroyed<const String> interactive(ASCIILiteral("interactive"));
1151 static NeverDestroyed<const String> complete(ASCIILiteral("complete"));
1153 switch (m_readyState) {
1162 ASSERT_NOT_REACHED();
1166 void Document::setReadyState(ReadyState readyState)
1168 if (readyState == m_readyState)
1171 #if ENABLE(WEB_TIMING)
1172 switch (readyState) {
1174 if (!m_documentTiming.domLoading)
1175 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1178 if (!m_documentTiming.domInteractive)
1179 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1182 if (!m_documentTiming.domComplete)
1183 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1188 m_readyState = readyState;
1189 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1191 if (settings() && settings()->suppressesIncrementalRendering())
1192 setVisualUpdatesAllowed(readyState);
1195 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1197 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1198 switch (readyState) {
1200 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1201 ASSERT(m_visualUpdatesAllowed);
1202 setVisualUpdatesAllowed(false);
1205 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1208 if (m_visualUpdatesSuppressionTimer.isActive()) {
1209 ASSERT(!m_visualUpdatesAllowed);
1211 if (!view()->visualUpdatesAllowedByClient())
1214 setVisualUpdatesAllowed(true);
1216 ASSERT(m_visualUpdatesAllowed);
1221 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1223 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1226 m_visualUpdatesAllowed = visualUpdatesAllowed;
1228 if (visualUpdatesAllowed)
1229 m_visualUpdatesSuppressionTimer.stop();
1231 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1233 if (!visualUpdatesAllowed)
1236 FrameView* frameView = view();
1237 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1241 if (Page* page = this->page()) {
1242 if (frame()->isMainFrame()) {
1243 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1244 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1245 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1250 view()->updateCompositingLayersAfterLayout();
1252 if (RenderView* renderView = this->renderView())
1253 renderView->repaintViewAndCompositedLayers();
1255 if (Frame* frame = this->frame())
1256 frame->loader().forcePageTransitionIfNeeded();
1259 void Document::visualUpdatesSuppressionTimerFired()
1261 ASSERT(!m_visualUpdatesAllowed);
1263 // If the client is extending the visual update suppression period explicitly, the
1264 // watchdog should not re-enable visual updates itself, but should wait for the client.
1265 if (!view()->visualUpdatesAllowedByClient())
1268 setVisualUpdatesAllowed(true);
1271 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1273 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1274 // both of which we can determine by looking at the timer.
1276 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1277 setVisualUpdatesAllowed(true);
1280 String Document::characterSetWithUTF8Fallback() const
1282 AtomicString name = encoding();
1285 return UTF8Encoding().domName();
1288 String Document::defaultCharset() const
1290 if (Settings* settings = this->settings())
1291 return settings->defaultTextEncodingName();
1295 void Document::setCharset(const String& charset)
1299 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1302 void Document::setContentLanguage(const String& language)
1304 if (m_contentLanguage == language)
1306 m_contentLanguage = language;
1308 // Recalculate style so language is used when selecting the initial font.
1309 styleResolverChanged(DeferRecalcStyle);
1312 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1314 if (!implementation().hasFeature("XML", String())) {
1315 ec = NOT_SUPPORTED_ERR;
1319 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1320 ec = NOT_SUPPORTED_ERR;
1324 m_xmlVersion = version;
1327 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1329 if (!implementation().hasFeature("XML", String())) {
1330 ec = NOT_SUPPORTED_ERR;
1334 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1337 void Document::setDocumentURI(const String& uri)
1339 // This property is read-only from JavaScript, but writable from Objective-C.
1340 m_documentURI = uri;
1344 void Document::setContent(const String& content)
1347 // FIXME: This should probably use insert(), but that's (intentionally)
1348 // not implemented for the XML parser as it's normally synonymous with
1349 // document.write(). append() will end up yielding, but close() will
1350 // pump the tokenizer syncrhonously and finish the parse.
1351 m_parser->append(content.impl());
1355 String Document::suggestedMIMEType() const
1357 if (isXHTMLDocument())
1358 return ASCIILiteral("application/xhtml+xml");
1359 if (isSVGDocument())
1360 return ASCIILiteral("image/svg+xml");
1361 if (xmlStandalone())
1362 return ASCIILiteral("text/xml");
1363 if (isHTMLDocument())
1364 return ASCIILiteral("text/html");
1365 if (DocumentLoader* loader = this->loader())
1366 return loader->responseMIMEType();
1370 void Document::overrideMIMEType(const String& mimeType)
1372 m_overriddenMIMEType = mimeType;
1375 String Document::contentType() const
1377 if (!m_overriddenMIMEType.isNull())
1378 return m_overriddenMIMEType;
1380 if (DocumentLoader* documentLoader = loader())
1381 return documentLoader->currentContentType();
1383 String mimeType = suggestedMIMEType();
1384 if (!mimeType.isNull())
1387 return ASCIILiteral("application/xml");
1390 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1392 if (!frame() || !view())
1395 Frame& frame = *this->frame();
1397 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1399 LayoutPoint contentsPoint = clientPoint;
1400 contentsPoint.scale(scaleFactor, scaleFactor);
1401 contentsPoint.moveBy(view()->contentsScrollPosition());
1403 LayoutRect visibleRect;
1405 visibleRect = view()->unobscuredContentRect();
1407 visibleRect = view()->visibleContentRect();
1409 if (!visibleRect.contains(contentsPoint))
1412 HitTestResult result(contentsPoint);
1413 renderView()->hitTest(HitTestRequest(), result);
1416 *localPoint = result.localPoint();
1418 return result.innerNode();
1421 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1423 if (!hasLivingRenderTree())
1426 Node* node = nodeFromPoint(clientPoint);
1427 while (node && !is<Element>(*node))
1428 node = node->parentNode();
1431 node = ancestorInThisScope(node);
1433 return downcast<Element>(node);
1436 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1438 return caretRangeFromPoint(LayoutPoint(x, y));
1441 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1443 if (!hasLivingRenderTree())
1446 LayoutPoint localPoint;
1447 Node* node = nodeFromPoint(clientPoint, &localPoint);
1451 Node* shadowAncestorNode = ancestorInThisScope(node);
1452 if (shadowAncestorNode != node) {
1453 unsigned offset = shadowAncestorNode->computeNodeIndex();
1454 ContainerNode* container = shadowAncestorNode->parentNode();
1455 return Range::create(*this, container, offset, container, offset);
1458 RenderObject* renderer = node->renderer();
1461 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1462 if (visiblePosition.isNull())
1465 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1466 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1469 Element* Document::scrollingElement()
1471 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1472 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1478 * Performs three operations:
1479 * 1. Convert control characters to spaces
1480 * 2. Trim leading and trailing spaces
1481 * 3. Collapse internal whitespace.
1483 template <typename CharacterType>
1484 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1486 const String& title = titleWithDirection.string();
1487 const CharacterType* characters = title.characters<CharacterType>();
1488 unsigned length = title.length();
1491 StringBuffer<CharacterType> buffer(length);
1492 unsigned builderIndex = 0;
1494 // Skip leading spaces and leading characters that would convert to spaces
1495 for (i = 0; i < length; ++i) {
1496 CharacterType c = characters[i];
1497 if (!(c <= 0x20 || c == 0x7F))
1502 return StringWithDirection();
1504 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1505 bool previousCharWasWS = false;
1506 for (; i < length; ++i) {
1507 CharacterType c = characters[i];
1508 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1509 if (previousCharWasWS)
1511 buffer[builderIndex++] = ' ';
1512 previousCharWasWS = true;
1514 buffer[builderIndex++] = c;
1515 previousCharWasWS = false;
1519 // Strip trailing spaces
1520 while (builderIndex > 0) {
1522 if (buffer[builderIndex] != ' ')
1526 if (!builderIndex && buffer[builderIndex] == ' ')
1527 return StringWithDirection();
1529 buffer.shrink(builderIndex + 1);
1531 // Replace the backslashes with currency symbols if the encoding requires it.
1532 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1534 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1537 void Document::updateTitle(const StringWithDirection& title)
1539 if (m_rawTitle == title)
1544 if (m_rawTitle.string().isEmpty())
1545 m_title = StringWithDirection();
1547 if (m_rawTitle.string().is8Bit())
1548 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1550 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1552 if (DocumentLoader* loader = this->loader())
1553 loader->setTitle(m_title);
1556 void Document::updateTitleFromTitleElement()
1558 if (!m_titleElement) {
1559 updateTitle(StringWithDirection());
1563 if (is<HTMLTitleElement>(*m_titleElement))
1564 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1565 else if (is<SVGTitleElement>(*m_titleElement)) {
1566 // FIXME: does SVG have a title text direction?
1567 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1571 void Document::setTitle(const String& title)
1573 if (!isHTMLDocument() && !isXHTMLDocument())
1574 m_titleElement = nullptr;
1575 else if (!m_titleElement) {
1576 auto* headElement = head();
1579 m_titleElement = createElement(titleTag, false);
1580 headElement->appendChild(*m_titleElement, ASSERT_NO_EXCEPTION);
1583 // The DOM API has no method of specifying direction, so assume LTR.
1584 updateTitle(StringWithDirection(title, LTR));
1586 if (is<HTMLTitleElement>(m_titleElement.get()))
1587 downcast<HTMLTitleElement>(*m_titleElement).setText(title);
1590 void Document::updateTitleElement(Element* newTitleElement)
1592 // Only allow the first title element in tree order to change the title -- others have no effect.
1593 if (m_titleElement) {
1594 if (isHTMLDocument() || isXHTMLDocument())
1595 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1596 else if (isSVGDocument())
1597 m_titleElement = descendantsOfType<SVGTitleElement>(*this).first();
1599 m_titleElement = newTitleElement;
1601 updateTitleFromTitleElement();
1604 void Document::titleElementAdded(Element& titleElement)
1606 if (m_titleElement == &titleElement)
1609 updateTitleElement(&titleElement);
1612 void Document::titleElementRemoved(Element& titleElement)
1614 if (m_titleElement != &titleElement)
1617 updateTitleElement(nullptr);
1620 void Document::titleElementTextChanged(Element& titleElement)
1622 if (m_titleElement != &titleElement)
1625 updateTitleFromTitleElement();
1628 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1630 m_visibilityStateCallbackElements.add(element);
1633 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1635 m_visibilityStateCallbackElements.remove(element);
1638 void Document::visibilityStateChanged()
1640 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1641 for (auto* element : m_visibilityStateCallbackElements)
1642 element->visibilityStateChanged();
1645 PageVisibilityState Document::pageVisibilityState() const
1647 // The visibility of the document is inherited from the visibility of the
1648 // page. If there is no page associated with the document, we will assume
1649 // that the page is hidden, as specified by the spec:
1650 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1651 if (!m_frame || !m_frame->page())
1652 return PageVisibilityStateHidden;
1653 return m_frame->page()->visibilityState();
1656 String Document::visibilityState() const
1658 return pageVisibilityStateString(pageVisibilityState());
1661 bool Document::hidden() const
1663 return pageVisibilityState() != PageVisibilityStateVisible;
1668 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1670 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1673 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1675 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1678 void Document::allowsMediaDocumentInlinePlaybackChanged()
1680 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1681 element->allowsMediaDocumentInlinePlaybackChanged();
1685 #if ENABLE(CSP_NEXT)
1686 DOMSecurityPolicy& Document::securityPolicy()
1688 if (!m_domSecurityPolicy)
1689 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1690 return *m_domSecurityPolicy;
1694 String Document::nodeName() const
1699 Node::NodeType Document::nodeType() const
1701 return DOCUMENT_NODE;
1704 FormController& Document::formController()
1706 if (!m_formController)
1707 m_formController = std::make_unique<FormController>();
1708 return *m_formController;
1711 Vector<String> Document::formElementsState() const
1713 if (!m_formController)
1714 return Vector<String>();
1715 return m_formController->formElementsState();
1718 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1720 if (!stateVector.size() && !m_formController)
1722 formController().setStateForNewFormElements(stateVector);
1725 FrameView* Document::view() const
1727 return m_frame ? m_frame->view() : nullptr;
1730 Page* Document::page() const
1732 return m_frame ? m_frame->page() : nullptr;
1735 Settings* Document::settings() const
1737 return m_frame ? &m_frame->settings() : nullptr;
1740 Ref<Range> Document::createRange()
1742 return Range::create(*this);
1745 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1747 return createNodeIterator(root, whatToShow, WTFMove(filter), ec);
1750 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1756 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1759 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1761 return createNodeIterator(root, whatToShow, nullptr, ec);
1764 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionCode& ec)
1766 return createNodeIterator(root, 0xFFFFFFFF, nullptr, ec);
1769 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1771 return createTreeWalker(root, whatToShow, WTFMove(filter), ec);
1774 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1780 return TreeWalker::create(*root, whatToShow, WTFMove(filter));
1783 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1785 return createTreeWalker(root, whatToShow, nullptr, ec);
1788 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionCode& ec)
1790 return createTreeWalker(root, 0xFFFFFFFF, nullptr, ec);
1793 void Document::scheduleForcedStyleRecalc()
1795 m_pendingStyleRecalcShouldForce = true;
1796 scheduleStyleRecalc();
1799 void Document::scheduleStyleRecalc()
1801 if (m_styleRecalcTimer.isActive() || inPageCache())
1804 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1806 // FIXME: Why on earth is this here? This is clearly misplaced.
1807 invalidateAccessKeyMap();
1809 m_styleRecalcTimer.startOneShot(0);
1811 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1814 void Document::unscheduleStyleRecalc()
1816 ASSERT(!childNeedsStyleRecalc());
1818 m_styleRecalcTimer.stop();
1819 m_pendingStyleRecalcShouldForce = false;
1822 bool Document::hasPendingStyleRecalc() const
1824 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1827 bool Document::hasPendingForcedStyleRecalc() const
1829 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1832 void Document::recalcStyle(Style::Change change)
1834 ASSERT(!view() || !view()->isPainting());
1836 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1840 FrameView& frameView = m_renderView->frameView();
1841 Ref<FrameView> protect(frameView);
1842 if (frameView.isPainting())
1845 if (m_inStyleRecalc)
1846 return; // Guard against re-entrancy. -dwh
1848 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1850 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1851 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1853 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1854 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1855 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1856 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1857 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1858 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1860 authorStyleSheets().flushPendingUpdates();
1862 frameView.willRecalcStyle();
1864 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1866 // FIXME: We never reset this flags.
1867 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1868 authorStyleSheets().setUsesRemUnit(true);
1869 // We don't call setUsesStyleBasedEditability here because the whole point of the flag is to avoid style recalc.
1870 // i.e. updating the flag here would be too late.
1872 m_inStyleRecalc = true;
1873 bool updatedCompositingLayers = false;
1875 Style::PostResolutionCallbackDisabler disabler(*this);
1876 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1878 if (m_pendingStyleRecalcShouldForce)
1879 change = Style::Force;
1881 if (change == Style::Force) {
1882 // This may get set again during style resolve.
1883 m_hasNodesWithPlaceholderStyle = false;
1885 auto documentStyle = Style::resolveForDocument(*this);
1887 // Inserting the pictograph font at the end of the font fallback list is done by the
1888 // font selector, so set a font selector if needed.
1889 if (Settings* settings = this->settings()) {
1890 if (settings->fontFallbackPrefersPictographs())
1891 documentStyle.get().fontCascade().update(&fontSelector());
1894 auto documentChange = Style::determineChange(documentStyle.get(), m_renderView->style());
1895 if (documentChange != Style::NoChange)
1896 renderView()->setStyle(WTFMove(documentStyle));
1899 Style::TreeResolver resolver(*this);
1900 resolver.resolve(change);
1902 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1904 clearNeedsStyleRecalc();
1905 clearChildNeedsStyleRecalc();
1906 unscheduleStyleRecalc();
1908 m_inStyleRecalc = false;
1911 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1912 if (m_closeAfterStyleRecalc) {
1913 m_closeAfterStyleRecalc = false;
1917 ++m_styleRecalcCount;
1919 InspectorInstrumentation::didRecalculateStyle(cookie);
1921 // Some animated images may now be inside the viewport due to style recalc,
1922 // resume them if necessary if there is no layout pending. Otherwise, we'll
1923 // check if they need to be resumed after layout.
1924 if (updatedCompositingLayers && !frameView.needsLayout())
1925 frameView.viewportContentsChanged();
1927 if (!frameView.needsLayout())
1928 frameView.frame().selection().updateAppearanceAfterLayout();
1930 // As a result of the style recalculation, the currently hovered element might have been
1931 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1932 // to check if any other elements ended up under the mouse pointer due to re-layout.
1933 if (m_hoveredElement && !m_hoveredElement->renderer())
1934 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1937 void Document::updateStyleIfNeeded()
1939 ASSERT(isMainThread());
1940 ASSERT(!view() || !view()->isPainting());
1942 if (!view() || view()->isInLayout())
1945 if (m_optimizedStyleSheetUpdateTimer.isActive())
1946 styleResolverChanged(RecalcStyleIfNeeded);
1948 if (!needsStyleRecalc())
1951 recalcStyle(Style::NoChange);
1954 void Document::updateLayout()
1956 ASSERT(isMainThread());
1958 FrameView* frameView = view();
1959 if (frameView && frameView->isInLayout()) {
1960 // View layout should not be re-entrant.
1961 ASSERT_NOT_REACHED();
1965 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1967 if (HTMLFrameOwnerElement* owner = ownerElement())
1968 owner->document().updateLayout();
1970 updateStyleIfNeeded();
1972 StackStats::LayoutCheckPoint layoutCheckPoint;
1974 // Only do a layout if changes have occurred that make it necessary.
1975 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1976 frameView->layout();
1979 // FIXME: This is a bad idea and needs to be removed eventually.
1980 // Other browsers load stylesheets before they continue parsing the web page.
1981 // Since we don't, we can run JavaScript code that needs answers before the
1982 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1983 // lets us get reasonable answers. The long term solution to this problem is
1984 // to instead suspend JavaScript execution.
1985 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1987 bool oldIgnore = m_ignorePendingStylesheets;
1989 if (!haveStylesheetsLoaded()) {
1990 m_ignorePendingStylesheets = true;
1991 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1992 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1993 // with accurate style information. (Our suppression involves blanking the whole page at the
1994 // moment. If it were more refined, we might be able to do something better.)
1995 // It's worth noting though that this entire method is a hack, since what we really want to do is
1996 // suspend JS instead of doing a layout with inaccurate information.
1997 HTMLElement* bodyElement = bodyOrFrameset();
1998 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1999 m_pendingSheetLayout = DidLayoutWithPendingSheets;
2000 styleResolverChanged(RecalcStyleImmediately);
2001 } else if (m_hasNodesWithPlaceholderStyle)
2002 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
2003 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
2004 // but here we need up-to-date style immediately.
2005 recalcStyle(Style::Force);
2010 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
2011 view()->flushAnyPendingPostLayoutTasks();
2013 m_ignorePendingStylesheets = oldIgnore;
2016 Ref<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, RenderStyle* parentStyle)
2018 ASSERT(&element.document() == this);
2020 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
2021 ResourceLoadSuspender suspender;
2023 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
2024 return element.resolveStyle(parentStyle);
2027 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2029 ASSERT(isMainThread());
2031 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2032 if (!haveStylesheetsLoaded()) {
2033 updateLayoutIgnorePendingStylesheets();
2037 // Check for re-entrancy and assert (same code that is in updateLayout()).
2038 FrameView* frameView = view();
2039 if (frameView && frameView->isInLayout()) {
2040 // View layout should not be re-entrant.
2041 ASSERT_NOT_REACHED();
2045 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2047 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2049 bool requireFullLayout = false;
2050 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2051 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2052 requireFullLayout = true;
2055 updateStyleIfNeeded();
2057 RenderObject* renderer = element.renderer();
2058 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2059 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2060 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2061 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2062 requireFullLayout = true;
2065 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2066 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2067 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2068 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2070 if (!requireFullLayout) {
2071 RenderBox* previousBox = nullptr;
2072 RenderBox* currentBox = nullptr;
2074 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2075 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2077 // Require the entire container chain to be boxes.
2078 if (!is<RenderBox>(currRenderer)) {
2079 requireFullLayout = true;
2083 previousBox = currentBox;
2084 currentBox = downcast<RenderBox>(currRenderer);
2086 // If a box needs layout for itself or if a box has changed children and sizes its width to
2087 // its content, then require a full layout.
2088 if (currentBox->selfNeedsLayout() ||
2089 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2090 requireFullLayout = true;
2094 // If a block contains floats and the child's height isn't specified, then
2095 // give up also, since our height could end up being influenced by the floats.
2096 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2097 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2098 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2099 requireFullLayout = true;
2104 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2105 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2106 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2107 // Disallow regions/columns from having the optimization.
2108 // Give up if the writing mode changes at all in the containing block chain.
2109 requireFullLayout = true;
2113 if (currRenderer == frameView->layoutRoot())
2118 StackStats::LayoutCheckPoint layoutCheckPoint;
2120 // Only do a layout if changes have occurred that make it necessary.
2121 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2122 frameView->layout();
2124 return requireFullLayout;
2127 bool Document::isPageBoxVisible(int pageIndex)
2129 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
2130 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2133 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2135 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
2137 int width = pageSize.width();
2138 int height = pageSize.height();
2139 switch (style->pageSizeType()) {
2140 case PAGE_SIZE_AUTO:
2142 case PAGE_SIZE_AUTO_LANDSCAPE:
2144 std::swap(width, height);
2146 case PAGE_SIZE_AUTO_PORTRAIT:
2148 std::swap(width, height);
2150 case PAGE_SIZE_RESOLVED: {
2151 LengthSize size = style->pageSize();
2152 ASSERT(size.width().isFixed());
2153 ASSERT(size.height().isFixed());
2154 width = valueForLength(size.width(), 0);
2155 height = valueForLength(size.height(), 0);
2159 ASSERT_NOT_REACHED();
2161 pageSize = IntSize(width, height);
2163 // The percentage is calculated with respect to the width even for margin top and bottom.
2164 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2165 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2166 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2167 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2168 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2171 void Document::createStyleResolver()
2173 m_styleResolver = std::make_unique<StyleResolver>(*this);
2174 m_styleResolver->appendAuthorStyleSheets(authorStyleSheets().activeStyleSheets());
2177 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2179 if (!m_userAgentShadowTreeStyleResolver) {
2180 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2182 // FIXME: Filter out shadow pseudo elements we don't want to expose to authors.
2183 auto& documentAuthorStyle = *ensureStyleResolver().ruleSets().authorStyle();
2184 if (documentAuthorStyle.hasShadowPseudoElementRules())
2185 m_userAgentShadowTreeStyleResolver->ruleSets().authorStyle()->copyShadowPseudoElementRulesFrom(documentAuthorStyle);
2188 return *m_userAgentShadowTreeStyleResolver;
2191 void Document::fontsNeedUpdate(FontSelector&)
2193 if (m_styleResolver)
2194 m_styleResolver->invalidateMatchedPropertiesCache();
2195 if (inPageCache() || !renderView())
2197 scheduleForcedStyleRecalc();
2200 CSSFontSelector& Document::fontSelector()
2202 if (!m_fontSelector) {
2203 m_fontSelector = CSSFontSelector::create(*this);
2204 m_fontSelector->registerForInvalidationCallbacks(*this);
2206 return *m_fontSelector;
2209 void Document::clearStyleResolver()
2211 m_styleResolver = nullptr;
2212 m_userAgentShadowTreeStyleResolver = nullptr;
2214 // FIXME: It would be better if the FontSelector could survive this operation.
2215 if (m_fontSelector) {
2216 m_fontSelector->clearDocument();
2217 m_fontSelector->unregisterForInvalidationCallbacks(*this);
2218 m_fontSelector = nullptr;
2222 void Document::createRenderTree()
2224 ASSERT(!renderView());
2225 ASSERT(!m_inPageCache);
2226 ASSERT(!m_axObjectCache || this != &topDocument());
2228 if (m_isNonRenderedPlaceholder)
2231 // FIXME: It would be better if we could pass the resolved document style directly here.
2232 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2233 Node::setRenderer(m_renderView.get());
2235 renderView()->setIsInWindow(true);
2237 recalcStyle(Style::Force);
2240 void Document::didBecomeCurrentDocumentInFrame()
2242 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2243 // If so, then m_frame could become 0, and we need to do something about that.
2245 m_frame->script().updateDocument();
2247 if (!hasLivingRenderTree())
2250 updateViewportArguments();
2252 // FIXME: Doing this only for the main frame is insufficient.
2253 // Changing a subframe can also change the wheel event handler count.
2254 // FIXME: Doing this only when a document goes into the frame is insufficient.
2255 // Removing a document can also change the wheel event handler count.
2256 // FIXME: Doing this every time is a waste. If the current document and its
2257 // subframes' documents have no wheel event handlers, then the count did not change,
2258 // unless the documents they are replacing had wheel event handlers.
2259 if (page() && m_frame->isMainFrame())
2260 wheelEventHandlersChanged();
2262 #if ENABLE(TOUCH_EVENTS)
2263 // FIXME: Doing this only for the main frame is insufficient.
2264 // A subframe could have touch event handlers.
2265 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2266 page()->chrome().client().needTouchEvents(true);
2269 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2270 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2271 // page cache, or simply newly created).
2272 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2273 m_frame->animation().suspendAnimationsForDocument(this);
2274 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2276 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2277 m_frame->animation().resumeAnimationsForDocument(this);
2281 void Document::disconnectFromFrame()
2286 void Document::destroyRenderTree()
2288 ASSERT(hasLivingRenderTree());
2289 ASSERT(!m_inPageCache);
2291 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2293 if (this == &topDocument())
2294 clearAXObjectCache();
2296 documentWillBecomeInactive();
2298 if (FrameView* frameView = view())
2299 frameView->detachCustomScrollbars();
2301 #if ENABLE(FULLSCREEN_API)
2302 if (m_fullScreenRenderer)
2303 setFullScreenRenderer(nullptr);
2306 m_hoveredElement = nullptr;
2307 m_focusedElement = nullptr;
2308 m_activeElement = nullptr;
2310 if (m_documentElement)
2311 Style::detachRenderTree(*m_documentElement);
2313 clearChildNeedsStyleRecalc();
2315 unscheduleStyleRecalc();
2317 m_renderView = nullptr;
2318 Node::setRenderer(nullptr);
2320 #if ENABLE(IOS_TEXT_AUTOSIZING)
2321 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2322 m_textAutoSizedNodes.clear();
2326 void Document::prepareForDestruction()
2328 if (m_hasPreparedForDestruction)
2331 #if ENABLE(IOS_TOUCH_EVENTS)
2332 clearTouchEventListeners();
2335 #if HAVE(ACCESSIBILITY)
2336 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2337 if (this != &topDocument()) {
2338 if (AXObjectCache* cache = existingAXObjectCache())
2339 cache->clearTextMarkerNodesInUse(this);
2343 disconnectDescendantFrames();
2344 if (m_domWindow && m_frame)
2345 m_domWindow->willDetachDocumentFromFrame();
2347 if (hasLivingRenderTree())
2348 destroyRenderTree();
2350 if (is<PluginDocument>(*this))
2351 downcast<PluginDocument>(*this).detachFromPluginElement();
2353 #if ENABLE(POINTER_LOCK)
2355 page()->pointerLockController().documentDetached(this);
2358 InspectorInstrumentation::documentDetached(*this);
2360 stopActiveDOMObjects();
2361 m_eventQueue.close();
2362 #if ENABLE(FULLSCREEN_API)
2363 m_fullScreenChangeEventTargetQueue.clear();
2364 m_fullScreenErrorEventTargetQueue.clear();
2369 #if ENABLE(TOUCH_EVENTS)
2370 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2371 parentDocument()->didRemoveEventTargetNode(*this);
2374 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2375 parentDocument()->didRemoveEventTargetNode(*this);
2377 if (m_mediaQueryMatcher)
2378 m_mediaQueryMatcher->documentDestroyed();
2380 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2381 if (!m_clientToIDMap.isEmpty() && page()) {
2382 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2383 copyKeysToVector(m_clientToIDMap, clients);
2384 for (auto* client : clients)
2385 removePlaybackTargetPickerClient(*client);
2389 disconnectFromFrame();
2391 m_hasPreparedForDestruction = true;
2394 void Document::removeAllEventListeners()
2396 EventTarget::removeAllEventListeners();
2399 m_domWindow->removeAllEventListeners();
2400 #if ENABLE(IOS_TOUCH_EVENTS)
2401 clearTouchEventListeners();
2403 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2404 node->removeAllEventListeners();
2407 void Document::suspendDeviceMotionAndOrientationUpdates()
2409 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2411 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2412 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2413 if (m_deviceMotionController)
2414 m_deviceMotionController->suspendUpdates();
2415 if (m_deviceOrientationController)
2416 m_deviceOrientationController->suspendUpdates();
2420 void Document::resumeDeviceMotionAndOrientationUpdates()
2422 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2424 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2425 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2426 if (m_deviceMotionController)
2427 m_deviceMotionController->resumeUpdates();
2428 if (m_deviceOrientationController)
2429 m_deviceOrientationController->resumeUpdates();
2433 void Document::platformSuspendOrStopActiveDOMObjects()
2436 if (WebThreadCountOfObservedContentModifiers() > 0) {
2437 Frame* frame = this->frame();
2438 if (Page* page = frame ? frame->page() : nullptr)
2439 page->chrome().client().clearContentChangeObservers(frame);
2444 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2446 ScriptExecutionContext::suspendActiveDOMObjects(why);
2447 suspendDeviceMotionAndOrientationUpdates();
2448 platformSuspendOrStopActiveDOMObjects();
2451 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2453 ScriptExecutionContext::resumeActiveDOMObjects(why);
2454 resumeDeviceMotionAndOrientationUpdates();
2455 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2458 void Document::stopActiveDOMObjects()
2460 ScriptExecutionContext::stopActiveDOMObjects();
2461 platformSuspendOrStopActiveDOMObjects();
2464 void Document::clearAXObjectCache()
2466 ASSERT(&topDocument() == this);
2467 // Clear the cache member variable before calling delete because attempts
2468 // are made to access it during destruction.
2469 m_axObjectCache = nullptr;
2472 AXObjectCache* Document::existingAXObjectCache() const
2474 Document& topDocument = this->topDocument();
2475 if (!topDocument.hasLivingRenderTree())
2477 return topDocument.m_axObjectCache.get();
2480 AXObjectCache* Document::axObjectCache() const
2482 if (!AXObjectCache::accessibilityEnabled())
2485 // The only document that actually has a AXObjectCache is the top-level
2486 // document. This is because we need to be able to get from any WebCoreAXObject
2487 // to any other WebCoreAXObject on the same page. Using a single cache allows
2488 // lookups across nested webareas (i.e. multiple documents).
2489 Document& topDocument = this->topDocument();
2491 // If the document has already been detached, do not make a new axObjectCache.
2492 if (!topDocument.hasLivingRenderTree())
2495 ASSERT(&topDocument == this || !m_axObjectCache);
2496 if (!topDocument.m_axObjectCache)
2497 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2498 return topDocument.m_axObjectCache.get();
2501 void Document::setVisuallyOrdered()
2503 m_visuallyOrdered = true;
2505 renderView()->style().setRTLOrdering(VisualOrder);
2508 Ref<DocumentParser> Document::createParser()
2510 // FIXME: this should probably pass the frame instead
2511 return XMLDocumentParser::create(*this, view());
2514 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2516 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2519 void Document::open(Document* ownerDocument)
2521 if (m_ignoreOpensDuringUnloadCount)
2524 if (ownerDocument) {
2525 setURL(ownerDocument->url());
2526 setCookieURL(ownerDocument->cookieURL());
2527 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2531 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2532 if (parser->isParsing()) {
2533 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2534 if (parser->isExecutingScript())
2537 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2542 if (m_frame->loader().state() == FrameStateProvisional)
2543 m_frame->loader().stopAllLoaders();
2546 removeAllEventListeners();
2548 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2549 parser->setWasCreatedByScript(true);
2552 m_frame->loader().didExplicitOpen();
2555 void Document::detachParser()
2563 void Document::cancelParsing()
2568 // We have to clear the parser to avoid possibly triggering
2569 // the onload handler when closing as a side effect of a cancel-style
2570 // change, such as opening a new document or closing the window while
2576 void Document::implicitOpen()
2582 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2584 m_parser = createParser();
2586 setReadyState(Loading);
2589 HTMLBodyElement* Document::body() const
2591 auto* element = documentElement();
2594 return childrenOfType<HTMLBodyElement>(*element).first();
2597 HTMLElement* Document::bodyOrFrameset() const
2599 // Return the first body or frameset child of the html element.
2600 auto* element = documentElement();
2603 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2604 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2610 void Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody, ExceptionCode& ec)
2612 // FIXME: This does not support setting a <frameset> Element, only a <body>. This does
2613 // not match the HTML specification:
2614 // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
2615 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2616 ec = HIERARCHY_REQUEST_ERR;
2620 if (&newBody->document() != this) {
2622 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2626 newBody = downcast<HTMLElement>(node.get());
2629 if (auto* body = bodyOrFrameset())
2630 documentElement()->replaceChild(newBody.releaseNonNull(), *body, ec);
2632 documentElement()->appendChild(newBody.releaseNonNull(), ec);
2635 Location* Document::location() const
2637 auto* window = domWindow();
2641 return window->location();
2644 HTMLHeadElement* Document::head()
2646 if (auto element = documentElement())
2647 return childrenOfType<HTMLHeadElement>(*element).first();
2651 void Document::close()
2653 // FIXME: We should follow the specification more closely:
2654 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2656 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2662 void Document::explicitClose()
2664 if (RefPtr<DocumentParser> parser = m_parser)
2668 // Because we have no frame, we don't know if all loading has completed,
2669 // so we just call implicitClose() immediately. FIXME: This might fire
2670 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2675 m_frame->loader().checkCompleted();
2678 void Document::implicitClose()
2680 // 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.
2681 if (m_inStyleRecalc) {
2682 m_closeAfterStyleRecalc = true;
2686 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2687 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2692 // Call to dispatchWindowLoadEvent can blow us from underneath.
2693 Ref<Document> protect(*this);
2695 m_processingLoadEvent = true;
2697 ScriptableDocumentParser* parser = scriptableDocumentParser();
2698 m_wellFormed = parser && parser->wellFormed();
2700 // We have to clear the parser, in case someone document.write()s from the
2701 // onLoad event handler, as in Radar 3206524.
2704 // FIXME: We kick off the icon loader when the Document is done parsing.
2705 // There are earlier opportunities we could start it:
2706 // -When the <head> finishes parsing
2707 // -When any new HTMLLinkElement is inserted into the document
2708 // But those add a dynamic component to the favicon that has UI
2709 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2712 f->loader().icon().startLoader();
2713 f->animation().startAnimationsIfNotSuspended(this);
2715 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2716 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2717 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2718 ImageLoader::dispatchPendingBeforeLoadEvents();
2719 ImageLoader::dispatchPendingLoadEvents();
2720 ImageLoader::dispatchPendingErrorEvents();
2721 HTMLLinkElement::dispatchPendingLoadEvents();
2722 HTMLStyleElement::dispatchPendingLoadEvents();
2725 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2726 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2727 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2728 if (svgExtensions())
2729 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2731 dispatchWindowLoadEvent();
2732 enqueuePageshowEvent(PageshowEventNotPersisted);
2733 if (m_pendingStateObject)
2734 enqueuePopstateEvent(m_pendingStateObject.release());
2737 f->loader().dispatchOnloadEvents();
2738 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2739 if (!ownerElement())
2740 printf("onload fired at %lld\n", elapsedTime().count());
2743 // An event handler may have removed the frame
2745 m_processingLoadEvent = false;
2749 // Make sure both the initial layout and reflow happen after the onload
2750 // fires. This will improve onload scores, and other browsers do it.
2751 // If they wanna cheat, we can too. -dwh
2753 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2754 // Just bail out. Before or during the onload we were shifted to another page.
2755 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2756 m_processingLoadEvent = false;
2757 view()->unscheduleRelayout();
2761 frame()->loader().checkCallImplicitClose();
2763 // We used to force a synchronous display and flush here. This really isn't
2764 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2765 // (if your platform is syncing flushes and limiting them to 60fps).
2766 m_overMinimumLayoutThreshold = true;
2767 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2768 updateStyleIfNeeded();
2770 // Always do a layout after loading if needed.
2771 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2775 m_processingLoadEvent = false;
2777 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2778 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2779 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2780 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2781 // exists in the cache (we ignore the return value because we don't need it here). This is
2782 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2784 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2785 // catch new AND page history loads, and that uses AXLoadComplete
2787 axObjectCache()->getOrCreate(renderView());
2788 if (this == &topDocument())
2789 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2791 // AXLoadComplete can only be posted on the top document, so if it's a document
2792 // in an iframe that just finished loading, post AXLayoutComplete instead.
2793 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2798 if (svgExtensions())
2799 accessSVGExtensions().startAnimations();
2802 void Document::setParsing(bool b)
2806 if (m_bParsing && !m_sharedObjectPool)
2807 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2809 if (!m_bParsing && view() && !view()->needsLayout())
2810 view()->fireLayoutRelatedMilestonesIfNeeded();
2812 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2813 if (!ownerElement() && !m_bParsing)
2814 printf("Parsing finished at %lld\n", elapsedTime().count());
2818 bool Document::shouldScheduleLayout()
2820 // This function will only be called when FrameView thinks a layout is needed.
2821 // This enforces a couple extra rules.
2823 // (a) Only schedule a layout once the stylesheets are loaded.
2824 // (b) Only schedule layout once we have a body element.
2826 return (haveStylesheetsLoaded() && bodyOrFrameset())
2827 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2830 bool Document::isLayoutTimerActive()
2832 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2835 std::chrono::milliseconds Document::minimumLayoutDelay()
2837 if (m_overMinimumLayoutThreshold)
2838 return std::chrono::milliseconds(0);
2840 std::chrono::milliseconds elapsed = elapsedTime();
2841 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2843 // We'll want to schedule the timer to fire at the minimum layout threshold.
2844 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2847 std::chrono::milliseconds Document::elapsedTime() const
2849 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2851 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2854 void Document::write(const SegmentedString& text, Document* ownerDocument)
2856 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2858 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2859 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2861 if (m_writeRecursionIsTooDeep)
2864 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2865 if (!ownerElement())
2866 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2869 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2870 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2873 if (!hasInsertionPoint)
2874 open(ownerDocument);
2877 m_parser->insert(text);
2879 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2880 if (!ownerElement())
2881 printf("Ending a document.write at %lld\n", elapsedTime().count());
2885 void Document::write(const String& text, Document* ownerDocument)
2887 write(SegmentedString(text), ownerDocument);
2890 void Document::writeln(const String& text, Document* ownerDocument)
2892 write(text, ownerDocument);
2893 write("\n", ownerDocument);
2896 double Document::minimumTimerInterval() const
2898 Page* page = this->page();
2900 return ScriptExecutionContext::minimumTimerInterval();
2901 return page->settings().minimumDOMTimerInterval();
2904 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2906 if (m_isTimerThrottlingEnabled == shouldThrottle)
2909 m_isTimerThrottlingEnabled = shouldThrottle;
2910 didChangeTimerAlignmentInterval();
2913 double Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2915 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2916 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2917 return DOMTimer::hiddenPageAlignmentInterval();
2919 Page* page = this->page();
2921 return ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2922 return page->settings().domTimerAlignmentInterval();
2925 EventTarget* Document::errorEventTarget()
2927 return m_domWindow.get();
2930 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2932 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2935 void Document::setURL(const URL& url)
2937 const URL& newURL = url.isEmpty() ? blankURL() : url;
2938 if (newURL == m_url)
2942 m_documentURI = m_url.string();
2946 void Document::updateBaseURL()
2948 URL oldBaseURL = m_baseURL;
2949 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2950 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2951 // from the Document interface otherwise.
2952 if (!m_baseElementURL.isEmpty())
2953 m_baseURL = m_baseElementURL;
2954 else if (!m_baseURLOverride.isEmpty())
2955 m_baseURL = m_baseURLOverride;
2957 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2958 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2959 // and DOM 3 Core does not specify how it should be resolved.
2960 m_baseURL = URL(ParsedURLString, documentURI());
2963 clearSelectorQueryCache();
2965 if (!m_baseURL.isValid())
2968 if (m_elementSheet) {
2969 // Element sheet is silly. It never contains anything.
2970 ASSERT(!m_elementSheet->contents().ruleCount());
2971 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2972 bool usesStyleBasedEditability = m_elementSheet->contents().usesStyleBasedEditability();
2973 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2974 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2976 m_elementSheet->contents().parserSetUsesRemUnits();
2977 if (usesStyleBasedEditability)
2978 m_elementSheet->contents().parserSetUsesStyleBasedEditability();
2981 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2982 // Base URL change changes any relative visited links.
2983 // 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.
2984 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2985 anchor.invalidateCachedVisitedLinkHash();
2989 void Document::setBaseURLOverride(const URL& url)
2991 m_baseURLOverride = url;
2995 void Document::processBaseElement()
2997 // Find the first href attribute in a base element and the first target attribute in a base element.
2998 const AtomicString* href = nullptr;
2999 const AtomicString* target = nullptr;
3000 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3001 for (auto& base : baseDescendants) {
3003 const AtomicString& value = base.fastGetAttribute(hrefAttr);
3004 if (!value.isNull()) {
3011 const AtomicString& value = base.fastGetAttribute(targetAttr);
3012 if (!value.isNull()) {
3020 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3023 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3024 if (!strippedHref.isEmpty())
3025 baseElementURL = URL(url(), strippedHref);
3027 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3028 m_baseElementURL = baseElementURL;
3032 m_baseTarget = target ? *target : nullAtom;
3035 String Document::userAgent(const URL& url) const
3037 return frame() ? frame()->loader().userAgent(url) : String();
3040 void Document::disableEval(const String& errorMessage)
3045 frame()->script().disableEval(errorMessage);
3048 bool Document::canNavigate(Frame* targetFrame)
3053 // FIXME: We shouldn't call this function without a target frame, but
3054 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3055 // returning true when supplied with a 0 targetFrame.
3059 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
3060 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3063 if (isSandboxed(SandboxNavigation)) {
3064 if (targetFrame->tree().isDescendantOf(m_frame))
3067 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
3068 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3069 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
3071 printNavigationErrorMessage(targetFrame, url(), reason);
3075 // This is the normal case. A document can navigate its decendant frames,
3076 // or, more generally, a document can navigate a frame if the document is
3077 // in the same origin as any of that frame's ancestors (in the frame
3080 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3081 // historical information about this security check.
3082 if (canAccessAncestor(securityOrigin(), targetFrame))
3085 // Top-level frames are easier to navigate than other frames because they
3086 // display their URLs in the address bar (in most browsers). However, there
3087 // are still some restrictions on navigation to avoid nuisance attacks.
3088 // Specifically, a document can navigate a top-level frame if that frame
3089 // opened the document or if the document is the same-origin with any of
3090 // the top-level frame's opener's ancestors (in the frame hierarchy).
3092 // In both of these cases, the document performing the navigation is in
3093 // some way related to the frame being navigate (e.g., by the "opener"
3094 // and/or "parent" relation). Requiring some sort of relation prevents a
3095 // document from navigating arbitrary, unrelated top-level frames.
3096 if (!targetFrame->tree().parent()) {
3097 if (targetFrame == m_frame->loader().opener())
3100 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3104 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3108 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3110 Frame* currentFrame = m_frame;
3114 Frame* ancestorFrame = currentFrame->tree().parent();
3116 while (ancestorFrame) {
3117 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3118 return currentFrame;
3119 currentFrame = ancestorFrame;
3120 ancestorFrame = ancestorFrame->tree().parent();
3125 void Document::didRemoveAllPendingStylesheet()
3127 m_needsNotifyRemoveAllPendingStylesheet = false;
3129 styleResolverChanged(DeferRecalcStyleIfNeeded);
3131 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3132 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3134 renderView()->repaintViewAndCompositedLayers();
3137 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3138 parser->executeScriptsWaitingForStylesheets();
3140 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3141 view()->scrollToFragment(m_url);
3144 CSSStyleSheet& Document::elementSheet()
3146 if (!m_elementSheet)
3147 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
3148 return *m_elementSheet;
3151 bool Document::usesStyleBasedEditability() const
3153 if (m_elementSheet && m_elementSheet->contents().usesStyleBasedEditability())
3156 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3157 ASSERT(!m_inStyleRecalc);
3159 auto& authorSheets = const_cast<AuthorStyleSheets&>(authorStyleSheets());
3160 authorSheets.flushPendingUpdates();
3161 return authorSheets.usesStyleBasedEditability();
3164 void Document::processHttpEquiv(const String& equiv, const String& content)
3166 ASSERT(!equiv.isNull() && !content.isNull());
3168 HttpEquivPolicy policy = httpEquivPolicy();
3169 if (policy != HttpEquivPolicy::Enabled) {
3172 case HttpEquivPolicy::Enabled:
3173 ASSERT_NOT_REACHED();
3175 case HttpEquivPolicy::DisabledBySettings:
3176 reason = "by the embedder.";
3178 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3179 reason = "for documents with Content-Disposition: attachment.";
3182 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3183 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3187 Frame* frame = this->frame();
3189 HTTPHeaderName headerName;
3190 if (!findHTTPHeaderName(equiv, headerName))
3193 switch (headerName) {
3194 case HTTPHeaderName::DefaultStyle:
3195 // The preferred style set has been overridden as per section
3196 // 14.3.2 of the HTML4.0 specification. We need to update the
3197 // sheet used variable and then update our style selector.
3198 // For more info, see the test at:
3199 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3201 authorStyleSheets().setSelectedStylesheetSetName(content);
3202 authorStyleSheets().setPreferredStylesheetSetName(content);
3203 styleResolverChanged(DeferRecalcStyle);
3206 case HTTPHeaderName::Refresh: {
3209 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
3211 if (urlString.isEmpty())
3212 completedURL = m_url;
3214 completedURL = completeURL(urlString);
3215 if (!protocolIsJavaScript(completedURL))
3216 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3218 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3219 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3226 case HTTPHeaderName::SetCookie:
3227 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3228 if (is<HTMLDocument>(*this)) {
3229 // Exception (for sandboxed documents) ignored.
3230 downcast<HTMLDocument>(*this).setCookie(content, IGNORE_EXCEPTION);
3234 case HTTPHeaderName::ContentLanguage:
3235 setContentLanguage(content);
3238 case HTTPHeaderName::XDNSPrefetchControl:
3239 parseDNSPrefetchControlHeader(content);
3242 case HTTPHeaderName::XFrameOptions:
3244 FrameLoader& frameLoader = frame->loader();
3245 unsigned long requestIdentifier = 0;
3246 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3247 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3248 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3249 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3250 frameLoader.stopAllLoaders();
3251 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3252 // intent, we must navigate away from the possibly partially-rendered document to a location that
3253 // doesn't inherit the parent's SecurityOrigin.
3254 frame->navigationScheduler().scheduleLocationChange(this, securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
3255 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3260 case HTTPHeaderName::ContentSecurityPolicy:
3261 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
3264 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
3265 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
3268 case HTTPHeaderName::XWebKitCSP:
3269 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
3272 case HTTPHeaderName::XWebKitCSPReportOnly:
3273 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
3281 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3282 static bool isSeparator(UChar c)
3284 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3287 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3289 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3290 unsigned keyBegin, keyEnd;
3291 unsigned valueBegin, valueEnd;
3293 String buffer = features.lower();
3294 unsigned length = buffer.length();
3295 for (unsigned i = 0; i < length; ) {
3296 // skip to first non-separator, but don't skip past the end of the string
3297 while (isSeparator(buffer[i])) {
3304 // skip to first separator
3305 while (!isSeparator(buffer[i]))
3309 // skip to first '=', but don't skip past a ',' or the end of the string
3310 while (buffer[i] != '=') {
3311 if (buffer[i] == ',' || i >= length)
3316 // skip to first non-separator, but don't skip past a ',' or the end of the string
3317 while (isSeparator(buffer[i])) {
3318 if (buffer[i] == ',' || i >= length)
3324 // skip to first separator
3325 while (!isSeparator(buffer[i]))
3329 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
3331 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3332 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3333 callback(keyString, valueString, this, data);
3337 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3339 ASSERT(!features.isNull());
3341 if (origin < m_viewportArguments.type)
3344 m_viewportArguments = ViewportArguments(origin);
3345 processArguments(features, (void*)&m_viewportArguments, setViewportFeature);
3347 updateViewportArguments();
3350 void Document::updateViewportArguments()
3352 if (page() && frame()->isMainFrame()) {
3354 m_didDispatchViewportPropertiesChanged = true;
3356 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3358 page()->chrome().didReceiveDocType(frame());
3365 // FIXME: Find a better place for this functionality.
3366 void setParserFeature(const String& key, const String& value, Document* document, void*)
3368 if (key == "telephone" && equalLettersIgnoringASCIICase(value, "no"))
3369 document->setIsTelephoneNumberParsingAllowed(false);
3372 void Document::processFormatDetection(const String& features)
3374 ASSERT(!features.isNull());
3375 processArguments(features, nullptr, setParserFeature);
3378 void Document::processWebAppOrientations()
3380 if (Page* page = this->page())
3381 page->chrome().client().webAppOrientationsUpdated();
3386 void Document::processReferrerPolicy(const String& policy)
3388 ASSERT(!policy.isNull());
3390 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3391 // even if the document has a meta tag saying otherwise.
3392 if (shouldEnforceContentDispositionAttachmentSandbox())
3395 // Note that we're supporting both the standard and legacy keywords for referrer
3396 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3397 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3398 setReferrerPolicy(ReferrerPolicyNever);
3399 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3400 setReferrerPolicy(ReferrerPolicyAlways);
3401 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3402 setReferrerPolicy(ReferrerPolicyOrigin);
3403 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3404 setReferrerPolicy(ReferrerPolicyDefault);
3406 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'.");
3407 setReferrerPolicy(ReferrerPolicyNever);
3411 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3413 if (!hasLivingRenderTree())
3414 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3416 HitTestResult result(documentPoint);
3417 renderView()->hitTest(request, result);
3419 if (!request.readOnly())
3420 updateHoverActiveState(request, result.innerElement());
3422 return MouseEventWithHitTestResults(event, result);
3425 // DOM Section 1.1.1
3426 bool Document::childTypeAllowed(NodeType type) const
3429 case ATTRIBUTE_NODE:
3430 case CDATA_SECTION_NODE:
3431 case DOCUMENT_FRAGMENT_NODE:
3436 case PROCESSING_INSTRUCTION_NODE:
3438 case DOCUMENT_TYPE_NODE:
3440 // Documents may contain no more than one of each of these.
3441 // (One Element and one DocumentType.)
3442 for (Node* c = firstChild(); c; c = c->nextSibling())
3443 if (c->nodeType() == type)
3450 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3452 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3455 switch (newChild.nodeType()) {
3456 case ATTRIBUTE_NODE:
3457 case CDATA_SECTION_NODE:
3462 case PROCESSING_INSTRUCTION_NODE:
3464 case DOCUMENT_FRAGMENT_NODE: {
3465 bool hasSeenElementChild = false;
3466 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3467 if (is<Element>(*node)) {
3468 if (hasSeenElementChild)
3470 hasSeenElementChild = true;
3472 if (!canAcceptChild(*node, refChild, operation))
3477 case DOCUMENT_TYPE_NODE: {
3478 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3479 if (operation == AcceptChildOperation::Replace) {
3480 // parent has a doctype child that is not child, or an element is preceding child.
3481 if (existingDocType && existingDocType != refChild)
3483 if (refChild->previousElementSibling())
3486 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3487 if (existingDocType)
3489 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3494 case ELEMENT_NODE: {
3495 auto* existingElementChild = firstElementChild();
3496 if (operation == AcceptChildOperation::Replace) {
3497 if (existingElementChild && existingElementChild != refChild)
3499 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3500 if (is<DocumentType>(*child))
3504 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3505 if (existingElementChild)
3507 for (auto* child = refChild; child; child = child->nextSibling()) {
3508 if (is<DocumentType>(*child))
3518 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3520 Ref<Document> clone = cloneDocumentWithoutChildren();
3521 clone->cloneDataFromDocument(*this);
3523 case CloningOperation::OnlySelf:
3524 case CloningOperation::SelfWithTemplateContent:
3526 case CloningOperation::Everything:
3527 cloneChildNodes(clone);
3530 return WTFMove(clone);
3533 Ref<Document> Document::cloneDocumentWithoutChildren() const
3535 if (isXMLDocument()) {
3536 if (isXHTMLDocument())
3537 return XMLDocument::createXHTML(nullptr, url());
3538 return XMLDocument::create(nullptr, url());
3540 return create(nullptr, url());
3543 void Document::cloneDataFromDocument(const Document& other)
3545 ASSERT(m_url == other.url());
3546 m_baseURL = other.baseURL();
3547 m_baseURLOverride = other.baseURLOverride();
3548 m_documentURI = other.documentURI();
3550 setCompatibilityMode(other.m_compatibilityMode);
3551 setSecurityOriginPolicy(other.securityOriginPolicy());
3552 overrideMIMEType(other.contentType());
3553 setDecoder(other.decoder());
3556 StyleSheetList& Document::styleSheets()
3558 if (!m_styleSheetList)
3559 m_styleSheetList = StyleSheetList::create(this);
3560 return *m_styleSheetList;
3563 String Document::preferredStylesheetSet() const
3565 return authorStyleSheets().preferredStylesheetSetName();
3568 String Document::selectedStylesheetSet() const
3570 return authorStyleSheets().selectedStylesheetSetName();
3573 void Document::setSelectedStylesheetSet(const String& aString)
3575 authorStyleSheets().setSelectedStylesheetSetName(aString);
3576 styleResolverChanged(DeferRecalcStyle);
3579 void Document::evaluateMediaQueryList()
3581 if (m_mediaQueryMatcher)
3582 m_mediaQueryMatcher->styleResolverChanged();
3584 checkViewportDependentPictures();
3587 void Document::checkViewportDependentPictures()
3589 Vector<HTMLPictureElement*, 16> changedPictures;
3590 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3591 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3592 if ((*it)->viewportChangeAffectedPicture())
3593 changedPictures.append(*it);
3595 for (auto* picture : changedPictures)
3596 picture->sourcesChanged();
3599 void Document::optimizedStyleSheetUpdateTimerFired()
3601 styleResolverChanged(RecalcStyleIfNeeded);
3604 void Document::scheduleOptimizedStyleSheetUpdate()
3606 if (m_optimizedStyleSheetUpdateTimer.isActive())
3608 authorStyleSheets().setPendingUpdateType(AuthorStyleSheets::OptimizedUpdate);
3609 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3612 void Document::updateViewportUnitsOnResize()
3614 if (!hasStyleWithViewportUnits())
3617 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3619 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3620 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3621 auto* renderer = element->renderer();
3622 if (renderer && renderer->style().hasViewportUnits())
3623 element->setNeedsStyleRecalc(InlineStyleChange);
3627 void Document::addAudioProducer(MediaProducer* audioProducer)
3629 m_audioProducers.add(audioProducer);
3630 updateIsPlayingMedia();
3633 void Document::removeAudioProducer(MediaProducer* audioProducer)
3635 m_audioProducers.remove(audioProducer);
3636 updateIsPlayingMedia();
3639 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3641 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3642 for (auto* audioProducer : m_audioProducers)
3643 state |= audioProducer->mediaState();
3645 #if ENABLE(MEDIA_SESSION)
3646 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3647 if (sourceElement->isPlaying())
3648 state |= MediaProducer::IsSourceElementPlaying;
3650 if (auto* session = sourceElement->session()) {
3651 if (auto* controls = session->controls()) {
3652 if (controls->previousTrackEnabled())
3653 state |= MediaProducer::IsPreviousTrackControlEnabled;
3654 if (controls->nextTrackEnabled())
3655 state |= MediaProducer::IsNextTrackControlEnabled;
3661 if (state == m_mediaState)
3664 m_mediaState = state;
3667 page()->updateIsPlayingMedia(sourceElementID);
3670 void Document::pageMutedStateDidChange()
3672 for (auto* audioProducer : m_audioProducers)
3673 audioProducer->pageMutedStateDidChange();
3676 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3678 if (m_optimizedStyleSheetUpdateTimer.isActive())
3679 m_optimizedStyleSheetUpdateTimer.stop();
3681 // Don't bother updating, since we haven't loaded all our style info yet
3682 // and haven't calculated the style selector for the first time.
3683 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3684 m_styleResolver = nullptr;
3687 m_didCalculateStyleResolver = true;
3689 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3690 if (!ownerElement())
3691 printf("Beginning update of style selector at time %lld.\n", elapsedTime().count());
3694 auto styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3695 ? AuthorStyleSheets::OptimizedUpdate
3696 : AuthorStyleSheets::FullUpdate;
3697 bool stylesheetChangeRequiresStyleRecalc = authorStyleSheets().updateActiveStyleSheets(styleSheetUpdate);
3699 if (updateFlag == DeferRecalcStyle) {
3700 scheduleForcedStyleRecalc();
3704 if (updateFlag == DeferRecalcStyleIfNeeded) {
3705 if (stylesheetChangeRequiresStyleRecalc)
3706 scheduleForcedStyleRecalc();
3710 if (!stylesheetChangeRequiresStyleRecalc)
3713 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3714 // make sure animations get the correct update time
3716 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
3717 recalcStyle(Style::Force);
3720 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3721 if (!ownerElement())
3722 printf("Finished update of style selector at time %lld\n", elapsedTime().count());
3726 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3728 view()->scheduleRelayout();
3731 evaluateMediaQueryList();
3734 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3736 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3739 Element* focusedElement = node->treeScope().focusedElement();
3740 if (!focusedElement)
3743 bool nodeInSubtree = false;
3744 if (amongChildrenOnly)
3745 nodeInSubtree = focusedElement->isDescendantOf(node);
3747 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3750 setFocusedElement(nullptr);
3753 void Document::hoveredElementDidDetach(Element* element)
3755 if (!m_hoveredElement || element != m_hoveredElement)
3758 m_hoveredElement = element->parentElement();
3759 while (m_hoveredElement && !m_hoveredElement->renderer())
3760 m_hoveredElement = m_hoveredElement->parentElement();
3762 frame()->eventHandler().scheduleHoverStateUpdate();
3765 void Document::elementInActiveChainDidDetach(Element* element)
3767 if (!m_activeElement || element != m_activeElement)
3770 m_activeElement = element->parentElement();
3771 while (m_activeElement && !m_activeElement->renderer())
3772 m_activeElement = m_activeElement->parentElement();
3775 #if ENABLE(DASHBOARD_SUPPORT)
3776 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3778 return m_annotatedRegions;
3781 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3783 m_annotatedRegions = regions;
3784 setAnnotatedRegionsDirty(false);
3788 bool Document::setFocusedElement(Element* element, FocusDirection direction)
3790 RefPtr<Element> newFocusedElement = element;
3791 // Make sure newFocusedElement is actually in this document
3792 if (newFocusedElement && (&newFocusedElement->document() != this))
3795 if (m_focusedElement == newFocusedElement)
3801 bool focusChangeBlocked = false;
3802 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3804 // Remove focus from the existing focus node (if any)
3805 if (oldFocusedElement) {
3806 if (oldFocusedElement->active())
3807 oldFocusedElement->setActive(false);
3809 oldFocusedElement->setFocus(false);
3811 // Dispatch a change event for form control elements that have been edited.
3812 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3813 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3814 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3815 formControlElement.dispatchFormControlChangeEvent();
3818 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3819 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3821 if (m_focusedElement) {
3822 // handler shifted focus
3823 focusChangeBlocked = true;
3824 newFocusedElement = nullptr;
3827 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3828 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3829 // on it, probably when <rdar://problem/8503958> is resolved.
3830 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3832 if (m_focusedElement) {
3833 // handler shifted focus
3834 focusChangeBlocked = true;
3835 newFocusedElement = nullptr;
3838 if (oldFocusedElement->isRootEditableElement())
3839 frame()->editor().didEndEditing();
3842 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3843 oldWidget->setFocus(false);
3845 view()->setFocus(false);
3849 if (newFocusedElement && newFocusedElement->isFocusable()) {
3850 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3851 // delegate blocks focus change
3852 focusChangeBlocked = true;
3853 goto SetFocusedNodeDone;
3855 // Set focus on the new node
3856 m_focusedElement = newFocusedElement;
3858 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3859 m_focusedElement->dispatchFocusEvent(oldFocusedElement.copyRef(), direction);
3861 if (m_focusedElement != newFocusedElement) {
3862 // handler shifted focus
3863 focusChangeBlocked = true;
3864 goto SetFocusedNodeDone;
3867 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.copyRef()); // DOM level 3 bubbling focus event.
3869 if (m_focusedElement != newFocusedElement) {
3870 // handler shifted focus
3871 focusChangeBlocked = true;
3872 goto SetFocusedNodeDone;
3875 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3876 // on it, probably when <rdar://problem/8503958> is m.
3877 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement.copyRef()); // DOM level 2 for compatibility.
3879 if (m_focusedElement != newFocusedElement) {
3880 // handler shifted focus
3881 focusChangeBlocked = true;
3882 goto SetFocusedNodeDone;
3885 m_focusedElement->setFocus(true);
3887 if (m_focusedElement->isRootEditableElement())
3888 frame()->editor().didBeginEditing();
3890 // eww, I suck. set the qt focus correctly
3891 // ### find a better place in the code for this
3893 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3895 // Make sure a widget has the right size before giving it focus.
3896 // Otherwise, we are testing edge cases of the Widget code.
3897 // Specifically, in WebCore this does not work well for text fields.
3899 // Re-get the widget in case updating the layout changed things.
3900 focusWidget = widgetForElement(m_focusedElement.get());
3903 focusWidget->setFocus(true);
3905 view()->setFocus(true);
3909 if (!focusChangeBlocked && m_focusedElement) {
3910 // Create the AXObject cache in a focus change because GTK relies on it.
3911 if (AXObjectCache* cache = axObjectCache())
3912 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3915 if (!focusChangeBlocked && page())
3916 page()->chrome().focusedElementChanged(m_focusedElement.get());
3919 updateStyleIfNeeded();
3920 return !focusChangeBlocked;
3923 void Document::setCSSTarget(Element* n)
3926 m_cssTarget->setNeedsStyleRecalc();
3929 n->setNeedsStyleRecalc();
3932 void Document::registerNodeListForInvalidation(LiveNodeList& list)
3934 m_nodeListAndCollectionCounts[list.invalidationType()]++;
3935 if (!list.isRootedAtDocument())
3937 ASSERT(!list.isRegisteredForInvalidationAtDocument());
3938 list.setRegisteredForInvalidationAtDocument(true);
3939 m_listsInvalidatedAtDocument.add(&list);
3942 void Document::unregisterNodeListForInvalidation(LiveNodeList& list)
3944 m_nodeListAndCollectionCounts[list.invalidationType()]--;
3945 if (!list.isRegisteredForInvalidationAtDocument())
3948 list.setRegisteredForInvalidationAtDocument(false);
3949 ASSERT(m_inInvalidateNodeListAndCollectionCaches
3950 ? m_listsInvalidatedAtDocument.isEmpty()
3951 : m_listsInvalidatedAtDocument.contains(&list));
3952 m_listsInvalidatedAtDocument.remove(&list);
3955 void Document::registerCollection(HTMLCollection& collection)
3957 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
3958 if (collection.isRootedAtDocument())
3959 m_collectionsInvalidatedAtDocument.add(&collection);
3962 void Document::unregisterCollection(HTMLCollection& collection)
3964 ASSERT(m_nodeListAndCollectionCounts[collection.invalidationType()]);
3965 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
3966 if (!collection.isRootedAtDocument())
3969 m_collectionsInvalidatedAtDocument.remove(&collection);
3972 void Document::collectionCachedIdNameMap(const HTMLCollection& collection)
3974 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3975 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
3978 void Document::collectionWillClearIdNameMap(const HTMLCollection& collection)
3980 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3981 ASSERT(m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]);
3982 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
3985 void Document::attachNodeIterator(NodeIterator* ni)
3987 m_nodeIterators.add(ni);
3990 void Document::detachNodeIterator(NodeIterator* ni)
3992 // The node iterator can be detached without having been attached if its root node didn't have a document
3993 // when the iterator was created, but has it now.
3994 m_nodeIterators.remove(ni);
3997 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3999 Vector<NodeIterator*> nodeIterators;
4000 copyToVector(m_nodeIterators, nodeIterators);
4001 for (auto* it : nodeIterators) {
4002 if (it->root() == node) {
4003 detachNodeIterator(it);
4004 newDocument->attachNodeIterator(it);
4009 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
4011 for (auto* range : m_ranges)
4012 range->nodeChildrenChanged(container);
4015 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
4017 for (auto* range : m_ranges)
4018 range->nodeChildrenWillBeRemoved(container);
4020 for (auto* it : m_nodeIterators) {
4021 for (Node* n = container.firstChild(); n; n = n->nextSibling())
4022 it->nodeWillBeRemoved(*n);
4025 if (Frame* frame = this->frame()) {
4026 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
4027 frame->eventHandler().nodeWillBeRemoved(*n);
4028 frame->selection().nodeWillBeRemoved(*n);
4029 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
4033 if (m_markers->hasMarkers()) {
4034 for (Text* textNode = TextNodeTraversal::firstChild(container); textNode; textNode = TextNodeTraversal::nextSibling(*textNode))
4035 m_markers->removeMarkers(textNode);
4039 void Document::nodeWillBeRemoved(Node& n)
4041 for (auto* it : m_nodeIterators)
4042 it->nodeWillBeRemoved(n);
4044 for (auto* range : m_ranges)
4045 range->nodeWillBeRemoved(n);
4047 if (Frame* frame = this->frame()) {
4048 frame->eventHandler().nodeWillBeRemoved(n);
4049 frame->selection().nodeWillBeRemoved(n);
4050 frame->page()->dragCaretController().nodeWillBeRemoved(n);
4054 m_markers->removeMarkers(&n);
4057 void Document::textInserted(Node* text, unsigned offset, unsigned length)
4059 if (!m_ranges.isEmpty()) {
4060 for (auto* range : m_ranges)
4061 range->textInserted(text, offset, length);
4064 // Update the markers for spelling and grammar checking.
4065 m_markers->shiftMarkers(text, offset, length);
4068 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
4070 if (!m_ranges.isEmpty()) {
4071 for (auto* range : m_ranges)
4072 range->textRemoved(text, offset, length);
4075 // Update the markers for spelling and grammar checking.
4076 m_markers->removeMarkers(text, offset, length);
4077 m_markers->shiftMarkers(text, offset + length, 0 - length);
4080 void Document::textNodesMerged(Text* oldNode, unsigned offset)
4082 if (!m_ranges.isEmpty()) {
4083 NodeWithIndex oldNodeWithIndex(oldNode);
4084 for (auto* range : m_ranges)
4085 range->textNodesMerged(oldNodeWithIndex, offset);
4088 // FIXME: This should update markers for spelling and grammar checking.
4091 void Document::textNodeSplit(Text* oldNode)
4093 for (auto* range : m_ranges)
4094 range->textNodeSplit(oldNode);
4096 // FIXME: This should update markers for spelling and grammar checking.
4099 void Document::createDOMWindow()
4102 ASSERT(!m_domWindow);
4104 m_domWindow = DOMWindow::create(this);
4106 ASSERT(m_domWindow->document() == this);
4107 ASSERT(m_domWindow->frame() == m_frame);
4110 void Document::takeDOMWindowFrom(Document* document)
4113 ASSERT(!m_domWindow);
4114 ASSERT(document->m_domWindow);
4115 // A valid DOMWindow is needed by CachedFrame for its documents.
4116 ASSERT(!document->inPageCache());
4118 m_domWindow = document->m_domWindow.release();
4119 m_domWindow->didSecureTransitionTo(this);
4121 ASSERT(m_domWindow->document() == this);
4122 ASSERT(m_domWindow->frame() == m_frame);
4125 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
4129 m_domWindow->setAttributeEventListener(eventType, listener);
4132 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
4136 setWindowAttributeEventListener(eventType, JSLazyEventListener::createForDOMWindow(*m_frame, attributeName, attributeValue));
4139 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
4143 return m_domWindow->getAttributeEventListener(eventType);
4146 void Document::dispatchWindowEvent(Event& event, EventTarget* target)
4148 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4151 m_domWindow->dispatchEvent(event, target);
4154 void Document::dispatchWindowLoadEvent()
4156 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4159 m_domWindow->dispatchLoadEvent();
4160 m_loadEventFinished = true;
4161 m_cachedResourceLoader->documentDidFinishLoadEvent();
4164 void Document::enqueueWindowEvent(Ref<Event>&& event)
4166 event->setTarget(m_domWindow.get());
4167 m_eventQueue.enqueueEvent(WTFMove(event));
4170 void Document::enqueueDocumentEvent(Ref<Event>&& event)
4172 event->setTarget(this);
4173 m_eventQueue.enqueueEvent(WTFMove(event));
4176 void Document::enqueueOverflowEvent(Ref<Event>&& event)
4178 m_eventQueue.enqueueEvent(WTFMove(event));
4181 RefPtr<Event> Document::createEvent(const String& type, ExceptionCode& ec)
4183 // Please do *not* add new event classes to this function unless they are
4184 // required for compatibility of some actual legacy web content.
4186 // This mechanism is superceded by use of event constructors.
4187 // That is what we should use for any new event classes.
4189 // The following strings are the ones from the DOM specification
4190 // <https://dom.spec.whatwg.org/#dom-document-createevent>.
4192 if (equalLettersIgnoringASCIICase(type, "customevent"))
4193 return CustomEvent::create();
4194 if (equalLettersIgnoringASCIICase(type, "event") || equalLettersIgnoringASCIICase(type, "events") || equalLettersIgnoringASCIICase(type, "htmlevents"))
4195 return Event::create();
4196 if (equalLettersIgnoringASCIICase(type, "keyboardevent") || equalLettersIgnoringASCIICase(type, "keyboardevents"))
4197 return KeyboardEvent::create();
4198 if (equalLettersIgnoringASCIICase(type, "messageevent"))
4199 return MessageEvent::create();
4200 if (equalLettersIgnoringASCIICase(type, "mouseevent") || equalLettersIgnoringASCIICase(type, "mouseevents"))
4201 return MouseEvent::create();
4202 if (equalLettersIgnoringASCIICase(type, "uievent") || equalLettersIgnoringASCIICase(type, "uievents"))
4203 return UIEvent::create();
4205 #if ENABLE(TOUCH_EVENTS)
4206 if (equalLettersIgnoringASCIICase(type, "touchevent"))
4207 return TouchEvent::create();
4210 // The following string comes from the SVG specifications
4211 // <http://www.w3.org/TR/SVG/script.html#InterfaceSVGZoomEvent>
4212 // <http://www.w3.org/TR/SVG2/interact.html#InterfaceSVGZoomEvent>.
4213 // However, since there is no provision for initializing the event once it is created,
4214 // there is no practical value in this feature.
4216 if (equalLettersIgnoringASCIICase(type, "svgzoomevents"))
4217 return SVGZoomEvent::create();
4219 // The following strings are for event classes where WebKit supplies an init function.
4220 // These strings are not part of the DOM specification and we would like to eliminate them.
4221 // However, we currently include these because we have concerns about backward compatibility.
4223 // FIXME: For each of the strings below, prove there is no content depending on it and remove
4224 // both the string and the corresponding init function for that class.
4226 if (equalLettersIgnoringASCIICase(type, "compositionevent"))
4227 return CompositionEvent::create();
4228 if (equalLettersIgnoringASCIICase(type, "hashchangeevent"))
4229 return HashChangeEvent::create();
4230 if (equalLettersIgnoringASCIICase(type, "mutationevent") || equalLettersIgnoringASCIICase(type, "mutationevents"))
4231 return MutationEvent::create();
4232 if (equalLettersIgnoringASCIICase(type, "overflowevent"))
4233 return OverflowEvent::create();
4234 if (equalLettersIgnoringASCIICase(type, "storageevent"))
4235 return StorageEvent::create();
4236 if (equalLettersIgnoringASCIICase(type, "textevent"))
4237 return TextEvent::create();
4238 if (equalLettersIgnoringASCIICase(type, "wheelevent"))
4239 return WheelEvent::create();
4241 #if ENABLE(DEVICE_ORIENTATION)
4242 if (equalLettersIgnoringASCIICase(type, "devicemotionevent"))
4243 return DeviceMotionEvent::create();
4244 if (equalLettersIgnoringASCIICase(type, "deviceorientationevent"))
4245 return DeviceOrientationEvent::create();
4248 ec = NOT_SUPPORTED_ERR;
4252 bool Document::hasListenerTypeForEventType(PlatformEvent::Type eventType) const
4254 switch (eventType) {
4255 case PlatformEvent::MouseForceChanged:
4256 return m_listenerTypes & Document::FORCECHANGED_LISTENER;
4257 case PlatformEvent::MouseForceDown:
4258 return m_listenerTypes & Document::FORCEDOWN_LISTENER;
4259 case PlatformEvent::MouseForceUp:
4260 return m_listenerTypes & Document::FORCEUP_LISTENER;
4261 case PlatformEvent::MouseScroll:
4262 return m_listenerTypes & Document::SCROLL_LISTENER;
4268 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
4270 if (eventType == eventNames().DOMSubtreeModifiedEvent)
4271 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
4272 else if (eventType == eventNames().DOMNodeInsertedEvent)
4273 addListenerType(DOMNODEINSERTED_LISTENER);
4274 else if (eventType == eventNames().DOMNodeRemovedEvent)
4275 addListenerType(DOMNODEREMOVED_LISTENER);
4276 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
4277 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
4278 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
4279 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
4280 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
4281 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
4282 else if (eventType == eventNames().overflowchangedEvent)
4283 addListenerType(OVERFLOWCHANGED_LISTENER);
4284 else if (eventType == eventNames().webkitAnimationStartEvent || eventType == eventNames().animationstartEvent)
4285 addListenerType(ANIMATIONSTART_LISTENER);
4286 else if (eventType == eventNames().webkitAnimationEndEvent || eventType == eventNames().animationendEvent)
4287 addListenerType(ANIMATIONEND_LISTENER);
4288 else if (eventType == eventNames().webkitAnimationIterationEvent || eventType == eventNames().animationiterationEvent)
4289 addListenerType(ANIMATIONITERATION_LISTENER);
4290 else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
4291 addListenerType(TRANSITIONEND_LISTENER);
4292 else if (eventType == eventNames().beforeloadEvent)
4293 addListenerType(BEFORELOAD_LISTENER);
4294 else if (eventType == eventNames().scrollEvent)
4295 addListenerType(SCROLL_LISTENER);
4296 else if (eventType == eventNames().webkitmouseforcewillbeginEvent)
4297 addListenerType(FORCEWILLBEGIN_LISTENER);
4298 else if (eventType == eventNames().webkitmouseforcechangedEvent)
4299 addListenerType(FORCECHANGED_LISTENER);
4300 else if (eventType == eventNames().webkitmouseforcedownEvent)
4301 addListenerType(FORCEDOWN_LISTENER);
4302 else if (eventType == eventNames().webkitmouseforceupEvent)
4303 addListenerType(FORCEUP_LISTENER);
4306 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)