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)
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 , m_touchEventHandlerCount(0)
485 #if ENABLE(UNDO_MANAGER)
488 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
489 , m_scheduledTasksAreSuspended(false)
490 , m_visualUpdatesAllowed(true)
491 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
493 , m_didDispatchViewportPropertiesChanged(false)
498 m_pageGroupUserSheetCacheValid = false;
501 m_paginatedForScreen = false;
503 m_ignoreAutofocus = false;
507 provideContextFeaturesToDocumentFrom(this, m_frame->page());
509 // We depend on the url getting immediately set in subframes, but we
510 // also depend on the url NOT getting immediately set in opened windows.
511 // See fast/dom/early-frame-url.html
512 // and fast/dom/location-new-window-no-crash.html, respectively.
513 // FIXME: Can/should we unify this behavior?
514 if ((frame && frame->ownerElement()) || !url.isEmpty())
519 m_markers = adoptPtr(new DocumentMarkerController);
521 m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
522 #if ENABLE(LINK_PRERENDER)
523 m_prerenderer = Prerenderer::create(this);
525 #if ENABLE(TEXT_AUTOSIZING)
526 m_textAutosizer = TextAutosizer::create(this);
528 m_visuallyOrdered = false;
530 m_wellFormed = false;
532 m_textColor = Color::black;
534 m_inStyleRecalc = false;
535 m_closeAfterStyleRecalc = false;
537 m_usesSiblingRules = false;
538 m_usesSiblingRulesOverride = false;
539 m_usesFirstLineRules = false;
540 m_usesFirstLetterRules = false;
541 m_usesBeforeAfterRules = false;
542 m_usesBeforeAfterRulesOverride = false;
543 m_usesRemUnits = false;
544 m_usesLinkRules = false;
546 m_gotoAnchorNeededAfterStylesheetsLoad = false;
548 m_didCalculateStyleResolver = false;
549 m_hasDirtyStyleResolver = false;
550 m_pendingStylesheets = 0;
551 m_ignorePendingStylesheets = false;
552 m_hasNodesWithPlaceholderStyle = false;
553 m_pendingSheetLayout = NoLayoutWithPendingSheets;
558 resetVisitedLinkColor();
559 resetActiveLinkColor();
561 m_processingLoadEvent = false;
563 initSecurityContext();
566 static int docID = 0;
569 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
570 m_nodeListCounts[i] = 0;
572 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
573 m_collections[i] = 0;
575 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
578 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
580 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
581 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
582 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
583 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
584 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
585 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
588 Document::~Document()
591 ASSERT(!m_inPageCache);
592 ASSERT(!m_savedRenderer);
593 ASSERT(m_ranges.isEmpty());
594 ASSERT(!m_styleRecalcTimer.isActive());
595 ASSERT(!m_parentTreeScope);
596 ASSERT(!m_guardRefCount);
598 m_scriptRunner.clear();
600 histogramMutationEventUsage(m_listenerTypes);
602 removeAllEventListeners();
604 // Currently we believe that Document can never outlive the parser.
605 // Although the Document may be replaced synchronously, DocumentParsers
606 // generally keep at least one reference to an Element which would in turn
607 // has a reference to the Document. If you hit this ASSERT, then that
608 // assumption is wrong. DocumentParser::detach() should ensure that even
609 // if the DocumentParser outlives the Document it won't cause badness.
610 ASSERT(!m_parser || m_parser->refCount() == 1);
613 m_renderArena.clear();
615 clearAXObjectCache();
620 m_styleSheets->documentDestroyed();
623 m_namedFlows->documentDestroyed();
626 m_elemSheet->clearOwnerNode();
628 m_pageUserSheet->clearOwnerNode();
629 if (m_pageGroupUserSheets) {
630 for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
631 (*m_pageGroupUserSheets)[i]->clearOwnerNode();
634 for (size_t i = 0; i < m_userSheets->size(); ++i)
635 (*m_userSheets)[i]->clearOwnerNode();
640 m_weakReference->clear();
642 if (m_mediaQueryMatcher)
643 m_mediaQueryMatcher->documentDestroyed();
645 clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
646 m_cachedResourceLoader.clear();
648 #if ENABLE(UNDO_MANAGER)
650 m_undoManager->undoScopeHostDestroyed();
653 // We must call clearRareData() here since a Document class inherits TreeScope
654 // as well as Node. See a comment on TreeScope.h for the reason.
658 ASSERT(!m_listsInvalidatedAtDocument.size());
660 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
661 ASSERT(!m_nodeListCounts[i]);
663 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
664 ASSERT(!m_collections[i]);
668 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
671 void Document::removedLastRef()
673 ASSERT(!m_deletionHasBegun);
674 if (m_guardRefCount) {
675 // If removing a child removes the last self-only ref, we don't
676 // want the scope to be destructed until after
677 // removeAllChildren returns, so we guard ourselves with an
678 // extra self-only ref.
681 // We must make sure not to be retaining any of our children through
682 // these extra pointers or we will create a reference cycle.
688 m_documentElement = 0;
689 m_contextFeatures = ContextFeatures::defaultSwitch();
690 #if ENABLE(FULLSCREEN_API)
691 m_fullScreenElement = 0;
692 m_fullScreenElementStack.clear();
697 // removeAllChildren() doesn't always unregister IDs,
698 // so tear down scope information upfront to avoid having stale references in the map.
699 destroyTreeScopeData();
704 m_cssCanvasElements.clear();
706 #if ENABLE(REQUEST_ANIMATION_FRAME)
707 // FIXME: consider using ActiveDOMObject.
708 if (m_scriptedAnimationController)
709 m_scriptedAnimationController->clearDocumentPointer();
710 m_scriptedAnimationController.clear();
714 m_inRemovedLastRefFunction = false;
720 m_deletionHasBegun = true;
726 Element* Document::getElementById(const AtomicString& id) const
728 return TreeScope::getElementById(id);
731 Element* Document::getElementByAccessKey(const String& key)
735 if (!m_accessKeyMapValid) {
736 buildAccessKeyMap(this);
737 m_accessKeyMapValid = true;
739 return m_elementsByAccessKey.get(key.impl());
742 void Document::buildAccessKeyMap(TreeScope* scope)
745 Node* rootNode = scope->rootNode();
746 for (Node* node = rootNode; node; node = node->traverseNextNode(rootNode)) {
747 if (!node->isElementNode())
749 Element* element = static_cast<Element*>(node);
750 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
751 if (!accessKey.isEmpty())
752 m_elementsByAccessKey.set(accessKey.impl(), element);
754 for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
755 buildAccessKeyMap(root);
759 void Document::invalidateAccessKeyMap()
761 m_accessKeyMapValid = false;
762 m_elementsByAccessKey.clear();
765 SelectorQueryCache* Document::selectorQueryCache()
767 if (!m_selectorQueryCache)
768 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
769 return m_selectorQueryCache.get();
772 MediaQueryMatcher* Document::mediaQueryMatcher()
774 if (!m_mediaQueryMatcher)
775 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
776 return m_mediaQueryMatcher.get();
779 void Document::setCompatibilityMode(CompatibilityMode mode)
781 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
783 ASSERT(!m_styleSheets->length());
784 bool wasInQuirksMode = inQuirksMode();
785 m_compatibilityMode = mode;
786 selectorQueryCache()->invalidate();
787 if (inQuirksMode() != wasInQuirksMode) {
788 // All user stylesheets have to reparse using the different mode.
789 clearPageUserSheet();
790 clearPageGroupUserSheets();
794 String Document::compatMode() const
796 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
799 void Document::resetLinkColor()
801 m_linkColor = Color(0, 0, 238);
804 void Document::resetVisitedLinkColor()
806 m_visitedLinkColor = Color(85, 26, 139);
809 void Document::resetActiveLinkColor()
811 m_activeLinkColor.setNamedColor("red");
814 void Document::setDocType(PassRefPtr<DocumentType> docType)
816 // This should never be called more than once.
817 ASSERT(!m_docType || !docType);
820 this->adoptIfNeeded(m_docType.get());
821 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
822 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
823 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
826 // Doctype affects the interpretation of the stylesheets.
827 clearStyleResolver();
830 DOMImplementation* Document::implementation()
832 if (!m_implementation)
833 m_implementation = DOMImplementation::create(this);
834 return m_implementation.get();
837 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
839 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
841 Element* newDocumentElement = firstElementChild(this);
842 if (newDocumentElement == m_documentElement)
844 m_documentElement = newDocumentElement;
845 // The root style used for media query matching depends on the document element.
846 clearStyleResolver();
849 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
851 if (!isValidName(name)) {
852 ec = INVALID_CHARACTER_ERR;
857 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
859 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
862 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
864 return DocumentFragment::create(document());
867 PassRefPtr<Text> Document::createTextNode(const String& data)
869 return Text::create(this, data);
872 PassRefPtr<Comment> Document::createComment(const String& data)
874 return Comment::create(this, data);
877 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
879 if (isHTMLDocument()) {
880 ec = NOT_SUPPORTED_ERR;
883 return CDATASection::create(this, data);
886 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
888 if (!isValidName(target)) {
889 ec = INVALID_CHARACTER_ERR;
892 if (isHTMLDocument()) {
893 ec = NOT_SUPPORTED_ERR;
896 return ProcessingInstruction::create(this, target, data);
899 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
901 if (!isValidName(name)) {
902 ec = INVALID_CHARACTER_ERR;
905 if (isHTMLDocument()) {
906 ec = NOT_SUPPORTED_ERR;
909 return EntityReference::create(this, name);
912 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
914 return EditingText::create(this, text);
917 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
919 return StylePropertySet::create()->ensureCSSStyleDeclaration();
922 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
927 ec = NOT_SUPPORTED_ERR;
931 switch (importedNode->nodeType()) {
933 return createTextNode(importedNode->nodeValue());
934 case CDATA_SECTION_NODE:
935 return createCDATASection(importedNode->nodeValue(), ec);
936 case ENTITY_REFERENCE_NODE:
937 return createEntityReference(importedNode->nodeName(), ec);
938 case PROCESSING_INSTRUCTION_NODE:
939 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
941 return createComment(importedNode->nodeValue());
943 Element* oldElement = static_cast<Element*>(importedNode);
944 // FIXME: The following check might be unnecessary. Is it possible that
945 // oldElement has mismatched prefix/namespace?
946 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
950 RefPtr<Element> newElement = createElement(oldElement->tagQName(), ec);
954 newElement->cloneDataFromElement(*oldElement);
957 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
958 RefPtr<Node> newChild = importNode(oldChild, true, ec);
961 newElement->appendChild(newChild.release(), ec);
967 return newElement.release();
970 return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
971 case DOCUMENT_FRAGMENT_NODE: {
972 if (importedNode->isShadowRoot()) {
973 // ShadowRoot nodes should not be explicitly importable.
974 // Either they are imported along with their host node, or created implicitly.
977 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
978 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
980 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
981 RefPtr<Node> newChild = importNode(oldChild, true, ec);
984 newFragment->appendChild(newChild.release(), ec);
990 return newFragment.release();
994 // 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.
995 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
997 case DOCUMENT_TYPE_NODE:
998 case XPATH_NAMESPACE_NODE:
1001 ec = NOT_SUPPORTED_ERR;
1006 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1009 ec = NOT_SUPPORTED_ERR;
1013 if (source->isReadOnlyNode()) {
1014 ec = NO_MODIFICATION_ALLOWED_ERR;
1018 EventQueueScope scope;
1020 switch (source->nodeType()) {
1024 case DOCUMENT_TYPE_NODE:
1025 case XPATH_NAMESPACE_NODE:
1026 ec = NOT_SUPPORTED_ERR;
1028 case ATTRIBUTE_NODE: {
1029 Attr* attr = static_cast<Attr*>(source.get());
1030 if (attr->ownerElement())
1031 attr->ownerElement()->removeAttributeNode(attr, ec);
1032 attr->setSpecified(true);
1036 if (source->isShadowRoot()) {
1037 // ShadowRoot cannot disconnect itself from the host node.
1038 ec = HIERARCHY_REQUEST_ERR;
1042 // FIXME: What about <frame> and <object>?
1043 if (source->hasTagName(iframeTag)) {
1044 HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
1045 if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
1046 ec = HIERARCHY_REQUEST_ERR;
1050 if (source->parentNode())
1051 source->parentNode()->removeChild(source.get(), ec);
1054 this->adoptIfNeeded(source.get());
1059 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1061 // These checks are from DOM Core Level 2, createElementNS
1062 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1063 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1065 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1068 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1069 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1070 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1071 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1077 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1079 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1080 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1081 // Note: The case of an "xmlns" qualified name with a namespace of
1082 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1083 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1085 return hasValidNamespaceForElements(qName);
1088 // FIXME: This should really be in a possible ElementFactory class
1089 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1093 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1094 if (qName.namespaceURI() == xhtmlNamespaceURI)
1095 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
1097 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1098 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
1101 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1102 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
1106 m_sawElementsInKnownNamespaces = true;
1108 e = Element::create(qName, document());
1110 // <image> uses imgTag so we need a special rule.
1111 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
1116 bool Document::regionBasedColumnsEnabled() const
1118 return settings() && settings()->regionBasedColumnsEnabled();
1121 bool Document::cssRegionsEnabled() const
1123 return settings() && settings()->cssRegionsEnabled();
1126 bool Document::cssGridLayoutEnabled() const
1128 return settings() && settings()->cssGridLayoutEnabled();
1131 #if ENABLE(CSS_REGIONS)
1133 PassRefPtr<WebKitNamedFlow> Document::webkitGetFlowByName(const String& flowName)
1135 if (!cssRegionsEnabled() || !renderer())
1138 // It's possible to have pending styles not applied that affect the existing flows.
1139 updateStyleIfNeeded();
1141 return namedFlows()->flowByName(flowName);
1145 WebKitNamedFlowCollection* Document::namedFlows()
1148 m_namedFlows = WebKitNamedFlowCollection::create(this);
1150 return m_namedFlows.get();
1153 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1155 String prefix, localName;
1156 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1159 QualifiedName qName(prefix, localName, namespaceURI);
1160 if (!hasValidNamespaceForElements(qName)) {
1165 return createElement(qName, false);
1168 String Document::readyState() const
1170 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1171 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1172 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1174 switch (m_readyState) {
1183 ASSERT_NOT_REACHED();
1187 void Document::setReadyState(ReadyState readyState)
1189 if (readyState == m_readyState)
1192 switch (readyState) {
1194 if (!m_documentTiming.domLoading)
1195 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1198 if (!m_documentTiming.domInteractive)
1199 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1202 if (!m_documentTiming.domComplete)
1203 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1207 m_readyState = readyState;
1208 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1210 if (settings() && settings()->suppressesIncrementalRendering())
1211 setVisualUpdatesAllowed(readyState);
1214 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1216 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1217 switch (readyState) {
1219 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1220 ASSERT(m_visualUpdatesAllowed);
1221 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1222 setVisualUpdatesAllowed(false);
1225 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1228 if (m_visualUpdatesSuppressionTimer.isActive()) {
1229 ASSERT(!m_visualUpdatesAllowed);
1230 m_visualUpdatesSuppressionTimer.stop();
1231 setVisualUpdatesAllowed(true);
1233 ASSERT(m_visualUpdatesAllowed);
1238 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1240 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1243 m_visualUpdatesAllowed = visualUpdatesAllowed;
1245 if (!visualUpdatesAllowed)
1248 #if USE(ACCELERATED_COMPOSITING)
1250 view()->updateCompositingLayersAfterLayout();
1254 renderer()->repaint();
1257 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1259 ASSERT(!m_visualUpdatesAllowed);
1260 setVisualUpdatesAllowed(true);
1263 String Document::encoding() const
1265 if (TextResourceDecoder* d = decoder())
1266 return d->encoding().domName();
1270 String Document::defaultCharset() const
1272 if (Settings* settings = this->settings())
1273 return settings->defaultTextEncodingName();
1277 void Document::setCharset(const String& charset)
1281 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1284 void Document::setContentLanguage(const String& language)
1286 if (m_contentLanguage == language)
1288 m_contentLanguage = language;
1290 // Recalculate style so language is used when selecting the initial font.
1291 styleResolverChanged(DeferRecalcStyle);
1294 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1296 if (!implementation()->hasFeature("XML", String())) {
1297 ec = NOT_SUPPORTED_ERR;
1301 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1302 ec = NOT_SUPPORTED_ERR;
1306 m_xmlVersion = version;
1309 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1311 if (!implementation()->hasFeature("XML", String())) {
1312 ec = NOT_SUPPORTED_ERR;
1316 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1319 void Document::setDocumentURI(const String& uri)
1321 // This property is read-only from JavaScript, but writable from Objective-C.
1322 m_documentURI = uri;
1326 KURL Document::baseURI() const
1331 void Document::setContent(const String& content)
1334 m_parser->append(content);
1338 String Document::suggestedMIMEType() const
1340 if (m_document->isXHTMLDocument())
1341 return "application/xhtml+xml";
1342 if (m_document->isSVGDocument())
1343 return "image/svg+xml";
1344 if (m_document->xmlStandalone())
1346 if (m_document->isHTMLDocument())
1349 if (DocumentLoader* documentLoader = loader())
1350 return documentLoader->responseMIMEType();
1354 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1355 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1356 // * making it receive the expading size of each direction separately,
1357 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1358 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
1360 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1363 Frame* frame = this->frame();
1366 FrameView* frameView = frame->view();
1370 float zoomFactor = frame->pageZoomFactor();
1371 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1373 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1375 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1377 type |= HitTestRequest::IgnoreClipping;
1378 else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1381 HitTestRequest request(type);
1383 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1384 // we special handle this case in order to return a valid NodeList.
1385 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1386 HitTestResult result(point);
1387 return handleZeroPadding(request, result);
1390 enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
1391 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding, shadowContentFilterPolicy);
1392 renderView()->hitTest(request, result);
1394 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1397 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1399 renderView()->hitTest(request, result);
1401 Node* node = result.innerNode();
1405 node = node->shadowAncestorNode();
1406 ListHashSet<RefPtr<Node> > list;
1408 return StaticHashSetNodeList::adopt(list);
1411 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1415 FrameView* frameView = frame->view();
1419 float zoomFactor = frame->pageZoomFactor();
1420 IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1422 if (!frameView->visibleContentRect().contains(point))
1425 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1426 HitTestResult result(point);
1427 renderView->hitTest(request, result);
1430 *localPoint = result.localPoint();
1432 return result.innerNode();
1435 Element* Document::elementFromPoint(int x, int y) const
1439 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1440 while (node && !node->isElementNode())
1441 node = node->parentNode();
1443 node = ancestorInThisScope(node);
1444 return static_cast<Element*>(node);
1447 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1451 LayoutPoint localPoint;
1452 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1456 Node* shadowAncestorNode = ancestorInThisScope(node);
1457 if (shadowAncestorNode != node) {
1458 unsigned offset = shadowAncestorNode->nodeIndex();
1459 ContainerNode* container = shadowAncestorNode->parentNode();
1460 return Range::create(this, container, offset, container, offset);
1463 RenderObject* renderer = node->renderer();
1466 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1467 if (visiblePosition.isNull())
1470 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1471 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1475 * Performs three operations:
1476 * 1. Convert control characters to spaces
1477 * 2. Trim leading and trailing spaces
1478 * 3. Collapse internal whitespace.
1480 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1482 const String& title = titleWithDirection.string();
1483 const UChar* characters = title.characters();
1484 unsigned length = title.length();
1487 StringBuffer<UChar> buffer(length);
1488 unsigned builderIndex = 0;
1490 // Skip leading spaces and leading characters that would convert to spaces
1491 for (i = 0; i < length; ++i) {
1492 UChar c = characters[i];
1493 if (!(c <= 0x20 || c == 0x7F))
1498 return StringWithDirection();
1500 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1501 bool previousCharWasWS = false;
1502 for (; i < length; ++i) {
1503 UChar c = characters[i];
1504 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1505 if (previousCharWasWS)
1507 buffer[builderIndex++] = ' ';
1508 previousCharWasWS = true;
1510 buffer[builderIndex++] = c;
1511 previousCharWasWS = false;
1515 // Strip trailing spaces
1516 while (builderIndex > 0) {
1518 if (buffer[builderIndex] != ' ')
1522 if (!builderIndex && buffer[builderIndex] == ' ')
1523 return StringWithDirection();
1525 buffer.shrink(builderIndex + 1);
1527 // Replace the backslashes with currency symbols if the encoding requires it.
1528 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1530 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1533 void Document::updateTitle(const StringWithDirection& title)
1535 if (m_rawTitle == title)
1539 m_title = canonicalizedTitle(this, m_rawTitle);
1540 if (Frame* f = frame())
1541 f->loader()->setTitle(m_title);
1544 void Document::setTitle(const String& title)
1546 // Title set by JavaScript -- overrides any title elements.
1547 m_titleSetExplicitly = true;
1548 if (!isHTMLDocument() && !isXHTMLDocument())
1550 else if (!m_titleElement) {
1551 if (HTMLElement* headElement = head()) {
1552 m_titleElement = createElement(titleTag, false);
1553 ExceptionCode ec = 0;
1554 headElement->appendChild(m_titleElement, ec);
1559 // The DOM API has no method of specifying direction, so assume LTR.
1560 updateTitle(StringWithDirection(title, LTR));
1562 if (m_titleElement) {
1563 ASSERT(m_titleElement->hasTagName(titleTag));
1564 if (m_titleElement->hasTagName(titleTag))
1565 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1569 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1571 if (titleElement != m_titleElement) {
1572 if (m_titleElement || m_titleSetExplicitly)
1573 // Only allow the first title element to change the title -- others have no effect.
1575 m_titleElement = titleElement;
1581 void Document::removeTitle(Element* titleElement)
1583 if (m_titleElement != titleElement)
1587 m_titleSetExplicitly = false;
1589 // Update title based on first title element in the head, if one exists.
1590 if (HTMLElement* headElement = head()) {
1591 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1592 if (e->hasTagName(titleTag)) {
1593 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1594 setTitleElement(titleElement->textWithDirection(), titleElement);
1599 if (!m_titleElement)
1600 updateTitle(StringWithDirection());
1603 #if ENABLE(PAGE_VISIBILITY_API)
1604 PageVisibilityState Document::visibilityState() const
1606 // The visibility of the document is inherited from the visibility of the
1607 // page. If there is no page associated with the document, we will assume
1608 // that the page is visible i.e. invisibility has to be explicitly
1609 // specified by the embedder.
1610 if (!m_frame || !m_frame->page())
1611 return PageVisibilityStateVisible;
1612 return m_frame->page()->visibilityState();
1615 String Document::webkitVisibilityState() const
1617 return pageVisibilityStateString(visibilityState());
1620 bool Document::webkitHidden() const
1622 return visibilityState() != PageVisibilityStateVisible;
1625 void Document::dispatchVisibilityStateChangeEvent()
1627 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1631 String Document::nodeName() const
1636 Node::NodeType Document::nodeType() const
1638 return DOCUMENT_NODE;
1641 FormController* Document::formController()
1643 if (!m_formController)
1644 m_formController = FormController::create();
1645 return m_formController.get();
1648 Vector<String> Document::formElementsState() const
1650 if (!m_formController)
1651 return Vector<String>();
1652 return m_formController->formElementsState();
1655 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1657 if (!stateVector.size() && !m_formController)
1659 formController()->setStateForNewFormElements(stateVector);
1662 FrameView* Document::view() const
1664 return m_frame ? m_frame->view() : 0;
1667 Page* Document::page() const
1669 return m_frame ? m_frame->page() : 0;
1672 Settings* Document::settings() const
1674 return m_frame ? m_frame->settings() : 0;
1677 PassRefPtr<Range> Document::createRange()
1679 return Range::create(this);
1682 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1683 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1686 ec = NOT_SUPPORTED_ERR;
1689 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1692 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1693 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1696 ec = NOT_SUPPORTED_ERR;
1699 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1702 void Document::scheduleForcedStyleRecalc()
1704 m_pendingStyleRecalcShouldForce = true;
1705 scheduleStyleRecalc();
1708 void Document::scheduleStyleRecalc()
1710 if (shouldDisplaySeamlesslyWithParent()) {
1711 // When we're seamless, our parent document manages our style recalcs.
1712 ownerElement()->setNeedsStyleRecalc();
1713 ownerElement()->document()->scheduleStyleRecalc();
1717 if (m_styleRecalcTimer.isActive() || inPageCache())
1720 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1722 if (!documentsThatNeedStyleRecalc)
1723 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1724 documentsThatNeedStyleRecalc->add(this);
1726 // FIXME: Why on earth is this here? This is clearly misplaced.
1727 invalidateAccessKeyMap();
1729 m_styleRecalcTimer.startOneShot(0);
1731 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1734 void Document::unscheduleStyleRecalc()
1736 ASSERT(!childNeedsStyleRecalc());
1738 if (documentsThatNeedStyleRecalc)
1739 documentsThatNeedStyleRecalc->remove(this);
1741 m_styleRecalcTimer.stop();
1742 m_pendingStyleRecalcShouldForce = false;
1745 bool Document::isPendingStyleRecalc() const
1747 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1750 void Document::styleRecalcTimerFired(Timer<Document>*)
1752 updateStyleIfNeeded();
1755 bool Document::childNeedsAndNotInStyleRecalc()
1757 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1760 void Document::recalcStyle(StyleChange change)
1762 // we should not enter style recalc while painting
1763 if (view() && view()->isPainting()) {
1764 ASSERT(!view()->isPainting());
1768 if (m_inStyleRecalc)
1769 return; // Guard against re-entrancy. -dwh
1771 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1772 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1773 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1774 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1775 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1776 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1778 if (m_hasDirtyStyleResolver)
1779 updateActiveStylesheets(RecalcStyleImmediately);
1781 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1783 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1784 m_usesRemUnits = true;
1786 m_inStyleRecalc = true;
1787 suspendPostAttachCallbacks();
1788 RenderWidget::suspendWidgetHierarchyUpdates();
1790 RefPtr<FrameView> frameView = view();
1792 frameView->pauseScheduledEvents();
1793 frameView->beginDeferredRepaints();
1796 ASSERT(!renderer() || renderArena());
1797 if (!renderer() || !renderArena())
1800 if (m_pendingStyleRecalcShouldForce)
1803 // Recalculating the root style (on the document) is not needed in the common case.
1804 if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
1805 // style selector may set this again during recalc
1806 m_hasNodesWithPlaceholderStyle = false;
1808 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
1809 StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
1811 renderer()->setStyle(documentStyle.release());
1814 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1815 if (!n->isElementNode())
1817 Element* element = static_cast<Element*>(n);
1818 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1819 element->recalcStyle(change);
1822 #if USE(ACCELERATED_COMPOSITING)
1824 bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1825 // If we didn't update compositing layers because of layout(), we need to do so here.
1827 view()->updateCompositingLayersAfterStyleChange();
1832 clearNeedsStyleRecalc();
1833 clearChildNeedsStyleRecalc();
1834 unscheduleStyleRecalc();
1836 m_inStyleRecalc = false;
1838 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1839 if (m_styleResolver)
1840 resetCSSFeatureFlags();
1843 frameView->resumeScheduledEvents();
1844 frameView->endDeferredRepaints();
1846 RenderWidget::resumeWidgetHierarchyUpdates();
1847 resumePostAttachCallbacks();
1849 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1850 if (m_closeAfterStyleRecalc) {
1851 m_closeAfterStyleRecalc = false;
1855 InspectorInstrumentation::didRecalculateStyle(cookie);
1858 void Document::updateStyleIfNeeded()
1860 ASSERT(isMainThread());
1861 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1863 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1866 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
1867 recalcStyle(NoChange);
1870 void Document::updateStyleForAllDocuments()
1872 ASSERT(isMainThread());
1873 if (!documentsThatNeedStyleRecalc)
1876 while (documentsThatNeedStyleRecalc->size()) {
1877 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1878 Document* doc = *it;
1879 documentsThatNeedStyleRecalc->remove(doc);
1880 doc->updateStyleIfNeeded();
1884 void Document::updateLayout()
1886 ASSERT(isMainThread());
1887 if (Element* oe = ownerElement())
1888 oe->document()->updateLayout();
1890 updateStyleIfNeeded();
1892 // Only do a layout if changes have occurred that make it necessary.
1893 FrameView* v = view();
1894 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1898 // FIXME: This is a bad idea and needs to be removed eventually.
1899 // Other browsers load stylesheets before they continue parsing the web page.
1900 // Since we don't, we can run JavaScript code that needs answers before the
1901 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1902 // lets us get reasonable answers. The long term solution to this problem is
1903 // to instead suspend JavaScript execution.
1904 void Document::updateLayoutIgnorePendingStylesheets()
1906 bool oldIgnore = m_ignorePendingStylesheets;
1908 if (!haveStylesheetsLoaded()) {
1909 m_ignorePendingStylesheets = true;
1910 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1911 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1912 // with accurate style information. (Our suppression involves blanking the whole page at the
1913 // moment. If it were more refined, we might be able to do something better.)
1914 // It's worth noting though that this entire method is a hack, since what we really want to do is
1915 // suspend JS instead of doing a layout with inaccurate information.
1916 HTMLElement* bodyElement = body();
1917 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1918 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1919 styleResolverChanged(RecalcStyleImmediately);
1920 } else if (m_hasNodesWithPlaceholderStyle)
1921 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1922 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1923 // but here we need up-to-date style immediately.
1929 m_ignorePendingStylesheets = oldIgnore;
1932 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1934 ASSERT_ARG(element, element->document() == this);
1936 bool oldIgnore = m_ignorePendingStylesheets;
1937 m_ignorePendingStylesheets = true;
1938 RefPtr<RenderStyle> style = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1939 m_ignorePendingStylesheets = oldIgnore;
1940 return style.release();
1943 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1945 RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
1946 return style.release();
1949 void Document::registerCustomFont(PassOwnPtr<FontData> fontData)
1951 m_customFonts.append(fontData);
1954 void Document::deleteCustomFonts()
1956 size_t size = m_customFonts.size();
1957 for (size_t i = 0; i < size; ++i)
1958 GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
1960 m_customFonts.clear();
1963 bool Document::isPageBoxVisible(int pageIndex)
1965 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1966 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1969 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1971 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1972 RenderView* view = renderView();
1974 int width = pageSize.width();
1975 int height = pageSize.height();
1976 switch (style->pageSizeType()) {
1977 case PAGE_SIZE_AUTO:
1979 case PAGE_SIZE_AUTO_LANDSCAPE:
1981 std::swap(width, height);
1983 case PAGE_SIZE_AUTO_PORTRAIT:
1985 std::swap(width, height);
1987 case PAGE_SIZE_RESOLVED: {
1988 LengthSize size = style->pageSize();
1989 ASSERT(size.width().isFixed());
1990 ASSERT(size.height().isFixed());
1991 width = valueForLength(size.width(), 0, view);
1992 height = valueForLength(size.height(), 0, view);
1996 ASSERT_NOT_REACHED();
1998 pageSize = IntSize(width, height);
2000 // The percentage is calculated with respect to the width even for margin top and bottom.
2001 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2002 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
2003 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
2004 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
2005 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
2008 void Document::setDocumentRareData(NodeRareData* rareData)
2010 m_documentRareData = rareData;
2013 void Document::setIsViewSource(bool isViewSource)
2015 m_isViewSource = isViewSource;
2016 if (!m_isViewSource)
2019 setSecurityOrigin(SecurityOrigin::createUnique());
2022 void Document::combineCSSFeatureFlags()
2024 // 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).
2025 m_usesSiblingRules = m_usesSiblingRules || m_styleResolver->usesSiblingRules();
2026 m_usesFirstLineRules = m_usesFirstLineRules || m_styleResolver->usesFirstLineRules();
2027 m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleResolver->usesBeforeAfterRules();
2028 m_usesLinkRules = m_usesLinkRules || m_styleResolver->usesLinkRules();
2031 void Document::resetCSSFeatureFlags()
2033 m_usesSiblingRules = m_styleResolver->usesSiblingRules();
2034 m_usesFirstLineRules = m_styleResolver->usesFirstLineRules();
2035 m_usesBeforeAfterRules = m_styleResolver->usesBeforeAfterRules();
2036 m_usesLinkRules = m_styleResolver->usesLinkRules();
2039 void Document::createStyleResolver()
2041 bool matchAuthorAndUserStyles = true;
2042 if (Settings* docSettings = settings())
2043 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
2044 m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
2045 combineCSSFeatureFlags();
2048 inline void Document::clearStyleResolver()
2050 m_styleResolver.clear();
2053 void Document::attach()
2055 ASSERT(!attached());
2056 ASSERT(!m_inPageCache);
2057 ASSERT(!m_axObjectCache || this != topDocument());
2060 m_renderArena = adoptPtr(new RenderArena);
2062 // Create the rendering tree
2063 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
2064 #if USE(ACCELERATED_COMPOSITING)
2065 renderView()->didMoveOnscreen();
2070 RenderObject* render = renderer();
2073 ContainerNode::attach();
2075 setRenderer(render);
2078 void Document::detach()
2081 ASSERT(!m_inPageCache);
2083 #if ENABLE(POINTER_LOCK)
2085 page()->pointerLockController()->documentDetached(this);
2088 if (this == topDocument())
2089 clearAXObjectCache();
2091 stopActiveDOMObjects();
2092 m_eventQueue->close();
2093 #if ENABLE(FULLSCREEN_API)
2094 m_fullScreenChangeEventTargetQueue.clear();
2095 m_fullScreenErrorEventTargetQueue.clear();
2098 #if ENABLE(REQUEST_ANIMATION_FRAME)
2099 // FIXME: consider using ActiveDOMObject.
2100 if (m_scriptedAnimationController)
2101 m_scriptedAnimationController->clearDocumentPointer();
2102 m_scriptedAnimationController.clear();
2105 RenderObject* render = renderer();
2107 documentWillBecomeInactive();
2109 #if ENABLE(SHARED_WORKERS)
2110 SharedWorkerRepository::documentDetached(this);
2114 FrameView* view = m_frame->view();
2116 view->detachCustomScrollbars();
2120 // indicate destruction mode, i.e. attached() but renderer == 0
2123 #if ENABLE(FULLSCREEN_API)
2124 if (m_fullScreenRenderer)
2125 setFullScreenRenderer(0);
2132 ContainerNode::detach();
2134 unscheduleStyleRecalc();
2139 // This is required, as our Frame might delete itself as soon as it detaches
2140 // us. However, this violates Node::detach() semantics, as it's never
2141 // possible to re-attach. Eventually Document::detach() should be renamed,
2142 // or this setting of the frame to 0 could be made explicit in each of the
2143 // callers of Document::detach().
2145 m_renderArena.clear();
2148 void Document::prepareForDestruction()
2150 disconnectDescendantFrames();
2151 if (DOMWindow* window = this->domWindow())
2152 window->willDetachDocumentFromFrame();
2156 void Document::removeAllEventListeners()
2158 EventTarget::removeAllEventListeners();
2160 if (DOMWindow* domWindow = this->domWindow())
2161 domWindow->removeAllEventListeners();
2162 for (Node* node = firstChild(); node; node = node->traverseNextNode())
2163 node->removeAllEventListeners();
2166 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2168 ScriptExecutionContext::suspendActiveDOMObjects(why);
2170 #if ENABLE(DEVICE_ORIENTATION)
2174 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2175 controller->suspendEventsForAllListeners(domWindow());
2176 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2177 controller->suspendEventsForAllListeners(domWindow());
2182 void Document::resumeActiveDOMObjects()
2184 ScriptExecutionContext::resumeActiveDOMObjects();
2186 #if ENABLE(DEVICE_ORIENTATION)
2190 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2191 controller->resumeEventsForAllListeners(domWindow());
2192 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2193 controller->resumeEventsForAllListeners(domWindow());
2197 RenderView* Document::renderView() const
2199 return toRenderView(renderer());
2202 void Document::clearAXObjectCache()
2204 // clear cache in top document
2205 if (m_axObjectCache) {
2206 // Clear the cache member variable before calling delete because attempts
2207 // are made to access it during destruction.
2208 AXObjectCache* axObjectCache = m_axObjectCache;
2209 m_axObjectCache = 0;
2210 delete axObjectCache;
2214 // ask the top-level document to clear its cache
2215 Document* doc = topDocument();
2217 doc->clearAXObjectCache();
2220 bool Document::axObjectCacheExists() const
2222 if (m_axObjectCache)
2225 Document* doc = topDocument();
2227 return doc->axObjectCacheExists();
2232 AXObjectCache* Document::axObjectCache() const
2234 // The only document that actually has a AXObjectCache is the top-level
2235 // document. This is because we need to be able to get from any WebCoreAXObject
2236 // to any other WebCoreAXObject on the same page. Using a single cache allows
2237 // lookups across nested webareas (i.e. multiple documents).
2239 if (m_axObjectCache) {
2240 // return already known top-level cache
2241 if (!ownerElement())
2242 return m_axObjectCache;
2244 // In some pages with frames, the cache is created before the sub-webarea is
2245 // inserted into the tree. Here, we catch that case and just toss the old
2246 // cache and start over.
2247 // NOTE: This recovery may no longer be needed. I have been unable to trigger
2248 // it again. See rdar://5794454
2249 // FIXME: Can this be fixed when inserting the subframe instead of now?
2250 // FIXME: If this function was called to get the cache in order to remove
2251 // an AXObject, we are now deleting the cache as a whole and returning a
2252 // new empty cache that does not contain the AXObject! That should actually
2253 // be OK. I am concerned about other cases like this where accessing the
2254 // cache blows away the AXObject being operated on.
2255 delete m_axObjectCache;
2256 m_axObjectCache = 0;
2259 // ask the top-level document for its cache
2260 Document* doc = topDocument();
2262 return doc->axObjectCache();
2264 // this is the top-level document, so install a new cache
2265 m_axObjectCache = new AXObjectCache(this);
2266 return m_axObjectCache;
2269 void Document::setVisuallyOrdered()
2271 m_visuallyOrdered = true;
2273 renderer()->style()->setRTLOrdering(VisualOrder);
2276 PassRefPtr<DocumentParser> Document::createParser()
2278 // FIXME: this should probably pass the frame instead
2280 return NewXMLDocumentParser::create(this);
2282 return XMLDocumentParser::create(this, view());
2286 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2288 return parser() ? parser()->asScriptableDocumentParser() : 0;
2291 void Document::open(Document* ownerDocument)
2293 if (ownerDocument) {
2294 setURL(ownerDocument->url());
2295 m_cookieURL = ownerDocument->cookieURL();
2296 setSecurityOrigin(ownerDocument->securityOrigin());
2300 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2301 if (parser->isParsing()) {
2302 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2303 if (parser->isExecutingScript())
2306 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2311 if (m_frame->loader()->state() == FrameStateProvisional)
2312 m_frame->loader()->stopAllLoaders();
2315 removeAllEventListeners();
2317 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2318 parser->setWasCreatedByScript(true);
2320 if (DOMWindow* domWindow = this->domWindow())
2321 domWindow->removeAllEventListeners();
2324 m_frame->loader()->didExplicitOpen();
2327 void Document::detachParser()
2335 void Document::cancelParsing()
2340 // We have to clear the parser to avoid possibly triggering
2341 // the onload handler when closing as a side effect of a cancel-style
2342 // change, such as opening a new document or closing the window while
2348 void Document::implicitOpen()
2354 setCompatibilityMode(NoQuirksMode);
2356 m_parser = createParser();
2358 setReadyState(Loading);
2361 HTMLElement* Document::body() const
2363 Node* de = documentElement();
2367 // try to prefer a FRAMESET element over BODY
2369 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2370 if (i->hasTagName(framesetTag))
2371 return toHTMLElement(i);
2373 if (i->hasTagName(bodyTag) && !body)
2376 return toHTMLElement(body);
2379 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2381 RefPtr<HTMLElement> newBody = prpNewBody;
2383 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2384 ec = HIERARCHY_REQUEST_ERR;
2388 if (newBody->document() && newBody->document() != this) {
2390 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2394 newBody = toHTMLElement(node.get());
2397 HTMLElement* b = body();
2399 documentElement()->appendChild(newBody.release(), ec);
2401 documentElement()->replaceChild(newBody.release(), b, ec);
2404 HTMLHeadElement* Document::head()
2406 Node* de = documentElement();
2410 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2411 if (e->hasTagName(headTag))
2412 return static_cast<HTMLHeadElement*>(e);
2417 void Document::close()
2419 // FIXME: We should follow the specification more closely:
2420 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2422 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2428 void Document::explicitClose()
2434 // Because we have no frame, we don't know if all loading has completed,
2435 // so we just call implicitClose() immediately. FIXME: This might fire
2436 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2441 m_frame->loader()->checkCompleted();
2444 void Document::implicitClose()
2446 // 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.
2447 if (m_inStyleRecalc) {
2448 m_closeAfterStyleRecalc = true;
2452 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2453 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2458 m_processingLoadEvent = true;
2460 ScriptableDocumentParser* parser = scriptableDocumentParser();
2461 m_wellFormed = parser && parser->wellFormed();
2463 // We have to clear the parser, in case someone document.write()s from the
2464 // onLoad event handler, as in Radar 3206524.
2467 // Parser should have picked up all preloads by now
2468 m_cachedResourceLoader->clearPreloads();
2470 // FIXME: We kick off the icon loader when the Document is done parsing.
2471 // There are earlier opportunities we could start it:
2472 // -When the <head> finishes parsing
2473 // -When any new HTMLLinkElement is inserted into the document
2474 // But those add a dynamic component to the favicon that has UI
2475 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2478 f->loader()->icon()->startLoader();
2479 f->animation()->resumeAnimationsForDocument(this);
2482 ImageLoader::dispatchPendingBeforeLoadEvents();
2483 ImageLoader::dispatchPendingLoadEvents();
2484 ImageLoader::dispatchPendingErrorEvents();
2486 HTMLLinkElement::dispatchPendingLoadEvents();
2487 HTMLStyleElement::dispatchPendingLoadEvents();
2490 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2491 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2492 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2493 if (svgExtensions())
2494 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2497 dispatchWindowLoadEvent();
2498 enqueuePageshowEvent(PageshowEventNotPersisted);
2499 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2502 f->loader()->handledOnloadEvents();
2503 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2504 if (!ownerElement())
2505 printf("onload fired at %d\n", elapsedTime());
2508 // An event handler may have removed the frame
2510 m_processingLoadEvent = false;
2514 // Make sure both the initial layout and reflow happen after the onload
2515 // fires. This will improve onload scores, and other browsers do it.
2516 // If they wanna cheat, we can too. -dwh
2518 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2519 // Just bail out. Before or during the onload we were shifted to another page.
2520 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2521 m_processingLoadEvent = false;
2522 view()->unscheduleRelayout();
2526 frame()->loader()->checkCallImplicitClose();
2527 RenderObject* renderObject = renderer();
2529 // We used to force a synchronous display and flush here. This really isn't
2530 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2531 // (if your platform is syncing flushes and limiting them to 60fps).
2532 m_overMinimumLayoutThreshold = true;
2533 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2534 updateStyleIfNeeded();
2536 // Always do a layout after loading if needed.
2537 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2541 m_processingLoadEvent = false;
2543 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2544 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2545 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2546 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2547 // exists in the cache (we ignore the return value because we don't need it here). This is
2548 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2549 axObjectCache()->getOrCreate(renderObject);
2550 if (this == topDocument())
2551 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2553 // AXLoadComplete can only be posted on the top document, so if it's a document
2554 // in an iframe that just finished loading, post AXLayoutComplete instead.
2555 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
2561 if (svgExtensions())
2562 accessSVGExtensions()->startAnimations();
2566 void Document::setParsing(bool b)
2569 if (!m_bParsing && view())
2570 view()->scheduleRelayout();
2572 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2573 if (!ownerElement() && !m_bParsing)
2574 printf("Parsing finished at %d\n", elapsedTime());
2578 bool Document::shouldScheduleLayout()
2580 // This function will only be called when FrameView thinks a layout is needed.
2581 // This enforces a couple extra rules.
2583 // (a) Only schedule a layout once the stylesheets are loaded.
2584 // (b) Only schedule layout once we have a body element.
2586 return (haveStylesheetsLoaded() && body())
2587 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2590 bool Document::isLayoutTimerActive()
2592 return view() && view()->layoutPending() && !minimumLayoutDelay();
2595 int Document::minimumLayoutDelay()
2597 if (m_overMinimumLayoutThreshold)
2600 int elapsed = elapsedTime();
2601 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2603 // We'll want to schedule the timer to fire at the minimum layout threshold.
2604 return max(0, cLayoutScheduleThreshold - elapsed);
2607 int Document::elapsedTime() const
2609 return static_cast<int>((currentTime() - m_startTime) * 1000);
2612 void Document::write(const SegmentedString& text, Document* ownerDocument)
2614 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2616 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2617 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2619 if (m_writeRecursionIsTooDeep)
2622 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2623 if (!ownerElement())
2624 printf("Beginning a document.write at %d\n", elapsedTime());
2627 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2628 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2631 if (!hasInsertionPoint)
2632 open(ownerDocument);
2635 m_parser->insert(text);
2637 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2638 if (!ownerElement())
2639 printf("Ending a document.write at %d\n", elapsedTime());
2643 void Document::write(const String& text, Document* ownerDocument)
2645 write(SegmentedString(text), ownerDocument);
2648 void Document::writeln(const String& text, Document* ownerDocument)
2650 write(text, ownerDocument);
2651 write("\n", ownerDocument);
2654 const KURL& Document::virtualURL() const
2659 KURL Document::virtualCompleteURL(const String& url) const
2661 return completeURL(url);
2664 double Document::minimumTimerInterval() const
2668 return ScriptExecutionContext::minimumTimerInterval();
2669 return p->settings()->minDOMTimerInterval();
2672 EventTarget* Document::errorEventTarget()
2677 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
2679 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
2682 void Document::setURL(const KURL& url)
2684 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2685 if (newURL == m_url)
2689 m_documentURI = m_url.string();
2691 contextFeatures()->urlDidChange(this);
2694 void Document::updateBaseURL()
2696 KURL oldBaseURL = m_baseURL;
2697 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2698 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2699 // from the Document interface otherwise.
2700 if (!m_baseElementURL.isEmpty())
2701 m_baseURL = m_baseElementURL;
2702 else if (!m_baseURLOverride.isEmpty())
2703 m_baseURL = m_baseURLOverride;
2705 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2706 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2707 // and DOM 3 Core does not specify how it should be resolved.
2708 m_baseURL = KURL(KURL(), documentURI());
2710 selectorQueryCache()->invalidate();
2712 if (!m_baseURL.isValid())
2716 // Element sheet is silly. It never contains anything.
2717 ASSERT(!m_elemSheet->contents()->ruleCount());
2718 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2719 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2720 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2721 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2724 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2725 // Base URL change changes any relative visited links.
2726 // 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.
2727 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
2728 if (node->hasTagName(aTag))
2729 static_cast<HTMLAnchorElement*>(node)->invalidateCachedVisitedLinkHash();
2734 void Document::setBaseURLOverride(const KURL& url)
2736 m_baseURLOverride = url;
2740 void Document::processBaseElement()
2742 // Find the first href attribute in a base element and the first target attribute in a base element.
2743 const AtomicString* href = 0;
2744 const AtomicString* target = 0;
2745 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2746 if (node->hasTagName(baseTag)) {
2748 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2749 if (!value.isNull())
2753 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2754 if (!value.isNull())
2760 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2761 KURL baseElementURL;
2763 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2764 if (!strippedHref.isEmpty())
2765 baseElementURL = KURL(url(), strippedHref);
2767 if (m_baseElementURL != baseElementURL) {
2768 m_baseElementURL = baseElementURL;
2772 m_baseTarget = target ? *target : nullAtom;
2775 String Document::userAgent(const KURL& url) const
2777 return frame() ? frame()->loader()->userAgent(url) : String();
2780 void Document::disableEval()
2785 frame()->script()->disableEval();
2788 bool Document::canNavigate(Frame* targetFrame)
2793 // FIXME: We shouldn't call this function without a target frame, but
2794 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2795 // returning true when supplied with a 0 targetFrame.
2799 // Frame-busting is generally allowed (unless we're sandboxed and prevent from frame-busting).
2800 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2803 if (isSandboxed(SandboxNavigation)) {
2804 if (targetFrame->tree()->isDescendantOf(m_frame))
2807 printNavigationErrorMessage(targetFrame, url());
2811 // This is the normal case. A document can navigate its decendant frames,
2812 // or, more generally, a document can navigate a frame if the document is
2813 // in the same origin as any of that frame's ancestors (in the frame
2816 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2817 // historical information about this security check.
2818 if (canAccessAncestor(securityOrigin(), targetFrame))
2821 // Top-level frames are easier to navigate than other frames because they
2822 // display their URLs in the address bar (in most browsers). However, there
2823 // are still some restrictions on navigation to avoid nuisance attacks.
2824 // Specifically, a document can navigate a top-level frame if that frame
2825 // opened the document or if the document is the same-origin with any of
2826 // the top-level frame's opener's ancestors (in the frame hierarchy).
2828 // In both of these cases, the document performing the navigation is in
2829 // some way related to the frame being navigate (e.g., by the "opener"
2830 // and/or "parent" relation). Requiring some sort of relation prevents a
2831 // document from navigating arbitrary, unrelated top-level frames.
2832 if (!targetFrame->tree()->parent()) {
2833 if (targetFrame == m_frame->loader()->opener())
2836 if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
2840 printNavigationErrorMessage(targetFrame, url());
2844 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2846 Frame* currentFrame = m_frame;
2847 Frame* ancestorFrame = currentFrame->tree()->parent();
2849 while (ancestorFrame) {
2850 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2851 return currentFrame;
2852 currentFrame = ancestorFrame;
2853 ancestorFrame = ancestorFrame->tree()->parent();
2858 CSSStyleSheet* Document::pageUserSheet()
2860 if (m_pageUserSheet)
2861 return m_pageUserSheet.get();
2863 Page* owningPage = page();
2867 String userSheetText = owningPage->userStyleSheet();
2868 if (userSheetText.isEmpty())
2871 // Parse the sheet and cache it.
2872 m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2873 m_pageUserSheet->contents()->setIsUserStyleSheet(true);
2874 m_pageUserSheet->contents()->parseString(userSheetText);
2875 return m_pageUserSheet.get();
2878 void Document::clearPageUserSheet()
2880 if (m_pageUserSheet) {
2881 m_pageUserSheet = 0;
2882 styleResolverChanged(DeferRecalcStyle);
2886 void Document::updatePageUserSheet()
2888 clearPageUserSheet();
2889 if (pageUserSheet())
2890 styleResolverChanged(RecalcStyleImmediately);
2893 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2895 if (m_pageGroupUserSheetCacheValid)
2896 return m_pageGroupUserSheets.get();
2898 m_pageGroupUserSheetCacheValid = true;
2900 Page* owningPage = page();
2904 const PageGroup& pageGroup = owningPage->group();
2905 const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2909 UserStyleSheetMap::const_iterator end = sheetsMap->end();
2910 for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2911 const UserStyleSheetVector* sheets = it->second.get();
2912 for (unsigned i = 0; i < sheets->size(); ++i) {
2913 const UserStyleSheet* sheet = sheets->at(i).get();
2914 if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2916 if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2918 RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2919 if (!m_pageGroupUserSheets)
2920 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2921 m_pageGroupUserSheets->append(groupSheet);
2922 groupSheet->contents()->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
2923 groupSheet->contents()->parseString(sheet->source());
2927 return m_pageGroupUserSheets.get();
2930 void Document::clearPageGroupUserSheets()
2932 m_pageGroupUserSheetCacheValid = false;
2933 if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
2934 m_pageGroupUserSheets->clear();
2935 styleResolverChanged(DeferRecalcStyle);
2939 void Document::updatePageGroupUserSheets()
2941 clearPageGroupUserSheets();
2942 if (pageGroupUserSheets() && pageGroupUserSheets()->size())
2943 styleResolverChanged(RecalcStyleImmediately);
2946 void Document::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
2949 m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2950 m_userSheets->append(CSSStyleSheet::create(userSheet, this));
2951 styleResolverChanged(RecalcStyleImmediately);
2954 void Document::seamlessParentUpdatedStylesheets()
2956 styleResolverChanged(RecalcStyleImmediately);
2959 CSSStyleSheet* Document::elementSheet()
2962 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2963 return m_elemSheet.get();
2966 int Document::nodeAbsIndex(Node *node)
2968 ASSERT(node->document() == this);
2971 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2976 Node* Document::nodeWithAbsIndex(int absIndex)
2979 for (int i = 0; n && (i < absIndex); i++)
2980 n = n->traverseNextNode();
2984 void Document::processHttpEquiv(const String& equiv, const String& content)
2986 ASSERT(!equiv.isNull() && !content.isNull());
2988 Frame* frame = this->frame();
2990 if (equalIgnoringCase(equiv, "default-style")) {
2991 // The preferred style set has been overridden as per section
2992 // 14.3.2 of the HTML4.0 specification. We need to update the
2993 // sheet used variable and then update our style selector.
2994 // For more info, see the test at:
2995 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2997 m_selectedStylesheetSet = content;
2998 m_preferredStylesheetSet = content;
2999 styleResolverChanged(DeferRecalcStyle);
3000 } else if (equalIgnoringCase(equiv, "refresh")) {
3003 if (frame && parseHTTPRefresh(content, true, delay, url)) {
3005 url = m_url.string();
3007 url = completeURL(url).string();
3008 frame->navigationScheduler()->scheduleRedirect(delay, url);
3010 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3011 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3012 if (isHTMLDocument()) {
3013 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
3014 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
3016 } else if (equalIgnoringCase(equiv, "content-language"))
3017 setContentLanguage(content);
3018 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
3019 parseDNSPrefetchControlHeader(content);
3020 else if (equalIgnoringCase(equiv, "x-frame-options")) {
3022 FrameLoader* frameLoader = frame->loader();
3023 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
3024 frameLoader->stopAllLoaders();
3025 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
3027 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
3028 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
3031 } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
3032 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
3033 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
3034 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
3037 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3038 static bool isSeparator(UChar c)
3040 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3043 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3045 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3046 int keyBegin, keyEnd;
3047 int valueBegin, valueEnd;
3050 int length = features.length();
3051 String buffer = features.lower();
3052 while (i < length) {
3053 // skip to first non-separator, but don't skip past the end of the string
3054 while (isSeparator(buffer[i])) {
3061 // skip to first separator
3062 while (!isSeparator(buffer[i]))
3066 // skip to first '=', but don't skip past a ',' or the end of the string
3067 while (buffer[i] != '=') {
3068 if (buffer[i] == ',' || i >= length)
3073 // skip to first non-separator, but don't skip past a ',' or the end of the string
3074 while (isSeparator(buffer[i])) {
3075 if (buffer[i] == ',' || i >= length)
3081 // skip to first separator
3082 while (!isSeparator(buffer[i]))
3086 ASSERT(i <= length);
3088 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3089 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3090 callback(keyString, valueString, this, data);
3094 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3096 ASSERT(!features.isNull());
3098 if (origin < m_viewportArguments.type)
3101 m_viewportArguments = ViewportArguments(origin);
3102 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3104 updateViewportArguments();
3107 void Document::updateViewportArguments()
3109 if (page() && page()->mainFrame() == frame()) {
3111 m_didDispatchViewportPropertiesChanged = true;
3113 page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
3117 void Document::processReferrerPolicy(const String& policy)
3119 ASSERT(!policy.isNull());
3121 m_referrerPolicy = ReferrerPolicyDefault;
3123 if (equalIgnoringCase(policy, "never"))
3124 m_referrerPolicy = ReferrerPolicyNever;
3125 else if (equalIgnoringCase(policy, "always"))
3126 m_referrerPolicy = ReferrerPolicyAlways;
3127 else if (equalIgnoringCase(policy, "origin"))
3128 m_referrerPolicy = ReferrerPolicyOrigin;
3131 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3133 ASSERT(!renderer() || renderer()->isRenderView());
3136 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3138 HitTestResult result(documentPoint);
3139 renderView()->hitTest(request, result);
3141 if (!request.readOnly())
3142 updateStyleIfNeeded();
3144 return MouseEventWithHitTestResults(event, result);
3147 // DOM Section 1.1.1
3148 bool Document::childTypeAllowed(NodeType type) const
3151 case ATTRIBUTE_NODE:
3152 case CDATA_SECTION_NODE:
3153 case DOCUMENT_FRAGMENT_NODE:
3156 case ENTITY_REFERENCE_NODE:
3159 case XPATH_NAMESPACE_NODE:
3162 case PROCESSING_INSTRUCTION_NODE:
3164 case DOCUMENT_TYPE_NODE:
3166 // Documents may contain no more than one of each of these.
3167 // (One Element and one DocumentType.)
3168 for (Node* c = firstChild(); c; c = c->nextSibling())
3169 if (c->nodeType() == type)
3176 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3179 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3182 if (oldChild->nodeType() == newChild->nodeType())
3185 int numDoctypes = 0;
3186 int numElements = 0;
3188 // First, check how many doctypes and elements we have, not counting
3189 // the child we're about to remove.
3190 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3194 switch (c->nodeType()) {
3195 case DOCUMENT_TYPE_NODE:
3206 // Then, see how many doctypes and elements might be added by the new child.
3207 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3208 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3209 switch (c->nodeType()) {
3210 case ATTRIBUTE_NODE:
3211 case CDATA_SECTION_NODE:
3212 case DOCUMENT_FRAGMENT_NODE:
3215 case ENTITY_REFERENCE_NODE:
3218 case XPATH_NAMESPACE_NODE:
3221 case PROCESSING_INSTRUCTION_NODE:
3223 case DOCUMENT_TYPE_NODE:
3232 switch (newChild->nodeType()) {
3233 case ATTRIBUTE_NODE:
3234 case CDATA_SECTION_NODE:
3235 case DOCUMENT_FRAGMENT_NODE:
3238 case ENTITY_REFERENCE_NODE:
3241 case XPATH_NAMESPACE_NODE:
3244 case PROCESSING_INSTRUCTION_NODE:
3246 case DOCUMENT_TYPE_NODE:
3255 if (numElements > 1 || numDoctypes > 1)
3261 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3263 // Spec says cloning Document nodes is "implementation dependent"
3264 // so we do not support it...
3268 StyleSheetList* Document::styleSheets()
3270 return m_styleSheets.get();
3273 String Document::preferredStylesheetSet() const
3275 return m_preferredStylesheetSet;
3278 String Document::selectedStylesheetSet() const
3280 return m_selectedStylesheetSet;
3283 void Document::setSelectedStylesheetSet(const String& aString)
3285 m_selectedStylesheetSet = aString;
3286 styleResolverChanged(DeferRecalcStyle);
3289 // This method is called whenever a top-level stylesheet has finished loading.
3290 void Document::removePendingSheet()
3292 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
3293 ASSERT(m_pendingStylesheets > 0);
3295 m_pendingStylesheets--;
3297 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3298 if (!ownerElement())
3299 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
3302 if (m_pendingStylesheets)
3305 styleResolverChanged(RecalcStyleIfNeeded);
3307 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3308 parser->executeScriptsWaitingForStylesheets();
3310 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3311 view()->scrollToFragment(m_url);
3314 void Document::evaluateMediaQueryList()
3316 if (m_mediaQueryMatcher)
3317 m_mediaQueryMatcher->styleResolverChanged();
3320 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3322 // Don't bother updating, since we haven't loaded all our style info yet
3323 // and haven't calculated the style selector for the first time.
3324 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3325 m_styleResolver.clear();
3329 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3330 if (!ownerElement())
3331 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3334 bool stylesheetChangeRequiresStyleRecalc = updateActiveStylesheets(updateFlag);
3336 if (updateFlag == DeferRecalcStyle) {
3337 scheduleForcedStyleRecalc();
3341 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
3342 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3344 renderer()->repaint();
3347 if (!stylesheetChangeRequiresStyleRecalc)
3350 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3351 // make sure animations get the correct update time
3353 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
3357 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3358 if (!ownerElement())
3359 printf("Finished update of style selector at time %d\n", elapsedTime());
3363 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3365 view()->scheduleRelayout();
3368 evaluateMediaQueryList();
3371 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
3373 if (!node->inDocument())
3376 // Until the <body> exists, we have no choice but to compare document positions,
3377 // since styles outside of the body and head continue to be shunted into the head
3378 // (and thus can shift to end up before dynamically added DOM content that is also
3379 // outside the body).
3380 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3381 m_styleSheetCandidateNodes.add(node);
3385 // Determine an appropriate insertion point.
3386 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3387 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3388 StyleSheetCandidateListHashSet::iterator it = end;
3389 Node* followingNode = 0;
3393 unsigned short position = n->compareDocumentPosition(node);
3394 if (position == DOCUMENT_POSITION_FOLLOWING) {
3395 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3399 } while (it != begin);
3401 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3404 void Document::removeStyleSheetCandidateNode(Node* node)
3406 m_styleSheetCandidateNodes.remove(node);
3409 void Document::collectActiveStylesheets(Vector<RefPtr<StyleSheet> >& sheets)
3411 if (settings() && !settings()->authorAndUserStylesEnabled())
3414 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3415 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3416 for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3418 StyleSheet* sheet = 0;
3419 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3420 // Processing instruction (XML documents only).
3421 // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3422 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3423 sheet = pi->sheet();
3425 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3426 if (pi->isXSL() && !transformSourceDocument()) {
3427 // Don't apply XSL transforms until loading is finished.
3429 applyXSLTransform(pi);
3433 } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3435 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3438 Element* e = static_cast<Element*>(n);
3439 AtomicString title = e->getAttribute(titleAttr);
3440 bool enabledViaScript = false;
3441 if (e->hasLocalName(linkTag)) {
3443 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3444 if (linkElement->isDisabled())
3446 enabledViaScript = linkElement->isEnabledViaScript();
3447 if (linkElement->styleSheetIsLoading()) {
3448 // it is loading but we should still decide which style sheet set to use
3449 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3450 const AtomicString& rel = e->getAttribute(relAttr);
3451 if (!rel.contains("alternate")) {
3452 m_preferredStylesheetSet = title;
3453 m_selectedStylesheetSet = title;
3458 if (!linkElement->sheet())
3461 // Get the current preferred styleset. This is the
3462 // set of sheets that will be enabled.
3464 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3465 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3468 if (e->hasLocalName(linkTag))
3469 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3472 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3473 // Check to see if this sheet belongs to a styleset
3474 // (thus making it PREFERRED or ALTERNATE rather than
3476 AtomicString rel = e->getAttribute(relAttr);
3477 if (!enabledViaScript && !title.isEmpty()) {
3478 // Yes, we have a title.
3479 if (m_preferredStylesheetSet.isEmpty()) {
3480 // No preferred set has been established. If
3481 // we are NOT an alternate sheet, then establish
3482 // us as the preferred set. Otherwise, just ignore
3484 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3485 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3487 if (title != m_preferredStylesheetSet)
3491 if (rel.contains("alternate") && title.isEmpty())
3495 sheets.append(sheet);
3499 bool Document::testAddedStylesheetRequiresStyleRecalc(StyleSheetContents* stylesheet)
3501 // See if all rules on the sheet are scoped to some specific ids or classes.
3502 // Then test if we actually have any of those in the tree at the moment.
3503 HashSet<AtomicStringImpl*> idScopes;
3504 HashSet<AtomicStringImpl*> classScopes;
3505 if (!StyleResolver::determineStylesheetSelectorScopes(stylesheet, idScopes, classScopes))
3507 // Invalidate the subtrees that match the scopes.
3508 Node* node = firstChild();
3510 if (!node->isStyledElement()) {
3511 node = node->traverseNextNode();
3514 StyledElement* element = static_cast<StyledElement*>(node);
3515 if (SelectorChecker::elementMatchesSelectorScopes(element, idScopes, classScopes)) {
3516 element->setNeedsStyleRecalc();
3517 // The whole subtree is now invalidated, we can skip to the next sibling.
3518 node = node->traverseNextSibling();
3521 node = node->traverseNextNode();
3526 void Document::analyzeStylesheetChange(StyleResolverUpdateFlag updateFlag, const Vector<RefPtr<StyleSheet> >& newStylesheets, bool& requiresStyleResolverReset, bool& requiresFullStyleRecalc)
3528 requiresStyleResolverReset = true;
3529 requiresFullStyleRecalc = true;
3531 // Stylesheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
3532 bool hasActiveLoadingStylesheet = false;
3533 unsigned newStylesheetCount = newStylesheets.size();
3534 for (unsigned i = 0; i < newStylesheetCount; ++i) {
3535 if (newStylesheets[i]->isLoading())
3536 hasActiveLoadingStylesheet = true;
3538 if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
3539 m_hadActiveLoadingStylesheet = false;
3542 m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
3544 if (updateFlag != RecalcStyleIfNeeded)
3546 if (!m_styleResolver)
3549 // See if we are just adding stylesheets.
3550 unsigned oldStylesheetCount = m_styleSheets->length();
3551 if (newStylesheetCount < oldStylesheetCount)
3553 for (unsigned i = 0; i < oldStylesheetCount; ++i) {
3554 if (m_styleSheets->item(i) != newStylesheets[i])
3557 requiresStyleResolverReset = false;
3559 // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
3560 if (!body() || m_hasNodesWithPlaceholderStyle)
3562 for (unsigned i = oldStylesheetCount; i < newStylesheetCount; ++i) {
3563 if (!newStylesheets[i]->isCSSStyleSheet())
3565 if (newStylesheets[i]->disabled())
3567 if (testAddedStylesheetRequiresStyleRecalc(static_cast<CSSStyleSheet*>(newStylesheets[i].get())->contents()))
3570 requiresFullStyleRecalc = false;
3573 static bool styleSheetsUseRemUnits(const Vector<RefPtr<StyleSheet> >& sheets)
3575 for (unsigned i = 0; i < sheets.size(); ++i) {
3576 if (!sheets[i]->isCSSStyleSheet())
3578 if (static_cast<CSSStyleSheet*>(sheets[i].get())->contents()->usesRemUnits())
3584 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3586 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3590 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3591 for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
3592 Document* childDocument = child->document();
3593 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3594 ASSERT(childDocument->seamlessParentIFrame()->document() == this);
3595 childDocument->seamlessParentUpdatedStylesheets();
3600 bool Document::updateActiveStylesheets(StyleResolverUpdateFlag updateFlag)
3602 if (m_inStyleRecalc) {
3603 // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3604 // https://bugs.webkit.org/show_bug.cgi?id=54344
3605 // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3606 m_hasDirtyStyleResolver = true;
3607 scheduleForcedStyleRecalc();
3610 if (!renderer() || !attached())
3613 StyleSheetVector newStylesheets;
3614 collectActiveStylesheets(newStylesheets);
3616 bool requiresStyleResolverReset;
3617 bool requiresFullStyleRecalc;
3618 analyzeStylesheetChange(updateFlag, newStylesheets, requiresStyleResolverReset, requiresFullStyleRecalc);
3620 if (requiresStyleResolverReset)
3621 clearStyleResolver();
3623 m_styleResolver->appendAuthorStylesheets(m_styleSheets->length(), newStylesheets);
3624 resetCSSFeatureFlags();
3626 m_styleSheets->swap(newStylesheets);
3628 m_usesRemUnits = styleSheetsUseRemUnits(m_styleSheets->vector());
3629 m_didCalculateStyleResolver = true;
3630 m_hasDirtyStyleResolver = false;
3632 notifySeamlessChildDocumentsOfStylesheetUpdate();
3634 return requiresFullStyleRecalc;
3637 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3639 m_hoverNode = newHoverNode;