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 "HTTPHeaderNames.h"
94 #include "HTTPParsers.h"
95 #include "HashChangeEvent.h"
97 #include "HitTestResult.h"
98 #include "IconController.h"
99 #include "ImageLoader.h"
100 #include "InspectorInstrumentation.h"
101 #include "JSLazyEventListener.h"
102 #include "JSModuleLoader.h"
103 #include "KeyboardEvent.h"
104 #include "Language.h"
105 #include "LoaderStrategy.h"
107 #include "MainFrame.h"
108 #include "MediaCanStartListener.h"
109 #include "MediaProducer.h"
110 #include "MediaQueryList.h"
111 #include "MediaQueryMatcher.h"
112 #include "MessageEvent.h"
113 #include "MouseEventWithHitTestResults.h"
114 #include "MutationEvent.h"
115 #include "NameNodeList.h"
116 #include "NestingLevelIncrementer.h"
117 #include "NodeIterator.h"
118 #include "NodeRareData.h"
119 #include "NodeWithIndex.h"
120 #include "OverflowEvent.h"
121 #include "PageConsoleClient.h"
122 #include "PageGroup.h"
123 #include "PageTransitionEvent.h"
124 #include "PlatformLocale.h"
125 #include "PlatformMediaSessionManager.h"
126 #include "PlatformStrategies.h"
127 #include "PlugInsResources.h"
128 #include "PluginDocument.h"
129 #include "PointerLockController.h"
130 #include "PopStateEvent.h"
131 #include "ProcessingInstruction.h"
132 #include "RenderChildIterator.h"
133 #include "RenderLayerCompositor.h"
134 #include "RenderView.h"
135 #include "RenderWidget.h"
136 #include "RuntimeEnabledFeatures.h"
137 #include "SVGDocumentExtensions.h"
138 #include "SVGElement.h"
139 #include "SVGElementFactory.h"
140 #include "SVGNames.h"
141 #include "SVGTitleElement.h"
142 #include "SVGZoomEvent.h"
143 #include "SchemeRegistry.h"
144 #include "ScopedEventQueue.h"
145 #include "ScriptController.h"
146 #include "ScriptRunner.h"
147 #include "ScriptSourceCode.h"
148 #include "ScrollingCoordinator.h"
149 #include "SecurityOrigin.h"
150 #include "SecurityOriginPolicy.h"
151 #include "SecurityPolicy.h"
152 #include "SegmentedString.h"
153 #include "SelectorQuery.h"
154 #include "Settings.h"
155 #include "ShadowRoot.h"
156 #include "StorageEvent.h"
157 #include "StyleProperties.h"
158 #include "StyleResolveForDocument.h"
159 #include "StyleResolver.h"
160 #include "StyleSheetContents.h"
161 #include "StyleSheetList.h"
162 #include "StyleTreeResolver.h"
163 #include "SubresourceLoader.h"
164 #include "TextEvent.h"
165 #include "TextNodeTraversal.h"
166 #include "TransformSource.h"
167 #include "TreeWalker.h"
168 #include "VisitedLinkState.h"
169 #include "WheelEvent.h"
170 #include "XMLDocumentParser.h"
171 #include "XMLNSNames.h"
172 #include "XMLNames.h"
173 #include "XPathEvaluator.h"
174 #include "XPathExpression.h"
175 #include "XPathNSResolver.h"
176 #include "XPathResult.h"
177 #include "htmlediting.h"
178 #include <JavaScriptCore/Profile.h>
180 #include <inspector/ScriptCallStack.h>
181 #include <wtf/CurrentTime.h>
182 #include <wtf/NeverDestroyed.h>
183 #include <wtf/TemporaryChange.h>
184 #include <wtf/text/StringBuffer.h>
185 #include <yarr/RegularExpression.h>
188 #include "DOMSecurityPolicy.h"
191 #if ENABLE(DEVICE_ORIENTATION)
192 #include "DeviceMotionEvent.h"
193 #include "DeviceOrientationEvent.h"
196 #if ENABLE(FULLSCREEN_API)
197 #include "RenderFullScreen.h"
201 #include "CSSFontSelector.h"
202 #include "DeviceMotionClientIOS.h"
203 #include "DeviceMotionController.h"
204 #include "DeviceOrientationClientIOS.h"
205 #include "DeviceOrientationController.h"
206 #include "Geolocation.h"
207 #include "Navigator.h"
208 #include "NavigatorGeolocation.h"
209 #include "WKContentObservation.h"
210 #include "WebCoreSystemInterface.h"
213 #if ENABLE(IOS_GESTURE_EVENTS)
214 #include "GestureEvent.h"
217 #if ENABLE(IOS_TEXT_AUTOSIZING)
218 #include "TextAutoSizing.h"
222 #include "MathMLElement.h"
223 #include "MathMLElementFactory.h"
224 #include "MathMLNames.h"
227 #if ENABLE(MEDIA_SESSION)
228 #include "MediaSession.h"
231 #if ENABLE(REQUEST_ANIMATION_FRAME)
232 #include "RequestAnimationFrameCallback.h"
233 #include "ScriptedAnimationController.h"
236 #if ENABLE(TEXT_AUTOSIZING)
237 #include "TextAutosizer.h"
240 #if ENABLE(TOUCH_EVENTS)
241 #include "TouchEvent.h"
242 #include "TouchList.h"
245 #if ENABLE(VIDEO_TRACK)
246 #include "CaptionUserPreferences.h"
249 #if ENABLE(WEB_REPLAY)
250 #include "WebReplayInputs.h"
251 #include <replay/EmptyInputCursor.h>
252 #include <replay/InputCursor.h>
255 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
256 #include "MediaPlaybackTargetClient.h"
260 #include "XSLTProcessor.h"
264 using namespace Unicode;
268 using namespace HTMLNames;
270 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
272 static const unsigned cMaxWriteRecursionDepth = 21;
274 // DOM Level 2 says (letters added):
276 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
277 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
278 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
279 // 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.
280 // 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.
281 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
282 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
283 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
284 // i) Characters ':' and '_' are allowed as name-start characters.
285 // j) Characters '-' and '.' are allowed as name characters.
287 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
289 static inline bool isValidNameStart(UChar32 c)
292 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
296 if (c == ':' || c == '_')
299 // rules (a) and (f) above
300 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)))
304 if (c >= 0xF900 && c < 0xFFFE)
308 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
309 if (type == U_DT_FONT || type == U_DT_COMPAT)
315 static inline bool isValidNamePart(UChar32 c)
317 // rules (a), (e), and (i) above
318 if (isValidNameStart(c))
321 // rules (g) and (h) above
322 if (c == 0x00B7 || c == 0x0387)
326 if (c == '-' || c == '.')
329 // rules (b) and (f) above
330 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
334 if (c >= 0xF900 && c < 0xFFFE)
338 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
339 if (type == U_DT_FONT || type == U_DT_COMPAT)
345 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
347 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
349 // If a Document has the address "about:blank"
350 // The origin of the Document is the origin it was assigned when its browsing context was created.
352 // Note: We generalize this to all "blank" URLs and invalid URLs because we
353 // treat all of these URLs as about:blank.
355 return url.isEmpty() || url.isBlankURL();
358 static Widget* widgetForElement(Element* focusedElement)
362 auto* renderer = focusedElement->renderer();
363 if (!is<RenderWidget>(renderer))
365 return downcast<RenderWidget>(*renderer).widget();
368 static bool acceptsEditingFocus(Node* node)
371 ASSERT(node->hasEditableStyle());
373 Node* root = node->rootEditableElement();
374 Frame* frame = node->document().frame();
378 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
381 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
383 // targetFrame can be 0 when we're trying to navigate a top-level frame
384 // that has a 0 opener.
388 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
389 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
390 Document* ancestorDocument = ancestorFrame->document();
391 // FIXME: Should be an ASSERT? Frames should alway have documents.
392 if (!ancestorDocument)
395 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
396 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
399 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
400 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
401 // something more general instead?
402 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
409 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
411 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
413 // FIXME: should we print to the console of the document performing the navigation instead?
414 frame->document()->domWindow()->printErrorMessage(message);
417 uint64_t Document::s_globalTreeVersion = 0;
419 #if ENABLE(IOS_TEXT_AUTOSIZING)
420 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
422 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
425 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
427 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
431 HashSet<Document*>& Document::allDocuments()
433 static NeverDestroyed<HashSet<Document*>> documents;
437 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
438 : ContainerNode(*this, CreateDocument)
440 #if ENABLE(IOS_TOUCH_EVENTS)
441 , m_handlingTouchEvent(false)
442 , m_touchEventRegionsDirty(false)
443 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
445 , m_referencingNodeCount(0)
446 , m_didCalculateStyleResolver(false)
447 , m_hasNodesWithPlaceholderStyle(false)
448 , m_needsNotifyRemoveAllPendingStylesheet(false)
449 , m_ignorePendingStylesheets(false)
450 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
452 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
453 , m_activeParserCount(0)
454 , m_wellFormed(false)
456 , m_paginatedForScreen(false)
457 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
458 , m_compatibilityModeLocked(false)
459 , m_textColor(Color::black)
460 , m_domTreeVersion(++s_globalTreeVersion)
462 , m_mutationObserverTypes(0)
463 , m_authorStyleSheets(std::make_unique<AuthorStyleSheets>(*this))
464 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
465 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
466 , m_visuallyOrdered(false)
467 , m_readyState(Complete)
469 , m_optimizedStyleSheetUpdateTimer(*this, &Document::optimizedStyleSheetUpdateTimerFired)
470 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
471 , m_pendingStyleRecalcShouldForce(false)
472 , m_inStyleRecalc(false)
473 , m_closeAfterStyleRecalc(false)
474 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
475 , m_frameElementsShouldIgnoreScrolling(false)
476 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
477 , m_ignoreDestructiveWriteCount(0)
478 , m_markers(std::make_unique<DocumentMarkerController>(*this))
479 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
480 , m_cssTarget(nullptr)
481 , m_processingLoadEvent(false)
482 , m_loadEventFinished(false)
483 , m_startTime(std::chrono::steady_clock::now())
484 , m_overMinimumLayoutThreshold(false)
485 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
486 , m_moduleLoader(std::make_unique<JSModuleLoader>(*this))
487 , m_xmlVersion(ASCIILiteral("1.0"))
488 , m_xmlStandalone(StandaloneUnspecified)
489 , m_hasXMLDeclaration(false)
490 , m_designMode(inherit)
492 , m_inInvalidateNodeListAndCollectionCaches(false)
494 #if ENABLE(DASHBOARD_SUPPORT)
495 , m_hasAnnotatedRegions(false)
496 , m_annotatedRegionsDirty(false)
498 , m_createRenderers(true)
499 , m_inPageCache(false)
500 , m_accessKeyMapValid(false)
501 , m_documentClasses(documentClasses)
502 , m_isSynthesized(constructionFlags & Synthesized)
503 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
504 , m_sawElementsInKnownNamespaces(false)
505 , m_isSrcdocDocument(false)
506 , m_eventQueue(*this)
507 , m_weakFactory(this)
508 #if ENABLE(FULLSCREEN_API)
509 , m_areKeysEnabledInFullScreen(0)
510 , m_fullScreenRenderer(nullptr)
511 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
512 , m_isAnimatingFullScreen(false)
514 , m_loadEventDelayCount(0)
515 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
516 , m_referrerPolicy(ReferrerPolicyDefault)
517 , m_directionSetOnDocumentElement(false)
518 , m_writingModeSetOnDocumentElement(false)
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 RefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
886 if (!isValidName(name)) {
887 ec = INVALID_CHARACTER_ERR;
891 if (isHTMLDocument())
892 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name.convertToASCIILowercase(), xhtmlNamespaceURI), *this);
894 if (isXHTMLDocument())
895 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
897 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
900 Ref<DocumentFragment> Document::createDocumentFragment()
902 return DocumentFragment::create(document());
905 Ref<Text> Document::createTextNode(const String& data)
907 return Text::create(*this, data);
910 Ref<Comment> Document::createComment(const String& data)
912 return Comment::create(*this, data);
915 RefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
917 if (isHTMLDocument()) {
918 ec = NOT_SUPPORTED_ERR;
921 return CDATASection::create(*this, data);
924 RefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
926 if (!isValidName(target)) {
927 ec = INVALID_CHARACTER_ERR;
931 if (data.contains("?>")) {
932 ec = INVALID_CHARACTER_ERR;
936 return ProcessingInstruction::create(*this, target, data);
939 RefPtr<EntityReference> Document::createEntityReference(const String&, ExceptionCode& ec)
941 ec = NOT_SUPPORTED_ERR;
945 Ref<Text> Document::createEditingTextNode(const String& text)
947 return Text::createEditingText(*this, text);
950 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
952 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
953 return *propertySet->ensureCSSStyleDeclaration();
956 RefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
959 ec = NOT_SUPPORTED_ERR;
963 switch (importedNode->nodeType()) {
966 case CDATA_SECTION_NODE:
967 case PROCESSING_INSTRUCTION_NODE:
969 case DOCUMENT_FRAGMENT_NODE:
970 return importedNode->cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
973 // FIXME: This will "Attr::normalize" child nodes of Attr.
974 return Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(*importedNode).name(), nullAtom), downcast<Attr>(*importedNode).value());
976 case DOCUMENT_NODE: // Can't import a document into another document.
977 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
981 ec = NOT_SUPPORTED_ERR;
986 RefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
989 ec = NOT_SUPPORTED_ERR;
993 EventQueueScope scope;
995 switch (source->nodeType()) {
997 ec = NOT_SUPPORTED_ERR;
999 case ATTRIBUTE_NODE: {
1000 Attr& attr = downcast<Attr>(*source);
1001 if (attr.ownerElement())
1002 attr.ownerElement()->removeAttributeNode(&attr, ec);
1006 if (source->isShadowRoot()) {
1007 // ShadowRoot cannot disconnect itself from the host node.
1008 ec = HIERARCHY_REQUEST_ERR;
1011 if (is<HTMLFrameOwnerElement>(*source)) {
1012 HTMLFrameOwnerElement& frameOwnerElement = downcast<HTMLFrameOwnerElement>(*source);
1013 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1014 ec = HIERARCHY_REQUEST_ERR;
1018 if (source->parentNode()) {
1019 source->parentNode()->removeChild(*source, ec);
1025 adoptIfNeeded(source.get());
1030 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1032 // These checks are from DOM Core Level 2, createElementNS
1033 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1034 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1036 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1039 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1040 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1041 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1042 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1043 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1044 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1047 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1049 return hasValidNamespaceForElements(qName);
1052 // FIXME: This should really be in a possible ElementFactory class.
1053 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1055 RefPtr<Element> element;
1057 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1058 if (name.namespaceURI() == xhtmlNamespaceURI)
1059 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1060 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1061 element = SVGElementFactory::createElement(name, *this, createdByParser);
1063 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1064 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1068 m_sawElementsInKnownNamespaces = true;
1070 element = Element::create(name, document());
1072 // <image> uses imgTag so we need a special rule.
1073 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1075 return element.releaseNonNull();
1078 bool Document::cssRegionsEnabled() const
1080 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1083 bool Document::cssCompositingEnabled() const
1085 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1088 #if ENABLE(CSS_REGIONS)
1090 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1092 if (!cssRegionsEnabled() || !renderView())
1095 updateStyleIfNeeded();
1097 return namedFlows().createCSSOMSnapshot();
1102 NamedFlowCollection& Document::namedFlows()
1105 m_namedFlows = NamedFlowCollection::create(this);
1107 return *m_namedFlows;
1110 RefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1112 String prefix, localName;
1113 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1116 QualifiedName qName(prefix, localName, namespaceURI);
1117 if (!hasValidNamespaceForElements(qName)) {
1122 return createElement(qName, false);
1125 String Document::readyState() const
1127 static NeverDestroyed<const String> loading(ASCIILiteral("loading"));
1128 static NeverDestroyed<const String> interactive(ASCIILiteral("interactive"));
1129 static NeverDestroyed<const String> complete(ASCIILiteral("complete"));
1131 switch (m_readyState) {
1140 ASSERT_NOT_REACHED();
1144 void Document::setReadyState(ReadyState readyState)
1146 if (readyState == m_readyState)
1149 #if ENABLE(WEB_TIMING)
1150 switch (readyState) {
1152 if (!m_documentTiming.domLoading)
1153 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1156 if (!m_documentTiming.domInteractive)
1157 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1160 if (!m_documentTiming.domComplete)
1161 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1166 m_readyState = readyState;
1167 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1169 if (settings() && settings()->suppressesIncrementalRendering())
1170 setVisualUpdatesAllowed(readyState);
1173 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1175 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1176 switch (readyState) {
1178 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1179 ASSERT(m_visualUpdatesAllowed);
1180 setVisualUpdatesAllowed(false);
1183 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1186 if (m_visualUpdatesSuppressionTimer.isActive()) {
1187 ASSERT(!m_visualUpdatesAllowed);
1189 if (!view()->visualUpdatesAllowedByClient())
1192 setVisualUpdatesAllowed(true);
1194 ASSERT(m_visualUpdatesAllowed);
1199 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1201 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1204 m_visualUpdatesAllowed = visualUpdatesAllowed;
1206 if (visualUpdatesAllowed)
1207 m_visualUpdatesSuppressionTimer.stop();
1209 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1211 if (!visualUpdatesAllowed)
1214 FrameView* frameView = view();
1215 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1219 if (Page* page = this->page()) {
1220 if (frame()->isMainFrame()) {
1221 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1222 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1223 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1228 view()->updateCompositingLayersAfterLayout();
1230 if (RenderView* renderView = this->renderView())
1231 renderView->repaintViewAndCompositedLayers();
1233 if (Frame* frame = this->frame())
1234 frame->loader().forcePageTransitionIfNeeded();
1237 void Document::visualUpdatesSuppressionTimerFired()
1239 ASSERT(!m_visualUpdatesAllowed);
1241 // If the client is extending the visual update suppression period explicitly, the
1242 // watchdog should not re-enable visual updates itself, but should wait for the client.
1243 if (!view()->visualUpdatesAllowedByClient())
1246 setVisualUpdatesAllowed(true);
1249 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1251 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1252 // both of which we can determine by looking at the timer.
1254 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1255 setVisualUpdatesAllowed(true);
1258 String Document::characterSetWithUTF8Fallback() const
1260 AtomicString name = encoding();
1263 return UTF8Encoding().domName();
1266 String Document::defaultCharset() const
1268 if (Settings* settings = this->settings())
1269 return settings->defaultTextEncodingName();
1273 void Document::setCharset(const String& charset)
1277 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1280 void Document::setContentLanguage(const String& language)
1282 if (m_contentLanguage == language)
1284 m_contentLanguage = language;
1286 // Recalculate style so language is used when selecting the initial font.
1287 styleResolverChanged(DeferRecalcStyle);
1290 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1292 if (!implementation().hasFeature("XML", String())) {
1293 ec = NOT_SUPPORTED_ERR;
1297 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1298 ec = NOT_SUPPORTED_ERR;
1302 m_xmlVersion = version;
1305 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1307 if (!implementation().hasFeature("XML", String())) {
1308 ec = NOT_SUPPORTED_ERR;
1312 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1315 void Document::setDocumentURI(const String& uri)
1317 // This property is read-only from JavaScript, but writable from Objective-C.
1318 m_documentURI = uri;
1322 void Document::setContent(const String& content)
1325 // FIXME: This should probably use insert(), but that's (intentionally)
1326 // not implemented for the XML parser as it's normally synonymous with
1327 // document.write(). append() will end up yielding, but close() will
1328 // pump the tokenizer syncrhonously and finish the parse.
1329 m_parser->append(content.impl());
1333 String Document::suggestedMIMEType() const
1335 if (isXHTMLDocument())
1336 return ASCIILiteral("application/xhtml+xml");
1337 if (isSVGDocument())
1338 return ASCIILiteral("image/svg+xml");
1339 if (xmlStandalone())
1340 return ASCIILiteral("text/xml");
1341 if (isHTMLDocument())
1342 return ASCIILiteral("text/html");
1343 if (DocumentLoader* loader = this->loader())
1344 return loader->responseMIMEType();
1348 void Document::overrideMIMEType(const String& mimeType)
1350 m_overriddenMIMEType = mimeType;
1353 String Document::contentType() const
1355 if (!m_overriddenMIMEType.isNull())
1356 return m_overriddenMIMEType;
1358 if (DocumentLoader* documentLoader = loader())
1359 return documentLoader->currentContentType();
1361 String mimeType = suggestedMIMEType();
1362 if (!mimeType.isNull())
1365 return ASCIILiteral("application/xml");
1368 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1370 if (!frame() || !view())
1373 Frame& frame = *this->frame();
1375 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1377 LayoutPoint contentsPoint = clientPoint;
1378 contentsPoint.scale(scaleFactor, scaleFactor);
1379 contentsPoint.moveBy(view()->contentsScrollPosition());
1381 LayoutRect visibleRect;
1383 visibleRect = view()->unobscuredContentRect();
1385 visibleRect = view()->visibleContentRect();
1387 if (!visibleRect.contains(contentsPoint))
1390 HitTestResult result(contentsPoint);
1391 renderView()->hitTest(HitTestRequest(), result);
1394 *localPoint = result.localPoint();
1396 return result.innerNode();
1399 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1401 if (!hasLivingRenderTree())
1404 Node* node = nodeFromPoint(clientPoint);
1405 while (node && !is<Element>(*node))
1406 node = node->parentNode();
1409 node = ancestorInThisScope(node);
1411 return downcast<Element>(node);
1414 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1416 return caretRangeFromPoint(LayoutPoint(x, y));
1419 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1421 if (!hasLivingRenderTree())
1424 LayoutPoint localPoint;
1425 Node* node = nodeFromPoint(clientPoint, &localPoint);
1429 Node* shadowAncestorNode = ancestorInThisScope(node);
1430 if (shadowAncestorNode != node) {
1431 unsigned offset = shadowAncestorNode->computeNodeIndex();
1432 ContainerNode* container = shadowAncestorNode->parentNode();
1433 return Range::create(*this, container, offset, container, offset);
1436 RenderObject* renderer = node->renderer();
1439 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1440 if (visiblePosition.isNull())
1443 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1444 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1447 Element* Document::scrollingElement()
1449 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1450 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1456 * Performs three operations:
1457 * 1. Convert control characters to spaces
1458 * 2. Trim leading and trailing spaces
1459 * 3. Collapse internal whitespace.
1461 template <typename CharacterType>
1462 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1464 const String& title = titleWithDirection.string();
1465 const CharacterType* characters = title.characters<CharacterType>();
1466 unsigned length = title.length();
1469 StringBuffer<CharacterType> buffer(length);
1470 unsigned builderIndex = 0;
1472 // Skip leading spaces and leading characters that would convert to spaces
1473 for (i = 0; i < length; ++i) {
1474 CharacterType c = characters[i];
1475 if (!(c <= 0x20 || c == 0x7F))
1480 return StringWithDirection();
1482 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1483 bool previousCharWasWS = false;
1484 for (; i < length; ++i) {
1485 CharacterType c = characters[i];
1486 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1487 if (previousCharWasWS)
1489 buffer[builderIndex++] = ' ';
1490 previousCharWasWS = true;
1492 buffer[builderIndex++] = c;
1493 previousCharWasWS = false;
1497 // Strip trailing spaces
1498 while (builderIndex > 0) {
1500 if (buffer[builderIndex] != ' ')
1504 if (!builderIndex && buffer[builderIndex] == ' ')
1505 return StringWithDirection();
1507 buffer.shrink(builderIndex + 1);
1509 // Replace the backslashes with currency symbols if the encoding requires it.
1510 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1512 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1515 void Document::updateTitle(const StringWithDirection& title)
1517 if (m_rawTitle == title)
1522 if (m_rawTitle.string().isEmpty())
1523 m_title = StringWithDirection();
1525 if (m_rawTitle.string().is8Bit())
1526 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1528 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1530 if (DocumentLoader* loader = this->loader())
1531 loader->setTitle(m_title);
1534 void Document::updateTitleFromTitleElement()
1536 if (!m_titleElement) {
1537 updateTitle(StringWithDirection());
1541 if (is<HTMLTitleElement>(*m_titleElement))
1542 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1543 else if (is<SVGTitleElement>(*m_titleElement)) {
1544 // FIXME: does SVG have a title text direction?
1545 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1549 void Document::setTitle(const String& title)
1551 if (!isHTMLDocument() && !isXHTMLDocument())
1552 m_titleElement = nullptr;
1553 else if (!m_titleElement) {
1554 auto* headElement = head();
1557 m_titleElement = createElement(titleTag, false);
1558 headElement->appendChild(*m_titleElement, ASSERT_NO_EXCEPTION);
1561 // The DOM API has no method of specifying direction, so assume LTR.
1562 updateTitle(StringWithDirection(title, LTR));
1564 if (is<HTMLTitleElement>(m_titleElement.get()))
1565 downcast<HTMLTitleElement>(*m_titleElement).setText(title);
1568 void Document::updateTitleElement(Element* newTitleElement)
1570 // Only allow the first title element in tree order to change the title -- others have no effect.
1571 if (m_titleElement) {
1572 if (isHTMLDocument() || isXHTMLDocument())
1573 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1574 else if (isSVGDocument())
1575 m_titleElement = descendantsOfType<SVGTitleElement>(*this).first();
1577 m_titleElement = newTitleElement;
1579 updateTitleFromTitleElement();
1582 void Document::titleElementAdded(Element& titleElement)
1584 if (m_titleElement == &titleElement)
1587 updateTitleElement(&titleElement);
1590 void Document::titleElementRemoved(Element& titleElement)
1592 if (m_titleElement != &titleElement)
1595 updateTitleElement(nullptr);
1598 void Document::titleElementTextChanged(Element& titleElement)
1600 if (m_titleElement != &titleElement)
1603 updateTitleFromTitleElement();
1606 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1608 m_visibilityStateCallbackElements.add(element);
1611 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1613 m_visibilityStateCallbackElements.remove(element);
1616 void Document::visibilityStateChanged()
1618 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1619 for (auto* element : m_visibilityStateCallbackElements)
1620 element->visibilityStateChanged();
1623 PageVisibilityState Document::pageVisibilityState() const
1625 // The visibility of the document is inherited from the visibility of the
1626 // page. If there is no page associated with the document, we will assume
1627 // that the page is hidden, as specified by the spec:
1628 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1629 if (!m_frame || !m_frame->page())
1630 return PageVisibilityStateHidden;
1631 return m_frame->page()->visibilityState();
1634 String Document::visibilityState() const
1636 return pageVisibilityStateString(pageVisibilityState());
1639 bool Document::hidden() const
1641 return pageVisibilityState() != PageVisibilityStateVisible;
1646 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1648 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1651 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1653 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1656 void Document::allowsMediaDocumentInlinePlaybackChanged()
1658 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1659 element->allowsMediaDocumentInlinePlaybackChanged();
1663 #if ENABLE(CSP_NEXT)
1664 DOMSecurityPolicy& Document::securityPolicy()
1666 if (!m_domSecurityPolicy)
1667 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1668 return *m_domSecurityPolicy;
1672 String Document::nodeName() const
1677 Node::NodeType Document::nodeType() const
1679 return DOCUMENT_NODE;
1682 FormController& Document::formController()
1684 if (!m_formController)
1685 m_formController = std::make_unique<FormController>();
1686 return *m_formController;
1689 Vector<String> Document::formElementsState() const
1691 if (!m_formController)
1692 return Vector<String>();
1693 return m_formController->formElementsState();
1696 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1698 if (!stateVector.size() && !m_formController)
1700 formController().setStateForNewFormElements(stateVector);
1703 FrameView* Document::view() const
1705 return m_frame ? m_frame->view() : nullptr;
1708 Page* Document::page() const
1710 return m_frame ? m_frame->page() : nullptr;
1713 Settings* Document::settings() const
1715 return m_frame ? &m_frame->settings() : nullptr;
1718 Ref<Range> Document::createRange()
1720 return Range::create(*this);
1723 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1725 return createNodeIterator(root, whatToShow, WTFMove(filter), ec);
1728 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1734 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1737 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1739 return createNodeIterator(root, whatToShow, nullptr, ec);
1742 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionCode& ec)
1744 return createNodeIterator(root, 0xFFFFFFFF, nullptr, ec);
1747 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool, ExceptionCode& ec)
1749 return createTreeWalker(root, whatToShow, WTFMove(filter), ec);
1752 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, ExceptionCode& ec)
1758 return TreeWalker::create(*root, whatToShow, WTFMove(filter));
1761 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned long whatToShow, ExceptionCode& ec)
1763 return createTreeWalker(root, whatToShow, nullptr, ec);
1766 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionCode& ec)
1768 return createTreeWalker(root, 0xFFFFFFFF, nullptr, ec);
1771 void Document::scheduleForcedStyleRecalc()
1773 m_pendingStyleRecalcShouldForce = true;
1774 scheduleStyleRecalc();
1777 void Document::scheduleStyleRecalc()
1779 if (m_styleRecalcTimer.isActive() || inPageCache())
1782 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1784 // FIXME: Why on earth is this here? This is clearly misplaced.
1785 invalidateAccessKeyMap();
1787 m_styleRecalcTimer.startOneShot(0);
1789 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1792 void Document::unscheduleStyleRecalc()
1794 ASSERT(!childNeedsStyleRecalc());
1796 m_styleRecalcTimer.stop();
1797 m_pendingStyleRecalcShouldForce = false;
1800 bool Document::hasPendingStyleRecalc() const
1802 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1805 bool Document::hasPendingForcedStyleRecalc() const
1807 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1810 void Document::recalcStyle(Style::Change change)
1812 ASSERT(!view() || !view()->isPainting());
1814 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1818 FrameView& frameView = m_renderView->frameView();
1819 Ref<FrameView> protect(frameView);
1820 if (frameView.isPainting())
1823 if (m_inStyleRecalc)
1824 return; // Guard against re-entrancy. -dwh
1826 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1827 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1829 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1830 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1831 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1832 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1833 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1834 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1836 authorStyleSheets().flushPendingUpdates();
1838 frameView.willRecalcStyle();
1840 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1842 // FIXME: We never reset this flags.
1843 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1844 authorStyleSheets().setUsesRemUnit(true);
1845 // We don't call setUsesStyleBasedEditability here because the whole point of the flag is to avoid style recalc.
1846 // i.e. updating the flag here would be too late.
1848 m_inStyleRecalc = true;
1849 bool updatedCompositingLayers = false;
1851 Style::PostResolutionCallbackDisabler disabler(*this);
1852 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1854 if (m_pendingStyleRecalcShouldForce)
1855 change = Style::Force;
1857 if (change == Style::Force) {
1858 // This may get set again during style resolve.
1859 m_hasNodesWithPlaceholderStyle = false;
1861 auto documentStyle = Style::resolveForDocument(*this);
1863 // Inserting the pictograph font at the end of the font fallback list is done by the
1864 // font selector, so set a font selector if needed.
1865 if (Settings* settings = this->settings()) {
1866 if (settings->fontFallbackPrefersPictographs())
1867 documentStyle.get().fontCascade().update(&fontSelector());
1870 auto documentChange = Style::determineChange(documentStyle.get(), m_renderView->style());
1871 if (documentChange != Style::NoChange)
1872 renderView()->setStyle(WTFMove(documentStyle));
1875 Style::TreeResolver resolver(*this);
1876 resolver.resolve(change);
1878 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1880 clearNeedsStyleRecalc();
1881 clearChildNeedsStyleRecalc();
1882 unscheduleStyleRecalc();
1884 m_inStyleRecalc = false;
1887 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1888 if (m_closeAfterStyleRecalc) {
1889 m_closeAfterStyleRecalc = false;
1893 ++m_styleRecalcCount;
1895 InspectorInstrumentation::didRecalculateStyle(cookie);
1897 // Some animated images may now be inside the viewport due to style recalc,
1898 // resume them if necessary if there is no layout pending. Otherwise, we'll
1899 // check if they need to be resumed after layout.
1900 if (updatedCompositingLayers && !frameView.needsLayout())
1901 frameView.viewportContentsChanged();
1903 if (!frameView.needsLayout())
1904 frameView.frame().selection().updateAppearanceAfterLayout();
1906 // As a result of the style recalculation, the currently hovered element might have been
1907 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1908 // to check if any other elements ended up under the mouse pointer due to re-layout.
1909 if (m_hoveredElement && !m_hoveredElement->renderer())
1910 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1913 void Document::updateStyleIfNeeded()
1915 ASSERT(isMainThread());
1916 ASSERT(!view() || !view()->isPainting());
1918 if (!view() || view()->isInLayout())
1921 if (m_optimizedStyleSheetUpdateTimer.isActive())
1922 styleResolverChanged(RecalcStyleIfNeeded);
1924 if (!needsStyleRecalc())
1927 recalcStyle(Style::NoChange);
1930 void Document::updateLayout()
1932 ASSERT(isMainThread());
1934 FrameView* frameView = view();
1935 if (frameView && frameView->isInLayout()) {
1936 // View layout should not be re-entrant.
1937 ASSERT_NOT_REACHED();
1941 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1943 if (HTMLFrameOwnerElement* owner = ownerElement())
1944 owner->document().updateLayout();
1946 updateStyleIfNeeded();
1948 StackStats::LayoutCheckPoint layoutCheckPoint;
1950 // Only do a layout if changes have occurred that make it necessary.
1951 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1952 frameView->layout();
1955 // FIXME: This is a bad idea and needs to be removed eventually.
1956 // Other browsers load stylesheets before they continue parsing the web page.
1957 // Since we don't, we can run JavaScript code that needs answers before the
1958 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1959 // lets us get reasonable answers. The long term solution to this problem is
1960 // to instead suspend JavaScript execution.
1961 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1963 bool oldIgnore = m_ignorePendingStylesheets;
1965 if (!haveStylesheetsLoaded()) {
1966 m_ignorePendingStylesheets = true;
1967 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1968 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1969 // with accurate style information. (Our suppression involves blanking the whole page at the
1970 // moment. If it were more refined, we might be able to do something better.)
1971 // It's worth noting though that this entire method is a hack, since what we really want to do is
1972 // suspend JS instead of doing a layout with inaccurate information.
1973 HTMLElement* bodyElement = bodyOrFrameset();
1974 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1975 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1976 styleResolverChanged(RecalcStyleImmediately);
1977 } else if (m_hasNodesWithPlaceholderStyle)
1978 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1979 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1980 // but here we need up-to-date style immediately.
1981 recalcStyle(Style::Force);
1986 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1987 view()->flushAnyPendingPostLayoutTasks();
1989 m_ignorePendingStylesheets = oldIgnore;
1992 Ref<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, RenderStyle* parentStyle)
1994 ASSERT(&element.document() == this);
1996 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1997 ResourceLoadSuspender suspender;
1999 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
2000 return element.resolveStyle(parentStyle);
2003 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2005 ASSERT(isMainThread());
2007 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2008 if (!haveStylesheetsLoaded()) {
2009 updateLayoutIgnorePendingStylesheets();
2013 // Check for re-entrancy and assert (same code that is in updateLayout()).
2014 FrameView* frameView = view();
2015 if (frameView && frameView->isInLayout()) {
2016 // View layout should not be re-entrant.
2017 ASSERT_NOT_REACHED();
2021 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2023 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2025 bool requireFullLayout = false;
2026 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2027 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2028 requireFullLayout = true;
2031 updateStyleIfNeeded();
2033 RenderObject* renderer = element.renderer();
2034 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2035 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2036 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2037 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2038 requireFullLayout = true;
2041 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2042 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2043 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2044 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2046 if (!requireFullLayout) {
2047 RenderBox* previousBox = nullptr;
2048 RenderBox* currentBox = nullptr;
2050 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2051 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2053 // Require the entire container chain to be boxes.
2054 if (!is<RenderBox>(currRenderer)) {
2055 requireFullLayout = true;
2059 previousBox = currentBox;
2060 currentBox = downcast<RenderBox>(currRenderer);
2062 // If a box needs layout for itself or if a box has changed children and sizes its width to
2063 // its content, then require a full layout.
2064 if (currentBox->selfNeedsLayout() ||
2065 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2066 requireFullLayout = true;
2070 // If a block contains floats and the child's height isn't specified, then
2071 // give up also, since our height could end up being influenced by the floats.
2072 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2073 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2074 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2075 requireFullLayout = true;
2080 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2081 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2082 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2083 // Disallow regions/columns from having the optimization.
2084 // Give up if the writing mode changes at all in the containing block chain.
2085 requireFullLayout = true;
2089 if (currRenderer == frameView->layoutRoot())
2094 StackStats::LayoutCheckPoint layoutCheckPoint;
2096 // Only do a layout if changes have occurred that make it necessary.
2097 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2098 frameView->layout();
2100 return requireFullLayout;
2103 bool Document::isPageBoxVisible(int pageIndex)
2105 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
2106 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2109 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2111 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
2113 int width = pageSize.width();
2114 int height = pageSize.height();
2115 switch (style->pageSizeType()) {
2116 case PAGE_SIZE_AUTO:
2118 case PAGE_SIZE_AUTO_LANDSCAPE:
2120 std::swap(width, height);
2122 case PAGE_SIZE_AUTO_PORTRAIT:
2124 std::swap(width, height);
2126 case PAGE_SIZE_RESOLVED: {
2127 LengthSize size = style->pageSize();
2128 ASSERT(size.width().isFixed());
2129 ASSERT(size.height().isFixed());
2130 width = valueForLength(size.width(), 0);
2131 height = valueForLength(size.height(), 0);
2135 ASSERT_NOT_REACHED();
2137 pageSize = IntSize(width, height);
2139 // The percentage is calculated with respect to the width even for margin top and bottom.
2140 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2141 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2142 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2143 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2144 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2147 void Document::createStyleResolver()
2149 m_styleResolver = std::make_unique<StyleResolver>(*this);
2150 m_styleResolver->appendAuthorStyleSheets(authorStyleSheets().activeStyleSheets());
2153 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2155 if (!m_userAgentShadowTreeStyleResolver) {
2156 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2158 // FIXME: Filter out shadow pseudo elements we don't want to expose to authors.
2159 auto& documentAuthorStyle = *ensureStyleResolver().ruleSets().authorStyle();
2160 if (documentAuthorStyle.hasShadowPseudoElementRules())
2161 m_userAgentShadowTreeStyleResolver->ruleSets().authorStyle()->copyShadowPseudoElementRulesFrom(documentAuthorStyle);
2164 return *m_userAgentShadowTreeStyleResolver;
2167 void Document::fontsNeedUpdate(FontSelector&)
2169 if (m_styleResolver)
2170 m_styleResolver->invalidateMatchedPropertiesCache();
2171 if (inPageCache() || !renderView())
2173 scheduleForcedStyleRecalc();
2176 CSSFontSelector& Document::fontSelector()
2178 if (!m_fontSelector) {
2179 m_fontSelector = CSSFontSelector::create(*this);
2180 m_fontSelector->registerForInvalidationCallbacks(*this);
2182 return *m_fontSelector;
2185 void Document::clearStyleResolver()
2187 m_styleResolver = nullptr;
2188 m_userAgentShadowTreeStyleResolver = nullptr;
2190 // FIXME: It would be better if the FontSelector could survive this operation.
2191 if (m_fontSelector) {
2192 m_fontSelector->clearDocument();
2193 m_fontSelector->unregisterForInvalidationCallbacks(*this);
2194 m_fontSelector = nullptr;
2198 void Document::createRenderTree()
2200 ASSERT(!renderView());
2201 ASSERT(!m_inPageCache);
2202 ASSERT(!m_axObjectCache || this != &topDocument());
2204 if (m_isNonRenderedPlaceholder)
2207 // FIXME: It would be better if we could pass the resolved document style directly here.
2208 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2209 Node::setRenderer(m_renderView.get());
2211 renderView()->setIsInWindow(true);
2213 recalcStyle(Style::Force);
2216 void Document::didBecomeCurrentDocumentInFrame()
2218 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2219 // If so, then m_frame could become 0, and we need to do something about that.
2221 m_frame->script().updateDocument();
2223 if (!hasLivingRenderTree())
2226 updateViewportArguments();
2228 // FIXME: Doing this only for the main frame is insufficient.
2229 // Changing a subframe can also change the wheel event handler count.
2230 // FIXME: Doing this only when a document goes into the frame is insufficient.
2231 // Removing a document can also change the wheel event handler count.
2232 // FIXME: Doing this every time is a waste. If the current document and its
2233 // subframes' documents have no wheel event handlers, then the count did not change,
2234 // unless the documents they are replacing had wheel event handlers.
2235 if (page() && m_frame->isMainFrame())
2236 wheelEventHandlersChanged();
2238 #if ENABLE(TOUCH_EVENTS)
2239 // FIXME: Doing this only for the main frame is insufficient.
2240 // A subframe could have touch event handlers.
2241 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2242 page()->chrome().client().needTouchEvents(true);
2245 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2246 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2247 // page cache, or simply newly created).
2248 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2249 m_frame->animation().suspendAnimationsForDocument(this);
2250 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2252 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2253 m_frame->animation().resumeAnimationsForDocument(this);
2257 void Document::disconnectFromFrame()
2262 void Document::destroyRenderTree()
2264 ASSERT(hasLivingRenderTree());
2265 ASSERT(!m_inPageCache);
2267 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2269 if (this == &topDocument())
2270 clearAXObjectCache();
2272 documentWillBecomeInactive();
2274 if (FrameView* frameView = view())
2275 frameView->detachCustomScrollbars();
2277 #if ENABLE(FULLSCREEN_API)
2278 if (m_fullScreenRenderer)
2279 setFullScreenRenderer(nullptr);
2282 m_hoveredElement = nullptr;
2283 m_focusedElement = nullptr;
2284 m_activeElement = nullptr;
2286 if (m_documentElement)
2287 Style::detachRenderTree(*m_documentElement);
2289 clearChildNeedsStyleRecalc();
2291 unscheduleStyleRecalc();
2293 m_renderView = nullptr;
2294 Node::setRenderer(nullptr);
2296 #if ENABLE(IOS_TEXT_AUTOSIZING)
2297 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2298 m_textAutoSizedNodes.clear();
2302 void Document::prepareForDestruction()
2304 if (m_hasPreparedForDestruction)
2307 #if ENABLE(IOS_TOUCH_EVENTS)
2308 clearTouchEventListeners();
2311 #if HAVE(ACCESSIBILITY)
2312 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2313 if (this != &topDocument()) {
2314 if (AXObjectCache* cache = existingAXObjectCache())
2315 cache->clearTextMarkerNodesInUse(this);
2319 disconnectDescendantFrames();
2320 if (m_domWindow && m_frame)
2321 m_domWindow->willDetachDocumentFromFrame();
2323 if (hasLivingRenderTree())
2324 destroyRenderTree();
2326 if (is<PluginDocument>(*this))
2327 downcast<PluginDocument>(*this).detachFromPluginElement();
2329 #if ENABLE(POINTER_LOCK)
2331 page()->pointerLockController().documentDetached(this);
2334 InspectorInstrumentation::documentDetached(*this);
2336 stopActiveDOMObjects();
2337 m_eventQueue.close();
2338 #if ENABLE(FULLSCREEN_API)
2339 m_fullScreenChangeEventTargetQueue.clear();
2340 m_fullScreenErrorEventTargetQueue.clear();
2345 #if ENABLE(TOUCH_EVENTS)
2346 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2347 parentDocument()->didRemoveEventTargetNode(*this);
2350 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2351 parentDocument()->didRemoveEventTargetNode(*this);
2353 if (m_mediaQueryMatcher)
2354 m_mediaQueryMatcher->documentDestroyed();
2356 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2357 if (!m_clientToIDMap.isEmpty() && page()) {
2358 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2359 copyKeysToVector(m_clientToIDMap, clients);
2360 for (auto* client : clients)
2361 removePlaybackTargetPickerClient(*client);
2365 disconnectFromFrame();
2367 m_hasPreparedForDestruction = true;
2370 void Document::removeAllEventListeners()
2372 EventTarget::removeAllEventListeners();
2375 m_domWindow->removeAllEventListeners();
2376 #if ENABLE(IOS_TOUCH_EVENTS)
2377 clearTouchEventListeners();
2379 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2380 node->removeAllEventListeners();
2383 void Document::suspendDeviceMotionAndOrientationUpdates()
2385 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2387 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2388 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2389 if (m_deviceMotionController)
2390 m_deviceMotionController->suspendUpdates();
2391 if (m_deviceOrientationController)
2392 m_deviceOrientationController->suspendUpdates();
2396 void Document::resumeDeviceMotionAndOrientationUpdates()
2398 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2400 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2401 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2402 if (m_deviceMotionController)
2403 m_deviceMotionController->resumeUpdates();
2404 if (m_deviceOrientationController)
2405 m_deviceOrientationController->resumeUpdates();
2409 void Document::platformSuspendOrStopActiveDOMObjects()
2412 if (WebThreadCountOfObservedContentModifiers() > 0) {
2413 Frame* frame = this->frame();
2414 if (Page* page = frame ? frame->page() : nullptr)
2415 page->chrome().client().clearContentChangeObservers(frame);
2420 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2422 ScriptExecutionContext::suspendActiveDOMObjects(why);
2423 suspendDeviceMotionAndOrientationUpdates();
2424 platformSuspendOrStopActiveDOMObjects();
2427 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2429 ScriptExecutionContext::resumeActiveDOMObjects(why);
2430 resumeDeviceMotionAndOrientationUpdates();
2431 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2434 void Document::stopActiveDOMObjects()
2436 ScriptExecutionContext::stopActiveDOMObjects();
2437 platformSuspendOrStopActiveDOMObjects();
2440 void Document::clearAXObjectCache()
2442 ASSERT(&topDocument() == this);
2443 // Clear the cache member variable before calling delete because attempts
2444 // are made to access it during destruction.
2445 m_axObjectCache = nullptr;
2448 AXObjectCache* Document::existingAXObjectCache() const
2450 Document& topDocument = this->topDocument();
2451 if (!topDocument.hasLivingRenderTree())
2453 return topDocument.m_axObjectCache.get();
2456 AXObjectCache* Document::axObjectCache() const
2458 if (!AXObjectCache::accessibilityEnabled())
2461 // The only document that actually has a AXObjectCache is the top-level
2462 // document. This is because we need to be able to get from any WebCoreAXObject
2463 // to any other WebCoreAXObject on the same page. Using a single cache allows
2464 // lookups across nested webareas (i.e. multiple documents).
2465 Document& topDocument = this->topDocument();
2467 // If the document has already been detached, do not make a new axObjectCache.
2468 if (!topDocument.hasLivingRenderTree())
2471 ASSERT(&topDocument == this || !m_axObjectCache);
2472 if (!topDocument.m_axObjectCache)
2473 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2474 return topDocument.m_axObjectCache.get();
2477 void Document::setVisuallyOrdered()
2479 m_visuallyOrdered = true;
2481 renderView()->style().setRTLOrdering(VisualOrder);
2484 Ref<DocumentParser> Document::createParser()
2486 // FIXME: this should probably pass the frame instead
2487 return XMLDocumentParser::create(*this, view());
2490 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2492 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2495 void Document::open(Document* ownerDocument)
2497 if (ownerDocument) {
2498 setURL(ownerDocument->url());
2499 setCookieURL(ownerDocument->cookieURL());
2500 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2504 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2505 if (parser->isParsing()) {
2506 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2507 if (parser->isExecutingScript())
2510 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2515 if (m_frame->loader().state() == FrameStateProvisional)
2516 m_frame->loader().stopAllLoaders();
2519 removeAllEventListeners();
2521 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2522 parser->setWasCreatedByScript(true);
2525 m_frame->loader().didExplicitOpen();
2528 void Document::detachParser()
2536 void Document::cancelParsing()
2541 // We have to clear the parser to avoid possibly triggering
2542 // the onload handler when closing as a side effect of a cancel-style
2543 // change, such as opening a new document or closing the window while
2549 void Document::implicitOpen()
2555 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2557 m_parser = createParser();
2559 setReadyState(Loading);
2562 HTMLBodyElement* Document::body() const
2564 auto* element = documentElement();
2567 return childrenOfType<HTMLBodyElement>(*element).first();
2570 HTMLElement* Document::bodyOrFrameset() const
2572 // Return the first body or frameset child of the html element.
2573 auto* element = documentElement();
2576 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2577 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2583 void Document::setBodyOrFrameset(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2585 RefPtr<HTMLElement> newBody = prpNewBody;
2587 // FIXME: This does not support setting a <frameset> Element, only a <body>. This does
2588 // not match the HTML specification:
2589 // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
2590 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2591 ec = HIERARCHY_REQUEST_ERR;
2595 if (&newBody->document() != this) {
2597 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2601 newBody = downcast<HTMLElement>(node.get());
2604 if (auto* body = bodyOrFrameset())
2605 documentElement()->replaceChild(newBody.releaseNonNull(), *body, ec);
2607 documentElement()->appendChild(newBody.releaseNonNull(), ec);
2610 Location* Document::location() const
2612 auto* window = domWindow();
2616 return window->location();
2619 HTMLHeadElement* Document::head()
2621 if (auto element = documentElement())
2622 return childrenOfType<HTMLHeadElement>(*element).first();
2626 void Document::close()
2628 // FIXME: We should follow the specification more closely:
2629 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2631 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2637 void Document::explicitClose()
2639 if (RefPtr<DocumentParser> parser = m_parser)
2643 // Because we have no frame, we don't know if all loading has completed,
2644 // so we just call implicitClose() immediately. FIXME: This might fire
2645 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2650 m_frame->loader().checkCompleted();
2653 void Document::implicitClose()
2655 // 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.
2656 if (m_inStyleRecalc) {
2657 m_closeAfterStyleRecalc = true;
2661 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2662 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2667 // Call to dispatchWindowLoadEvent can blow us from underneath.
2668 Ref<Document> protect(*this);
2670 m_processingLoadEvent = true;
2672 ScriptableDocumentParser* parser = scriptableDocumentParser();
2673 m_wellFormed = parser && parser->wellFormed();
2675 // We have to clear the parser, in case someone document.write()s from the
2676 // onLoad event handler, as in Radar 3206524.
2679 // FIXME: We kick off the icon loader when the Document is done parsing.
2680 // There are earlier opportunities we could start it:
2681 // -When the <head> finishes parsing
2682 // -When any new HTMLLinkElement is inserted into the document
2683 // But those add a dynamic component to the favicon that has UI
2684 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2687 f->loader().icon().startLoader();
2688 f->animation().startAnimationsIfNotSuspended(this);
2690 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2691 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2692 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2693 ImageLoader::dispatchPendingBeforeLoadEvents();
2694 ImageLoader::dispatchPendingLoadEvents();
2695 ImageLoader::dispatchPendingErrorEvents();
2696 HTMLLinkElement::dispatchPendingLoadEvents();
2697 HTMLStyleElement::dispatchPendingLoadEvents();
2700 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2701 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2702 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2703 if (svgExtensions())
2704 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2706 dispatchWindowLoadEvent();
2707 enqueuePageshowEvent(PageshowEventNotPersisted);
2708 if (m_pendingStateObject)
2709 enqueuePopstateEvent(m_pendingStateObject.release());
2712 f->loader().dispatchOnloadEvents();
2713 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2714 if (!ownerElement())
2715 printf("onload fired at %lld\n", elapsedTime().count());
2718 // An event handler may have removed the frame
2720 m_processingLoadEvent = false;
2724 // Make sure both the initial layout and reflow happen after the onload
2725 // fires. This will improve onload scores, and other browsers do it.
2726 // If they wanna cheat, we can too. -dwh
2728 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2729 // Just bail out. Before or during the onload we were shifted to another page.
2730 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2731 m_processingLoadEvent = false;
2732 view()->unscheduleRelayout();
2736 frame()->loader().checkCallImplicitClose();
2738 // We used to force a synchronous display and flush here. This really isn't
2739 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2740 // (if your platform is syncing flushes and limiting them to 60fps).
2741 m_overMinimumLayoutThreshold = true;
2742 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2743 updateStyleIfNeeded();
2745 // Always do a layout after loading if needed.
2746 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2750 m_processingLoadEvent = false;
2752 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2753 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2754 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2755 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2756 // exists in the cache (we ignore the return value because we don't need it here). This is
2757 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2759 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2760 // catch new AND page history loads, and that uses AXLoadComplete
2762 axObjectCache()->getOrCreate(renderView());
2763 if (this == &topDocument())
2764 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2766 // AXLoadComplete can only be posted on the top document, so if it's a document
2767 // in an iframe that just finished loading, post AXLayoutComplete instead.
2768 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2773 if (svgExtensions())
2774 accessSVGExtensions().startAnimations();
2777 void Document::setParsing(bool b)
2781 if (m_bParsing && !m_sharedObjectPool)
2782 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2784 if (!m_bParsing && view() && !view()->needsLayout())
2785 view()->fireLayoutRelatedMilestonesIfNeeded();
2787 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2788 if (!ownerElement() && !m_bParsing)
2789 printf("Parsing finished at %lld\n", elapsedTime().count());
2793 bool Document::shouldScheduleLayout()
2795 // This function will only be called when FrameView thinks a layout is needed.
2796 // This enforces a couple extra rules.
2798 // (a) Only schedule a layout once the stylesheets are loaded.
2799 // (b) Only schedule layout once we have a body element.
2801 return (haveStylesheetsLoaded() && bodyOrFrameset())
2802 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2805 bool Document::isLayoutTimerActive()
2807 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2810 std::chrono::milliseconds Document::minimumLayoutDelay()
2812 if (m_overMinimumLayoutThreshold)
2813 return std::chrono::milliseconds(0);
2815 std::chrono::milliseconds elapsed = elapsedTime();
2816 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2818 // We'll want to schedule the timer to fire at the minimum layout threshold.
2819 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2822 std::chrono::milliseconds Document::elapsedTime() const
2824 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2826 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2829 void Document::write(const SegmentedString& text, Document* ownerDocument)
2831 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2833 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2834 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2836 if (m_writeRecursionIsTooDeep)
2839 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2840 if (!ownerElement())
2841 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2844 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2845 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2848 if (!hasInsertionPoint)
2849 open(ownerDocument);
2852 m_parser->insert(text);
2854 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2855 if (!ownerElement())
2856 printf("Ending a document.write at %lld\n", elapsedTime().count());
2860 void Document::write(const String& text, Document* ownerDocument)
2862 write(SegmentedString(text), ownerDocument);
2865 void Document::writeln(const String& text, Document* ownerDocument)
2867 write(text, ownerDocument);
2868 write("\n", ownerDocument);
2871 double Document::minimumTimerInterval() const
2873 Page* page = this->page();
2875 return ScriptExecutionContext::minimumTimerInterval();
2876 return page->settings().minimumDOMTimerInterval();
2879 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2881 if (m_isTimerThrottlingEnabled == shouldThrottle)
2884 m_isTimerThrottlingEnabled = shouldThrottle;
2885 didChangeTimerAlignmentInterval();
2888 double Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2890 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2891 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2892 return DOMTimer::hiddenPageAlignmentInterval();
2894 Page* page = this->page();
2896 return ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2897 return page->settings().domTimerAlignmentInterval();
2900 EventTarget* Document::errorEventTarget()
2902 return m_domWindow.get();
2905 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2907 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2910 void Document::setURL(const URL& url)
2912 const URL& newURL = url.isEmpty() ? blankURL() : url;
2913 if (newURL == m_url)
2917 m_documentURI = m_url.string();
2921 void Document::updateBaseURL()
2923 URL oldBaseURL = m_baseURL;
2924 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2925 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2926 // from the Document interface otherwise.
2927 if (!m_baseElementURL.isEmpty())
2928 m_baseURL = m_baseElementURL;
2929 else if (!m_baseURLOverride.isEmpty())
2930 m_baseURL = m_baseURLOverride;
2932 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2933 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2934 // and DOM 3 Core does not specify how it should be resolved.
2935 m_baseURL = URL(ParsedURLString, documentURI());
2938 clearSelectorQueryCache();
2940 if (!m_baseURL.isValid())
2943 if (m_elementSheet) {
2944 // Element sheet is silly. It never contains anything.
2945 ASSERT(!m_elementSheet->contents().ruleCount());
2946 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2947 bool usesStyleBasedEditability = m_elementSheet->contents().usesStyleBasedEditability();
2948 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2949 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2951 m_elementSheet->contents().parserSetUsesRemUnits();
2952 if (usesStyleBasedEditability)
2953 m_elementSheet->contents().parserSetUsesStyleBasedEditability();
2956 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2957 // Base URL change changes any relative visited links.
2958 // 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.
2959 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2960 anchor.invalidateCachedVisitedLinkHash();
2964 void Document::setBaseURLOverride(const URL& url)
2966 m_baseURLOverride = url;
2970 void Document::processBaseElement()
2972 // Find the first href attribute in a base element and the first target attribute in a base element.
2973 const AtomicString* href = nullptr;
2974 const AtomicString* target = nullptr;
2975 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2976 for (auto& base : baseDescendants) {
2978 const AtomicString& value = base.fastGetAttribute(hrefAttr);
2979 if (!value.isNull()) {
2986 const AtomicString& value = base.fastGetAttribute(targetAttr);
2987 if (!value.isNull()) {
2995 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2998 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2999 if (!strippedHref.isEmpty())
3000 baseElementURL = URL(url(), strippedHref);
3002 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3003 m_baseElementURL = baseElementURL;
3007 m_baseTarget = target ? *target : nullAtom;
3010 String Document::userAgent(const URL& url) const
3012 return frame() ? frame()->loader().userAgent(url) : String();
3015 void Document::disableEval(const String& errorMessage)
3020 frame()->script().disableEval(errorMessage);
3023 bool Document::canNavigate(Frame* targetFrame)
3028 // FIXME: We shouldn't call this function without a target frame, but
3029 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3030 // returning true when supplied with a 0 targetFrame.
3034 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
3035 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3038 if (isSandboxed(SandboxNavigation)) {
3039 if (targetFrame->tree().isDescendantOf(m_frame))
3042 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
3043 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
3044 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
3046 printNavigationErrorMessage(targetFrame, url(), reason);
3050 // This is the normal case. A document can navigate its decendant frames,
3051 // or, more generally, a document can navigate a frame if the document is
3052 // in the same origin as any of that frame's ancestors (in the frame
3055 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3056 // historical information about this security check.
3057 if (canAccessAncestor(securityOrigin(), targetFrame))
3060 // Top-level frames are easier to navigate than other frames because they
3061 // display their URLs in the address bar (in most browsers). However, there
3062 // are still some restrictions on navigation to avoid nuisance attacks.
3063 // Specifically, a document can navigate a top-level frame if that frame
3064 // opened the document or if the document is the same-origin with any of
3065 // the top-level frame's opener's ancestors (in the frame hierarchy).
3067 // In both of these cases, the document performing the navigation is in
3068 // some way related to the frame being navigate (e.g., by the "opener"
3069 // and/or "parent" relation). Requiring some sort of relation prevents a
3070 // document from navigating arbitrary, unrelated top-level frames.
3071 if (!targetFrame->tree().parent()) {
3072 if (targetFrame == m_frame->loader().opener())
3075 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3079 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3083 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3085 Frame* currentFrame = m_frame;
3089 Frame* ancestorFrame = currentFrame->tree().parent();
3091 while (ancestorFrame) {
3092 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3093 return currentFrame;
3094 currentFrame = ancestorFrame;
3095 ancestorFrame = ancestorFrame->tree().parent();
3100 void Document::didRemoveAllPendingStylesheet()
3102 m_needsNotifyRemoveAllPendingStylesheet = false;
3104 styleResolverChanged(DeferRecalcStyleIfNeeded);
3106 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3107 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3109 renderView()->repaintViewAndCompositedLayers();
3112 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3113 parser->executeScriptsWaitingForStylesheets();
3115 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3116 view()->scrollToFragment(m_url);
3119 CSSStyleSheet& Document::elementSheet()
3121 if (!m_elementSheet)
3122 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
3123 return *m_elementSheet;
3126 bool Document::usesStyleBasedEditability() const
3128 if (m_elementSheet && m_elementSheet->contents().usesStyleBasedEditability())
3131 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3132 ASSERT(!m_inStyleRecalc);
3134 auto& authorSheets = const_cast<AuthorStyleSheets&>(authorStyleSheets());
3135 authorSheets.flushPendingUpdates();
3136 return authorSheets.usesStyleBasedEditability();
3139 void Document::processHttpEquiv(const String& equiv, const String& content)
3141 ASSERT(!equiv.isNull() && !content.isNull());
3143 HttpEquivPolicy policy = httpEquivPolicy();
3144 if (policy != HttpEquivPolicy::Enabled) {
3147 case HttpEquivPolicy::Enabled:
3148 ASSERT_NOT_REACHED();
3150 case HttpEquivPolicy::DisabledBySettings:
3151 reason = "by the embedder.";
3153 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3154 reason = "for documents with Content-Disposition: attachment.";
3157 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3158 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3162 Frame* frame = this->frame();
3164 HTTPHeaderName headerName;
3165 if (!findHTTPHeaderName(equiv, headerName))
3168 switch (headerName) {
3169 case HTTPHeaderName::DefaultStyle:
3170 // The preferred style set has been overridden as per section
3171 // 14.3.2 of the HTML4.0 specification. We need to update the
3172 // sheet used variable and then update our style selector.
3173 // For more info, see the test at:
3174 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3176 authorStyleSheets().setSelectedStylesheetSetName(content);
3177 authorStyleSheets().setPreferredStylesheetSetName(content);
3178 styleResolverChanged(DeferRecalcStyle);
3181 case HTTPHeaderName::Refresh: {
3184 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
3186 if (urlString.isEmpty())
3187 completedURL = m_url;
3189 completedURL = completeURL(urlString);
3190 if (!protocolIsJavaScript(completedURL))
3191 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3193 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3194 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3201 case HTTPHeaderName::SetCookie:
3202 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3203 if (is<HTMLDocument>(*this)) {
3204 // Exception (for sandboxed documents) ignored.
3205 downcast<HTMLDocument>(*this).setCookie(content, IGNORE_EXCEPTION);
3209 case HTTPHeaderName::ContentLanguage:
3210 setContentLanguage(content);
3213 case HTTPHeaderName::XDNSPrefetchControl:
3214 parseDNSPrefetchControlHeader(content);
3217 case HTTPHeaderName::XFrameOptions:
3219 FrameLoader& frameLoader = frame->loader();
3220 unsigned long requestIdentifier = 0;
3221 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3222 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3223 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3224 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3225 frameLoader.stopAllLoaders();
3226 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3227 // intent, we must navigate away from the possibly partially-rendered document to a location that
3228 // doesn't inherit the parent's SecurityOrigin.
3229 frame->navigationScheduler().scheduleLocationChange(this, securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
3230 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3235 case HTTPHeaderName::ContentSecurityPolicy:
3236 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
3239 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
3240 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
3243 case HTTPHeaderName::XWebKitCSP:
3244 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
3247 case HTTPHeaderName::XWebKitCSPReportOnly:
3248 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
3256 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3257 static bool isSeparator(UChar c)
3259 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3262 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3264 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3265 unsigned keyBegin, keyEnd;
3266 unsigned valueBegin, valueEnd;
3268 String buffer = features.lower();
3269 unsigned length = buffer.length();
3270 for (unsigned i = 0; i < length; ) {
3271 // skip to first non-separator, but don't skip past the end of the string
3272 while (isSeparator(buffer[i])) {
3279 // skip to first separator
3280 while (!isSeparator(buffer[i]))
3284 // skip to first '=', but don't skip past a ',' or the end of the string
3285 while (buffer[i] != '=') {
3286 if (buffer[i] == ',' || i >= length)
3291 // skip to first non-separator, but don't skip past a ',' or the end of the string
3292 while (isSeparator(buffer[i])) {
3293 if (buffer[i] == ',' || i >= length)
3299 // skip to first separator
3300 while (!isSeparator(buffer[i]))
3304 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
3306 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3307 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3308 callback(keyString, valueString, this, data);
3312 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3314 ASSERT(!features.isNull());
3316 if (origin < m_viewportArguments.type)
3319 m_viewportArguments = ViewportArguments(origin);
3320 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3322 updateViewportArguments();
3325 void Document::updateViewportArguments()
3327 if (page() && frame()->isMainFrame()) {
3329 m_didDispatchViewportPropertiesChanged = true;
3331 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3333 page()->chrome().didReceiveDocType(frame());
3339 // FIXME: Find a better place for this functionality.
3340 void setParserFeature(const String& key, const String& value, Document* document, void*)
3342 if (key == "telephone" && equalIgnoringCase(value, "no"))
3343 document->setIsTelephoneNumberParsingAllowed(false);
3346 void Document::processFormatDetection(const String& features)
3348 ASSERT(!features.isNull());
3349 processArguments(features, nullptr, &setParserFeature);
3352 void Document::processWebAppOrientations()
3354 if (Page* page = this->page())
3355 page->chrome().client().webAppOrientationsUpdated();
3359 void Document::processReferrerPolicy(const String& policy)
3361 ASSERT(!policy.isNull());
3363 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3364 // even if the document has a meta tag saying otherwise.
3365 if (shouldEnforceContentDispositionAttachmentSandbox())
3368 // Note that we're supporting both the standard and legacy keywords for referrer
3369 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3370 if (equalIgnoringCase(policy, "no-referrer") || equalIgnoringCase(policy, "never"))
3371 setReferrerPolicy(ReferrerPolicyNever);
3372 else if (equalIgnoringCase(policy, "unsafe-url") || equalIgnoringCase(policy, "always"))
3373 setReferrerPolicy(ReferrerPolicyAlways);
3374 else if (equalIgnoringCase(policy, "origin"))
3375 setReferrerPolicy(ReferrerPolicyOrigin);
3376 else if (equalIgnoringCase(policy, "no-referrer-when-downgrade") || equalIgnoringCase(policy, "default"))
3377 setReferrerPolicy(ReferrerPolicyDefault);
3379 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'.");
3380 setReferrerPolicy(ReferrerPolicyNever);
3384 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3386 if (!hasLivingRenderTree())
3387 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3389 HitTestResult result(documentPoint);
3390 renderView()->hitTest(request, result);
3392 if (!request.readOnly())
3393 updateHoverActiveState(request, result.innerElement());
3395 return MouseEventWithHitTestResults(event, result);
3398 // DOM Section 1.1.1
3399 bool Document::childTypeAllowed(NodeType type) const
3402 case ATTRIBUTE_NODE:
3403 case CDATA_SECTION_NODE:
3404 case DOCUMENT_FRAGMENT_NODE:
3409 case PROCESSING_INSTRUCTION_NODE:
3411 case DOCUMENT_TYPE_NODE:
3413 // Documents may contain no more than one of each of these.
3414 // (One Element and one DocumentType.)
3415 for (Node* c = firstChild(); c; c = c->nextSibling())
3416 if (c->nodeType() == type)
3423 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3425 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3428 switch (newChild.nodeType()) {
3429 case ATTRIBUTE_NODE:
3430 case CDATA_SECTION_NODE:
3435 case PROCESSING_INSTRUCTION_NODE:
3437 case DOCUMENT_FRAGMENT_NODE: {
3438 bool hasSeenElementChild = false;
3439 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3440 if (is<Element>(*node)) {
3441 if (hasSeenElementChild)
3443 hasSeenElementChild = true;
3445 if (!canAcceptChild(*node, refChild, operation))
3450 case DOCUMENT_TYPE_NODE: {
3451 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3452 if (operation == AcceptChildOperation::Replace) {
3453 // parent has a doctype child that is not child, or an element is preceding child.
3454 if (existingDocType && existingDocType != refChild)
3456 if (refChild->previousElementSibling())
3459 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3460 if (existingDocType)
3462 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3467 case ELEMENT_NODE: {
3468 auto* existingElementChild = firstElementChild();
3469 if (operation == AcceptChildOperation::Replace) {
3470 if (existingElementChild && existingElementChild != refChild)
3472 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3473 if (is<DocumentType>(*child))
3477 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3478 if (existingElementChild)
3480 for (auto* child = refChild; child; child = child->nextSibling()) {
3481 if (is<DocumentType>(*child))
3491 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3493 Ref<Document> clone = cloneDocumentWithoutChildren();
3494 clone->cloneDataFromDocument(*this);
3496 case CloningOperation::OnlySelf:
3497 case CloningOperation::SelfWithTemplateContent:
3499 case CloningOperation::Everything:
3500 cloneChildNodes(clone);
3503 return WTFMove(clone);
3506 Ref<Document> Document::cloneDocumentWithoutChildren() const
3508 return isXHTMLDocument() ? createXHTML(nullptr, url()) : create(nullptr, url());
3511 void Document::cloneDataFromDocument(const Document& other)
3513 ASSERT(m_url == other.url());
3514 m_baseURL = other.baseURL();
3515 m_baseURLOverride = other.baseURLOverride();
3516 m_documentURI = other.documentURI();
3518 setCompatibilityMode(other.m_compatibilityMode);
3519 setSecurityOriginPolicy(other.securityOriginPolicy());
3520 overrideMIMEType(other.contentType());
3521 setDecoder(other.decoder());
3524 StyleSheetList& Document::styleSheets()
3526 if (!m_styleSheetList)
3527 m_styleSheetList = StyleSheetList::create(this);
3528 return *m_styleSheetList;
3531 String Document::preferredStylesheetSet() const
3533 return authorStyleSheets().preferredStylesheetSetName();
3536 String Document::selectedStylesheetSet() const
3538 return authorStyleSheets().selectedStylesheetSetName();
3541 void Document::setSelectedStylesheetSet(const String& aString)
3543 authorStyleSheets().setSelectedStylesheetSetName(aString);
3544 styleResolverChanged(DeferRecalcStyle);
3547 void Document::evaluateMediaQueryList()
3549 if (m_mediaQueryMatcher)
3550 m_mediaQueryMatcher->styleResolverChanged();
3552 checkViewportDependentPictures();
3555 void Document::checkViewportDependentPictures()
3557 Vector<HTMLPictureElement*, 16> changedPictures;
3558 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3559 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3560 if ((*it)->viewportChangeAffectedPicture())
3561 changedPictures.append(*it);
3563 for (auto* picture : changedPictures)
3564 picture->sourcesChanged();
3567 void Document::optimizedStyleSheetUpdateTimerFired()
3569 styleResolverChanged(RecalcStyleIfNeeded);
3572 void Document::scheduleOptimizedStyleSheetUpdate()
3574 if (m_optimizedStyleSheetUpdateTimer.isActive())
3576 authorStyleSheets().setPendingUpdateType(AuthorStyleSheets::OptimizedUpdate);
3577 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3580 void Document::updateViewportUnitsOnResize()
3582 if (!hasStyleWithViewportUnits())
3585 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3587 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3588 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3589 auto* renderer = element->renderer();
3590 if (renderer && renderer->style().hasViewportUnits())
3591 element->setNeedsStyleRecalc(InlineStyleChange);
3595 void Document::addAudioProducer(MediaProducer* audioProducer)
3597 m_audioProducers.add(audioProducer);
3598 updateIsPlayingMedia();
3601 void Document::removeAudioProducer(MediaProducer* audioProducer)
3603 m_audioProducers.remove(audioProducer);
3604 updateIsPlayingMedia();
3607 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3609 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3610 for (auto* audioProducer : m_audioProducers)
3611 state |= audioProducer->mediaState();
3613 #if ENABLE(MEDIA_SESSION)
3614 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3615 if (sourceElement->isPlaying())
3616 state |= MediaProducer::IsSourceElementPlaying;
3618 if (auto* session = sourceElement->session()) {
3619 if (auto* controls = session->controls()) {
3620 if (controls->previousTrackEnabled())
3621 state |= MediaProducer::IsPreviousTrackControlEnabled;
3622 if (controls->nextTrackEnabled())
3623 state |= MediaProducer::IsNextTrackControlEnabled;
3629 if (state == m_mediaState)
3632 m_mediaState = state;
3635 page()->updateIsPlayingMedia(sourceElementID);
3638 void Document::pageMutedStateDidChange()
3640 for (auto* audioProducer : m_audioProducers)
3641 audioProducer->pageMutedStateDidChange();
3644 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3646 if (m_optimizedStyleSheetUpdateTimer.isActive())
3647 m_optimizedStyleSheetUpdateTimer.stop();
3649 // Don't bother updating, since we haven't loaded all our style info yet
3650 // and haven't calculated the style selector for the first time.
3651 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3652 m_styleResolver = nullptr;