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 "Attribute.h"
35 #include "CDATASection.h"
36 #include "CSSStyleDeclaration.h"
37 #include "CSSStyleSheet.h"
38 #include "CachedCSSStyleSheet.h"
39 #include "CachedResourceLoader.h"
41 #include "ChromeClient.h"
43 #include "ContentSecurityPolicy.h"
44 #include "CookieJar.h"
45 #include "CustomElementConstructor.h"
46 #include "CustomElementRegistry.h"
47 #include "DOMImplementation.h"
48 #include "DOMNamedFlowCollection.h"
49 #include "DOMWindow.h"
50 #include "DateComponents.h"
51 #include "Dictionary.h"
52 #include "DocumentEventQueue.h"
53 #include "DocumentFragment.h"
54 #include "DocumentLoader.h"
55 #include "DocumentMarkerController.h"
56 #include "DocumentSharedObjectPool.h"
57 #include "DocumentType.h"
60 #include "ElementIterator.h"
61 #include "EntityReference.h"
63 #include "EventFactory.h"
64 #include "EventHandler.h"
65 #include "EventListener.h"
66 #include "EventNames.h"
67 #include "ExceptionCode.h"
68 #include "FontLoader.h"
69 #include "FormController.h"
70 #include "FrameLoader.h"
71 #include "FrameLoaderClient.h"
72 #include "FrameView.h"
73 #include "HashChangeEvent.h"
74 #include "HistogramSupport.h"
76 #include "HTMLAllCollection.h"
77 #include "HTMLAnchorElement.h"
78 #include "HTMLBaseElement.h"
79 #include "HTMLCanvasElement.h"
80 #include "HTMLCollection.h"
81 #include "HTMLDocument.h"
82 #include "HTMLElementFactory.h"
83 #include "HTMLFormControlElement.h"
84 #include "HTMLFrameOwnerElement.h"
85 #include "HTMLHeadElement.h"
86 #include "HTMLIFrameElement.h"
87 #include "HTMLImageElement.h"
88 #include "HTMLLinkElement.h"
89 #include "HTMLMediaElement.h"
90 #include "HTMLNameCollection.h"
91 #include "HTMLNames.h"
92 #include "HTMLParserIdioms.h"
93 #include "HTMLPlugInElement.h"
94 #include "HTMLScriptElement.h"
95 #include "HTMLStyleElement.h"
96 #include "HTMLTitleElement.h"
97 #include "HTTPParsers.h"
98 #include "HitTestRequest.h"
99 #include "HitTestResult.h"
100 #include "IconController.h"
101 #include "ImageLoader.h"
102 #include "InspectorCounters.h"
103 #include "InspectorInstrumentation.h"
104 #include "JSLazyEventListener.h"
105 #include "Language.h"
107 #include "MainFrame.h"
108 #include "MediaCanStartListener.h"
109 #include "MediaQueryList.h"
110 #include "MediaQueryMatcher.h"
111 #include "MouseEventWithHitTestResults.h"
112 #include "NameNodeList.h"
113 #include "NamedFlowCollection.h"
114 #include "NestingLevelIncrementer.h"
115 #include "NodeFilter.h"
116 #include "NodeIterator.h"
117 #include "NodeRareData.h"
118 #include "NodeWithIndex.h"
120 #include "PageConsole.h"
121 #include "PageGroup.h"
122 #include "PageTransitionEvent.h"
123 #include "PlatformLocale.h"
124 #include "PlugInsResources.h"
125 #include "PluginDocument.h"
126 #include "PointerLockController.h"
127 #include "PopStateEvent.h"
128 #include "ProcessingInstruction.h"
129 #include "QualifiedName.h"
130 #include "RenderArena.h"
131 #include "RenderView.h"
132 #include "RenderWidget.h"
133 #include "ResourceLoader.h"
134 #include "RuntimeEnabledFeatures.h"
135 #include "SchemeRegistry.h"
136 #include "ScopedEventQueue.h"
137 #include "ScriptCallStack.h"
138 #include "ScriptController.h"
139 #include "ScriptRunner.h"
140 #include "ScriptSourceCode.h"
141 #include "ScriptValue.h"
142 #include "ScrollingCoordinator.h"
143 #include "SecurityOrigin.h"
144 #include "SecurityPolicy.h"
145 #include "SegmentedString.h"
146 #include "SelectorQuery.h"
147 #include "Settings.h"
148 #include "ShadowRoot.h"
149 #include "StylePropertySet.h"
150 #include "StyleResolver.h"
151 #include "StyleSheetContents.h"
152 #include "StyleSheetList.h"
153 #include "TextResourceDecoder.h"
155 #include "TransformSource.h"
156 #include "TreeWalker.h"
157 #include "VisitedLinkState.h"
158 #include "XMLDocumentParser.h"
159 #include "XMLNSNames.h"
160 #include "XMLNames.h"
161 #include "XPathEvaluator.h"
162 #include "XPathExpression.h"
163 #include "XPathNSResolver.h"
164 #include "XPathResult.h"
165 #include "htmlediting.h"
166 #include <wtf/CurrentTime.h>
167 #include <wtf/MainThread.h>
168 #include <wtf/PassRefPtr.h>
170 #include <wtf/TemporaryChange.h>
171 #include <wtf/text/StringBuffer.h>
173 #if USE(ACCELERATED_COMPOSITING)
174 #include "RenderLayerCompositor.h"
177 #if ENABLE(SHARED_WORKERS)
178 #include "SharedWorkerRepository.h"
182 #include "XSLTProcessor.h"
186 #include "SVGDocumentExtensions.h"
187 #include "SVGElementFactory.h"
188 #include "SVGNames.h"
189 #include "SVGSVGElement.h"
192 #if ENABLE(TOUCH_EVENTS)
193 #include "TouchList.h"
197 #include "MathMLElement.h"
198 #include "MathMLElementFactory.h"
199 #include "MathMLNames.h"
202 #if ENABLE(FULLSCREEN_API)
203 #include "RenderFullScreen.h"
206 #if ENABLE(REQUEST_ANIMATION_FRAME)
207 #include "RequestAnimationFrameCallback.h"
208 #include "ScriptedAnimationController.h"
211 #if ENABLE(IOS_TEXT_AUTOSIZING)
212 #include "TextAutoSizing.h"
215 #if ENABLE(TEXT_AUTOSIZING)
216 #include "TextAutosizer.h"
220 #include "DOMSecurityPolicy.h"
223 #if ENABLE(VIDEO_TRACK)
224 #include "CaptionUserPreferences.h"
229 using namespace Unicode;
233 using namespace HTMLNames;
235 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
237 static const unsigned cMaxWriteRecursionDepth = 21;
239 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
240 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
242 static const int cLayoutScheduleThreshold = 250;
244 // DOM Level 2 says (letters added):
246 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
247 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
248 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
249 // 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.
250 // 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.
251 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
252 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
253 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
254 // i) Characters ':' and '_' are allowed as name-start characters.
255 // j) Characters '-' and '.' are allowed as name characters.
257 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
259 static inline bool isValidNameStart(UChar32 c)
262 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
266 if (c == ':' || c == '_')
269 // rules (a) and (f) above
270 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
271 if (!(Unicode::category(c) & nameStartMask))
275 if (c >= 0xF900 && c < 0xFFFE)
279 DecompositionType decompType = decompositionType(c);
280 if (decompType == DecompositionFont || decompType == DecompositionCompat)
286 static inline bool isValidNamePart(UChar32 c)
288 // rules (a), (e), and (i) above
289 if (isValidNameStart(c))
292 // rules (g) and (h) above
293 if (c == 0x00B7 || c == 0x0387)
297 if (c == '-' || c == '.')
300 // rules (b) and (f) above
301 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
302 if (!(Unicode::category(c) & otherNamePartMask))
306 if (c >= 0xF900 && c < 0xFFFE)
310 DecompositionType decompType = decompositionType(c);
311 if (decompType == DecompositionFont || decompType == DecompositionCompat)
317 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
319 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
321 // If a Document has the address "about:blank"
322 // The origin of the Document is the origin it was assigned when its browsing context was created.
324 // Note: We generalize this to all "blank" URLs and invalid URLs because we
325 // treat all of these URLs as about:blank.
327 return url.isEmpty() || url.isBlankURL();
330 static Widget* widgetForNode(Node* focusedNode)
334 RenderObject* renderer = focusedNode->renderer();
335 if (!renderer || !renderer->isWidget())
337 return toRenderWidget(renderer)->widget();
340 static bool acceptsEditingFocus(Node* node)
343 ASSERT(node->rendererIsEditable());
345 Node* root = node->rootEditableElement();
346 Frame* frame = node->document().frame();
350 return frame->editor().shouldBeginEditing(rangeOfContents(root).get());
353 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
355 // targetFrame can be 0 when we're trying to navigate a top-level frame
356 // that has a 0 opener.
360 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
361 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
362 Document* ancestorDocument = ancestorFrame->document();
363 // FIXME: Should be an ASSERT? Frames should alway have documents.
364 if (!ancestorDocument)
367 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
368 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
371 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
372 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
373 // something more general instead?
374 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
381 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
383 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
385 // FIXME: should we print to the console of the document performing the navigation instead?
386 frame->document()->domWindow()->printErrorMessage(message);
389 uint64_t Document::s_globalTreeVersion = 0;
391 static const double timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds = 30;
393 #if ENABLE(IOS_TEXT_AUTOSIZING)
394 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
396 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
399 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
401 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
405 Document::Document(Frame* frame, const URL& url, unsigned documentClasses)
406 : ContainerNode(0, CreateDocument)
408 , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired, timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds)
409 , m_didCalculateStyleResolver(false)
410 , m_hasNodesWithPlaceholderStyle(false)
411 , m_needsNotifyRemoveAllPendingStylesheet(false)
412 , m_ignorePendingStylesheets(false)
413 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
415 , m_activeParserCount(0)
416 , m_wellFormed(false)
418 , m_paginatedForScreen(false)
419 , m_ignoreAutofocus(false)
420 , m_compatibilityMode(NoQuirksMode)
421 , m_compatibilityModeLocked(false)
422 , m_textColor(Color::black)
423 , m_domTreeVersion(++s_globalTreeVersion)
425 , m_mutationObserverTypes(0)
426 , m_styleSheetCollection(*this)
427 , m_visitedLinkState(VisitedLinkState::create(*this))
428 , m_visuallyOrdered(false)
429 , m_readyState(Complete)
431 , m_optimizedStyleSheetUpdateTimer(this, &Document::optimizedStyleSheetUpdateTimerFired)
432 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
433 , m_pendingStyleRecalcShouldForce(false)
434 , m_inStyleRecalc(false)
435 , m_closeAfterStyleRecalc(false)
436 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
437 , m_frameElementsShouldIgnoreScrolling(false)
438 , m_containsValidityStyleRules(false)
439 , m_updateFocusAppearanceRestoresSelection(false)
440 , m_ignoreDestructiveWriteCount(0)
441 , m_titleSetExplicitly(false)
442 , m_markers(adoptPtr(new DocumentMarkerController))
443 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
444 , m_resetHiddenFocusElementTimer(this, &Document::resetHiddenFocusElementTimer)
446 , m_processingLoadEvent(false)
447 , m_loadEventFinished(false)
448 , m_startTime(monotonicallyIncreasingTimeMS())
449 , m_overMinimumLayoutThreshold(false)
450 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
451 , m_xmlVersion(ASCIILiteral("1.0"))
452 , m_xmlStandalone(StandaloneUnspecified)
453 , m_hasXMLDeclaration(0)
454 , m_savedRenderView(0)
455 , m_designMode(inherit)
456 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
457 , m_hasAnnotatedRegions(false)
458 , m_annotatedRegionsDirty(false)
460 , m_createRenderers(true)
461 , m_inPageCache(false)
462 , m_accessKeyMapValid(false)
463 , m_documentClasses(documentClasses)
464 , m_isViewSource(false)
465 , m_sawElementsInKnownNamespaces(false)
466 , m_isSrcdocDocument(false)
468 , m_eventQueue(*this)
469 , m_weakFactory(this)
470 , m_idAttributeName(idAttr)
471 #if ENABLE(FULLSCREEN_API)
472 , m_areKeysEnabledInFullScreen(0)
473 , m_fullScreenRenderer(0)
474 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
475 , m_isAnimatingFullScreen(false)
477 , m_loadEventDelayCount(0)
478 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
479 , m_referrerPolicy(ReferrerPolicyDefault)
480 , m_directionSetOnDocumentElement(false)
481 , m_writingModeSetOnDocumentElement(false)
482 , m_writeRecursionIsTooDeep(false)
483 , m_writeRecursionDepth(0)
484 , m_wheelEventHandlerCount(0)
485 , m_lastHandledUserGestureTimestamp(0)
486 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
487 , m_scheduledTasksAreSuspended(false)
488 , m_visualUpdatesAllowed(true)
489 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
490 , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
492 , m_didDispatchViewportPropertiesChanged(false)
494 #if ENABLE(TEMPLATE_ELEMENT)
495 , m_templateDocumentHost(0)
497 #if ENABLE(FONT_LOAD_EVENTS)
500 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
501 , m_hasInjectedPlugInsScript(false)
502 , m_renderTreeBeingDestroyed(false)
504 // We depend on the url getting immediately set in subframes, but we
505 // also depend on the url NOT getting immediately set in opened windows.
506 // See fast/dom/early-frame-url.html
507 // and fast/dom/location-new-window-no-crash.html, respectively.
508 // FIXME: Can/should we unify this behavior?
509 if ((frame && frame->ownerElement()) || !url.isEmpty())
513 m_cachedResourceLoader = m_frame->loader().activeDocumentLoader()->cachedResourceLoader();
514 if (!m_cachedResourceLoader)
515 m_cachedResourceLoader = CachedResourceLoader::create(0);
516 m_cachedResourceLoader->setDocument(this);
518 #if ENABLE(TEXT_AUTOSIZING)
519 m_textAutosizer = TextAutosizer::create(this);
523 resetVisitedLinkColor();
524 resetActiveLinkColor();
526 initSecurityContext();
529 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
530 m_nodeListCounts[i] = 0;
532 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
535 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
537 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
538 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
539 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
540 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
541 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
542 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
545 #if ENABLE(FULLSCREEN_API)
546 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
551 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
553 } while ((owner = owner->document().ownerElement()));
558 Document::~Document()
560 ASSERT(!renderView());
561 ASSERT(!m_inPageCache);
562 ASSERT(!m_savedRenderView);
563 ASSERT(m_ranges.isEmpty());
564 ASSERT(!m_styleRecalcTimer.isActive());
565 ASSERT(!m_parentTreeScope);
567 #if ENABLE(TEMPLATE_ELEMENT)
568 if (m_templateDocument)
569 m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
572 #if ENABLE(TOUCH_EVENT_TRACKING)
573 // FIXME: This is dead code. The ownerDocument function returns 0 when called on a document.
574 if (Document* ownerDocument = this->ownerDocument())
575 ownerDocument->didRemoveEventTargetNode(this);
578 // FIXME: Should we reset m_domWindow when we detach from the Frame?
580 m_domWindow->resetUnlessSuspendedForPageCache();
582 m_scriptRunner = nullptr;
584 histogramMutationEventUsage(m_listenerTypes);
586 removeAllEventListeners();
588 // Currently we believe that Document can never outlive the parser.
589 // Although the Document may be replaced synchronously, DocumentParsers
590 // generally keep at least one reference to an Element which would in turn
591 // has a reference to the Document. If you hit this ASSERT, then that
592 // assumption is wrong. DocumentParser::detach() should ensure that even
593 // if the DocumentParser outlives the Document it won't cause badness.
594 ASSERT(!m_parser || m_parser->refCount() == 1);
597 m_renderArena = nullptr;
599 if (this == topDocument())
600 clearAXObjectCache();
604 if (m_styleSheetList)
605 m_styleSheetList->detachFromDocument();
608 m_elementSheet->detachFromDocument();
609 m_styleSheetCollection.detachFromDocument();
611 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
613 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
614 // load the initial empty document and the SVGDocument with the same DocumentLoader).
615 if (m_cachedResourceLoader->document() == this)
616 m_cachedResourceLoader->setDocument(0);
617 m_cachedResourceLoader.clear();
619 // We must call clearRareData() here since a Document class inherits TreeScope
620 // as well as Node. See a comment on TreeScope.h for the reason.
624 ASSERT(!m_listsInvalidatedAtDocument.size());
626 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
627 ASSERT(!m_nodeListCounts[i]);
629 clearDocumentScope();
631 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
634 void Document::dropChildren()
636 ASSERT(!m_deletionHasBegun);
638 // We must make sure not to be retaining any of our children through
639 // these extra pointers or we will create a reference cycle.
640 m_focusedElement = 0;
641 m_hoveredElement = 0;
644 m_documentElement = 0;
645 m_userActionElements.documentDidRemoveLastRef();
646 #if ENABLE(FULLSCREEN_API)
647 m_fullScreenElement = 0;
648 m_fullScreenElementStack.clear();
653 #if ENABLE(CUSTOM_ELEMENTS)
657 // removeDetachedChildren() doesn't always unregister IDs,
658 // so tear down scope information up front to avoid having
659 // stale references in the map.
661 destroyTreeScopeData();
662 removeDetachedChildren();
663 m_formController.clear();
667 m_cssCanvasElements.clear();
669 #if ENABLE(REQUEST_ANIMATION_FRAME)
670 clearScriptedAnimationController();
674 Element* Document::getElementById(const AtomicString& id) const
676 return TreeScope::getElementById(id);
679 Element* Document::getElementByAccessKey(const String& key)
683 if (!m_accessKeyMapValid) {
684 buildAccessKeyMap(this);
685 m_accessKeyMapValid = true;
687 return m_elementsByAccessKey.get(key.impl());
690 void Document::buildAccessKeyMap(TreeScope* scope)
693 ContainerNode* rootNode = scope->rootNode();
694 for (auto element = elementDescendants(rootNode).begin(), end = elementDescendants(rootNode).end(); element != end; ++element) {
695 const AtomicString& accessKey = element->fastGetAttribute(accesskeyAttr);
696 if (!accessKey.isEmpty())
697 m_elementsByAccessKey.set(accessKey.impl(), &*element);
699 if (ShadowRoot* root = element->shadowRoot())
700 buildAccessKeyMap(root);
704 void Document::invalidateAccessKeyMap()
706 m_accessKeyMapValid = false;
707 m_elementsByAccessKey.clear();
710 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
712 return m_imagesByUsemap.add(name, element);
715 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
717 return m_imagesByUsemap.remove(name, element);
720 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
722 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
725 SelectorQueryCache& Document::selectorQueryCache()
727 if (!m_selectorQueryCache)
728 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
729 return *m_selectorQueryCache;
732 MediaQueryMatcher& Document::mediaQueryMatcher()
734 if (!m_mediaQueryMatcher)
735 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
736 return *m_mediaQueryMatcher;
739 void Document::setCompatibilityMode(CompatibilityMode mode)
741 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
743 bool wasInQuirksMode = inQuirksMode();
744 m_compatibilityMode = mode;
746 if (m_selectorQueryCache)
747 m_selectorQueryCache->invalidate();
749 if (inQuirksMode() != wasInQuirksMode) {
750 // All user stylesheets have to reparse using the different mode.
751 m_styleSheetCollection.clearPageUserSheet();
752 m_styleSheetCollection.invalidateInjectedStyleSheetCache();
756 String Document::compatMode() const
758 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
761 void Document::resetLinkColor()
763 m_linkColor = Color(0, 0, 238);
766 void Document::resetVisitedLinkColor()
768 m_visitedLinkColor = Color(85, 26, 139);
771 void Document::resetActiveLinkColor()
773 m_activeLinkColor.setNamedColor("red");
776 DOMImplementation* Document::implementation()
778 if (!m_implementation)
779 m_implementation = DOMImplementation::create(*this);
780 return m_implementation.get();
783 bool Document::hasManifest() const
785 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
788 DocumentType* Document::doctype() const
790 for (Node* node = firstChild(); node; node = node->nextSibling()) {
791 if (node->isDocumentTypeNode())
792 return static_cast<DocumentType*>(node);
797 void Document::childrenChanged(const ChildChange& change)
799 ContainerNode::childrenChanged(change);
801 // NOTE: Per DOM, dynamically inserting/removing doctype nodes doesn't affect compatibility mode.
803 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
804 // FIXME: It's a little strange to add these rules when a DocumentType with this prefix is added,
805 // but not remove these rules when a DocumentType with this prefix is removed. It seems this should
806 // be handled more the way the compatibility mode is, by fetching the doctype at the appropriate time,
807 // rather than by responding when a document type node is inserted.
808 if (DocumentType* documentType = doctype()) {
809 if (documentType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
810 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
814 Element* newDocumentElement = elementChildren(this).first();
816 if (newDocumentElement == m_documentElement)
818 m_documentElement = newDocumentElement;
819 // The root style used for media query matching depends on the document element.
820 clearStyleResolver();
823 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
825 if (!isValidName(name)) {
826 ec = INVALID_CHARACTER_ERR;
830 if (isXHTMLDocument())
831 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
833 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
836 #if ENABLE(CUSTOM_ELEMENTS)
837 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionCode& ec)
839 if (!isValidName(localName)) {
840 ec = INVALID_CHARACTER_ERR;
845 if (PassRefPtr<Element> created = m_registry->createElement(QualifiedName(nullAtom, localName, xhtmlNamespaceURI), typeExtension))
849 return setTypeExtension(createElement(localName, ec), typeExtension);
852 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionCode& ec)
854 String prefix, localName;
855 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
858 QualifiedName qName(prefix, localName, namespaceURI);
859 if (!hasValidNamespaceForElements(qName)) {
865 if (PassRefPtr<Element> created = m_registry->createElement(qName, typeExtension))
869 return setTypeExtension(createElementNS(namespaceURI, qualifiedName, ec), typeExtension);
872 PassRefPtr<CustomElementConstructor> Document::registerElement(JSC::ExecState* state, const AtomicString& name, ExceptionCode& ec)
874 return registerElement(state, name, Dictionary(), ec);
877 PassRefPtr<CustomElementConstructor> Document::registerElement(JSC::ExecState* state, const AtomicString& name, const Dictionary& options, ExceptionCode& ec)
879 if (!isHTMLDocument() && !isXHTMLDocument()) {
880 ec = NOT_SUPPORTED_ERR;
885 m_registry = adoptRef(new CustomElementRegistry(this));
886 return m_registry->registerElement(state, name, options, ec);
889 void Document::didCreateCustomElement(Element* element, CustomElementConstructor* constructor)
891 // m_registry is cleared Document::releaseChildren() and can be null here.
893 m_registry->didCreateElement(element);
895 #endif // ENABLE(CUSTOM_ELEMENTS)
897 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
899 return DocumentFragment::create(document());
902 PassRefPtr<Text> Document::createTextNode(const String& data)
904 return Text::create(*this, data);
907 PassRefPtr<Comment> Document::createComment(const String& data)
909 return Comment::create(*this, data);
912 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
914 if (isHTMLDocument()) {
915 ec = NOT_SUPPORTED_ERR;
918 return CDATASection::create(*this, data);
921 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
923 if (!isValidName(target)) {
924 ec = INVALID_CHARACTER_ERR;
927 if (isHTMLDocument()) {
928 ec = NOT_SUPPORTED_ERR;
931 return ProcessingInstruction::create(*this, target, data);
934 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
936 if (!isValidName(name)) {
937 ec = INVALID_CHARACTER_ERR;
940 if (isHTMLDocument()) {
941 ec = NOT_SUPPORTED_ERR;
944 return EntityReference::create(*this, name);
947 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
949 return Text::createEditingText(*this, text);
952 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
954 return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
957 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
962 ec = NOT_SUPPORTED_ERR;
966 switch (importedNode->nodeType()) {
968 return createTextNode(importedNode->nodeValue());
969 case CDATA_SECTION_NODE:
970 return createCDATASection(importedNode->nodeValue(), ec);
971 case ENTITY_REFERENCE_NODE:
972 return createEntityReference(importedNode->nodeName(), ec);
973 case PROCESSING_INSTRUCTION_NODE:
974 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
976 return createComment(importedNode->nodeValue());
978 Element* oldElement = toElement(importedNode);
979 // FIXME: The following check might be unnecessary. Is it possible that
980 // oldElement has mismatched prefix/namespace?
981 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
985 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
987 newElement->cloneDataFromElement(*oldElement);
990 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
991 RefPtr<Node> newChild = importNode(oldChild, true, ec);
994 newElement->appendChild(newChild.release(), ec);
1000 return newElement.release();
1002 case ATTRIBUTE_NODE:
1003 return Attr::create(*this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
1004 case DOCUMENT_FRAGMENT_NODE: {
1005 if (importedNode->isShadowRoot()) {
1006 // ShadowRoot nodes should not be explicitly importable.
1007 // Either they are imported along with their host node, or created implicitly.
1010 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
1011 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
1013 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
1014 RefPtr<Node> newChild = importNode(oldChild, true, ec);
1017 newFragment->appendChild(newChild.release(), ec);
1023 return newFragment.release();
1027 // 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.
1028 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
1030 case DOCUMENT_TYPE_NODE:
1031 case XPATH_NAMESPACE_NODE:
1034 ec = NOT_SUPPORTED_ERR;
1039 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1042 ec = NOT_SUPPORTED_ERR;
1046 if (source->isReadOnlyNode()) {
1047 ec = NO_MODIFICATION_ALLOWED_ERR;
1051 EventQueueScope scope;
1053 switch (source->nodeType()) {
1057 case DOCUMENT_TYPE_NODE:
1058 case XPATH_NAMESPACE_NODE:
1059 ec = NOT_SUPPORTED_ERR;
1061 case ATTRIBUTE_NODE: {
1062 Attr* attr = static_cast<Attr*>(source.get());
1063 if (attr->ownerElement())
1064 attr->ownerElement()->removeAttributeNode(attr, ec);
1065 attr->setSpecified(true);
1069 if (source->isShadowRoot()) {
1070 // ShadowRoot cannot disconnect itself from the host node.
1071 ec = HIERARCHY_REQUEST_ERR;
1075 if (source->isFrameOwnerElement()) {
1076 HTMLFrameOwnerElement* frameOwnerElement = toFrameOwnerElement(source.get());
1077 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
1078 ec = HIERARCHY_REQUEST_ERR;
1082 if (source->parentNode()) {
1083 source->parentNode()->removeChild(source.get(), ec);
1089 this->adoptIfNeeded(source.get());
1094 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1096 // These checks are from DOM Core Level 2, createElementNS
1097 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1098 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1100 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1103 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1104 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1105 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1106 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1112 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1114 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1115 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1116 // Note: The case of an "xmlns" qualified name with a namespace of
1117 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1118 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1120 return hasValidNamespaceForElements(qName);
1123 // FIXME: This should really be in a possible ElementFactory class.
1124 PassRefPtr<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1126 RefPtr<Element> element;
1128 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1129 if (name.namespaceURI() == xhtmlNamespaceURI)
1130 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1132 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1133 element = SVGElementFactory::createElement(name, *this, createdByParser);
1136 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1137 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1141 m_sawElementsInKnownNamespaces = true;
1143 element = Element::create(name, document());
1145 // <image> uses imgTag so we need a special rule.
1146 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1148 return element.release();
1151 bool Document::regionBasedColumnsEnabled() const
1153 return settings() && settings()->regionBasedColumnsEnabled();
1156 bool Document::cssStickyPositionEnabled() const
1158 return settings() && settings()->cssStickyPositionEnabled();
1161 bool Document::cssRegionsEnabled() const
1163 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1166 bool Document::cssCompositingEnabled() const
1168 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1171 bool Document::cssGridLayoutEnabled() const
1173 return settings() && settings()->cssGridLayoutEnabled();
1176 #if ENABLE(CSS_REGIONS)
1178 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1180 if (!cssRegionsEnabled() || !renderView())
1183 updateStyleIfNeeded();
1185 return namedFlows()->createCSSOMSnapshot();
1190 NamedFlowCollection* Document::namedFlows()
1193 m_namedFlows = NamedFlowCollection::create(this);
1195 return m_namedFlows.get();
1198 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1200 String prefix, localName;
1201 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1204 QualifiedName qName(prefix, localName, namespaceURI);
1205 if (!hasValidNamespaceForElements(qName)) {
1210 return createElement(qName, false);
1213 String Document::readyState() const
1215 DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1216 DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1217 DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1219 switch (m_readyState) {
1228 ASSERT_NOT_REACHED();
1232 void Document::setReadyState(ReadyState readyState)
1234 if (readyState == m_readyState)
1237 #if ENABLE(WEB_TIMING)
1238 switch (readyState) {
1240 if (!m_documentTiming.domLoading)
1241 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1244 if (!m_documentTiming.domInteractive)
1245 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1248 if (!m_documentTiming.domComplete)
1249 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1254 m_readyState = readyState;
1255 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1257 if (settings() && settings()->suppressesIncrementalRendering())
1258 setVisualUpdatesAllowed(readyState);
1261 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1263 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1264 switch (readyState) {
1266 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1267 ASSERT(m_visualUpdatesAllowed);
1268 setVisualUpdatesAllowed(false);
1271 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1274 if (m_visualUpdatesSuppressionTimer.isActive()) {
1275 ASSERT(!m_visualUpdatesAllowed);
1277 if (!view()->visualUpdatesAllowedByClient())
1280 setVisualUpdatesAllowed(true);
1282 ASSERT(m_visualUpdatesAllowed);
1287 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1289 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1292 m_visualUpdatesAllowed = visualUpdatesAllowed;
1294 if (visualUpdatesAllowed)
1295 m_visualUpdatesSuppressionTimer.stop();
1297 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1299 if (!visualUpdatesAllowed)
1302 FrameView* frameView = view();
1303 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1307 if (Page* page = this->page()) {
1308 if (frame()->isMainFrame()) {
1309 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1310 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1311 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1315 #if USE(ACCELERATED_COMPOSITING)
1317 view()->updateCompositingLayersAfterLayout();
1320 if (RenderView* renderView = this->renderView())
1321 renderView->repaintViewAndCompositedLayers();
1323 if (Frame* frame = this->frame())
1324 frame->loader().forcePageTransitionIfNeeded();
1327 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1329 ASSERT(!m_visualUpdatesAllowed);
1331 // If the client is extending the visual update suppression period explicitly, the
1332 // watchdog should not re-enable visual updates itself, but should wait for the client.
1333 if (!view()->visualUpdatesAllowedByClient())
1336 setVisualUpdatesAllowed(true);
1339 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1341 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1342 // both of which we can determine by looking at the timer.
1344 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1345 setVisualUpdatesAllowed(true);
1348 String Document::encoding() const
1350 if (TextResourceDecoder* d = decoder())
1351 return d->encoding().domName();
1355 String Document::defaultCharset() const
1357 if (Settings* settings = this->settings())
1358 return settings->defaultTextEncodingName();
1362 void Document::setCharset(const String& charset)
1366 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1369 void Document::setContentLanguage(const String& language)
1371 if (m_contentLanguage == language)
1373 m_contentLanguage = language;
1375 // Recalculate style so language is used when selecting the initial font.
1376 styleResolverChanged(DeferRecalcStyle);
1379 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1381 if (!implementation()->hasFeature("XML", String())) {
1382 ec = NOT_SUPPORTED_ERR;
1386 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1387 ec = NOT_SUPPORTED_ERR;
1391 m_xmlVersion = version;
1394 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1396 if (!implementation()->hasFeature("XML", String())) {
1397 ec = NOT_SUPPORTED_ERR;
1401 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1404 void Document::setDocumentURI(const String& uri)
1406 // This property is read-only from JavaScript, but writable from Objective-C.
1407 m_documentURI = uri;
1411 URL Document::baseURI() const
1416 void Document::setContent(const String& content)
1419 // FIXME: This should probably use insert(), but that's (intentionally)
1420 // not implemented for the XML parser as it's normally synonymous with
1421 // document.write(). append() will end up yielding, but close() will
1422 // pump the tokenizer syncrhonously and finish the parse.
1423 m_parser->pinToMainThread();
1424 m_parser->append(content.impl());
1428 String Document::suggestedMIMEType() const
1430 if (isXHTMLDocument())
1431 return ASCIILiteral("application/xhtml+xml");
1432 if (isSVGDocument())
1433 return ASCIILiteral("image/svg+xml");
1434 if (xmlStandalone())
1435 return ASCIILiteral("text/xml");
1436 if (isHTMLDocument())
1437 return ASCIILiteral("text/html");
1438 if (DocumentLoader* loader = this->loader())
1439 return loader->responseMIMEType();
1443 Element* Document::elementFromPoint(int x, int y) const
1445 if (!hasLivingRenderTree())
1448 return TreeScope::elementFromPoint(x, y);
1451 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1453 if (!hasLivingRenderTree())
1455 LayoutPoint localPoint;
1456 Node* node = nodeFromPoint(this, x, y, &localPoint);
1460 Node* shadowAncestorNode = ancestorInThisScope(node);
1461 if (shadowAncestorNode != node) {
1462 unsigned offset = shadowAncestorNode->nodeIndex();
1463 ContainerNode* container = shadowAncestorNode->parentNode();
1464 return Range::create(this, container, offset, container, offset);
1467 RenderObject* renderer = node->renderer();
1470 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1471 if (visiblePosition.isNull())
1474 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1475 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1479 * Performs three operations:
1480 * 1. Convert control characters to spaces
1481 * 2. Trim leading and trailing spaces
1482 * 3. Collapse internal whitespace.
1484 template <typename CharacterType>
1485 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1487 const String& title = titleWithDirection.string();
1488 const CharacterType* characters = title.getCharacters<CharacterType>();
1489 unsigned length = title.length();
1492 StringBuffer<CharacterType> buffer(length);
1493 unsigned builderIndex = 0;
1495 // Skip leading spaces and leading characters that would convert to spaces
1496 for (i = 0; i < length; ++i) {
1497 CharacterType c = characters[i];
1498 if (!(c <= 0x20 || c == 0x7F))
1503 return StringWithDirection();
1505 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1506 bool previousCharWasWS = false;
1507 for (; i < length; ++i) {
1508 CharacterType c = characters[i];
1509 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1510 if (previousCharWasWS)
1512 buffer[builderIndex++] = ' ';
1513 previousCharWasWS = true;
1515 buffer[builderIndex++] = c;
1516 previousCharWasWS = false;
1520 // Strip trailing spaces
1521 while (builderIndex > 0) {
1523 if (buffer[builderIndex] != ' ')
1527 if (!builderIndex && buffer[builderIndex] == ' ')
1528 return StringWithDirection();
1530 buffer.shrink(builderIndex + 1);
1532 // Replace the backslashes with currency symbols if the encoding requires it.
1533 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1535 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1538 void Document::updateTitle(const StringWithDirection& title)
1540 if (m_rawTitle == title)
1545 if (m_rawTitle.string().isEmpty())
1546 m_title = StringWithDirection();
1548 if (m_rawTitle.string().is8Bit())
1549 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1551 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1553 if (DocumentLoader* loader = this->loader())
1554 loader->setTitle(m_title);
1557 void Document::setTitle(const String& title)
1559 // Title set by JavaScript -- overrides any title elements.
1560 m_titleSetExplicitly = true;
1561 if (!isHTMLDocument() && !isXHTMLDocument())
1563 else if (!m_titleElement) {
1564 if (HTMLElement* headElement = head()) {
1565 m_titleElement = createElement(titleTag, false);
1566 headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION);
1570 // The DOM API has no method of specifying direction, so assume LTR.
1571 updateTitle(StringWithDirection(title, LTR));
1573 if (m_titleElement) {
1574 ASSERT(isHTMLTitleElement(m_titleElement.get()));
1575 if (isHTMLTitleElement(m_titleElement.get()))
1576 toHTMLTitleElement(m_titleElement.get())->setText(title);
1580 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1582 if (titleElement != m_titleElement) {
1583 if (m_titleElement || m_titleSetExplicitly) {
1584 // Only allow the first title element to change the title -- others have no effect.
1587 m_titleElement = titleElement;
1593 void Document::removeTitle(Element* titleElement)
1595 if (m_titleElement != titleElement)
1599 m_titleSetExplicitly = false;
1601 // Update title based on first title element in the head, if one exists.
1602 if (HTMLElement* headElement = head()) {
1603 if (auto firstTitle = childrenOfType<HTMLTitleElement>(headElement).first())
1604 setTitleElement(firstTitle->textWithDirection(), firstTitle);
1607 if (!m_titleElement)
1608 updateTitle(StringWithDirection());
1611 #if ENABLE(PAGE_VISIBILITY_API)
1612 PageVisibilityState Document::pageVisibilityState() const
1614 // The visibility of the document is inherited from the visibility of the
1615 // page. If there is no page associated with the document, we will assume
1616 // that the page is hidden, as specified by the spec:
1617 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1618 if (!m_frame || !m_frame->page())
1619 return PageVisibilityStateHidden;
1620 return m_frame->page()->visibilityState();
1623 String Document::visibilityState() const
1625 return pageVisibilityStateString(pageVisibilityState());
1628 bool Document::hidden() const
1630 return pageVisibilityState() != PageVisibilityStateVisible;
1634 #if ENABLE(CSP_NEXT)
1635 DOMSecurityPolicy* Document::securityPolicy()
1637 if (!m_domSecurityPolicy)
1638 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1639 return m_domSecurityPolicy.get();
1643 String Document::nodeName() const
1648 Node::NodeType Document::nodeType() const
1650 return DOCUMENT_NODE;
1653 FormController& Document::formController()
1655 if (!m_formController)
1656 m_formController = FormController::create();
1657 return *m_formController;
1660 Vector<String> Document::formElementsState() const
1662 if (!m_formController)
1663 return Vector<String>();
1664 return m_formController->formElementsState();
1667 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1669 if (!stateVector.size() && !m_formController)
1671 formController().setStateForNewFormElements(stateVector);
1674 FrameView* Document::view() const
1676 return m_frame ? m_frame->view() : 0;
1679 Page* Document::page() const
1681 return m_frame ? m_frame->page() : 0;
1684 Settings* Document::settings() const
1686 return m_frame ? &m_frame->settings() : 0;
1689 PassRefPtr<Range> Document::createRange()
1691 return Range::create(this);
1694 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1695 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1698 ec = NOT_SUPPORTED_ERR;
1701 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1704 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1705 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1708 ec = NOT_SUPPORTED_ERR;
1711 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1714 void Document::scheduleForcedStyleRecalc()
1716 m_pendingStyleRecalcShouldForce = true;
1717 scheduleStyleRecalc();
1720 void Document::scheduleStyleRecalc()
1722 if (shouldDisplaySeamlesslyWithParent()) {
1723 // When we're seamless, our parent document manages our style recalcs.
1724 ownerElement()->setNeedsStyleRecalc();
1725 ownerElement()->document().scheduleStyleRecalc();
1729 if (m_styleRecalcTimer.isActive() || inPageCache())
1732 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1734 // FIXME: Why on earth is this here? This is clearly misplaced.
1735 invalidateAccessKeyMap();
1737 m_styleRecalcTimer.startOneShot(0);
1739 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1742 void Document::unscheduleStyleRecalc()
1744 ASSERT(!childNeedsStyleRecalc());
1746 m_styleRecalcTimer.stop();
1747 m_pendingStyleRecalcShouldForce = false;
1750 bool Document::hasPendingStyleRecalc() const
1752 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1755 bool Document::hasPendingForcedStyleRecalc() const
1757 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1760 void Document::styleRecalcTimerFired(Timer<Document>*)
1762 updateStyleIfNeeded();
1765 void Document::recalcStyle(Style::Change change)
1767 ASSERT(!view() || !view()->isPainting());
1769 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1773 FrameView& frameView = m_renderView->frameView();
1774 if (frameView.isPainting())
1777 if (m_inStyleRecalc)
1778 return; // Guard against re-entrancy. -dwh
1780 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1781 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1782 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1783 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1784 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1785 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1787 m_styleSheetCollection.flushPendingUpdates();
1789 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1791 if (m_elementSheet && m_elementSheet->contents()->usesRemUnits())
1792 m_styleSheetCollection.setUsesRemUnit(true);
1794 m_inStyleRecalc = true;
1796 PostAttachCallbackDisabler disabler(*this);
1797 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1799 frameView.pauseScheduledEvents();
1800 frameView.beginDeferredRepaints();
1802 if (m_pendingStyleRecalcShouldForce)
1803 change = Style::Force;
1805 if (change == Style::Force) {
1806 // This may get set again during style resolve.
1807 m_hasNodesWithPlaceholderStyle = false;
1810 Style::resolveTree(*this, change);
1812 #if USE(ACCELERATED_COMPOSITING)
1813 frameView.updateCompositingLayersAfterStyleChange();
1816 clearNeedsStyleRecalc();
1817 clearChildNeedsStyleRecalc();
1818 unscheduleStyleRecalc();
1820 m_inStyleRecalc = false;
1822 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1823 if (m_styleResolver)
1824 m_styleSheetCollection.resetCSSFeatureFlags();
1826 frameView.resumeScheduledEvents();
1827 frameView.endDeferredRepaints();
1830 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1831 if (m_closeAfterStyleRecalc) {
1832 m_closeAfterStyleRecalc = false;
1836 InspectorInstrumentation::didRecalculateStyle(cookie);
1838 // As a result of the style recalculation, the currently hovered element might have been
1839 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1840 // to check if any other elements ended up under the mouse pointer due to re-layout.
1841 if (m_hoveredElement && !m_hoveredElement->renderer())
1842 frameView.frame().eventHandler().dispatchFakeMouseMoveEventSoon();
1844 // Style change may reset the focus, e.g. display: none, visibility: hidden.
1845 resetHiddenFocusElementSoon();
1848 void Document::updateStyleIfNeeded()
1850 ASSERT(isMainThread());
1851 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1853 if (m_optimizedStyleSheetUpdateTimer.isActive())
1854 styleResolverChanged(RecalcStyleIfNeeded);
1856 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1859 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
1860 recalcStyle(Style::NoChange);
1863 void Document::updateLayout()
1865 ASSERT(isMainThread());
1867 FrameView* frameView = view();
1868 if (frameView && frameView->isInLayout()) {
1869 // View layout should not be re-entrant.
1870 ASSERT_NOT_REACHED();
1874 if (Element* oe = ownerElement())
1875 oe->document().updateLayout();
1877 updateStyleIfNeeded();
1879 StackStats::LayoutCheckPoint layoutCheckPoint;
1881 // Only do a layout if changes have occurred that make it necessary.
1882 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1883 frameView->layout();
1885 // Active focus element's isFocusable() state may change after Layout. e.g. width: 0px or height: 0px.
1886 resetHiddenFocusElementSoon();
1889 // FIXME: This is a bad idea and needs to be removed eventually.
1890 // Other browsers load stylesheets before they continue parsing the web page.
1891 // Since we don't, we can run JavaScript code that needs answers before the
1892 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1893 // lets us get reasonable answers. The long term solution to this problem is
1894 // to instead suspend JavaScript execution.
1895 void Document::updateLayoutIgnorePendingStylesheets()
1897 bool oldIgnore = m_ignorePendingStylesheets;
1899 if (!haveStylesheetsLoaded()) {
1900 m_ignorePendingStylesheets = true;
1901 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1902 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1903 // with accurate style information. (Our suppression involves blanking the whole page at the
1904 // moment. If it were more refined, we might be able to do something better.)
1905 // It's worth noting though that this entire method is a hack, since what we really want to do is
1906 // suspend JS instead of doing a layout with inaccurate information.
1907 HTMLElement* bodyElement = body();
1908 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1909 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1910 styleResolverChanged(RecalcStyleImmediately);
1911 } else if (m_hasNodesWithPlaceholderStyle)
1912 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1913 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1914 // but here we need up-to-date style immediately.
1915 recalcStyle(Style::Force);
1920 m_ignorePendingStylesheets = oldIgnore;
1923 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1925 ASSERT_ARG(element, &element->document() == this);
1927 bool oldIgnore = m_ignorePendingStylesheets;
1928 m_ignorePendingStylesheets = true;
1929 RefPtr<RenderStyle> style = ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1930 m_ignorePendingStylesheets = oldIgnore;
1931 return style.release();
1934 bool Document::isPageBoxVisible(int pageIndex)
1936 return ensureStyleResolver().styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
1939 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1941 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
1942 RenderView* view = renderView();
1944 int width = pageSize.width();
1945 int height = pageSize.height();
1946 switch (style->pageSizeType()) {
1947 case PAGE_SIZE_AUTO:
1949 case PAGE_SIZE_AUTO_LANDSCAPE:
1951 std::swap(width, height);
1953 case PAGE_SIZE_AUTO_PORTRAIT:
1955 std::swap(width, height);
1957 case PAGE_SIZE_RESOLVED: {
1958 LengthSize size = style->pageSize();
1959 ASSERT(size.width().isFixed());
1960 ASSERT(size.height().isFixed());
1961 width = valueForLength(size.width(), 0, view);
1962 height = valueForLength(size.height(), 0, view);
1966 ASSERT_NOT_REACHED();
1968 pageSize = IntSize(width, height);
1970 // The percentage is calculated with respect to the width even for margin top and bottom.
1971 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1972 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
1973 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
1974 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
1975 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
1978 void Document::setIsViewSource(bool isViewSource)
1980 m_isViewSource = isViewSource;
1981 if (!m_isViewSource)
1984 setSecurityOrigin(SecurityOrigin::createUnique());
1987 void Document::createStyleResolver()
1989 bool matchAuthorAndUserStyles = true;
1990 if (Settings* settings = this->settings())
1991 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
1992 m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
1993 m_styleSheetCollection.combineCSSFeatureFlags();
1996 void Document::clearStyleResolver()
1998 m_styleResolver.clear();
2001 void Document::setRenderView(RenderView* renderView)
2003 m_renderView = renderView;
2004 Node::setRenderer(renderView);
2007 void Document::createRenderTree()
2009 ASSERT(!attached());
2010 ASSERT(!m_inPageCache);
2011 ASSERT(!m_axObjectCache || this != topDocument());
2014 m_renderArena = std::make_unique<RenderArena>();
2016 setRenderView(new (*m_renderArena) RenderView(*this));
2017 #if USE(ACCELERATED_COMPOSITING)
2018 renderView()->setIsInWindow(true);
2021 recalcStyle(Style::Force);
2023 if (m_documentElement)
2024 Style::attachRenderTree(*m_documentElement);
2029 static void pageWheelEventHandlerCountChanged(Page& page)
2032 for (const Frame* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
2033 if (Document* document = frame->document())
2034 count += document->wheelEventHandlerCount();
2036 page.chrome().client().numWheelEventHandlersChanged(count);
2039 void Document::didBecomeCurrentDocumentInFrame()
2041 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2042 // If so, then m_frame could become 0, and we need to do something about that.
2044 m_frame->script().updateDocument();
2049 updateViewportArguments();
2051 // FIXME: Doing this only for the main frame is insufficient.
2052 // Changing a subframe can also change the wheel event handler count.
2053 // FIXME: Doing this only when a document goes into the frame is insufficient.
2054 // Removing a document can also change the wheel event handler count.
2055 // FIXME: Doing this every time is a waste. If the current document and its
2056 // subframes' documents have no wheel event handlers, then the count did not change,
2057 // unless the documents they are replacing had wheel event handlers.
2058 if (page() && m_frame->isMainFrame())
2059 pageWheelEventHandlerCountChanged(*page());
2061 #if ENABLE(TOUCH_EVENTS)
2062 // FIXME: Doing this only for the main frame is insufficient.
2063 // A subframe could have touch event handlers.
2064 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2065 page()->chrome().client().needTouchEvents(true);
2068 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2069 suspendScriptedAnimationControllerCallbacks();
2070 m_frame->animation().suspendAnimationsForDocument(this);
2071 suspendActiveDOMObjects(ActiveDOMObject::PageWillBeSuspended);
2075 void Document::disconnectFromFrame()
2080 void Document::destroyRenderTree()
2083 ASSERT(!m_inPageCache);
2085 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2087 if (this == topDocument())
2088 clearAXObjectCache();
2090 documentWillBecomeInactive();
2092 if (FrameView* frameView = view())
2093 frameView->detachCustomScrollbars();
2095 #if ENABLE(FULLSCREEN_API)
2096 if (m_fullScreenRenderer)
2097 setFullScreenRenderer(0);
2100 m_hoveredElement = 0;
2101 m_focusedElement = 0;
2102 m_activeElement = 0;
2104 if (m_documentElement)
2105 Style::detachRenderTree(*m_documentElement);
2107 clearChildNeedsStyleRecalc();
2110 unscheduleStyleRecalc();
2113 renderView()->destroy();
2116 #if ENABLE(IOS_TEXT_AUTOSIZING)
2117 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2118 m_textAutoSizedNodes.clear();
2121 m_renderArena = nullptr;
2124 void Document::prepareForDestruction()
2126 disconnectDescendantFrames();
2127 if (m_domWindow && m_frame)
2128 m_domWindow->willDetachDocumentFromFrame();
2130 destroyRenderTree();
2132 if (isPluginDocument())
2133 toPluginDocument(this)->detachFromPluginElement();
2135 #if ENABLE(POINTER_LOCK)
2137 page()->pointerLockController()->documentDetached(this);
2140 stopActiveDOMObjects();
2141 m_eventQueue.close();
2142 #if ENABLE(FULLSCREEN_API)
2143 m_fullScreenChangeEventTargetQueue.clear();
2144 m_fullScreenErrorEventTargetQueue.clear();
2147 #if ENABLE(REQUEST_ANIMATION_FRAME)
2148 clearScriptedAnimationController();
2151 #if ENABLE(SHARED_WORKERS)
2152 SharedWorkerRepository::documentDetached(this);
2155 #if ENABLE(TOUCH_EVENTS)
2156 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2157 parentDocument()->didRemoveEventTargetNode(this);
2160 if (m_mediaQueryMatcher)
2161 m_mediaQueryMatcher->documentDestroyed();
2163 disconnectFromFrame();
2166 void Document::removeAllEventListeners()
2168 EventTarget::removeAllEventListeners();
2171 m_domWindow->removeAllEventListeners();
2172 for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
2173 node->removeAllEventListeners();
2176 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2178 ScriptExecutionContext::suspendActiveDOMObjects(why);
2181 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2183 ScriptExecutionContext::resumeActiveDOMObjects(why);
2186 void Document::clearAXObjectCache()
2188 ASSERT(topDocument() == this);
2189 // Clear the cache member variable before calling delete because attempts
2190 // are made to access it during destruction.
2191 m_axObjectCache.clear();
2194 AXObjectCache* Document::existingAXObjectCache() const
2196 if (!AXObjectCache::accessibilityEnabled())
2199 if (!topDocument()->hasLivingRenderTree())
2202 return topDocument()->m_axObjectCache.get();
2205 AXObjectCache* Document::axObjectCache() const
2207 if (!AXObjectCache::accessibilityEnabled())
2210 // The only document that actually has a AXObjectCache is the top-level
2211 // document. This is because we need to be able to get from any WebCoreAXObject
2212 // to any other WebCoreAXObject on the same page. Using a single cache allows
2213 // lookups across nested webareas (i.e. multiple documents).
2214 Document* topDocument = this->topDocument();
2216 // If the document has already been detached, do not make a new axObjectCache.
2217 if (!topDocument->hasLivingRenderTree())
2220 ASSERT(topDocument == this || !m_axObjectCache);
2221 if (!topDocument->m_axObjectCache)
2222 topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(*topDocument));
2223 return topDocument->m_axObjectCache.get();
2226 void Document::setVisuallyOrdered()
2228 m_visuallyOrdered = true;
2230 renderView()->style()->setRTLOrdering(VisualOrder);
2233 PassRefPtr<DocumentParser> Document::createParser()
2235 // FIXME: this should probably pass the frame instead
2236 return XMLDocumentParser::create(*this, view());
2239 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2241 return parser() ? parser()->asScriptableDocumentParser() : 0;
2244 void Document::open(Document* ownerDocument)
2246 if (ownerDocument) {
2247 setURL(ownerDocument->url());
2248 m_cookieURL = ownerDocument->cookieURL();
2249 setSecurityOrigin(ownerDocument->securityOrigin());
2253 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2254 if (parser->isParsing()) {
2255 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2256 if (parser->isExecutingScript())
2259 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2264 if (m_frame->loader().state() == FrameStateProvisional)
2265 m_frame->loader().stopAllLoaders();
2268 removeAllEventListeners();
2270 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2271 parser->setWasCreatedByScript(true);
2274 m_frame->loader().didExplicitOpen();
2277 void Document::detachParser()
2285 void Document::cancelParsing()
2290 // We have to clear the parser to avoid possibly triggering
2291 // the onload handler when closing as a side effect of a cancel-style
2292 // change, such as opening a new document or closing the window while
2298 void Document::implicitOpen()
2304 setCompatibilityMode(NoQuirksMode);
2306 // Documents rendered seamlessly should start out requiring a stylesheet
2307 // collection update in order to ensure they inherit all the relevant data
2308 // from their parent.
2309 if (shouldDisplaySeamlesslyWithParent())
2310 styleResolverChanged(DeferRecalcStyle);
2312 m_parser = createParser();
2314 setReadyState(Loading);
2317 HTMLElement* Document::body() const
2319 Node* de = documentElement();
2323 // try to prefer a FRAMESET element over BODY
2325 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2326 if (i->hasTagName(framesetTag))
2327 return toHTMLElement(i);
2329 if (i->hasTagName(bodyTag) && !body)
2332 return toHTMLElement(body);
2335 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2337 RefPtr<HTMLElement> newBody = prpNewBody;
2339 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2340 ec = HIERARCHY_REQUEST_ERR;
2344 if (&newBody->document() != this) {
2346 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2350 newBody = toHTMLElement(node.get());
2353 HTMLElement* b = body();
2355 documentElement()->appendChild(newBody.release(), ec);
2357 documentElement()->replaceChild(newBody.release(), b, ec);
2360 HTMLHeadElement* Document::head()
2362 Node* de = documentElement();
2366 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2367 if (e->hasTagName(headTag))
2368 return static_cast<HTMLHeadElement*>(e);
2373 void Document::close()
2375 // FIXME: We should follow the specification more closely:
2376 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2378 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2384 void Document::explicitClose()
2386 if (RefPtr<DocumentParser> parser = m_parser)
2390 // Because we have no frame, we don't know if all loading has completed,
2391 // so we just call implicitClose() immediately. FIXME: This might fire
2392 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2397 m_frame->loader().checkCompleted();
2400 void Document::implicitClose()
2402 // 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.
2403 if (m_inStyleRecalc) {
2404 m_closeAfterStyleRecalc = true;
2408 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2409 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2414 // Call to dispatchWindowLoadEvent can blow us from underneath.
2415 Ref<Document> protect(*this);
2417 m_processingLoadEvent = true;
2419 ScriptableDocumentParser* parser = scriptableDocumentParser();
2420 m_wellFormed = parser && parser->wellFormed();
2422 // We have to clear the parser, in case someone document.write()s from the
2423 // onLoad event handler, as in Radar 3206524.
2426 // FIXME: We kick off the icon loader when the Document is done parsing.
2427 // There are earlier opportunities we could start it:
2428 // -When the <head> finishes parsing
2429 // -When any new HTMLLinkElement is inserted into the document
2430 // But those add a dynamic component to the favicon that has UI
2431 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2434 f->loader().icon().startLoader();
2435 f->animation().startAnimationsIfNotSuspended(this);
2438 ImageLoader::dispatchPendingBeforeLoadEvents();
2439 ImageLoader::dispatchPendingLoadEvents();
2440 ImageLoader::dispatchPendingErrorEvents();
2442 HTMLLinkElement::dispatchPendingLoadEvents();
2443 HTMLStyleElement::dispatchPendingLoadEvents();
2446 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2447 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2448 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2449 if (svgExtensions())
2450 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2453 dispatchWindowLoadEvent();
2454 enqueuePageshowEvent(PageshowEventNotPersisted);
2455 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2458 f->loader().handledOnloadEvents();
2459 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2460 if (!ownerElement())
2461 printf("onload fired at %d\n", elapsedTime());
2464 // An event handler may have removed the frame
2466 m_processingLoadEvent = false;
2470 // Make sure both the initial layout and reflow happen after the onload
2471 // fires. This will improve onload scores, and other browsers do it.
2472 // If they wanna cheat, we can too. -dwh
2474 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2475 // Just bail out. Before or during the onload we were shifted to another page.
2476 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2477 m_processingLoadEvent = false;
2478 view()->unscheduleRelayout();
2482 frame()->loader().checkCallImplicitClose();
2484 // We used to force a synchronous display and flush here. This really isn't
2485 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2486 // (if your platform is syncing flushes and limiting them to 60fps).
2487 m_overMinimumLayoutThreshold = true;
2488 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2489 updateStyleIfNeeded();
2491 // Always do a layout after loading if needed.
2492 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2496 m_processingLoadEvent = false;
2498 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2499 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2500 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2501 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2502 // exists in the cache (we ignore the return value because we don't need it here). This is
2503 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2504 axObjectCache()->getOrCreate(renderView());
2505 if (this == topDocument())
2506 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLoadComplete);
2508 // AXLoadComplete can only be posted on the top document, so if it's a document
2509 // in an iframe that just finished loading, post AXLayoutComplete instead.
2510 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2516 if (svgExtensions())
2517 accessSVGExtensions()->startAnimations();
2521 void Document::setParsing(bool b)
2525 if (m_bParsing && !m_sharedObjectPool)
2526 m_sharedObjectPool = DocumentSharedObjectPool::create();
2528 if (!m_bParsing && view())
2529 view()->scheduleRelayout();
2531 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2532 if (!ownerElement() && !m_bParsing)
2533 printf("Parsing finished at %d\n", elapsedTime());
2537 bool Document::shouldScheduleLayout()
2539 // This function will only be called when FrameView thinks a layout is needed.
2540 // This enforces a couple extra rules.
2542 // (a) Only schedule a layout once the stylesheets are loaded.
2543 // (b) Only schedule layout once we have a body element.
2545 return (haveStylesheetsLoaded() && body())
2546 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2549 bool Document::isLayoutTimerActive()
2551 return view() && view()->layoutPending() && !minimumLayoutDelay();
2554 int Document::minimumLayoutDelay()
2556 if (m_overMinimumLayoutThreshold)
2559 int elapsed = elapsedTime();
2560 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2562 // We'll want to schedule the timer to fire at the minimum layout threshold.
2563 return max(0, cLayoutScheduleThreshold - elapsed);
2566 int Document::elapsedTime() const
2568 return static_cast<int>(monotonicallyIncreasingTimeMS() - m_startTime);
2571 void Document::write(const SegmentedString& text, Document* ownerDocument)
2573 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2575 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2576 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2578 if (m_writeRecursionIsTooDeep)
2581 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2582 if (!ownerElement())
2583 printf("Beginning a document.write at %d\n", elapsedTime());
2586 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2587 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2590 if (!hasInsertionPoint)
2591 open(ownerDocument);
2594 m_parser->insert(text);
2596 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2597 if (!ownerElement())
2598 printf("Ending a document.write at %d\n", elapsedTime());
2602 void Document::write(const String& text, Document* ownerDocument)
2604 write(SegmentedString(text), ownerDocument);
2607 void Document::writeln(const String& text, Document* ownerDocument)
2609 write(text, ownerDocument);
2610 write("\n", ownerDocument);
2613 double Document::minimumTimerInterval() const
2617 return ScriptExecutionContext::minimumTimerInterval();
2618 return p->settings().minDOMTimerInterval();
2621 double Document::timerAlignmentInterval() const
2625 return ScriptExecutionContext::timerAlignmentInterval();
2626 return p->settings().domTimerAlignmentInterval();
2629 EventTarget* Document::errorEventTarget()
2631 return m_domWindow.get();
2634 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2636 addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber, callStack);
2639 void Document::setURL(const URL& url)
2641 const URL& newURL = url.isEmpty() ? blankURL() : url;
2642 if (newURL == m_url)
2646 m_documentURI = m_url.string();
2650 void Document::updateBaseURL()
2652 URL oldBaseURL = m_baseURL;
2653 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2654 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2655 // from the Document interface otherwise.
2656 if (!m_baseElementURL.isEmpty())
2657 m_baseURL = m_baseElementURL;
2658 else if (!m_baseURLOverride.isEmpty())
2659 m_baseURL = m_baseURLOverride;
2661 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2662 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2663 // and DOM 3 Core does not specify how it should be resolved.
2664 m_baseURL = URL(ParsedURLString, documentURI());
2667 if (m_selectorQueryCache)
2668 m_selectorQueryCache->invalidate();
2670 if (!m_baseURL.isValid())
2673 if (m_elementSheet) {
2674 // Element sheet is silly. It never contains anything.
2675 ASSERT(!m_elementSheet->contents()->ruleCount());
2676 bool usesRemUnits = m_elementSheet->contents()->usesRemUnits();
2677 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2678 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2679 m_elementSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2682 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2683 // Base URL change changes any relative visited links.
2684 // 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.
2685 auto anchorDescendants = descendantsOfType<HTMLAnchorElement>(this);
2686 for (auto anchor = anchorDescendants.begin(), end = anchorDescendants.end(); anchor != end; ++anchor)
2687 anchor->invalidateCachedVisitedLinkHash();
2691 void Document::setBaseURLOverride(const URL& url)
2693 m_baseURLOverride = url;
2697 void Document::processBaseElement()
2699 // Find the first href attribute in a base element and the first target attribute in a base element.
2700 const AtomicString* href = 0;
2701 const AtomicString* target = 0;
2702 auto baseDescendants = descendantsOfType<HTMLBaseElement>(this);
2703 for (auto base = baseDescendants.begin(), end = baseDescendants.end(); base != end && (!href || !target); ++base) {
2705 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2706 if (!value.isNull())
2710 const AtomicString& value = base->fastGetAttribute(targetAttr);
2711 if (!value.isNull())
2716 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2719 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2720 if (!strippedHref.isEmpty())
2721 baseElementURL = URL(url(), strippedHref);
2723 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2724 m_baseElementURL = baseElementURL;
2728 m_baseTarget = target ? *target : nullAtom;
2731 String Document::userAgent(const URL& url) const
2733 return frame() ? frame()->loader().userAgent(url) : String();
2736 void Document::disableEval(const String& errorMessage)
2741 frame()->script().disableEval(errorMessage);
2744 bool Document::canNavigate(Frame* targetFrame)
2749 // FIXME: We shouldn't call this function without a target frame, but
2750 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2751 // returning true when supplied with a 0 targetFrame.
2755 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2756 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2759 if (isSandboxed(SandboxNavigation)) {
2760 if (targetFrame->tree().isDescendantOf(m_frame))
2763 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2764 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2765 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2767 printNavigationErrorMessage(targetFrame, url(), reason);
2771 // This is the normal case. A document can navigate its decendant frames,
2772 // or, more generally, a document can navigate a frame if the document is
2773 // in the same origin as any of that frame's ancestors (in the frame
2776 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2777 // historical information about this security check.
2778 if (canAccessAncestor(securityOrigin(), targetFrame))
2781 // Top-level frames are easier to navigate than other frames because they
2782 // display their URLs in the address bar (in most browsers). However, there
2783 // are still some restrictions on navigation to avoid nuisance attacks.
2784 // Specifically, a document can navigate a top-level frame if that frame
2785 // opened the document or if the document is the same-origin with any of
2786 // the top-level frame's opener's ancestors (in the frame hierarchy).
2788 // In both of these cases, the document performing the navigation is in
2789 // some way related to the frame being navigate (e.g., by the "opener"
2790 // and/or "parent" relation). Requiring some sort of relation prevents a
2791 // document from navigating arbitrary, unrelated top-level frames.
2792 if (!targetFrame->tree().parent()) {
2793 if (targetFrame == m_frame->loader().opener())
2796 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
2800 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2804 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2806 Frame* currentFrame = m_frame;
2810 Frame* ancestorFrame = currentFrame->tree().parent();
2812 while (ancestorFrame) {
2813 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2814 return currentFrame;
2815 currentFrame = ancestorFrame;
2816 ancestorFrame = ancestorFrame->tree().parent();
2822 void Document::seamlessParentUpdatedStylesheets()
2824 styleResolverChanged(RecalcStyleImmediately);
2827 void Document::didRemoveAllPendingStylesheet()
2829 m_needsNotifyRemoveAllPendingStylesheet = false;
2831 styleResolverChanged(RecalcStyleIfNeeded);
2833 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2834 parser->executeScriptsWaitingForStylesheets();
2836 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2837 view()->scrollToFragment(m_url);
2840 CSSStyleSheet& Document::elementSheet()
2842 if (!m_elementSheet)
2843 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2844 return *m_elementSheet;
2847 void Document::processHttpEquiv(const String& equiv, const String& content)
2849 ASSERT(!equiv.isNull() && !content.isNull());
2851 Frame* frame = this->frame();
2853 if (equalIgnoringCase(equiv, "default-style")) {
2854 // The preferred style set has been overridden as per section
2855 // 14.3.2 of the HTML4.0 specification. We need to update the
2856 // sheet used variable and then update our style selector.
2857 // For more info, see the test at:
2858 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2860 m_styleSheetCollection.setSelectedStylesheetSetName(content);
2861 m_styleSheetCollection.setPreferredStylesheetSetName(content);
2862 styleResolverChanged(DeferRecalcStyle);
2863 } else if (equalIgnoringCase(equiv, "refresh")) {
2866 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2868 url = m_url.string();
2870 url = completeURL(url).string();
2871 frame->navigationScheduler().scheduleRedirect(delay, url);
2873 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2874 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2875 if (isHTMLDocument()) {
2876 // Exception (for sandboxed documents) ignored.
2877 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
2879 } else if (equalIgnoringCase(equiv, "content-language"))
2880 setContentLanguage(content);
2881 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2882 parseDNSPrefetchControlHeader(content);
2883 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2885 FrameLoader& frameLoader = frame->loader();
2886 unsigned long requestIdentifier = 0;
2887 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
2888 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
2889 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
2890 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
2891 frameLoader.stopAllLoaders();
2892 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
2893 // intent, we must navigate away from the possibly partially-rendered document to a location that
2894 // doesn't inherit the parent's SecurityOrigin.
2895 frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
2896 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
2899 } else if (equalIgnoringCase(equiv, "content-security-policy"))
2900 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
2901 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2902 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
2903 else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2904 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
2905 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2906 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
2909 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2910 static bool isSeparator(UChar c)
2912 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2915 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2917 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2918 int keyBegin, keyEnd;
2919 int valueBegin, valueEnd;
2922 int length = features.length();
2923 String buffer = features.lower();
2924 while (i < length) {
2925 // skip to first non-separator, but don't skip past the end of the string
2926 while (isSeparator(buffer[i])) {
2933 // skip to first separator
2934 while (!isSeparator(buffer[i]))
2938 // skip to first '=', but don't skip past a ',' or the end of the string
2939 while (buffer[i] != '=') {
2940 if (buffer[i] == ',' || i >= length)
2945 // skip to first non-separator, but don't skip past a ',' or the end of the string
2946 while (isSeparator(buffer[i])) {
2947 if (buffer[i] == ',' || i >= length)
2953 // skip to first separator
2954 while (!isSeparator(buffer[i]))
2958 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
2960 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2961 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2962 callback(keyString, valueString, this, data);
2966 void Document::processViewport(const String& features, ViewportArguments::Type origin)
2968 ASSERT(!features.isNull());
2970 if (origin < m_viewportArguments.type)
2973 m_viewportArguments = ViewportArguments(origin);
2974 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2976 updateViewportArguments();
2979 void Document::updateViewportArguments()
2981 if (page() && frame()->isMainFrame()) {
2983 m_didDispatchViewportPropertiesChanged = true;
2985 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
2989 void Document::processReferrerPolicy(const String& policy)
2991 ASSERT(!policy.isNull());
2993 m_referrerPolicy = ReferrerPolicyDefault;
2995 if (equalIgnoringCase(policy, "never"))
2996 m_referrerPolicy = ReferrerPolicyNever;
2997 else if (equalIgnoringCase(policy, "always"))
2998 m_referrerPolicy = ReferrerPolicyAlways;
2999 else if (equalIgnoringCase(policy, "origin"))
3000 m_referrerPolicy = ReferrerPolicyOrigin;
3003 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3005 if (!hasLivingRenderTree())
3006 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3008 HitTestResult result(documentPoint);
3009 renderView()->hitTest(request, result);
3011 if (!request.readOnly())
3012 updateHoverActiveState(request, result.innerElement(), &event);
3014 return MouseEventWithHitTestResults(event, result);
3017 // DOM Section 1.1.1
3018 bool Document::childTypeAllowed(NodeType type) const
3021 case ATTRIBUTE_NODE:
3022 case CDATA_SECTION_NODE:
3023 case DOCUMENT_FRAGMENT_NODE:
3026 case ENTITY_REFERENCE_NODE:
3029 case XPATH_NAMESPACE_NODE:
3032 case PROCESSING_INSTRUCTION_NODE:
3034 case DOCUMENT_TYPE_NODE:
3036 // Documents may contain no more than one of each of these.
3037 // (One Element and one DocumentType.)
3038 for (Node* c = firstChild(); c; c = c->nextSibling())
3039 if (c->nodeType() == type)
3046 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3049 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3052 if (oldChild->nodeType() == newChild->nodeType())
3055 int numDoctypes = 0;
3056 int numElements = 0;
3058 // First, check how many doctypes and elements we have, not counting
3059 // the child we're about to remove.
3060 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3064 switch (c->nodeType()) {
3065 case DOCUMENT_TYPE_NODE:
3076 // Then, see how many doctypes and elements might be added by the new child.
3077 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3078 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3079 switch (c->nodeType()) {
3080 case ATTRIBUTE_NODE:
3081 case CDATA_SECTION_NODE:
3082 case DOCUMENT_FRAGMENT_NODE:
3085 case ENTITY_REFERENCE_NODE:
3088 case XPATH_NAMESPACE_NODE:
3091 case PROCESSING_INSTRUCTION_NODE:
3093 case DOCUMENT_TYPE_NODE:
3102 switch (newChild->nodeType()) {
3103 case ATTRIBUTE_NODE:
3104 case CDATA_SECTION_NODE:
3105 case DOCUMENT_FRAGMENT_NODE:
3108 case ENTITY_REFERENCE_NODE:
3111 case XPATH_NAMESPACE_NODE:
3114 case PROCESSING_INSTRUCTION_NODE:
3116 case DOCUMENT_TYPE_NODE:
3125 if (numElements > 1 || numDoctypes > 1)
3131 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3133 // Spec says cloning Document nodes is "implementation dependent"
3134 // so we do not support it...
3138 StyleSheetList* Document::styleSheets()
3140 if (!m_styleSheetList)
3141 m_styleSheetList = StyleSheetList::create(this);
3142 return m_styleSheetList.get();
3145 String Document::preferredStylesheetSet() const
3147 return m_styleSheetCollection.preferredStylesheetSetName();
3150 String Document::selectedStylesheetSet() const
3152 return m_styleSheetCollection.selectedStylesheetSetName();
3155 void Document::setSelectedStylesheetSet(const String& aString)
3157 m_styleSheetCollection.setSelectedStylesheetSetName(aString);
3158 styleResolverChanged(DeferRecalcStyle);
3161 void Document::evaluateMediaQueryList()
3163 if (m_mediaQueryMatcher)
3164 m_mediaQueryMatcher->styleResolverChanged();
3167 void Document::optimizedStyleSheetUpdateTimerFired(Timer<Document>*)
3169 styleResolverChanged(RecalcStyleIfNeeded);
3172 void Document::scheduleOptimizedStyleSheetUpdate()
3174 if (m_optimizedStyleSheetUpdateTimer.isActive())
3176 m_styleSheetCollection.setPendingUpdateType(DocumentStyleSheetCollection::OptimizedUpdate);
3177 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3180 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3182 if (m_optimizedStyleSheetUpdateTimer.isActive())
3183 m_optimizedStyleSheetUpdateTimer.stop();
3185 // Don't bother updating, since we haven't loaded all our style info yet
3186 // and haven't calculated the style selector for the first time.
3187 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3188 m_styleResolver.clear();
3191 m_didCalculateStyleResolver = true;
3193 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3194 if (!ownerElement())
3195 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3198 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3199 ? DocumentStyleSheetCollection::OptimizedUpdate
3200 : DocumentStyleSheetCollection::FullUpdate;
3201 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection.updateActiveStyleSheets(styleSheetUpdate);
3203 if (updateFlag == DeferRecalcStyle) {
3204 scheduleForcedStyleRecalc();
3208 if (updateFlag == DeferRecalcStyleIfNeeded) {
3209 if (stylesheetChangeRequiresStyleRecalc)
3210 scheduleForcedStyleRecalc();
3214 if (didLayoutWithPendingStylesheets() && !m_styleSheetCollection.hasPendingSheets()) {
3215 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3217 renderView()->repaintViewAndCompositedLayers();
3220 if (!stylesheetChangeRequiresStyleRecalc)
3223 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3224 // make sure animations get the correct update time
3226 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
3227 recalcStyle(Style::Force);
3230 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3231 if (!ownerElement())
3232 printf("Finished update of style selector at time %d\n", elapsedTime());
3236 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3238 view()->scheduleRelayout();
3241 evaluateMediaQueryList();
3244 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3246 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3250 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3251 for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
3252 Document* childDocument = child->document();
3253 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3254 ASSERT(&childDocument->seamlessParentIFrame()->document() == this);
3255 childDocument->seamlessParentUpdatedStylesheets();
3260 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3262 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3265 Element* focusedElement = node->treeScope().focusedElement();
3266 if (!focusedElement)
3269 bool nodeInSubtree = false;
3270 if (amongChildrenOnly)
3271 nodeInSubtree = focusedElement->isDescendantOf(node);
3273 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3276 setFocusedElement(0);
3279 void Document::hoveredElementDidDetach(Element* element)
3281 if (!m_hoveredElement || element != m_hoveredElement)
3284 m_hoveredElement = element->parentElement();
3285 while (m_hoveredElement && !m_hoveredElement->renderer())
3286 m_hoveredElement = m_hoveredElement->parentElement();
3288 frame()->eventHandler().scheduleHoverStateUpdate();
3291 void Document::elementInActiveChainDidDetach(Element* element)
3293 if (!m_activeElement || element != m_activeElement)
3296 m_activeElement = element->parentElement();
3297 while (m_activeElement && !m_activeElement->renderer())
3298 m_activeElement = m_activeElement->parentElement();
3301 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3302 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3304 return m_annotatedRegions;
3307 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3309 m_annotatedRegions = regions;
3310 setAnnotatedRegionsDirty(false);
3314 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
3316 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3318 // Make sure newFocusedElement is actually in this document
3319 if (newFocusedElement && (&newFocusedElement->document() != this))
3322 if (m_focusedElement == newFocusedElement)
3328 bool focusChangeBlocked = false;
3329 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3331 // Remove focus from the existing focus node (if any)
3332 if (oldFocusedElement) {
3333 if (oldFocusedElement->active())
3334 oldFocusedElement->setActive(false);
3336 oldFocusedElement->setFocus(false);
3338 // Dispatch a change event for form control elements that have been edited.
3339 if (oldFocusedElement->isFormControlElement()) {
3340 HTMLFormControlElement* formControlElement = toHTMLFormControlElement(oldFocusedElement.get());
3341 if (formControlElement->wasChangedSinceLastFormControlChangeEvent())
3342 formControlElement->dispatchFormControlChangeEvent();
3345 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3346 oldFocusedElement->dispatchBlurEvent(newFocusedElement);
3348 if (m_focusedElement) {
3349 // handler shifted focus
3350 focusChangeBlocked = true;
3351 newFocusedElement = 0;
3354 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement); // DOM level 3 name for the bubbling blur event.
3355 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3356 // on it, probably when <rdar://problem/8503958> is resolved.
3357 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement); // DOM level 2 name for compatibility.
3359 if (m_focusedElement) {
3360 // handler shifted focus
3361 focusChangeBlocked = true;
3362 newFocusedElement = 0;
3365 if (oldFocusedElement->isRootEditableElement())
3366 frame()->editor().didEndEditing();
3369 Widget* oldWidget = widgetForNode(oldFocusedElement.get());
3371 oldWidget->setFocus(false);
3373 view()->setFocus(false);
3377 if (newFocusedElement && newFocusedElement->isFocusable()) {
3378 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3379 // delegate blocks focus change
3380 focusChangeBlocked = true;
3381 goto SetFocusedNodeDone;
3383 // Set focus on the new node
3384 m_focusedElement = newFocusedElement;
3386 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3387 m_focusedElement->dispatchFocusEvent(oldFocusedElement, direction);
3389 if (m_focusedElement != newFocusedElement) {
3390 // handler shifted focus
3391 focusChangeBlocked = true;
3392 goto SetFocusedNodeDone;
3395 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement); // DOM level 3 bubbling focus event.
3397 if (m_focusedElement != newFocusedElement) {
3398 // handler shifted focus
3399 focusChangeBlocked = true;
3400 goto SetFocusedNodeDone;
3403 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3404 // on it, probably when <rdar://problem/8503958> is m.
3405 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement); // DOM level 2 for compatibility.
3407 if (m_focusedElement != newFocusedElement) {
3408 // handler shifted focus
3409 focusChangeBlocked = true;
3410 goto SetFocusedNodeDone;
3413 m_focusedElement->setFocus(true);
3415 if (m_focusedElement->isRootEditableElement())
3416 frame()->editor().didBeginEditing();
3418 // eww, I suck. set the qt focus correctly
3419 // ### find a better place in the code for this
3421 Widget* focusWidget = widgetForNode(m_focusedElement.get());
3423 // Make sure a widget has the right size before giving it focus.
3424 // Otherwise, we are testing edge cases of the Widget code.
3425 // Specifically, in WebCore this does not work well for text fields.
3427 // Re-get the widget in case updating the layout changed things.
3428 focusWidget = widgetForNode(m_focusedElement.get());
3431 focusWidget->setFocus(true);
3433 view()->setFocus(true);
3437 if (!focusChangeBlocked && m_focusedElement) {
3438 // Create the AXObject cache in a focus change because GTK relies on it.
3439 if (AXObjectCache* cache = axObjectCache())
3440 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3443 if (!focusChangeBlocked && page())
3444 page()->chrome().focusedElementChanged(m_focusedElement.get());
3447 updateStyleIfNeeded();
3448 return !focusChangeBlocked;
3451 void Document::setCSSTarget(Element* n)
3454 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3457 n->didAffectSelector(AffectedSelectorTarget);
3460 void Document::registerNodeList(LiveNodeListBase* list)
3462 if (list->hasIdNameCache())
3463 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3464 m_nodeListCounts[list->invalidationType()]++;
3465 if (list->isRootedAtDocument())
3466 m_listsInvalidatedAtDocument.add(list);
3469 void Document::unregisterNodeList(LiveNodeListBase* list)
3471 if (list->hasIdNameCache())
3472 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3473 m_nodeListCounts[list->invalidationType()]--;
3474 if (list->isRootedAtDocument()) {
3475 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3476 m_listsInvalidatedAtDocument.remove(list);
3480 void Document::attachNodeIterator(NodeIterator* ni)
3482 m_nodeIterators.add(ni);
3485 void Document::detachNodeIterator(NodeIterator* ni)
3487 // The node iterator can be detached without having been attached if its root node didn't have a document
3488 // when the iterator was created, but has it now.
3489 m_nodeIterators.remove(ni);
3492 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3494 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3495 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3496 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3497 if ((*it)->root() == node) {
3498 detachNodeIterator(*it);
3499 newDocument->attachNodeIterator(*it);
3504 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
3506 if (!m_ranges.isEmpty()) {
3507 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3508 (*it)->nodeChildrenChanged(container);
3512 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3514 if (!m_ranges.isEmpty()) {
3515 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3516 (*it)->nodeChildrenWillBeRemoved(container);
3519 for (auto it = m_nodeIterators.begin(), end = m_nodeIterators.end(); it != end; ++it) {
3520 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3521 (*it)->nodeWillBeRemoved(n);
3524 if (Frame* frame = this->frame()) {
3525 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3526 frame->eventHandler().nodeWillBeRemoved(n);
3527 frame->selection().nodeWillBeRemoved(n);
3528 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3533 void Document::nodeWillBeRemoved(Node* n)
3535 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3536 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3537 (*it)->nodeWillBeRemoved(n);
3539 if (!m_ranges.isEmpty()) {
3540 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3541 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3542 (*it)->nodeWillBeRemoved(n);
3545 if (Frame* frame = this->frame()) {
3546 frame->eventHandler().nodeWillBeRemoved(n);
3547 frame->selection().nodeWillBeRemoved(n);
3548 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3552 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3554 if (!m_ranges.isEmpty()) {
3555 HashSet<Range*>::const_iterator end = m_ranges.end();
3556 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3557 (*it)->textInserted(text, offset, length);
3560 // Update the markers for spelling and grammar checking.
3561 m_markers->shiftMarkers(text, offset, length);
3564 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3566 if (!m_ranges.isEmpty()) {
3567 HashSet<Range*>::const_iterator end = m_ranges.end();
3568 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3569 (*it)->textRemoved(text, offset, length);
3572 // Update the markers for spelling and grammar checking.
3573 m_markers->removeMarkers(text, offset, length);
3574 m_markers->shiftMarkers(text, offset + length, 0 - length);
3577 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3579 if (!m_ranges.isEmpty()) {
3580 NodeWithIndex oldNodeWithIndex(oldNode);
3581 HashSet<Range*>::const_iterator end = m_ranges.end();
3582 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3583 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3586 // FIXME: This should update markers for spelling and grammar checking.
3589 void Document::textNodeSplit(Text* oldNode)
3591 if (!m_ranges.isEmpty()) {
3592 HashSet<Range*>::const_iterator end = m_ranges.end();
3593 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3594 (*it)->textNodeSplit(oldNode);
3597 // FIXME: This should update markers for spelling and grammar checking.
3600 void Document::createDOMWindow()
3603 ASSERT(!m_domWindow);
3605 m_domWindow = DOMWindow::create(this);
3607 ASSERT(m_domWindow->document() == this);
3608 ASSERT(m_domWindow->frame() == m_frame);
3611 void Document::takeDOMWindowFrom(Document* document)
3614 ASSERT(!m_domWindow);
3615 ASSERT(document->m_domWindow);
3616 // A valid DOMWindow is needed by CachedFrame for its documents.
3617 ASSERT(!document->inPageCache());
3619 m_domWindow = document->m_domWindow.release();
3620 m_domWindow->didSecureTransitionTo(this);
3622 ASSERT(m_domWindow->document() == this);
3623 ASSERT(m_domWindow->frame() == m_frame);
3626 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3630 m_domWindow->setAttributeEventListener(eventType, listener);
3633 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
3637 setWindowAttributeEventListener(eventType, JSLazyEventListener::createForDOMWindow(*m_frame, attributeName, attributeValue));
3640 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3644 return m_domWindow->getAttributeEventListener(eventType);
3647 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3649 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3652 m_domWindow->dispatchEvent(event, target);
3655 void Document::dispatchWindowLoadEvent()
3657 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3660 m_domWindow->dispatchLoadEvent();
3661 m_loadEventFinished = true;
3664 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3666 event->setTarget(m_domWindow.get());
3667 m_eventQueue.enqueueEvent(event);
3670 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
3672 event->setTarget(this);
3673 m_eventQueue.enqueueEvent(event);
3676 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
3678 RefPtr<Event> event = EventFactory::create(eventType);
3680 return event.release();
3682 ec = NOT_SUPPORTED_ERR;
3686 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3688 if (eventType == eventNames().DOMSubtreeModifiedEvent)
3689 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
3690 else if (eventType == eventNames().DOMNodeInsertedEvent)
3691 addListenerType(DOMNODEINSERTED_LISTENER);
3692 else if (eventType == eventNames().DOMNodeRemovedEvent)
3693 addListenerType(DOMNODEREMOVED_LISTENER);
3694 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
3695 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3696 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
3697 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3698 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
3699 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
3700 else if (eventType == eventNames().overflowchangedEvent)
3701 addListenerType(OVERFLOWCHANGED_LISTENER);
3702 else if (eventType == eventNames().webkitAnimationStartEvent)
3703 addListenerType(ANIMATIONSTART_LISTENER);
3704 else if (eventType == eventNames().webkitAnimationEndEvent)
3705 addListenerType(ANIMATIONEND_LISTENER);
3706 else if (eventType == eventNames().webkitAnimationIterationEvent)
3707 addListenerType(ANIMATIONITERATION_LISTENER);
3708 else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
3709 addListenerType(TRANSITIONEND_LISTENER);
3710 else if (eventType == eventNames().beforeloadEvent)
3711 addListenerType(BEFORELOAD_LISTENER);
3712 else if (eventType == eventNames().scrollEvent)
3713 addListenerType(SCROLL_LISTENER);
3716 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3721 HTMLFrameOwnerElement* Document::ownerElement() const
3725 return frame()->ownerElement();
3728 String Document::cookie(ExceptionCode& ec) const
3730 if (page() && !page()->settings().cookieEnabled())
3733 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3734 // INVALID_STATE_ERR exception on getting if the Document has no
3735 // browsing context.
3737 if (!securityOrigin()->canAccessCookies()) {
3742 URL cookieURL = this->cookieURL();
3743 if (cookieURL.isEmpty())
3746 return cookies(this, cookieURL);
3749 void Document::setCookie(const String& value, ExceptionCode& ec)
3751 if (page() && !page()->settings().cookieEnabled())
3754 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3755 // INVALID_STATE_ERR exception on setting if the Document has no
3756 // browsing context.
3758 if (!securityOrigin()->canAccessCookies()) {
3763 URL cookieURL = this->cookieURL();
3764 if (cookieURL.isEmpty())
3767 setCookies(this, cookieURL, value);
3770 String Document::referrer() const
3773 return frame()->loader().referrer();
3777 String Document::domain() const
3779 return securityOrigin()->domain();
3782 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
3784 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3789 // Both NS and IE specify that changing the domain is only allowed when
3790 // the new domain is a suffix of the old domain.
3792 // FIXME: We should add logging indicating why a domain was not allowed.
3794 // If the new domain is the same as the old domain, still call
3795 // securityOrigin()->setDomainForDOM. This will change the
3796 // security check behavior. For example, if a page loaded on port 8000
3797 // assigns its current domain using document.domain, the page will
3798 // allow other pages loaded on different ports in the same domain that
3799 // have also assigned to access this page.
3800 if (equalIgnoringCase(domain(), newDomain)) {
3801 securityOrigin()->setDomainFromDOM(newDomain);
3805 int oldLength = domain().length();
3806 int newLength = newDomain.length();
3807 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
3808 if (newLength >= oldLength) {
3813 String test = domain();
3814 // Check that it's a subdomain, not e.g. "ebkit.org"
3815 if (test[oldLength - newLength - 1] != '.') {
3820 // Now test is "webkit.org" from domain()
3821 // and we check that it's the same thing as newDomain
3822 test.remove(0, oldLength - newLength);
3823 if (test != newDomain) {
3828 securityOrigin()->setDomainFromDOM(newDomain);
3831 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3832 String Document::lastModified() const
3834 DateComponents date;
3835 bool foundDate = false;
3837 String httpLastModified;
3838 if (DocumentLoader* documentLoader = loader())
3839 httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3840 if (!httpLastModified.isEmpty()) {
3841 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3845 // FIXME: If this document came from the file system, the HTML5
3846 // specificiation tells us to read the last modification date from the file
3849 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3850 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3853 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
3855 if (!isValidNameStart(characters[0]))
3858 for (unsigned i = 1; i < length; ++i) {
3859 if (!isValidNamePart(characters[i]))
3866 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3871 U16_NEXT(characters, i, length, c)
3872 if (!isValidNameStart(c))
3875 while (i < length) {
3876 U16_NEXT(characters, i, length, c)
3877 if (!isValidNamePart(c))
3884 template<typename CharType>
3885 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
3887 CharType c = characters[0];
3888 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3891 for (unsigned i = 1; i < length; ++i) {
3893 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3900 bool Document::isValidName(const String& name)
3902 unsigned length = name.length();
3906 if (name.is8Bit()) {
3907 const LChar* characters = name.characters8();
3909 if (isValidNameASCII(characters, length))
3912 return isValidNameNonASCII(characters, length);
3915 const UChar* characters = name.characters16();
3917 if (isValidNameASCII(characters, length))
3920 return isValidNameNonASCII(characters, length);
3923 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3925 unsigned length = qualifiedName.length();
3928 ec = INVALID_CHARACTER_ERR;
3932 bool nameStart = true;
3933 bool sawColon = false;
3936 const UChar* s = qualifiedName.characters();
3937 for (unsigned i = 0; i < length;) {
3939 U16_NEXT(s, i, length, c)
3943 return false; // multiple colons: not allowed
3948 } else if (nameStart) {
3949 if (!isValidNameStart(c)) {
3950 ec = INVALID_CHARACTER_ERR;
3955 if (!isValidNamePart(c)) {
3956 ec = INVALID_CHARACTER_ERR;
3964 localName = qualifiedName;
3966 prefix = qualifiedName.substring(0, colonPos);
3967 if (prefix.isEmpty()) {
3971 localName = qualifiedName.substring(colonPos + 1);
3974 if (localName.isEmpty()) {
3982 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3984 m_decoder = decoder;
3987 URL Document::completeURL(const String& url, const URL& baseURLOverride) const
3989 // Always return a null URL when passed a null string.
3990 // FIXME: Should we change the URL constructor to have this behavior?
3991 // See also [CSS]StyleSheet::completeURL(const String&)
3994 const URL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
3996 return URL(baseURL, url);
3997 return URL(baseURL, url, m_decoder->encoding());
4000 URL Document::completeURL(const String& url) const
4002 return completeURL(url, m_baseURL);
4005 void Document::setInPageCache(bool flag)
4007 if (m_inPageCache == flag)
4010 m_inPageCache = flag;
4012 FrameView* v = view();
4013 Page* page = this->page();
4016 page->lockAllOverlayScrollbarsToHidden(flag);
4019 ASSERT(!m_savedRenderView);
4020 m_savedRenderView = renderView();
4022 // FIXME: There is some scrolling related work that needs to happen whenever a page goes into the
4023 // page cache and similar work that needs to occur when it comes out. This is where we do the work
4024 // that needs to happen when we enter, and the work that needs to happen when we exit is in
4025 // HistoryController::restoreScrollPositionAndViewState(). It can't be here because this function is
4026 // called too early on in the process of a page exiting the cache for that work to be possible in this
4027 // function. It would be nice if there was more symmetry here.
4028 // https://bugs.webkit.org/show_bug.cgi?id=98698
4029 v->cacheCurrentScrollPosition();
4030 if (page && m_frame->isMainFrame()) {
4031 v->resetScrollbarsAndClearContentsSize();
4032 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
4033 scrollingCoordinator->clearStateTree();
4035 v->resetScrollbars();
4037 m_styleRecalcTimer.stop();
4039 ASSERT(!renderView() || renderView() == m_savedRenderView);
4040 ASSERT(m_renderArena);
4041 setRenderView(m_savedRenderView);
4042 m_savedRenderView = 0;
4044 if (childNeedsStyleRecalc())
4045 scheduleStyleRecalc();
4049 void Document::documentWillBecomeInactive()
4051 #if USE(ACCELERATED_COMPOSITING)
4053 renderView()->setIsInWindow(false);
4057 void Document::documentWillSuspendForPageCache()
4059 documentWillBecomeInactive();
4061 HashSet<Element*>::iterator end = m_documentSuspensionCallbackElements.end();
4062 for (HashSet<Element*>::iterator i = m_documentSuspensionCallbackElements.begin(); i != end; ++i)
4063 (*i)->documentWillSuspendForPageCache();
4066 // Clear the update flag to be able to check if the viewport arguments update
4067 // is dispatched, after the document is restored from the page cache.
4068 m_didDispatchViewportPropertiesChanged = false;
4072 void Document::documentDidResumeFromPageCache()
4074 Vector<Element*> elements;
4075 copyToVector(m_documentSuspensionCallbackElements, elements);
4076 Vector<Element*>::iterator end = elements.end();
4077 for (Vector<Element*>::iterator i = elements.begin(); i != end; ++i)
4078 (*i)->documentDidResumeFromPageCache();
4080 #if USE(ACCELERATED_COMPOSITING)
4082 renderView()->setIsInWindow(true);
4086 page()->lockAllOverlayScrollbarsToHidden(false);
4089 m_frame->loader().client().dispatchDidBecomeFrameset(isFrameSet());
4092 void Document::registerForPageCacheSuspensionCallbacks(Element* e)
4094 m_documentSuspensionCallbackElements.add(e);
4097 void Document::unregisterForPageCacheSuspensionCallbacks(Element* e)
4099 m_documentSuspensionCallbackElements.remove(e);
4102 void Document::mediaVolumeDidChange()
4104 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
4105 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
4106 (*i)->mediaVolumeDidChange();
4109 void Document::registerForMediaVolumeCallbacks(Element* e)
4111 m_mediaVolumeCallbackElements.add(e);
4114 void Document::unregisterForMediaVolumeCallbacks(Element* e)
4116 m_mediaVolumeCallbackElements.remove(e);
4119 void Document::storageBlockingStateDidChange()
4121 if (Settings* settings = this->settings())
4122 securityOrigin()->setStorageBlockingPolicy(settings->storageBlockingPolicy());
4125 void Document::privateBrowsingStateDidChange()
4127 HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
4128 for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
4129 (*it)->privateBrowsingStateDidChange();
4132 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
4134 m_privateBrowsingStateChangedElements.add(e);
4137 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
4139 m_privateBrowsingStateChangedElements.remove(e);
4142 #if ENABLE(VIDEO_TRACK)
4143 void Document::registerForCaptionPreferencesChangedCallbacks(Element* e)
4146 page()->group().captionPreferences()->setInterestedInCaptionPreferenceChanges();
4148 m_captionPreferencesChangedElements.add(e);
4151 void Document::unregisterForCaptionPreferencesChangedCallbacks(Element* e)
4153 m_captionPreferencesChangedElements.remove(e);
4156 void Document::captionPreferencesChanged()
4158 HashSet<Element*>::iterator end = m_captionPreferencesChangedElements.end();
4159 for (HashSet<Element*>::iterator it = m_captionPreferencesChangedElements.begin(); it != end; ++it)
4160 (*it)->captionPreferencesChanged();
4164 void Document::setShouldCreateRenderers(bool f)
4166 m_createRenderers = f;
4169 bool Document::shouldCreateRenderers()
4171 return m_createRenderers;
4174 // Support for Javascript execCommand, and related methods
4176 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4178 Frame* frame = document->frame();
4179 if (!frame || frame->document() != document)
4180 return Editor::Command();
4182 document->updateStyleIfNeeded();
4184 return frame->editor().command(commandName,
4185 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4188 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4190 return command(this, commandName, userInterface).execute(value);
4193 bool Document::queryCommandEnabled(const String& commandName)
4195 return command(this, commandName).isEnabled();
4198 bool Document::queryCommandIndeterm(const String& commandName)
4200 return command(this, commandName).state() == MixedTriState;
4203 bool Document::queryCommandState(const String& commandName)
4205 return command(this, commandName).state() == TrueTriState;
4208 bool Document::queryCommandSupported(const String& commandName)
4210 return command(this, commandName).isSupported();
4213 String Document::queryCommandValue(const String& commandName)
4215 return command(this, commandName).value();
4218 URL Document::openSearchDescriptionURL()
4220 static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
4221 static const char* const openSearchRelation = "search";
4223 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4224 if (!frame() || frame()->tree().parent())
4227 // FIXME: Why do we need to wait for FrameStateComplete?
4228 if (frame()->loader().state() != FrameStateComplete)
4234 RefPtr<HTMLCollection> children = head()->children();
4235 for (unsigned i = 0; Node* child = children->item(i); i++) {
4236 if (!child->hasTagName(linkTag))
4238 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4239 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4241 if (linkElement->href().isEmpty())
4243 return linkElement->href();
4249 void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
4251 ASSERT(newCurrentScript);
4252 m_currentScriptStack.append(newCurrentScript);
4255 void Document::popCurrentScript()
4257 ASSERT(!m_currentScriptStack.isEmpty());
4258 m_currentScriptStack.removeLast();
4263 void Document::applyXSLTransform(ProcessingInstruction* pi)
4265 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4266 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
4267 String resultMIMEType;
4269 String resultEncoding;
4270 if (!processor->transformToString(*this, resultMIMEType, newSource, resultEncoding))
4272 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4273 Frame* ownerFrame = frame();
4274 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4275 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4278 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4280 m_transformSource = source;
4285 void Document::setDesignMode(InheritedBool value)
4287 m_designMode = value;
4288 for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
4289 frame->document()->scheduleForcedStyleRecalc();
4292 Document::InheritedBool Document::getDesignMode() const
4294 return m_designMode;
4297 bool Document::inDesignMode() const
4299 for (const Document* d = this; d; d = d->parentDocument()) {
4300 if (d->m_designMode != inherit)
4301 return d->m_designMode;
4306 Document* Document::parentDocument() const
4310 Frame* parent = m_frame->tree().parent();
4313 return parent->document();
4316 Document* Document::topDocument() const
4318 // FIXME: Why does this walk up owner elements instead using the frame tree as parentDocument does?
4319 // The frame tree even has a top() function.
4320 Document* document = const_cast<Document*>(this);
4321 while (Element* element = document->ownerElement())
4322 document = &element->document();
4326 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
4328 return createAttributeNS(String(), name, ec, true);
4331 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
4333 String prefix, localName;
4334 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))