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 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 "DOMSelection.h"
51 #include "DOMWindow.h"
52 #include "DateComponents.h"
53 #include "DeviceMotionController.h"
54 #include "DeviceMotionEvent.h"
55 #include "DeviceOrientationController.h"
56 #include "DeviceOrientationEvent.h"
57 #include "DocumentEventQueue.h"
58 #include "DocumentFragment.h"
59 #include "DocumentLoader.h"
60 #include "DocumentMarkerController.h"
61 #include "DocumentType.h"
62 #include "EditingText.h"
65 #include "ElementShadow.h"
66 #include "EntityReference.h"
68 #include "EventFactory.h"
69 #include "EventHandler.h"
70 #include "EventListener.h"
71 #include "EventNames.h"
72 #include "ExceptionCode.h"
73 #include "FlowThreadController.h"
74 #include "FocusController.h"
75 #include "FormController.h"
77 #include "FrameLoader.h"
78 #include "FrameLoaderClient.h"
79 #include "FrameSelection.h"
80 #include "FrameTree.h"
81 #include "FrameView.h"
82 #include "GeolocationController.h"
83 #include "HashChangeEvent.h"
84 #include "HistogramSupport.h"
86 #include "HTMLAllCollection.h"
87 #include "HTMLAnchorElement.h"
88 #include "HTMLBodyElement.h"
89 #include "HTMLCanvasElement.h"
90 #include "HTMLCollection.h"
91 #include "HTMLDocument.h"
92 #include "HTMLElementFactory.h"
93 #include "HTMLFrameOwnerElement.h"
94 #include "HTMLHeadElement.h"
95 #include "HTMLIFrameElement.h"
96 #include "HTMLLinkElement.h"
97 #include "HTMLMapElement.h"
98 #include "HTMLNameCollection.h"
99 #include "HTMLNames.h"
100 #include "HTMLParserIdioms.h"
101 #include "HTMLStyleElement.h"
102 #include "HTMLTitleElement.h"
103 #include "HTTPParsers.h"
104 #include "HitTestRequest.h"
105 #include "HitTestResult.h"
106 #include "ImageLoader.h"
107 #include "InspectorCounters.h"
108 #include "InspectorInstrumentation.h"
110 #include "MediaQueryList.h"
111 #include "MediaQueryMatcher.h"
112 #include "MemoryInstrumentation.h"
113 #include "MouseEventWithHitTestResults.h"
114 #include "NameNodeList.h"
115 #include "NestingLevelIncrementer.h"
116 #include "NewXMLDocumentParser.h"
117 #include "NodeFilter.h"
118 #include "NodeIterator.h"
119 #include "NodeRareData.h"
120 #include "NodeWithIndex.h"
122 #include "PageGroup.h"
123 #include "PageTransitionEvent.h"
124 #include "PlatformKeyboardEvent.h"
125 #include "PluginDocument.h"
126 #include "PointerLockController.h"
127 #include "PopStateEvent.h"
128 #include "ProcessingInstruction.h"
129 #include "RegisteredEventListener.h"
130 #include "RenderArena.h"
131 #include "RenderNamedFlowThread.h"
132 #include "RenderTextControl.h"
133 #include "RenderView.h"
134 #include "RenderWidget.h"
135 #include "SchemeRegistry.h"
136 #include "ScopedEventQueue.h"
137 #include "ScriptCallStack.h"
138 #include "ScriptController.h"
139 #include "ScriptElement.h"
140 #include "ScriptEventListener.h"
141 #include "ScriptRunner.h"
142 #include "ScrollingCoordinator.h"
143 #include "SecurityOrigin.h"
144 #include "SecurityPolicy.h"
145 #include "SegmentedString.h"
146 #include "SelectorQuery.h"
147 #include "Settings.h"
148 #include "ShadowRoot.h"
149 #include "StaticHashSetNodeList.h"
150 #include "StyleResolver.h"
151 #include "StyleSheetContents.h"
152 #include "StyleSheetList.h"
153 #include "TextResourceDecoder.h"
155 #include "TransformSource.h"
156 #include "TreeWalker.h"
157 #include "UndoManager.h"
158 #include "UserContentURLPattern.h"
159 #include "WebKitNamedFlow.h"
160 #include "WebKitNamedFlowCollection.h"
161 #include "XMLDocumentParser.h"
162 #include "XMLHttpRequest.h"
163 #include "XMLNSNames.h"
164 #include "XMLNames.h"
165 #include "XPathEvaluator.h"
166 #include "XPathExpression.h"
167 #include "XPathNSResolver.h"
168 #include "XPathResult.h"
169 #include "htmlediting.h"
170 #include <wtf/CurrentTime.h>
171 #include <wtf/HashFunctions.h>
172 #include <wtf/MainThread.h>
173 #include <wtf/PassRefPtr.h>
174 #include <wtf/StdLibExtras.h>
175 #include <wtf/text/StringBuffer.h>
177 #if ENABLE(SHARED_WORKERS)
178 #include "SharedWorkerRepository.h"
182 #include "XSLTProcessor.h"
186 #include "SVGDocumentExtensions.h"
187 #include "SVGElementFactory.h"
188 #include "SVGNames.h"
189 #include "SVGSVGElement.h"
190 #include "SVGStyleElement.h"
193 #if ENABLE(TOUCH_EVENTS)
194 #include "TouchList.h"
198 #include "MathMLElement.h"
199 #include "MathMLElementFactory.h"
200 #include "MathMLNames.h"
203 #if ENABLE(FULLSCREEN_API)
204 #include "RenderFullScreen.h"
207 #if ENABLE(REQUEST_ANIMATION_FRAME)
208 #include "RequestAnimationFrameCallback.h"
209 #include "ScriptedAnimationController.h"
212 #if ENABLE(MICRODATA)
213 #include "MicroDataItemList.h"
214 #include "NodeRareData.h"
217 #if ENABLE(LINK_PRERENDER)
218 #include "Prerenderer.h"
221 #if ENABLE(TEXT_AUTOSIZING)
222 #include "TextAutosizer.h"
227 using namespace Unicode;
231 using namespace HTMLNames;
233 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
235 static const unsigned cMaxWriteRecursionDepth = 21;
237 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
238 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
240 static const int cLayoutScheduleThreshold = 250;
242 // DOM Level 2 says (letters added):
244 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
245 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
246 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
247 // 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.
248 // 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.
249 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
250 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
251 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
252 // i) Characters ':' and '_' are allowed as name-start characters.
253 // j) Characters '-' and '.' are allowed as name characters.
255 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
257 static inline bool isValidNameStart(UChar32 c)
260 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
264 if (c == ':' || c == '_')
267 // rules (a) and (f) above
268 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
269 if (!(Unicode::category(c) & nameStartMask))
273 if (c >= 0xF900 && c < 0xFFFE)
277 DecompositionType decompType = decompositionType(c);
278 if (decompType == DecompositionFont || decompType == DecompositionCompat)
284 static inline bool isValidNamePart(UChar32 c)
286 // rules (a), (e), and (i) above
287 if (isValidNameStart(c))
290 // rules (g) and (h) above
291 if (c == 0x00B7 || c == 0x0387)
295 if (c == '-' || c == '.')
298 // rules (b) and (f) above
299 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
300 if (!(Unicode::category(c) & otherNamePartMask))
304 if (c >= 0xF900 && c < 0xFFFE)
308 DecompositionType decompType = decompositionType(c);
309 if (decompType == DecompositionFont || decompType == DecompositionCompat)
315 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
317 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
319 // If a Document has the address "about:blank"
320 // The origin of the Document is the origin it was assigned when its browsing context was created.
322 // Note: We generalize this to all "blank" URLs and invalid URLs because we
323 // treat all of these URLs as about:blank.
325 return !url.isValid() || url.isBlankURL();
328 static Widget* widgetForNode(Node* focusedNode)
332 RenderObject* renderer = focusedNode->renderer();
333 if (!renderer || !renderer->isWidget())
335 return toRenderWidget(renderer)->widget();
338 static bool acceptsEditingFocus(Node* node)
341 ASSERT(node->rendererIsEditable());
343 Node* root = node->rootEditableElement();
344 Frame* frame = node->document()->frame();
348 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
351 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
353 // targetFrame can be 0 when we're trying to navigate a top-level frame
354 // that has a 0 opener.
358 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
359 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
360 Document* ancestorDocument = ancestorFrame->document();
361 // FIXME: Should be an ASSERT? Frames should alway have documents.
362 if (!ancestorDocument)
365 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
366 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
369 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
370 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
371 // something more general instead?
372 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
379 static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL)
381 // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
382 String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
383 frame->document()->url().string() + " from frame with URL " + activeURL.string() + ".\n";
385 // FIXME: should we print to the console of the document performing the navigation instead?
386 frame->domWindow()->printErrorMessage(message);
389 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
391 class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
393 static PassRefPtr<DocumentWeakReference> create(Document* document)
395 return adoptRef(new DocumentWeakReference(document));
400 ASSERT(isMainThread());
406 ASSERT(isMainThread());
411 DocumentWeakReference(Document* document)
412 : m_document(document)
414 ASSERT(isMainThread());
417 Document* m_document;
420 uint64_t Document::s_globalTreeVersion = 0;
422 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
423 : ContainerNode(0, CreateDocument)
424 , TreeScope(this, this)
426 , m_contextFeatures(ContextFeatures::defaultSwitch())
427 , m_compatibilityMode(NoQuirksMode)
428 , m_compatibilityModeLocked(false)
429 , m_domTreeVersion(++s_globalTreeVersion)
430 #if ENABLE(MUTATION_OBSERVERS)
431 , m_mutationObserverTypes(0)
433 , m_styleSheets(StyleSheetList::create(this))
434 , m_hadActiveLoadingStylesheet(false)
435 , m_readyState(Complete)
436 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
437 , m_pendingStyleRecalcShouldForce(false)
438 , m_frameElementsShouldIgnoreScrolling(false)
439 , m_containsValidityStyleRules(false)
440 , m_updateFocusAppearanceRestoresSelection(false)
441 , m_ignoreDestructiveWriteCount(0)
442 , m_titleSetExplicitly(false)
443 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
444 , m_loadEventFinished(false)
445 , m_startTime(currentTime())
446 , m_overMinimumLayoutThreshold(false)
447 , m_scriptRunner(ScriptRunner::create(this))
448 , m_xmlVersion("1.0")
449 , m_xmlStandalone(StandaloneUnspecified)
450 , m_hasXMLDeclaration(0)
452 , m_designMode(inherit)
453 #if ENABLE(DASHBOARD_SUPPORT)
454 , m_hasDashboardRegions(false)
455 , m_dashboardRegionsDirty(false)
457 , m_createRenderers(true)
458 , m_inPageCache(false)
459 , m_accessKeyMapValid(false)
460 , m_useSecureKeyboardEntryWhenActive(false)
463 , m_isViewSource(false)
464 , m_sawElementsInKnownNamespaces(false)
465 , m_isSrcdocDocument(false)
466 , m_documentRareData(0)
467 , m_eventQueue(DocumentEventQueue::create(this))
468 , m_weakReference(DocumentWeakReference::create(this))
469 , m_idAttributeName(idAttr)
470 #if ENABLE(FULLSCREEN_API)
471 , m_areKeysEnabledInFullScreen(0)
472 , m_fullScreenRenderer(0)
473 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
474 , m_isAnimatingFullScreen(false)
476 , m_loadEventDelayCount(0)
477 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
478 , m_referrerPolicy(ReferrerPolicyDefault)
479 , m_directionSetOnDocumentElement(false)
480 , m_writingModeSetOnDocumentElement(false)
481 , m_writeRecursionIsTooDeep(false)
482 , m_writeRecursionDepth(0)
483 , m_wheelEventHandlerCount(0)
484 #if ENABLE(TOUCH_EVENTS)
485 , m_touchEventHandlerCount(0)
487 #if ENABLE(UNDO_MANAGER)
490 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
491 , m_scheduledTasksAreSuspended(false)
492 , m_visualUpdatesAllowed(true)
493 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
495 , m_didDispatchViewportPropertiesChanged(false)
500 m_pageGroupUserSheetCacheValid = false;
503 m_paginatedForScreen = false;
505 m_ignoreAutofocus = false;
509 provideContextFeaturesToDocumentFrom(this, m_frame->page());
511 // We depend on the url getting immediately set in subframes, but we
512 // also depend on the url NOT getting immediately set in opened windows.
513 // See fast/dom/early-frame-url.html
514 // and fast/dom/location-new-window-no-crash.html, respectively.
515 // FIXME: Can/should we unify this behavior?
516 if ((frame && frame->ownerElement()) || !url.isEmpty())
521 m_markers = adoptPtr(new DocumentMarkerController);
523 m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
524 #if ENABLE(LINK_PRERENDER)
525 m_prerenderer = Prerenderer::create(this);
527 #if ENABLE(TEXT_AUTOSIZING)
528 m_textAutosizer = TextAutosizer::create(this);
530 m_visuallyOrdered = false;
532 m_wellFormed = false;
534 m_textColor = Color::black;
536 m_inStyleRecalc = false;
537 m_closeAfterStyleRecalc = false;
539 m_usesSiblingRules = false;
540 m_usesSiblingRulesOverride = false;
541 m_usesFirstLineRules = false;
542 m_usesFirstLetterRules = false;
543 m_usesBeforeAfterRules = false;
544 m_usesBeforeAfterRulesOverride = false;
545 m_usesRemUnits = false;
546 m_usesLinkRules = false;
548 m_gotoAnchorNeededAfterStylesheetsLoad = false;
550 m_didCalculateStyleResolver = false;
551 m_hasDirtyStyleResolver = false;
552 m_pendingStylesheets = 0;
553 m_ignorePendingStylesheets = false;
554 m_hasNodesWithPlaceholderStyle = false;
555 m_pendingSheetLayout = NoLayoutWithPendingSheets;
560 resetVisitedLinkColor();
561 resetActiveLinkColor();
563 m_processingLoadEvent = false;
565 initSecurityContext();
568 static int docID = 0;
571 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
572 m_nodeListCounts[i] = 0;
574 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
575 m_collections[i] = 0;
577 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
580 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
582 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
583 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
584 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
585 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
586 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
587 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
590 #if ENABLE(FULLSCREEN_API)
591 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const HTMLFrameOwnerElement* owner)
596 if (!owner->hasAttribute(attribute))
598 } while ((owner = owner->document()->ownerElement()));
603 Document::~Document()
606 ASSERT(!m_inPageCache);
607 ASSERT(!m_savedRenderer);
608 ASSERT(m_ranges.isEmpty());
609 ASSERT(!m_styleRecalcTimer.isActive());
610 ASSERT(!m_parentTreeScope);
611 ASSERT(!m_guardRefCount);
613 m_scriptRunner.clear();
615 histogramMutationEventUsage(m_listenerTypes);
617 removeAllEventListeners();
619 // Currently we believe that Document can never outlive the parser.
620 // Although the Document may be replaced synchronously, DocumentParsers
621 // generally keep at least one reference to an Element which would in turn
622 // has a reference to the Document. If you hit this ASSERT, then that
623 // assumption is wrong. DocumentParser::detach() should ensure that even
624 // if the DocumentParser outlives the Document it won't cause badness.
625 ASSERT(!m_parser || m_parser->refCount() == 1);
628 m_renderArena.clear();
630 clearAXObjectCache();
635 m_styleSheets->documentDestroyed();
638 m_namedFlows->documentDestroyed();
641 m_elemSheet->clearOwnerNode();
643 m_pageUserSheet->clearOwnerNode();
644 if (m_pageGroupUserSheets) {
645 for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
646 (*m_pageGroupUserSheets)[i]->clearOwnerNode();
649 for (size_t i = 0; i < m_userSheets->size(); ++i)
650 (*m_userSheets)[i]->clearOwnerNode();
655 m_weakReference->clear();
657 if (m_mediaQueryMatcher)
658 m_mediaQueryMatcher->documentDestroyed();
660 clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
661 m_cachedResourceLoader.clear();
663 #if ENABLE(UNDO_MANAGER)
665 m_undoManager->undoScopeHostDestroyed();
668 // We must call clearRareData() here since a Document class inherits TreeScope
669 // as well as Node. See a comment on TreeScope.h for the reason.
673 ASSERT(!m_listsInvalidatedAtDocument.size());
675 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
676 ASSERT(!m_nodeListCounts[i]);
678 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
679 ASSERT(!m_collections[i]);
683 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
686 void Document::removedLastRef()
688 ASSERT(!m_deletionHasBegun);
689 if (m_guardRefCount) {
690 // If removing a child removes the last self-only ref, we don't
691 // want the scope to be destructed until after
692 // removeAllChildren returns, so we guard ourselves with an
693 // extra self-only ref.
696 // We must make sure not to be retaining any of our children through
697 // these extra pointers or we will create a reference cycle.
703 m_documentElement = 0;
704 m_contextFeatures = ContextFeatures::defaultSwitch();
705 #if ENABLE(FULLSCREEN_API)
706 m_fullScreenElement = 0;
707 m_fullScreenElementStack.clear();
712 // removeAllChildren() doesn't always unregister IDs,
713 // so tear down scope information upfront to avoid having stale references in the map.
714 destroyTreeScopeData();
719 m_cssCanvasElements.clear();
721 #if ENABLE(REQUEST_ANIMATION_FRAME)
722 // FIXME: consider using ActiveDOMObject.
723 if (m_scriptedAnimationController)
724 m_scriptedAnimationController->clearDocumentPointer();
725 m_scriptedAnimationController.clear();
729 m_inRemovedLastRefFunction = false;
735 m_deletionHasBegun = true;
741 Element* Document::getElementById(const AtomicString& id) const
743 return TreeScope::getElementById(id);
746 Element* Document::getElementByAccessKey(const String& key)
750 if (!m_accessKeyMapValid) {
751 buildAccessKeyMap(this);
752 m_accessKeyMapValid = true;
754 return m_elementsByAccessKey.get(key.impl());
757 void Document::buildAccessKeyMap(TreeScope* scope)
760 Node* rootNode = scope->rootNode();
761 for (Node* node = rootNode; node; node = node->traverseNextNode(rootNode)) {
762 if (!node->isElementNode())
764 Element* element = static_cast<Element*>(node);
765 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
766 if (!accessKey.isEmpty())
767 m_elementsByAccessKey.set(accessKey.impl(), element);
769 for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
770 buildAccessKeyMap(root);
774 void Document::invalidateAccessKeyMap()
776 m_accessKeyMapValid = false;
777 m_elementsByAccessKey.clear();
780 SelectorQueryCache* Document::selectorQueryCache()
782 if (!m_selectorQueryCache)
783 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
784 return m_selectorQueryCache.get();
787 MediaQueryMatcher* Document::mediaQueryMatcher()
789 if (!m_mediaQueryMatcher)
790 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
791 return m_mediaQueryMatcher.get();
794 void Document::setCompatibilityMode(CompatibilityMode mode)
796 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
798 ASSERT(!m_styleSheets->length());
799 bool wasInQuirksMode = inQuirksMode();
800 m_compatibilityMode = mode;
801 selectorQueryCache()->invalidate();
802 if (inQuirksMode() != wasInQuirksMode) {
803 // All user stylesheets have to reparse using the different mode.
804 clearPageUserSheet();
805 clearPageGroupUserSheets();
809 String Document::compatMode() const
811 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
814 void Document::resetLinkColor()
816 m_linkColor = Color(0, 0, 238);
819 void Document::resetVisitedLinkColor()
821 m_visitedLinkColor = Color(85, 26, 139);
824 void Document::resetActiveLinkColor()
826 m_activeLinkColor.setNamedColor("red");
829 void Document::setDocType(PassRefPtr<DocumentType> docType)
831 // This should never be called more than once.
832 ASSERT(!m_docType || !docType);
835 this->adoptIfNeeded(m_docType.get());
836 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
837 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
838 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
841 // Doctype affects the interpretation of the stylesheets.
842 clearStyleResolver();
845 DOMImplementation* Document::implementation()
847 if (!m_implementation)
848 m_implementation = DOMImplementation::create(this);
849 return m_implementation.get();
852 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
854 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
856 Element* newDocumentElement = firstElementChild(this);
857 if (newDocumentElement == m_documentElement)
859 m_documentElement = newDocumentElement;
860 // The root style used for media query matching depends on the document element.
861 clearStyleResolver();
864 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
866 if (!isValidName(name)) {
867 ec = INVALID_CHARACTER_ERR;
872 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
874 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
877 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
879 return DocumentFragment::create(document());
882 PassRefPtr<Text> Document::createTextNode(const String& data)
884 return Text::create(this, data);
887 PassRefPtr<Comment> Document::createComment(const String& data)
889 return Comment::create(this, data);
892 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
894 if (isHTMLDocument()) {
895 ec = NOT_SUPPORTED_ERR;
898 return CDATASection::create(this, data);
901 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
903 if (!isValidName(target)) {
904 ec = INVALID_CHARACTER_ERR;
907 if (isHTMLDocument()) {
908 ec = NOT_SUPPORTED_ERR;
911 return ProcessingInstruction::create(this, target, data);
914 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
916 if (!isValidName(name)) {
917 ec = INVALID_CHARACTER_ERR;
920 if (isHTMLDocument()) {
921 ec = NOT_SUPPORTED_ERR;
924 return EntityReference::create(this, name);
927 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
929 return EditingText::create(this, text);
932 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
934 return StylePropertySet::create()->ensureCSSStyleDeclaration();
937 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
942 ec = NOT_SUPPORTED_ERR;
946 switch (importedNode->nodeType()) {
948 return createTextNode(importedNode->nodeValue());
949 case CDATA_SECTION_NODE:
950 return createCDATASection(importedNode->nodeValue(), ec);
951 case ENTITY_REFERENCE_NODE:
952 return createEntityReference(importedNode->nodeName(), ec);
953 case PROCESSING_INSTRUCTION_NODE:
954 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
956 return createComment(importedNode->nodeValue());
958 Element* oldElement = static_cast<Element*>(importedNode);
959 // FIXME: The following check might be unnecessary. Is it possible that
960 // oldElement has mismatched prefix/namespace?
961 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
965 RefPtr<Element> newElement = createElement(oldElement->tagQName(), ec);
969 newElement->cloneDataFromElement(*oldElement);
972 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
973 RefPtr<Node> newChild = importNode(oldChild, true, ec);
976 newElement->appendChild(newChild.release(), ec);
982 return newElement.release();
985 return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
986 case DOCUMENT_FRAGMENT_NODE: {
987 if (importedNode->isShadowRoot()) {
988 // ShadowRoot nodes should not be explicitly importable.
989 // Either they are imported along with their host node, or created implicitly.
992 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
993 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
995 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
996 RefPtr<Node> newChild = importNode(oldChild, true, ec);
999 newFragment->appendChild(newChild.release(), ec);
1005 return newFragment.release();
1009 // 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.
1010 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
1012 case DOCUMENT_TYPE_NODE:
1013 case XPATH_NAMESPACE_NODE:
1016 ec = NOT_SUPPORTED_ERR;
1021 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1024 ec = NOT_SUPPORTED_ERR;
1028 if (source->isReadOnlyNode()) {
1029 ec = NO_MODIFICATION_ALLOWED_ERR;
1033 EventQueueScope scope;
1035 switch (source->nodeType()) {
1039 case DOCUMENT_TYPE_NODE:
1040 case XPATH_NAMESPACE_NODE:
1041 ec = NOT_SUPPORTED_ERR;
1043 case ATTRIBUTE_NODE: {
1044 Attr* attr = static_cast<Attr*>(source.get());
1045 if (attr->ownerElement())
1046 attr->ownerElement()->removeAttributeNode(attr, ec);
1047 attr->setSpecified(true);
1051 if (source->isShadowRoot()) {
1052 // ShadowRoot cannot disconnect itself from the host node.
1053 ec = HIERARCHY_REQUEST_ERR;
1057 // FIXME: What about <frame> and <object>?
1058 if (source->hasTagName(iframeTag)) {
1059 HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
1060 if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
1061 ec = HIERARCHY_REQUEST_ERR;
1065 if (source->parentNode())
1066 source->parentNode()->removeChild(source.get(), ec);
1069 this->adoptIfNeeded(source.get());
1074 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1076 // These checks are from DOM Core Level 2, createElementNS
1077 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1078 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1080 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1083 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1084 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1085 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1086 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1092 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1094 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1095 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1096 // Note: The case of an "xmlns" qualified name with a namespace of
1097 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1098 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1100 return hasValidNamespaceForElements(qName);
1103 // FIXME: This should really be in a possible ElementFactory class
1104 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1108 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1109 if (qName.namespaceURI() == xhtmlNamespaceURI)
1110 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
1112 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1113 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
1116 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1117 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
1121 m_sawElementsInKnownNamespaces = true;
1123 e = Element::create(qName, document());
1125 // <image> uses imgTag so we need a special rule.
1126 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
1131 bool Document::regionBasedColumnsEnabled() const
1133 return settings() && settings()->regionBasedColumnsEnabled();
1136 bool Document::cssRegionsEnabled() const
1138 return settings() && settings()->cssRegionsEnabled();
1141 bool Document::cssGridLayoutEnabled() const
1143 return settings() && settings()->cssGridLayoutEnabled();
1146 #if ENABLE(CSS_REGIONS)
1148 PassRefPtr<WebKitNamedFlow> Document::webkitGetFlowByName(const String& flowName)
1150 if (!cssRegionsEnabled() || !renderer())
1153 // It's possible to have pending styles not applied that affect the existing flows.
1154 updateStyleIfNeeded();
1156 return namedFlows()->flowByName(flowName);
1160 WebKitNamedFlowCollection* Document::namedFlows()
1163 m_namedFlows = WebKitNamedFlowCollection::create(this);
1165 return m_namedFlows.get();
1168 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1170 String prefix, localName;
1171 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1174 QualifiedName qName(prefix, localName, namespaceURI);
1175 if (!hasValidNamespaceForElements(qName)) {
1180 return createElement(qName, false);
1183 String Document::readyState() const
1185 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1186 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1187 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1189 switch (m_readyState) {
1198 ASSERT_NOT_REACHED();
1202 void Document::setReadyState(ReadyState readyState)
1204 if (readyState == m_readyState)
1207 switch (readyState) {
1209 if (!m_documentTiming.domLoading)
1210 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1213 if (!m_documentTiming.domInteractive)
1214 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1217 if (!m_documentTiming.domComplete)
1218 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1222 m_readyState = readyState;
1223 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1225 if (settings() && settings()->suppressesIncrementalRendering())
1226 setVisualUpdatesAllowed(readyState);
1229 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1231 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1232 switch (readyState) {
1234 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1235 ASSERT(m_visualUpdatesAllowed);
1236 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1237 setVisualUpdatesAllowed(false);
1240 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1243 if (m_visualUpdatesSuppressionTimer.isActive()) {
1244 ASSERT(!m_visualUpdatesAllowed);
1245 m_visualUpdatesSuppressionTimer.stop();
1246 setVisualUpdatesAllowed(true);
1248 ASSERT(m_visualUpdatesAllowed);
1253 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1255 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1258 m_visualUpdatesAllowed = visualUpdatesAllowed;
1260 if (!visualUpdatesAllowed)
1263 #if USE(ACCELERATED_COMPOSITING)
1265 view()->updateCompositingLayersAfterLayout();
1269 renderer()->repaint();
1272 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1274 ASSERT(!m_visualUpdatesAllowed);
1275 setVisualUpdatesAllowed(true);
1278 String Document::encoding() const
1280 if (TextResourceDecoder* d = decoder())
1281 return d->encoding().domName();
1285 String Document::defaultCharset() const
1287 if (Settings* settings = this->settings())
1288 return settings->defaultTextEncodingName();
1292 void Document::setCharset(const String& charset)
1296 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1299 void Document::setContentLanguage(const String& language)
1301 if (m_contentLanguage == language)
1303 m_contentLanguage = language;
1305 // Recalculate style so language is used when selecting the initial font.
1306 styleResolverChanged(DeferRecalcStyle);
1309 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1311 if (!implementation()->hasFeature("XML", String())) {
1312 ec = NOT_SUPPORTED_ERR;
1316 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1317 ec = NOT_SUPPORTED_ERR;
1321 m_xmlVersion = version;
1324 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1326 if (!implementation()->hasFeature("XML", String())) {
1327 ec = NOT_SUPPORTED_ERR;
1331 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1334 void Document::setDocumentURI(const String& uri)
1336 // This property is read-only from JavaScript, but writable from Objective-C.
1337 m_documentURI = uri;
1341 KURL Document::baseURI() const
1346 void Document::setContent(const String& content)
1349 m_parser->append(content);
1353 String Document::suggestedMIMEType() const
1355 Document* doc = document();
1356 if (doc->isXHTMLDocument())
1357 return "application/xhtml+xml";
1358 if (doc->isSVGDocument())
1359 return "image/svg+xml";
1360 if (doc->xmlStandalone())
1362 if (doc->isHTMLDocument())
1365 if (DocumentLoader* documentLoader = loader())
1366 return documentLoader->responseMIMEType();
1370 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1371 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1372 // * making it receive the expading size of each direction separately,
1373 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1374 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
1376 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1379 Frame* frame = this->frame();
1382 FrameView* frameView = frame->view();
1386 float zoomFactor = frame->pageZoomFactor();
1387 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1389 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1391 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1393 type |= HitTestRequest::IgnoreClipping;
1394 else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1397 HitTestRequest request(type);
1399 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1400 // we special handle this case in order to return a valid NodeList.
1401 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1402 HitTestResult result(point);
1403 return handleZeroPadding(request, result);
1406 enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
1407 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding, shadowContentFilterPolicy);
1408 renderView()->hitTest(request, result);
1410 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1413 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1415 renderView()->hitTest(request, result);
1417 Node* node = result.innerNode();
1421 node = node->shadowAncestorNode();
1422 ListHashSet<RefPtr<Node> > list;
1424 return StaticHashSetNodeList::adopt(list);
1427 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1431 FrameView* frameView = frame->view();
1435 float zoomFactor = frame->pageZoomFactor();
1436 IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1438 if (!frameView->visibleContentRect().contains(point))
1441 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1442 HitTestResult result(point);
1443 renderView->hitTest(request, result);
1446 *localPoint = result.localPoint();
1448 return result.innerNode();
1451 Element* Document::elementFromPoint(int x, int y) const
1455 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1456 while (node && !node->isElementNode())
1457 node = node->parentNode();
1459 node = ancestorInThisScope(node);
1460 return static_cast<Element*>(node);
1463 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1467 LayoutPoint localPoint;
1468 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1472 Node* shadowAncestorNode = ancestorInThisScope(node);
1473 if (shadowAncestorNode != node) {
1474 unsigned offset = shadowAncestorNode->nodeIndex();
1475 ContainerNode* container = shadowAncestorNode->parentNode();
1476 return Range::create(this, container, offset, container, offset);
1479 RenderObject* renderer = node->renderer();
1482 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1483 if (visiblePosition.isNull())
1486 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1487 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1491 * Performs three operations:
1492 * 1. Convert control characters to spaces
1493 * 2. Trim leading and trailing spaces
1494 * 3. Collapse internal whitespace.
1496 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1498 const String& title = titleWithDirection.string();
1499 const UChar* characters = title.characters();
1500 unsigned length = title.length();
1503 StringBuffer<UChar> buffer(length);
1504 unsigned builderIndex = 0;
1506 // Skip leading spaces and leading characters that would convert to spaces
1507 for (i = 0; i < length; ++i) {
1508 UChar c = characters[i];
1509 if (!(c <= 0x20 || c == 0x7F))
1514 return StringWithDirection();
1516 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1517 bool previousCharWasWS = false;
1518 for (; i < length; ++i) {
1519 UChar c = characters[i];
1520 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1521 if (previousCharWasWS)
1523 buffer[builderIndex++] = ' ';
1524 previousCharWasWS = true;
1526 buffer[builderIndex++] = c;
1527 previousCharWasWS = false;
1531 // Strip trailing spaces
1532 while (builderIndex > 0) {
1534 if (buffer[builderIndex] != ' ')
1538 if (!builderIndex && buffer[builderIndex] == ' ')
1539 return StringWithDirection();
1541 buffer.shrink(builderIndex + 1);
1543 // Replace the backslashes with currency symbols if the encoding requires it.
1544 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1546 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1549 void Document::updateTitle(const StringWithDirection& title)
1551 if (m_rawTitle == title)
1555 m_title = canonicalizedTitle(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 visible i.e. invisibility has to be explicitly
1625 // specified by the embedder.
1626 if (!m_frame || !m_frame->page())
1627 return PageVisibilityStateVisible;
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 String Document::nodeName() const
1652 Node::NodeType Document::nodeType() const
1654 return DOCUMENT_NODE;
1657 FormController* Document::formController()
1659 if (!m_formController)
1660 m_formController = FormController::create();
1661 return m_formController.get();
1664 Vector<String> Document::formElementsState() const
1666 if (!m_formController)
1667 return Vector<String>();
1668 return m_formController->formElementsState();
1671 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1673 if (!stateVector.size() && !m_formController)
1675 formController()->setStateForNewFormElements(stateVector);
1678 FrameView* Document::view() const
1680 return m_frame ? m_frame->view() : 0;
1683 Page* Document::page() const
1685 return m_frame ? m_frame->page() : 0;
1688 Settings* Document::settings() const
1690 return m_frame ? m_frame->settings() : 0;
1693 PassRefPtr<Range> Document::createRange()
1695 return Range::create(this);
1698 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1699 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1702 ec = NOT_SUPPORTED_ERR;
1705 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1708 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1709 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1712 ec = NOT_SUPPORTED_ERR;
1715 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1718 void Document::scheduleForcedStyleRecalc()
1720 m_pendingStyleRecalcShouldForce = true;
1721 scheduleStyleRecalc();
1724 void Document::scheduleStyleRecalc()
1726 if (shouldDisplaySeamlesslyWithParent()) {
1727 // When we're seamless, our parent document manages our style recalcs.
1728 ownerElement()->setNeedsStyleRecalc();
1729 ownerElement()->document()->scheduleStyleRecalc();
1733 if (m_styleRecalcTimer.isActive() || inPageCache())
1736 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1738 if (!documentsThatNeedStyleRecalc)
1739 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1740 documentsThatNeedStyleRecalc->add(this);
1742 // FIXME: Why on earth is this here? This is clearly misplaced.
1743 invalidateAccessKeyMap();
1745 m_styleRecalcTimer.startOneShot(0);
1747 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1750 void Document::unscheduleStyleRecalc()
1752 ASSERT(!childNeedsStyleRecalc());
1754 if (documentsThatNeedStyleRecalc)
1755 documentsThatNeedStyleRecalc->remove(this);
1757 m_styleRecalcTimer.stop();
1758 m_pendingStyleRecalcShouldForce = false;
1761 bool Document::isPendingStyleRecalc() const
1763 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1766 void Document::styleRecalcTimerFired(Timer<Document>*)
1768 updateStyleIfNeeded();
1771 bool Document::childNeedsAndNotInStyleRecalc()
1773 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1776 void Document::recalcStyle(StyleChange change)
1778 // we should not enter style recalc while painting
1779 if (view() && view()->isPainting()) {
1780 ASSERT(!view()->isPainting());
1784 if (m_inStyleRecalc)
1785 return; // Guard against re-entrancy. -dwh
1787 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1788 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1789 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1790 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1791 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1792 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1794 if (m_hasDirtyStyleResolver)
1795 updateActiveStylesheets(RecalcStyleImmediately);
1797 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1799 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1800 m_usesRemUnits = true;
1802 m_inStyleRecalc = true;
1803 suspendPostAttachCallbacks();
1804 RenderWidget::suspendWidgetHierarchyUpdates();
1806 RefPtr<FrameView> frameView = view();
1808 frameView->pauseScheduledEvents();
1809 frameView->beginDeferredRepaints();
1812 ASSERT(!renderer() || renderArena());
1813 if (!renderer() || !renderArena())
1816 if (m_pendingStyleRecalcShouldForce)
1819 // Recalculating the root style (on the document) is not needed in the common case.
1820 if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
1821 // style selector may set this again during recalc
1822 m_hasNodesWithPlaceholderStyle = false;
1824 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
1825 StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
1827 renderer()->setStyle(documentStyle.release());
1830 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1831 if (!n->isElementNode())
1833 Element* element = static_cast<Element*>(n);
1834 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1835 element->recalcStyle(change);
1838 #if USE(ACCELERATED_COMPOSITING)
1840 bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1841 // If we didn't update compositing layers because of layout(), we need to do so here.
1843 view()->updateCompositingLayersAfterStyleChange();
1848 clearNeedsStyleRecalc();
1849 clearChildNeedsStyleRecalc();
1850 unscheduleStyleRecalc();
1852 m_inStyleRecalc = false;
1854 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1855 if (m_styleResolver)
1856 resetCSSFeatureFlags();
1859 frameView->resumeScheduledEvents();
1860 frameView->endDeferredRepaints();
1862 RenderWidget::resumeWidgetHierarchyUpdates();
1863 resumePostAttachCallbacks();
1865 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1866 if (m_closeAfterStyleRecalc) {
1867 m_closeAfterStyleRecalc = false;
1871 InspectorInstrumentation::didRecalculateStyle(cookie);
1874 void Document::updateStyleIfNeeded()
1876 ASSERT(isMainThread());
1877 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1879 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1882 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
1883 recalcStyle(NoChange);
1886 void Document::updateStyleForAllDocuments()
1888 ASSERT(isMainThread());
1889 if (!documentsThatNeedStyleRecalc)
1892 while (documentsThatNeedStyleRecalc->size()) {
1893 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1894 Document* doc = *it;
1895 documentsThatNeedStyleRecalc->remove(doc);
1896 doc->updateStyleIfNeeded();
1900 void Document::updateLayout()
1902 ASSERT(isMainThread());
1903 if (Element* oe = ownerElement())
1904 oe->document()->updateLayout();
1906 updateStyleIfNeeded();
1908 // Only do a layout if changes have occurred that make it necessary.
1909 FrameView* v = view();
1910 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1914 // FIXME: This is a bad idea and needs to be removed eventually.
1915 // Other browsers load stylesheets before they continue parsing the web page.
1916 // Since we don't, we can run JavaScript code that needs answers before the
1917 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1918 // lets us get reasonable answers. The long term solution to this problem is
1919 // to instead suspend JavaScript execution.
1920 void Document::updateLayoutIgnorePendingStylesheets()
1922 bool oldIgnore = m_ignorePendingStylesheets;
1924 if (!haveStylesheetsLoaded()) {
1925 m_ignorePendingStylesheets = true;
1926 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1927 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1928 // with accurate style information. (Our suppression involves blanking the whole page at the
1929 // moment. If it were more refined, we might be able to do something better.)
1930 // It's worth noting though that this entire method is a hack, since what we really want to do is
1931 // suspend JS instead of doing a layout with inaccurate information.
1932 HTMLElement* bodyElement = body();
1933 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1934 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1935 styleResolverChanged(RecalcStyleImmediately);
1936 } else if (m_hasNodesWithPlaceholderStyle)
1937 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1938 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1939 // but here we need up-to-date style immediately.
1945 m_ignorePendingStylesheets = oldIgnore;
1948 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1950 ASSERT_ARG(element, element->document() == this);
1952 bool oldIgnore = m_ignorePendingStylesheets;
1953 m_ignorePendingStylesheets = true;
1954 RefPtr<RenderStyle> style = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1955 m_ignorePendingStylesheets = oldIgnore;
1956 return style.release();
1959 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1961 RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
1962 return style.release();
1965 void Document::registerCustomFont(PassOwnPtr<FontData> fontData)
1967 m_customFonts.append(fontData);
1970 void Document::deleteCustomFonts()
1972 size_t size = m_customFonts.size();
1973 for (size_t i = 0; i < size; ++i)
1974 GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
1976 m_customFonts.clear();
1979 bool Document::isPageBoxVisible(int pageIndex)
1981 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1982 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1985 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1987 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1988 RenderView* view = renderView();
1990 int width = pageSize.width();
1991 int height = pageSize.height();
1992 switch (style->pageSizeType()) {
1993 case PAGE_SIZE_AUTO:
1995 case PAGE_SIZE_AUTO_LANDSCAPE:
1997 std::swap(width, height);
1999 case PAGE_SIZE_AUTO_PORTRAIT:
2001 std::swap(width, height);
2003 case PAGE_SIZE_RESOLVED: {
2004 LengthSize size = style->pageSize();
2005 ASSERT(size.width().isFixed());
2006 ASSERT(size.height().isFixed());
2007 width = valueForLength(size.width(), 0, view);
2008 height = valueForLength(size.height(), 0, view);
2012 ASSERT_NOT_REACHED();
2014 pageSize = IntSize(width, height);
2016 // The percentage is calculated with respect to the width even for margin top and bottom.
2017 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2018 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
2019 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
2020 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
2021 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
2024 void Document::setDocumentRareData(NodeRareData* rareData)
2026 m_documentRareData = rareData;
2029 void Document::setIsViewSource(bool isViewSource)
2031 m_isViewSource = isViewSource;
2032 if (!m_isViewSource)
2035 setSecurityOrigin(SecurityOrigin::createUnique());
2038 void Document::combineCSSFeatureFlags()
2040 // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
2041 m_usesSiblingRules = m_usesSiblingRules || m_styleResolver->usesSiblingRules();
2042 m_usesFirstLineRules = m_usesFirstLineRules || m_styleResolver->usesFirstLineRules();
2043 m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleResolver->usesBeforeAfterRules();
2044 m_usesLinkRules = m_usesLinkRules || m_styleResolver->usesLinkRules();
2047 void Document::resetCSSFeatureFlags()
2049 m_usesSiblingRules = m_styleResolver->usesSiblingRules();
2050 m_usesFirstLineRules = m_styleResolver->usesFirstLineRules();
2051 m_usesBeforeAfterRules = m_styleResolver->usesBeforeAfterRules();
2052 m_usesLinkRules = m_styleResolver->usesLinkRules();
2055 void Document::createStyleResolver()
2057 bool matchAuthorAndUserStyles = true;
2058 if (Settings* docSettings = settings())
2059 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
2060 m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
2061 combineCSSFeatureFlags();
2064 inline void Document::clearStyleResolver()
2066 m_styleResolver.clear();
2069 void Document::attach()
2071 ASSERT(!attached());
2072 ASSERT(!m_inPageCache);
2073 ASSERT(!m_axObjectCache || this != topDocument());
2076 m_renderArena = adoptPtr(new RenderArena);
2078 // Create the rendering tree
2079 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
2080 #if USE(ACCELERATED_COMPOSITING)
2081 renderView()->didMoveOnscreen();
2086 RenderObject* render = renderer();
2089 ContainerNode::attach();
2091 setRenderer(render);
2094 void Document::detach()
2097 ASSERT(!m_inPageCache);
2099 #if ENABLE(POINTER_LOCK)
2101 page()->pointerLockController()->documentDetached(this);
2104 if (this == topDocument())
2105 clearAXObjectCache();
2107 stopActiveDOMObjects();
2108 m_eventQueue->close();
2109 #if ENABLE(FULLSCREEN_API)
2110 m_fullScreenChangeEventTargetQueue.clear();
2111 m_fullScreenErrorEventTargetQueue.clear();
2114 #if ENABLE(REQUEST_ANIMATION_FRAME)
2115 // FIXME: consider using ActiveDOMObject.
2116 if (m_scriptedAnimationController)
2117 m_scriptedAnimationController->clearDocumentPointer();
2118 m_scriptedAnimationController.clear();
2121 RenderObject* render = renderer();
2123 documentWillBecomeInactive();
2125 #if ENABLE(SHARED_WORKERS)
2126 SharedWorkerRepository::documentDetached(this);
2130 FrameView* view = m_frame->view();
2132 view->detachCustomScrollbars();
2136 // indicate destruction mode, i.e. attached() but renderer == 0
2139 #if ENABLE(FULLSCREEN_API)
2140 if (m_fullScreenRenderer)
2141 setFullScreenRenderer(0);
2148 ContainerNode::detach();
2150 unscheduleStyleRecalc();
2155 // This is required, as our Frame might delete itself as soon as it detaches
2156 // us. However, this violates Node::detach() semantics, as it's never
2157 // possible to re-attach. Eventually Document::detach() should be renamed,
2158 // or this setting of the frame to 0 could be made explicit in each of the
2159 // callers of Document::detach().
2161 m_renderArena.clear();
2164 void Document::prepareForDestruction()
2166 disconnectDescendantFrames();
2167 if (DOMWindow* window = this->domWindow())
2168 window->willDetachDocumentFromFrame();
2172 void Document::removeAllEventListeners()
2174 EventTarget::removeAllEventListeners();
2176 if (DOMWindow* domWindow = this->domWindow())
2177 domWindow->removeAllEventListeners();
2178 for (Node* node = firstChild(); node; node = node->traverseNextNode())
2179 node->removeAllEventListeners();
2182 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2184 ScriptExecutionContext::suspendActiveDOMObjects(why);
2186 #if ENABLE(DEVICE_ORIENTATION)
2190 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2191 controller->suspendEventsForAllListeners(domWindow());
2192 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2193 controller->suspendEventsForAllListeners(domWindow());
2198 void Document::resumeActiveDOMObjects()
2200 ScriptExecutionContext::resumeActiveDOMObjects();
2202 #if ENABLE(DEVICE_ORIENTATION)
2206 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2207 controller->resumeEventsForAllListeners(domWindow());
2208 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2209 controller->resumeEventsForAllListeners(domWindow());
2213 RenderView* Document::renderView() const
2215 return toRenderView(renderer());
2218 void Document::clearAXObjectCache()
2220 // clear cache in top document
2221 if (m_axObjectCache) {
2222 // Clear the cache member variable before calling delete because attempts
2223 // are made to access it during destruction.
2224 AXObjectCache* axObjectCache = m_axObjectCache;
2225 m_axObjectCache = 0;
2226 delete axObjectCache;
2230 // ask the top-level document to clear its cache
2231 Document* doc = topDocument();
2233 doc->clearAXObjectCache();
2236 bool Document::axObjectCacheExists() const
2238 if (m_axObjectCache)
2241 Document* doc = topDocument();
2243 return doc->axObjectCacheExists();
2248 AXObjectCache* Document::axObjectCache() const
2250 // The only document that actually has a AXObjectCache is the top-level
2251 // document. This is because we need to be able to get from any WebCoreAXObject
2252 // to any other WebCoreAXObject on the same page. Using a single cache allows
2253 // lookups across nested webareas (i.e. multiple documents).
2255 if (m_axObjectCache) {
2256 // return already known top-level cache
2257 if (!ownerElement())
2258 return m_axObjectCache;
2260 // In some pages with frames, the cache is created before the sub-webarea is
2261 // inserted into the tree. Here, we catch that case and just toss the old
2262 // cache and start over.
2263 // NOTE: This recovery may no longer be needed. I have been unable to trigger
2264 // it again. See rdar://5794454
2265 // FIXME: Can this be fixed when inserting the subframe instead of now?
2266 // FIXME: If this function was called to get the cache in order to remove
2267 // an AXObject, we are now deleting the cache as a whole and returning a
2268 // new empty cache that does not contain the AXObject! That should actually
2269 // be OK. I am concerned about other cases like this where accessing the
2270 // cache blows away the AXObject being operated on.
2271 delete m_axObjectCache;
2272 m_axObjectCache = 0;
2275 // ask the top-level document for its cache
2276 Document* doc = topDocument();
2278 return doc->axObjectCache();
2280 // this is the top-level document, so install a new cache
2281 m_axObjectCache = new AXObjectCache(this);
2282 return m_axObjectCache;
2285 void Document::setVisuallyOrdered()
2287 m_visuallyOrdered = true;
2289 renderer()->style()->setRTLOrdering(VisualOrder);
2292 PassRefPtr<DocumentParser> Document::createParser()
2294 // FIXME: this should probably pass the frame instead
2296 return NewXMLDocumentParser::create(this);
2298 return XMLDocumentParser::create(this, view());
2302 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2304 return parser() ? parser()->asScriptableDocumentParser() : 0;
2307 void Document::open(Document* ownerDocument)
2309 if (ownerDocument) {
2310 setURL(ownerDocument->url());
2311 m_cookieURL = ownerDocument->cookieURL();
2312 setSecurityOrigin(ownerDocument->securityOrigin());
2316 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2317 if (parser->isParsing()) {
2318 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2319 if (parser->isExecutingScript())
2322 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2327 if (m_frame->loader()->state() == FrameStateProvisional)
2328 m_frame->loader()->stopAllLoaders();
2331 removeAllEventListeners();
2333 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2334 parser->setWasCreatedByScript(true);
2336 if (DOMWindow* domWindow = this->domWindow())
2337 domWindow->removeAllEventListeners();
2340 m_frame->loader()->didExplicitOpen();
2343 void Document::detachParser()
2351 void Document::cancelParsing()
2356 // We have to clear the parser to avoid possibly triggering
2357 // the onload handler when closing as a side effect of a cancel-style
2358 // change, such as opening a new document or closing the window while
2364 void Document::implicitOpen()
2370 setCompatibilityMode(NoQuirksMode);
2372 m_parser = createParser();
2374 setReadyState(Loading);
2377 HTMLElement* Document::body() const
2379 Node* de = documentElement();
2383 // try to prefer a FRAMESET element over BODY
2385 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2386 if (i->hasTagName(framesetTag))
2387 return toHTMLElement(i);
2389 if (i->hasTagName(bodyTag) && !body)
2392 return toHTMLElement(body);
2395 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2397 RefPtr<HTMLElement> newBody = prpNewBody;
2399 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2400 ec = HIERARCHY_REQUEST_ERR;
2404 if (newBody->document() && newBody->document() != this) {
2406 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2410 newBody = toHTMLElement(node.get());
2413 HTMLElement* b = body();
2415 documentElement()->appendChild(newBody.release(), ec);
2417 documentElement()->replaceChild(newBody.release(), b, ec);
2420 HTMLHeadElement* Document::head()
2422 Node* de = documentElement();
2426 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2427 if (e->hasTagName(headTag))
2428 return static_cast<HTMLHeadElement*>(e);
2433 void Document::close()
2435 // FIXME: We should follow the specification more closely:
2436 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2438 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2444 void Document::explicitClose()
2450 // Because we have no frame, we don't know if all loading has completed,
2451 // so we just call implicitClose() immediately. FIXME: This might fire
2452 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2457 m_frame->loader()->checkCompleted();
2460 void Document::implicitClose()
2462 // 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.
2463 if (m_inStyleRecalc) {
2464 m_closeAfterStyleRecalc = true;
2468 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2469 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2474 m_processingLoadEvent = true;
2476 ScriptableDocumentParser* parser = scriptableDocumentParser();
2477 m_wellFormed = parser && parser->wellFormed();
2479 // We have to clear the parser, in case someone document.write()s from the
2480 // onLoad event handler, as in Radar 3206524.
2483 // Parser should have picked up all preloads by now
2484 m_cachedResourceLoader->clearPreloads();
2486 // FIXME: We kick off the icon loader when the Document is done parsing.
2487 // There are earlier opportunities we could start it:
2488 // -When the <head> finishes parsing
2489 // -When any new HTMLLinkElement is inserted into the document
2490 // But those add a dynamic component to the favicon that has UI
2491 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2494 f->loader()->icon()->startLoader();
2495 f->animation()->resumeAnimationsForDocument(this);
2498 ImageLoader::dispatchPendingBeforeLoadEvents();
2499 ImageLoader::dispatchPendingLoadEvents();
2500 ImageLoader::dispatchPendingErrorEvents();
2502 HTMLLinkElement::dispatchPendingLoadEvents();
2503 HTMLStyleElement::dispatchPendingLoadEvents();
2506 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2507 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2508 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2509 if (svgExtensions())
2510 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2513 dispatchWindowLoadEvent();
2514 enqueuePageshowEvent(PageshowEventNotPersisted);
2515 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2518 f->loader()->handledOnloadEvents();
2519 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2520 if (!ownerElement())
2521 printf("onload fired at %d\n", elapsedTime());
2524 // An event handler may have removed the frame
2526 m_processingLoadEvent = false;
2530 // Make sure both the initial layout and reflow happen after the onload
2531 // fires. This will improve onload scores, and other browsers do it.
2532 // If they wanna cheat, we can too. -dwh
2534 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2535 // Just bail out. Before or during the onload we were shifted to another page.
2536 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2537 m_processingLoadEvent = false;
2538 view()->unscheduleRelayout();
2542 frame()->loader()->checkCallImplicitClose();
2543 RenderObject* renderObject = renderer();
2545 // We used to force a synchronous display and flush here. This really isn't
2546 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2547 // (if your platform is syncing flushes and limiting them to 60fps).
2548 m_overMinimumLayoutThreshold = true;
2549 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2550 updateStyleIfNeeded();
2552 // Always do a layout after loading if needed.
2553 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2557 m_processingLoadEvent = false;
2559 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2560 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2561 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2562 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2563 // exists in the cache (we ignore the return value because we don't need it here). This is
2564 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2565 axObjectCache()->getOrCreate(renderObject);
2566 if (this == topDocument())
2567 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2569 // AXLoadComplete can only be posted on the top document, so if it's a document
2570 // in an iframe that just finished loading, post AXLayoutComplete instead.
2571 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
2577 if (svgExtensions())
2578 accessSVGExtensions()->startAnimations();
2582 void Document::setParsing(bool b)
2585 if (!m_bParsing && view())
2586 view()->scheduleRelayout();
2588 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2589 if (!ownerElement() && !m_bParsing)
2590 printf("Parsing finished at %d\n", elapsedTime());
2594 bool Document::shouldScheduleLayout()
2596 // This function will only be called when FrameView thinks a layout is needed.
2597 // This enforces a couple extra rules.
2599 // (a) Only schedule a layout once the stylesheets are loaded.
2600 // (b) Only schedule layout once we have a body element.
2602 return (haveStylesheetsLoaded() && body())
2603 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2606 bool Document::isLayoutTimerActive()
2608 return view() && view()->layoutPending() && !minimumLayoutDelay();
2611 int Document::minimumLayoutDelay()
2613 if (m_overMinimumLayoutThreshold)
2616 int elapsed = elapsedTime();
2617 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2619 // We'll want to schedule the timer to fire at the minimum layout threshold.
2620 return max(0, cLayoutScheduleThreshold - elapsed);
2623 int Document::elapsedTime() const
2625 return static_cast<int>((currentTime() - m_startTime) * 1000);
2628 void Document::write(const SegmentedString& text, Document* ownerDocument)
2630 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2632 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2633 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2635 if (m_writeRecursionIsTooDeep)
2638 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2639 if (!ownerElement())
2640 printf("Beginning a document.write at %d\n", elapsedTime());
2643 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2644 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2647 if (!hasInsertionPoint)
2648 open(ownerDocument);
2651 m_parser->insert(text);
2653 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2654 if (!ownerElement())
2655 printf("Ending a document.write at %d\n", elapsedTime());
2659 void Document::write(const String& text, Document* ownerDocument)
2661 write(SegmentedString(text), ownerDocument);
2664 void Document::writeln(const String& text, Document* ownerDocument)
2666 write(text, ownerDocument);
2667 write("\n", ownerDocument);
2670 const KURL& Document::virtualURL() const
2675 KURL Document::virtualCompleteURL(const String& url) const
2677 return completeURL(url);
2680 double Document::minimumTimerInterval() const
2684 return ScriptExecutionContext::minimumTimerInterval();
2685 return p->settings()->minDOMTimerInterval();
2688 EventTarget* Document::errorEventTarget()
2693 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
2695 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
2698 void Document::setURL(const KURL& url)
2700 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2701 if (newURL == m_url)
2705 m_documentURI = m_url.string();
2707 contextFeatures()->urlDidChange(this);
2710 void Document::updateBaseURL()
2712 KURL oldBaseURL = m_baseURL;
2713 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2714 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2715 // from the Document interface otherwise.
2716 if (!m_baseElementURL.isEmpty())
2717 m_baseURL = m_baseElementURL;
2718 else if (!m_baseURLOverride.isEmpty())
2719 m_baseURL = m_baseURLOverride;
2721 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2722 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2723 // and DOM 3 Core does not specify how it should be resolved.
2724 m_baseURL = KURL(KURL(), documentURI());
2726 selectorQueryCache()->invalidate();
2728 if (!m_baseURL.isValid())
2732 // Element sheet is silly. It never contains anything.
2733 ASSERT(!m_elemSheet->contents()->ruleCount());
2734 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2735 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2736 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2737 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2740 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2741 // Base URL change changes any relative visited links.
2742 // 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.
2743 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
2744 if (node->hasTagName(aTag))
2745 static_cast<HTMLAnchorElement*>(node)->invalidateCachedVisitedLinkHash();
2750 void Document::setBaseURLOverride(const KURL& url)
2752 m_baseURLOverride = url;
2756 void Document::processBaseElement()
2758 // Find the first href attribute in a base element and the first target attribute in a base element.
2759 const AtomicString* href = 0;
2760 const AtomicString* target = 0;
2761 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2762 if (node->hasTagName(baseTag)) {
2764 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2765 if (!value.isNull())
2769 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2770 if (!value.isNull())
2776 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2777 KURL baseElementURL;
2779 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2780 if (!strippedHref.isEmpty())
2781 baseElementURL = KURL(url(), strippedHref);
2783 if (m_baseElementURL != baseElementURL) {
2784 m_baseElementURL = baseElementURL;
2788 m_baseTarget = target ? *target : nullAtom;
2791 String Document::userAgent(const KURL& url) const
2793 return frame() ? frame()->loader()->userAgent(url) : String();
2796 void Document::disableEval()
2801 frame()->script()->disableEval();
2804 bool Document::canNavigate(Frame* targetFrame)
2809 // FIXME: We shouldn't call this function without a target frame, but
2810 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2811 // returning true when supplied with a 0 targetFrame.
2815 // Frame-busting is generally allowed (unless we're sandboxed and prevent from frame-busting).
2816 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2819 if (isSandboxed(SandboxNavigation)) {
2820 if (targetFrame->tree()->isDescendantOf(m_frame))
2823 printNavigationErrorMessage(targetFrame, url());
2827 // This is the normal case. A document can navigate its decendant frames,
2828 // or, more generally, a document can navigate a frame if the document is
2829 // in the same origin as any of that frame's ancestors (in the frame
2832 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2833 // historical information about this security check.
2834 if (canAccessAncestor(securityOrigin(), targetFrame))
2837 // Top-level frames are easier to navigate than other frames because they
2838 // display their URLs in the address bar (in most browsers). However, there
2839 // are still some restrictions on navigation to avoid nuisance attacks.
2840 // Specifically, a document can navigate a top-level frame if that frame
2841 // opened the document or if the document is the same-origin with any of
2842 // the top-level frame's opener's ancestors (in the frame hierarchy).
2844 // In both of these cases, the document performing the navigation is in
2845 // some way related to the frame being navigate (e.g., by the "opener"
2846 // and/or "parent" relation). Requiring some sort of relation prevents a
2847 // document from navigating arbitrary, unrelated top-level frames.
2848 if (!targetFrame->tree()->parent()) {
2849 if (targetFrame == m_frame->loader()->opener())
2852 if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
2856 printNavigationErrorMessage(targetFrame, url());
2860 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2862 Frame* currentFrame = m_frame;
2863 Frame* ancestorFrame = currentFrame->tree()->parent();
2865 while (ancestorFrame) {
2866 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2867 return currentFrame;
2868 currentFrame = ancestorFrame;
2869 ancestorFrame = ancestorFrame->tree()->parent();
2874 CSSStyleSheet* Document::pageUserSheet()
2876 if (m_pageUserSheet)
2877 return m_pageUserSheet.get();
2879 Page* owningPage = page();
2883 String userSheetText = owningPage->userStyleSheet();
2884 if (userSheetText.isEmpty())
2887 // Parse the sheet and cache it.
2888 m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2889 m_pageUserSheet->contents()->setIsUserStyleSheet(true);
2890 m_pageUserSheet->contents()->parseString(userSheetText);
2891 return m_pageUserSheet.get();
2894 void Document::clearPageUserSheet()
2896 if (m_pageUserSheet) {
2897 m_pageUserSheet = 0;
2898 styleResolverChanged(DeferRecalcStyle);
2902 void Document::updatePageUserSheet()
2904 clearPageUserSheet();
2905 if (pageUserSheet())
2906 styleResolverChanged(RecalcStyleImmediately);
2909 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2911 if (m_pageGroupUserSheetCacheValid)
2912 return m_pageGroupUserSheets.get();
2914 m_pageGroupUserSheetCacheValid = true;
2916 Page* owningPage = page();
2920 const PageGroup& pageGroup = owningPage->group();
2921 const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2925 UserStyleSheetMap::const_iterator end = sheetsMap->end();
2926 for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2927 const UserStyleSheetVector* sheets = it->second.get();
2928 for (unsigned i = 0; i < sheets->size(); ++i) {
2929 const UserStyleSheet* sheet = sheets->at(i).get();
2930 if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2932 if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2934 RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2935 if (!m_pageGroupUserSheets)
2936 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2937 m_pageGroupUserSheets->append(groupSheet);
2938 groupSheet->contents()->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
2939 groupSheet->contents()->parseString(sheet->source());
2943 return m_pageGroupUserSheets.get();
2946 void Document::clearPageGroupUserSheets()
2948 m_pageGroupUserSheetCacheValid = false;
2949 if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
2950 m_pageGroupUserSheets->clear();
2951 styleResolverChanged(DeferRecalcStyle);
2955 void Document::updatePageGroupUserSheets()
2957 clearPageGroupUserSheets();
2958 if (pageGroupUserSheets() && pageGroupUserSheets()->size())
2959 styleResolverChanged(RecalcStyleImmediately);
2962 void Document::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
2965 m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2966 m_userSheets->append(CSSStyleSheet::create(userSheet, this));
2967 styleResolverChanged(RecalcStyleImmediately);
2970 void Document::seamlessParentUpdatedStylesheets()
2972 styleResolverChanged(RecalcStyleImmediately);
2975 CSSStyleSheet* Document::elementSheet()
2978 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2979 return m_elemSheet.get();
2982 int Document::nodeAbsIndex(Node *node)
2984 ASSERT(node->document() == this);
2987 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2992 Node* Document::nodeWithAbsIndex(int absIndex)
2995 for (int i = 0; n && (i < absIndex); i++)
2996 n = n->traverseNextNode();
3000 void Document::processHttpEquiv(const String& equiv, const String& content)
3002 ASSERT(!equiv.isNull() && !content.isNull());
3004 Frame* frame = this->frame();
3006 if (equalIgnoringCase(equiv, "default-style")) {
3007 // The preferred style set has been overridden as per section
3008 // 14.3.2 of the HTML4.0 specification. We need to update the
3009 // sheet used variable and then update our style selector.
3010 // For more info, see the test at:
3011 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3013 m_selectedStylesheetSet = content;
3014 m_preferredStylesheetSet = content;
3015 styleResolverChanged(DeferRecalcStyle);
3016 } else if (equalIgnoringCase(equiv, "refresh")) {
3019 if (frame && parseHTTPRefresh(content, true, delay, url)) {
3021 url = m_url.string();
3023 url = completeURL(url).string();
3024 frame->navigationScheduler()->scheduleRedirect(delay, url);
3026 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3027 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3028 if (isHTMLDocument()) {
3029 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
3030 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
3032 } else if (equalIgnoringCase(equiv, "content-language"))
3033 setContentLanguage(content);
3034 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
3035 parseDNSPrefetchControlHeader(content);
3036 else if (equalIgnoringCase(equiv, "x-frame-options")) {
3038 FrameLoader* frameLoader = frame->loader();
3039 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
3040 frameLoader->stopAllLoaders();
3041 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
3043 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
3044 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
3047 } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
3048 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
3049 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
3050 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
3053 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3054 static bool isSeparator(UChar c)
3056 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3059 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3061 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3062 int keyBegin, keyEnd;
3063 int valueBegin, valueEnd;
3066 int length = features.length();
3067 String buffer = features.lower();
3068 while (i < length) {
3069 // skip to first non-separator, but don't skip past the end of the string
3070 while (isSeparator(buffer[i])) {
3077 // skip to first separator
3078 while (!isSeparator(buffer[i]))
3082 // skip to first '=', but don't skip past a ',' or the end of the string
3083 while (buffer[i] != '=') {
3084 if (buffer[i] == ',' || i >= length)
3089 // skip to first non-separator, but don't skip past a ',' or the end of the string
3090 while (isSeparator(buffer[i])) {
3091 if (buffer[i] == ',' || i >= length)
3097 // skip to first separator
3098 while (!isSeparator(buffer[i]))
3102 ASSERT(i <= length);
3104 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3105 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3106 callback(keyString, valueString, this, data);
3110 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3112 ASSERT(!features.isNull());
3114 if (origin < m_viewportArguments.type)
3117 m_viewportArguments = ViewportArguments(origin);
3118 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3120 updateViewportArguments();
3123 void Document::updateViewportArguments()
3125 if (page() && page()->mainFrame() == frame()) {
3127 m_didDispatchViewportPropertiesChanged = true;
3129 page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
3133 void Document::processReferrerPolicy(const String& policy)
3135 ASSERT(!policy.isNull());
3137 m_referrerPolicy = ReferrerPolicyDefault;
3139 if (equalIgnoringCase(policy, "never"))
3140 m_referrerPolicy = ReferrerPolicyNever;
3141 else if (equalIgnoringCase(policy, "always"))
3142 m_referrerPolicy = ReferrerPolicyAlways;
3143 else if (equalIgnoringCase(policy, "origin"))
3144 m_referrerPolicy = ReferrerPolicyOrigin;
3147 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3149 ASSERT(!renderer() || renderer()->isRenderView());
3152 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3154 HitTestResult result(documentPoint);
3155 renderView()->hitTest(request, result);
3157 if (!request.readOnly())
3158 updateStyleIfNeeded();
3160 return MouseEventWithHitTestResults(event, result);
3163 // DOM Section 1.1.1
3164 bool Document::childTypeAllowed(NodeType type) const
3167 case ATTRIBUTE_NODE:
3168 case CDATA_SECTION_NODE:
3169 case DOCUMENT_FRAGMENT_NODE:
3172 case ENTITY_REFERENCE_NODE:
3175 case XPATH_NAMESPACE_NODE:
3178 case PROCESSING_INSTRUCTION_NODE:
3180 case DOCUMENT_TYPE_NODE:
3182 // Documents may contain no more than one of each of these.
3183 // (One Element and one DocumentType.)
3184 for (Node* c = firstChild(); c; c = c->nextSibling())
3185 if (c->nodeType() == type)
3192 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3195 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3198 if (oldChild->nodeType() == newChild->nodeType())
3201 int numDoctypes = 0;
3202 int numElements = 0;
3204 // First, check how many doctypes and elements we have, not counting
3205 // the child we're about to remove.
3206 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3210 switch (c->nodeType()) {
3211 case DOCUMENT_TYPE_NODE:
3222 // Then, see how many doctypes and elements might be added by the new child.
3223 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3224 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3225 switch (c->nodeType()) {
3226 case ATTRIBUTE_NODE:
3227 case CDATA_SECTION_NODE:
3228 case DOCUMENT_FRAGMENT_NODE:
3231 case ENTITY_REFERENCE_NODE:
3234 case XPATH_NAMESPACE_NODE:
3237 case PROCESSING_INSTRUCTION_NODE:
3239 case DOCUMENT_TYPE_NODE:
3248 switch (newChild->nodeType()) {
3249 case ATTRIBUTE_NODE:
3250 case CDATA_SECTION_NODE:
3251 case DOCUMENT_FRAGMENT_NODE:
3254 case ENTITY_REFERENCE_NODE:
3257 case XPATH_NAMESPACE_NODE:
3260 case PROCESSING_INSTRUCTION_NODE:
3262 case DOCUMENT_TYPE_NODE:
3271 if (numElements > 1 || numDoctypes > 1)
3277 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3279 // Spec says cloning Document nodes is "implementation dependent"
3280 // so we do not support it...
3284 StyleSheetList* Document::styleSheets()
3286 return m_styleSheets.get();
3289 String Document::preferredStylesheetSet() const
3291 return m_preferredStylesheetSet;
3294 String Document::selectedStylesheetSet() const
3296 return m_selectedStylesheetSet;
3299 void Document::setSelectedStylesheetSet(const String& aString)
3301 m_selectedStylesheetSet = aString;
3302 styleResolverChanged(DeferRecalcStyle);
3305 // This method is called whenever a top-level stylesheet has finished loading.
3306 void Document::removePendingSheet()
3308 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
3309 ASSERT(m_pendingStylesheets > 0);
3311 m_pendingStylesheets--;
3313 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3314 if (!ownerElement())
3315 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
3318 if (m_pendingStylesheets)
3321 styleResolverChanged(RecalcStyleIfNeeded);
3323 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3324 parser->executeScriptsWaitingForStylesheets();
3326 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3327 view()->scrollToFragment(m_url);
3330 void Document::evaluateMediaQueryList()
3332 if (m_mediaQueryMatcher)
3333 m_mediaQueryMatcher->styleResolverChanged();
3336 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3338 // Don't bother updating, since we haven't loaded all our style info yet
3339 // and haven't calculated the style selector for the first time.
3340 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3341 m_styleResolver.clear();
3345 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3346 if (!ownerElement())
3347 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3350 bool stylesheetChangeRequiresStyleRecalc = updateActiveStylesheets(updateFlag);
3352 if (updateFlag == DeferRecalcStyle) {
3353 scheduleForcedStyleRecalc();
3357 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
3358 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3360 renderer()->repaint();
3363 if (!stylesheetChangeRequiresStyleRecalc)
3366 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3367 // make sure animations get the correct update time
3369 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
3373 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3374 if (!ownerElement())
3375 printf("Finished update of style selector at time %d\n", elapsedTime());
3379 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3381 view()->scheduleRelayout();
3384 evaluateMediaQueryList();
3387 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
3389 if (!node->inDocument())
3392 // Until the <body> exists, we have no choice but to compare document positions,
3393 // since styles outside of the body and head continue to be shunted into the head
3394 // (and thus can shift to end up before dynamically added DOM content that is also
3395 // outside the body).
3396 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3397 m_styleSheetCandidateNodes.add(node);
3401 // Determine an appropriate insertion point.
3402 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3403 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3404 StyleSheetCandidateListHashSet::iterator it = end;
3405 Node* followingNode = 0;
3409 unsigned short position = n->compareDocumentPosition(node);
3410 if (position == DOCUMENT_POSITION_FOLLOWING) {
3411 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3415 } while (it != begin);
3417 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3420 void Document::removeStyleSheetCandidateNode(Node* node)
3422 m_styleSheetCandidateNodes.remove(node);
3425 void Document::collectActiveStylesheets(Vector<RefPtr<StyleSheet> >& sheets)
3427 if (settings() && !settings()->authorAndUserStylesEnabled())
3430 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3431 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3432 for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3434 StyleSheet* sheet = 0;
3435 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3436 // Processing instruction (XML documents only).
3437 // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3438 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3439 sheet = pi->sheet();
3441 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3442 if (pi->isXSL() && !transformSourceDocument()) {
3443 // Don't apply XSL transforms until loading is finished.
3445 applyXSLTransform(pi);
3449 } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3451 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3454 Element* e = static_cast<Element*>(n);
3455 AtomicString title = e->getAttribute(titleAttr);
3456 bool enabledViaScript = false;
3457 if (e->hasLocalName(linkTag)) {
3459 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3460 if (linkElement->isDisabled())
3462 enabledViaScript = linkElement->isEnabledViaScript();
3463 if (linkElement->styleSheetIsLoading()) {
3464 // it is loading but we should still decide which style sheet set to use
3465 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3466 const AtomicString& rel = e->getAttribute(relAttr);
3467 if (!rel.contains("alternate")) {
3468 m_preferredStylesheetSet = title;
3469 m_selectedStylesheetSet = title;
3474 if (!linkElement->sheet())
3477 // Get the current preferred styleset. This is the
3478 // set of sheets that will be enabled.
3480 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3481 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3484 if (e->hasLocalName(linkTag))
3485 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3488 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3489 // Check to see if this sheet belongs to a styleset
3490 // (thus making it PREFERRED or ALTERNATE rather than
3492 AtomicString rel = e->getAttribute(relAttr);
3493 if (!enabledViaScript && !title.isEmpty()) {
3494 // Yes, we have a title.
3495 if (m_preferredStylesheetSet.isEmpty()) {
3496 // No preferred set has been established. If
3497 // we are NOT an alternate sheet, then establish
3498 // us as the preferred set. Otherwise, just ignore
3500 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3501 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3503 if (title != m_preferredStylesheetSet)
3507 if (rel.contains("alternate") && title.isEmpty())
3511 sheets.append(sheet);
3515 bool Document::testAddedStylesheetRequiresStyleRecalc(StyleSheetContents* stylesheet)
3517 // See if all rules on the sheet are scoped to some specific ids or classes.
3518 // Then test if we actually have any of those in the tree at the moment.
3519 HashSet<AtomicStringImpl*> idScopes;
3520 HashSet<AtomicStringImpl*> classScopes;
3521 if (!StyleResolver::determineStylesheetSelectorScopes(stylesheet, idScopes, classScopes))
3523 // Invalidate the subtrees that match the scopes.
3524 Node* node = firstChild();
3526 if (!node->isStyledElement()) {
3527 node = node->traverseNextNode();
3530 StyledElement* element = static_cast<StyledElement*>(node);
3531 if (SelectorChecker::elementMatchesSelectorScopes(element, idScopes, classScopes)) {
3532 element->setNeedsStyleRecalc();
3533 // The whole subtree is now invalidated, we can skip to the next sibling.
3534 node = node->traverseNextSibling();
3537 node = node->traverseNextNode();
3542 void Document::analyzeStylesheetChange(StyleResolverUpdateFlag updateFlag, const Vector<RefPtr<StyleSheet> >& newStylesheets, bool& requiresStyleResolverReset, bool& requiresFullStyleRecalc)
3544 requiresStyleResolverReset = true;
3545 requiresFullStyleRecalc = true;
3547 // Stylesheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
3548 bool hasActiveLoadingStylesheet = false;
3549 unsigned newStylesheetCount = newStylesheets.size();
3550 for (unsigned i = 0; i < newStylesheetCount; ++i) {
3551 if (newStylesheets[i]->isLoading())
3552 hasActiveLoadingStylesheet = true;
3554 if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
3555 m_hadActiveLoadingStylesheet = false;
3558 m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
3560 if (updateFlag != RecalcStyleIfNeeded)
3562 if (!m_styleResolver)
3565 // See if we are just adding stylesheets.
3566 unsigned oldStylesheetCount = m_styleSheets->length();
3567 if (newStylesheetCount < oldStylesheetCount)
3569 for (unsigned i = 0; i < oldStylesheetCount; ++i) {
3570 if (m_styleSheets->item(i) != newStylesheets[i])
3573 requiresStyleResolverReset = false;
3575 // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
3576 if (!body() || m_hasNodesWithPlaceholderStyle)
3578 for (unsigned i = oldStylesheetCount; i < newStylesheetCount; ++i) {
3579 if (!newStylesheets[i]->isCSSStyleSheet())
3581 if (newStylesheets[i]->disabled())
3583 if (testAddedStylesheetRequiresStyleRecalc(static_cast<CSSStyleSheet*>(newStylesheets[i].get())->contents()))
3586 requiresFullStyleRecalc = false;
3589 static bool styleSheetsUseRemUnits(const Vector<RefPtr<StyleSheet> >& sheets)
3591 for (unsigned i = 0; i < sheets.size(); ++i) {
3592 if (!sheets[i]->isCSSStyleSheet())
3594 if (static_cast<CSSStyleSheet*>(sheets[i].get())->contents()->usesRemUnits())
3600 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3602 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3606 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3607 for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
3608 Document* childDocument = child->document();
3609 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3610 ASSERT(childDocument->seamlessParentIFrame()->document() == this);
3611 childDocument->seamlessParentUpdatedStylesheets();
3616 bool Document::updateActiveStylesheets(StyleResolverUpdateFlag updateFlag)
3618 if (m_inStyleRecalc) {
3619 // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3620 // https://bugs.webkit.org/show_bug.cgi?id=54344
3621 // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3622 m_hasDirtyStyleResolver = true;
3623 scheduleForcedStyleRecalc();
3626 if (!renderer() || !attached())
3629 StyleSheetVector newStylesheets;
3630 collectActiveStylesheets(newStylesheets);
3632 bool requiresStyleResolverReset;
3633 bool requiresFullStyleRecalc;
3634 analyzeStylesheetChange(updateFlag, newStylesheets, requiresStyleResolverReset, requiresFullStyleRecalc);
3636 if (requiresStyleResolverReset)
3637 clearStyleResolver();
3639 m_styleResolver->appendAuthorStylesheets(m_styleSheets->length(), newStylesheets);
3640 resetCSSFeatureFlags();
3642 m_styleSheets->swap(newStylesheets);
3644 m_usesRemUnits = styleSheetsUseRemUnits(m_styleSheets->vector());
3645 m_didCalculateStyleResolver = true;
3646 m_hasDirtyStyleResolver = false;
3648 notifySeamlessChildDocumentsOfStylesheetUpdate();
3650 return requiresFullStyleRecalc;
3653 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3655 m_hoverNode = newHoverNode;
3658 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3660 m_activeNode = newActiveNode;
3663 void Document::focusedNodeRemoved()
3668 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3670 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3673 bool nodeInSubtree = false;
3674 if (amongChildrenOnly)
3675 nodeInSubtree = m_focusedNode->isDescendantOf(node);
3677 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
3680 document()->focusedNodeRemoved();
3683 void Document::hoveredNodeDetached(Node* node)
3685 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3688 m_hoverNode = node->parentNode();
3689 while (m_hoverNode && !m_hoverNode->renderer())
3690 m_hoverNode = m_hoverNode->parentNode();
3692 frame()->eventHandler()->scheduleHoverStateUpdate();
3695 void Document::activeChainNodeDetached(Node* node)
3697 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3700 m_activeNode = node->parentNode();
3701 while (m_activeNode && !m_activeNode->renderer())
3702 m_activeNode = m_activeNode->parentNode();
3705 #if ENABLE(DASHBOARD_SUPPORT)
3706 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
3708 return m_dashboardRegions;
3711 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
3713 m_dashboardRegions = regions;
3714 setDashboardRegionsDirty(false);
3718 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3720 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3722 // Make sure newFocusedNode is actually in this document
3723 if (newFocusedNode && (newFocusedNode->document() != this))
3726 if (m_focusedNode == newFocusedNode)
3732 bool focusChangeBlocked = false;
3733 RefPtr<Node> oldFocusedNode = m_focusedNode;
3736 // Remove focus from the existing focus node (if any)
3737 if (oldFocusedNode) {
3738 ASSERT(!oldFocusedNode->inDetach());
3740 if (oldFocusedNode->active())
3741 oldFocusedNode->setActive(false);
3743 oldFocusedNode->setFocus(false);
3745 // Dispatch a change event for text fields or textareas that have been edited
3746 if (oldFocusedNode->isElementNode()) {
3747 Element* element = static_cast<Element*>(oldFocusedNode.get());
3748 if (element->wasChangedSinceLastFormControlChangeEvent())
3749 element->dispatchFormControlChangeEvent();
3752 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3753 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3755 if (m_focusedNode) {
3756 // handler shifted focus
3757 focusChangeBlocked = true;
3761 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3762 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3763 // on it, probably when <rdar://problem/8503958> is resolved.
3764 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3766 if (m_focusedNode) {
3767 // handler shifted focus
3768 focusChangeBlocked = true;
3771 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3774 if (oldFocusedNode->isRootEditableElement())
3775 frame()->editor()->didEndEditing();
3778 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3780 oldWidget->setFocus(false);
3782 view()->setFocus(false);
3786 if (newFocusedNode) {
3787 if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3788 // delegate blocks focus change
3789 focusChangeBlocked = true;
3790 goto SetFocusedNodeDone;
3792 // Set focus on the new node
3793 m_focusedNode = newFocusedNode;
3795 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3796 m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3798 if (m_focusedNode != newFocusedNode) {
3799 // handler shifted focus
3800 focusChangeBlocked = true;
3801 goto SetFocusedNodeDone;
3804 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3806 if (m_focusedNode != newFocusedNode) {
3807 // handler shifted focus
3808 focusChangeBlocked = true;
3809 goto SetFocusedNodeDone;
3812 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3813 // on it, probably when <rdar://problem/8503958> is m.
3814 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3816 if (m_focusedNode != newFocusedNode) {
3817 // handler shifted focus
3818 focusChangeBlocked = true;
3819 goto SetFocusedNodeDone;
3821 m_focusedNode->setFocus(true);
3823 if (m_focusedNode->isRootEditableElement())
3824 frame()->editor()->didBeginEditing();
3826 // eww, I suck. set the qt focus correctly
3827 // ### find a better place in the code for this
3829 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3831 // Make sure a widget has the right size before giving it focus.
3832 // Otherwise, we are testing edge cases of the Widget code.
3833 // Specifically, in WebCore this does not work well for text fields.
3835 // Re-get the widget in case updating the layout changed things.
3836 focusWidget = widgetForNode(m_focusedNode.get());
3839 focusWidget->setFocus(true);
3841 view()->setFocus(true);
3845 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3846 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
3847 RenderObject* oldFocusedRenderer = 0;
3848 RenderObject* newFocusedRenderer = 0;
3851 oldFocusedRenderer = oldFocusedNode->renderer();
3853 newFocusedRenderer = newFocusedNode->renderer();
3855 axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
3858 if (!focusChangeBlocked)
3859 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3862 updateStyleIfNeeded();
3863 return !focusChangeBlocked;
3866 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3870 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3871 if (node->isFocusable())
3876 void Document::setCSSTarget(Element* n)
3879 m_cssTarget->setNeedsStyleRecalc();
3882 n->setNeedsStyleRecalc();
3885 void Document::registerNodeListCache(DynamicNodeListCacheBase* list)
3887 if (list->type() != NodeListCollectionType)
3888 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3889 m_nodeListCounts[list->invalidationType()]++;
3890 if (list->isRootedAtDocument())
3891 m_listsInvalidatedAtDocument.add(list);
3894 void Document::unregisterNodeListCache(DynamicNodeListCacheBase* list)
3896 if (list->type() != NodeListCollectionType)
3897 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3898 m_nodeListCounts[list->invalidationType()]--;
3899 if (list->isRootedAtDocument()) {
3900 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3901 m_listsInvalidatedAtDocument.remove(list);
3905 void Document::attachNodeIterator(NodeIterator* ni)
3907 m_nodeIterators.add(ni);
3910 void Document::detachNodeIterator(NodeIterator* ni)
3912 // The node iterator can be detached without having been attached if its root node didn't have a document
3913 // when the iterator was created, but has it now.
3914 m_nodeIterators.remove(ni);
3917 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3919 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3920 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3921 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3922 if ((*it)->root() == node) {
3923 detachNodeIterator(*it);
3924 newDocument->attachNodeIterator(*it);
3929 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3931 if (!m_ranges.isEmpty()) {
3932 HashSet<Range*>::const_iterator end = m_ranges.end();
3933 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3934 (*it)->nodeChildrenChanged(container);
3938 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3940 if (!m_ranges.isEmpty()) {
3941 HashSet<Range*>::const_iterator end = m_ranges.end();
3942 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3943 (*it)->nodeChildrenWillBeRemoved(container);
3946 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3947 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3948 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3949 (*it)->nodeWillBeRemoved(n);
3952 if (Frame* frame = this->frame()) {
3953 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3954 frame->eventHandler()->nodeWillBeRemoved(n);
3955 frame->selection()->nodeWillBeRemoved(n);
3956 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3961 void Document::nodeWillBeRemoved(Node* n)
3963 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3964 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3965 (*it)->nodeWillBeRemoved(n);
3967 if (!m_ranges.isEmpty()) {
3968 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3969 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3970 (*it)->nodeWillBeRemoved(n);
3973 if (Frame* frame = this->frame()) {
3974 frame->eventHandler()->nodeWillBeRemoved(n);
3975 frame->selection()->nodeWillBeRemoved(n);
3976 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3980 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3982 if (!m_ranges.isEmpty()) {
3983 HashSet<Range*>::const_iterator end = m_ranges.end();
3984 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3985 (*it)->textInserted(text, offset, length);
3988 // Update the markers for spelling and grammar checking.
3989 m_markers->shiftMarkers(text, offset, length);
3992 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3994 if (!m_ranges.isEmpty()) {
3995 HashSet<Range*>::const_iterator end = m_ranges.end();
3996 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3997 (*it)->textRemoved(text, offset, length);
4000 // Update the markers for spelling and grammar checking.
4001 m_markers->removeMarkers(text, offset, length);
4002 m_markers->shiftMarkers(text, offset + length, 0 - length);
4005 void Document::textNodesMerged(Text* oldNode, unsigned offset)
4007 if (!m_ranges.isEmpty()) {
4008 NodeWithIndex oldNodeWithIndex(oldNode);
4009 HashSet<Range*>::const_iterator end = m_ranges.end();
4010 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4011 (*it)->textNodesMerged(oldNodeWithIndex, offset);
4014 // FIXME: This should update markers for spelling and grammar checking.
4017 void Document::textNodeSplit(Text* oldNode)
4019 if (!m_ranges.isEmpty()) {
4020 HashSet<Range*>::const_iterator end = m_ranges.end();
4021 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4022 (*it)->textNodeSplit(oldNode);
4025 // FIXME: This should update markers for spelling and grammar checking.
4028 // FIXME: eventually, this should return a DOMWindow stored in the document.
4029 DOMWindow* Document::domWindow() const
4034 // The m_frame pointer is not (not always?) zeroed out when the document is put into b/f cache, so the frame can hold an unrelated document/window pair.
4035 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
4036 if (m_frame->document() != this)
4039 return frame()->domWindow();
4042 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
4044 DOMWindow* domWindow = this->domWindow();
4047 domWindow->setAttributeEventListener(eventType, listener);
4050 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
4052 DOMWindow* domWindow = this->domWindow();
4055 return domWindow->getAttributeEventListener(eventType);
4058 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
4060 ASSERT(!eventDispatchForbidden());
4061 DOMWindow* domWindow = this->domWindow();
4064 domWindow->dispatchEvent(event, target);
4067 void Document::dispatchWindowLoadEvent()
4069 ASSERT(!eventDispatchForbidden());
4070 DOMWindow* domWindow = this->domWindow();
4073 domWindow->dispatchLoadEvent();
4074 m_loadEventFinished = true;
4077 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
4079 event->setTarget(domWindow());
4080 m_eventQueue->enqueueEvent(event);
4083 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
4085 event->setTarget(this);
4086 m_eventQueue->enqueueEvent(event);
4089 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
4091 RefPtr<Event> event = EventFactory::create(eventType);
4093 return event.release();
4095 ec = NOT_SUPPORTED_ERR;
4099 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
4101 if (eventType == eventNames().DOMSubtreeModifiedEvent)
4102 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
4103 else if (eventType == eventNames().DOMNodeInsertedEvent)
4104 addListenerType(DOMNODEINSERTED_LISTENER);
4105 else if (eventType == eventNames().DOMNodeRemovedEvent)
4106 addListenerType(DOMNODEREMOVED_LISTENER);
4107 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
4108 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
4109 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
4110 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
4111 else if (eventType == eventNames().DOMAttrModifiedEvent)
4112 addListenerType(DOMATTRMODIFIED_LISTENER);
4113 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
4114 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
4115 else if (eventType == eventNames().overflowchangedEvent)
4116 addListenerType(OVERFLOWCHANGED_LISTENER);
4117 else if (eventType == eventNames().webkitAnimationStartEvent)
4118 addListenerType(ANIMATIONSTART_LISTENER);
4119 else if (eventType == eventNames().webkitAnimationEndEvent)
4120 addListenerType(ANIMATIONEND_LISTENER);
4121 else if (eventType == eventNames().webkitAnimationIterationEvent)
4122 addListenerType(ANIMATIONITERATION_LISTENER);
4123 else if (eventType == eventNames().webkitTransitionEndEvent)
4124 addListenerType(TRANSITIONEND_LISTENER);
4125 else if (eventType == eventNames().beforeloadEvent)
4126 addListenerType(BEFORELOAD_LISTENER);
4127 #if ENABLE(TOUCH_EVENTS)
4128 else if (eventType == eventNames().touchstartEvent
4129 || eventType == eventNames().touchmoveEvent
4130 || eventType == eventNames().touchendEvent
4131 || eventType == eventNames().touchcancelEvent) {
4132 addListenerType(TOUCH_LISTENER);
4133 if (Page* page = this->page())
4134 page->chrome()->client()->needTouchEvents(true);
4137 else if (eventType == eventNames().scrollEvent)
4138 addListenerType(SCROLL_LISTENER);
4139 else if (eventType == eventNames().webkitRegionLayoutUpdateEvent)
4140 addListenerType(REGIONLAYOUTUPDATE_LISTENER);
4143 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
4148 HTMLFrameOwnerElement* Document::ownerElement() const
4152 return frame()->ownerElement();
4155 String Document::cookie(ExceptionCode& ec) const
4157 if (page() && !page()->settings()->cookieEnabled())
4160 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4161 // INVALID_STATE_ERR exception on getting if the Document has no
4162 // browsing context.
4164 if (!securityOrigin()->canAccessCookies()) {
4169 KURL cookieURL = this->cookieURL();
4170 if (cookieURL.isEmpty())
4173 return cookies(this, cookieURL);
4176 void Document::setCookie(const String& value, ExceptionCode& ec)
4178 if (page() && !page()->settings()->cookieEnabled())
4181 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4182 // INVALID_STATE_ERR exception on setting if the Document has no
4183 // browsing context.
4185 if (!securityOrigin()->canAccessCookies()) {
4190 KURL cookieURL = this->cookieURL();
4191 if (cookieURL.isEmpty())
4194 setCookies(this, cookieURL, value);
4197 String Document::referrer() const
4200 return frame()->loader()->referrer();
4204 String Document::domain() const
4206 return securityOrigin()->domain();
4209 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
4211 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4216 // Both NS and IE specify that changing the domain is only allowed when
4217 // the new domain is a suffix of the old domain.
4219 // FIXME: We should add logging indicating why a domain was not allowed.
4221 // If the new domain is the same as the old domain, still call
4222 // securityOrigin()->setDomainForDOM. This will change the
4223 // security check behavior. For example, if a page loaded on port 8000
4224 // assigns its current domain using document.domain, the page will
4225 // allow other pages loaded on different ports in the same domain that
4226 // have also assigned to access this page.
4227 if (equalIgnoringCase(domain(), newDomain)) {
4228 securityOrigin()->setDomainFromDOM(newDomain);
4230 m_frame->script()->updateSecurityOrigin();
4234 int oldLength = domain().length();
4235 int newLength = newDomain.length();
4236 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
4237 if (newLength >= oldLength) {
4242 String test = domain();
4243 // Check that it's a subdomain, not e.g. "ebkit.org"
4244 if (test[oldLength - newLength - 1] != '.') {
4249 // Now test is "webkit.org" from domain()
4250 // and we check that it's the same thing as newDomain
4251 test.remove(0, oldLength - newLength);
4252 if (test != newDomain) {
4257 securityOrigin()->setDomainFromDOM(newDomain);
4259 m_frame->script()->updateSecurityOrigin();
4262 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4263 String Document::lastModified() const
4265 DateComponents date;
4266 bool foundDate = false;
4268 String httpLastModified;
4269 if (DocumentLoader* documentLoader = loader())
4270 httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4271 if (!httpLastModified.isEmpty()) {
4272 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4276 // FIXME: If this document came from the file system, the HTML5
4277 // specificiation tells us to read the last modification date from the file
4280 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4281 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4284 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4289 U16_NEXT(characters, i, length, c)
4290 if (!isValidNameStart(c))
4293 while (i < length) {
4294 U16_NEXT(characters, i, length, c)
4295 if (!isValidNamePart(c))