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, 2005, 2006, 2007, 2008, 2009, 2011, 2012, 2013 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
32 #include "AnimationController.h"
34 #include "CDATASection.h"
35 #include "CSSFontSelector.h"
36 #include "CSSStyleDeclaration.h"
37 #include "CSSStyleSheet.h"
38 #include "CachedCSSStyleSheet.h"
39 #include "CachedResourceLoader.h"
41 #include "ChromeClient.h"
43 #include "ContentSecurityPolicy.h"
44 #include "CookieJar.h"
45 #include "DOMImplementation.h"
46 #include "DOMNamedFlowCollection.h"
47 #include "DOMWindow.h"
48 #include "DateComponents.h"
49 #include "DebugPageOverlays.h"
50 #include "Dictionary.h"
51 #include "DocumentLoader.h"
52 #include "DocumentMarkerController.h"
53 #include "DocumentSharedObjectPool.h"
54 #include "DocumentType.h"
56 #include "ElementIterator.h"
57 #include "EntityReference.h"
58 #include "EventFactory.h"
59 #include "EventHandler.h"
60 #include "FocusController.h"
61 #include "FontLoader.h"
62 #include "FormController.h"
63 #include "FrameLoader.h"
64 #include "FrameLoaderClient.h"
65 #include "FrameView.h"
66 #include "HTMLAllCollection.h"
67 #include "HTMLAnchorElement.h"
68 #include "HTMLBaseElement.h"
69 #include "HTMLBodyElement.h"
70 #include "HTMLCanvasElement.h"
71 #include "HTMLCollection.h"
72 #include "HTMLDocument.h"
73 #include "HTMLElementFactory.h"
74 #include "HTMLFormControlElement.h"
75 #include "HTMLFrameOwnerElement.h"
76 #include "HTMLFrameSetElement.h"
77 #include "HTMLHeadElement.h"
78 #include "HTMLIFrameElement.h"
79 #include "HTMLImageElement.h"
80 #include "HTMLLinkElement.h"
81 #include "HTMLMediaElement.h"
82 #include "HTMLNameCollection.h"
83 #include "HTMLParserIdioms.h"
84 #include "HTMLPlugInElement.h"
85 #include "HTMLScriptElement.h"
86 #include "HTMLStyleElement.h"
87 #include "HTMLTitleElement.h"
88 #include "HTTPHeaderNames.h"
89 #include "HTTPParsers.h"
90 #include "HashChangeEvent.h"
92 #include "HitTestResult.h"
93 #include "IconController.h"
94 #include "ImageLoader.h"
95 #include "InspectorInstrumentation.h"
96 #include "JSLazyEventListener.h"
98 #include "LoaderStrategy.h"
100 #include "MainFrame.h"
101 #include "MediaCanStartListener.h"
102 #include "MediaProducer.h"
103 #include "MediaQueryList.h"
104 #include "MediaQueryMatcher.h"
105 #include "MouseEventWithHitTestResults.h"
106 #include "NameNodeList.h"
107 #include "NestingLevelIncrementer.h"
108 #include "NodeIterator.h"
109 #include "NodeRareData.h"
110 #include "NodeWithIndex.h"
111 #include "PageConsoleClient.h"
112 #include "PageGroup.h"
113 #include "PageTransitionEvent.h"
114 #include "PlatformLocale.h"
115 #include "PlatformStrategies.h"
116 #include "PlugInsResources.h"
117 #include "PluginDocument.h"
118 #include "PointerLockController.h"
119 #include "PopStateEvent.h"
120 #include "ProcessingInstruction.h"
121 #include "RenderChildIterator.h"
122 #include "RenderLayerCompositor.h"
123 #include "RenderView.h"
124 #include "RenderWidget.h"
125 #include "ResourceLoadScheduler.h"
126 #include "ResourceLoader.h"
127 #include "RuntimeEnabledFeatures.h"
128 #include "SVGDocumentExtensions.h"
129 #include "SVGElement.h"
130 #include "SVGElementFactory.h"
131 #include "SVGNames.h"
132 #include "SchemeRegistry.h"
133 #include "ScopedEventQueue.h"
134 #include "ScriptController.h"
135 #include "ScriptRunner.h"
136 #include "ScriptSourceCode.h"
137 #include "ScrollingCoordinator.h"
138 #include "SecurityOrigin.h"
139 #include "SecurityOriginPolicy.h"
140 #include "SecurityPolicy.h"
141 #include "SegmentedString.h"
142 #include "SelectorQuery.h"
143 #include "Settings.h"
144 #include "ShadowRoot.h"
145 #include "StyleProperties.h"
146 #include "StyleResolver.h"
147 #include "StyleSheetContents.h"
148 #include "StyleSheetList.h"
149 #include "TextNodeTraversal.h"
150 #include "TextResourceDecoder.h"
151 #include "TransformSource.h"
152 #include "TreeWalker.h"
153 #include "VisitedLinkState.h"
154 #include "XMLDocumentParser.h"
155 #include "XMLNSNames.h"
156 #include "XMLNames.h"
157 #include "XPathEvaluator.h"
158 #include "XPathExpression.h"
159 #include "XPathNSResolver.h"
160 #include "XPathResult.h"
161 #include "htmlediting.h"
162 #include <JavaScriptCore/Profile.h>
163 #include <inspector/ScriptCallStack.h>
164 #include <wtf/CurrentTime.h>
165 #include <wtf/TemporaryChange.h>
166 #include <wtf/text/StringBuffer.h>
167 #include <yarr/RegularExpression.h>
170 #include "XSLTProcessor.h"
174 #if ENABLE(TOUCH_EVENTS)
175 #include "TouchList.h"
179 #include "CSSFontSelector.h"
180 #include "DeviceMotionClientIOS.h"
181 #include "DeviceMotionController.h"
182 #include "DeviceOrientationClientIOS.h"
183 #include "DeviceOrientationController.h"
184 #include "Geolocation.h"
185 #include "Navigator.h"
186 #include "NavigatorGeolocation.h"
187 #include "WKContentObservation.h"
188 #include "WebCoreSystemInterface.h"
191 #if ENABLE(IOS_GESTURE_EVENTS)
192 #include "GestureEvent.h"
196 #include "MathMLElement.h"
197 #include "MathMLElementFactory.h"
198 #include "MathMLNames.h"
201 #if ENABLE(FULLSCREEN_API)
202 #include "RenderFullScreen.h"
205 #if ENABLE(REQUEST_ANIMATION_FRAME)
206 #include "RequestAnimationFrameCallback.h"
207 #include "ScriptedAnimationController.h"
210 #if ENABLE(IOS_TEXT_AUTOSIZING)
211 #include "TextAutoSizing.h"
214 #if ENABLE(TEXT_AUTOSIZING)
215 #include "TextAutosizer.h"
219 #include "DOMSecurityPolicy.h"
222 #if ENABLE(VIDEO_TRACK)
223 #include "CaptionUserPreferences.h"
226 #if ENABLE(WEB_REPLAY)
227 #include "WebReplayInputs.h"
228 #include <replay/EmptyInputCursor.h>
229 #include <replay/InputCursor.h>
232 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
233 #include "MediaPlaybackTargetClient.h"
237 using namespace Unicode;
241 using namespace HTMLNames;
243 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
245 static const unsigned cMaxWriteRecursionDepth = 21;
247 // DOM Level 2 says (letters added):
249 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
250 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
251 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
252 // 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.
253 // 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.
254 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
255 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
256 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
257 // i) Characters ':' and '_' are allowed as name-start characters.
258 // j) Characters '-' and '.' are allowed as name characters.
260 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
262 static inline bool isValidNameStart(UChar32 c)
265 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
269 if (c == ':' || c == '_')
272 // rules (a) and (f) above
273 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)))
277 if (c >= 0xF900 && c < 0xFFFE)
281 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
282 if (type == U_DT_FONT || type == U_DT_COMPAT)
288 static inline bool isValidNamePart(UChar32 c)
290 // rules (a), (e), and (i) above
291 if (isValidNameStart(c))
294 // rules (g) and (h) above
295 if (c == 0x00B7 || c == 0x0387)
299 if (c == '-' || c == '.')
302 // rules (b) and (f) above
303 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
307 if (c >= 0xF900 && c < 0xFFFE)
311 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
312 if (type == U_DT_FONT || type == U_DT_COMPAT)
318 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
320 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
322 // If a Document has the address "about:blank"
323 // The origin of the Document is the origin it was assigned when its browsing context was created.
325 // Note: We generalize this to all "blank" URLs and invalid URLs because we
326 // treat all of these URLs as about:blank.
328 return url.isEmpty() || url.isBlankURL();
331 static Widget* widgetForElement(Element* focusedElement)
335 auto* renderer = focusedElement->renderer();
336 if (!is<RenderWidget>(renderer))
338 return downcast<RenderWidget>(*renderer).widget();
341 static bool acceptsEditingFocus(Node* node)
344 ASSERT(node->hasEditableStyle());
346 Node* root = node->rootEditableElement();
347 Frame* frame = node->document().frame();
351 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
354 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
356 // targetFrame can be 0 when we're trying to navigate a top-level frame
357 // that has a 0 opener.
361 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
362 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
363 Document* ancestorDocument = ancestorFrame->document();
364 // FIXME: Should be an ASSERT? Frames should alway have documents.
365 if (!ancestorDocument)
368 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
369 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
372 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
373 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
374 // something more general instead?
375 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
382 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
384 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
386 // FIXME: should we print to the console of the document performing the navigation instead?
387 frame->document()->domWindow()->printErrorMessage(message);
390 uint64_t Document::s_globalTreeVersion = 0;
392 #if ENABLE(IOS_TEXT_AUTOSIZING)
393 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
395 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
398 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
400 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
404 HashSet<Document*>& Document::allDocuments()
406 static NeverDestroyed<HashSet<Document*>> documents;
410 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
411 : ContainerNode(*this, CreateDocument)
413 #if ENABLE(IOS_TOUCH_EVENTS)
414 , m_handlingTouchEvent(false)
415 , m_touchEventRegionsDirty(false)
416 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
418 , m_referencingNodeCount(0)
419 , m_didCalculateStyleResolver(false)
420 , m_hasNodesWithPlaceholderStyle(false)
421 , m_needsNotifyRemoveAllPendingStylesheet(false)
422 , m_ignorePendingStylesheets(false)
423 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
425 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
426 , m_activeParserCount(0)
427 , m_wellFormed(false)
429 , m_paginatedForScreen(false)
430 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
431 , m_compatibilityModeLocked(false)
432 , m_textColor(Color::black)
433 , m_domTreeVersion(++s_globalTreeVersion)
435 , m_mutationObserverTypes(0)
436 , m_styleSheetCollection(*this)
437 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
438 , m_visuallyOrdered(false)
439 , m_readyState(Complete)
441 , m_optimizedStyleSheetUpdateTimer(*this, &Document::optimizedStyleSheetUpdateTimerFired)
442 , m_styleRecalcTimer(*this, &Document::styleRecalcTimerFired)
443 , m_pendingStyleRecalcShouldForce(false)
444 , m_inStyleRecalc(false)
445 , m_closeAfterStyleRecalc(false)
446 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
447 , m_frameElementsShouldIgnoreScrolling(false)
448 , m_updateFocusAppearanceRestoresSelection(false)
449 , m_ignoreDestructiveWriteCount(0)
450 , m_titleSetExplicitly(false)
451 , m_markers(std::make_unique<DocumentMarkerController>())
452 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
453 , m_cssTarget(nullptr)
454 , m_processingLoadEvent(false)
455 , m_loadEventFinished(false)
456 , m_startTime(std::chrono::steady_clock::now())
457 , m_overMinimumLayoutThreshold(false)
458 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
459 , m_xmlVersion(ASCIILiteral("1.0"))
460 , m_xmlStandalone(StandaloneUnspecified)
461 , m_hasXMLDeclaration(false)
462 , m_designMode(inherit)
464 , m_inInvalidateNodeListAndCollectionCaches(false)
466 #if ENABLE(DASHBOARD_SUPPORT)
467 , m_hasAnnotatedRegions(false)
468 , m_annotatedRegionsDirty(false)
470 , m_createRenderers(true)
471 , m_inPageCache(false)
472 , m_accessKeyMapValid(false)
473 , m_documentClasses(documentClasses)
474 , m_isSynthesized(constructionFlags & Synthesized)
475 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
476 , m_sawElementsInKnownNamespaces(false)
477 , m_isSrcdocDocument(false)
478 , m_eventQueue(*this)
479 , m_weakFactory(this)
480 #if ENABLE(FULLSCREEN_API)
481 , m_areKeysEnabledInFullScreen(0)
482 , m_fullScreenRenderer(nullptr)
483 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
484 , m_isAnimatingFullScreen(false)
486 , m_loadEventDelayCount(0)
487 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
488 , m_referrerPolicy(ReferrerPolicyDefault)
489 , m_directionSetOnDocumentElement(false)
490 , m_writingModeSetOnDocumentElement(false)
491 , m_writeRecursionIsTooDeep(false)
492 , m_writeRecursionDepth(0)
493 , m_lastHandledUserGestureTimestamp(0)
495 #if ENABLE(DEVICE_ORIENTATION)
496 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
497 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
498 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
499 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
502 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
503 , m_isTelephoneNumberParsingAllowed(true)
505 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
506 , m_scheduledTasksAreSuspended(false)
507 , m_visualUpdatesAllowed(true)
508 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
509 , m_sharedObjectPoolClearTimer(*this, &Document::sharedObjectPoolClearTimerFired)
511 , m_didDispatchViewportPropertiesChanged(false)
513 #if ENABLE(TEMPLATE_ELEMENT)
514 , m_templateDocumentHost(nullptr)
516 #if ENABLE(WEB_REPLAY)
517 , m_inputCursor(EmptyInputCursor::create())
519 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
520 , m_cookieCacheExpiryTimer(*this, &Document::domCookieCacheExpiryTimerFired)
521 , m_disabledFieldsetElementsCount(0)
522 , m_hasInjectedPlugInsScript(false)
523 , m_renderTreeBeingDestroyed(false)
524 , m_hasPreparedForDestruction(false)
525 , m_hasStyleWithViewportUnits(false)
527 allDocuments().add(this);
529 // We depend on the url getting immediately set in subframes, but we
530 // also depend on the url NOT getting immediately set in opened windows.
531 // See fast/dom/early-frame-url.html
532 // and fast/dom/location-new-window-no-crash.html, respectively.
533 // FIXME: Can/should we unify this behavior?
534 if ((frame && frame->ownerElement()) || !url.isEmpty())
537 m_cachedResourceLoader->setDocument(this);
539 #if ENABLE(TEXT_AUTOSIZING)
540 m_textAutosizer = std::make_unique<TextAutosizer>(this);
544 resetVisitedLinkColor();
545 resetActiveLinkColor();
547 initSecurityContext();
550 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
551 m_nodeListAndCollectionCounts[i] = 0;
554 #if ENABLE(FULLSCREEN_API)
555 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
560 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
562 } while ((owner = owner->document().ownerElement()));
567 Ref<Document> Document::create(ScriptExecutionContext& context)
569 Ref<Document> document = adoptRef(*new Document(nullptr, URL()));
570 document->setSecurityOriginPolicy(context.securityOriginPolicy());
575 Document::~Document()
577 allDocuments().remove(this);
579 ASSERT(!renderView());
580 ASSERT(!m_inPageCache);
581 ASSERT(m_ranges.isEmpty());
582 ASSERT(!m_parentTreeScope);
583 ASSERT(!m_disabledFieldsetElementsCount);
585 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
586 m_deviceMotionClient->deviceMotionControllerDestroyed();
587 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
590 #if ENABLE(TEMPLATE_ELEMENT)
591 if (m_templateDocument)
592 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
595 // FIXME: Should we reset m_domWindow when we detach from the Frame?
597 m_domWindow->resetUnlessSuspendedForPageCache();
599 m_scriptRunner = nullptr;
601 removeAllEventListeners();
603 // Currently we believe that Document can never outlive the parser.
604 // Although the Document may be replaced synchronously, DocumentParsers
605 // generally keep at least one reference to an Element which would in turn
606 // has a reference to the Document. If you hit this ASSERT, then that
607 // assumption is wrong. DocumentParser::detach() should ensure that even
608 // if the DocumentParser outlives the Document it won't cause badness.
609 ASSERT(!m_parser || m_parser->refCount() == 1);
612 if (this == &topDocument())
613 clearAXObjectCache();
617 if (m_styleSheetList)
618 m_styleSheetList->detachFromDocument();
621 m_elementSheet->detachFromDocument();
622 m_styleSheetCollection.detachFromDocument();
624 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
626 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
627 // load the initial empty document and the SVGDocument with the same DocumentLoader).
628 if (m_cachedResourceLoader->document() == this)
629 m_cachedResourceLoader->setDocument(nullptr);
631 // We must call clearRareData() here since a Document class inherits TreeScope
632 // as well as Node. See a comment on TreeScope.h for the reason.
636 ASSERT(!m_listsInvalidatedAtDocument.size());
637 ASSERT(!m_collectionsInvalidatedAtDocument.size());
639 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
640 ASSERT(!m_nodeListAndCollectionCounts[i]);
643 void Document::removedLastRef()
645 ASSERT(!m_deletionHasBegun);
646 if (m_referencingNodeCount) {
647 // If removing a child removes the last node reference, we don't want the scope to be destroyed
648 // until after removeDetachedChildren returns, so we protect ourselves.
649 incrementReferencingNodeCount();
651 // We must make sure not to be retaining any of our children through
652 // these extra pointers or we will create a reference cycle.
653 m_focusedElement = nullptr;
654 m_hoveredElement = nullptr;
655 m_activeElement = nullptr;
656 m_titleElement = nullptr;
657 m_documentElement = nullptr;
658 m_userActionElements.documentDidRemoveLastRef();
659 #if ENABLE(FULLSCREEN_API)
660 m_fullScreenElement = nullptr;
661 m_fullScreenElementStack.clear();
666 // removeDetachedChildren() doesn't always unregister IDs,
667 // so tear down scope information up front to avoid having
668 // stale references in the map.
670 destroyTreeScopeData();
671 removeDetachedChildren();
672 m_formController = nullptr;
676 m_cssCanvasElements.clear();
681 // We need to do this right now since selfOnlyDeref() can delete this.
682 m_inRemovedLastRefFunction = false;
684 decrementReferencingNodeCount();
687 m_inRemovedLastRefFunction = false;
688 m_deletionHasBegun = true;
694 void Document::commonTeardown()
697 accessSVGExtensions().pauseAnimations();
699 #if ENABLE(REQUEST_ANIMATION_FRAME)
700 clearScriptedAnimationController();
704 Element* Document::getElementByAccessKey(const String& key)
708 if (!m_accessKeyMapValid) {
709 buildAccessKeyMap(this);
710 m_accessKeyMapValid = true;
712 return m_elementsByAccessKey.get(key.impl());
715 void Document::buildAccessKeyMap(TreeScope* scope)
718 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
719 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
720 if (!accessKey.isEmpty())
721 m_elementsByAccessKey.set(accessKey.impl(), &element);
723 if (ShadowRoot* root = element.shadowRoot())
724 buildAccessKeyMap(root);
728 void Document::invalidateAccessKeyMap()
730 m_accessKeyMapValid = false;
731 m_elementsByAccessKey.clear();
734 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
736 return m_imagesByUsemap.add(name, element, *this);
739 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
741 return m_imagesByUsemap.remove(name, element);
744 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
746 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
749 SelectorQuery* Document::selectorQueryForString(const String& selectorString, ExceptionCode& ec)
751 if (selectorString.isEmpty()) {
756 if (!m_selectorQueryCache)
757 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
758 return m_selectorQueryCache->add(selectorString, *this, ec);
761 void Document::clearSelectorQueryCache()
763 m_selectorQueryCache = nullptr;
766 MediaQueryMatcher& Document::mediaQueryMatcher()
768 if (!m_mediaQueryMatcher)
769 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
770 return *m_mediaQueryMatcher;
773 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
775 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
777 bool wasInQuirksMode = inQuirksMode();
778 m_compatibilityMode = mode;
780 clearSelectorQueryCache();
782 if (inQuirksMode() != wasInQuirksMode) {
783 // All user stylesheets have to reparse using the different mode.
784 m_styleSheetCollection.clearPageUserSheet();
785 m_styleSheetCollection.invalidateInjectedStyleSheetCache();
789 String Document::compatMode() const
791 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
794 void Document::resetLinkColor()
796 m_linkColor = Color(0, 0, 238);
799 void Document::resetVisitedLinkColor()
801 m_visitedLinkColor = Color(85, 26, 139);
804 void Document::resetActiveLinkColor()
806 m_activeLinkColor.setNamedColor("red");
809 DOMImplementation& Document::implementation()
811 if (!m_implementation)
812 m_implementation = std::make_unique<DOMImplementation>(*this);
813 return *m_implementation;
816 bool Document::hasManifest() const
818 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->fastHasAttribute(manifestAttr);
821 DocumentType* Document::doctype() const
823 for (Node* node = firstChild(); node; node = node->nextSibling()) {
824 if (node->isDocumentTypeNode())
825 return static_cast<DocumentType*>(node);
830 void Document::childrenChanged(const ChildChange& change)
832 ContainerNode::childrenChanged(change);
835 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
836 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
837 // otherwise, we need to detect the doc type changes before updating the viewport.
838 if (Page* page = this->page())
839 page->chrome().didReceiveDocType(frame());
842 Element* newDocumentElement = childrenOfType<Element>(*this).first();
843 if (newDocumentElement == m_documentElement)
845 m_documentElement = newDocumentElement;
846 // The root style used for media query matching depends on the document element.
847 clearStyleResolver();
850 RefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
852 if (!isValidName(name)) {
853 ec = INVALID_CHARACTER_ERR;
857 if (isXHTMLDocument())
858 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
860 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
863 Ref<DocumentFragment> Document::createDocumentFragment()
865 return DocumentFragment::create(document());
868 Ref<Text> Document::createTextNode(const String& data)
870 return Text::create(*this, data);
873 Ref<Comment> Document::createComment(const String& data)
875 return Comment::create(*this, data);
878 RefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
880 if (isHTMLDocument()) {
881 ec = NOT_SUPPORTED_ERR;
884 return CDATASection::create(*this, data);
887 RefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
889 if (!isValidName(target)) {
890 ec = INVALID_CHARACTER_ERR;
893 if (isHTMLDocument()) {
894 ec = NOT_SUPPORTED_ERR;
897 return ProcessingInstruction::create(*this, target, data);
900 RefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
902 if (!isValidName(name)) {
903 ec = INVALID_CHARACTER_ERR;
906 if (isHTMLDocument()) {
907 ec = NOT_SUPPORTED_ERR;
910 return EntityReference::create(*this, name);
913 Ref<Text> Document::createEditingTextNode(const String& text)
915 return Text::createEditingText(*this, text);
918 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
920 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
921 return *propertySet->ensureCSSStyleDeclaration();
924 RefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
927 ec = NOT_SUPPORTED_ERR;
931 switch (importedNode->nodeType()) {
934 case CDATA_SECTION_NODE:
935 case ENTITY_REFERENCE_NODE:
936 case PROCESSING_INSTRUCTION_NODE:
938 case DOCUMENT_FRAGMENT_NODE:
939 return importedNode->cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
942 // FIXME: This will "Attr::normalize" child nodes of Attr.
943 return Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(*importedNode).name(), nullAtom), downcast<Attr>(*importedNode).value());
945 case DOCUMENT_NODE: // Can't import a document into another document.
946 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
950 case XPATH_NAMESPACE_NODE:
951 ASSERT_NOT_REACHED(); // These two types of DOM nodes are not implemented.
954 ec = NOT_SUPPORTED_ERR;
959 RefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
962 ec = NOT_SUPPORTED_ERR;
966 if (source->isReadOnlyNode()) {
967 ec = NO_MODIFICATION_ALLOWED_ERR;
971 EventQueueScope scope;
973 switch (source->nodeType()) {
976 case DOCUMENT_TYPE_NODE:
977 case XPATH_NAMESPACE_NODE:
978 ec = NOT_SUPPORTED_ERR;
980 case ATTRIBUTE_NODE: {
981 Attr& attr = downcast<Attr>(*source);
982 if (attr.ownerElement())
983 attr.ownerElement()->removeAttributeNode(&attr, ec);
987 if (source->isShadowRoot()) {
988 // ShadowRoot cannot disconnect itself from the host node.
989 ec = HIERARCHY_REQUEST_ERR;
992 if (is<HTMLFrameOwnerElement>(*source)) {
993 HTMLFrameOwnerElement& frameOwnerElement = downcast<HTMLFrameOwnerElement>(*source);
994 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
995 ec = HIERARCHY_REQUEST_ERR;
999 if (source->parentNode()) {
1000 source->parentNode()->removeChild(source.get(), ec);
1006 adoptIfNeeded(source.get());
1011 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1013 // These checks are from DOM Core Level 2, createElementNS
1014 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1015 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1017 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1020 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1021 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1022 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1023 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1024 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1025 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1028 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1030 return hasValidNamespaceForElements(qName);
1033 // FIXME: This should really be in a possible ElementFactory class.
1034 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1036 RefPtr<Element> element;
1038 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1039 if (name.namespaceURI() == xhtmlNamespaceURI)
1040 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1041 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1042 element = SVGElementFactory::createElement(name, *this, createdByParser);
1044 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1045 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1049 m_sawElementsInKnownNamespaces = true;
1051 element = Element::create(name, document());
1053 // <image> uses imgTag so we need a special rule.
1054 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1056 return element.releaseNonNull();
1059 bool Document::cssRegionsEnabled() const
1061 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1064 bool Document::cssCompositingEnabled() const
1066 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1069 #if ENABLE(CSS_REGIONS)
1071 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1073 if (!cssRegionsEnabled() || !renderView())
1076 updateStyleIfNeeded();
1078 return namedFlows().createCSSOMSnapshot();
1083 NamedFlowCollection& Document::namedFlows()
1086 m_namedFlows = NamedFlowCollection::create(this);
1088 return *m_namedFlows;
1091 RefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1093 String prefix, localName;
1094 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1097 QualifiedName qName(prefix, localName, namespaceURI);
1098 if (!hasValidNamespaceForElements(qName)) {
1103 return createElement(qName, false);
1106 String Document::readyState() const
1108 DEPRECATED_DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1109 DEPRECATED_DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1110 DEPRECATED_DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1112 switch (m_readyState) {
1121 ASSERT_NOT_REACHED();
1125 void Document::setReadyState(ReadyState readyState)
1127 if (readyState == m_readyState)
1130 #if ENABLE(WEB_TIMING)
1131 switch (readyState) {
1133 if (!m_documentTiming.domLoading)
1134 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1137 if (!m_documentTiming.domInteractive)
1138 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1141 if (!m_documentTiming.domComplete)
1142 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1147 m_readyState = readyState;
1148 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1150 if (settings() && settings()->suppressesIncrementalRendering())
1151 setVisualUpdatesAllowed(readyState);
1154 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1156 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1157 switch (readyState) {
1159 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1160 ASSERT(m_visualUpdatesAllowed);
1161 setVisualUpdatesAllowed(false);
1164 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1167 if (m_visualUpdatesSuppressionTimer.isActive()) {
1168 ASSERT(!m_visualUpdatesAllowed);
1170 if (!view()->visualUpdatesAllowedByClient())
1173 setVisualUpdatesAllowed(true);
1175 ASSERT(m_visualUpdatesAllowed);
1180 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1182 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1185 m_visualUpdatesAllowed = visualUpdatesAllowed;
1187 if (visualUpdatesAllowed)
1188 m_visualUpdatesSuppressionTimer.stop();
1190 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1192 if (!visualUpdatesAllowed)
1195 FrameView* frameView = view();
1196 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1200 if (Page* page = this->page()) {
1201 if (frame()->isMainFrame()) {
1202 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1203 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1204 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1209 view()->updateCompositingLayersAfterLayout();
1211 if (RenderView* renderView = this->renderView())
1212 renderView->repaintViewAndCompositedLayers();
1214 if (Frame* frame = this->frame())
1215 frame->loader().forcePageTransitionIfNeeded();
1218 void Document::visualUpdatesSuppressionTimerFired()
1220 ASSERT(!m_visualUpdatesAllowed);
1222 // If the client is extending the visual update suppression period explicitly, the
1223 // watchdog should not re-enable visual updates itself, but should wait for the client.
1224 if (!view()->visualUpdatesAllowedByClient())
1227 setVisualUpdatesAllowed(true);
1230 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1232 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1233 // both of which we can determine by looking at the timer.
1235 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1236 setVisualUpdatesAllowed(true);
1239 AtomicString Document::encoding() const
1241 if (TextResourceDecoder* d = decoder())
1242 return d->encoding().domName();
1246 String Document::defaultCharset() const
1248 if (Settings* settings = this->settings())
1249 return settings->defaultTextEncodingName();
1253 void Document::setCharset(const String& charset)
1257 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1260 void Document::setContentLanguage(const String& language)
1262 if (m_contentLanguage == language)
1264 m_contentLanguage = language;
1266 // Recalculate style so language is used when selecting the initial font.
1267 styleResolverChanged(DeferRecalcStyle);
1270 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1272 if (!implementation().hasFeature("XML", String())) {
1273 ec = NOT_SUPPORTED_ERR;
1277 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1278 ec = NOT_SUPPORTED_ERR;
1282 m_xmlVersion = version;
1285 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1287 if (!implementation().hasFeature("XML", String())) {
1288 ec = NOT_SUPPORTED_ERR;
1292 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1295 void Document::setDocumentURI(const String& uri)
1297 // This property is read-only from JavaScript, but writable from Objective-C.
1298 m_documentURI = uri;
1302 URL Document::baseURI() const
1307 void Document::setContent(const String& content)
1310 // FIXME: This should probably use insert(), but that's (intentionally)
1311 // not implemented for the XML parser as it's normally synonymous with
1312 // document.write(). append() will end up yielding, but close() will
1313 // pump the tokenizer syncrhonously and finish the parse.
1314 m_parser->append(content.impl());
1318 String Document::suggestedMIMEType() const
1320 if (isXHTMLDocument())
1321 return ASCIILiteral("application/xhtml+xml");
1322 if (isSVGDocument())
1323 return ASCIILiteral("image/svg+xml");
1324 if (xmlStandalone())
1325 return ASCIILiteral("text/xml");
1326 if (isHTMLDocument())
1327 return ASCIILiteral("text/html");
1328 if (DocumentLoader* loader = this->loader())
1329 return loader->responseMIMEType();
1333 void Document::overrideMIMEType(const String& mimeType)
1335 m_overriddenMIMEType = mimeType;
1338 String Document::contentType() const
1340 if (!m_overriddenMIMEType.isNull())
1341 return m_overriddenMIMEType;
1343 if (DocumentLoader* documentLoader = loader())
1344 return documentLoader->currentContentType();
1346 String mimeType = suggestedMIMEType();
1347 if (!mimeType.isNull())
1350 return ASCIILiteral("application/xml");
1353 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1355 if (!frame() || !view())
1358 Frame& frame = *this->frame();
1360 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1362 LayoutPoint contentsPoint = clientPoint;
1363 contentsPoint.scale(scaleFactor, scaleFactor);
1364 contentsPoint.moveBy(view()->contentsScrollPosition());
1366 LayoutRect visibleRect;
1368 visibleRect = view()->unobscuredContentRect();
1370 visibleRect = view()->visibleContentRect();
1372 if (!visibleRect.contains(contentsPoint))
1375 HitTestResult result(contentsPoint);
1376 renderView()->hitTest(HitTestRequest(), result);
1379 *localPoint = result.localPoint();
1381 return result.innerNode();
1384 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1386 if (!hasLivingRenderTree())
1389 Node* node = nodeFromPoint(clientPoint);
1390 while (node && !is<Element>(*node))
1391 node = node->parentNode();
1394 node = ancestorInThisScope(node);
1396 return downcast<Element>(node);
1399 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1401 return caretRangeFromPoint(LayoutPoint(x, y));
1404 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1406 if (!hasLivingRenderTree())
1409 LayoutPoint localPoint;
1410 Node* node = nodeFromPoint(clientPoint, &localPoint);
1414 Node* shadowAncestorNode = ancestorInThisScope(node);
1415 if (shadowAncestorNode != node) {
1416 unsigned offset = shadowAncestorNode->computeNodeIndex();
1417 ContainerNode* container = shadowAncestorNode->parentNode();
1418 return Range::create(*this, container, offset, container, offset);
1421 RenderObject* renderer = node->renderer();
1424 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1425 if (visiblePosition.isNull())
1428 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1429 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1433 * Performs three operations:
1434 * 1. Convert control characters to spaces
1435 * 2. Trim leading and trailing spaces
1436 * 3. Collapse internal whitespace.
1438 template <typename CharacterType>
1439 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1441 const String& title = titleWithDirection.string();
1442 const CharacterType* characters = title.characters<CharacterType>();
1443 unsigned length = title.length();
1446 StringBuffer<CharacterType> buffer(length);
1447 unsigned builderIndex = 0;
1449 // Skip leading spaces and leading characters that would convert to spaces
1450 for (i = 0; i < length; ++i) {
1451 CharacterType c = characters[i];
1452 if (!(c <= 0x20 || c == 0x7F))
1457 return StringWithDirection();
1459 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1460 bool previousCharWasWS = false;
1461 for (; i < length; ++i) {
1462 CharacterType c = characters[i];
1463 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1464 if (previousCharWasWS)
1466 buffer[builderIndex++] = ' ';
1467 previousCharWasWS = true;
1469 buffer[builderIndex++] = c;
1470 previousCharWasWS = false;
1474 // Strip trailing spaces
1475 while (builderIndex > 0) {
1477 if (buffer[builderIndex] != ' ')
1481 if (!builderIndex && buffer[builderIndex] == ' ')
1482 return StringWithDirection();
1484 buffer.shrink(builderIndex + 1);
1486 // Replace the backslashes with currency symbols if the encoding requires it.
1487 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1489 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1492 void Document::updateTitle(const StringWithDirection& title)
1494 if (m_rawTitle == title)
1499 if (m_rawTitle.string().isEmpty())
1500 m_title = StringWithDirection();
1502 if (m_rawTitle.string().is8Bit())
1503 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1505 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1507 if (DocumentLoader* loader = this->loader())
1508 loader->setTitle(m_title);
1511 void Document::setTitle(const String& title)
1513 // Title set by JavaScript -- overrides any title elements.
1514 m_titleSetExplicitly = true;
1515 if (!isHTMLDocument() && !isXHTMLDocument())
1516 m_titleElement = nullptr;
1517 else if (!m_titleElement) {
1518 if (HTMLElement* headElement = head()) {
1519 m_titleElement = createElement(titleTag, false);
1520 headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION);
1524 // The DOM API has no method of specifying direction, so assume LTR.
1525 updateTitle(StringWithDirection(title, LTR));
1527 if (is<HTMLTitleElement>(m_titleElement.get()))
1528 downcast<HTMLTitleElement>(*m_titleElement).setText(title);
1531 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1533 if (titleElement != m_titleElement) {
1534 if (m_titleElement || m_titleSetExplicitly) {
1535 // Only allow the first title element to change the title -- others have no effect.
1538 m_titleElement = titleElement;
1544 void Document::removeTitle(Element* titleElement)
1546 if (m_titleElement != titleElement)
1549 m_titleElement = nullptr;
1550 m_titleSetExplicitly = false;
1552 // Update title based on first title element in the head, if one exists.
1553 if (HTMLElement* headElement = head()) {
1554 if (auto firstTitle = childrenOfType<HTMLTitleElement>(*headElement).first())
1555 setTitleElement(firstTitle->textWithDirection(), firstTitle);
1558 if (!m_titleElement)
1559 updateTitle(StringWithDirection());
1562 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1564 m_visibilityStateCallbackElements.add(element);
1567 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1569 m_visibilityStateCallbackElements.remove(element);
1572 void Document::visibilityStateChanged()
1574 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1575 for (auto* element : m_visibilityStateCallbackElements)
1576 element->visibilityStateChanged();
1579 PageVisibilityState Document::pageVisibilityState() const
1581 // The visibility of the document is inherited from the visibility of the
1582 // page. If there is no page associated with the document, we will assume
1583 // that the page is hidden, as specified by the spec:
1584 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1585 if (!m_frame || !m_frame->page())
1586 return PageVisibilityStateHidden;
1587 return m_frame->page()->visibilityState();
1590 String Document::visibilityState() const
1592 return pageVisibilityStateString(pageVisibilityState());
1595 bool Document::hidden() const
1597 return pageVisibilityState() != PageVisibilityStateVisible;
1600 #if ENABLE(CSP_NEXT)
1601 DOMSecurityPolicy& Document::securityPolicy()
1603 if (!m_domSecurityPolicy)
1604 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1605 return *m_domSecurityPolicy;
1609 String Document::nodeName() const
1614 Node::NodeType Document::nodeType() const
1616 return DOCUMENT_NODE;
1619 FormController& Document::formController()
1621 if (!m_formController)
1622 m_formController = std::make_unique<FormController>();
1623 return *m_formController;
1626 Vector<String> Document::formElementsState() const
1628 if (!m_formController)
1629 return Vector<String>();
1630 return m_formController->formElementsState();
1633 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1635 if (!stateVector.size() && !m_formController)
1637 formController().setStateForNewFormElements(stateVector);
1640 FrameView* Document::view() const
1642 return m_frame ? m_frame->view() : nullptr;
1645 Page* Document::page() const
1647 return m_frame ? m_frame->page() : nullptr;
1650 Settings* Document::settings() const
1652 return m_frame ? &m_frame->settings() : nullptr;
1655 Ref<Range> Document::createRange()
1657 return Range::create(*this);
1660 RefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1661 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1664 ec = NOT_SUPPORTED_ERR;
1667 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1670 RefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1671 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1674 ec = NOT_SUPPORTED_ERR;
1677 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1680 void Document::scheduleForcedStyleRecalc()
1682 m_pendingStyleRecalcShouldForce = true;
1683 scheduleStyleRecalc();
1686 void Document::scheduleStyleRecalc()
1688 if (m_styleRecalcTimer.isActive() || inPageCache())
1691 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1693 // FIXME: Why on earth is this here? This is clearly misplaced.
1694 invalidateAccessKeyMap();
1696 m_styleRecalcTimer.startOneShot(0);
1698 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1701 void Document::unscheduleStyleRecalc()
1703 ASSERT(!childNeedsStyleRecalc());
1705 m_styleRecalcTimer.stop();
1706 m_pendingStyleRecalcShouldForce = false;
1709 bool Document::hasPendingStyleRecalc() const
1711 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1714 bool Document::hasPendingForcedStyleRecalc() const
1716 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1719 void Document::styleRecalcTimerFired()
1721 updateStyleIfNeeded();
1724 void Document::recalcStyle(Style::Change change)
1726 ASSERT(!view() || !view()->isPainting());
1728 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1732 FrameView& frameView = m_renderView->frameView();
1733 if (frameView.isPainting())
1736 if (m_inStyleRecalc)
1737 return; // Guard against re-entrancy. -dwh
1739 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1740 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1742 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1743 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1744 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1745 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1746 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1747 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1749 m_styleSheetCollection.flushPendingUpdates();
1751 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1753 // FIXME: We never reset this flags.
1754 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1755 m_styleSheetCollection.setUsesRemUnit(true);
1756 // We don't call setUsesStyleBasedEditability here because the whole point of the flag is to avoid style recalc.
1757 // i.e. updating the flag here would be too late.
1759 m_inStyleRecalc = true;
1761 Style::PostResolutionCallbackDisabler disabler(*this);
1762 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1764 if (m_pendingStyleRecalcShouldForce)
1765 change = Style::Force;
1767 if (change == Style::Force) {
1768 // This may get set again during style resolve.
1769 m_hasNodesWithPlaceholderStyle = false;
1772 Style::resolveTree(*this, change);
1774 frameView.updateCompositingLayersAfterStyleChange();
1776 clearNeedsStyleRecalc();
1777 clearChildNeedsStyleRecalc();
1778 unscheduleStyleRecalc();
1780 m_inStyleRecalc = false;
1782 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1783 if (m_styleResolver)
1784 m_styleSheetCollection.resetCSSFeatureFlags();
1787 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1788 if (m_closeAfterStyleRecalc) {
1789 m_closeAfterStyleRecalc = false;
1793 ++m_styleRecalcCount;
1795 InspectorInstrumentation::didRecalculateStyle(cookie);
1797 // Some animated images may now be inside the viewport due to style recalc,
1798 // resume them if necessary if there is no layout pending. Otherwise, we'll
1799 // check if they need to be resumed after layout.
1800 if (!frameView.needsLayout())
1801 frameView.viewportContentsChanged();
1803 // As a result of the style recalculation, the currently hovered element might have been
1804 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1805 // to check if any other elements ended up under the mouse pointer due to re-layout.
1806 if (m_hoveredElement && !m_hoveredElement->renderer())
1807 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1810 void Document::updateStyleIfNeeded()
1812 ASSERT(isMainThread());
1813 ASSERT(!view() || !view()->isPainting());
1815 if (!view() || view()->isInLayout())
1818 if (m_optimizedStyleSheetUpdateTimer.isActive())
1819 styleResolverChanged(RecalcStyleIfNeeded);
1821 if (!needsStyleRecalc())
1824 recalcStyle(Style::NoChange);
1827 void Document::updateLayout()
1829 ASSERT(isMainThread());
1831 FrameView* frameView = view();
1832 if (frameView && frameView->isInLayout()) {
1833 // View layout should not be re-entrant.
1834 ASSERT_NOT_REACHED();
1838 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1840 if (HTMLFrameOwnerElement* owner = ownerElement())
1841 owner->document().updateLayout();
1843 updateStyleIfNeeded();
1845 StackStats::LayoutCheckPoint layoutCheckPoint;
1847 // Only do a layout if changes have occurred that make it necessary.
1848 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1849 frameView->layout();
1852 // FIXME: This is a bad idea and needs to be removed eventually.
1853 // Other browsers load stylesheets before they continue parsing the web page.
1854 // Since we don't, we can run JavaScript code that needs answers before the
1855 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1856 // lets us get reasonable answers. The long term solution to this problem is
1857 // to instead suspend JavaScript execution.
1858 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1860 bool oldIgnore = m_ignorePendingStylesheets;
1862 if (!haveStylesheetsLoaded()) {
1863 m_ignorePendingStylesheets = true;
1864 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1865 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1866 // with accurate style information. (Our suppression involves blanking the whole page at the
1867 // moment. If it were more refined, we might be able to do something better.)
1868 // It's worth noting though that this entire method is a hack, since what we really want to do is
1869 // suspend JS instead of doing a layout with inaccurate information.
1870 HTMLElement* bodyElement = bodyOrFrameset();
1871 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1872 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1873 styleResolverChanged(RecalcStyleImmediately);
1874 } else if (m_hasNodesWithPlaceholderStyle)
1875 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1876 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1877 // but here we need up-to-date style immediately.
1878 recalcStyle(Style::Force);
1883 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1884 view()->flushAnyPendingPostLayoutTasks();
1886 m_ignorePendingStylesheets = oldIgnore;
1889 Ref<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1891 ASSERT_ARG(element, &element->document() == this);
1893 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1894 ResourceLoadScheduler::Suspender suspender(*platformStrategies()->loaderStrategy()->resourceLoadScheduler());
1896 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
1897 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : nullptr);
1900 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
1902 ASSERT(isMainThread());
1904 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
1905 if (!haveStylesheetsLoaded()) {
1906 updateLayoutIgnorePendingStylesheets();
1910 // Check for re-entrancy and assert (same code that is in updateLayout()).
1911 FrameView* frameView = view();
1912 if (frameView && frameView->isInLayout()) {
1913 // View layout should not be re-entrant.
1914 ASSERT_NOT_REACHED();
1918 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1920 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
1922 bool requireFullLayout = false;
1923 if (HTMLFrameOwnerElement* owner = ownerElement()) {
1924 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
1925 requireFullLayout = true;
1928 updateStyleIfNeeded();
1930 RenderObject* renderer = element.renderer();
1931 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
1932 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
1933 // Named flows can have auto height, so don't try to enforce the optimization in this case.
1934 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
1935 requireFullLayout = true;
1938 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
1939 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
1940 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && !isVertical);
1941 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
1943 if (!requireFullLayout) {
1944 RenderBox* previousBox = nullptr;
1945 RenderBox* currentBox = nullptr;
1947 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
1948 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
1950 // Require the entire container chain to be boxes.
1951 if (!is<RenderBox>(currRenderer)) {
1952 requireFullLayout = true;
1956 previousBox = currentBox;
1957 currentBox = downcast<RenderBox>(currRenderer);
1959 // If a box needs layout for itself or if a box has changed children and sizes its width to
1960 // its content, then require a full layout.
1961 if (currentBox->selfNeedsLayout() ||
1962 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
1963 requireFullLayout = true;
1967 // If a block contains floats and the child's height isn't specified, then
1968 // give up also, since our height could end up being influenced by the floats.
1969 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
1970 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
1971 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
1972 requireFullLayout = true;
1977 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
1978 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
1979 // for now, and we'll expand it in future patches to apply to more and more scenarios.
1980 // Disallow regions/columns from having the optimization.
1981 // Give up if the writing mode changes at all in the containing block chain.
1982 requireFullLayout = true;
1986 if (currRenderer == frameView->layoutRoot())
1991 StackStats::LayoutCheckPoint layoutCheckPoint;
1993 // Only do a layout if changes have occurred that make it necessary.
1994 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1995 frameView->layout();
1997 return requireFullLayout;
2000 bool Document::isPageBoxVisible(int pageIndex)
2002 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
2003 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2006 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2008 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
2010 int width = pageSize.width();
2011 int height = pageSize.height();
2012 switch (style->pageSizeType()) {
2013 case PAGE_SIZE_AUTO:
2015 case PAGE_SIZE_AUTO_LANDSCAPE:
2017 std::swap(width, height);
2019 case PAGE_SIZE_AUTO_PORTRAIT:
2021 std::swap(width, height);
2023 case PAGE_SIZE_RESOLVED: {
2024 LengthSize size = style->pageSize();
2025 ASSERT(size.width().isFixed());
2026 ASSERT(size.height().isFixed());
2027 width = valueForLength(size.width(), 0);
2028 height = valueForLength(size.height(), 0);
2032 ASSERT_NOT_REACHED();
2034 pageSize = IntSize(width, height);
2036 // The percentage is calculated with respect to the width even for margin top and bottom.
2037 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2038 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2039 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2040 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2041 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2044 void Document::createStyleResolver()
2046 bool matchAuthorAndUserStyles = true;
2047 if (Settings* settings = this->settings())
2048 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
2049 m_styleResolver = std::make_unique<StyleResolver>(*this, matchAuthorAndUserStyles);
2050 m_styleSheetCollection.combineCSSFeatureFlags();
2053 void Document::fontsNeedUpdate(FontSelector*)
2055 if (m_styleResolver)
2056 m_styleResolver->invalidateMatchedPropertiesCache();
2057 if (inPageCache() || !renderView())
2059 scheduleForcedStyleRecalc();
2062 CSSFontSelector& Document::fontSelector()
2064 if (!m_fontSelector) {
2065 m_fontSelector = CSSFontSelector::create(*this);
2066 m_fontSelector->registerForInvalidationCallbacks(this);
2068 return *m_fontSelector;
2071 void Document::clearStyleResolver()
2073 m_styleResolver = nullptr;
2075 // FIXME: It would be better if the FontSelector could survive this operation.
2076 if (m_fontSelector) {
2077 m_fontSelector->clearDocument();
2078 m_fontSelector->unregisterForInvalidationCallbacks(this);
2079 m_fontSelector = nullptr;
2083 void Document::createRenderTree()
2085 ASSERT(!renderView());
2086 ASSERT(!m_inPageCache);
2087 ASSERT(!m_axObjectCache || this != &topDocument());
2089 if (m_isNonRenderedPlaceholder)
2092 // FIXME: It would be better if we could pass the resolved document style directly here.
2093 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2094 Node::setRenderer(m_renderView.get());
2096 renderView()->setIsInWindow(true);
2098 recalcStyle(Style::Force);
2101 void Document::didBecomeCurrentDocumentInFrame()
2103 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2104 // If so, then m_frame could become 0, and we need to do something about that.
2106 m_frame->script().updateDocument();
2108 if (!hasLivingRenderTree())
2111 updateViewportArguments();
2113 // FIXME: Doing this only for the main frame is insufficient.
2114 // Changing a subframe can also change the wheel event handler count.
2115 // FIXME: Doing this only when a document goes into the frame is insufficient.
2116 // Removing a document can also change the wheel event handler count.
2117 // FIXME: Doing this every time is a waste. If the current document and its
2118 // subframes' documents have no wheel event handlers, then the count did not change,
2119 // unless the documents they are replacing had wheel event handlers.
2120 if (page() && m_frame->isMainFrame())
2121 wheelEventHandlersChanged();
2123 #if ENABLE(TOUCH_EVENTS)
2124 // FIXME: Doing this only for the main frame is insufficient.
2125 // A subframe could have touch event handlers.
2126 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2127 page()->chrome().client().needTouchEvents(true);
2131 // Ensure that document scheduled task state matches frame timer state. It can be out of sync
2132 // if timers state changed while the document was not in the frame (possibly in page cache,
2133 // or simply newly created).
2134 // FIXME: How does this interact with cross-platform code below?
2135 if (m_frame->timersPaused())
2136 suspendScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
2138 resumeScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
2141 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2142 suspendScriptedAnimationControllerCallbacks();
2143 m_frame->animation().suspendAnimationsForDocument(this);
2144 suspendActiveDOMObjects(ActiveDOMObject::PageWillBeSuspended);
2148 void Document::disconnectFromFrame()
2153 void Document::destroyRenderTree()
2155 ASSERT(hasLivingRenderTree());
2156 ASSERT(!m_inPageCache);
2158 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2160 if (this == &topDocument())
2161 clearAXObjectCache();
2163 documentWillBecomeInactive();
2165 if (FrameView* frameView = view())
2166 frameView->detachCustomScrollbars();
2168 #if ENABLE(FULLSCREEN_API)
2169 if (m_fullScreenRenderer)
2170 setFullScreenRenderer(nullptr);
2173 m_hoveredElement = nullptr;
2174 m_focusedElement = nullptr;
2175 m_activeElement = nullptr;
2177 if (m_documentElement)
2178 Style::detachRenderTree(*m_documentElement);
2180 clearChildNeedsStyleRecalc();
2182 unscheduleStyleRecalc();
2184 m_renderView = nullptr;
2185 Node::setRenderer(nullptr);
2187 #if ENABLE(IOS_TEXT_AUTOSIZING)
2188 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2189 m_textAutoSizedNodes.clear();
2193 void Document::prepareForDestruction()
2195 if (m_hasPreparedForDestruction)
2198 #if ENABLE(IOS_TOUCH_EVENTS)
2199 clearTouchEventListeners();
2202 #if HAVE(ACCESSIBILITY)
2203 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2204 if (this != &topDocument()) {
2205 if (AXObjectCache* cache = existingAXObjectCache())
2206 cache->clearTextMarkerNodesInUse(this);
2210 disconnectDescendantFrames();
2211 if (m_domWindow && m_frame)
2212 m_domWindow->willDetachDocumentFromFrame();
2214 if (hasLivingRenderTree())
2215 destroyRenderTree();
2217 if (is<PluginDocument>(*this))
2218 downcast<PluginDocument>(*this).detachFromPluginElement();
2220 #if ENABLE(POINTER_LOCK)
2222 page()->pointerLockController().documentDetached(this);
2225 stopActiveDOMObjects();
2226 m_eventQueue.close();
2227 #if ENABLE(FULLSCREEN_API)
2228 m_fullScreenChangeEventTargetQueue.clear();
2229 m_fullScreenErrorEventTargetQueue.clear();
2234 #if ENABLE(TOUCH_EVENTS)
2235 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2236 parentDocument()->didRemoveEventTargetNode(*this);
2239 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2240 parentDocument()->didRemoveEventTargetNode(*this);
2242 if (m_mediaQueryMatcher)
2243 m_mediaQueryMatcher->documentDestroyed();
2245 disconnectFromFrame();
2247 m_hasPreparedForDestruction = true;
2250 void Document::removeAllEventListeners()
2252 EventTarget::removeAllEventListeners();
2255 m_domWindow->removeAllEventListeners();
2256 #if ENABLE(IOS_TOUCH_EVENTS)
2257 clearTouchEventListeners();
2259 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2260 node->removeAllEventListeners();
2263 void Document::platformSuspendOrStopActiveDOMObjects()
2266 #if ENABLE(DEVICE_ORIENTATION)
2267 if (m_deviceMotionController)
2268 m_deviceMotionController->suspendUpdates();
2269 if (m_deviceOrientationController)
2270 m_deviceOrientationController->suspendUpdates();
2273 if (WebThreadCountOfObservedContentModifiers() > 0) {
2274 Frame* frame = this->frame();
2275 if (Page* page = frame ? frame->page() : nullptr)
2276 page->chrome().client().clearContentChangeObservers(frame);
2281 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2283 ScriptExecutionContext::suspendActiveDOMObjects(why);
2284 platformSuspendOrStopActiveDOMObjects();
2287 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2289 ScriptExecutionContext::resumeActiveDOMObjects(why);
2291 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2292 if (m_deviceMotionController)
2293 m_deviceMotionController->resumeUpdates();
2294 if (m_deviceOrientationController)
2295 m_deviceOrientationController->resumeUpdates();
2297 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2300 void Document::stopActiveDOMObjects()
2302 ScriptExecutionContext::stopActiveDOMObjects();
2303 platformSuspendOrStopActiveDOMObjects();
2306 void Document::clearAXObjectCache()
2308 ASSERT(&topDocument() == this);
2309 // Clear the cache member variable before calling delete because attempts
2310 // are made to access it during destruction.
2311 m_axObjectCache = nullptr;
2314 AXObjectCache* Document::existingAXObjectCache() const
2316 Document& topDocument = this->topDocument();
2317 if (!topDocument.hasLivingRenderTree())
2319 return topDocument.m_axObjectCache.get();
2322 AXObjectCache* Document::axObjectCache() const
2324 if (!AXObjectCache::accessibilityEnabled())
2327 // The only document that actually has a AXObjectCache is the top-level
2328 // document. This is because we need to be able to get from any WebCoreAXObject
2329 // to any other WebCoreAXObject on the same page. Using a single cache allows
2330 // lookups across nested webareas (i.e. multiple documents).
2331 Document& topDocument = this->topDocument();
2333 // If the document has already been detached, do not make a new axObjectCache.
2334 if (!topDocument.hasLivingRenderTree())
2337 ASSERT(&topDocument == this || !m_axObjectCache);
2338 if (!topDocument.m_axObjectCache)
2339 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2340 return topDocument.m_axObjectCache.get();
2343 void Document::setVisuallyOrdered()
2345 m_visuallyOrdered = true;
2347 renderView()->style().setRTLOrdering(VisualOrder);
2350 Ref<DocumentParser> Document::createParser()
2352 // FIXME: this should probably pass the frame instead
2353 return XMLDocumentParser::create(*this, view());
2356 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2358 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2361 void Document::open(Document* ownerDocument)
2363 if (ownerDocument) {
2364 setURL(ownerDocument->url());
2365 setCookieURL(ownerDocument->cookieURL());
2366 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2370 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2371 if (parser->isParsing()) {
2372 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2373 if (parser->isExecutingScript())
2376 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2381 if (m_frame->loader().state() == FrameStateProvisional)
2382 m_frame->loader().stopAllLoaders();
2385 removeAllEventListeners();
2387 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2388 parser->setWasCreatedByScript(true);
2391 m_frame->loader().didExplicitOpen();
2394 void Document::detachParser()
2402 void Document::cancelParsing()
2407 // We have to clear the parser to avoid possibly triggering
2408 // the onload handler when closing as a side effect of a cancel-style
2409 // change, such as opening a new document or closing the window while
2415 void Document::implicitOpen()
2421 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2423 m_parser = createParser();
2425 setReadyState(Loading);
2428 HTMLBodyElement* Document::body() const
2430 auto* element = documentElement();
2433 return childrenOfType<HTMLBodyElement>(*element).first();
2436 HTMLElement* Document::bodyOrFrameset() const
2438 // If the document element contains both a frameset and a body, the frameset wins.
2439 auto* element = documentElement();
2442 if (auto* frameset = childrenOfType<HTMLFrameSetElement>(*element).first())
2444 return childrenOfType<HTMLBodyElement>(*element).first();
2447 void Document::setBodyOrFrameset(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2449 RefPtr<HTMLElement> newBody = prpNewBody;
2451 // FIXME: This does not support setting a <frameset> Element, only a <body>. This does
2452 // not match the HTML specification:
2453 // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
2454 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2455 ec = HIERARCHY_REQUEST_ERR;
2459 if (&newBody->document() != this) {
2461 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2465 newBody = downcast<HTMLElement>(node.get());
2468 HTMLElement* b = bodyOrFrameset();
2470 documentElement()->appendChild(newBody.release(), ec);
2472 documentElement()->replaceChild(newBody.release(), b, ec);
2475 HTMLHeadElement* Document::head()
2477 if (auto element = documentElement())
2478 return childrenOfType<HTMLHeadElement>(*element).first();
2482 void Document::close()
2484 // FIXME: We should follow the specification more closely:
2485 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2487 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2493 void Document::explicitClose()
2495 if (RefPtr<DocumentParser> parser = m_parser)
2499 // Because we have no frame, we don't know if all loading has completed,
2500 // so we just call implicitClose() immediately. FIXME: This might fire
2501 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2506 m_frame->loader().checkCompleted();
2509 void Document::implicitClose()
2511 // 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.
2512 if (m_inStyleRecalc) {
2513 m_closeAfterStyleRecalc = true;
2517 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2518 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2523 // Call to dispatchWindowLoadEvent can blow us from underneath.
2524 Ref<Document> protect(*this);
2526 m_processingLoadEvent = true;
2528 ScriptableDocumentParser* parser = scriptableDocumentParser();
2529 m_wellFormed = parser && parser->wellFormed();
2531 // We have to clear the parser, in case someone document.write()s from the
2532 // onLoad event handler, as in Radar 3206524.
2535 // FIXME: We kick off the icon loader when the Document is done parsing.
2536 // There are earlier opportunities we could start it:
2537 // -When the <head> finishes parsing
2538 // -When any new HTMLLinkElement is inserted into the document
2539 // But those add a dynamic component to the favicon that has UI
2540 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2543 f->loader().icon().startLoader();
2544 f->animation().startAnimationsIfNotSuspended(this);
2546 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2547 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2548 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2549 ImageLoader::dispatchPendingBeforeLoadEvents();
2550 ImageLoader::dispatchPendingLoadEvents();
2551 ImageLoader::dispatchPendingErrorEvents();
2552 HTMLLinkElement::dispatchPendingLoadEvents();
2553 HTMLStyleElement::dispatchPendingLoadEvents();
2556 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2557 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2558 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2559 if (svgExtensions())
2560 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2562 dispatchWindowLoadEvent();
2563 enqueuePageshowEvent(PageshowEventNotPersisted);
2564 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2567 f->loader().handledOnloadEvents();
2568 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2569 if (!ownerElement())
2570 printf("onload fired at %lld\n", elapsedTime().count());
2573 // An event handler may have removed the frame
2575 m_processingLoadEvent = false;
2579 // Make sure both the initial layout and reflow happen after the onload
2580 // fires. This will improve onload scores, and other browsers do it.
2581 // If they wanna cheat, we can too. -dwh
2583 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2584 // Just bail out. Before or during the onload we were shifted to another page.
2585 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2586 m_processingLoadEvent = false;
2587 view()->unscheduleRelayout();
2591 frame()->loader().checkCallImplicitClose();
2593 // We used to force a synchronous display and flush here. This really isn't
2594 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2595 // (if your platform is syncing flushes and limiting them to 60fps).
2596 m_overMinimumLayoutThreshold = true;
2597 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2598 updateStyleIfNeeded();
2600 // Always do a layout after loading if needed.
2601 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2605 m_processingLoadEvent = false;
2607 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2608 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2609 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2610 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2611 // exists in the cache (we ignore the return value because we don't need it here). This is
2612 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2614 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2615 // catch new AND page history loads, and that uses AXLoadComplete
2617 axObjectCache()->getOrCreate(renderView());
2618 if (this == &topDocument())
2619 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2621 // AXLoadComplete can only be posted on the top document, so if it's a document
2622 // in an iframe that just finished loading, post AXLayoutComplete instead.
2623 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2628 if (svgExtensions())
2629 accessSVGExtensions().startAnimations();
2632 void Document::setParsing(bool b)
2636 if (m_bParsing && !m_sharedObjectPool)
2637 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2639 if (!m_bParsing && view() && !view()->needsLayout())
2640 view()->fireLayoutRelatedMilestonesIfNeeded();
2642 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2643 if (!ownerElement() && !m_bParsing)
2644 printf("Parsing finished at %lld\n", elapsedTime().count());
2648 bool Document::shouldScheduleLayout()
2650 // This function will only be called when FrameView thinks a layout is needed.
2651 // This enforces a couple extra rules.
2653 // (a) Only schedule a layout once the stylesheets are loaded.
2654 // (b) Only schedule layout once we have a body element.
2656 return (haveStylesheetsLoaded() && bodyOrFrameset())
2657 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2660 bool Document::isLayoutTimerActive()
2662 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2665 std::chrono::milliseconds Document::minimumLayoutDelay()
2667 if (m_overMinimumLayoutThreshold)
2668 return std::chrono::milliseconds(0);
2670 std::chrono::milliseconds elapsed = elapsedTime();
2671 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2673 // We'll want to schedule the timer to fire at the minimum layout threshold.
2674 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2677 std::chrono::milliseconds Document::elapsedTime() const
2679 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2681 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2684 void Document::write(const SegmentedString& text, Document* ownerDocument)
2686 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2688 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2689 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2691 if (m_writeRecursionIsTooDeep)
2694 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2695 if (!ownerElement())
2696 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2699 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2700 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2703 if (!hasInsertionPoint)
2704 open(ownerDocument);
2707 m_parser->insert(text);
2709 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2710 if (!ownerElement())
2711 printf("Ending a document.write at %lld\n", elapsedTime().count());
2715 void Document::write(const String& text, Document* ownerDocument)
2717 write(SegmentedString(text), ownerDocument);
2720 void Document::writeln(const String& text, Document* ownerDocument)
2722 write(text, ownerDocument);
2723 write("\n", ownerDocument);
2726 double Document::minimumTimerInterval() const
2728 Page* page = this->page();
2730 return ScriptExecutionContext::minimumTimerInterval();
2731 return page->settings().minimumDOMTimerInterval();
2734 double Document::timerAlignmentInterval() const
2736 Page* page = this->page();
2738 return ScriptExecutionContext::timerAlignmentInterval();
2739 return page->settings().domTimerAlignmentInterval();
2742 EventTarget* Document::errorEventTarget()
2744 return m_domWindow.get();
2747 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2749 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTF::move(callStack));
2752 void Document::setURL(const URL& url)
2754 const URL& newURL = url.isEmpty() ? blankURL() : url;
2755 if (newURL == m_url)
2759 m_documentURI = m_url.string();
2763 void Document::updateBaseURL()
2765 URL oldBaseURL = m_baseURL;
2766 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2767 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2768 // from the Document interface otherwise.
2769 if (!m_baseElementURL.isEmpty())
2770 m_baseURL = m_baseElementURL;
2771 else if (!m_baseURLOverride.isEmpty())
2772 m_baseURL = m_baseURLOverride;
2774 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2775 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2776 // and DOM 3 Core does not specify how it should be resolved.
2777 m_baseURL = URL(ParsedURLString, documentURI());
2780 clearSelectorQueryCache();
2782 if (!m_baseURL.isValid())
2785 if (m_elementSheet) {
2786 // Element sheet is silly. It never contains anything.
2787 ASSERT(!m_elementSheet->contents().ruleCount());
2788 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2789 bool usesStyleBasedEditability = m_elementSheet->contents().usesStyleBasedEditability();
2790 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2791 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2793 m_elementSheet->contents().parserSetUsesRemUnits();
2794 if (usesStyleBasedEditability)
2795 m_elementSheet->contents().parserSetUsesStyleBasedEditability();
2798 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2799 // Base URL change changes any relative visited links.
2800 // 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.
2801 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2802 anchor.invalidateCachedVisitedLinkHash();
2806 void Document::setBaseURLOverride(const URL& url)
2808 m_baseURLOverride = url;
2812 void Document::processBaseElement()
2814 // Find the first href attribute in a base element and the first target attribute in a base element.
2815 const AtomicString* href = nullptr;
2816 const AtomicString* target = nullptr;
2817 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2818 for (auto& base : baseDescendants) {
2820 const AtomicString& value = base.fastGetAttribute(hrefAttr);
2821 if (!value.isNull()) {
2828 const AtomicString& value = base.fastGetAttribute(targetAttr);
2829 if (!value.isNull()) {
2837 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2840 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2841 if (!strippedHref.isEmpty())
2842 baseElementURL = URL(url(), strippedHref);
2844 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2845 m_baseElementURL = baseElementURL;
2849 m_baseTarget = target ? *target : nullAtom;
2852 String Document::userAgent(const URL& url) const
2854 return frame() ? frame()->loader().userAgent(url) : String();
2857 void Document::disableEval(const String& errorMessage)
2862 frame()->script().disableEval(errorMessage);
2865 bool Document::canNavigate(Frame* targetFrame)
2870 // FIXME: We shouldn't call this function without a target frame, but
2871 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2872 // returning true when supplied with a 0 targetFrame.
2876 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2877 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2880 if (isSandboxed(SandboxNavigation)) {
2881 if (targetFrame->tree().isDescendantOf(m_frame))
2884 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2885 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2886 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2888 printNavigationErrorMessage(targetFrame, url(), reason);
2892 // This is the normal case. A document can navigate its decendant frames,
2893 // or, more generally, a document can navigate a frame if the document is
2894 // in the same origin as any of that frame's ancestors (in the frame
2897 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2898 // historical information about this security check.
2899 if (canAccessAncestor(securityOrigin(), targetFrame))
2902 // Top-level frames are easier to navigate than other frames because they
2903 // display their URLs in the address bar (in most browsers). However, there
2904 // are still some restrictions on navigation to avoid nuisance attacks.
2905 // Specifically, a document can navigate a top-level frame if that frame
2906 // opened the document or if the document is the same-origin with any of
2907 // the top-level frame's opener's ancestors (in the frame hierarchy).
2909 // In both of these cases, the document performing the navigation is in
2910 // some way related to the frame being navigate (e.g., by the "opener"
2911 // and/or "parent" relation). Requiring some sort of relation prevents a
2912 // document from navigating arbitrary, unrelated top-level frames.
2913 if (!targetFrame->tree().parent()) {
2914 if (targetFrame == m_frame->loader().opener())
2917 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
2921 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2925 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2927 Frame* currentFrame = m_frame;
2931 Frame* ancestorFrame = currentFrame->tree().parent();
2933 while (ancestorFrame) {
2934 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2935 return currentFrame;
2936 currentFrame = ancestorFrame;
2937 ancestorFrame = ancestorFrame->tree().parent();
2942 void Document::didRemoveAllPendingStylesheet()
2944 m_needsNotifyRemoveAllPendingStylesheet = false;
2946 styleResolverChanged(DeferRecalcStyleIfNeeded);
2948 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
2949 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2951 renderView()->repaintViewAndCompositedLayers();
2954 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2955 parser->executeScriptsWaitingForStylesheets();
2957 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2958 view()->scrollToFragment(m_url);
2961 CSSStyleSheet& Document::elementSheet()
2963 if (!m_elementSheet)
2964 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2965 return *m_elementSheet;
2968 bool Document::usesStyleBasedEditability() const
2970 if (m_elementSheet && m_elementSheet->contents().usesStyleBasedEditability())
2973 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
2974 ASSERT(!m_inStyleRecalc);
2976 auto& collection = document().styleSheetCollection();
2977 collection.flushPendingUpdates();
2978 return collection.usesStyleBasedEditability();
2981 void Document::processHttpEquiv(const String& equiv, const String& content)
2983 ASSERT(!equiv.isNull() && !content.isNull());
2985 Frame* frame = this->frame();
2987 HTTPHeaderName headerName;
2988 if (!findHTTPHeaderName(equiv, headerName))
2991 switch (headerName) {
2992 case HTTPHeaderName::DefaultStyle:
2993 // The preferred style set has been overridden as per section
2994 // 14.3.2 of the HTML4.0 specification. We need to update the
2995 // sheet used variable and then update our style selector.
2996 // For more info, see the test at:
2997 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2999 m_styleSheetCollection.setSelectedStylesheetSetName(content);
3000 m_styleSheetCollection.setPreferredStylesheetSetName(content);
3001 styleResolverChanged(DeferRecalcStyle);
3004 case HTTPHeaderName::Refresh: {
3007 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
3009 if (urlString.isEmpty())
3010 completedURL = m_url;
3012 completedURL = completeURL(urlString);
3013 if (!protocolIsJavaScript(completedURL))
3014 frame->navigationScheduler().scheduleRedirect(delay, completedURL);
3016 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3017 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3024 case HTTPHeaderName::SetCookie:
3025 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3026 if (is<HTMLDocument>(*this)) {
3027 // Exception (for sandboxed documents) ignored.
3028 downcast<HTMLDocument>(*this).setCookie(content, IGNORE_EXCEPTION);
3032 case HTTPHeaderName::ContentLanguage:
3033 setContentLanguage(content);
3036 case HTTPHeaderName::XDNSPrefetchControl:
3037 parseDNSPrefetchControlHeader(content);
3040 case HTTPHeaderName::XFrameOptions:
3042 FrameLoader& frameLoader = frame->loader();
3043 unsigned long requestIdentifier = 0;
3044 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3045 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3046 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3047 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3048 frameLoader.stopAllLoaders();
3049 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3050 // intent, we must navigate away from the possibly partially-rendered document to a location that
3051 // doesn't inherit the parent's SecurityOrigin.
3052 frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
3053 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3058 case HTTPHeaderName::ContentSecurityPolicy:
3059 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
3062 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
3063 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
3066 case HTTPHeaderName::XWebKitCSP:
3067 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
3070 case HTTPHeaderName::XWebKitCSPReportOnly:
3071 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
3079 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3080 static bool isSeparator(UChar c)
3082 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3085 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3087 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3088 unsigned keyBegin, keyEnd;
3089 unsigned valueBegin, valueEnd;
3091 String buffer = features.lower();
3092 unsigned length = buffer.length();
3093 for (unsigned i = 0; i < length; ) {
3094 // skip to first non-separator, but don't skip past the end of the string
3095 while (isSeparator(buffer[i])) {
3102 // skip to first separator
3103 while (!isSeparator(buffer[i]))
3107 // skip to first '=', but don't skip past a ',' or the end of the string
3108 while (buffer[i] != '=') {
3109 if (buffer[i] == ',' || i >= length)
3114 // skip to first non-separator, but don't skip past a ',' or the end of the string
3115 while (isSeparator(buffer[i])) {
3116 if (buffer[i] == ',' || i >= length)
3122 // skip to first separator
3123 while (!isSeparator(buffer[i]))
3127 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
3129 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3130 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3131 callback(keyString, valueString, this, data);
3135 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3137 ASSERT(!features.isNull());
3139 if (origin < m_viewportArguments.type)
3142 m_viewportArguments = ViewportArguments(origin);
3143 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3145 updateViewportArguments();
3148 void Document::updateViewportArguments()
3150 if (page() && frame()->isMainFrame()) {
3152 m_didDispatchViewportPropertiesChanged = true;
3154 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3156 page()->chrome().didReceiveDocType(frame());
3162 // FIXME: Find a better place for this functionality.
3163 void setParserFeature(const String& key, const String& value, Document* document, void*)
3165 if (key == "telephone" && equalIgnoringCase(value, "no"))
3166 document->setIsTelephoneNumberParsingAllowed(false);
3169 void Document::processFormatDetection(const String& features)
3171 ASSERT(!features.isNull());
3172 processArguments(features, nullptr, &setParserFeature);
3175 void Document::processWebAppOrientations()
3177 if (Page* page = this->page())
3178 page->chrome().client().webAppOrientationsUpdated();
3182 void Document::processReferrerPolicy(const String& policy)
3184 ASSERT(!policy.isNull());
3186 // Note that we're supporting both the standard and legacy keywords for referrer
3187 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3188 if (equalIgnoringCase(policy, "no-referrer") || equalIgnoringCase(policy, "never"))
3189 setReferrerPolicy(ReferrerPolicyNever);
3190 else if (equalIgnoringCase(policy, "unsafe-url") || equalIgnoringCase(policy, "always"))
3191 setReferrerPolicy(ReferrerPolicyAlways);
3192 else if (equalIgnoringCase(policy, "origin"))
3193 setReferrerPolicy(ReferrerPolicyOrigin);
3194 else if (equalIgnoringCase(policy, "no-referrer-when-downgrade") || equalIgnoringCase(policy, "default"))
3195 setReferrerPolicy(ReferrerPolicyDefault);
3197 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'.");
3198 setReferrerPolicy(ReferrerPolicyNever);
3202 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3204 if (!hasLivingRenderTree())
3205 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3207 HitTestResult result(documentPoint);
3208 renderView()->hitTest(request, result);
3210 if (!request.readOnly())
3211 updateHoverActiveState(request, result.innerElement());
3213 return MouseEventWithHitTestResults(event, result);
3216 // DOM Section 1.1.1
3217 bool Document::childTypeAllowed(NodeType type) const
3220 case ATTRIBUTE_NODE:
3221 case CDATA_SECTION_NODE:
3222 case DOCUMENT_FRAGMENT_NODE:
3225 case ENTITY_REFERENCE_NODE:
3227 case XPATH_NAMESPACE_NODE:
3230 case PROCESSING_INSTRUCTION_NODE:
3232 case DOCUMENT_TYPE_NODE:
3234 // Documents may contain no more than one of each of these.
3235 // (One Element and one DocumentType.)
3236 for (Node* c = firstChild(); c; c = c->nextSibling())
3237 if (c->nodeType() == type)
3244 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3247 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3250 if (oldChild->nodeType() == newChild->nodeType())
3253 int numDoctypes = 0;
3254 int numElements = 0;
3256 // First, check how many doctypes and elements we have, not counting
3257 // the child we're about to remove.
3258 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3262 switch (c->nodeType()) {
3263 case DOCUMENT_TYPE_NODE:
3274 // Then, see how many doctypes and elements might be added by the new child.
3275 if (newChild->isDocumentFragment()) {
3276 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3277 switch (c->nodeType()) {
3278 case ATTRIBUTE_NODE:
3279 case CDATA_SECTION_NODE:
3280 case DOCUMENT_FRAGMENT_NODE:
3283 case ENTITY_REFERENCE_NODE:
3285 case XPATH_NAMESPACE_NODE:
3288 case PROCESSING_INSTRUCTION_NODE:
3290 case DOCUMENT_TYPE_NODE:
3299 switch (newChild->nodeType()) {
3300 case ATTRIBUTE_NODE:
3301 case CDATA_SECTION_NODE:
3302 case DOCUMENT_FRAGMENT_NODE:
3305 case ENTITY_REFERENCE_NODE:
3307 case XPATH_NAMESPACE_NODE:
3310 case PROCESSING_INSTRUCTION_NODE:
3312 case DOCUMENT_TYPE_NODE:
3321 if (numElements > 1 || numDoctypes > 1)
3327 RefPtr<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3329 Ref<Document> clone = cloneDocumentWithoutChildren();
3330 clone->cloneDataFromDocument(*this);
3332 case CloningOperation::OnlySelf:
3333 case CloningOperation::SelfWithTemplateContent:
3335 case CloningOperation::Everything:
3336 cloneChildNodes(clone.ptr());
3339 return WTF::move(clone);
3342 Ref<Document> Document::cloneDocumentWithoutChildren() const
3344 return isXHTMLDocument() ? createXHTML(nullptr, url()) : create(nullptr, url());
3347 void Document::cloneDataFromDocument(const Document& other)
3349 ASSERT(m_url == other.url());
3350 m_baseURL = other.baseURL();
3351 m_baseURLOverride = other.baseURLOverride();
3352 m_documentURI = other.documentURI();
3354 setCompatibilityMode(other.m_compatibilityMode);
3355 setSecurityOriginPolicy(other.securityOriginPolicy());
3356 overrideMIMEType(other.contentType());
3357 setDecoder(other.decoder());
3360 StyleSheetList& Document::styleSheets()
3362 if (!m_styleSheetList)
3363 m_styleSheetList = StyleSheetList::create(this);
3364 return *m_styleSheetList;
3367 String Document::preferredStylesheetSet() const
3369 return m_styleSheetCollection.preferredStylesheetSetName();
3372 String Document::selectedStylesheetSet() const
3374 return m_styleSheetCollection.selectedStylesheetSetName();
3377 void Document::setSelectedStylesheetSet(const String& aString)
3379 m_styleSheetCollection.setSelectedStylesheetSetName(aString);
3380 styleResolverChanged(DeferRecalcStyle);
3383 void Document::evaluateMediaQueryList()
3385 if (m_mediaQueryMatcher)
3386 m_mediaQueryMatcher->styleResolverChanged();
3389 void Document::optimizedStyleSheetUpdateTimerFired()
3391 styleResolverChanged(RecalcStyleIfNeeded);
3394 void Document::scheduleOptimizedStyleSheetUpdate()
3396 if (m_optimizedStyleSheetUpdateTimer.isActive())
3398 m_styleSheetCollection.setPendingUpdateType(DocumentStyleSheetCollection::OptimizedUpdate);
3399 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3402 void Document::updateViewportUnitsOnResize()
3404 if (!hasStyleWithViewportUnits())
3407 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3409 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3410 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3411 auto* renderer = element->renderer();
3412 if (renderer && renderer->style().hasViewportUnits())
3413 element->setNeedsStyleRecalc(InlineStyleChange);
3417 void Document::addAudioProducer(MediaProducer* audioProducer)
3419 m_audioProducers.add(audioProducer);
3420 updateIsPlayingMedia();
3423 void Document::removeAudioProducer(MediaProducer* audioProducer)
3425 m_audioProducers.remove(audioProducer);
3426 updateIsPlayingMedia();
3429 void Document::updateIsPlayingMedia()
3431 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3432 for (auto audioProducer : m_audioProducers)
3433 state |= audioProducer->mediaState();
3435 if (state == m_mediaState)
3438 m_mediaState = state;
3441 page()->updateIsPlayingMedia();
3444 void Document::pageMutedStateDidChange()
3446 for (auto audioProducer : m_audioProducers)
3447 audioProducer->pageMutedStateDidChange();
3450 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3452 if (m_optimizedStyleSheetUpdateTimer.isActive())
3453 m_optimizedStyleSheetUpdateTimer.stop();
3455 // Don't bother updating, since we haven't loaded all our style info yet
3456 // and haven't calculated the style selector for the first time.
3457 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3458 m_styleResolver = nullptr;
3461 m_didCalculateStyleResolver = true;
3463 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3464 if (!ownerElement())
3465 printf("Beginning update of style selector at time %lld.\n", elapsedTime().count());
3468 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3469 ? DocumentStyleSheetCollection::OptimizedUpdate
3470 : DocumentStyleSheetCollection::FullUpdate;
3471 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection.updateActiveStyleSheets(styleSheetUpdate);
3473 if (updateFlag == DeferRecalcStyle) {
3474 scheduleForcedStyleRecalc();
3478 if (updateFlag == DeferRecalcStyleIfNeeded) {
3479 if (stylesheetChangeRequiresStyleRecalc)
3480 scheduleForcedStyleRecalc();
3484 if (!stylesheetChangeRequiresStyleRecalc)
3487 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3488 // make sure animations get the correct update time
3490 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
3491 recalcStyle(Style::Force);
3494 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3495 if (!ownerElement())
3496 printf("Finished update of style selector at time %lld\n", elapsedTime().count());
3500 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3502 view()->scheduleRelayout();
3505 evaluateMediaQueryList();
3508 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3510 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3513 Element* focusedElement = node->treeScope().focusedElement();
3514 if (!focusedElement)
3517 bool nodeInSubtree = false;
3518 if (amongChildrenOnly)
3519 nodeInSubtree = focusedElement->isDescendantOf(node);
3521 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3524 setFocusedElement(nullptr);
3527 void Document::hoveredElementDidDetach(Element* element)
3529 if (!m_hoveredElement || element != m_hoveredElement)
3532 m_hoveredElement = element->parentElement();
3533 while (m_hoveredElement && !m_hoveredElement->renderer())
3534 m_hoveredElement = m_hoveredElement->parentElement();
3536 frame()->eventHandler().scheduleHoverStateUpdate();
3539 void Document::elementInActiveChainDidDetach(Element* element)
3541 if (!m_activeElement || element != m_activeElement)
3544 m_activeElement = element->parentElement();
3545 while (m_activeElement && !m_activeElement->renderer())
3546 m_activeElement = m_activeElement->parentElement();
3549 #if ENABLE(DASHBOARD_SUPPORT)
3550 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3552 return m_annotatedRegions;
3555 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3557 m_annotatedRegions = regions;
3558 setAnnotatedRegionsDirty(false);
3562 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
3564 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3566 // Make sure newFocusedElement is actually in this document
3567 if (newFocusedElement && (&newFocusedElement->document() != this))
3570 if (m_focusedElement == newFocusedElement)
3576 bool focusChangeBlocked = false;
3577 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3579 // Remove focus from the existing focus node (if any)
3580 if (oldFocusedElement) {
3581 if (oldFocusedElement->active())
3582 oldFocusedElement->setActive(false);
3584 oldFocusedElement->setFocus(false);
3586 // Dispatch a change event for form control elements that have been edited.
3587 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3588 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3589 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3590 formControlElement.dispatchFormControlChangeEvent();
3593 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3594 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3596 if (m_focusedElement) {
3597 // handler shifted focus
3598 focusChangeBlocked = true;
3599 newFocusedElement = nullptr;
3602 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3603 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3604 // on it, probably when <rdar://problem/8503958> is resolved.
3605 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3607 if (m_focusedElement) {
3608 // handler shifted focus
3609 focusChangeBlocked = true;
3610 newFocusedElement = nullptr;
3613 if (oldFocusedElement->isRootEditableElement())
3614 frame()->editor().didEndEditing();
3617 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3618 oldWidget->setFocus(false);
3620 view()->setFocus(false);
3624 if (newFocusedElement && newFocusedElement->isFocusable()) {
3625 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3626 // delegate blocks focus change
3627 focusChangeBlocked = true;
3628 goto SetFocusedNodeDone;
3630 // Set focus on the new node
3631 m_focusedElement = newFocusedElement;
3633 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3634 m_focusedElement->dispatchFocusEvent(oldFocusedElement.copyRef(), direction);
3636 if (m_focusedElement != newFocusedElement) {
3637 // handler shifted focus
3638 focusChangeBlocked = true;
3639 goto SetFocusedNodeDone;
3642 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.copyRef()); // DOM level 3 bubbling focus event.
3644 if (m_focusedElement != newFocusedElement) {
3645 // handler shifted focus
3646 focusChangeBlocked = true;
3647 goto SetFocusedNodeDone;