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 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 "CSSParser.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CSSValueKeywords.h"
40 #include "CachedCSSStyleSheet.h"
41 #include "CachedResourceLoader.h"
43 #include "ChromeClient.h"
46 #include "ContentSecurityPolicy.h"
47 #include "ContextFeatures.h"
48 #include "CookieJar.h"
49 #include "DOMImplementation.h"
50 #include "DOMNamedFlowCollection.h"
51 #include "DOMSelection.h"
52 #include "DOMWindow.h"
53 #include "DateComponents.h"
54 #include "DocumentEventQueue.h"
55 #include "DocumentFragment.h"
56 #include "DocumentLoader.h"
57 #include "DocumentMarkerController.h"
58 #include "DocumentSharedObjectPool.h"
59 #include "DocumentStyleSheetCollection.h"
60 #include "DocumentType.h"
63 #include "ElementShadow.h"
64 #include "EntityReference.h"
66 #include "EventFactory.h"
67 #include "EventHandler.h"
68 #include "EventListener.h"
69 #include "EventNames.h"
70 #include "ExceptionCode.h"
71 #include "FlowThreadController.h"
72 #include "FocusController.h"
73 #include "FormController.h"
75 #include "FrameLoader.h"
76 #include "FrameLoaderClient.h"
77 #include "FrameSelection.h"
78 #include "FrameTree.h"
79 #include "FrameView.h"
80 #include "GeolocationController.h"
81 #include "HashChangeEvent.h"
82 #include "HistogramSupport.h"
84 #include "HTMLAllCollection.h"
85 #include "HTMLAnchorElement.h"
86 #include "HTMLBodyElement.h"
87 #include "HTMLCanvasElement.h"
88 #include "HTMLCollection.h"
89 #include "HTMLDocument.h"
90 #include "HTMLElementFactory.h"
91 #include "HTMLFrameOwnerElement.h"
92 #include "HTMLHeadElement.h"
93 #include "HTMLIFrameElement.h"
94 #include "HTMLLinkElement.h"
95 #include "HTMLMapElement.h"
96 #include "HTMLNameCollection.h"
97 #include "HTMLNames.h"
98 #include "HTMLParserIdioms.h"
99 #include "HTMLStyleElement.h"
100 #include "HTMLTitleElement.h"
101 #include "HTTPParsers.h"
102 #include "HitTestRequest.h"
103 #include "HitTestResult.h"
104 #include "ImageLoader.h"
105 #include "InspectorCounters.h"
106 #include "InspectorInstrumentation.h"
107 #include "Language.h"
109 #include "MainResourceLoader.h"
110 #include "MediaCanStartListener.h"
111 #include "MediaQueryList.h"
112 #include "MediaQueryMatcher.h"
113 #include "MouseEventWithHitTestResults.h"
114 #include "NameNodeList.h"
115 #include "NamedFlowCollection.h"
116 #include "NestingLevelIncrementer.h"
117 #include "NodeFilter.h"
118 #include "NodeIterator.h"
119 #include "NodeRareData.h"
120 #include "NodeTraversal.h"
121 #include "NodeWithIndex.h"
123 #include "PageGroup.h"
124 #include "PageTransitionEvent.h"
125 #include "PlatformKeyboardEvent.h"
126 #include "PlatformLocale.h"
127 #include "PluginDocument.h"
128 #include "PointerLockController.h"
129 #include "PopStateEvent.h"
130 #include "ProcessingInstruction.h"
131 #include "QualifiedName.h"
132 #include "RegisteredEventListener.h"
133 #include "RenderArena.h"
134 #include "RenderNamedFlowThread.h"
135 #include "RenderTextControl.h"
136 #include "RenderView.h"
137 #include "RenderWidget.h"
138 #include "RuntimeEnabledFeatures.h"
139 #include "SchemeRegistry.h"
140 #include "ScopedEventQueue.h"
141 #include "ScriptCallStack.h"
142 #include "ScriptController.h"
143 #include "ScriptElement.h"
144 #include "ScriptEventListener.h"
145 #include "ScriptRunner.h"
146 #include "ScrollingCoordinator.h"
147 #include "SecurityOrigin.h"
148 #include "SecurityPolicy.h"
149 #include "SegmentedString.h"
150 #include "SelectorQuery.h"
151 #include "Settings.h"
152 #include "ShadowRoot.h"
153 #include "StaticHashSetNodeList.h"
154 #include "StyleResolver.h"
155 #include "StyleSheetContents.h"
156 #include "StyleSheetList.h"
157 #include "TextResourceDecoder.h"
159 #include "TransformSource.h"
160 #include "TreeWalker.h"
161 #include "UserActionElementSet.h"
162 #include "UserContentURLPattern.h"
163 #include "VisitedLinkState.h"
164 #include "WebCoreMemoryInstrumentation.h"
165 #include "WebKitNamedFlow.h"
166 #include "XMLDocumentParser.h"
167 #include "XMLHttpRequest.h"
168 #include "XMLNSNames.h"
169 #include "XMLNames.h"
170 #include "XPathEvaluator.h"
171 #include "XPathExpression.h"
172 #include "XPathNSResolver.h"
173 #include "XPathResult.h"
174 #include "htmlediting.h"
175 #include <wtf/CurrentTime.h>
176 #include <wtf/HashFunctions.h>
177 #include <wtf/MainThread.h>
178 #include <wtf/MemoryInstrumentationHashCountedSet.h>
179 #include <wtf/MemoryInstrumentationHashMap.h>
180 #include <wtf/MemoryInstrumentationHashSet.h>
181 #include <wtf/MemoryInstrumentationVector.h>
182 #include <wtf/PassRefPtr.h>
183 #include <wtf/StdLibExtras.h>
184 #include <wtf/text/StringBuffer.h>
186 #if USE(ACCELERATED_COMPOSITING)
187 #include "RenderLayerCompositor.h"
190 #if ENABLE(SHARED_WORKERS)
191 #include "SharedWorkerRepository.h"
195 #include "XSLTProcessor.h"
199 #include "SVGDocumentExtensions.h"
200 #include "SVGElementFactory.h"
201 #include "SVGNames.h"
202 #include "SVGSVGElement.h"
203 #include "SVGStyleElement.h"
206 #if ENABLE(TOUCH_EVENTS)
207 #include "TouchList.h"
211 #include "MathMLElement.h"
212 #include "MathMLElementFactory.h"
213 #include "MathMLNames.h"
216 #if ENABLE(FULLSCREEN_API)
217 #include "RenderFullScreen.h"
220 #if ENABLE(REQUEST_ANIMATION_FRAME)
221 #include "RequestAnimationFrameCallback.h"
222 #include "ScriptedAnimationController.h"
225 #if ENABLE(MICRODATA)
226 #include "MicroDataItemList.h"
227 #include "NodeRareData.h"
230 #if ENABLE(LINK_PRERENDER)
231 #include "Prerenderer.h"
234 #if ENABLE(TEXT_AUTOSIZING)
235 #include "TextAutosizer.h"
239 #include "DOMSecurityPolicy.h"
244 using namespace Unicode;
248 using namespace HTMLNames;
250 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
252 static const unsigned cMaxWriteRecursionDepth = 21;
254 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
255 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
257 static const int cLayoutScheduleThreshold = 250;
259 // DOM Level 2 says (letters added):
261 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
262 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
263 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
264 // 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.
265 // 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.
266 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
267 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
268 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
269 // i) Characters ':' and '_' are allowed as name-start characters.
270 // j) Characters '-' and '.' are allowed as name characters.
272 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
274 static inline bool isValidNameStart(UChar32 c)
277 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
281 if (c == ':' || c == '_')
284 // rules (a) and (f) above
285 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
286 if (!(Unicode::category(c) & nameStartMask))
290 if (c >= 0xF900 && c < 0xFFFE)
294 DecompositionType decompType = decompositionType(c);
295 if (decompType == DecompositionFont || decompType == DecompositionCompat)
301 static inline bool isValidNamePart(UChar32 c)
303 // rules (a), (e), and (i) above
304 if (isValidNameStart(c))
307 // rules (g) and (h) above
308 if (c == 0x00B7 || c == 0x0387)
312 if (c == '-' || c == '.')
315 // rules (b) and (f) above
316 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
317 if (!(Unicode::category(c) & otherNamePartMask))
321 if (c >= 0xF900 && c < 0xFFFE)
325 DecompositionType decompType = decompositionType(c);
326 if (decompType == DecompositionFont || decompType == DecompositionCompat)
332 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
334 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
336 // If a Document has the address "about:blank"
337 // The origin of the Document is the origin it was assigned when its browsing context was created.
339 // Note: We generalize this to all "blank" URLs and invalid URLs because we
340 // treat all of these URLs as about:blank.
342 return url.isEmpty() || url.isBlankURL();
345 static Widget* widgetForNode(Node* focusedNode)
349 RenderObject* renderer = focusedNode->renderer();
350 if (!renderer || !renderer->isWidget())
352 return toRenderWidget(renderer)->widget();
355 static bool acceptsEditingFocus(Node* node)
358 ASSERT(node->rendererIsEditable());
360 Node* root = node->rootEditableElement();
361 Frame* frame = node->document()->frame();
365 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
368 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
370 // targetFrame can be 0 when we're trying to navigate a top-level frame
371 // that has a 0 opener.
375 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
376 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
377 Document* ancestorDocument = ancestorFrame->document();
378 // FIXME: Should be an ASSERT? Frames should alway have documents.
379 if (!ancestorDocument)
382 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
383 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
386 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
387 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
388 // something more general instead?
389 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
396 static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL, const char* reason)
398 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
400 // FIXME: should we print to the console of the document performing the navigation instead?
401 frame->document()->domWindow()->printErrorMessage(message);
404 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
406 uint64_t Document::s_globalTreeVersion = 0;
408 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
409 : ContainerNode(0, CreateDocument)
412 , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired)
413 , m_lastStyleResolverAccessTime(0)
414 , m_contextFeatures(ContextFeatures::defaultSwitch())
415 , m_compatibilityMode(NoQuirksMode)
416 , m_compatibilityModeLocked(false)
417 , m_domTreeVersion(++s_globalTreeVersion)
418 , m_mutationObserverTypes(0)
419 , m_styleSheetCollection(DocumentStyleSheetCollection::create(this))
420 , m_visitedLinkState(VisitedLinkState::create(this))
421 , m_readyState(Complete)
422 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
423 , m_pendingStyleRecalcShouldForce(false)
424 , m_frameElementsShouldIgnoreScrolling(false)
425 , m_containsValidityStyleRules(false)
426 , m_updateFocusAppearanceRestoresSelection(false)
427 , m_ignoreDestructiveWriteCount(0)
428 , m_titleSetExplicitly(false)
429 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
430 , m_loadEventFinished(false)
431 , m_startTime(currentTime())
432 , m_overMinimumLayoutThreshold(false)
433 , m_scriptRunner(ScriptRunner::create(this))
434 , m_xmlVersion("1.0")
435 , m_xmlStandalone(StandaloneUnspecified)
436 , m_hasXMLDeclaration(0)
438 , m_designMode(inherit)
439 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
440 , m_hasAnnotatedRegions(false)
441 , m_annotatedRegionsDirty(false)
443 , m_createRenderers(true)
444 , m_inPageCache(false)
445 , m_accessKeyMapValid(false)
446 , m_useSecureKeyboardEntryWhenActive(false)
449 , m_isViewSource(false)
450 , m_sawElementsInKnownNamespaces(false)
451 , m_isSrcdocDocument(false)
453 , m_eventQueue(DocumentEventQueue::create(this))
454 , m_weakFactory(this)
455 , m_idAttributeName(idAttr)
456 #if ENABLE(FULLSCREEN_API)
457 , m_areKeysEnabledInFullScreen(0)
458 , m_fullScreenRenderer(0)
459 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
460 , m_isAnimatingFullScreen(false)
462 , m_loadEventDelayCount(0)
463 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
464 , m_referrerPolicy(ReferrerPolicyDefault)
465 , m_directionSetOnDocumentElement(false)
466 , m_writingModeSetOnDocumentElement(false)
467 , m_writeRecursionIsTooDeep(false)
468 , m_writeRecursionDepth(0)
469 , m_wheelEventHandlerCount(0)
470 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
471 , m_scheduledTasksAreSuspended(false)
472 , m_visualUpdatesAllowed(true)
473 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
474 , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
476 , m_didDispatchViewportPropertiesChanged(false)
478 #if ENABLE(TEMPLATE_ELEMENT)
479 , m_templateDocumentHost(0)
485 m_paginatedForScreen = false;
487 m_ignoreAutofocus = false;
491 provideContextFeaturesToDocumentFrom(this, m_frame->page());
493 // We depend on the url getting immediately set in subframes, but we
494 // also depend on the url NOT getting immediately set in opened windows.
495 // See fast/dom/early-frame-url.html
496 // and fast/dom/location-new-window-no-crash.html, respectively.
497 // FIXME: Can/should we unify this behavior?
498 if ((frame && frame->ownerElement()) || !url.isEmpty())
501 m_markers = adoptPtr(new DocumentMarkerController);
504 m_cachedResourceLoader = m_frame->loader()->activeDocumentLoader()->cachedResourceLoader();
505 if (!m_cachedResourceLoader)
506 m_cachedResourceLoader = CachedResourceLoader::create(0);
507 m_cachedResourceLoader->setDocument(this);
509 #if ENABLE(LINK_PRERENDER)
510 m_prerenderer = Prerenderer::create(this);
512 #if ENABLE(TEXT_AUTOSIZING)
513 m_textAutosizer = TextAutosizer::create(this);
515 m_visuallyOrdered = false;
517 m_wellFormed = false;
519 m_textColor = Color::black;
521 m_inStyleRecalc = false;
522 m_closeAfterStyleRecalc = false;
524 m_gotoAnchorNeededAfterStylesheetsLoad = false;
526 m_didCalculateStyleResolver = false;
527 m_ignorePendingStylesheets = false;
528 m_needsNotifyRemoveAllPendingStylesheet = false;
529 m_hasNodesWithPlaceholderStyle = false;
530 m_pendingSheetLayout = NoLayoutWithPendingSheets;
535 resetVisitedLinkColor();
536 resetActiveLinkColor();
538 m_processingLoadEvent = false;
540 initSecurityContext();
543 static int docID = 0;
546 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
547 m_nodeListCounts[i] = 0;
549 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
552 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
554 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
555 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
556 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
557 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
558 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
559 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
562 #if ENABLE(FULLSCREEN_API)
563 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const HTMLFrameOwnerElement* owner)
568 if (!owner->hasAttribute(attribute))
570 } while ((owner = owner->document()->ownerElement()));
575 Document::~Document()
578 ASSERT(!m_inPageCache);
579 ASSERT(!m_savedRenderer);
580 ASSERT(m_ranges.isEmpty());
581 ASSERT(!m_styleRecalcTimer.isActive());
582 ASSERT(!m_parentTreeScope);
583 ASSERT(!m_guardRefCount);
585 #if ENABLE(TEMPLATE_ELEMENT)
586 if (m_templateDocument)
587 m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
590 #if ENABLE(TOUCH_EVENT_TRACKING)
591 if (Document* ownerDocument = this->ownerDocument())
592 ownerDocument->didRemoveEventTargetNode(this);
594 // FIXME: Should we reset m_domWindow when we detach from the Frame?
596 m_domWindow->resetUnlessSuspendedForPageCache();
598 m_scriptRunner.clear();
600 histogramMutationEventUsage(m_listenerTypes);
602 removeAllEventListeners();
604 // Currently we believe that Document can never outlive the parser.
605 // Although the Document may be replaced synchronously, DocumentParsers
606 // generally keep at least one reference to an Element which would in turn
607 // has a reference to the Document. If you hit this ASSERT, then that
608 // assumption is wrong. DocumentParser::detach() should ensure that even
609 // if the DocumentParser outlives the Document it won't cause badness.
610 ASSERT(!m_parser || m_parser->refCount() == 1);
613 m_renderArena.clear();
615 clearAXObjectCache();
619 if (m_styleSheetList)
620 m_styleSheetList->detachFromDocument();
622 m_styleSheetCollection.clear();
625 m_elemSheet->clearOwnerNode();
627 clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
629 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
630 // load the initial empty document and the SVGDocument with the same DocumentLoader).
631 if (m_cachedResourceLoader->document() == this)
632 m_cachedResourceLoader->setDocument(0);
633 m_cachedResourceLoader.clear();
635 // We must call clearRareData() here since a Document class inherits TreeScope
636 // as well as Node. See a comment on TreeScope.h for the reason.
640 ASSERT(!m_listsInvalidatedAtDocument.size());
642 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
643 ASSERT(!m_nodeListCounts[i]);
645 clearDocumentScope();
647 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
650 void Document::removedLastRef()
652 ASSERT(!m_deletionHasBegun);
653 if (m_guardRefCount) {
654 // If removing a child removes the last self-only ref, we don't
655 // want the scope to be destructed until after
656 // removeDetachedChildren returns, so we guard ourselves with an
657 // extra self-only ref.
660 // We must make sure not to be retaining any of our children through
661 // these extra pointers or we will create a reference cycle.
667 m_documentElement = 0;
668 m_contextFeatures = ContextFeatures::defaultSwitch();
669 m_userActionElements.documentDidRemoveLastRef();
670 #if ENABLE(FULLSCREEN_API)
671 m_fullScreenElement = 0;
672 m_fullScreenElementStack.clear();
677 // removeDetachedChildren() doesn't always unregister IDs,
678 // so tear down scope information upfront to avoid having stale references in the map.
679 destroyTreeScopeData();
680 removeDetachedChildren();
684 m_cssCanvasElements.clear();
686 #if ENABLE(REQUEST_ANIMATION_FRAME)
687 // FIXME: consider using ActiveDOMObject.
688 if (m_scriptedAnimationController)
689 m_scriptedAnimationController->clearDocumentPointer();
690 m_scriptedAnimationController.clear();
694 m_inRemovedLastRefFunction = false;
700 m_deletionHasBegun = true;
706 Element* Document::getElementById(const AtomicString& id) const
708 return TreeScope::getElementById(id);
711 Element* Document::getElementByAccessKey(const String& key)
715 if (!m_accessKeyMapValid) {
716 buildAccessKeyMap(this);
717 m_accessKeyMapValid = true;
719 return m_elementsByAccessKey.get(key.impl());
722 void Document::buildAccessKeyMap(TreeScope* scope)
725 Node* rootNode = scope->rootNode();
726 for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
727 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
728 if (!accessKey.isEmpty())
729 m_elementsByAccessKey.set(accessKey.impl(), element);
731 for (ShadowRoot* root = element->youngestShadowRoot(); root; root = root->olderShadowRoot())
732 buildAccessKeyMap(root);
736 void Document::invalidateAccessKeyMap()
738 m_accessKeyMapValid = false;
739 m_elementsByAccessKey.clear();
742 SelectorQueryCache* Document::selectorQueryCache()
744 if (!m_selectorQueryCache)
745 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
746 return m_selectorQueryCache.get();
749 MediaQueryMatcher* Document::mediaQueryMatcher()
751 if (!m_mediaQueryMatcher)
752 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
753 return m_mediaQueryMatcher.get();
756 void Document::setCompatibilityMode(CompatibilityMode mode)
758 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
760 bool wasInQuirksMode = inQuirksMode();
761 m_compatibilityMode = mode;
762 selectorQueryCache()->invalidate();
763 if (inQuirksMode() != wasInQuirksMode) {
764 // All user stylesheets have to reparse using the different mode.
765 m_styleSheetCollection->clearPageUserSheet();
766 m_styleSheetCollection->invalidateInjectedStyleSheetCache();
770 String Document::compatMode() const
772 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
775 void Document::resetLinkColor()
777 m_linkColor = Color(0, 0, 238);
780 void Document::resetVisitedLinkColor()
782 m_visitedLinkColor = Color(85, 26, 139);
785 void Document::resetActiveLinkColor()
787 m_activeLinkColor.setNamedColor("red");
790 void Document::setDocType(PassRefPtr<DocumentType> docType)
792 // This should never be called more than once.
793 ASSERT(!m_docType || !docType);
796 this->adoptIfNeeded(m_docType.get());
797 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
798 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
799 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
802 // Doctype affects the interpretation of the stylesheets.
803 clearStyleResolver();
806 DOMImplementation* Document::implementation()
808 if (!m_implementation)
809 m_implementation = DOMImplementation::create(this);
810 return m_implementation.get();
813 bool Document::hasManifest() const
815 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
818 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
820 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
822 Element* newDocumentElement = ElementTraversal::firstWithin(this);
823 if (newDocumentElement == m_documentElement)
825 m_documentElement = newDocumentElement;
826 // The root style used for media query matching depends on the document element.
827 clearStyleResolver();
830 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
832 if (!isValidName(name)) {
833 ec = INVALID_CHARACTER_ERR;
838 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
840 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
843 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
845 return DocumentFragment::create(document());
848 PassRefPtr<Text> Document::createTextNode(const String& data)
850 return Text::create(this, data);
853 PassRefPtr<Comment> Document::createComment(const String& data)
855 return Comment::create(this, data);
858 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
860 if (isHTMLDocument()) {
861 ec = NOT_SUPPORTED_ERR;
864 return CDATASection::create(this, data);
867 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
869 if (!isValidName(target)) {
870 ec = INVALID_CHARACTER_ERR;
873 if (isHTMLDocument()) {
874 ec = NOT_SUPPORTED_ERR;
877 return ProcessingInstruction::create(this, target, data);
880 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
882 if (!isValidName(name)) {
883 ec = INVALID_CHARACTER_ERR;
886 if (isHTMLDocument()) {
887 ec = NOT_SUPPORTED_ERR;
890 return EntityReference::create(this, name);
893 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
895 return Text::createEditingText(this, text);
898 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
900 return StylePropertySet::create()->ensureCSSStyleDeclaration();
903 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
908 ec = NOT_SUPPORTED_ERR;
912 switch (importedNode->nodeType()) {
914 return createTextNode(importedNode->nodeValue());
915 case CDATA_SECTION_NODE:
916 return createCDATASection(importedNode->nodeValue(), ec);
917 case ENTITY_REFERENCE_NODE:
918 return createEntityReference(importedNode->nodeName(), ec);
919 case PROCESSING_INSTRUCTION_NODE:
920 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
922 return createComment(importedNode->nodeValue());
924 Element* oldElement = static_cast<Element*>(importedNode);
925 // FIXME: The following check might be unnecessary. Is it possible that
926 // oldElement has mismatched prefix/namespace?
927 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
931 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
933 newElement->cloneDataFromElement(*oldElement);
936 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
937 RefPtr<Node> newChild = importNode(oldChild, true, ec);
940 newElement->appendChild(newChild.release(), ec);
946 return newElement.release();
949 return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
950 case DOCUMENT_FRAGMENT_NODE: {
951 if (importedNode->isShadowRoot()) {
952 // ShadowRoot nodes should not be explicitly importable.
953 // Either they are imported along with their host node, or created implicitly.
956 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
957 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
959 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
960 RefPtr<Node> newChild = importNode(oldChild, true, ec);
963 newFragment->appendChild(newChild.release(), ec);
969 return newFragment.release();
973 // 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.
974 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
976 case DOCUMENT_TYPE_NODE:
977 case XPATH_NAMESPACE_NODE:
980 ec = NOT_SUPPORTED_ERR;
985 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
988 ec = NOT_SUPPORTED_ERR;
992 if (source->isReadOnlyNode()) {
993 ec = NO_MODIFICATION_ALLOWED_ERR;
997 EventQueueScope scope;
999 switch (source->nodeType()) {
1003 case DOCUMENT_TYPE_NODE:
1004 case XPATH_NAMESPACE_NODE:
1005 ec = NOT_SUPPORTED_ERR;
1007 case ATTRIBUTE_NODE: {
1008 Attr* attr = static_cast<Attr*>(source.get());
1009 if (attr->ownerElement())
1010 attr->ownerElement()->removeAttributeNode(attr, ec);
1011 attr->setSpecified(true);
1015 if (source->isShadowRoot()) {
1016 // ShadowRoot cannot disconnect itself from the host node.
1017 ec = HIERARCHY_REQUEST_ERR;
1021 if (source->isFrameOwnerElement()) {
1022 HTMLFrameOwnerElement* frameOwnerElement = toFrameOwnerElement(source.get());
1023 if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
1024 ec = HIERARCHY_REQUEST_ERR;
1028 if (source->parentNode()) {
1029 source->parentNode()->removeChild(source.get(), ec);
1035 this->adoptIfNeeded(source.get());
1040 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1042 // These checks are from DOM Core Level 2, createElementNS
1043 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1044 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1046 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1049 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1050 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1051 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1052 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1058 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1060 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1061 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1062 // Note: The case of an "xmlns" qualified name with a namespace of
1063 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1064 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1066 return hasValidNamespaceForElements(qName);
1069 // FIXME: This should really be in a possible ElementFactory class
1070 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1074 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1075 if (qName.namespaceURI() == xhtmlNamespaceURI)
1076 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
1078 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1079 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
1082 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1083 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
1087 m_sawElementsInKnownNamespaces = true;
1089 e = Element::create(qName, document());
1091 // <image> uses imgTag so we need a special rule.
1092 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
1097 bool Document::regionBasedColumnsEnabled() const
1099 return settings() && settings()->regionBasedColumnsEnabled();
1102 bool Document::cssStickyPositionEnabled() const
1104 return settings() && settings()->cssStickyPositionEnabled();
1107 bool Document::cssRegionsEnabled() const
1109 return RuntimeEnabledFeatures::cssRegionsEnabled();
1112 bool Document::cssGridLayoutEnabled() const
1114 return settings() && settings()->cssGridLayoutEnabled();
1117 #if ENABLE(CSS_REGIONS)
1119 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1121 if (!cssRegionsEnabled() || !renderer())
1124 updateStyleIfNeeded();
1126 return namedFlows()->createCSSOMSnapshot();
1131 NamedFlowCollection* Document::namedFlows()
1134 m_namedFlows = NamedFlowCollection::create(this);
1136 return m_namedFlows.get();
1139 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1141 String prefix, localName;
1142 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1145 QualifiedName qName(prefix, localName, namespaceURI);
1146 if (!hasValidNamespaceForElements(qName)) {
1151 return createElement(qName, false);
1154 String Document::readyState() const
1156 DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1157 DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1158 DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1160 switch (m_readyState) {
1169 ASSERT_NOT_REACHED();
1173 void Document::setReadyState(ReadyState readyState)
1175 if (readyState == m_readyState)
1178 switch (readyState) {
1180 if (!m_documentTiming.domLoading)
1181 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1184 if (!m_documentTiming.domInteractive)
1185 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1188 if (!m_documentTiming.domComplete)
1189 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1193 m_readyState = readyState;
1194 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1196 if (settings() && settings()->suppressesIncrementalRendering())
1197 setVisualUpdatesAllowed(readyState);
1200 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1202 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1203 switch (readyState) {
1205 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1206 ASSERT(m_visualUpdatesAllowed);
1207 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1208 setVisualUpdatesAllowed(false);
1211 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1214 if (m_visualUpdatesSuppressionTimer.isActive()) {
1215 ASSERT(!m_visualUpdatesAllowed);
1216 m_visualUpdatesSuppressionTimer.stop();
1217 setVisualUpdatesAllowed(true);
1219 ASSERT(m_visualUpdatesAllowed);
1224 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1226 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1229 m_visualUpdatesAllowed = visualUpdatesAllowed;
1231 if (!visualUpdatesAllowed)
1234 FrameView* frameView = view();
1235 bool needsLayout = frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout());
1237 // There might be a layout pending, so make sure we don't update the screen with bogus data.
1238 // The layout will actually update the compositing layers and repaint if needed.
1242 #if USE(ACCELERATED_COMPOSITING)
1244 view()->updateCompositingLayersAfterLayout();
1248 renderer()->repaint();
1251 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1253 ASSERT(!m_visualUpdatesAllowed);
1254 setVisualUpdatesAllowed(true);
1257 String Document::encoding() const
1259 if (TextResourceDecoder* d = decoder())
1260 return d->encoding().domName();
1264 String Document::defaultCharset() const
1266 if (Settings* settings = this->settings())
1267 return settings->defaultTextEncodingName();
1271 void Document::setCharset(const String& charset)
1275 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1278 void Document::setContentLanguage(const String& language)
1280 if (m_contentLanguage == language)
1282 m_contentLanguage = language;
1284 // Recalculate style so language is used when selecting the initial font.
1285 styleResolverChanged(DeferRecalcStyle);
1288 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1290 if (!implementation()->hasFeature("XML", String())) {
1291 ec = NOT_SUPPORTED_ERR;
1295 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1296 ec = NOT_SUPPORTED_ERR;
1300 m_xmlVersion = version;
1303 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1305 if (!implementation()->hasFeature("XML", String())) {
1306 ec = NOT_SUPPORTED_ERR;
1310 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1313 void Document::setDocumentURI(const String& uri)
1315 // This property is read-only from JavaScript, but writable from Objective-C.
1316 m_documentURI = uri;
1320 KURL Document::baseURI() const
1325 void Document::setContent(const String& content)
1328 m_parser->append(content);
1332 String Document::suggestedMIMEType() const
1334 if (isXHTMLDocument())
1335 return "application/xhtml+xml";
1336 if (isSVGDocument())
1337 return "image/svg+xml";
1338 if (xmlStandalone())
1340 if (isHTMLDocument())
1343 if (DocumentLoader* documentLoader = loader())
1344 return documentLoader->responseMIMEType();
1348 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1349 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1350 // * making it receive the expading size of each direction separately,
1351 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1352 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
1354 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1357 Frame* frame = this->frame();
1360 FrameView* frameView = frame->view();
1364 float zoomFactor = frame->pageZoomFactor();
1365 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1367 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1369 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1371 type |= HitTestRequest::IgnoreClipping;
1372 else if (!frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1374 if (allowShadowContent)
1375 type |= HitTestRequest::AllowShadowContent;
1377 HitTestRequest request(type);
1379 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1380 // we special handle this case in order to return a valid NodeList.
1381 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1382 HitTestResult result(point);
1383 return handleZeroPadding(request, result);
1386 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1387 renderView()->hitTest(request, result);
1389 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1392 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1394 renderView()->hitTest(request, result);
1396 Node* node = result.innerNode();
1400 node = node->deprecatedShadowAncestorNode();
1401 ListHashSet<RefPtr<Node> > list;
1403 return StaticHashSetNodeList::adopt(list);
1406 Element* Document::elementFromPoint(int x, int y) const
1411 return TreeScope::elementFromPoint(x, y);
1414 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1418 LayoutPoint localPoint;
1419 Node* node = nodeFromPoint(this, x, y, &localPoint);
1423 Node* shadowAncestorNode = ancestorInThisScope(node);
1424 if (shadowAncestorNode != node) {
1425 unsigned offset = shadowAncestorNode->nodeIndex();
1426 ContainerNode* container = shadowAncestorNode->parentNode();
1427 return Range::create(this, container, offset, container, offset);
1430 RenderObject* renderer = node->renderer();
1433 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1434 if (visiblePosition.isNull())
1437 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1438 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1442 * Performs three operations:
1443 * 1. Convert control characters to spaces
1444 * 2. Trim leading and trailing spaces
1445 * 3. Collapse internal whitespace.
1447 template <typename CharacterType>
1448 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1450 const String& title = titleWithDirection.string();
1451 const CharacterType* characters = title.getCharacters<CharacterType>();
1452 unsigned length = title.length();
1455 StringBuffer<CharacterType> buffer(length);
1456 unsigned builderIndex = 0;
1458 // Skip leading spaces and leading characters that would convert to spaces
1459 for (i = 0; i < length; ++i) {
1460 CharacterType c = characters[i];
1461 if (!(c <= 0x20 || c == 0x7F))
1466 return StringWithDirection();
1468 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1469 bool previousCharWasWS = false;
1470 for (; i < length; ++i) {
1471 CharacterType c = characters[i];
1472 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1473 if (previousCharWasWS)
1475 buffer[builderIndex++] = ' ';
1476 previousCharWasWS = true;
1478 buffer[builderIndex++] = c;
1479 previousCharWasWS = false;
1483 // Strip trailing spaces
1484 while (builderIndex > 0) {
1486 if (buffer[builderIndex] != ' ')
1490 if (!builderIndex && buffer[builderIndex] == ' ')
1491 return StringWithDirection();
1493 buffer.shrink(builderIndex + 1);
1495 // Replace the backslashes with currency symbols if the encoding requires it.
1496 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1498 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1501 void Document::updateTitle(const StringWithDirection& title)
1503 if (m_rawTitle == title)
1508 if (m_rawTitle.string().isEmpty())
1509 m_title = StringWithDirection();
1511 if (m_rawTitle.string().is8Bit())
1512 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1514 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1516 if (Frame* f = frame())
1517 f->loader()->setTitle(m_title);
1520 void Document::setTitle(const String& title)
1522 // Title set by JavaScript -- overrides any title elements.
1523 m_titleSetExplicitly = true;
1524 if (!isHTMLDocument() && !isXHTMLDocument())
1526 else if (!m_titleElement) {
1527 if (HTMLElement* headElement = head()) {
1528 m_titleElement = createElement(titleTag, false);
1529 ExceptionCode ec = 0;
1530 headElement->appendChild(m_titleElement, ec);
1535 // The DOM API has no method of specifying direction, so assume LTR.
1536 updateTitle(StringWithDirection(title, LTR));
1538 if (m_titleElement) {
1539 ASSERT(m_titleElement->hasTagName(titleTag));
1540 if (m_titleElement->hasTagName(titleTag))
1541 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1545 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1547 if (titleElement != m_titleElement) {
1548 if (m_titleElement || m_titleSetExplicitly)
1549 // Only allow the first title element to change the title -- others have no effect.
1551 m_titleElement = titleElement;
1557 void Document::removeTitle(Element* titleElement)
1559 if (m_titleElement != titleElement)
1563 m_titleSetExplicitly = false;
1565 // Update title based on first title element in the head, if one exists.
1566 if (HTMLElement* headElement = head()) {
1567 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1568 if (e->hasTagName(titleTag)) {
1569 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1570 setTitleElement(titleElement->textWithDirection(), titleElement);
1575 if (!m_titleElement)
1576 updateTitle(StringWithDirection());
1579 #if ENABLE(PAGE_VISIBILITY_API)
1580 PageVisibilityState Document::visibilityState() const
1582 // The visibility of the document is inherited from the visibility of the
1583 // page. If there is no page associated with the document, we will assume
1584 // that the page is hidden, as specified by the spec:
1585 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1586 if (!m_frame || !m_frame->page())
1587 return PageVisibilityStateHidden;
1588 return m_frame->page()->visibilityState();
1591 String Document::webkitVisibilityState() const
1593 return pageVisibilityStateString(visibilityState());
1596 bool Document::webkitHidden() const
1598 return visibilityState() != PageVisibilityStateVisible;
1601 void Document::dispatchVisibilityStateChangeEvent()
1603 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1607 #if ENABLE(CSP_NEXT)
1608 DOMSecurityPolicy* Document::securityPolicy()
1610 if (!m_domSecurityPolicy)
1611 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1612 return m_domSecurityPolicy.get();
1616 String Document::nodeName() const
1621 Node::NodeType Document::nodeType() const
1623 return DOCUMENT_NODE;
1626 FormController* Document::formController()
1628 if (!m_formController)
1629 m_formController = FormController::create();
1630 return m_formController.get();
1633 Vector<String> Document::formElementsState() const
1635 if (!m_formController)
1636 return Vector<String>();
1637 return m_formController->formElementsState();
1640 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1642 if (!stateVector.size() && !m_formController)
1644 formController()->setStateForNewFormElements(stateVector);
1647 FrameView* Document::view() const
1649 return m_frame ? m_frame->view() : 0;
1652 Page* Document::page() const
1654 return m_frame ? m_frame->page() : 0;
1657 Settings* Document::settings() const
1659 return m_frame ? m_frame->settings() : 0;
1662 PassRefPtr<Range> Document::createRange()
1664 return Range::create(this);
1667 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1668 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1671 ec = NOT_SUPPORTED_ERR;
1674 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1677 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1678 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1681 ec = NOT_SUPPORTED_ERR;
1684 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1687 void Document::scheduleForcedStyleRecalc()
1689 m_pendingStyleRecalcShouldForce = true;
1690 scheduleStyleRecalc();
1693 void Document::scheduleStyleRecalc()
1695 if (shouldDisplaySeamlesslyWithParent()) {
1696 // When we're seamless, our parent document manages our style recalcs.
1697 ownerElement()->setNeedsStyleRecalc();
1698 ownerElement()->document()->scheduleStyleRecalc();
1702 if (m_styleRecalcTimer.isActive() || inPageCache())
1705 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1707 if (!documentsThatNeedStyleRecalc)
1708 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1709 documentsThatNeedStyleRecalc->add(this);
1711 // FIXME: Why on earth is this here? This is clearly misplaced.
1712 invalidateAccessKeyMap();
1714 m_styleRecalcTimer.startOneShot(0);
1716 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1719 void Document::unscheduleStyleRecalc()
1721 ASSERT(!childNeedsStyleRecalc());
1723 if (documentsThatNeedStyleRecalc)
1724 documentsThatNeedStyleRecalc->remove(this);
1726 m_styleRecalcTimer.stop();
1727 m_pendingStyleRecalcShouldForce = false;
1730 bool Document::hasPendingStyleRecalc() const
1732 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1735 bool Document::hasPendingForcedStyleRecalc() const
1737 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1740 void Document::styleRecalcTimerFired(Timer<Document>*)
1742 updateStyleIfNeeded();
1745 bool Document::childNeedsAndNotInStyleRecalc()
1747 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1750 void Document::recalcStyle(StyleChange change)
1752 // we should not enter style recalc while painting
1753 ASSERT(!view() || !view()->isPainting());
1754 if (view() && view()->isPainting())
1757 if (m_inStyleRecalc)
1758 return; // Guard against re-entrancy. -dwh
1760 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1761 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1762 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1763 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1764 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1765 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1767 if (m_styleSheetCollection->needsUpdateActiveStylesheetsOnStyleRecalc())
1768 m_styleSheetCollection->updateActiveStyleSheets(DocumentStyleSheetCollection::FullUpdate);
1770 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1772 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1773 m_styleSheetCollection->setUsesRemUnit(true);
1775 m_inStyleRecalc = true;
1777 PostAttachCallbackDisabler disabler(this);
1778 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1780 RefPtr<FrameView> frameView = view();
1782 frameView->pauseScheduledEvents();
1783 frameView->beginDeferredRepaints();
1786 ASSERT(!renderer() || renderArena());
1787 if (!renderer() || !renderArena())
1790 if (m_pendingStyleRecalcShouldForce)
1793 // Recalculating the root style (on the document) is not needed in the common case.
1794 if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
1795 // style selector may set this again during recalc
1796 m_hasNodesWithPlaceholderStyle = false;
1798 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
1799 StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
1801 renderer()->setStyle(documentStyle.release());
1804 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1805 if (!n->isElementNode())
1807 Element* element = static_cast<Element*>(n);
1808 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1809 element->recalcStyle(change);
1812 #if USE(ACCELERATED_COMPOSITING)
1814 view()->updateCompositingLayersAfterStyleChange();
1818 clearNeedsStyleRecalc();
1819 clearChildNeedsStyleRecalc();
1820 unscheduleStyleRecalc();
1822 m_inStyleRecalc = false;
1824 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1825 if (m_styleResolver)
1826 m_styleSheetCollection->resetCSSFeatureFlags();
1829 frameView->resumeScheduledEvents();
1830 frameView->endDeferredRepaints();
1834 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1835 if (m_closeAfterStyleRecalc) {
1836 m_closeAfterStyleRecalc = false;
1840 InspectorInstrumentation::didRecalculateStyle(cookie);
1843 void Document::updateStyleIfNeeded()
1845 ASSERT(isMainThread());
1846 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1848 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1851 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
1852 recalcStyle(NoChange);
1855 void Document::updateStyleForAllDocuments()
1857 ASSERT(isMainThread());
1858 if (!documentsThatNeedStyleRecalc)
1861 while (documentsThatNeedStyleRecalc->size()) {
1862 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1863 Document* doc = *it;
1864 documentsThatNeedStyleRecalc->remove(doc);
1865 doc->updateStyleIfNeeded();
1869 void Document::updateLayout()
1871 ASSERT(isMainThread());
1873 FrameView* frameView = view();
1874 if (frameView && frameView->isInLayout()) {
1875 // View layout should not be re-entrant.
1876 ASSERT_NOT_REACHED();
1880 if (Element* oe = ownerElement())
1881 oe->document()->updateLayout();
1883 updateStyleIfNeeded();
1885 StackStats::LayoutCheckPoint layoutCheckPoint;
1887 // Only do a layout if changes have occurred that make it necessary.
1888 if (frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout()))
1889 frameView->layout();
1892 // FIXME: This is a bad idea and needs to be removed eventually.
1893 // Other browsers load stylesheets before they continue parsing the web page.
1894 // Since we don't, we can run JavaScript code that needs answers before the
1895 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1896 // lets us get reasonable answers. The long term solution to this problem is
1897 // to instead suspend JavaScript execution.
1898 void Document::updateLayoutIgnorePendingStylesheets()
1900 bool oldIgnore = m_ignorePendingStylesheets;
1902 if (!haveStylesheetsLoaded()) {
1903 m_ignorePendingStylesheets = true;
1904 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1905 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1906 // with accurate style information. (Our suppression involves blanking the whole page at the
1907 // moment. If it were more refined, we might be able to do something better.)
1908 // It's worth noting though that this entire method is a hack, since what we really want to do is
1909 // suspend JS instead of doing a layout with inaccurate information.
1910 HTMLElement* bodyElement = body();
1911 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1912 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1913 styleResolverChanged(RecalcStyleImmediately);
1914 } else if (m_hasNodesWithPlaceholderStyle)
1915 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1916 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1917 // but here we need up-to-date style immediately.
1923 m_ignorePendingStylesheets = oldIgnore;
1926 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1928 ASSERT_ARG(element, element->document() == this);
1930 bool oldIgnore = m_ignorePendingStylesheets;
1931 m_ignorePendingStylesheets = true;
1932 RefPtr<RenderStyle> style = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1933 m_ignorePendingStylesheets = oldIgnore;
1934 return style.release();
1937 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1939 RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
1940 return style.release();
1943 bool Document::isPageBoxVisible(int pageIndex)
1945 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1946 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1949 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1951 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1952 RenderView* view = renderView();
1954 int width = pageSize.width();
1955 int height = pageSize.height();
1956 switch (style->pageSizeType()) {
1957 case PAGE_SIZE_AUTO:
1959 case PAGE_SIZE_AUTO_LANDSCAPE:
1961 std::swap(width, height);
1963 case PAGE_SIZE_AUTO_PORTRAIT:
1965 std::swap(width, height);
1967 case PAGE_SIZE_RESOLVED: {
1968 LengthSize size = style->pageSize();
1969 ASSERT(size.width().isFixed());
1970 ASSERT(size.height().isFixed());
1971 width = valueForLength(size.width(), 0, view);
1972 height = valueForLength(size.height(), 0, view);
1976 ASSERT_NOT_REACHED();
1978 pageSize = IntSize(width, height);
1980 // The percentage is calculated with respect to the width even for margin top and bottom.
1981 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1982 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
1983 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
1984 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
1985 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
1988 void Document::setIsViewSource(bool isViewSource)
1990 m_isViewSource = isViewSource;
1991 if (!m_isViewSource)
1994 setSecurityOrigin(SecurityOrigin::createUnique());
1995 didUpdateSecurityOrigin();
1998 void Document::createStyleResolver()
2000 bool matchAuthorAndUserStyles = true;
2001 if (Settings* docSettings = settings())
2002 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
2003 m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
2004 m_styleSheetCollection->combineCSSFeatureFlags();
2007 void Document::clearStyleResolver()
2009 m_styleResolver.clear();
2012 void Document::attach()
2014 ASSERT(!attached());
2015 ASSERT(!m_inPageCache);
2016 ASSERT(!m_axObjectCache || this != topDocument());
2019 m_renderArena = adoptPtr(new RenderArena);
2021 // Create the rendering tree
2022 setRenderer(new (m_renderArena.get()) RenderView(this));
2023 #if USE(ACCELERATED_COMPOSITING)
2024 renderView()->didMoveOnscreen();
2029 RenderObject* render = renderer();
2032 ContainerNode::attach();
2034 setRenderer(render);
2037 void Document::detach()
2040 ASSERT(!m_inPageCache);
2042 #if ENABLE(POINTER_LOCK)
2044 page()->pointerLockController()->documentDetached(this);
2047 if (this == topDocument())
2048 clearAXObjectCache();
2050 stopActiveDOMObjects();
2051 m_eventQueue->close();
2052 #if ENABLE(FULLSCREEN_API)
2053 m_fullScreenChangeEventTargetQueue.clear();
2054 m_fullScreenErrorEventTargetQueue.clear();
2057 #if ENABLE(REQUEST_ANIMATION_FRAME)
2058 // FIXME: consider using ActiveDOMObject.
2059 if (m_scriptedAnimationController)
2060 m_scriptedAnimationController->clearDocumentPointer();
2061 m_scriptedAnimationController.clear();
2064 RenderObject* render = renderer();
2066 documentWillBecomeInactive();
2068 #if ENABLE(SHARED_WORKERS)
2069 SharedWorkerRepository::documentDetached(this);
2073 FrameView* view = m_frame->view();
2075 view->detachCustomScrollbars();
2079 // indicate destruction mode, i.e. attached() but renderer == 0
2082 #if ENABLE(FULLSCREEN_API)
2083 if (m_fullScreenRenderer)
2084 setFullScreenRenderer(0);
2089 m_activeElement = 0;
2091 ContainerNode::detach();
2093 unscheduleStyleRecalc();
2098 #if ENABLE(TOUCH_EVENTS)
2099 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2100 parentDocument()->didRemoveEventTargetNode(this);
2103 // This is required, as our Frame might delete itself as soon as it detaches
2104 // us. However, this violates Node::detach() semantics, as it's never
2105 // possible to re-attach. Eventually Document::detach() should be renamed,
2106 // or this setting of the frame to 0 could be made explicit in each of the
2107 // callers of Document::detach().
2109 m_renderArena.clear();
2111 if (m_mediaQueryMatcher)
2112 m_mediaQueryMatcher->documentDestroyed();
2115 void Document::prepareForDestruction()
2117 disconnectDescendantFrames();
2118 if (DOMWindow* window = this->domWindow())
2119 window->willDetachDocumentFromFrame();
2123 void Document::removeAllEventListeners()
2125 EventTarget::removeAllEventListeners();
2127 if (DOMWindow* domWindow = this->domWindow())
2128 domWindow->removeAllEventListeners();
2129 for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
2130 node->removeAllEventListeners();
2133 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2135 ScriptExecutionContext::suspendActiveDOMObjects(why);
2138 void Document::resumeActiveDOMObjects()
2140 ScriptExecutionContext::resumeActiveDOMObjects();
2143 void Document::clearAXObjectCache()
2145 // Clear the cache member variable before calling delete because attempts
2146 // are made to access it during destruction.
2147 topDocument()->m_axObjectCache.release();
2150 bool Document::axObjectCacheExists() const
2152 return topDocument()->m_axObjectCache;
2155 AXObjectCache* Document::axObjectCache() const
2157 // The only document that actually has a AXObjectCache is the top-level
2158 // document. This is because we need to be able to get from any WebCoreAXObject
2159 // to any other WebCoreAXObject on the same page. Using a single cache allows
2160 // lookups across nested webareas (i.e. multiple documents).
2161 Document* topDocument = this->topDocument();
2162 ASSERT(topDocument == this || !m_axObjectCache);
2163 if (!topDocument->m_axObjectCache)
2164 topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2165 return topDocument->m_axObjectCache.get();
2168 void Document::setVisuallyOrdered()
2170 m_visuallyOrdered = true;
2172 renderer()->style()->setRTLOrdering(VisualOrder);
2175 PassRefPtr<DocumentParser> Document::createParser()
2177 // FIXME: this should probably pass the frame instead
2178 return XMLDocumentParser::create(this, view());
2181 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2183 return parser() ? parser()->asScriptableDocumentParser() : 0;
2186 void Document::open(Document* ownerDocument)
2188 if (ownerDocument) {
2189 setURL(ownerDocument->url());
2190 m_cookieURL = ownerDocument->cookieURL();
2191 setSecurityOrigin(ownerDocument->securityOrigin());
2195 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2196 if (parser->isParsing()) {
2197 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2198 if (parser->isExecutingScript())
2201 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2206 if (m_frame->loader()->state() == FrameStateProvisional)
2207 m_frame->loader()->stopAllLoaders();
2210 removeAllEventListeners();
2212 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2213 parser->setWasCreatedByScript(true);
2215 if (DOMWindow* domWindow = this->domWindow())
2216 domWindow->removeAllEventListeners();
2219 m_frame->loader()->didExplicitOpen();
2222 void Document::detachParser()
2230 void Document::cancelParsing()
2235 // We have to clear the parser to avoid possibly triggering
2236 // the onload handler when closing as a side effect of a cancel-style
2237 // change, such as opening a new document or closing the window while
2243 void Document::implicitOpen()
2249 setCompatibilityMode(NoQuirksMode);
2251 // Documents rendered seamlessly should start out requiring a stylesheet
2252 // collection update in order to ensure they inherit all the relevant data
2253 // from their parent.
2254 if (shouldDisplaySeamlesslyWithParent())
2255 styleResolverChanged(DeferRecalcStyle);
2257 m_parser = createParser();
2259 setReadyState(Loading);
2262 HTMLElement* Document::body() const
2264 Node* de = documentElement();
2268 // try to prefer a FRAMESET element over BODY
2270 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2271 if (i->hasTagName(framesetTag))
2272 return toHTMLElement(i);
2274 if (i->hasTagName(bodyTag) && !body)
2277 return toHTMLElement(body);
2280 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2282 RefPtr<HTMLElement> newBody = prpNewBody;
2284 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2285 ec = HIERARCHY_REQUEST_ERR;
2289 if (newBody->document() && newBody->document() != this) {
2291 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2295 newBody = toHTMLElement(node.get());
2298 HTMLElement* b = body();
2300 documentElement()->appendChild(newBody.release(), ec);
2302 documentElement()->replaceChild(newBody.release(), b, ec);
2305 HTMLHeadElement* Document::head()
2307 Node* de = documentElement();
2311 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2312 if (e->hasTagName(headTag))
2313 return static_cast<HTMLHeadElement*>(e);
2318 void Document::close()
2320 // FIXME: We should follow the specification more closely:
2321 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2323 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2329 void Document::explicitClose()
2331 if (RefPtr<DocumentParser> parser = m_parser)
2335 // Because we have no frame, we don't know if all loading has completed,
2336 // so we just call implicitClose() immediately. FIXME: This might fire
2337 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2342 m_frame->loader()->checkCompleted();
2345 void Document::implicitClose()
2347 // 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.
2348 if (m_inStyleRecalc) {
2349 m_closeAfterStyleRecalc = true;
2353 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2354 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2359 // Call to dispatchWindowLoadEvent can blow us from underneath.
2360 RefPtr<Document> protect(this);
2362 m_processingLoadEvent = true;
2364 ScriptableDocumentParser* parser = scriptableDocumentParser();
2365 m_wellFormed = parser && parser->wellFormed();
2367 // We have to clear the parser, in case someone document.write()s from the
2368 // onLoad event handler, as in Radar 3206524.
2371 // Parser should have picked up all preloads by now
2372 m_cachedResourceLoader->clearPreloads();
2374 // FIXME: We kick off the icon loader when the Document is done parsing.
2375 // There are earlier opportunities we could start it:
2376 // -When the <head> finishes parsing
2377 // -When any new HTMLLinkElement is inserted into the document
2378 // But those add a dynamic component to the favicon that has UI
2379 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2382 f->loader()->icon()->startLoader();
2383 f->animation()->resumeAnimationsForDocument(this);
2386 ImageLoader::dispatchPendingBeforeLoadEvents();
2387 ImageLoader::dispatchPendingLoadEvents();
2388 ImageLoader::dispatchPendingErrorEvents();
2390 HTMLLinkElement::dispatchPendingLoadEvents();
2391 HTMLStyleElement::dispatchPendingLoadEvents();
2394 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2395 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2396 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2397 if (svgExtensions())
2398 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2401 dispatchWindowLoadEvent();
2402 enqueuePageshowEvent(PageshowEventNotPersisted);
2403 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2406 f->loader()->handledOnloadEvents();
2407 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2408 if (!ownerElement())
2409 printf("onload fired at %d\n", elapsedTime());
2412 // An event handler may have removed the frame
2414 m_processingLoadEvent = false;
2418 // Make sure both the initial layout and reflow happen after the onload
2419 // fires. This will improve onload scores, and other browsers do it.
2420 // If they wanna cheat, we can too. -dwh
2422 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2423 // Just bail out. Before or during the onload we were shifted to another page.
2424 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2425 m_processingLoadEvent = false;
2426 view()->unscheduleRelayout();
2430 frame()->loader()->checkCallImplicitClose();
2431 RenderObject* renderObject = renderer();
2433 // We used to force a synchronous display and flush here. This really isn't
2434 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2435 // (if your platform is syncing flushes and limiting them to 60fps).
2436 m_overMinimumLayoutThreshold = true;
2437 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2438 updateStyleIfNeeded();
2440 // Always do a layout after loading if needed.
2441 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2445 m_processingLoadEvent = false;
2447 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2448 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2449 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2450 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2451 // exists in the cache (we ignore the return value because we don't need it here). This is
2452 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2453 axObjectCache()->getOrCreate(renderObject);
2454 if (this == topDocument())
2455 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2457 // AXLoadComplete can only be posted on the top document, so if it's a document
2458 // in an iframe that just finished loading, post AXLayoutComplete instead.
2459 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
2465 if (svgExtensions())
2466 accessSVGExtensions()->startAnimations();
2470 void Document::setParsing(bool b)
2474 if (m_bParsing && !m_sharedObjectPool)
2475 m_sharedObjectPool = DocumentSharedObjectPool::create();
2477 if (!m_bParsing && view())
2478 view()->scheduleRelayout();
2480 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2481 if (!ownerElement() && !m_bParsing)
2482 printf("Parsing finished at %d\n", elapsedTime());
2486 bool Document::shouldScheduleLayout()
2488 // This function will only be called when FrameView thinks a layout is needed.
2489 // This enforces a couple extra rules.
2491 // (a) Only schedule a layout once the stylesheets are loaded.
2492 // (b) Only schedule layout once we have a body element.
2494 return (haveStylesheetsLoaded() && body())
2495 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2498 bool Document::isLayoutTimerActive()
2500 return view() && view()->layoutPending() && !minimumLayoutDelay();
2503 int Document::minimumLayoutDelay()
2505 if (m_overMinimumLayoutThreshold)
2508 int elapsed = elapsedTime();
2509 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2511 // We'll want to schedule the timer to fire at the minimum layout threshold.
2512 return max(0, cLayoutScheduleThreshold - elapsed);
2515 int Document::elapsedTime() const
2517 return static_cast<int>((currentTime() - m_startTime) * 1000);
2520 void Document::write(const SegmentedString& text, Document* ownerDocument)
2522 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2524 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2525 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2527 if (m_writeRecursionIsTooDeep)
2530 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2531 if (!ownerElement())
2532 printf("Beginning a document.write at %d\n", elapsedTime());
2535 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2536 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2539 if (!hasInsertionPoint)
2540 open(ownerDocument);
2543 m_parser->insert(text);
2545 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2546 if (!ownerElement())
2547 printf("Ending a document.write at %d\n", elapsedTime());
2551 void Document::write(const String& text, Document* ownerDocument)
2553 write(SegmentedString(text), ownerDocument);
2556 void Document::writeln(const String& text, Document* ownerDocument)
2558 write(text, ownerDocument);
2559 write("\n", ownerDocument);
2562 const KURL& Document::virtualURL() const
2567 KURL Document::virtualCompleteURL(const String& url) const
2569 return completeURL(url);
2572 double Document::minimumTimerInterval() const
2576 return ScriptExecutionContext::minimumTimerInterval();
2577 return p->settings()->minDOMTimerInterval();
2580 double Document::timerAlignmentInterval() const
2584 return ScriptExecutionContext::timerAlignmentInterval();
2585 return p->settings()->domTimerAlignmentInterval();
2588 EventTarget* Document::errorEventTarget()
2593 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
2595 addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
2598 void Document::setURL(const KURL& url)
2600 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2601 if (newURL == m_url)
2605 m_documentURI = m_url.string();
2607 contextFeatures()->urlDidChange(this);
2610 void Document::updateBaseURL()
2612 KURL oldBaseURL = m_baseURL;
2613 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2614 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2615 // from the Document interface otherwise.
2616 if (!m_baseElementURL.isEmpty())
2617 m_baseURL = m_baseElementURL;
2618 else if (!m_baseURLOverride.isEmpty())
2619 m_baseURL = m_baseURLOverride;
2621 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2622 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2623 // and DOM 3 Core does not specify how it should be resolved.
2624 m_baseURL = KURL(KURL(), documentURI());
2626 selectorQueryCache()->invalidate();
2628 if (!m_baseURL.isValid())
2632 // Element sheet is silly. It never contains anything.
2633 ASSERT(!m_elemSheet->contents()->ruleCount());
2634 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2635 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2636 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2637 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2640 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2641 // Base URL change changes any relative visited links.
2642 // 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.
2643 for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element)) {
2644 if (element->hasTagName(aTag))
2645 static_cast<HTMLAnchorElement*>(element)->invalidateCachedVisitedLinkHash();
2650 void Document::setBaseURLOverride(const KURL& url)
2652 m_baseURLOverride = url;
2656 void Document::processBaseElement()
2658 // Find the first href attribute in a base element and the first target attribute in a base element.
2659 const AtomicString* href = 0;
2660 const AtomicString* target = 0;
2661 for (Element* element = ElementTraversal::firstWithin(this); element && (!href || !target); element = ElementTraversal::next(element)) {
2662 if (element->hasTagName(baseTag)) {
2664 const AtomicString& value = element->fastGetAttribute(hrefAttr);
2665 if (!value.isNull())
2669 const AtomicString& value = element->fastGetAttribute(targetAttr);
2670 if (!value.isNull())
2676 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2677 KURL baseElementURL;
2679 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2680 if (!strippedHref.isEmpty())
2681 baseElementURL = KURL(url(), strippedHref);
2683 if (m_baseElementURL != baseElementURL) {
2684 m_baseElementURL = baseElementURL;
2688 m_baseTarget = target ? *target : nullAtom;
2691 String Document::userAgent(const KURL& url) const
2693 return frame() ? frame()->loader()->userAgent(url) : String();
2696 void Document::disableEval(const String& errorMessage)
2701 frame()->script()->disableEval(errorMessage);
2704 bool Document::canNavigate(Frame* targetFrame)
2709 // FIXME: We shouldn't call this function without a target frame, but
2710 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2711 // returning true when supplied with a 0 targetFrame.
2715 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2716 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2719 if (isSandboxed(SandboxNavigation)) {
2720 if (targetFrame->tree()->isDescendantOf(m_frame))
2723 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2724 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2725 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2727 printNavigationErrorMessage(targetFrame, url(), reason);
2731 // This is the normal case. A document can navigate its decendant frames,
2732 // or, more generally, a document can navigate a frame if the document is
2733 // in the same origin as any of that frame's ancestors (in the frame
2736 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2737 // historical information about this security check.
2738 if (canAccessAncestor(securityOrigin(), targetFrame))
2741 // Top-level frames are easier to navigate than other frames because they
2742 // display their URLs in the address bar (in most browsers). However, there
2743 // are still some restrictions on navigation to avoid nuisance attacks.
2744 // Specifically, a document can navigate a top-level frame if that frame
2745 // opened the document or if the document is the same-origin with any of
2746 // the top-level frame's opener's ancestors (in the frame hierarchy).
2748 // In both of these cases, the document performing the navigation is in
2749 // some way related to the frame being navigate (e.g., by the "opener"
2750 // and/or "parent" relation). Requiring some sort of relation prevents a
2751 // document from navigating arbitrary, unrelated top-level frames.
2752 if (!targetFrame->tree()->parent()) {
2753 if (targetFrame == m_frame->loader()->opener())
2756 if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
2760 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2764 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2766 Frame* currentFrame = m_frame;
2767 Frame* ancestorFrame = currentFrame->tree()->parent();
2769 while (ancestorFrame) {
2770 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2771 return currentFrame;
2772 currentFrame = ancestorFrame;
2773 ancestorFrame = ancestorFrame->tree()->parent();
2779 void Document::seamlessParentUpdatedStylesheets()
2781 styleResolverChanged(RecalcStyleImmediately);
2784 void Document::didRemoveAllPendingStylesheet()
2786 m_needsNotifyRemoveAllPendingStylesheet = false;
2788 styleResolverChanged(RecalcStyleIfNeeded);
2790 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2791 parser->executeScriptsWaitingForStylesheets();
2793 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2794 view()->scrollToFragment(m_url);
2797 CSSStyleSheet* Document::elementSheet()
2800 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2801 return m_elemSheet.get();
2804 int Document::nodeAbsIndex(Node *node)
2806 ASSERT(node->document() == this);
2809 for (Node* n = node; n && n != this; n = NodeTraversal::previous(n))
2814 Node* Document::nodeWithAbsIndex(int absIndex)
2817 for (int i = 0; n && (i < absIndex); i++)
2818 n = NodeTraversal::next(n);
2822 void Document::processHttpEquiv(const String& equiv, const String& content)
2824 ASSERT(!equiv.isNull() && !content.isNull());
2826 Frame* frame = this->frame();
2828 if (equalIgnoringCase(equiv, "default-style")) {
2829 // The preferred style set has been overridden as per section
2830 // 14.3.2 of the HTML4.0 specification. We need to update the
2831 // sheet used variable and then update our style selector.
2832 // For more info, see the test at:
2833 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2835 m_styleSheetCollection->setSelectedStylesheetSetName(content);
2836 m_styleSheetCollection->setPreferredStylesheetSetName(content);
2837 styleResolverChanged(DeferRecalcStyle);
2838 } else if (equalIgnoringCase(equiv, "refresh")) {
2841 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2843 url = m_url.string();
2845 url = completeURL(url).string();
2846 frame->navigationScheduler()->scheduleRedirect(delay, url);
2848 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2849 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2850 if (isHTMLDocument()) {
2851 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
2852 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
2854 } else if (equalIgnoringCase(equiv, "content-language"))
2855 setContentLanguage(content);
2856 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2857 parseDNSPrefetchControlHeader(content);
2858 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2860 FrameLoader* frameLoader = frame->loader();
2861 unsigned long requestIdentifier = 0;
2862 if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader())
2863 requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier();
2864 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
2865 String message = "Refused to display '" + url().string() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
2866 frameLoader->stopAllLoaders();
2867 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
2868 addConsoleMessage(JSMessageSource, ErrorMessageLevel, message, requestIdentifier);
2871 } else if (equalIgnoringCase(equiv, "content-security-policy"))
2872 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforceStableDirectives);
2873 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2874 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportStableDirectives);
2875 else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2876 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforceAllDirectives);
2877 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2878 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportAllDirectives);
2881 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2882 static bool isSeparator(UChar c)
2884 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2887 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2889 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2890 int keyBegin, keyEnd;
2891 int valueBegin, valueEnd;
2894 int length = features.length();
2895 String buffer = features.lower();
2896 while (i < length) {
2897 // skip to first non-separator, but don't skip past the end of the string
2898 while (isSeparator(buffer[i])) {
2905 // skip to first separator
2906 while (!isSeparator(buffer[i]))
2910 // skip to first '=', but don't skip past a ',' or the end of the string
2911 while (buffer[i] != '=') {
2912 if (buffer[i] == ',' || i >= length)
2917 // skip to first non-separator, but don't skip past a ',' or the end of the string
2918 while (isSeparator(buffer[i])) {
2919 if (buffer[i] == ',' || i >= length)
2925 // skip to first separator
2926 while (!isSeparator(buffer[i]))
2930 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
2932 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2933 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2934 callback(keyString, valueString, this, data);
2938 void Document::processViewport(const String& features, ViewportArguments::Type origin)
2940 ASSERT(!features.isNull());
2942 if (origin < m_viewportArguments.type)
2945 m_viewportArguments = ViewportArguments(origin);
2946 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2948 updateViewportArguments();
2951 void Document::updateViewportArguments()
2953 if (page() && page()->mainFrame() == frame()) {
2955 m_didDispatchViewportPropertiesChanged = true;
2957 page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
2961 void Document::processReferrerPolicy(const String& policy)
2963 ASSERT(!policy.isNull());
2965 m_referrerPolicy = ReferrerPolicyDefault;
2967 if (equalIgnoringCase(policy, "never"))
2968 m_referrerPolicy = ReferrerPolicyNever;
2969 else if (equalIgnoringCase(policy, "always"))
2970 m_referrerPolicy = ReferrerPolicyAlways;
2971 else if (equalIgnoringCase(policy, "origin"))
2972 m_referrerPolicy = ReferrerPolicyOrigin;
2975 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2977 ASSERT(!renderer() || renderer()->isRenderView());
2980 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
2982 HitTestResult result(documentPoint);
2983 renderView()->hitTest(request, result);
2985 if (!request.readOnly())
2986 updateStyleIfNeeded();
2988 return MouseEventWithHitTestResults(event, result);
2991 // DOM Section 1.1.1
2992 bool Document::childTypeAllowed(NodeType type) const
2995 case ATTRIBUTE_NODE:
2996 case CDATA_SECTION_NODE:
2997 case DOCUMENT_FRAGMENT_NODE:
3000 case ENTITY_REFERENCE_NODE:
3003 case XPATH_NAMESPACE_NODE:
3006 case PROCESSING_INSTRUCTION_NODE:
3008 case DOCUMENT_TYPE_NODE:
3010 // Documents may contain no more than one of each of these.
3011 // (One Element and one DocumentType.)
3012 for (Node* c = firstChild(); c; c = c->nextSibling())
3013 if (c->nodeType() == type)
3020 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3023 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3026 if (oldChild->nodeType() == newChild->nodeType())
3029 int numDoctypes = 0;
3030 int numElements = 0;
3032 // First, check how many doctypes and elements we have, not counting
3033 // the child we're about to remove.
3034 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3038 switch (c->nodeType()) {
3039 case DOCUMENT_TYPE_NODE:
3050 // Then, see how many doctypes and elements might be added by the new child.
3051 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3052 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3053 switch (c->nodeType()) {
3054 case ATTRIBUTE_NODE:
3055 case CDATA_SECTION_NODE:
3056 case DOCUMENT_FRAGMENT_NODE:
3059 case ENTITY_REFERENCE_NODE:
3062 case XPATH_NAMESPACE_NODE:
3065 case PROCESSING_INSTRUCTION_NODE:
3067 case DOCUMENT_TYPE_NODE:
3076 switch (newChild->nodeType()) {
3077 case ATTRIBUTE_NODE:
3078 case CDATA_SECTION_NODE:
3079 case DOCUMENT_FRAGMENT_NODE:
3082 case ENTITY_REFERENCE_NODE:
3085 case XPATH_NAMESPACE_NODE:
3088 case PROCESSING_INSTRUCTION_NODE:
3090 case DOCUMENT_TYPE_NODE:
3099 if (numElements > 1 || numDoctypes > 1)
3105 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3107 // Spec says cloning Document nodes is "implementation dependent"
3108 // so we do not support it...
3112 StyleSheetList* Document::styleSheets()
3114 if (!m_styleSheetList)
3115 m_styleSheetList = StyleSheetList::create(this);
3116 return m_styleSheetList.get();
3119 String Document::preferredStylesheetSet() const
3121 return m_styleSheetCollection->preferredStylesheetSetName();
3124 String Document::selectedStylesheetSet() const
3126 return m_styleSheetCollection->selectedStylesheetSetName();
3129 void Document::setSelectedStylesheetSet(const String& aString)
3131 m_styleSheetCollection->setSelectedStylesheetSetName(aString);
3132 styleResolverChanged(DeferRecalcStyle);
3135 void Document::evaluateMediaQueryList()
3137 if (m_mediaQueryMatcher)
3138 m_mediaQueryMatcher->styleResolverChanged();
3141 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3143 // Don't bother updating, since we haven't loaded all our style info yet
3144 // and haven't calculated the style selector for the first time.
3145 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3146 m_styleResolver.clear();
3149 m_didCalculateStyleResolver = true;
3151 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3152 if (!ownerElement())
3153 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3156 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded)
3157 ? DocumentStyleSheetCollection::OptimizedUpdate
3158 : DocumentStyleSheetCollection::FullUpdate;
3159 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection->updateActiveStyleSheets(styleSheetUpdate);
3161 if (updateFlag == DeferRecalcStyle) {
3162 scheduleForcedStyleRecalc();
3166 if (didLayoutWithPendingStylesheets() && !m_styleSheetCollection->hasPendingSheets()) {
3167 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3169 renderView()->repaintViewAndCompositedLayers();
3172 if (!stylesheetChangeRequiresStyleRecalc)
3175 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3176 // make sure animations get the correct update time
3178 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
3182 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3183 if (!ownerElement())
3184 printf("Finished update of style selector at time %d\n", elapsedTime());
3188 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3190 view()->scheduleRelayout();
3193 evaluateMediaQueryList();
3196 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3198 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3202 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3203 for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
3204 Document* childDocument = child->document();
3205 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3206 ASSERT(childDocument->seamlessParentIFrame()->document() == this);
3207 childDocument->seamlessParentUpdatedStylesheets();
3212 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3214 m_hoverNode = newHoverNode;
3217 void Document::setActiveElement(PassRefPtr<Element> newActiveElement)
3219 if (!newActiveElement) {
3220 m_activeElement.clear();
3224 m_activeElement = newActiveElement;
3227 void Document::focusedNodeRemoved()
3232 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3234 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3237 Node* focusedNode = node->treeScope()->focusedNode();
3241 bool nodeInSubtree = false;
3242 if (amongChildrenOnly)
3243 nodeInSubtree = focusedNode->isDescendantOf(node);
3245 nodeInSubtree = (focusedNode == node) || focusedNode->isDescendantOf(node);
3248 document()->focusedNodeRemoved();
3251 void Document::hoveredNodeDetached(Node* node)
3253 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3256 m_hoverNode = node->parentNode();
3257 while (m_hoverNode && !m_hoverNode->renderer())
3258 m_hoverNode = m_hoverNode->parentNode();
3260 frame()->eventHandler()->scheduleHoverStateUpdate();
3263 void Document::activeChainNodeDetached(Node* node)
3265 if (!m_activeElement || (node != m_activeElement && (!m_activeElement->isTextNode() || node != m_activeElement->parentNode())))
3268 m_activeElement = node->parentElement();
3269 while (m_activeElement && !m_activeElement->renderer())
3270 m_activeElement = m_activeElement->parentElement();
3273 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3274 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3276 return m_annotatedRegions;
3279 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3281 m_annotatedRegions = regions;
3282 setAnnotatedRegionsDirty(false);
3286 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode, FocusDirection direction)
3288 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3290 // Make sure newFocusedNode is actually in this document
3291 if (newFocusedNode && (newFocusedNode->document() != this))
3294 if (m_focusedNode == newFocusedNode)
3300 bool focusChangeBlocked = false;
3301 RefPtr<Node> oldFocusedNode = m_focusedNode;
3304 // Remove focus from the existing focus node (if any)
3305 if (oldFocusedNode) {
3306 ASSERT(!oldFocusedNode->inDetach());
3308 if (oldFocusedNode->active())
3309 oldFocusedNode->setActive(false);
3311 oldFocusedNode->setFocus(false);
3313 // Dispatch a change event for text fields or textareas that have been edited
3314 if (oldFocusedNode->isElementNode()) {
3315 Element* element = static_cast<Element*>(oldFocusedNode.get());
3316 if (element->wasChangedSinceLastFormControlChangeEvent())
3317 element->dispatchFormControlChangeEvent();
3320 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3321 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3323 if (m_focusedNode) {
3324 // handler shifted focus
3325 focusChangeBlocked = true;
3329 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3330 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3331 // on it, probably when <rdar://problem/8503958> is resolved.
3332 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3334 if (m_focusedNode) {
3335 // handler shifted focus
3336 focusChangeBlocked = true;
3339 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3342 if (oldFocusedNode->isRootEditableElement())
3343 frame()->editor()->didEndEditing();
3346 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3348 oldWidget->setFocus(false);
3350 view()->setFocus(false);
3354 if (newFocusedNode) {
3355 if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3356 // delegate blocks focus change
3357 focusChangeBlocked = true;
3358 goto SetFocusedNodeDone;
3360 // Set focus on the new node
3361 m_focusedNode = newFocusedNode;
3363 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3364 m_focusedNode->dispatchFocusEvent(oldFocusedNode, direction);
3366 if (m_focusedNode != newFocusedNode) {
3367 // handler shifted focus
3368 focusChangeBlocked = true;
3369 goto SetFocusedNodeDone;
3372 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3374 if (m_focusedNode != newFocusedNode) {
3375 // handler shifted focus
3376 focusChangeBlocked = true;
3377 goto SetFocusedNodeDone;
3380 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3381 // on it, probably when <rdar://problem/8503958> is m.
3382 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3384 if (m_focusedNode != newFocusedNode) {
3385 // handler shifted focus
3386 focusChangeBlocked = true;
3387 goto SetFocusedNodeDone;
3389 m_focusedNode->setFocus(true);
3391 if (m_focusedNode->isRootEditableElement())
3392 frame()->editor()->didBeginEditing();
3394 // eww, I suck. set the qt focus correctly
3395 // ### find a better place in the code for this
3397 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3399 // Make sure a widget has the right size before giving it focus.
3400 // Otherwise, we are testing edge cases of the Widget code.
3401 // Specifically, in WebCore this does not work well for text fields.
3403 // Re-get the widget in case updating the layout changed things.
3404 focusWidget = widgetForNode(m_focusedNode.get());
3407 focusWidget->setFocus(true);
3409 view()->setFocus(true);
3413 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3414 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
3415 axObjectCache()->handleFocusedUIElementChanged(oldFocusedNode.get(), newFocusedNode.get());
3417 if (!focusChangeBlocked)
3418 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3421 updateStyleIfNeeded();
3422 return !focusChangeBlocked;
3425 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3429 for (Node* node = firstChild(); node; node = NodeTraversal::next(node)) {
3430 if (node->isFocusable())
3435 void Document::setCSSTarget(Element* n)
3438 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3441 n->didAffectSelector(AffectedSelectorTarget);
3444 void Document::registerNodeList(LiveNodeListBase* list)
3446 if (list->hasIdNameCache())
3447 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3448 m_nodeListCounts[list->invalidationType()]++;
3449 if (list->isRootedAtDocument())
3450 m_listsInvalidatedAtDocument.add(list);
3453 void Document::unregisterNodeList(LiveNodeListBase* list)
3455 if (list->hasIdNameCache())
3456 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3457 m_nodeListCounts[list->invalidationType()]--;
3458 if (list->isRootedAtDocument()) {
3459 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3460 m_listsInvalidatedAtDocument.remove(list);
3464 void Document::attachNodeIterator(NodeIterator* ni)
3466 m_nodeIterators.add(ni);
3469 void Document::detachNodeIterator(NodeIterator* ni)
3471 // The node iterator can be detached without having been attached if its root node didn't have a document
3472 // when the iterator was created, but has it now.
3473 m_nodeIterators.remove(ni);
3476 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3478 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3479 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3480 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3481 if ((*it)->root() == node) {
3482 detachNodeIterator(*it);
3483 newDocument->attachNodeIterator(*it);
3488 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3490 if (!m_ranges.isEmpty()) {
3491 HashSet<Range*>::const_iterator end = m_ranges.end();
3492 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3493 (*it)->nodeChildrenChanged(container);
3497 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3499 if (!m_ranges.isEmpty()) {
3500 HashSet<Range*>::const_iterator end = m_ranges.end();
3501 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3502 (*it)->nodeChildrenWillBeRemoved(container);
3505 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3506 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3507 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3508 (*it)->nodeWillBeRemoved(n);
3511 if (Frame* frame = this->frame()) {
3512 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3513 frame->eventHandler()->nodeWillBeRemoved(n);
3514 frame->selection()->nodeWillBeRemoved(n);
3515 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3520 void Document::nodeWillBeRemoved(Node* n)
3522 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3523 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3524 (*it)->nodeWillBeRemoved(n);
3526 if (!m_ranges.isEmpty()) {
3527 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3528 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3529 (*it)->nodeWillBeRemoved(n);
3532 if (Frame* frame = this->frame()) {
3533 frame->eventHandler()->nodeWillBeRemoved(n);
3534 frame->selection()->nodeWillBeRemoved(n);
3535 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3539 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3541 if (!m_ranges.isEmpty()) {
3542 HashSet<Range*>::const_iterator end = m_ranges.end();
3543 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3544 (*it)->textInserted(text, offset, length);
3547 // Update the markers for spelling and grammar checking.
3548 m_markers->shiftMarkers(text, offset, length);
3551 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3553 if (!m_ranges.isEmpty()) {
3554 HashSet<Range*>::const_iterator end = m_ranges.end();
3555 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3556 (*it)->textRemoved(text, offset, length);
3559 // Update the markers for spelling and grammar checking.
3560 m_markers->removeMarkers(text, offset, length);
3561 m_markers->shiftMarkers(text, offset + length, 0 - length);
3564 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3566 if (!m_ranges.isEmpty()) {
3567 NodeWithIndex oldNodeWithIndex(oldNode);
3568 HashSet<Range*>::const_iterator end = m_ranges.end();
3569 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3570 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3573 // FIXME: This should update markers for spelling and grammar checking.
3576 void Document::textNodeSplit(Text* oldNode)
3578 if (!m_ranges.isEmpty()) {
3579 HashSet<Range*>::const_iterator end = m_ranges.end();
3580 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3581 (*it)->textNodeSplit(oldNode);
3584 // FIXME: This should update markers for spelling and grammar checking.
3587 void Document::createDOMWindow()
3590 ASSERT(!m_domWindow);
3592 m_domWindow = DOMWindow::create(this);
3594 ASSERT(m_domWindow->document() == this);
3595 ASSERT(m_domWindow->frame() == m_frame);
3598 void Document::takeDOMWindowFrom(Document* document)
3601 ASSERT(!m_domWindow);
3602 ASSERT(document->domWindow());
3603 // A valid DOMWindow is needed by CachedFrame for its documents.
3604 ASSERT(!document->inPageCache());
3606 m_domWindow = document->m_domWindow.release();
3607 m_domWindow->didSecureTransitionTo(this);
3609 ASSERT(m_domWindow->document() == this);
3610 ASSERT(m_domWindow->frame() == m_frame);
3613 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3615 DOMWindow* domWindow = this->domWindow();
3618 domWindow->setAttributeEventListener(eventType, listener);
3621 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3623 DOMWindow* domWindow = this->domWindow();
3626 return domWindow->getAttributeEventListener(eventType);
3629 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3631 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3632 DOMWindow* domWindow = this->domWindow();
3635 domWindow->dispatchEvent(event, target);
3638 void Document::dispatchWindowLoadEvent()
3640 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3641 DOMWindow* domWindow = this->domWindow();
3644 domWindow->dispatchLoadEvent();
3645 m_loadEventFinished = true;
3648 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3650 event->setTarget(domWindow());
3651 m_eventQueue->enqueueEvent(event);