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 "NewXMLDocumentParser.h"
118 #include "NodeFilter.h"
119 #include "NodeIterator.h"
120 #include "NodeRareData.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 "UserContentURLPattern.h"
162 #include "WebCoreMemoryInstrumentation.h"
163 #include "WebKitNamedFlow.h"
164 #include "XMLDocumentParser.h"
165 #include "XMLHttpRequest.h"
166 #include "XMLNSNames.h"
167 #include "XMLNames.h"
168 #include "XPathEvaluator.h"
169 #include "XPathExpression.h"
170 #include "XPathNSResolver.h"
171 #include "XPathResult.h"
172 #include "htmlediting.h"
173 #include <wtf/CurrentTime.h>
174 #include <wtf/HashFunctions.h>
175 #include <wtf/MainThread.h>
176 #include <wtf/MemoryInstrumentationHashMap.h>
177 #include <wtf/MemoryInstrumentationHashSet.h>
178 #include <wtf/MemoryInstrumentationVector.h>
179 #include <wtf/PassRefPtr.h>
180 #include <wtf/StdLibExtras.h>
181 #include <wtf/text/StringBuffer.h>
183 #if USE(ACCELERATED_COMPOSITING)
184 #include "RenderLayerCompositor.h"
187 #if ENABLE(SHARED_WORKERS)
188 #include "SharedWorkerRepository.h"
192 #include "XSLTProcessor.h"
196 #include "SVGDocumentExtensions.h"
197 #include "SVGElementFactory.h"
198 #include "SVGNames.h"
199 #include "SVGSVGElement.h"
200 #include "SVGStyleElement.h"
203 #if ENABLE(TOUCH_EVENTS)
204 #include "TouchList.h"
208 #include "MathMLElement.h"
209 #include "MathMLElementFactory.h"
210 #include "MathMLNames.h"
213 #if ENABLE(FULLSCREEN_API)
214 #include "RenderFullScreen.h"
217 #if ENABLE(REQUEST_ANIMATION_FRAME)
218 #include "RequestAnimationFrameCallback.h"
219 #include "ScriptedAnimationController.h"
222 #if ENABLE(MICRODATA)
223 #include "MicroDataItemList.h"
224 #include "NodeRareData.h"
227 #if ENABLE(LINK_PRERENDER)
228 #include "Prerenderer.h"
231 #if ENABLE(TEXT_AUTOSIZING)
232 #include "TextAutosizer.h"
236 #include "DOMSecurityPolicy.h"
241 using namespace Unicode;
245 using namespace HTMLNames;
247 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
249 static const unsigned cMaxWriteRecursionDepth = 21;
251 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
252 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
254 static const int cLayoutScheduleThreshold = 250;
256 // DOM Level 2 says (letters added):
258 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
259 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
260 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
261 // 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.
262 // 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.
263 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
264 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
265 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
266 // i) Characters ':' and '_' are allowed as name-start characters.
267 // j) Characters '-' and '.' are allowed as name characters.
269 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
271 static inline bool isValidNameStart(UChar32 c)
274 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
278 if (c == ':' || c == '_')
281 // rules (a) and (f) above
282 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
283 if (!(Unicode::category(c) & nameStartMask))
287 if (c >= 0xF900 && c < 0xFFFE)
291 DecompositionType decompType = decompositionType(c);
292 if (decompType == DecompositionFont || decompType == DecompositionCompat)
298 static inline bool isValidNamePart(UChar32 c)
300 // rules (a), (e), and (i) above
301 if (isValidNameStart(c))
304 // rules (g) and (h) above
305 if (c == 0x00B7 || c == 0x0387)
309 if (c == '-' || c == '.')
312 // rules (b) and (f) above
313 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
314 if (!(Unicode::category(c) & otherNamePartMask))
318 if (c >= 0xF900 && c < 0xFFFE)
322 DecompositionType decompType = decompositionType(c);
323 if (decompType == DecompositionFont || decompType == DecompositionCompat)
329 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
331 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
333 // If a Document has the address "about:blank"
334 // The origin of the Document is the origin it was assigned when its browsing context was created.
336 // Note: We generalize this to all "blank" URLs and invalid URLs because we
337 // treat all of these URLs as about:blank.
339 return !url.isValid() || url.isBlankURL();
342 static Widget* widgetForNode(Node* focusedNode)
346 RenderObject* renderer = focusedNode->renderer();
347 if (!renderer || !renderer->isWidget())
349 return toRenderWidget(renderer)->widget();
352 static bool acceptsEditingFocus(Node* node)
355 ASSERT(node->rendererIsEditable());
357 Node* root = node->rootEditableElement();
358 Frame* frame = node->document()->frame();
362 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
365 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
367 // targetFrame can be 0 when we're trying to navigate a top-level frame
368 // that has a 0 opener.
372 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
373 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
374 Document* ancestorDocument = ancestorFrame->document();
375 // FIXME: Should be an ASSERT? Frames should alway have documents.
376 if (!ancestorDocument)
379 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
380 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
383 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
384 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
385 // something more general instead?
386 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
393 static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL)
395 // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
396 String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
397 frame->document()->url().string() + " from frame with URL " + activeURL.string() + ".\n";
399 // FIXME: should we print to the console of the document performing the navigation instead?
400 frame->document()->domWindow()->printErrorMessage(message);
403 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
405 class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
407 static PassRefPtr<DocumentWeakReference> create(Document* document)
409 return adoptRef(new DocumentWeakReference(document));
414 ASSERT(isMainThread());
420 ASSERT(isMainThread());
425 DocumentWeakReference(Document* document)
426 : m_document(document)
428 ASSERT(isMainThread());
431 Document* m_document;
434 uint64_t Document::s_globalTreeVersion = 0;
436 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
437 : ContainerNode(0, CreateDocument)
440 , m_contextFeatures(ContextFeatures::defaultSwitch())
441 , m_compatibilityMode(NoQuirksMode)
442 , m_compatibilityModeLocked(false)
443 , m_domTreeVersion(++s_globalTreeVersion)
444 #if ENABLE(MUTATION_OBSERVERS)
445 , m_mutationObserverTypes(0)
447 , m_styleSheetCollection(DocumentStyleSheetCollection::create(this))
448 , m_readyState(Complete)
449 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
450 , m_pendingStyleRecalcShouldForce(false)
451 , m_frameElementsShouldIgnoreScrolling(false)
452 , m_containsValidityStyleRules(false)
453 , m_updateFocusAppearanceRestoresSelection(false)
454 , m_ignoreDestructiveWriteCount(0)
455 , m_titleSetExplicitly(false)
456 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
457 , m_loadEventFinished(false)
458 , m_startTime(currentTime())
459 , m_overMinimumLayoutThreshold(false)
460 , m_scriptRunner(ScriptRunner::create(this))
461 , m_xmlVersion("1.0")
462 , m_xmlStandalone(StandaloneUnspecified)
463 , m_hasXMLDeclaration(0)
465 , m_designMode(inherit)
466 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
467 , m_hasAnnotatedRegions(false)
468 , m_annotatedRegionsDirty(false)
470 , m_createRenderers(true)
471 , m_inPageCache(false)
472 , m_accessKeyMapValid(false)
473 , m_useSecureKeyboardEntryWhenActive(false)
476 , m_isViewSource(false)
477 , m_sawElementsInKnownNamespaces(false)
478 , m_isSrcdocDocument(false)
480 , m_eventQueue(DocumentEventQueue::create(this))
481 , m_weakReference(DocumentWeakReference::create(this))
482 , m_idAttributeName(idAttr)
483 #if ENABLE(FULLSCREEN_API)
484 , m_areKeysEnabledInFullScreen(0)
485 , m_fullScreenRenderer(0)
486 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
487 , m_isAnimatingFullScreen(false)
489 , m_loadEventDelayCount(0)
490 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
491 , m_referrerPolicy(ReferrerPolicyDefault)
492 , m_directionSetOnDocumentElement(false)
493 , m_writingModeSetOnDocumentElement(false)
494 , m_writeRecursionIsTooDeep(false)
495 , m_writeRecursionDepth(0)
496 , m_wheelEventHandlerCount(0)
497 #if ENABLE(TOUCH_EVENTS)
498 , m_touchEventHandlerCount(0)
500 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
501 , m_scheduledTasksAreSuspended(false)
502 , m_visualUpdatesAllowed(true)
503 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
504 , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
506 , m_didDispatchViewportPropertiesChanged(false)
512 m_paginatedForScreen = false;
514 m_ignoreAutofocus = false;
518 provideContextFeaturesToDocumentFrom(this, m_frame->page());
520 // We depend on the url getting immediately set in subframes, but we
521 // also depend on the url NOT getting immediately set in opened windows.
522 // See fast/dom/early-frame-url.html
523 // and fast/dom/location-new-window-no-crash.html, respectively.
524 // FIXME: Can/should we unify this behavior?
525 if ((frame && frame->ownerElement()) || !url.isEmpty())
528 m_markers = adoptPtr(new DocumentMarkerController);
531 m_cachedResourceLoader = m_frame->loader()->activeDocumentLoader()->cachedResourceLoader();
532 if (!m_cachedResourceLoader)
533 m_cachedResourceLoader = CachedResourceLoader::create(0);
534 m_cachedResourceLoader->setDocument(this);
536 #if ENABLE(LINK_PRERENDER)
537 m_prerenderer = Prerenderer::create(this);
539 #if ENABLE(TEXT_AUTOSIZING)
540 m_textAutosizer = TextAutosizer::create(this);
542 m_visuallyOrdered = false;
544 m_wellFormed = false;
546 m_textColor = Color::black;
548 m_inStyleRecalc = false;
549 m_closeAfterStyleRecalc = false;
551 m_gotoAnchorNeededAfterStylesheetsLoad = false;
553 m_didCalculateStyleResolver = false;
554 m_ignorePendingStylesheets = false;
555 m_needsNotifyRemoveAllPendingStylesheet = false;
556 m_hasNodesWithPlaceholderStyle = false;
557 m_pendingSheetLayout = NoLayoutWithPendingSheets;
562 resetVisitedLinkColor();
563 resetActiveLinkColor();
565 m_processingLoadEvent = false;
567 initSecurityContext();
570 static int docID = 0;
573 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
574 m_nodeListCounts[i] = 0;
576 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
579 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
581 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
582 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
583 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
584 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
585 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
586 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
589 #if ENABLE(FULLSCREEN_API)
590 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const HTMLFrameOwnerElement* owner)
595 if (!owner->hasAttribute(attribute))
597 } while ((owner = owner->document()->ownerElement()));
602 Document::~Document()
605 ASSERT(!m_inPageCache);
606 ASSERT(!m_savedRenderer);
607 ASSERT(m_ranges.isEmpty());
608 ASSERT(!m_styleRecalcTimer.isActive());
609 ASSERT(!m_parentTreeScope);
610 ASSERT(!m_guardRefCount);
612 // FIXME: Should we reset m_domWindow when we detach from the Frame?
614 m_domWindow->resetUnlessSuspendedForPageCache();
616 m_scriptRunner.clear();
618 histogramMutationEventUsage(m_listenerTypes);
620 removeAllEventListeners();
622 // Currently we believe that Document can never outlive the parser.
623 // Although the Document may be replaced synchronously, DocumentParsers
624 // generally keep at least one reference to an Element which would in turn
625 // has a reference to the Document. If you hit this ASSERT, then that
626 // assumption is wrong. DocumentParser::detach() should ensure that even
627 // if the DocumentParser outlives the Document it won't cause badness.
628 ASSERT(!m_parser || m_parser->refCount() == 1);
631 m_renderArena.clear();
633 clearAXObjectCache();
637 if (m_styleSheetList)
638 m_styleSheetList->detachFromDocument();
640 m_styleSheetCollection.clear();
643 m_namedFlows->documentDestroyed();
646 m_elemSheet->clearOwnerNode();
648 m_weakReference->clear();
650 clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
652 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
653 // load the initial empty document and the SVGDocument with the same DocumentLoader).
654 if (m_cachedResourceLoader->document() == this)
655 m_cachedResourceLoader->setDocument(0);
656 m_cachedResourceLoader.clear();
658 // We must call clearRareData() here since a Document class inherits TreeScope
659 // as well as Node. See a comment on TreeScope.h for the reason.
663 ASSERT(!m_listsInvalidatedAtDocument.size());
665 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
666 ASSERT(!m_nodeListCounts[i]);
670 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
673 void Document::removedLastRef()
675 ASSERT(!m_deletionHasBegun);
676 if (m_guardRefCount) {
677 // If removing a child removes the last self-only ref, we don't
678 // want the scope to be destructed until after
679 // removeAllChildren returns, so we guard ourselves with an
680 // extra self-only ref.
683 // We must make sure not to be retaining any of our children through
684 // these extra pointers or we will create a reference cycle.
690 m_documentElement = 0;
691 m_contextFeatures = ContextFeatures::defaultSwitch();
692 #if ENABLE(FULLSCREEN_API)
693 m_fullScreenElement = 0;
694 m_fullScreenElementStack.clear();
699 // removeAllChildren() doesn't always unregister IDs,
700 // so tear down scope information upfront to avoid having stale references in the map.
701 destroyTreeScopeData();
706 m_cssCanvasElements.clear();
708 #if ENABLE(REQUEST_ANIMATION_FRAME)
709 // FIXME: consider using ActiveDOMObject.
710 if (m_scriptedAnimationController)
711 m_scriptedAnimationController->clearDocumentPointer();
712 m_scriptedAnimationController.clear();
716 m_inRemovedLastRefFunction = false;
722 m_deletionHasBegun = true;
728 Element* Document::getElementById(const AtomicString& id) const
730 return TreeScope::getElementById(id);
733 Element* Document::getElementByAccessKey(const String& key)
737 if (!m_accessKeyMapValid) {
738 buildAccessKeyMap(this);
739 m_accessKeyMapValid = true;
741 return m_elementsByAccessKey.get(key.impl());
744 void Document::buildAccessKeyMap(TreeScope* scope)
747 Node* rootNode = scope->rootNode();
748 for (Node* node = rootNode; node; node = node->traverseNextNode(rootNode)) {
749 if (!node->isElementNode())
751 Element* element = static_cast<Element*>(node);
752 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
753 if (!accessKey.isEmpty())
754 m_elementsByAccessKey.set(accessKey.impl(), element);
756 for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
757 buildAccessKeyMap(root);
761 void Document::invalidateAccessKeyMap()
763 m_accessKeyMapValid = false;
764 m_elementsByAccessKey.clear();
767 SelectorQueryCache* Document::selectorQueryCache()
769 if (!m_selectorQueryCache)
770 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
771 return m_selectorQueryCache.get();
774 MediaQueryMatcher* Document::mediaQueryMatcher()
776 if (!m_mediaQueryMatcher)
777 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
778 return m_mediaQueryMatcher.get();
781 void Document::setCompatibilityMode(CompatibilityMode mode)
783 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
785 bool wasInQuirksMode = inQuirksMode();
786 m_compatibilityMode = mode;
787 selectorQueryCache()->invalidate();
788 if (inQuirksMode() != wasInQuirksMode) {
789 // All user stylesheets have to reparse using the different mode.
790 m_styleSheetCollection->clearPageUserStyleSheet();
791 m_styleSheetCollection->invalidateInjectedStyleSheetCache();
795 String Document::compatMode() const
797 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
800 void Document::resetLinkColor()
802 m_linkColor = Color(0, 0, 238);
805 void Document::resetVisitedLinkColor()
807 m_visitedLinkColor = Color(85, 26, 139);
810 void Document::resetActiveLinkColor()
812 m_activeLinkColor.setNamedColor("red");
815 void Document::setDocType(PassRefPtr<DocumentType> docType)
817 // This should never be called more than once.
818 ASSERT(!m_docType || !docType);
821 this->adoptIfNeeded(m_docType.get());
822 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
823 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
824 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
827 // Doctype affects the interpretation of the stylesheets.
828 clearStyleResolver();
831 DOMImplementation* Document::implementation()
833 if (!m_implementation)
834 m_implementation = DOMImplementation::create(this);
835 return m_implementation.get();
838 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
840 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
842 Element* newDocumentElement = firstElementChild(this);
843 if (newDocumentElement == m_documentElement)
845 m_documentElement = newDocumentElement;
846 // The root style used for media query matching depends on the document element.
847 clearStyleResolver();
850 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
852 if (!isValidName(name)) {
853 ec = INVALID_CHARACTER_ERR;
858 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
860 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
863 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
865 return DocumentFragment::create(document());
868 PassRefPtr<Text> Document::createTextNode(const String& data)
870 return Text::create(this, data);
873 PassRefPtr<Comment> Document::createComment(const String& data)
875 return Comment::create(this, data);
878 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
880 if (isHTMLDocument()) {
881 ec = NOT_SUPPORTED_ERR;
884 return CDATASection::create(this, data);
887 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
889 if (!isValidName(target)) {
890 ec = INVALID_CHARACTER_ERR;
893 if (isHTMLDocument()) {
894 ec = NOT_SUPPORTED_ERR;
897 return ProcessingInstruction::create(this, target, data);
900 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
902 if (!isValidName(name)) {
903 ec = INVALID_CHARACTER_ERR;
906 if (isHTMLDocument()) {
907 ec = NOT_SUPPORTED_ERR;
910 return EntityReference::create(this, name);
913 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
915 return Text::createEditingText(this, text);
918 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
920 return StylePropertySet::create()->ensureCSSStyleDeclaration();
923 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
928 ec = NOT_SUPPORTED_ERR;
932 switch (importedNode->nodeType()) {
934 return createTextNode(importedNode->nodeValue());
935 case CDATA_SECTION_NODE:
936 return createCDATASection(importedNode->nodeValue(), ec);
937 case ENTITY_REFERENCE_NODE:
938 return createEntityReference(importedNode->nodeName(), ec);
939 case PROCESSING_INSTRUCTION_NODE:
940 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
942 return createComment(importedNode->nodeValue());
944 Element* oldElement = static_cast<Element*>(importedNode);
945 // FIXME: The following check might be unnecessary. Is it possible that
946 // oldElement has mismatched prefix/namespace?
947 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
951 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
953 newElement->cloneDataFromElement(*oldElement);
956 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
957 RefPtr<Node> newChild = importNode(oldChild, true, ec);
960 newElement->appendChild(newChild.release(), ec);
966 return newElement.release();
969 return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
970 case DOCUMENT_FRAGMENT_NODE: {
971 if (importedNode->isShadowRoot()) {
972 // ShadowRoot nodes should not be explicitly importable.
973 // Either they are imported along with their host node, or created implicitly.
976 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
977 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
979 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
980 RefPtr<Node> newChild = importNode(oldChild, true, ec);
983 newFragment->appendChild(newChild.release(), ec);
989 return newFragment.release();
993 // 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.
994 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
996 case DOCUMENT_TYPE_NODE:
997 case XPATH_NAMESPACE_NODE:
1000 ec = NOT_SUPPORTED_ERR;
1005 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1008 ec = NOT_SUPPORTED_ERR;
1012 if (source->isReadOnlyNode()) {
1013 ec = NO_MODIFICATION_ALLOWED_ERR;
1017 EventQueueScope scope;
1019 switch (source->nodeType()) {
1023 case DOCUMENT_TYPE_NODE:
1024 case XPATH_NAMESPACE_NODE:
1025 ec = NOT_SUPPORTED_ERR;
1027 case ATTRIBUTE_NODE: {
1028 Attr* attr = static_cast<Attr*>(source.get());
1029 if (attr->ownerElement())
1030 attr->ownerElement()->removeAttributeNode(attr, ec);
1031 attr->setSpecified(true);
1035 if (source->isShadowRoot()) {
1036 // ShadowRoot cannot disconnect itself from the host node.
1037 ec = HIERARCHY_REQUEST_ERR;
1041 if (source->isFrameOwnerElement()) {
1042 HTMLFrameOwnerElement* frameOwnerElement = toFrameOwnerElement(source.get());
1043 if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
1044 ec = HIERARCHY_REQUEST_ERR;
1048 if (source->parentNode()) {
1049 source->parentNode()->removeChild(source.get(), ec);
1055 this->adoptIfNeeded(source.get());
1060 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1062 // These checks are from DOM Core Level 2, createElementNS
1063 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1064 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1066 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1069 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1070 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1071 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1072 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1078 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1080 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1081 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1082 // Note: The case of an "xmlns" qualified name with a namespace of
1083 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1084 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1086 return hasValidNamespaceForElements(qName);
1089 // FIXME: This should really be in a possible ElementFactory class
1090 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1094 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1095 if (qName.namespaceURI() == xhtmlNamespaceURI)
1096 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
1098 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1099 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
1102 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1103 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
1107 m_sawElementsInKnownNamespaces = true;
1109 e = Element::create(qName, document());
1111 // <image> uses imgTag so we need a special rule.
1112 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
1117 bool Document::regionBasedColumnsEnabled() const
1119 return settings() && settings()->regionBasedColumnsEnabled();
1122 bool Document::cssStickyPositionEnabled() const
1124 return settings() && settings()->cssStickyPositionEnabled();
1127 bool Document::cssRegionsEnabled() const
1129 return RuntimeEnabledFeatures::cssRegionsEnabled();
1132 bool Document::cssGridLayoutEnabled() const
1134 return settings() && settings()->cssGridLayoutEnabled();
1137 #if ENABLE(CSS_REGIONS)
1139 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1141 if (!cssRegionsEnabled() || !renderer())
1144 updateStyleIfNeeded();
1146 return namedFlows()->createCSSOMSnapshot();
1151 NamedFlowCollection* Document::namedFlows()
1154 m_namedFlows = NamedFlowCollection::create(this);
1156 return m_namedFlows.get();
1159 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1161 String prefix, localName;
1162 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1165 QualifiedName qName(prefix, localName, namespaceURI);
1166 if (!hasValidNamespaceForElements(qName)) {
1171 return createElement(qName, false);
1174 String Document::readyState() const
1176 DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1177 DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1178 DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1180 switch (m_readyState) {
1189 ASSERT_NOT_REACHED();
1193 void Document::setReadyState(ReadyState readyState)
1195 if (readyState == m_readyState)
1198 switch (readyState) {
1200 if (!m_documentTiming.domLoading)
1201 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1204 if (!m_documentTiming.domInteractive)
1205 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1208 if (!m_documentTiming.domComplete)
1209 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1213 m_readyState = readyState;
1214 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1216 if (settings() && settings()->suppressesIncrementalRendering())
1217 setVisualUpdatesAllowed(readyState);
1220 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1222 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1223 switch (readyState) {
1225 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1226 ASSERT(m_visualUpdatesAllowed);
1227 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1228 setVisualUpdatesAllowed(false);
1231 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1234 if (m_visualUpdatesSuppressionTimer.isActive()) {
1235 ASSERT(!m_visualUpdatesAllowed);
1236 m_visualUpdatesSuppressionTimer.stop();
1237 setVisualUpdatesAllowed(true);
1239 ASSERT(m_visualUpdatesAllowed);
1244 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1246 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1249 m_visualUpdatesAllowed = visualUpdatesAllowed;
1251 if (!visualUpdatesAllowed)
1254 #if USE(ACCELERATED_COMPOSITING)
1256 view()->updateCompositingLayersAfterLayout();
1260 renderer()->repaint();
1263 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1265 ASSERT(!m_visualUpdatesAllowed);
1266 setVisualUpdatesAllowed(true);
1269 String Document::encoding() const
1271 if (TextResourceDecoder* d = decoder())
1272 return d->encoding().domName();
1276 String Document::defaultCharset() const
1278 if (Settings* settings = this->settings())
1279 return settings->defaultTextEncodingName();
1283 void Document::setCharset(const String& charset)
1287 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1290 void Document::setContentLanguage(const String& language)
1292 if (m_contentLanguage == language)
1294 m_contentLanguage = language;
1296 // Recalculate style so language is used when selecting the initial font.
1297 styleResolverChanged(DeferRecalcStyle);
1300 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1302 if (!implementation()->hasFeature("XML", String())) {
1303 ec = NOT_SUPPORTED_ERR;
1307 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1308 ec = NOT_SUPPORTED_ERR;
1312 m_xmlVersion = version;
1315 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1317 if (!implementation()->hasFeature("XML", String())) {
1318 ec = NOT_SUPPORTED_ERR;
1322 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1325 void Document::setDocumentURI(const String& uri)
1327 // This property is read-only from JavaScript, but writable from Objective-C.
1328 m_documentURI = uri;
1332 KURL Document::baseURI() const
1337 void Document::setContent(const String& content)
1340 m_parser->append(content);
1344 String Document::suggestedMIMEType() const
1346 if (m_document->isXHTMLDocument())
1347 return "application/xhtml+xml";
1348 if (m_document->isSVGDocument())
1349 return "image/svg+xml";
1350 if (m_document->xmlStandalone())
1352 if (m_document->isHTMLDocument())
1355 if (DocumentLoader* documentLoader = loader())
1356 return documentLoader->responseMIMEType();
1360 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1361 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1362 // * making it receive the expading size of each direction separately,
1363 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1364 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
1366 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1369 Frame* frame = this->frame();
1372 FrameView* frameView = frame->view();
1376 float zoomFactor = frame->pageZoomFactor();
1377 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1379 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1381 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1383 type |= HitTestRequest::IgnoreClipping;
1384 else if (!frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1386 if (allowShadowContent)
1387 type |= HitTestRequest::AllowShadowContent;
1389 HitTestRequest request(type);
1391 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1392 // we special handle this case in order to return a valid NodeList.
1393 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1394 HitTestResult result(point);
1395 return handleZeroPadding(request, result);
1398 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1399 renderView()->hitTest(request, result);
1401 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1404 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1406 renderView()->hitTest(request, result);
1408 Node* node = result.innerNode();
1412 node = node->shadowAncestorNode();
1413 ListHashSet<RefPtr<Node> > list;
1415 return StaticHashSetNodeList::adopt(list);
1418 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1422 FrameView* frameView = frame->view();
1426 float scaleFactor = frame->pageZoomFactor() * frame->frameScaleFactor();
1427 IntPoint point = roundedIntPoint(FloatPoint(x * scaleFactor + frameView->scrollX(), y * scaleFactor + frameView->scrollY()));
1429 if (!frameView->visibleContentRect().contains(point))
1432 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1433 HitTestResult result(point);
1434 renderView->hitTest(request, result);
1437 *localPoint = result.localPoint();
1439 return result.innerNode();
1442 Element* Document::elementFromPoint(int x, int y) const
1446 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1447 while (node && !node->isElementNode())
1448 node = node->parentNode();
1450 node = ancestorInThisScope(node);
1451 return static_cast<Element*>(node);
1454 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1458 LayoutPoint localPoint;
1459 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1463 Node* shadowAncestorNode = ancestorInThisScope(node);
1464 if (shadowAncestorNode != node) {
1465 unsigned offset = shadowAncestorNode->nodeIndex();
1466 ContainerNode* container = shadowAncestorNode->parentNode();
1467 return Range::create(this, container, offset, container, offset);
1470 RenderObject* renderer = node->renderer();
1473 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1474 if (visiblePosition.isNull())
1477 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1478 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1482 * Performs three operations:
1483 * 1. Convert control characters to spaces
1484 * 2. Trim leading and trailing spaces
1485 * 3. Collapse internal whitespace.
1487 template <typename CharacterType>
1488 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1490 const String& title = titleWithDirection.string();
1491 const CharacterType* characters = title.getCharacters<CharacterType>();
1492 unsigned length = title.length();
1495 StringBuffer<CharacterType> buffer(length);
1496 unsigned builderIndex = 0;
1498 // Skip leading spaces and leading characters that would convert to spaces
1499 for (i = 0; i < length; ++i) {
1500 CharacterType c = characters[i];
1501 if (!(c <= 0x20 || c == 0x7F))
1506 return StringWithDirection();
1508 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1509 bool previousCharWasWS = false;
1510 for (; i < length; ++i) {
1511 CharacterType c = characters[i];
1512 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1513 if (previousCharWasWS)
1515 buffer[builderIndex++] = ' ';
1516 previousCharWasWS = true;
1518 buffer[builderIndex++] = c;
1519 previousCharWasWS = false;
1523 // Strip trailing spaces
1524 while (builderIndex > 0) {
1526 if (buffer[builderIndex] != ' ')
1530 if (!builderIndex && buffer[builderIndex] == ' ')
1531 return StringWithDirection();
1533 buffer.shrink(builderIndex + 1);
1535 // Replace the backslashes with currency symbols if the encoding requires it.
1536 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1538 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1541 void Document::updateTitle(const StringWithDirection& title)
1543 if (m_rawTitle == title)
1548 if (m_rawTitle.string().isEmpty())
1549 m_title = StringWithDirection();
1551 if (m_rawTitle.string().is8Bit())
1552 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1554 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1556 if (Frame* f = frame())
1557 f->loader()->setTitle(m_title);
1560 void Document::setTitle(const String& title)
1562 // Title set by JavaScript -- overrides any title elements.
1563 m_titleSetExplicitly = true;
1564 if (!isHTMLDocument() && !isXHTMLDocument())
1566 else if (!m_titleElement) {
1567 if (HTMLElement* headElement = head()) {
1568 m_titleElement = createElement(titleTag, false);
1569 ExceptionCode ec = 0;
1570 headElement->appendChild(m_titleElement, ec);
1575 // The DOM API has no method of specifying direction, so assume LTR.
1576 updateTitle(StringWithDirection(title, LTR));
1578 if (m_titleElement) {
1579 ASSERT(m_titleElement->hasTagName(titleTag));
1580 if (m_titleElement->hasTagName(titleTag))
1581 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1585 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1587 if (titleElement != m_titleElement) {
1588 if (m_titleElement || m_titleSetExplicitly)
1589 // Only allow the first title element to change the title -- others have no effect.
1591 m_titleElement = titleElement;
1597 void Document::removeTitle(Element* titleElement)
1599 if (m_titleElement != titleElement)
1603 m_titleSetExplicitly = false;
1605 // Update title based on first title element in the head, if one exists.
1606 if (HTMLElement* headElement = head()) {
1607 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1608 if (e->hasTagName(titleTag)) {
1609 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1610 setTitleElement(titleElement->textWithDirection(), titleElement);
1615 if (!m_titleElement)
1616 updateTitle(StringWithDirection());
1619 #if ENABLE(PAGE_VISIBILITY_API)
1620 PageVisibilityState Document::visibilityState() const
1622 // The visibility of the document is inherited from the visibility of the
1623 // page. If there is no page associated with the document, we will assume
1624 // that the page is hidden, as specified by the spec:
1625 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1626 if (!m_frame || !m_frame->page())
1627 return PageVisibilityStateHidden;
1628 return m_frame->page()->visibilityState();
1631 String Document::webkitVisibilityState() const
1633 return pageVisibilityStateString(visibilityState());
1636 bool Document::webkitHidden() const
1638 return visibilityState() != PageVisibilityStateVisible;
1641 void Document::dispatchVisibilityStateChangeEvent()
1643 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1647 #if ENABLE(CSP_NEXT)
1648 DOMSecurityPolicy* Document::securityPolicy()
1650 if (!m_domSecurityPolicy)
1651 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1652 return m_domSecurityPolicy.get();
1656 String Document::nodeName() const
1661 Node::NodeType Document::nodeType() const
1663 return DOCUMENT_NODE;
1666 FormController* Document::formController()
1668 if (!m_formController)
1669 m_formController = FormController::create();
1670 return m_formController.get();
1673 Vector<String> Document::formElementsState() const
1675 if (!m_formController)
1676 return Vector<String>();
1677 return m_formController->formElementsState();
1680 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1682 if (!stateVector.size() && !m_formController)
1684 formController()->setStateForNewFormElements(stateVector);
1687 FrameView* Document::view() const
1689 return m_frame ? m_frame->view() : 0;
1692 Page* Document::page() const
1694 return m_frame ? m_frame->page() : 0;
1697 Settings* Document::settings() const
1699 return m_frame ? m_frame->settings() : 0;
1702 PassRefPtr<Range> Document::createRange()
1704 return Range::create(this);
1707 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1708 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1711 ec = NOT_SUPPORTED_ERR;
1714 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1717 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1718 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1721 ec = NOT_SUPPORTED_ERR;
1724 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1727 void Document::scheduleForcedStyleRecalc()
1729 m_pendingStyleRecalcShouldForce = true;
1730 scheduleStyleRecalc();
1733 void Document::scheduleStyleRecalc()
1735 if (shouldDisplaySeamlesslyWithParent()) {
1736 // When we're seamless, our parent document manages our style recalcs.
1737 ownerElement()->setNeedsStyleRecalc();
1738 ownerElement()->document()->scheduleStyleRecalc();
1742 if (m_styleRecalcTimer.isActive() || inPageCache())
1745 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1747 if (!documentsThatNeedStyleRecalc)
1748 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1749 documentsThatNeedStyleRecalc->add(this);
1751 // FIXME: Why on earth is this here? This is clearly misplaced.
1752 invalidateAccessKeyMap();
1754 m_styleRecalcTimer.startOneShot(0);
1756 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1759 void Document::unscheduleStyleRecalc()
1761 ASSERT(!childNeedsStyleRecalc());
1763 if (documentsThatNeedStyleRecalc)
1764 documentsThatNeedStyleRecalc->remove(this);
1766 m_styleRecalcTimer.stop();
1767 m_pendingStyleRecalcShouldForce = false;
1770 bool Document::hasPendingStyleRecalc() const
1772 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1775 bool Document::hasPendingForcedStyleRecalc() const
1777 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1780 void Document::styleRecalcTimerFired(Timer<Document>*)
1782 updateStyleIfNeeded();
1785 bool Document::childNeedsAndNotInStyleRecalc()
1787 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1790 void Document::recalcStyle(StyleChange change)
1792 // we should not enter style recalc while painting
1793 ASSERT(!view() || !view()->isPainting());
1794 if (view() && view()->isPainting())
1797 if (m_inStyleRecalc)
1798 return; // Guard against re-entrancy. -dwh
1800 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1801 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1802 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1803 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1804 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1805 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1807 if (m_styleSheetCollection->needsUpdateActiveStylesheetsOnStyleRecalc())
1808 m_styleSheetCollection->updateActiveStyleSheets(DocumentStyleSheetCollection::FullUpdate);
1810 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1812 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1813 m_styleSheetCollection->setUsesRemUnit(true);
1815 m_inStyleRecalc = true;
1816 suspendPostAttachCallbacks();
1818 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1820 RefPtr<FrameView> frameView = view();
1822 frameView->pauseScheduledEvents();
1823 frameView->beginDeferredRepaints();
1826 ASSERT(!renderer() || renderArena());
1827 if (!renderer() || !renderArena())
1830 if (m_pendingStyleRecalcShouldForce)
1833 // Recalculating the root style (on the document) is not needed in the common case.
1834 if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
1835 // style selector may set this again during recalc
1836 m_hasNodesWithPlaceholderStyle = false;
1838 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
1839 StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
1841 renderer()->setStyle(documentStyle.release());
1844 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1845 if (!n->isElementNode())
1847 Element* element = static_cast<Element*>(n);
1848 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1849 element->recalcStyle(change);
1852 #if USE(ACCELERATED_COMPOSITING)
1854 view()->updateCompositingLayersAfterStyleChange();
1858 clearNeedsStyleRecalc();
1859 clearChildNeedsStyleRecalc();
1860 unscheduleStyleRecalc();
1862 m_inStyleRecalc = false;
1864 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1865 if (m_styleResolver)
1866 m_styleSheetCollection->resetCSSFeatureFlags();
1869 frameView->resumeScheduledEvents();
1870 frameView->endDeferredRepaints();
1873 resumePostAttachCallbacks();
1875 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1876 if (m_closeAfterStyleRecalc) {
1877 m_closeAfterStyleRecalc = false;
1881 InspectorInstrumentation::didRecalculateStyle(cookie);
1884 void Document::updateStyleIfNeeded()
1886 ASSERT(isMainThread());
1887 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1889 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1892 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
1893 recalcStyle(NoChange);
1896 void Document::updateStyleForAllDocuments()
1898 ASSERT(isMainThread());
1899 if (!documentsThatNeedStyleRecalc)
1902 while (documentsThatNeedStyleRecalc->size()) {
1903 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1904 Document* doc = *it;
1905 documentsThatNeedStyleRecalc->remove(doc);
1906 doc->updateStyleIfNeeded();
1910 void Document::updateLayout()
1912 ASSERT(isMainThread());
1913 if (Element* oe = ownerElement())
1914 oe->document()->updateLayout();
1916 updateStyleIfNeeded();
1918 StackStats::LayoutCheckPoint layoutCheckPoint;
1919 // Only do a layout if changes have occurred that make it necessary.
1920 FrameView* v = view();
1921 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1925 // FIXME: This is a bad idea and needs to be removed eventually.
1926 // Other browsers load stylesheets before they continue parsing the web page.
1927 // Since we don't, we can run JavaScript code that needs answers before the
1928 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1929 // lets us get reasonable answers. The long term solution to this problem is
1930 // to instead suspend JavaScript execution.
1931 void Document::updateLayoutIgnorePendingStylesheets()
1933 bool oldIgnore = m_ignorePendingStylesheets;
1935 if (!haveStylesheetsLoaded()) {
1936 m_ignorePendingStylesheets = true;
1937 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1938 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1939 // with accurate style information. (Our suppression involves blanking the whole page at the
1940 // moment. If it were more refined, we might be able to do something better.)
1941 // It's worth noting though that this entire method is a hack, since what we really want to do is
1942 // suspend JS instead of doing a layout with inaccurate information.
1943 HTMLElement* bodyElement = body();
1944 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1945 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1946 styleResolverChanged(RecalcStyleImmediately);
1947 } else if (m_hasNodesWithPlaceholderStyle)
1948 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1949 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1950 // but here we need up-to-date style immediately.
1956 m_ignorePendingStylesheets = oldIgnore;
1959 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1961 ASSERT_ARG(element, element->document() == this);
1963 bool oldIgnore = m_ignorePendingStylesheets;
1964 m_ignorePendingStylesheets = true;
1965 RefPtr<RenderStyle> style = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1966 m_ignorePendingStylesheets = oldIgnore;
1967 return style.release();
1970 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1972 RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
1973 return style.release();
1976 bool Document::isPageBoxVisible(int pageIndex)
1978 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1979 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1982 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1984 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1985 RenderView* view = renderView();
1987 int width = pageSize.width();
1988 int height = pageSize.height();
1989 switch (style->pageSizeType()) {
1990 case PAGE_SIZE_AUTO:
1992 case PAGE_SIZE_AUTO_LANDSCAPE:
1994 std::swap(width, height);
1996 case PAGE_SIZE_AUTO_PORTRAIT:
1998 std::swap(width, height);
2000 case PAGE_SIZE_RESOLVED: {
2001 LengthSize size = style->pageSize();
2002 ASSERT(size.width().isFixed());
2003 ASSERT(size.height().isFixed());
2004 width = valueForLength(size.width(), 0, view);
2005 height = valueForLength(size.height(), 0, view);
2009 ASSERT_NOT_REACHED();
2011 pageSize = IntSize(width, height);
2013 // The percentage is calculated with respect to the width even for margin top and bottom.
2014 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2015 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
2016 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
2017 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
2018 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
2021 void Document::setIsViewSource(bool isViewSource)
2023 m_isViewSource = isViewSource;
2024 if (!m_isViewSource)
2027 setSecurityOrigin(SecurityOrigin::createUnique());
2028 didUpdateSecurityOrigin();
2031 void Document::createStyleResolver()
2033 bool matchAuthorAndUserStyles = true;
2034 if (Settings* docSettings = settings())
2035 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
2036 m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
2037 m_styleSheetCollection->combineCSSFeatureFlags();
2040 void Document::clearStyleResolver()
2042 m_styleResolver.clear();
2045 void Document::attach()
2047 ASSERT(!attached());
2048 ASSERT(!m_inPageCache);
2049 ASSERT(!m_axObjectCache || this != topDocument());
2052 m_renderArena = adoptPtr(new RenderArena);
2054 // Create the rendering tree
2055 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
2056 #if USE(ACCELERATED_COMPOSITING)
2057 renderView()->didMoveOnscreen();
2062 RenderObject* render = renderer();
2065 ContainerNode::attach();
2067 setRenderer(render);
2070 void Document::detach()
2073 ASSERT(!m_inPageCache);
2075 #if ENABLE(POINTER_LOCK)
2077 page()->pointerLockController()->documentDetached(this);
2080 if (this == topDocument())
2081 clearAXObjectCache();
2083 stopActiveDOMObjects();
2084 m_eventQueue->close();
2085 #if ENABLE(FULLSCREEN_API)
2086 m_fullScreenChangeEventTargetQueue.clear();
2087 m_fullScreenErrorEventTargetQueue.clear();
2090 #if ENABLE(REQUEST_ANIMATION_FRAME)
2091 // FIXME: consider using ActiveDOMObject.
2092 if (m_scriptedAnimationController)
2093 m_scriptedAnimationController->clearDocumentPointer();
2094 m_scriptedAnimationController.clear();
2097 RenderObject* render = renderer();
2099 documentWillBecomeInactive();
2101 #if ENABLE(SHARED_WORKERS)
2102 SharedWorkerRepository::documentDetached(this);
2106 FrameView* view = m_frame->view();
2108 view->detachCustomScrollbars();
2112 // indicate destruction mode, i.e. attached() but renderer == 0
2115 #if ENABLE(FULLSCREEN_API)
2116 if (m_fullScreenRenderer)
2117 setFullScreenRenderer(0);
2124 ContainerNode::detach();
2126 unscheduleStyleRecalc();
2131 // This is required, as our Frame might delete itself as soon as it detaches
2132 // us. However, this violates Node::detach() semantics, as it's never
2133 // possible to re-attach. Eventually Document::detach() should be renamed,
2134 // or this setting of the frame to 0 could be made explicit in each of the
2135 // callers of Document::detach().
2137 m_renderArena.clear();
2139 if (m_mediaQueryMatcher)
2140 m_mediaQueryMatcher->documentDestroyed();
2143 void Document::prepareForDestruction()
2145 disconnectDescendantFrames();
2146 if (DOMWindow* window = this->domWindow())
2147 window->willDetachDocumentFromFrame();
2151 void Document::removeAllEventListeners()
2153 EventTarget::removeAllEventListeners();
2155 if (DOMWindow* domWindow = this->domWindow())
2156 domWindow->removeAllEventListeners();
2157 for (Node* node = firstChild(); node; node = node->traverseNextNode())
2158 node->removeAllEventListeners();
2161 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2163 ScriptExecutionContext::suspendActiveDOMObjects(why);
2166 void Document::resumeActiveDOMObjects()
2168 ScriptExecutionContext::resumeActiveDOMObjects();
2171 void Document::clearAXObjectCache()
2173 // Clear the cache member variable before calling delete because attempts
2174 // are made to access it during destruction.
2175 topDocument()->m_axObjectCache.release();
2178 bool Document::axObjectCacheExists() const
2180 return topDocument()->m_axObjectCache;
2183 AXObjectCache* Document::axObjectCache() const
2185 // The only document that actually has a AXObjectCache is the top-level
2186 // document. This is because we need to be able to get from any WebCoreAXObject
2187 // to any other WebCoreAXObject on the same page. Using a single cache allows
2188 // lookups across nested webareas (i.e. multiple documents).
2189 Document* topDocument = this->topDocument();
2190 ASSERT(topDocument == this || !m_axObjectCache);
2191 if (!topDocument->m_axObjectCache)
2192 topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(this));
2193 return topDocument->m_axObjectCache.get();
2196 void Document::setVisuallyOrdered()
2198 m_visuallyOrdered = true;
2200 renderer()->style()->setRTLOrdering(VisualOrder);
2203 PassRefPtr<DocumentParser> Document::createParser()
2205 // FIXME: this should probably pass the frame instead
2207 return NewXMLDocumentParser::create(this);
2209 return XMLDocumentParser::create(this, view());
2213 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2215 return parser() ? parser()->asScriptableDocumentParser() : 0;
2218 void Document::open(Document* ownerDocument)
2220 if (ownerDocument) {
2221 setURL(ownerDocument->url());
2222 m_cookieURL = ownerDocument->cookieURL();
2223 setSecurityOrigin(ownerDocument->securityOrigin());
2227 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2228 if (parser->isParsing()) {
2229 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2230 if (parser->isExecutingScript())
2233 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2238 if (m_frame->loader()->state() == FrameStateProvisional)
2239 m_frame->loader()->stopAllLoaders();
2242 removeAllEventListeners();
2244 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2245 parser->setWasCreatedByScript(true);
2247 if (DOMWindow* domWindow = this->domWindow())
2248 domWindow->removeAllEventListeners();
2251 m_frame->loader()->didExplicitOpen();
2254 void Document::detachParser()
2262 void Document::cancelParsing()
2267 // We have to clear the parser to avoid possibly triggering
2268 // the onload handler when closing as a side effect of a cancel-style
2269 // change, such as opening a new document or closing the window while
2275 void Document::implicitOpen()
2281 setCompatibilityMode(NoQuirksMode);
2283 m_parser = createParser();
2285 setReadyState(Loading);
2288 HTMLElement* Document::body() const
2290 Node* de = documentElement();
2294 // try to prefer a FRAMESET element over BODY
2296 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2297 if (i->hasTagName(framesetTag))
2298 return toHTMLElement(i);
2300 if (i->hasTagName(bodyTag) && !body)
2303 return toHTMLElement(body);
2306 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2308 RefPtr<HTMLElement> newBody = prpNewBody;
2310 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2311 ec = HIERARCHY_REQUEST_ERR;
2315 if (newBody->document() && newBody->document() != this) {
2317 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2321 newBody = toHTMLElement(node.get());
2324 HTMLElement* b = body();
2326 documentElement()->appendChild(newBody.release(), ec);
2328 documentElement()->replaceChild(newBody.release(), b, ec);
2331 HTMLHeadElement* Document::head()
2333 Node* de = documentElement();
2337 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2338 if (e->hasTagName(headTag))
2339 return static_cast<HTMLHeadElement*>(e);
2344 void Document::close()
2346 // FIXME: We should follow the specification more closely:
2347 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2349 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2355 void Document::explicitClose()
2361 // Because we have no frame, we don't know if all loading has completed,
2362 // so we just call implicitClose() immediately. FIXME: This might fire
2363 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2368 m_frame->loader()->checkCompleted();
2371 void Document::implicitClose()
2373 // 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.
2374 if (m_inStyleRecalc) {
2375 m_closeAfterStyleRecalc = true;
2379 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2380 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2385 m_processingLoadEvent = true;
2387 ScriptableDocumentParser* parser = scriptableDocumentParser();
2388 m_wellFormed = parser && parser->wellFormed();
2390 // We have to clear the parser, in case someone document.write()s from the
2391 // onLoad event handler, as in Radar 3206524.
2394 // Parser should have picked up all preloads by now
2395 m_cachedResourceLoader->clearPreloads();
2397 // FIXME: We kick off the icon loader when the Document is done parsing.
2398 // There are earlier opportunities we could start it:
2399 // -When the <head> finishes parsing
2400 // -When any new HTMLLinkElement is inserted into the document
2401 // But those add a dynamic component to the favicon that has UI
2402 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2405 f->loader()->icon()->startLoader();
2406 f->animation()->resumeAnimationsForDocument(this);
2409 ImageLoader::dispatchPendingBeforeLoadEvents();
2410 ImageLoader::dispatchPendingLoadEvents();
2411 ImageLoader::dispatchPendingErrorEvents();
2413 HTMLLinkElement::dispatchPendingLoadEvents();
2414 HTMLStyleElement::dispatchPendingLoadEvents();
2417 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2418 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2419 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2420 if (svgExtensions())
2421 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2424 dispatchWindowLoadEvent();
2425 enqueuePageshowEvent(PageshowEventNotPersisted);
2426 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2429 f->loader()->handledOnloadEvents();
2430 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2431 if (!ownerElement())
2432 printf("onload fired at %d\n", elapsedTime());
2435 // An event handler may have removed the frame
2437 m_processingLoadEvent = false;
2441 // Make sure both the initial layout and reflow happen after the onload
2442 // fires. This will improve onload scores, and other browsers do it.
2443 // If they wanna cheat, we can too. -dwh
2445 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2446 // Just bail out. Before or during the onload we were shifted to another page.
2447 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2448 m_processingLoadEvent = false;
2449 view()->unscheduleRelayout();
2453 frame()->loader()->checkCallImplicitClose();
2454 RenderObject* renderObject = renderer();
2456 // We used to force a synchronous display and flush here. This really isn't
2457 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2458 // (if your platform is syncing flushes and limiting them to 60fps).
2459 m_overMinimumLayoutThreshold = true;
2460 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2461 updateStyleIfNeeded();
2463 // Always do a layout after loading if needed.
2464 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2468 m_processingLoadEvent = false;
2470 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2471 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2472 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2473 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2474 // exists in the cache (we ignore the return value because we don't need it here). This is
2475 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2476 axObjectCache()->getOrCreate(renderObject);
2477 if (this == topDocument())
2478 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2480 // AXLoadComplete can only be posted on the top document, so if it's a document
2481 // in an iframe that just finished loading, post AXLayoutComplete instead.
2482 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
2488 if (svgExtensions())
2489 accessSVGExtensions()->startAnimations();
2493 void Document::setParsing(bool b)
2497 if (m_bParsing && !m_sharedObjectPool)
2498 m_sharedObjectPool = DocumentSharedObjectPool::create();
2500 if (!m_bParsing && view())
2501 view()->scheduleRelayout();
2503 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2504 if (!ownerElement() && !m_bParsing)
2505 printf("Parsing finished at %d\n", elapsedTime());
2509 bool Document::shouldScheduleLayout()
2511 // This function will only be called when FrameView thinks a layout is needed.
2512 // This enforces a couple extra rules.
2514 // (a) Only schedule a layout once the stylesheets are loaded.
2515 // (b) Only schedule layout once we have a body element.
2517 return (haveStylesheetsLoaded() && body())
2518 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2521 bool Document::isLayoutTimerActive()
2523 return view() && view()->layoutPending() && !minimumLayoutDelay();
2526 int Document::minimumLayoutDelay()
2528 if (m_overMinimumLayoutThreshold)
2531 int elapsed = elapsedTime();
2532 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2534 // We'll want to schedule the timer to fire at the minimum layout threshold.
2535 return max(0, cLayoutScheduleThreshold - elapsed);
2538 int Document::elapsedTime() const
2540 return static_cast<int>((currentTime() - m_startTime) * 1000);
2543 void Document::write(const SegmentedString& text, Document* ownerDocument)
2545 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2547 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2548 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2550 if (m_writeRecursionIsTooDeep)
2553 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2554 if (!ownerElement())
2555 printf("Beginning a document.write at %d\n", elapsedTime());
2558 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2559 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2562 if (!hasInsertionPoint)
2563 open(ownerDocument);
2566 m_parser->insert(text);
2568 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2569 if (!ownerElement())
2570 printf("Ending a document.write at %d\n", elapsedTime());
2574 void Document::write(const String& text, Document* ownerDocument)
2576 write(SegmentedString(text), ownerDocument);
2579 void Document::writeln(const String& text, Document* ownerDocument)
2581 write(text, ownerDocument);
2582 write("\n", ownerDocument);
2585 const KURL& Document::virtualURL() const
2590 KURL Document::virtualCompleteURL(const String& url) const
2592 return completeURL(url);
2595 double Document::minimumTimerInterval() const
2599 return ScriptExecutionContext::minimumTimerInterval();
2600 return p->settings()->minDOMTimerInterval();
2603 double Document::timerAlignmentInterval() const
2607 return ScriptExecutionContext::timerAlignmentInterval();
2608 return p->settings()->domTimerAlignmentInterval();
2611 EventTarget* Document::errorEventTarget()
2616 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
2618 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
2621 void Document::setURL(const KURL& url)
2623 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2624 if (newURL == m_url)
2628 m_documentURI = m_url.string();
2630 contextFeatures()->urlDidChange(this);
2633 void Document::updateBaseURL()
2635 KURL oldBaseURL = m_baseURL;
2636 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2637 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2638 // from the Document interface otherwise.
2639 if (!m_baseElementURL.isEmpty())
2640 m_baseURL = m_baseElementURL;
2641 else if (!m_baseURLOverride.isEmpty())
2642 m_baseURL = m_baseURLOverride;
2644 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2645 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2646 // and DOM 3 Core does not specify how it should be resolved.
2647 m_baseURL = KURL(KURL(), documentURI());
2649 selectorQueryCache()->invalidate();
2651 if (!m_baseURL.isValid())
2655 // Element sheet is silly. It never contains anything.
2656 ASSERT(!m_elemSheet->contents()->ruleCount());
2657 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2658 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2659 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2660 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2663 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2664 // Base URL change changes any relative visited links.
2665 // 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.
2666 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
2667 if (node->hasTagName(aTag))
2668 static_cast<HTMLAnchorElement*>(node)->invalidateCachedVisitedLinkHash();
2673 void Document::setBaseURLOverride(const KURL& url)
2675 m_baseURLOverride = url;
2679 void Document::processBaseElement()
2681 // Find the first href attribute in a base element and the first target attribute in a base element.
2682 const AtomicString* href = 0;
2683 const AtomicString* target = 0;
2684 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2685 if (node->hasTagName(baseTag)) {
2687 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2688 if (!value.isNull())
2692 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2693 if (!value.isNull())
2699 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2700 KURL baseElementURL;
2702 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2703 if (!strippedHref.isEmpty())
2704 baseElementURL = KURL(url(), strippedHref);
2706 if (m_baseElementURL != baseElementURL) {
2707 m_baseElementURL = baseElementURL;
2711 m_baseTarget = target ? *target : nullAtom;
2714 String Document::userAgent(const KURL& url) const
2716 return frame() ? frame()->loader()->userAgent(url) : String();
2719 void Document::disableEval(const String& errorMessage)
2724 frame()->script()->disableEval(errorMessage);
2727 bool Document::canNavigate(Frame* targetFrame)
2732 // FIXME: We shouldn't call this function without a target frame, but
2733 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2734 // returning true when supplied with a 0 targetFrame.
2738 // Frame-busting is generally allowed (unless we're sandboxed and prevent from frame-busting).
2739 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2742 if (isSandboxed(SandboxNavigation)) {
2743 if (targetFrame->tree()->isDescendantOf(m_frame))
2746 printNavigationErrorMessage(targetFrame, url());
2750 // This is the normal case. A document can navigate its decendant frames,
2751 // or, more generally, a document can navigate a frame if the document is
2752 // in the same origin as any of that frame's ancestors (in the frame
2755 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2756 // historical information about this security check.
2757 if (canAccessAncestor(securityOrigin(), targetFrame))
2760 // Top-level frames are easier to navigate than other frames because they
2761 // display their URLs in the address bar (in most browsers). However, there
2762 // are still some restrictions on navigation to avoid nuisance attacks.
2763 // Specifically, a document can navigate a top-level frame if that frame
2764 // opened the document or if the document is the same-origin with any of
2765 // the top-level frame's opener's ancestors (in the frame hierarchy).
2767 // In both of these cases, the document performing the navigation is in
2768 // some way related to the frame being navigate (e.g., by the "opener"
2769 // and/or "parent" relation). Requiring some sort of relation prevents a
2770 // document from navigating arbitrary, unrelated top-level frames.
2771 if (!targetFrame->tree()->parent()) {
2772 if (targetFrame == m_frame->loader()->opener())
2775 if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
2779 printNavigationErrorMessage(targetFrame, url());
2783 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2785 Frame* currentFrame = m_frame;
2786 Frame* ancestorFrame = currentFrame->tree()->parent();
2788 while (ancestorFrame) {
2789 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2790 return currentFrame;
2791 currentFrame = ancestorFrame;
2792 ancestorFrame = ancestorFrame->tree()->parent();
2798 void Document::seamlessParentUpdatedStylesheets()
2800 styleResolverChanged(RecalcStyleImmediately);
2803 void Document::didRemoveAllPendingStylesheet()
2805 m_needsNotifyRemoveAllPendingStylesheet = false;
2807 styleResolverChanged(RecalcStyleIfNeeded);
2809 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2810 parser->executeScriptsWaitingForStylesheets();
2812 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2813 view()->scrollToFragment(m_url);
2816 CSSStyleSheet* Document::elementSheet()
2819 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2820 return m_elemSheet.get();
2823 int Document::nodeAbsIndex(Node *node)
2825 ASSERT(node->document() == this);
2828 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2833 Node* Document::nodeWithAbsIndex(int absIndex)
2836 for (int i = 0; n && (i < absIndex); i++)
2837 n = n->traverseNextNode();
2841 void Document::processHttpEquiv(const String& equiv, const String& content)
2843 ASSERT(!equiv.isNull() && !content.isNull());
2845 Frame* frame = this->frame();
2847 if (equalIgnoringCase(equiv, "default-style")) {
2848 // The preferred style set has been overridden as per section
2849 // 14.3.2 of the HTML4.0 specification. We need to update the
2850 // sheet used variable and then update our style selector.
2851 // For more info, see the test at:
2852 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2854 m_styleSheetCollection->setSelectedStylesheetSetName(content);
2855 m_styleSheetCollection->setPreferredStylesheetSetName(content);
2856 styleResolverChanged(DeferRecalcStyle);
2857 } else if (equalIgnoringCase(equiv, "refresh")) {
2860 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2862 url = m_url.string();
2864 url = completeURL(url).string();
2865 frame->navigationScheduler()->scheduleRedirect(delay, url);
2867 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2868 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2869 if (isHTMLDocument()) {
2870 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
2871 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
2873 } else if (equalIgnoringCase(equiv, "content-language"))
2874 setContentLanguage(content);
2875 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2876 parseDNSPrefetchControlHeader(content);
2877 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2879 FrameLoader* frameLoader = frame->loader();
2880 unsigned long requestIdentifier = 0;
2881 if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader())
2882 requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier();
2883 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
2884 String message = "Refused to display '" + url().string() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
2885 frameLoader->stopAllLoaders();
2886 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
2887 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, url().string(), 0, 0, requestIdentifier);
2890 } else if (equalIgnoringCase(equiv, "content-security-policy"))
2891 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforceStableDirectives);
2892 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2893 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportStableDirectives);
2894 else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2895 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforceAllDirectives);
2896 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2897 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportAllDirectives);
2900 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2901 static bool isSeparator(UChar c)
2903 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2906 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2908 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2909 int keyBegin, keyEnd;
2910 int valueBegin, valueEnd;
2913 int length = features.length();
2914 String buffer = features.lower();
2915 while (i < length) {
2916 // skip to first non-separator, but don't skip past the end of the string
2917 while (isSeparator(buffer[i])) {
2924 // skip to first separator
2925 while (!isSeparator(buffer[i]))
2929 // skip to first '=', but don't skip past a ',' or the end of the string
2930 while (buffer[i] != '=') {
2931 if (buffer[i] == ',' || i >= length)
2936 // skip to first non-separator, but don't skip past a ',' or the end of the string
2937 while (isSeparator(buffer[i])) {
2938 if (buffer[i] == ',' || i >= length)
2944 // skip to first separator
2945 while (!isSeparator(buffer[i]))
2949 ASSERT(i <= length);
2951 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2952 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2953 callback(keyString, valueString, this, data);
2957 void Document::processViewport(const String& features, ViewportArguments::Type origin)
2959 ASSERT(!features.isNull());
2961 if (origin < m_viewportArguments.type)
2964 m_viewportArguments = ViewportArguments(origin);
2965 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2967 updateViewportArguments();
2970 void Document::updateViewportArguments()
2972 if (page() && page()->mainFrame() == frame()) {
2974 m_didDispatchViewportPropertiesChanged = true;
2976 page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
2980 void Document::processReferrerPolicy(const String& policy)
2982 ASSERT(!policy.isNull());
2984 m_referrerPolicy = ReferrerPolicyDefault;
2986 if (equalIgnoringCase(policy, "never"))
2987 m_referrerPolicy = ReferrerPolicyNever;
2988 else if (equalIgnoringCase(policy, "always"))
2989 m_referrerPolicy = ReferrerPolicyAlways;
2990 else if (equalIgnoringCase(policy, "origin"))
2991 m_referrerPolicy = ReferrerPolicyOrigin;
2994 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2996 ASSERT(!renderer() || renderer()->isRenderView());
2999 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3001 HitTestResult result(documentPoint);
3002 renderView()->hitTest(request, result);
3004 if (!request.readOnly())
3005 updateStyleIfNeeded();
3007 return MouseEventWithHitTestResults(event, result);
3010 // DOM Section 1.1.1
3011 bool Document::childTypeAllowed(NodeType type) const
3014 case ATTRIBUTE_NODE:
3015 case CDATA_SECTION_NODE:
3016 case DOCUMENT_FRAGMENT_NODE:
3019 case ENTITY_REFERENCE_NODE:
3022 case XPATH_NAMESPACE_NODE:
3025 case PROCESSING_INSTRUCTION_NODE:
3027 case DOCUMENT_TYPE_NODE:
3029 // Documents may contain no more than one of each of these.
3030 // (One Element and one DocumentType.)
3031 for (Node* c = firstChild(); c; c = c->nextSibling())
3032 if (c->nodeType() == type)
3039 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3042 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3045 if (oldChild->nodeType() == newChild->nodeType())
3048 int numDoctypes = 0;
3049 int numElements = 0;
3051 // First, check how many doctypes and elements we have, not counting
3052 // the child we're about to remove.
3053 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3057 switch (c->nodeType()) {
3058 case DOCUMENT_TYPE_NODE:
3069 // Then, see how many doctypes and elements might be added by the new child.
3070 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3071 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3072 switch (c->nodeType()) {
3073 case ATTRIBUTE_NODE:
3074 case CDATA_SECTION_NODE:
3075 case DOCUMENT_FRAGMENT_NODE:
3078 case ENTITY_REFERENCE_NODE:
3081 case XPATH_NAMESPACE_NODE:
3084 case PROCESSING_INSTRUCTION_NODE:
3086 case DOCUMENT_TYPE_NODE:
3095 switch (newChild->nodeType()) {
3096 case ATTRIBUTE_NODE:
3097 case CDATA_SECTION_NODE:
3098 case DOCUMENT_FRAGMENT_NODE:
3101 case ENTITY_REFERENCE_NODE:
3104 case XPATH_NAMESPACE_NODE:
3107 case PROCESSING_INSTRUCTION_NODE:
3109 case DOCUMENT_TYPE_NODE:
3118 if (numElements > 1 || numDoctypes > 1)
3124 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3126 // Spec says cloning Document nodes is "implementation dependent"
3127 // so we do not support it...
3131 StyleSheetList* Document::styleSheets()
3133 if (!m_styleSheetList)
3134 m_styleSheetList = StyleSheetList::create(this);
3135 return m_styleSheetList.get();
3138 String Document::preferredStylesheetSet() const
3140 return m_styleSheetCollection->preferredStylesheetSetName();
3143 String Document::selectedStylesheetSet() const
3145 return m_styleSheetCollection->selectedStylesheetSetName();
3148 void Document::setSelectedStylesheetSet(const String& aString)
3150 m_styleSheetCollection->setSelectedStylesheetSetName(aString);
3151 styleResolverChanged(DeferRecalcStyle);
3154 void Document::evaluateMediaQueryList()
3156 if (m_mediaQueryMatcher)
3157 m_mediaQueryMatcher->styleResolverChanged();
3160 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3162 // Don't bother updating, since we haven't loaded all our style info yet
3163 // and haven't calculated the style selector for the first time.
3164 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3165 m_styleResolver.clear();
3168 m_didCalculateStyleResolver = true;
3170 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3171 if (!ownerElement())
3172 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3175 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded)
3176 ? DocumentStyleSheetCollection::OptimizedUpdate
3177 : DocumentStyleSheetCollection::FullUpdate;
3178 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection->updateActiveStyleSheets(styleSheetUpdate);
3180 if (updateFlag == DeferRecalcStyle) {
3181 scheduleForcedStyleRecalc();
3185 if (didLayoutWithPendingStylesheets() && !m_styleSheetCollection->hasPendingSheets()) {
3186 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3188 renderView()->repaintViewAndCompositedLayers();
3191 if (!stylesheetChangeRequiresStyleRecalc)
3194 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3195 // make sure animations get the correct update time
3197 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
3201 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3202 if (!ownerElement())
3203 printf("Finished update of style selector at time %d\n", elapsedTime());
3207 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3209 view()->scheduleRelayout();
3212 evaluateMediaQueryList();
3215 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3217 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3221 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3222 for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
3223 Document* childDocument = child->document();
3224 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3225 ASSERT(childDocument->seamlessParentIFrame()->document() == this);
3226 childDocument->seamlessParentUpdatedStylesheets();
3231 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3233 m_hoverNode = newHoverNode;
3236 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3238 m_activeNode = newActiveNode;
3241 void Document::focusedNodeRemoved()
3246 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3248 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3251 Node* focusedNode = node->treeScope()->focusedNode();
3255 bool nodeInSubtree = false;
3256 if (amongChildrenOnly)
3257 nodeInSubtree = focusedNode->isDescendantOf(node);
3259 nodeInSubtree = (focusedNode == node) || focusedNode->isDescendantOf(node);
3262 document()->focusedNodeRemoved();
3265 void Document::hoveredNodeDetached(Node* node)
3267 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3270 m_hoverNode = node->parentNode();
3271 while (m_hoverNode && !m_hoverNode->renderer())
3272 m_hoverNode = m_hoverNode->parentNode();
3274 frame()->eventHandler()->scheduleHoverStateUpdate();
3277 void Document::activeChainNodeDetached(Node* node)
3279 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3282 m_activeNode = node->parentNode();
3283 while (m_activeNode && !m_activeNode->renderer())
3284 m_activeNode = m_activeNode->parentNode();
3287 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3288 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3290 return m_annotatedRegions;
3293 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3295 m_annotatedRegions = regions;
3296 setAnnotatedRegionsDirty(false);
3300 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3302 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3304 // Make sure newFocusedNode is actually in this document
3305 if (newFocusedNode && (newFocusedNode->document() != this))
3308 if (m_focusedNode == newFocusedNode)
3314 bool focusChangeBlocked = false;
3315 RefPtr<Node> oldFocusedNode = m_focusedNode;
3318 // Remove focus from the existing focus node (if any)
3319 if (oldFocusedNode) {
3320 ASSERT(!oldFocusedNode->inDetach());
3322 if (oldFocusedNode->active())
3323 oldFocusedNode->setActive(false);
3325 oldFocusedNode->setFocus(false);
3327 // Dispatch a change event for text fields or textareas that have been edited
3328 if (oldFocusedNode->isElementNode()) {
3329 Element* element = static_cast<Element*>(oldFocusedNode.get());
3330 if (element->wasChangedSinceLastFormControlChangeEvent())
3331 element->dispatchFormControlChangeEvent();
3334 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3335 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3337 if (m_focusedNode) {
3338 // handler shifted focus
3339 focusChangeBlocked = true;
3343 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3344 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3345 // on it, probably when <rdar://problem/8503958> is resolved.
3346 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3348 if (m_focusedNode) {
3349 // handler shifted focus
3350 focusChangeBlocked = true;
3353 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3356 if (oldFocusedNode->isRootEditableElement())
3357 frame()->editor()->didEndEditing();
3360 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3362 oldWidget->setFocus(false);
3364 view()->setFocus(false);
3368 if (newFocusedNode) {
3369 if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3370 // delegate blocks focus change
3371 focusChangeBlocked = true;
3372 goto SetFocusedNodeDone;
3374 // Set focus on the new node
3375 m_focusedNode = newFocusedNode;
3377 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3378 m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3380 if (m_focusedNode != newFocusedNode) {
3381 // handler shifted focus
3382 focusChangeBlocked = true;
3383 goto SetFocusedNodeDone;
3386 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3388 if (m_focusedNode != newFocusedNode) {
3389 // handler shifted focus
3390 focusChangeBlocked = true;
3391 goto SetFocusedNodeDone;
3394 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3395 // on it, probably when <rdar://problem/8503958> is m.
3396 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3398 if (m_focusedNode != newFocusedNode) {
3399 // handler shifted focus
3400 focusChangeBlocked = true;
3401 goto SetFocusedNodeDone;
3403 m_focusedNode->setFocus(true);
3405 if (m_focusedNode->isRootEditableElement())
3406 frame()->editor()->didBeginEditing();
3408 // eww, I suck. set the qt focus correctly
3409 // ### find a better place in the code for this
3411 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3413 // Make sure a widget has the right size before giving it focus.
3414 // Otherwise, we are testing edge cases of the Widget code.
3415 // Specifically, in WebCore this does not work well for text fields.
3417 // Re-get the widget in case updating the layout changed things.
3418 focusWidget = widgetForNode(m_focusedNode.get());
3421 focusWidget->setFocus(true);
3423 view()->setFocus(true);
3427 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3428 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
3429 axObjectCache()->handleFocusedUIElementChanged(oldFocusedNode.get(), newFocusedNode.get());
3431 if (!focusChangeBlocked)
3432 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3435 updateStyleIfNeeded();
3436 return !focusChangeBlocked;
3439 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3443 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3444 if (node->isFocusable())
3449 void Document::setCSSTarget(Element* n)
3452 m_cssTarget->setNeedsStyleRecalc();
3453 invalidateParentDistributionIfNecessary(m_cssTarget, SelectRuleFeatureSet::RuleFeatureTarget);
3457 n->setNeedsStyleRecalc();
3458 invalidateParentDistributionIfNecessary(n, SelectRuleFeatureSet::RuleFeatureTarget);
3462 void Document::registerNodeList(LiveNodeListBase* list)
3464 if (list->hasIdNameCache())
3465 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3466 m_nodeListCounts[list->invalidationType()]++;
3467 if (list->isRootedAtDocument())
3468 m_listsInvalidatedAtDocument.add(list);
3471 void Document::unregisterNodeList(LiveNodeListBase* list)
3473 if (list->hasIdNameCache())
3474 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3475 m_nodeListCounts[list->invalidationType()]--;
3476 if (list->isRootedAtDocument()) {
3477 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3478 m_listsInvalidatedAtDocument.remove(list);
3482 void Document::attachNodeIterator(NodeIterator* ni)
3484 m_nodeIterators.add(ni);
3487 void Document::detachNodeIterator(NodeIterator* ni)
3489 // The node iterator can be detached without having been attached if its root node didn't have a document
3490 // when the iterator was created, but has it now.
3491 m_nodeIterators.remove(ni);
3494 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3496 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3497 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3498 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3499 if ((*it)->root() == node) {
3500 detachNodeIterator(*it);
3501 newDocument->attachNodeIterator(*it);
3506 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3508 if (!m_ranges.isEmpty()) {
3509 HashSet<Range*>::const_iterator end = m_ranges.end();
3510 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3511 (*it)->nodeChildrenChanged(container);
3515 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3517 if (!m_ranges.isEmpty()) {
3518 HashSet<Range*>::const_iterator end = m_ranges.end();
3519 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3520 (*it)->nodeChildrenWillBeRemoved(container);
3523 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3524 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3525 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3526 (*it)->nodeWillBeRemoved(n);
3529 if (Frame* frame = this->frame()) {
3530 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3531 frame->eventHandler()->nodeWillBeRemoved(n);
3532 frame->selection()->nodeWillBeRemoved(n);
3533 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3538 void Document::nodeWillBeRemoved(Node* n)
3540 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3541 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3542 (*it)->nodeWillBeRemoved(n);
3544 if (!m_ranges.isEmpty()) {
3545 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3546 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3547 (*it)->nodeWillBeRemoved(n);
3550 if (Frame* frame = this->frame()) {
3551 frame->eventHandler()->nodeWillBeRemoved(n);
3552 frame->selection()->nodeWillBeRemoved(n);
3553 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3557 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3559 if (!m_ranges.isEmpty()) {
3560 HashSet<Range*>::const_iterator end = m_ranges.end();
3561 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3562 (*it)->textInserted(text, offset, length);
3565 // Update the markers for spelling and grammar checking.
3566 m_markers->shiftMarkers(text, offset, length);
3569 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3571 if (!m_ranges.isEmpty()) {
3572 HashSet<Range*>::const_iterator end = m_ranges.end();
3573 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3574 (*it)->textRemoved(text, offset, length);
3577 // Update the markers for spelling and grammar checking.
3578 m_markers->removeMarkers(text, offset, length);
3579 m_markers->shiftMarkers(text, offset + length, 0 - length);
3582 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3584 if (!m_ranges.isEmpty()) {
3585 NodeWithIndex oldNodeWithIndex(oldNode);
3586 HashSet<Range*>::const_iterator end = m_ranges.end();
3587 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3588 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3591 // FIXME: This should update markers for spelling and grammar checking.
3594 void Document::textNodeSplit(Text* oldNode)
3596 if (!m_ranges.isEmpty()) {
3597 HashSet<Range*>::const_iterator end = m_ranges.end();
3598 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3599 (*it)->textNodeSplit(oldNode);
3602 // FIXME: This should update markers for spelling and grammar checking.
3605 void Document::createDOMWindow()
3608 ASSERT(!m_domWindow);
3610 m_domWindow = DOMWindow::create(this);
3612 ASSERT(m_domWindow->document() == this);
3613 ASSERT(m_domWindow->frame() == m_frame);
3616 void Document::takeDOMWindowFrom(Document* document)
3619 ASSERT(!m_domWindow);
3620 ASSERT(document->domWindow());
3622 m_domWindow = document->m_domWindow.release();
3623 m_domWindow->didSecureTransitionTo(this);
3625 ASSERT(m_domWindow->document() == this);
3626 ASSERT(m_domWindow->frame() == m_frame);
3629 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3631 DOMWindow* domWindow = this->domWindow();
3634 domWindow->setAttributeEventListener(eventType, listener);
3637 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3639 DOMWindow* domWindow = this->domWindow();
3642 return domWindow->getAttributeEventListener(eventType);
3645 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3647 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3648 DOMWindow* domWindow = this->domWindow();
3651 domWindow->dispatchEvent(event, target);
3654 void Document::dispatchWindowLoadEvent()
3656 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3657 DOMWindow* domWindow = this->domWindow();