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 "CSSStyleDeclaration.h"
36 #include "CSSStyleSheet.h"
37 #include "CachedCSSStyleSheet.h"
38 #include "CachedResourceLoader.h"
40 #include "ChromeClient.h"
42 #include "ContentSecurityPolicy.h"
43 #include "CookieJar.h"
44 #include "DOMImplementation.h"
45 #include "DOMNamedFlowCollection.h"
46 #include "DOMWindow.h"
47 #include "DateComponents.h"
48 #include "Dictionary.h"
49 #include "DocumentLoader.h"
50 #include "DocumentMarkerController.h"
51 #include "DocumentSharedObjectPool.h"
52 #include "DocumentType.h"
54 #include "ElementIterator.h"
55 #include "EntityReference.h"
56 #include "EventFactory.h"
57 #include "EventHandler.h"
58 #include "FontLoader.h"
59 #include "FormController.h"
60 #include "FrameLoader.h"
61 #include "FrameLoaderClient.h"
62 #include "FrameView.h"
63 #include "HashChangeEvent.h"
64 #include "HistogramSupport.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 "HTTPParsers.h"
89 #include "HitTestResult.h"
90 #include "IconController.h"
91 #include "ImageLoader.h"
92 #include "InspectorInstrumentation.h"
93 #include "JSLazyEventListener.h"
95 #include "LoaderStrategy.h"
97 #include "MainFrame.h"
98 #include "MediaCanStartListener.h"
99 #include "MediaQueryList.h"
100 #include "MediaQueryMatcher.h"
101 #include "MouseEventWithHitTestResults.h"
102 #include "NameNodeList.h"
103 #include "NestingLevelIncrementer.h"
104 #include "NodeIterator.h"
105 #include "NodeRareData.h"
106 #include "NodeWithIndex.h"
107 #include "PageConsole.h"
108 #include "PageGroup.h"
109 #include "PageTransitionEvent.h"
110 #include "PlatformLocale.h"
111 #include "PlatformStrategies.h"
112 #include "PlugInsResources.h"
113 #include "PluginDocument.h"
114 #include "PointerLockController.h"
115 #include "PopStateEvent.h"
116 #include "ProcessingInstruction.h"
117 #include "RenderLayerCompositor.h"
118 #include "RenderView.h"
119 #include "RenderWidget.h"
120 #include "ResourceLoadScheduler.h"
121 #include "ResourceLoader.h"
122 #include "RuntimeEnabledFeatures.h"
123 #include "SchemeRegistry.h"
124 #include "ScopedEventQueue.h"
125 #include "ScriptCallStack.h"
126 #include "ScriptController.h"
127 #include "ScriptRunner.h"
128 #include "ScriptSourceCode.h"
129 #include "ScrollingCoordinator.h"
130 #include "SecurityOrigin.h"
131 #include "SecurityPolicy.h"
132 #include "SegmentedString.h"
133 #include "SelectorQuery.h"
134 #include "Settings.h"
135 #include "ShadowRoot.h"
136 #include "StyleProperties.h"
137 #include "StyleResolver.h"
138 #include "StyleSheetContents.h"
139 #include "StyleSheetList.h"
140 #include "TextResourceDecoder.h"
141 #include "TransformSource.h"
142 #include "TreeWalker.h"
143 #include "VisitedLinkState.h"
144 #include "XMLDocumentParser.h"
145 #include "XMLNSNames.h"
146 #include "XMLNames.h"
147 #include "XPathEvaluator.h"
148 #include "XPathExpression.h"
149 #include "XPathNSResolver.h"
150 #include "XPathResult.h"
151 #include "htmlediting.h"
152 #include <wtf/CurrentTime.h>
153 #include <wtf/TemporaryChange.h>
154 #include <wtf/text/StringBuffer.h>
156 #if ENABLE(SHARED_WORKERS)
157 #include "SharedWorkerRepository.h"
161 #include "XSLTProcessor.h"
165 #include "SVGDocumentExtensions.h"
166 #include "SVGElementFactory.h"
167 #include "SVGNames.h"
168 #include "SVGSVGElement.h"
171 #if ENABLE(TOUCH_EVENTS)
172 #include "TouchList.h"
176 #include "CSSFontSelector.h"
177 #include "DeviceMotionClientIOS.h"
178 #include "DeviceMotionController.h"
179 #include "DeviceOrientationClientIOS.h"
180 #include "DeviceOrientationController.h"
181 #include "Geolocation.h"
182 #include "Navigator.h"
183 #include "NavigatorGeolocation.h"
184 #include "WKContentObservation.h"
185 #include "WebCoreSystemInterface.h"
188 #if ENABLE(IOS_GESTURE_EVENTS)
189 #include "GestureEvent.h"
193 #include "MathMLElement.h"
194 #include "MathMLElementFactory.h"
195 #include "MathMLNames.h"
198 #if ENABLE(FULLSCREEN_API)
199 #include "RenderFullScreen.h"
202 #if ENABLE(REQUEST_ANIMATION_FRAME)
203 #include "RequestAnimationFrameCallback.h"
204 #include "ScriptedAnimationController.h"
207 #if ENABLE(IOS_TEXT_AUTOSIZING)
208 #include "TextAutoSizing.h"
211 #if ENABLE(TEXT_AUTOSIZING)
212 #include "TextAutosizer.h"
216 #include "DOMSecurityPolicy.h"
219 #if ENABLE(VIDEO_TRACK)
220 #include "CaptionUserPreferences.h"
223 #if ENABLE(WEB_REPLAY)
224 #include <replay/EmptyInputCursor.h>
228 using namespace Unicode;
232 using namespace HTMLNames;
234 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
236 static const unsigned cMaxWriteRecursionDepth = 21;
238 // DOM Level 2 says (letters added):
240 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
241 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
242 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
243 // 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.
244 // 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.
245 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
246 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
247 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
248 // i) Characters ':' and '_' are allowed as name-start characters.
249 // j) Characters '-' and '.' are allowed as name characters.
251 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
253 static inline bool isValidNameStart(UChar32 c)
256 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
260 if (c == ':' || c == '_')
263 // rules (a) and (f) above
264 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)))
268 if (c >= 0xF900 && c < 0xFFFE)
272 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
273 if (type == U_DT_FONT || type == U_DT_COMPAT)
279 static inline bool isValidNamePart(UChar32 c)
281 // rules (a), (e), and (i) above
282 if (isValidNameStart(c))
285 // rules (g) and (h) above
286 if (c == 0x00B7 || c == 0x0387)
290 if (c == '-' || c == '.')
293 // rules (b) and (f) above
294 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
298 if (c >= 0xF900 && c < 0xFFFE)
302 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
303 if (type == U_DT_FONT || type == U_DT_COMPAT)
309 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
311 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
313 // If a Document has the address "about:blank"
314 // The origin of the Document is the origin it was assigned when its browsing context was created.
316 // Note: We generalize this to all "blank" URLs and invalid URLs because we
317 // treat all of these URLs as about:blank.
319 return url.isEmpty() || url.isBlankURL();
322 static Widget* widgetForElement(Element* focusedElement)
326 auto renderer = focusedElement->renderer();
327 if (!renderer || !renderer->isWidget())
329 return toRenderWidget(renderer)->widget();
332 static bool acceptsEditingFocus(Node* node)
335 ASSERT(node->hasEditableStyle());
337 Node* root = node->rootEditableElement();
338 Frame* frame = node->document().frame();
342 return frame->editor().shouldBeginEditing(rangeOfContents(*root).get());
345 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
347 // targetFrame can be 0 when we're trying to navigate a top-level frame
348 // that has a 0 opener.
352 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
353 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
354 Document* ancestorDocument = ancestorFrame->document();
355 // FIXME: Should be an ASSERT? Frames should alway have documents.
356 if (!ancestorDocument)
359 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
360 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
363 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
364 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
365 // something more general instead?
366 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
373 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
375 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
377 // FIXME: should we print to the console of the document performing the navigation instead?
378 frame->document()->domWindow()->printErrorMessage(message);
381 uint64_t Document::s_globalTreeVersion = 0;
383 static const double timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds = 30;
385 #if ENABLE(IOS_TEXT_AUTOSIZING)
386 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
388 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
391 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
393 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
397 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
398 : ContainerNode(nullptr, CreateDocument)
400 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
401 , m_handlingTouchEvent(false)
402 , m_touchEventRegionsDirty(false)
403 , m_touchEventsChangedTimer(this, &Document::touchEventsChangedTimerFired)
405 , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired, timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds)
406 , m_didCalculateStyleResolver(false)
407 , m_hasNodesWithPlaceholderStyle(false)
408 , m_needsNotifyRemoveAllPendingStylesheet(false)
409 , m_ignorePendingStylesheets(false)
410 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
412 , m_activeParserCount(0)
413 , m_wellFormed(false)
415 , m_paginatedForScreen(false)
416 , m_ignoreAutofocus(false)
417 , m_compatibilityMode(NoQuirksMode)
418 , m_compatibilityModeLocked(false)
419 , m_textColor(Color::black)
420 , m_domTreeVersion(++s_globalTreeVersion)
422 , m_mutationObserverTypes(0)
423 , m_styleSheetCollection(*this)
424 , m_visitedLinkState(VisitedLinkState::create(*this))
425 , m_visuallyOrdered(false)
426 , m_readyState(Complete)
428 , m_optimizedStyleSheetUpdateTimer(this, &Document::optimizedStyleSheetUpdateTimerFired)
429 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
430 , m_pendingStyleRecalcShouldForce(false)
431 , m_inStyleRecalc(false)
432 , m_closeAfterStyleRecalc(false)
433 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
434 , m_frameElementsShouldIgnoreScrolling(false)
435 , m_containsValidityStyleRules(false)
436 , m_updateFocusAppearanceRestoresSelection(false)
437 , m_ignoreDestructiveWriteCount(0)
438 , m_titleSetExplicitly(false)
439 , m_markers(adoptPtr(new DocumentMarkerController))
440 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
441 , m_resetHiddenFocusElementTimer(this, &Document::resetHiddenFocusElementTimer)
442 , m_cssTarget(nullptr)
443 , m_processingLoadEvent(false)
444 , m_loadEventFinished(false)
445 , m_startTime(std::chrono::steady_clock::now())
446 , m_overMinimumLayoutThreshold(false)
447 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
448 , m_xmlVersion(ASCIILiteral("1.0"))
449 , m_xmlStandalone(StandaloneUnspecified)
450 , m_hasXMLDeclaration(false)
451 , m_designMode(inherit)
452 #if ENABLE(DASHBOARD_SUPPORT)
453 , m_hasAnnotatedRegions(false)
454 , m_annotatedRegionsDirty(false)
456 , m_createRenderers(true)
457 , m_inPageCache(false)
458 , m_accessKeyMapValid(false)
459 , m_documentClasses(documentClasses)
460 , m_isSynthesized(constructionFlags & Synthesized)
461 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
462 , m_isViewSource(false)
463 , m_sawElementsInKnownNamespaces(false)
464 , m_isSrcdocDocument(false)
465 , m_eventQueue(*this)
466 , m_weakFactory(this)
467 , m_idAttributeName(idAttr)
468 #if ENABLE(FULLSCREEN_API)
469 , m_areKeysEnabledInFullScreen(0)
470 , m_fullScreenRenderer(nullptr)
471 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
472 , m_isAnimatingFullScreen(false)
474 , m_loadEventDelayCount(0)
475 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
476 , m_referrerPolicy(ReferrerPolicyDefault)
477 , m_directionSetOnDocumentElement(false)
478 , m_writingModeSetOnDocumentElement(false)
479 , m_writeRecursionIsTooDeep(false)
480 , m_writeRecursionDepth(0)
481 , m_wheelEventHandlerCount(0)
482 , m_lastHandledUserGestureTimestamp(0)
484 #if ENABLE(DEVICE_ORIENTATION)
485 , m_deviceMotionClient(DeviceMotionClientIOS::create())
486 , m_deviceMotionController(DeviceMotionController::create(m_deviceMotionClient.get()))
487 , m_deviceOrientationClient(DeviceOrientationClientIOS::create())
488 , m_deviceOrientationController(DeviceOrientationController::create(m_deviceOrientationClient.get()))
490 , m_isTelephoneNumberParsingAllowed(true)
492 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
493 , m_scheduledTasksAreSuspended(false)
494 , m_visualUpdatesAllowed(true)
495 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
496 , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
498 , m_didDispatchViewportPropertiesChanged(false)
500 #if ENABLE(TEMPLATE_ELEMENT)
501 , m_templateDocumentHost(nullptr)
503 #if ENABLE(WEB_REPLAY)
504 , m_inputCursor(EmptyInputCursor::create())
506 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
507 , m_hasInjectedPlugInsScript(false)
508 , m_renderTreeBeingDestroyed(false)
510 // We depend on the url getting immediately set in subframes, but we
511 // also depend on the url NOT getting immediately set in opened windows.
512 // See fast/dom/early-frame-url.html
513 // and fast/dom/location-new-window-no-crash.html, respectively.
514 // FIXME: Can/should we unify this behavior?
515 if ((frame && frame->ownerElement()) || !url.isEmpty())
519 m_cachedResourceLoader = &m_frame->loader().activeDocumentLoader()->cachedResourceLoader();
520 if (!m_cachedResourceLoader)
521 m_cachedResourceLoader = CachedResourceLoader::create(nullptr);
522 m_cachedResourceLoader->setDocument(this);
524 #if ENABLE(TEXT_AUTOSIZING)
525 m_textAutosizer = TextAutosizer::create(this);
529 resetVisitedLinkColor();
530 resetActiveLinkColor();
532 initSecurityContext();
535 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
536 m_nodeListAndCollectionCounts[i] = 0;
538 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
541 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
543 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
544 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
545 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
546 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
547 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
548 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
551 #if ENABLE(FULLSCREEN_API)
552 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
557 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
559 } while ((owner = owner->document().ownerElement()));
564 Document::~Document()
566 ASSERT(!renderView());
567 ASSERT(!m_inPageCache);
568 ASSERT(m_ranges.isEmpty());
569 ASSERT(!m_parentTreeScope);
571 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
572 m_deviceMotionClient->deviceMotionControllerDestroyed();
573 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
576 #if ENABLE(TEMPLATE_ELEMENT)
577 if (m_templateDocument)
578 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
581 // FIXME: Should we reset m_domWindow when we detach from the Frame?
583 m_domWindow->resetUnlessSuspendedForPageCache();
585 m_scriptRunner = nullptr;
587 histogramMutationEventUsage(m_listenerTypes);
589 removeAllEventListeners();
591 // Currently we believe that Document can never outlive the parser.
592 // Although the Document may be replaced synchronously, DocumentParsers
593 // generally keep at least one reference to an Element which would in turn
594 // has a reference to the Document. If you hit this ASSERT, then that
595 // assumption is wrong. DocumentParser::detach() should ensure that even
596 // if the DocumentParser outlives the Document it won't cause badness.
597 ASSERT(!m_parser || m_parser->refCount() == 1);
600 if (this == &topDocument())
601 clearAXObjectCache();
605 if (m_styleSheetList)
606 m_styleSheetList->detachFromDocument();
609 m_elementSheet->detachFromDocument();
610 m_styleSheetCollection.detachFromDocument();
612 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
614 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
615 // load the initial empty document and the SVGDocument with the same DocumentLoader).
616 if (m_cachedResourceLoader->document() == this)
617 m_cachedResourceLoader->setDocument(nullptr);
618 m_cachedResourceLoader.clear();
620 // We must call clearRareData() here since a Document class inherits TreeScope
621 // as well as Node. See a comment on TreeScope.h for the reason.
625 ASSERT(!m_listsInvalidatedAtDocument.size());
626 ASSERT(!m_collectionsInvalidatedAtDocument.size());
628 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
629 ASSERT(!m_nodeListAndCollectionCounts[i]);
631 clearDocumentScope();
633 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
636 void Document::dropChildren()
638 ASSERT(!m_deletionHasBegun);
640 // We must make sure not to be retaining any of our children through
641 // these extra pointers or we will create a reference cycle.
642 m_focusedElement = nullptr;
643 m_hoveredElement = nullptr;
644 m_activeElement = nullptr;
645 m_titleElement = nullptr;
646 m_documentElement = nullptr;
647 m_userActionElements.documentDidRemoveLastRef();
648 #if ENABLE(FULLSCREEN_API)
649 m_fullScreenElement = nullptr;
650 m_fullScreenElementStack.clear();
655 // removeDetachedChildren() doesn't always unregister IDs,
656 // so tear down scope information up front to avoid having
657 // stale references in the map.
659 destroyTreeScopeData();
660 removeDetachedChildren();
661 m_formController.clear();
665 m_cssCanvasElements.clear();
670 void Document::commonTeardown()
674 accessSVGExtensions()->pauseAnimations();
677 #if ENABLE(REQUEST_ANIMATION_FRAME)
678 clearScriptedAnimationController();
682 Element* Document::getElementByAccessKey(const String& key)
686 if (!m_accessKeyMapValid) {
687 buildAccessKeyMap(this);
688 m_accessKeyMapValid = true;
690 return m_elementsByAccessKey.get(key.impl());
693 void Document::buildAccessKeyMap(TreeScope* scope)
696 ContainerNode* rootNode = scope->rootNode();
697 for (auto& element : descendantsOfType<Element>(*rootNode)) {
698 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
699 if (!accessKey.isEmpty())
700 m_elementsByAccessKey.set(accessKey.impl(), &element);
702 if (ShadowRoot* root = element.shadowRoot())
703 buildAccessKeyMap(root);
707 void Document::invalidateAccessKeyMap()
709 m_accessKeyMapValid = false;
710 m_elementsByAccessKey.clear();
713 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
715 return m_imagesByUsemap.add(name, element, *this);
718 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
720 return m_imagesByUsemap.remove(name, element);
723 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
725 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
728 SelectorQueryCache& Document::selectorQueryCache()
730 if (!m_selectorQueryCache)
731 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
732 return *m_selectorQueryCache;
735 MediaQueryMatcher& Document::mediaQueryMatcher()
737 if (!m_mediaQueryMatcher)
738 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
739 return *m_mediaQueryMatcher;
742 void Document::setCompatibilityMode(CompatibilityMode mode)
744 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
746 bool wasInQuirksMode = inQuirksMode();
747 m_compatibilityMode = mode;
749 if (m_selectorQueryCache)
750 m_selectorQueryCache->invalidate();
752 if (inQuirksMode() != wasInQuirksMode) {
753 // All user stylesheets have to reparse using the different mode.
754 m_styleSheetCollection.clearPageUserSheet();
755 m_styleSheetCollection.invalidateInjectedStyleSheetCache();
759 String Document::compatMode() const
761 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
764 void Document::resetLinkColor()
766 m_linkColor = Color(0, 0, 238);
769 void Document::resetVisitedLinkColor()
771 m_visitedLinkColor = Color(85, 26, 139);
774 void Document::resetActiveLinkColor()
776 m_activeLinkColor.setNamedColor("red");
779 DOMImplementation* Document::implementation()
781 if (!m_implementation)
782 m_implementation = DOMImplementation::create(*this);
783 return m_implementation.get();
786 bool Document::hasManifest() const
788 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
791 DocumentType* Document::doctype() const
793 for (Node* node = firstChild(); node; node = node->nextSibling()) {
794 if (node->isDocumentTypeNode())
795 return static_cast<DocumentType*>(node);
800 void Document::childrenChanged(const ChildChange& change)
802 ContainerNode::childrenChanged(change);
804 Element* newDocumentElement = childrenOfType<Element>(*this).first();
805 if (newDocumentElement == m_documentElement)
807 m_documentElement = newDocumentElement;
808 // The root style used for media query matching depends on the document element.
809 clearStyleResolver();
812 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
814 if (!isValidName(name)) {
815 ec = INVALID_CHARACTER_ERR;
819 if (isXHTMLDocument())
820 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
822 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
825 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
827 return DocumentFragment::create(document());
830 PassRefPtr<Text> Document::createTextNode(const String& data)
832 return Text::create(*this, data);
835 PassRefPtr<Comment> Document::createComment(const String& data)
837 return Comment::create(*this, data);
840 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
842 if (isHTMLDocument()) {
843 ec = NOT_SUPPORTED_ERR;
846 return CDATASection::create(*this, data);
849 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
851 if (!isValidName(target)) {
852 ec = INVALID_CHARACTER_ERR;
855 if (isHTMLDocument()) {
856 ec = NOT_SUPPORTED_ERR;
859 return ProcessingInstruction::create(*this, target, data);
862 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
864 if (!isValidName(name)) {
865 ec = INVALID_CHARACTER_ERR;
868 if (isHTMLDocument()) {
869 ec = NOT_SUPPORTED_ERR;
872 return EntityReference::create(*this, name);
875 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
877 return Text::createEditingText(*this, text);
880 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
882 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
883 return propertySet->ensureCSSStyleDeclaration();
886 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
891 ec = NOT_SUPPORTED_ERR;
895 switch (importedNode->nodeType()) {
897 return createTextNode(importedNode->nodeValue());
898 case CDATA_SECTION_NODE:
899 return createCDATASection(importedNode->nodeValue(), ec);
900 case ENTITY_REFERENCE_NODE:
901 return createEntityReference(importedNode->nodeName(), ec);
902 case PROCESSING_INSTRUCTION_NODE:
903 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
905 return createComment(importedNode->nodeValue());
907 Element& oldElement = toElement(*importedNode);
908 // FIXME: The following check might be unnecessary. Is it possible that
909 // oldElement has mismatched prefix/namespace?
910 if (!hasValidNamespaceForElements(oldElement.tagQName())) {
915 RefPtr<Element> newElement = createElement(oldElement.tagQName(), false);
916 newElement->cloneDataFromElement(oldElement);
919 for (Node* oldChild = oldElement.firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
920 RefPtr<Node> newChild = importNode(oldChild, true, ec);
923 newElement->appendChild(newChild.release(), ec);
929 return newElement.release();
932 return Attr::create(*this, QualifiedName(nullAtom, toAttr(*importedNode).name(), nullAtom), toAttr(*importedNode).value());
933 case DOCUMENT_FRAGMENT_NODE: {
934 if (importedNode->isShadowRoot()) {
935 // ShadowRoot nodes should not be explicitly importable.
936 // Either they are imported along with their host node, or created implicitly.
939 DocumentFragment& oldFragment = toDocumentFragment(*importedNode);
940 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
942 for (Node* oldChild = oldFragment.firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
943 RefPtr<Node> newChild = importNode(oldChild, true, ec);
946 newFragment->appendChild(newChild.release(), ec);
952 return newFragment.release();
956 // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
957 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
959 case DOCUMENT_TYPE_NODE:
960 case XPATH_NAMESPACE_NODE:
963 ec = NOT_SUPPORTED_ERR;
968 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
971 ec = NOT_SUPPORTED_ERR;
975 if (source->isReadOnlyNode()) {
976 ec = NO_MODIFICATION_ALLOWED_ERR;
980 EventQueueScope scope;
982 switch (source->nodeType()) {
986 case DOCUMENT_TYPE_NODE:
987 case XPATH_NAMESPACE_NODE:
988 ec = NOT_SUPPORTED_ERR;
990 case ATTRIBUTE_NODE: {
991 Attr& attr = toAttr(*source);
992 if (attr.ownerElement())
993 attr.ownerElement()->removeAttributeNode(&attr, ec);
997 if (source->isShadowRoot()) {
998 // ShadowRoot cannot disconnect itself from the host node.
999 ec = HIERARCHY_REQUEST_ERR;
1002 if (source->isFrameOwnerElement()) {
1003 HTMLFrameOwnerElement& frameOwnerElement = toHTMLFrameOwnerElement(*source);
1004 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1005 ec = HIERARCHY_REQUEST_ERR;
1009 if (source->parentNode()) {
1010 source->parentNode()->removeChild(source.get(), ec);
1016 adoptIfNeeded(source.get());
1021 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1023 // These checks are from DOM Core Level 2, createElementNS
1024 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1025 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1027 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1030 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1031 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1032 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1033 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1034 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1035 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1038 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1040 return hasValidNamespaceForElements(qName);
1043 // FIXME: This should really be in a possible ElementFactory class.
1044 PassRefPtr<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1046 RefPtr<Element> element;
1048 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1049 if (name.namespaceURI() == xhtmlNamespaceURI)
1050 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1052 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1053 element = SVGElementFactory::createElement(name, *this, createdByParser);
1056 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1057 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1061 m_sawElementsInKnownNamespaces = true;
1063 element = Element::create(name, document());
1065 // <image> uses imgTag so we need a special rule.
1066 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1068 return element.release();
1071 bool Document::regionBasedColumnsEnabled() const
1073 return settings() && settings()->regionBasedColumnsEnabled();
1076 bool Document::cssStickyPositionEnabled() const
1078 return settings() && settings()->cssStickyPositionEnabled();
1081 bool Document::cssRegionsEnabled() const
1083 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1086 bool Document::cssCompositingEnabled() const
1088 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1091 bool Document::cssGridLayoutEnabled() const
1093 return settings() && settings()->cssGridLayoutEnabled();
1096 #if ENABLE(CSS_REGIONS)
1098 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1100 if (!cssRegionsEnabled() || !renderView())
1103 updateStyleIfNeeded();
1105 return namedFlows()->createCSSOMSnapshot();
1110 NamedFlowCollection* Document::namedFlows()
1113 m_namedFlows = NamedFlowCollection::create(this);
1115 return m_namedFlows.get();
1118 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1120 String prefix, localName;
1121 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1124 QualifiedName qName(prefix, localName, namespaceURI);
1125 if (!hasValidNamespaceForElements(qName)) {
1130 return createElement(qName, false);
1133 String Document::readyState() const
1135 DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1136 DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1137 DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1139 switch (m_readyState) {
1148 ASSERT_NOT_REACHED();
1152 void Document::setReadyState(ReadyState readyState)
1154 if (readyState == m_readyState)
1157 #if ENABLE(WEB_TIMING)
1158 switch (readyState) {
1160 if (!m_documentTiming.domLoading)
1161 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1164 if (!m_documentTiming.domInteractive)
1165 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1168 if (!m_documentTiming.domComplete)
1169 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1174 m_readyState = readyState;
1175 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1177 if (settings() && settings()->suppressesIncrementalRendering())
1178 setVisualUpdatesAllowed(readyState);
1181 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1183 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1184 switch (readyState) {
1186 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1187 ASSERT(m_visualUpdatesAllowed);
1188 setVisualUpdatesAllowed(false);
1191 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1194 if (m_visualUpdatesSuppressionTimer.isActive()) {
1195 ASSERT(!m_visualUpdatesAllowed);
1197 if (!view()->visualUpdatesAllowedByClient())
1200 setVisualUpdatesAllowed(true);
1202 ASSERT(m_visualUpdatesAllowed);
1207 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1209 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1212 m_visualUpdatesAllowed = visualUpdatesAllowed;
1214 if (visualUpdatesAllowed)
1215 m_visualUpdatesSuppressionTimer.stop();
1217 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1219 if (!visualUpdatesAllowed)
1222 FrameView* frameView = view();
1223 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1227 if (Page* page = this->page()) {
1228 if (frame()->isMainFrame()) {
1229 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1230 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1231 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1236 view()->updateCompositingLayersAfterLayout();
1238 if (RenderView* renderView = this->renderView())
1239 renderView->repaintViewAndCompositedLayers();
1241 if (Frame* frame = this->frame())
1242 frame->loader().forcePageTransitionIfNeeded();
1245 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>&)
1247 ASSERT(!m_visualUpdatesAllowed);
1249 // If the client is extending the visual update suppression period explicitly, the
1250 // watchdog should not re-enable visual updates itself, but should wait for the client.
1251 if (!view()->visualUpdatesAllowedByClient())
1254 setVisualUpdatesAllowed(true);
1257 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1259 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1260 // both of which we can determine by looking at the timer.
1262 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1263 setVisualUpdatesAllowed(true);
1266 AtomicString Document::encoding() const
1268 if (TextResourceDecoder* d = decoder())
1269 return d->encoding().domName();
1273 String Document::defaultCharset() const
1275 if (Settings* settings = this->settings())
1276 return settings->defaultTextEncodingName();
1280 void Document::setCharset(const String& charset)
1284 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1287 void Document::setContentLanguage(const String& language)
1289 if (m_contentLanguage == language)
1291 m_contentLanguage = language;
1293 // Recalculate style so language is used when selecting the initial font.
1294 styleResolverChanged(DeferRecalcStyle);
1297 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1299 if (!implementation()->hasFeature("XML", String())) {
1300 ec = NOT_SUPPORTED_ERR;
1304 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1305 ec = NOT_SUPPORTED_ERR;
1309 m_xmlVersion = version;
1312 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1314 if (!implementation()->hasFeature("XML", String())) {
1315 ec = NOT_SUPPORTED_ERR;
1319 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1322 void Document::setDocumentURI(const String& uri)
1324 // This property is read-only from JavaScript, but writable from Objective-C.
1325 m_documentURI = uri;
1329 URL Document::baseURI() const
1334 void Document::setContent(const String& content)
1337 // FIXME: This should probably use insert(), but that's (intentionally)
1338 // not implemented for the XML parser as it's normally synonymous with
1339 // document.write(). append() will end up yielding, but close() will
1340 // pump the tokenizer syncrhonously and finish the parse.
1341 m_parser->append(content.impl());
1345 String Document::suggestedMIMEType() const
1347 if (isXHTMLDocument())
1348 return ASCIILiteral("application/xhtml+xml");
1349 if (isSVGDocument())
1350 return ASCIILiteral("image/svg+xml");
1351 if (xmlStandalone())
1352 return ASCIILiteral("text/xml");
1353 if (isHTMLDocument())
1354 return ASCIILiteral("text/html");
1355 if (DocumentLoader* loader = this->loader())
1356 return loader->responseMIMEType();
1360 Element* Document::elementFromPoint(int x, int y) const
1362 if (!hasLivingRenderTree())
1365 return TreeScope::elementFromPoint(x, y);
1368 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1370 if (!hasLivingRenderTree())
1372 LayoutPoint localPoint;
1373 Node* node = nodeFromPoint(this, x, y, &localPoint);
1377 Node* shadowAncestorNode = ancestorInThisScope(node);
1378 if (shadowAncestorNode != node) {
1379 unsigned offset = shadowAncestorNode->nodeIndex();
1380 ContainerNode* container = shadowAncestorNode->parentNode();
1381 return Range::create(*this, container, offset, container, offset);
1384 RenderObject* renderer = node->renderer();
1387 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1388 if (visiblePosition.isNull())
1391 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1392 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1396 * Performs three operations:
1397 * 1. Convert control characters to spaces
1398 * 2. Trim leading and trailing spaces
1399 * 3. Collapse internal whitespace.
1401 template <typename CharacterType>
1402 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1404 const String& title = titleWithDirection.string();
1405 const CharacterType* characters = title.getCharacters<CharacterType>();
1406 unsigned length = title.length();
1409 StringBuffer<CharacterType> buffer(length);
1410 unsigned builderIndex = 0;
1412 // Skip leading spaces and leading characters that would convert to spaces
1413 for (i = 0; i < length; ++i) {
1414 CharacterType c = characters[i];
1415 if (!(c <= 0x20 || c == 0x7F))
1420 return StringWithDirection();
1422 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1423 bool previousCharWasWS = false;
1424 for (; i < length; ++i) {
1425 CharacterType c = characters[i];
1426 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1427 if (previousCharWasWS)
1429 buffer[builderIndex++] = ' ';
1430 previousCharWasWS = true;
1432 buffer[builderIndex++] = c;
1433 previousCharWasWS = false;
1437 // Strip trailing spaces
1438 while (builderIndex > 0) {
1440 if (buffer[builderIndex] != ' ')
1444 if (!builderIndex && buffer[builderIndex] == ' ')
1445 return StringWithDirection();
1447 buffer.shrink(builderIndex + 1);
1449 // Replace the backslashes with currency symbols if the encoding requires it.
1450 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1452 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1455 void Document::updateTitle(const StringWithDirection& title)
1457 if (m_rawTitle == title)
1462 if (m_rawTitle.string().isEmpty())
1463 m_title = StringWithDirection();
1465 if (m_rawTitle.string().is8Bit())
1466 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1468 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1470 if (DocumentLoader* loader = this->loader())
1471 loader->setTitle(m_title);
1474 void Document::setTitle(const String& title)
1476 // Title set by JavaScript -- overrides any title elements.
1477 m_titleSetExplicitly = true;
1478 if (!isHTMLDocument() && !isXHTMLDocument())
1479 m_titleElement = nullptr;
1480 else if (!m_titleElement) {
1481 if (HTMLElement* headElement = head()) {
1482 m_titleElement = createElement(titleTag, false);
1483 headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION);
1487 // The DOM API has no method of specifying direction, so assume LTR.
1488 updateTitle(StringWithDirection(title, LTR));
1490 if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
1491 toHTMLTitleElement(m_titleElement.get())->setText(title);
1494 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1496 if (titleElement != m_titleElement) {
1497 if (m_titleElement || m_titleSetExplicitly) {
1498 // Only allow the first title element to change the title -- others have no effect.
1501 m_titleElement = titleElement;
1507 void Document::removeTitle(Element* titleElement)
1509 if (m_titleElement != titleElement)
1512 m_titleElement = nullptr;
1513 m_titleSetExplicitly = false;
1515 // Update title based on first title element in the head, if one exists.
1516 if (HTMLElement* headElement = head()) {
1517 if (auto firstTitle = childrenOfType<HTMLTitleElement>(*headElement).first())
1518 setTitleElement(firstTitle->textWithDirection(), firstTitle);
1521 if (!m_titleElement)
1522 updateTitle(StringWithDirection());
1525 #if ENABLE(PAGE_VISIBILITY_API)
1526 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1528 m_visibilityStateCallbackElements.add(element);
1531 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1533 m_visibilityStateCallbackElements.remove(element);
1536 void Document::visibilityStateChanged()
1538 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1539 for (auto it = m_visibilityStateCallbackElements.begin(); it != m_visibilityStateCallbackElements.end(); ++it)
1540 (*it)->visibilityStateChanged();
1543 PageVisibilityState Document::pageVisibilityState() const
1545 // The visibility of the document is inherited from the visibility of the
1546 // page. If there is no page associated with the document, we will assume
1547 // that the page is hidden, as specified by the spec:
1548 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1549 if (!m_frame || !m_frame->page())
1550 return PageVisibilityStateHidden;
1551 return m_frame->page()->visibilityState();
1554 String Document::visibilityState() const
1556 return pageVisibilityStateString(pageVisibilityState());
1559 bool Document::hidden() const
1561 return pageVisibilityState() != PageVisibilityStateVisible;
1565 #if ENABLE(CSP_NEXT)
1566 DOMSecurityPolicy* Document::securityPolicy()
1568 if (!m_domSecurityPolicy)
1569 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1570 return m_domSecurityPolicy.get();
1574 String Document::nodeName() const
1579 Node::NodeType Document::nodeType() const
1581 return DOCUMENT_NODE;
1584 FormController& Document::formController()
1586 if (!m_formController)
1587 m_formController = FormController::create();
1588 return *m_formController;
1591 Vector<String> Document::formElementsState() const
1593 if (!m_formController)
1594 return Vector<String>();
1595 return m_formController->formElementsState();
1598 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1600 if (!stateVector.size() && !m_formController)
1602 formController().setStateForNewFormElements(stateVector);
1605 FrameView* Document::view() const
1607 return m_frame ? m_frame->view() : nullptr;
1610 Page* Document::page() const
1612 return m_frame ? m_frame->page() : nullptr;
1615 Settings* Document::settings() const
1617 return m_frame ? &m_frame->settings() : nullptr;
1620 PassRefPtr<Range> Document::createRange()
1622 return Range::create(*this);
1625 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1626 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1629 ec = NOT_SUPPORTED_ERR;
1632 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1635 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1636 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1639 ec = NOT_SUPPORTED_ERR;
1642 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1645 void Document::scheduleForcedStyleRecalc()
1647 m_pendingStyleRecalcShouldForce = true;
1648 scheduleStyleRecalc();
1651 void Document::scheduleStyleRecalc()
1653 if (shouldDisplaySeamlesslyWithParent()) {
1654 // When we're seamless, our parent document manages our style recalcs.
1655 ownerElement()->setNeedsStyleRecalc();
1656 ownerElement()->document().scheduleStyleRecalc();
1660 if (m_styleRecalcTimer.isActive() || inPageCache())
1663 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1665 // FIXME: Why on earth is this here? This is clearly misplaced.
1666 invalidateAccessKeyMap();
1668 m_styleRecalcTimer.startOneShot(0);
1670 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1673 void Document::unscheduleStyleRecalc()
1675 ASSERT(!childNeedsStyleRecalc());
1677 m_styleRecalcTimer.stop();
1678 m_pendingStyleRecalcShouldForce = false;
1681 bool Document::hasPendingStyleRecalc() const
1683 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1686 bool Document::hasPendingForcedStyleRecalc() const
1688 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1691 void Document::styleRecalcTimerFired(Timer<Document>&)
1693 updateStyleIfNeeded();
1696 void Document::recalcStyle(Style::Change change)
1698 ASSERT(!view() || !view()->isPainting());
1700 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1704 FrameView& frameView = m_renderView->frameView();
1705 if (frameView.isPainting())
1708 if (m_inStyleRecalc)
1709 return; // Guard against re-entrancy. -dwh
1711 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1713 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1714 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1715 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1716 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1717 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1718 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1720 m_styleSheetCollection.flushPendingUpdates();
1722 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1724 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1725 m_styleSheetCollection.setUsesRemUnit(true);
1727 m_inStyleRecalc = true;
1729 PostAttachCallbackDisabler disabler(*this);
1730 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1732 if (m_pendingStyleRecalcShouldForce)
1733 change = Style::Force;
1735 if (change == Style::Force) {
1736 // This may get set again during style resolve.
1737 m_hasNodesWithPlaceholderStyle = false;
1740 Style::resolveTree(*this, change);
1742 frameView.updateCompositingLayersAfterStyleChange();
1744 clearNeedsStyleRecalc();
1745 clearChildNeedsStyleRecalc();
1746 unscheduleStyleRecalc();
1748 m_inStyleRecalc = false;
1750 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1751 if (m_styleResolver)
1752 m_styleSheetCollection.resetCSSFeatureFlags();
1755 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1756 if (m_closeAfterStyleRecalc) {
1757 m_closeAfterStyleRecalc = false;
1761 InspectorInstrumentation::didRecalculateStyle(cookie);
1763 // As a result of the style recalculation, the currently hovered element might have been
1764 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1765 // to check if any other elements ended up under the mouse pointer due to re-layout.
1766 if (m_hoveredElement && !m_hoveredElement->renderer())
1767 frameView.frame().eventHandler().dispatchFakeMouseMoveEventSoon();
1769 // Style change may reset the focus, e.g. display: none, visibility: hidden.
1770 resetHiddenFocusElementSoon();
1773 void Document::updateStyleIfNeeded()
1775 ASSERT(isMainThread());
1776 ASSERT(!view() || !view()->isPainting());
1778 if (!view() || view()->isInLayout())
1781 if (m_optimizedStyleSheetUpdateTimer.isActive())
1782 styleResolverChanged(RecalcStyleIfNeeded);
1784 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1787 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
1788 recalcStyle(Style::NoChange);
1791 void Document::updateLayout()
1793 ASSERT(isMainThread());
1795 FrameView* frameView = view();
1796 if (frameView && frameView->isInLayout()) {
1797 // View layout should not be re-entrant.
1798 ASSERT_NOT_REACHED();
1802 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1804 if (Element* oe = ownerElement())
1805 oe->document().updateLayout();
1807 updateStyleIfNeeded();
1809 StackStats::LayoutCheckPoint layoutCheckPoint;
1811 // Only do a layout if changes have occurred that make it necessary.
1812 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1813 frameView->layout();
1815 // Active focus element's isFocusable() state may change after Layout. e.g. width: 0px or height: 0px.
1816 resetHiddenFocusElementSoon();
1819 // FIXME: This is a bad idea and needs to be removed eventually.
1820 // Other browsers load stylesheets before they continue parsing the web page.
1821 // Since we don't, we can run JavaScript code that needs answers before the
1822 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1823 // lets us get reasonable answers. The long term solution to this problem is
1824 // to instead suspend JavaScript execution.
1825 void Document::updateLayoutIgnorePendingStylesheets()
1827 bool oldIgnore = m_ignorePendingStylesheets;
1829 if (!haveStylesheetsLoaded()) {
1830 m_ignorePendingStylesheets = true;
1831 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1832 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1833 // with accurate style information. (Our suppression involves blanking the whole page at the
1834 // moment. If it were more refined, we might be able to do something better.)
1835 // It's worth noting though that this entire method is a hack, since what we really want to do is
1836 // suspend JS instead of doing a layout with inaccurate information.
1837 HTMLElement* bodyElement = body();
1838 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1839 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1840 styleResolverChanged(RecalcStyleImmediately);
1841 } else if (m_hasNodesWithPlaceholderStyle)
1842 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1843 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1844 // but here we need up-to-date style immediately.
1845 recalcStyle(Style::Force);
1850 m_ignorePendingStylesheets = oldIgnore;
1853 PassRef<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1855 ASSERT_ARG(element, &element->document() == this);
1857 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1858 ResourceLoadScheduler::Suspender suspender(*platformStrategies()->loaderStrategy()->resourceLoadScheduler());
1860 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
1861 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : nullptr);
1864 bool Document::isPageBoxVisible(int pageIndex)
1866 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
1867 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
1870 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1872 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
1873 RenderView* view = renderView();
1875 int width = pageSize.width();
1876 int height = pageSize.height();
1877 switch (style->pageSizeType()) {
1878 case PAGE_SIZE_AUTO:
1880 case PAGE_SIZE_AUTO_LANDSCAPE:
1882 std::swap(width, height);
1884 case PAGE_SIZE_AUTO_PORTRAIT:
1886 std::swap(width, height);
1888 case PAGE_SIZE_RESOLVED: {
1889 LengthSize size = style->pageSize();
1890 ASSERT(size.width().isFixed());
1891 ASSERT(size.height().isFixed());
1892 width = valueForLength(size.width(), 0, view);
1893 height = valueForLength(size.height(), 0, view);
1897 ASSERT_NOT_REACHED();
1899 pageSize = IntSize(width, height);
1901 // The percentage is calculated with respect to the width even for margin top and bottom.
1902 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1903 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
1904 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
1905 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
1906 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
1909 void Document::setIsViewSource(bool isViewSource)
1911 m_isViewSource = isViewSource;
1912 if (!m_isViewSource)
1915 setSecurityOrigin(SecurityOrigin::createUnique());
1918 void Document::createStyleResolver()
1920 bool matchAuthorAndUserStyles = true;
1921 if (Settings* settings = this->settings())
1922 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
1923 m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
1924 m_styleSheetCollection.combineCSSFeatureFlags();
1927 void Document::clearStyleResolver()
1929 m_styleResolver.clear();
1932 void Document::createRenderTree()
1934 ASSERT(!renderView());
1935 ASSERT(!m_inPageCache);
1936 ASSERT(!m_axObjectCache || this != &topDocument());
1938 if (m_isNonRenderedPlaceholder)
1941 // FIXME: It would be better if we could pass the resolved document style directly here.
1942 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
1943 Node::setRenderer(m_renderView.get());
1945 renderView()->setIsInWindow(true);
1947 recalcStyle(Style::Force);
1950 static void pageWheelEventHandlerCountChanged(Page& page)
1953 for (const Frame* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
1954 if (Document* document = frame->document())
1955 count += document->wheelEventHandlerCount();
1957 page.chrome().client().numWheelEventHandlersChanged(count);
1960 void Document::didBecomeCurrentDocumentInFrame()
1962 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
1963 // If so, then m_frame could become 0, and we need to do something about that.
1965 m_frame->script().updateDocument();
1967 if (!hasLivingRenderTree())
1970 updateViewportArguments();
1972 // FIXME: Doing this only for the main frame is insufficient.
1973 // Changing a subframe can also change the wheel event handler count.
1974 // FIXME: Doing this only when a document goes into the frame is insufficient.
1975 // Removing a document can also change the wheel event handler count.
1976 // FIXME: Doing this every time is a waste. If the current document and its
1977 // subframes' documents have no wheel event handlers, then the count did not change,
1978 // unless the documents they are replacing had wheel event handlers.
1979 if (page() && m_frame->isMainFrame())
1980 pageWheelEventHandlerCountChanged(*page());
1982 #if ENABLE(TOUCH_EVENTS)
1983 // FIXME: Doing this only for the main frame is insufficient.
1984 // A subframe could have touch event handlers.
1985 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
1986 page()->chrome().client().needTouchEvents(true);
1990 // Ensure that document scheduled task state matches frame timer state. It can be out of sync
1991 // if timers state changed while the document was not in the frame (possibly in page cache,
1992 // or simply newly created).
1993 // FIXME: How does this interact with cross-platform code below?
1994 if (m_frame->timersPaused())
1995 suspendScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
1997 resumeScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
2000 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2001 suspendScriptedAnimationControllerCallbacks();
2002 m_frame->animation().suspendAnimationsForDocument(this);
2003 suspendActiveDOMObjects(ActiveDOMObject::PageWillBeSuspended);
2007 void Document::disconnectFromFrame()
2012 void Document::destroyRenderTree()
2014 ASSERT(hasLivingRenderTree());
2015 ASSERT(!m_inPageCache);
2017 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2019 if (this == &topDocument())
2020 clearAXObjectCache();
2022 documentWillBecomeInactive();
2024 if (FrameView* frameView = view())
2025 frameView->detachCustomScrollbars();
2027 #if ENABLE(FULLSCREEN_API)
2028 if (m_fullScreenRenderer)
2029 setFullScreenRenderer(nullptr);
2032 m_hoveredElement = nullptr;
2033 m_focusedElement = nullptr;
2034 m_activeElement = nullptr;
2036 if (m_documentElement)
2037 Style::detachRenderTree(*m_documentElement);
2039 clearChildNeedsStyleRecalc();
2041 unscheduleStyleRecalc();
2043 m_renderView = nullptr;
2044 Node::setRenderer(nullptr);
2046 #if ENABLE(IOS_TEXT_AUTOSIZING)
2047 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2048 m_textAutoSizedNodes.clear();
2052 void Document::prepareForDestruction()
2054 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
2055 clearTouchEventListeners();
2058 disconnectDescendantFrames();
2059 if (m_domWindow && m_frame)
2060 m_domWindow->willDetachDocumentFromFrame();
2062 destroyRenderTree();
2064 if (isPluginDocument())
2065 toPluginDocument(this)->detachFromPluginElement();
2067 #if ENABLE(POINTER_LOCK)
2069 page()->pointerLockController()->documentDetached(this);
2072 stopActiveDOMObjects();
2073 m_eventQueue.close();
2074 #if ENABLE(FULLSCREEN_API)
2075 m_fullScreenChangeEventTargetQueue.clear();
2076 m_fullScreenErrorEventTargetQueue.clear();
2081 #if ENABLE(SHARED_WORKERS)
2082 SharedWorkerRepository::documentDetached(this);
2085 #if ENABLE(TOUCH_EVENTS)
2086 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2087 parentDocument()->didRemoveEventTargetNode(this);
2090 if (m_mediaQueryMatcher)
2091 m_mediaQueryMatcher->documentDestroyed();
2093 disconnectFromFrame();
2096 void Document::removeAllEventListeners()
2098 EventTarget::removeAllEventListeners();
2101 m_domWindow->removeAllEventListeners();
2102 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
2103 clearTouchEventListeners();
2105 for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
2106 node->removeAllEventListeners();
2109 void Document::platformSuspendOrStopActiveDOMObjects()
2112 #if ENABLE(DEVICE_ORIENTATION)
2113 if (m_deviceMotionController)
2114 m_deviceMotionController->suspendUpdates();
2115 if (m_deviceOrientationController)
2116 m_deviceOrientationController->suspendUpdates();
2119 if (WebThreadCountOfObservedContentModifiers() > 0) {
2120 Frame* frame = this->frame();
2121 if (Page* page = frame ? frame->page() : nullptr)
2122 page->chrome().client().clearContentChangeObservers(frame);
2127 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2129 ScriptExecutionContext::suspendActiveDOMObjects(why);
2130 platformSuspendOrStopActiveDOMObjects();
2133 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2135 ScriptExecutionContext::resumeActiveDOMObjects(why);
2137 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2138 if (m_deviceMotionController)
2139 m_deviceMotionController->resumeUpdates();
2140 if (m_deviceOrientationController)
2141 m_deviceOrientationController->resumeUpdates();
2143 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2146 void Document::stopActiveDOMObjects()
2148 ScriptExecutionContext::stopActiveDOMObjects();
2149 platformSuspendOrStopActiveDOMObjects();
2152 void Document::clearAXObjectCache()
2154 ASSERT(&topDocument() == this);
2155 // Clear the cache member variable before calling delete because attempts
2156 // are made to access it during destruction.
2157 m_axObjectCache.clear();
2160 AXObjectCache* Document::existingAXObjectCache() const
2162 Document& topDocument = this->topDocument();
2163 if (!topDocument.hasLivingRenderTree())
2165 return topDocument.m_axObjectCache.get();
2168 AXObjectCache* Document::axObjectCache() const
2170 if (!AXObjectCache::accessibilityEnabled())
2173 // The only document that actually has a AXObjectCache is the top-level
2174 // document. This is because we need to be able to get from any WebCoreAXObject
2175 // to any other WebCoreAXObject on the same page. Using a single cache allows
2176 // lookups across nested webareas (i.e. multiple documents).
2177 Document& topDocument = this->topDocument();
2179 // If the document has already been detached, do not make a new axObjectCache.
2180 if (!topDocument.hasLivingRenderTree())
2183 ASSERT(&topDocument == this || !m_axObjectCache);
2184 if (!topDocument.m_axObjectCache)
2185 topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2186 return topDocument.m_axObjectCache.get();
2189 void Document::setVisuallyOrdered()
2191 m_visuallyOrdered = true;
2193 renderView()->style().setRTLOrdering(VisualOrder);
2196 PassRefPtr<DocumentParser> Document::createParser()
2198 // FIXME: this should probably pass the frame instead
2199 return XMLDocumentParser::create(*this, view());
2202 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2204 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2207 void Document::open(Document* ownerDocument)
2209 if (ownerDocument) {
2210 setURL(ownerDocument->url());
2211 m_cookieURL = ownerDocument->cookieURL();
2212 setSecurityOrigin(ownerDocument->securityOrigin());
2216 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2217 if (parser->isParsing()) {
2218 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2219 if (parser->isExecutingScript())
2222 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2227 if (m_frame->loader().state() == FrameStateProvisional)
2228 m_frame->loader().stopAllLoaders();
2231 removeAllEventListeners();
2233 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2234 parser->setWasCreatedByScript(true);
2237 m_frame->loader().didExplicitOpen();
2240 void Document::detachParser()
2248 void Document::cancelParsing()
2253 // We have to clear the parser to avoid possibly triggering
2254 // the onload handler when closing as a side effect of a cancel-style
2255 // change, such as opening a new document or closing the window while
2261 void Document::implicitOpen()
2267 setCompatibilityMode(NoQuirksMode);
2269 // Documents rendered seamlessly should start out requiring a stylesheet
2270 // collection update in order to ensure they inherit all the relevant data
2271 // from their parent.
2272 if (shouldDisplaySeamlesslyWithParent())
2273 styleResolverChanged(DeferRecalcStyle);
2275 m_parser = createParser();
2277 setReadyState(Loading);
2280 HTMLElement* Document::body() const
2282 // If the document element contains both a frameset and a body, the frameset wins.
2283 auto element = documentElement();
2286 if (auto frameset = childrenOfType<HTMLFrameSetElement>(*element).first())
2288 return childrenOfType<HTMLBodyElement>(*element).first();
2291 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2293 RefPtr<HTMLElement> newBody = prpNewBody;
2295 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2296 ec = HIERARCHY_REQUEST_ERR;
2300 if (&newBody->document() != this) {
2302 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2306 newBody = toHTMLElement(node.get());
2309 HTMLElement* b = body();
2311 documentElement()->appendChild(newBody.release(), ec);
2313 documentElement()->replaceChild(newBody.release(), b, ec);
2316 HTMLHeadElement* Document::head()
2318 if (auto element = documentElement())
2319 return childrenOfType<HTMLHeadElement>(*element).first();
2323 void Document::close()
2325 // FIXME: We should follow the specification more closely:
2326 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2328 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2334 void Document::explicitClose()
2336 if (RefPtr<DocumentParser> parser = m_parser)
2340 // Because we have no frame, we don't know if all loading has completed,
2341 // so we just call implicitClose() immediately. FIXME: This might fire
2342 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2347 m_frame->loader().checkCompleted();
2350 void Document::implicitClose()
2352 // 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.
2353 if (m_inStyleRecalc) {
2354 m_closeAfterStyleRecalc = true;
2358 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2359 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2364 // Call to dispatchWindowLoadEvent can blow us from underneath.
2365 Ref<Document> protect(*this);
2367 m_processingLoadEvent = true;
2369 ScriptableDocumentParser* parser = scriptableDocumentParser();
2370 m_wellFormed = parser && parser->wellFormed();
2372 // We have to clear the parser, in case someone document.write()s from the
2373 // onLoad event handler, as in Radar 3206524.
2376 // FIXME: We kick off the icon loader when the Document is done parsing.
2377 // There are earlier opportunities we could start it:
2378 // -When the <head> finishes parsing
2379 // -When any new HTMLLinkElement is inserted into the document
2380 // But those add a dynamic component to the favicon that has UI
2381 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2384 f->loader().icon().startLoader();
2385 f->animation().startAnimationsIfNotSuspended(this);
2388 ImageLoader::dispatchPendingBeforeLoadEvents();
2389 ImageLoader::dispatchPendingLoadEvents();
2390 ImageLoader::dispatchPendingErrorEvents();
2392 HTMLLinkElement::dispatchPendingLoadEvents();
2393 HTMLStyleElement::dispatchPendingLoadEvents();
2396 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2397 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2398 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2399 if (svgExtensions())
2400 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2403 dispatchWindowLoadEvent();
2404 enqueuePageshowEvent(PageshowEventNotPersisted);
2405 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2408 f->loader().handledOnloadEvents();
2409 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2410 if (!ownerElement())
2411 printf("onload fired at %lld\n", elapsedTime().count());
2414 // An event handler may have removed the frame
2416 m_processingLoadEvent = false;
2420 // Make sure both the initial layout and reflow happen after the onload
2421 // fires. This will improve onload scores, and other browsers do it.
2422 // If they wanna cheat, we can too. -dwh
2424 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2425 // Just bail out. Before or during the onload we were shifted to another page.
2426 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2427 m_processingLoadEvent = false;
2428 view()->unscheduleRelayout();
2432 frame()->loader().checkCallImplicitClose();
2434 // We used to force a synchronous display and flush here. This really isn't
2435 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2436 // (if your platform is syncing flushes and limiting them to 60fps).
2437 m_overMinimumLayoutThreshold = true;
2438 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2439 updateStyleIfNeeded();
2441 // Always do a layout after loading if needed.
2442 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2446 m_processingLoadEvent = false;
2448 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2449 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2450 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2451 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2452 // exists in the cache (we ignore the return value because we don't need it here). This is
2453 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2454 axObjectCache()->getOrCreate(renderView());
2455 if (this == &topDocument())
2456 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLoadComplete);
2458 // AXLoadComplete can only be posted on the top document, so if it's a document
2459 // in an iframe that just finished loading, post AXLayoutComplete instead.
2460 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2466 if (svgExtensions())
2467 accessSVGExtensions()->startAnimations();
2471 void Document::setParsing(bool b)
2475 if (m_bParsing && !m_sharedObjectPool)
2476 m_sharedObjectPool = DocumentSharedObjectPool::create();
2478 if (!m_bParsing && view())
2479 view()->scheduleRelayout();
2481 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2482 if (!ownerElement() && !m_bParsing)
2483 printf("Parsing finished at %lld\n", elapsedTime().count());
2487 bool Document::shouldScheduleLayout()
2489 // This function will only be called when FrameView thinks a layout is needed.
2490 // This enforces a couple extra rules.
2492 // (a) Only schedule a layout once the stylesheets are loaded.
2493 // (b) Only schedule layout once we have a body element.
2495 return (haveStylesheetsLoaded() && body())
2496 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2499 bool Document::isLayoutTimerActive()
2501 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2504 std::chrono::milliseconds Document::minimumLayoutDelay()
2506 if (m_overMinimumLayoutThreshold)
2507 return std::chrono::milliseconds(0);
2509 std::chrono::milliseconds elapsed = elapsedTime();
2510 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2512 // We'll want to schedule the timer to fire at the minimum layout threshold.
2513 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2516 std::chrono::milliseconds Document::elapsedTime() const
2518 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2520 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2523 void Document::write(const SegmentedString& text, Document* ownerDocument)
2525 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2527 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2528 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2530 if (m_writeRecursionIsTooDeep)
2533 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2534 if (!ownerElement())
2535 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2538 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2539 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2542 if (!hasInsertionPoint)
2543 open(ownerDocument);
2546 m_parser->insert(text);
2548 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2549 if (!ownerElement())
2550 printf("Ending a document.write at %lld\n", elapsedTime().count());
2554 void Document::write(const String& text, Document* ownerDocument)
2556 write(SegmentedString(text), ownerDocument);
2559 void Document::writeln(const String& text, Document* ownerDocument)
2561 write(text, ownerDocument);
2562 write("\n", ownerDocument);
2565 double Document::minimumTimerInterval() const
2569 return ScriptExecutionContext::minimumTimerInterval();
2570 return p->settings().minDOMTimerInterval();
2573 double Document::timerAlignmentInterval() const
2577 return ScriptExecutionContext::timerAlignmentInterval();
2578 return p->settings().domTimerAlignmentInterval();
2581 EventTarget* Document::errorEventTarget()
2583 return m_domWindow.get();
2586 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2588 addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber, callStack);
2591 void Document::setURL(const URL& url)
2593 const URL& newURL = url.isEmpty() ? blankURL() : url;
2594 if (newURL == m_url)
2598 m_documentURI = m_url.string();
2602 void Document::updateBaseURL()
2604 URL oldBaseURL = m_baseURL;
2605 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2606 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2607 // from the Document interface otherwise.
2608 if (!m_baseElementURL.isEmpty())
2609 m_baseURL = m_baseElementURL;
2610 else if (!m_baseURLOverride.isEmpty())
2611 m_baseURL = m_baseURLOverride;
2613 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2614 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2615 // and DOM 3 Core does not specify how it should be resolved.
2616 m_baseURL = URL(ParsedURLString, documentURI());
2619 if (m_selectorQueryCache)
2620 m_selectorQueryCache->invalidate();
2622 if (!m_baseURL.isValid())
2625 if (m_elementSheet) {
2626 // Element sheet is silly. It never contains anything.
2627 ASSERT(!m_elementSheet->contents().ruleCount());
2628 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2629 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2630 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2631 m_elementSheet->contents().parserSetUsesRemUnits(usesRemUnits);
2634 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2635 // Base URL change changes any relative visited links.
2636 // 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.
2637 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2638 anchor.invalidateCachedVisitedLinkHash();
2642 void Document::setBaseURLOverride(const URL& url)
2644 m_baseURLOverride = url;
2648 void Document::processBaseElement()
2650 // Find the first href attribute in a base element and the first target attribute in a base element.
2651 const AtomicString* href = nullptr;
2652 const AtomicString* target = nullptr;
2653 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2654 for (auto base = baseDescendants.begin(), end = baseDescendants.end(); base != end && (!href || !target); ++base) {
2656 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2657 if (!value.isNull())
2661 const AtomicString& value = base->fastGetAttribute(targetAttr);
2662 if (!value.isNull())
2667 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2670 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2671 if (!strippedHref.isEmpty())
2672 baseElementURL = URL(url(), strippedHref);
2674 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2675 m_baseElementURL = baseElementURL;
2679 m_baseTarget = target ? *target : nullAtom;
2682 String Document::userAgent(const URL& url) const
2684 return frame() ? frame()->loader().userAgent(url) : String();
2687 void Document::disableEval(const String& errorMessage)
2692 frame()->script().disableEval(errorMessage);
2695 bool Document::canNavigate(Frame* targetFrame)
2700 // FIXME: We shouldn't call this function without a target frame, but
2701 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2702 // returning true when supplied with a 0 targetFrame.
2706 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2707 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2710 if (isSandboxed(SandboxNavigation)) {
2711 if (targetFrame->tree().isDescendantOf(m_frame))
2714 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2715 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2716 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2718 printNavigationErrorMessage(targetFrame, url(), reason);
2722 // This is the normal case. A document can navigate its decendant frames,
2723 // or, more generally, a document can navigate a frame if the document is
2724 // in the same origin as any of that frame's ancestors (in the frame
2727 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2728 // historical information about this security check.
2729 if (canAccessAncestor(securityOrigin(), targetFrame))
2732 // Top-level frames are easier to navigate than other frames because they
2733 // display their URLs in the address bar (in most browsers). However, there
2734 // are still some restrictions on navigation to avoid nuisance attacks.
2735 // Specifically, a document can navigate a top-level frame if that frame
2736 // opened the document or if the document is the same-origin with any of
2737 // the top-level frame's opener's ancestors (in the frame hierarchy).
2739 // In both of these cases, the document performing the navigation is in
2740 // some way related to the frame being navigate (e.g., by the "opener"
2741 // and/or "parent" relation). Requiring some sort of relation prevents a
2742 // document from navigating arbitrary, unrelated top-level frames.
2743 if (!targetFrame->tree().parent()) {
2744 if (targetFrame == m_frame->loader().opener())
2747 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
2751 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2755 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2757 Frame* currentFrame = m_frame;
2761 Frame* ancestorFrame = currentFrame->tree().parent();
2763 while (ancestorFrame) {
2764 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2765 return currentFrame;
2766 currentFrame = ancestorFrame;
2767 ancestorFrame = ancestorFrame->tree().parent();
2773 void Document::seamlessParentUpdatedStylesheets()
2775 styleResolverChanged(RecalcStyleImmediately);
2778 void Document::didRemoveAllPendingStylesheet()
2780 m_needsNotifyRemoveAllPendingStylesheet = false;
2782 styleResolverChanged(DeferRecalcStyleIfNeeded);
2784 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
2785 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2787 renderView()->repaintViewAndCompositedLayers();
2790 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2791 parser->executeScriptsWaitingForStylesheets();
2793 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2794 view()->scrollToFragment(m_url);
2797 CSSStyleSheet& Document::elementSheet()
2799 if (!m_elementSheet)
2800 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2801 return *m_elementSheet;
2804 void Document::processHttpEquiv(const String& equiv, const String& content)
2806 ASSERT(!equiv.isNull() && !content.isNull());
2808 Frame* frame = this->frame();
2810 if (equalIgnoringCase(equiv, "default-style")) {
2811 // The preferred style set has been overridden as per section
2812 // 14.3.2 of the HTML4.0 specification. We need to update the
2813 // sheet used variable and then update our style selector.
2814 // For more info, see the test at:
2815 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2817 m_styleSheetCollection.setSelectedStylesheetSetName(content);
2818 m_styleSheetCollection.setPreferredStylesheetSetName(content);
2819 styleResolverChanged(DeferRecalcStyle);
2820 } else if (equalIgnoringCase(equiv, "refresh")) {
2823 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2825 url = m_url.string();
2827 url = completeURL(url).string();
2828 frame->navigationScheduler().scheduleRedirect(delay, url);
2830 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2831 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2832 if (isHTMLDocument()) {
2833 // Exception (for sandboxed documents) ignored.
2834 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
2836 } else if (equalIgnoringCase(equiv, "content-language"))
2837 setContentLanguage(content);
2838 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2839 parseDNSPrefetchControlHeader(content);
2840 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2842 FrameLoader& frameLoader = frame->loader();
2843 unsigned long requestIdentifier = 0;
2844 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
2845 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
2846 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
2847 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
2848 frameLoader.stopAllLoaders();
2849 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
2850 // intent, we must navigate away from the possibly partially-rendered document to a location that
2851 // doesn't inherit the parent's SecurityOrigin.
2852 frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
2853 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
2856 } else if (equalIgnoringCase(equiv, "content-security-policy"))
2857 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
2858 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2859 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
2860 else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2861 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
2862 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2863 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
2866 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2867 static bool isSeparator(UChar c)
2869 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2872 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2874 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2875 int keyBegin, keyEnd;
2876 int valueBegin, valueEnd;
2879 int length = features.length();
2880 String buffer = features.lower();
2881 while (i < length) {
2882 // skip to first non-separator, but don't skip past the end of the string
2883 while (isSeparator(buffer[i])) {
2890 // skip to first separator
2891 while (!isSeparator(buffer[i]))
2895 // skip to first '=', but don't skip past a ',' or the end of the string
2896 while (buffer[i] != '=') {
2897 if (buffer[i] == ',' || i >= length)
2902 // skip to first non-separator, but don't skip past a ',' or the end of the string
2903 while (isSeparator(buffer[i])) {
2904 if (buffer[i] == ',' || i >= length)
2910 // skip to first separator
2911 while (!isSeparator(buffer[i]))
2915 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
2917 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2918 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2919 callback(keyString, valueString, this, data);
2923 void Document::processViewport(const String& features, ViewportArguments::Type origin)
2925 ASSERT(!features.isNull());
2927 if (origin < m_viewportArguments.type)
2930 m_viewportArguments = ViewportArguments(origin);
2931 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2934 // FIXME: <rdar://problem/8955959> Investigate moving to ToT WebKit's extended Viewport Implementation
2935 // Moving to ToT's implementation would mean calling findConfigurationForViewportData, which does
2936 // bounds checking and determining concrete values for ValueAuto which we already do in UIKit.
2937 // To maintain old behavior, we just need to update a few values, leaving Auto's for UIKit.
2938 finalizeViewportArguments(m_viewportArguments);
2941 updateViewportArguments();
2944 void Document::updateViewportArguments()
2946 if (page() && frame()->isMainFrame()) {
2948 m_didDispatchViewportPropertiesChanged = true;
2950 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
2952 page()->chrome().didReceiveDocType(frame());
2958 // FIXME: Find a better place for this functionality.
2959 void setParserFeature(const String& key, const String& value, Document* document, void*)
2961 if (key == "telephone" && equalIgnoringCase(value, "no"))
2962 document->setIsTelephoneNumberParsingAllowed(false);
2965 void Document::processFormatDetection(const String& features)
2967 ASSERT(!features.isNull());
2968 processArguments(features, nullptr, &setParserFeature);
2971 void Document::processWebAppOrientations()
2973 if (Page* page = this->page())
2974 page->chrome().client().webAppOrientationsUpdated();
2978 void Document::processReferrerPolicy(const String& policy)
2980 ASSERT(!policy.isNull());
2982 m_referrerPolicy = ReferrerPolicyDefault;
2984 if (equalIgnoringCase(policy, "never"))
2985 m_referrerPolicy = ReferrerPolicyNever;
2986 else if (equalIgnoringCase(policy, "always"))
2987 m_referrerPolicy = ReferrerPolicyAlways;
2988 else if (equalIgnoringCase(policy, "origin"))
2989 m_referrerPolicy = ReferrerPolicyOrigin;
2992 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2994 if (!hasLivingRenderTree())
2995 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
2997 HitTestResult result(documentPoint);
2998 renderView()->hitTest(request, result);
3000 if (!request.readOnly())
3001 updateHoverActiveState(request, result.innerElement(), &event);
3003 return MouseEventWithHitTestResults(event, result);
3006 // DOM Section 1.1.1
3007 bool Document::childTypeAllowed(NodeType type) const
3010 case ATTRIBUTE_NODE:
3011 case CDATA_SECTION_NODE:
3012 case DOCUMENT_FRAGMENT_NODE:
3015 case ENTITY_REFERENCE_NODE:
3018 case XPATH_NAMESPACE_NODE:
3021 case PROCESSING_INSTRUCTION_NODE:
3023 case DOCUMENT_TYPE_NODE:
3025 // Documents may contain no more than one of each of these.
3026 // (One Element and one DocumentType.)
3027 for (Node* c = firstChild(); c; c = c->nextSibling())
3028 if (c->nodeType() == type)
3035 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3038 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3041 if (oldChild->nodeType() == newChild->nodeType())
3044 int numDoctypes = 0;
3045 int numElements = 0;
3047 // First, check how many doctypes and elements we have, not counting
3048 // the child we're about to remove.
3049 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3053 switch (c->nodeType()) {
3054 case DOCUMENT_TYPE_NODE:
3065 // Then, see how many doctypes and elements might be added by the new child.
3066 if (newChild->isDocumentFragment()) {
3067 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3068 switch (c->nodeType()) {
3069 case ATTRIBUTE_NODE:
3070 case CDATA_SECTION_NODE:
3071 case DOCUMENT_FRAGMENT_NODE:
3074 case ENTITY_REFERENCE_NODE:
3077 case XPATH_NAMESPACE_NODE:
3080 case PROCESSING_INSTRUCTION_NODE:
3082 case DOCUMENT_TYPE_NODE:
3091 switch (newChild->nodeType()) {
3092 case ATTRIBUTE_NODE:
3093 case CDATA_SECTION_NODE:
3094 case DOCUMENT_FRAGMENT_NODE:
3097 case ENTITY_REFERENCE_NODE:
3100 case XPATH_NAMESPACE_NODE:
3103 case PROCESSING_INSTRUCTION_NODE:
3105 case DOCUMENT_TYPE_NODE:
3114 if (numElements > 1 || numDoctypes > 1)
3120 PassRefPtr<Node> Document::cloneNode(bool deep)
3122 RefPtr<Document> clone = cloneDocumentWithoutChildren();
3123 clone->cloneDataFromDocument(*this);
3125 cloneChildNodes(clone.get());
3126 return clone.release();
3129 PassRefPtr<Document> Document::cloneDocumentWithoutChildren() const
3131 return isXHTMLDocument() ? createXHTML(nullptr, url()) : create(nullptr, url());
3134 void Document::cloneDataFromDocument(const Document& other)
3136 ASSERT(m_url == other.url());
3137 m_baseURL = other.baseURL();
3138 m_baseURLOverride = other.baseURLOverride();
3139 m_documentURI = other.documentURI();
3141 setCompatibilityMode(other.compatibilityMode());
3142 setSecurityOrigin(other.securityOrigin());
3143 setDecoder(other.decoder());
3146 StyleSheetList* Document::styleSheets()
3148 if (!m_styleSheetList)
3149 m_styleSheetList = StyleSheetList::create(this);
3150 return m_styleSheetList.get();
3153 String Document::preferredStylesheetSet() const
3155 return m_styleSheetCollection.preferredStylesheetSetName();
3158 String Document::selectedStylesheetSet() const
3160 return m_styleSheetCollection.selectedStylesheetSetName();
3163 void Document::setSelectedStylesheetSet(const String& aString)
3165 m_styleSheetCollection.setSelectedStylesheetSetName(aString);
3166 styleResolverChanged(DeferRecalcStyle);
3169 void Document::evaluateMediaQueryList()
3171 if (m_mediaQueryMatcher)
3172 m_mediaQueryMatcher->styleResolverChanged();
3175 void Document::optimizedStyleSheetUpdateTimerFired(Timer<Document>&)
3177 styleResolverChanged(RecalcStyleIfNeeded);
3180 void Document::scheduleOptimizedStyleSheetUpdate()
3182 if (m_optimizedStyleSheetUpdateTimer.isActive())
3184 m_styleSheetCollection.setPendingUpdateType(DocumentStyleSheetCollection::OptimizedUpdate);
3185 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3188 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3190 if (m_optimizedStyleSheetUpdateTimer.isActive())
3191 m_optimizedStyleSheetUpdateTimer.stop();
3193 // Don't bother updating, since we haven't loaded all our style info yet
3194 // and haven't calculated the style selector for the first time.
3195 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3196 m_styleResolver.clear();
3199 m_didCalculateStyleResolver = true;
3201 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3202 if (!ownerElement())
3203 printf("Beginning update of style selector at time %lld.\n", elapsedTime().count());
3206 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3207 ? DocumentStyleSheetCollection::OptimizedUpdate
3208 : DocumentStyleSheetCollection::FullUpdate;
3209 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection.updateActiveStyleSheets(styleSheetUpdate);
3211 if (updateFlag == DeferRecalcStyle) {
3212 scheduleForcedStyleRecalc();
3216 if (updateFlag == DeferRecalcStyleIfNeeded) {
3217 if (stylesheetChangeRequiresStyleRecalc)
3218 scheduleForcedStyleRecalc();
3222 if (!stylesheetChangeRequiresStyleRecalc)
3225 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3226 // make sure animations get the correct update time
3228 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
3229 recalcStyle(Style::Force);
3232 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3233 if (!ownerElement())
3234 printf("Finished update of style selector at time %lld\n", elapsedTime().count());
3238 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3240 view()->scheduleRelayout();
3243 evaluateMediaQueryList();
3246 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3248 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3252 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3253 for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
3254 Document* childDocument = child->document();
3255 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3256 ASSERT(&childDocument->seamlessParentIFrame()->document() == this);
3257 childDocument->seamlessParentUpdatedStylesheets();
3262 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3264 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3267 Element* focusedElement = node->treeScope().focusedElement();
3268 if (!focusedElement)
3271 bool nodeInSubtree = false;
3272 if (amongChildrenOnly)
3273 nodeInSubtree = focusedElement->isDescendantOf(node);
3275 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3278 setFocusedElement(nullptr);
3281 void Document::hoveredElementDidDetach(Element* element)
3283 if (!m_hoveredElement || element != m_hoveredElement)
3286 m_hoveredElement = element->parentElement();
3287 while (m_hoveredElement && !m_hoveredElement->renderer())
3288 m_hoveredElement = m_hoveredElement->parentElement();
3290 frame()->eventHandler().scheduleHoverStateUpdate();
3293 void Document::elementInActiveChainDidDetach(Element* element)
3295 if (!m_activeElement || element != m_activeElement)
3298 m_activeElement = element->parentElement();
3299 while (m_activeElement && !m_activeElement->renderer())
3300 m_activeElement = m_activeElement->parentElement();
3303 #if ENABLE(DASHBOARD_SUPPORT)
3304 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3306 return m_annotatedRegions;
3309 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3311 m_annotatedRegions = regions;
3312 setAnnotatedRegionsDirty(false);
3316 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
3318 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3320 // Make sure newFocusedElement is actually in this document
3321 if (newFocusedElement && (&newFocusedElement->document() != this))
3324 if (m_focusedElement == newFocusedElement)
3330 bool focusChangeBlocked = false;
3331 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3333 // Remove focus from the existing focus node (if any)
3334 if (oldFocusedElement) {
3335 if (oldFocusedElement->active())
3336 oldFocusedElement->setActive(false);
3338 oldFocusedElement->setFocus(false);
3340 // Dispatch a change event for form control elements that have been edited.
3341 if (oldFocusedElement->isFormControlElement()) {
3342 HTMLFormControlElement* formControlElement = toHTMLFormControlElement(oldFocusedElement.get());
3343 if (formControlElement->wasChangedSinceLastFormControlChangeEvent())
3344 formControlElement->dispatchFormControlChangeEvent();
3347 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3348 oldFocusedElement->dispatchBlurEvent(newFocusedElement);
3350 if (m_focusedElement) {
3351 // handler shifted focus
3352 focusChangeBlocked = true;
3353 newFocusedElement = nullptr;
3356 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement); // DOM level 3 name for the bubbling blur event.
3357 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3358 // on it, probably when <rdar://problem/8503958> is resolved.
3359 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement); // DOM level 2 name for compatibility.
3361 if (m_focusedElement) {
3362 // handler shifted focus
3363 focusChangeBlocked = true;
3364 newFocusedElement = nullptr;
3367 if (oldFocusedElement->isRootEditableElement())
3368 frame()->editor().didEndEditing();
3371 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3372 oldWidget->setFocus(false);
3374 view()->setFocus(false);
3378 if (newFocusedElement && newFocusedElement->isFocusable()) {
3379 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3380 // delegate blocks focus change
3381 focusChangeBlocked = true;
3382 goto SetFocusedNodeDone;
3384 // Set focus on the new node
3385 m_focusedElement = newFocusedElement;
3387 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3388 m_focusedElement->dispatchFocusEvent(oldFocusedElement, direction);
3390 if (m_focusedElement != newFocusedElement) {
3391 // handler shifted focus
3392 focusChangeBlocked = true;
3393 goto SetFocusedNodeDone;
3396 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement); // DOM level 3 bubbling focus event.
3398 if (m_focusedElement != newFocusedElement) {
3399 // handler shifted focus
3400 focusChangeBlocked = true;
3401 goto SetFocusedNodeDone;
3404 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3405 // on it, probably when <rdar://problem/8503958> is m.
3406 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement); // DOM level 2 for compatibility.
3408 if (m_focusedElement != newFocusedElement) {
3409 // handler shifted focus
3410 focusChangeBlocked = true;
3411 goto SetFocusedNodeDone;
3414 m_focusedElement->setFocus(true);
3416 if (m_focusedElement->isRootEditableElement())
3417 frame()->editor().didBeginEditing();
3419 // eww, I suck. set the qt focus correctly
3420 // ### find a better place in the code for this
3422 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3424 // Make sure a widget has the right size before giving it focus.
3425 // Otherwise, we are testing edge cases of the Widget code.
3426 // Specifically, in WebCore this does not work well for text fields.
3428 // Re-get the widget in case updating the layout changed things.
3429 focusWidget = widgetForElement(m_focusedElement.get());
3432 focusWidget->setFocus(true);
3434 view()->setFocus(true);
3438 if (!focusChangeBlocked && m_focusedElement) {
3439 // Create the AXObject cache in a focus change because GTK relies on it.
3440 if (AXObjectCache* cache = axObjectCache())
3441 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3444 if (!focusChangeBlocked && page())
3445 page()->chrome().focusedElementChanged(m_focusedElement.get());
3448 updateStyleIfNeeded();
3449 return !focusChangeBlocked;
3452 void Document::setCSSTarget(Element* n)
3455 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3458 n->didAffectSelector(AffectedSelectorTarget);
3461 void Document::registerNodeList(LiveNodeList& list)
3463 m_nodeListAndCollectionCounts[list.invalidationType()]++;
3464 if (list.isRootedAtDocument())
3465 m_listsInvalidatedAtDocument.add(&list);
3468 void Document::unregisterNodeList(LiveNodeList& list)
3470 m_nodeListAndCollectionCounts[list.invalidationType()]--;
3471 if (list.isRootedAtDocument()) {
3472 ASSERT(m_listsInvalidatedAtDocument.contains(&list));
3473 m_listsInvalidatedAtDocument.remove(&list);
3477 void Document::registerCollection(HTMLCollection& collection)
3479 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
3480 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
3481 if (collection.isRootedAtDocument())
3482 m_collectionsInvalidatedAtDocument.add(&collection);
3485 void Document::unregisterCollection(HTMLCollection& collection)
3487 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
3488 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
3489 if (collection.isRootedAtDocument()) {
3490 ASSERT(m_collectionsInvalidatedAtDocument.contains(&collection));
3491 m_collectionsInvalidatedAtDocument.remove(&collection);
3495 void Document::attachNodeIterator(NodeIterator* ni)
3497 m_nodeIterators.add(ni);
3500 void Document::detachNodeIterator(NodeIterator* ni)
3502 // The node iterator can be detached without having been attached if its root node didn't have a document
3503 // when the iterator was created, but has it now.
3504 m_nodeIterators.remove(ni);
3507 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3509 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3510 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3511 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3512 if ((*it)->root() == node) {
3513 detachNodeIterator(*it);
3514 newDocument->attachNodeIterator(*it);
3519 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
3521 if (!m_ranges.isEmpty()) {
3522 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3523 (*it)->nodeChildrenChanged(container);
3527 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3529 if (!m_ranges.isEmpty()) {
3530 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3531 (*it)->nodeChildrenWillBeRemoved(container);
3534 for (auto it = m_nodeIterators.begin(), end = m_nodeIterators.end(); it != end; ++it) {
3535 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3536 (*it)->nodeWillBeRemoved(n);
3539 if (Frame* frame = this->frame()) {
3540 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3541 frame->eventHandler().nodeWillBeRemoved(n);
3542 frame->selection().nodeWillBeRemoved(n);
3543 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3548 void Document::nodeWillBeRemoved(Node* n)
3550 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3551 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3552 (*it)->nodeWillBeRemoved(n);
3554 if (!m_ranges.isEmpty()) {
3555 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3556 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3557 (*it)->nodeWillBeRemoved(n);
3560 if (Frame* frame = this->frame()) {
3561 frame->eventHandler().nodeWillBeRemoved(n);
3562 frame->selection().nodeWillBeRemoved(n);
3563 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3567 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3569 if (!m_ranges.isEmpty()) {
3570 HashSet<Range*>::const_iterator end = m_ranges.end();
3571 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3572 (*it)->textInserted(text, offset, length);
3575 // Update the markers for spelling and grammar checking.
3576 m_markers->shiftMarkers(text, offset, length);
3579 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3581 if (!m_ranges.isEmpty()) {
3582 HashSet<Range*>::const_iterator end = m_ranges.end();
3583 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3584 (*it)->textRemoved(text, offset, length);
3587 // Update the markers for spelling and grammar checking.
3588 m_markers->removeMarkers(text, offset, length);
3589 m_markers->shiftMarkers(text, offset + length, 0 - length);
3592 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3594 if (!m_ranges.isEmpty()) {
3595 NodeWithIndex oldNodeWithIndex(oldNode);
3596 HashSet<Range*>::const_iterator end = m_ranges.end();
3597 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3598 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3601 // FIXME: This should update markers for spelling and grammar checking.
3604 void Document::textNodeSplit(Text* oldNode)
3606 if (!m_ranges.isEmpty()) {
3607 HashSet<Range*>::const_iterator end = m_ranges.end();
3608 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3609 (*it)->textNodeSplit(oldNode);
3612 // FIXME: This should update markers for spelling and grammar checking.
3615 void Document::createDOMWindow()
3618 ASSERT(!m_domWindow);
3620 m_domWindow = DOMWindow::create(this);
3622 ASSERT(m_domWindow->document() == this);
3623 ASSERT(m_domWindow->frame() == m_frame);
3626 void Document::takeDOMWindowFrom(Document* document)
3629 ASSERT(!m_domWindow);
3630 ASSERT(document->m_domWindow);
3631 // A valid DOMWindow is needed by CachedFrame for its documents.
3632 ASSERT(!document->inPageCache());
3634 m_domWindow = document->m_domWindow.release();
3635 m_domWindow->didSecureTransitionTo(this);
3637 ASSERT(m_domWindow->document() == this);
3638 ASSERT(m_domWindow->frame() == m_frame);
3641 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3645 m_domWindow->setAttributeEventListener(eventType, listener);
3648 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
3652 setWindowAttributeEventListener(eventType, JSLazyEventListener::createForDOMWindow(*m_frame, attributeName, attributeValue));