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 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)
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
30 #include "AXObjectCache.h"
31 #include "AnimationController.h"
33 #include "Attribute.h"
34 #include "CDATASection.h"
35 #include "CSSStyleSelector.h"
36 #include "CSSStyleSheet.h"
37 #include "CSSValueKeywords.h"
38 #include "CSSValuePool.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedResourceLoader.h"
42 #include "ChromeClient.h"
45 #include "ContentSecurityPolicy.h"
46 #include "CookieJar.h"
47 #include "DOMImplementation.h"
48 #include "DOMWindow.h"
49 #include "DateComponents.h"
50 #include "DeviceMotionController.h"
51 #include "DeviceMotionEvent.h"
52 #include "DeviceOrientationController.h"
53 #include "DeviceOrientationEvent.h"
54 #include "DocumentEventQueue.h"
55 #include "DocumentFragment.h"
56 #include "DocumentLoader.h"
57 #include "DocumentMarkerController.h"
58 #include "DocumentType.h"
59 #include "EditingText.h"
62 #include "EntityReference.h"
64 #include "EventFactory.h"
65 #include "EventHandler.h"
66 #include "EventListener.h"
67 #include "EventNames.h"
68 #include "ExceptionCode.h"
69 #include "FocusController.h"
70 #include "FormAssociatedElement.h"
72 #include "FrameLoader.h"
73 #include "FrameLoaderClient.h"
74 #include "FrameSelection.h"
75 #include "FrameTree.h"
76 #include "FrameView.h"
77 #include "GeolocationController.h"
78 #include "HashChangeEvent.h"
79 #include "HTMLAllCollection.h"
80 #include "HTMLAnchorElement.h"
81 #include "HTMLBodyElement.h"
82 #include "HTMLCanvasElement.h"
83 #include "HTMLCollection.h"
84 #include "HTMLDocument.h"
85 #include "HTMLElementFactory.h"
86 #include "HTMLFrameOwnerElement.h"
87 #include "HTMLHeadElement.h"
88 #include "HTMLIFrameElement.h"
89 #include "HTMLInputElement.h"
90 #include "HTMLLinkElement.h"
91 #include "HTMLMapElement.h"
92 #include "HTMLNameCollection.h"
93 #include "HTMLNames.h"
94 #include "HTMLParserIdioms.h"
95 #include "HTMLStyleElement.h"
96 #include "HTMLTitleElement.h"
97 #include "HTTPParsers.h"
98 #include "HitTestRequest.h"
99 #include "HitTestResult.h"
100 #include "ImageLoader.h"
101 #include "InspectorInstrumentation.h"
103 #include "MediaQueryList.h"
104 #include "MediaQueryMatcher.h"
105 #include "MouseEventWithHitTestResults.h"
106 #include "NameNodeList.h"
107 #include "NestingLevelIncrementer.h"
108 #include "NewXMLDocumentParser.h"
109 #include "NodeFilter.h"
110 #include "NodeIterator.h"
111 #include "NodeWithIndex.h"
113 #include "PageGroup.h"
114 #include "PageTransitionEvent.h"
115 #include "PlatformKeyboardEvent.h"
116 #include "PopStateEvent.h"
117 #include "ProcessingInstruction.h"
118 #include "RegisteredEventListener.h"
119 #include "RenderArena.h"
120 #include "RenderLayer.h"
121 #include "RenderLayerBacking.h"
122 #include "RenderTextControl.h"
123 #include "RenderView.h"
124 #include "RenderWidget.h"
125 #include "SchemeRegistry.h"
126 #include "ScopedEventQueue.h"
127 #include "ScriptCallStack.h"
128 #include "ScriptController.h"
129 #include "ScriptElement.h"
130 #include "ScriptEventListener.h"
131 #include "ScriptRunner.h"
132 #include "SecurityOrigin.h"
133 #include "SecurityPolicy.h"
134 #include "SegmentedString.h"
135 #include "Settings.h"
136 #include "ShadowRoot.h"
137 #include "StaticHashSetNodeList.h"
138 #include "StyleSheetList.h"
139 #include "TextResourceDecoder.h"
141 #include "TransformSource.h"
142 #include "TreeWalker.h"
143 #include "UserContentURLPattern.h"
144 #include "XMLDocumentParser.h"
145 #include "XMLHttpRequest.h"
146 #include "XMLNSNames.h"
147 #include "XMLNames.h"
148 #include "XPathEvaluator.h"
149 #include "XPathExpression.h"
150 #include "XPathNSResolver.h"
151 #include "XPathResult.h"
152 #include "htmlediting.h"
153 #include <wtf/CurrentTime.h>
154 #include <wtf/HashFunctions.h>
155 #include <wtf/MainThread.h>
156 #include <wtf/PassRefPtr.h>
157 #include <wtf/StdLibExtras.h>
158 #include <wtf/text/StringBuffer.h>
160 #if PLATFORM(CHROMIUM)
161 #include "PlatformSupport.h"
164 #if ENABLE(SHARED_WORKERS)
165 #include "SharedWorkerRepository.h"
169 #include "XSLTProcessor.h"
173 #include "SVGDocumentExtensions.h"
174 #include "SVGElementFactory.h"
175 #include "SVGNames.h"
176 #include "SVGStyleElement.h"
179 #if ENABLE(TOUCH_EVENTS)
180 #include "TouchList.h"
184 #include "MathMLElement.h"
185 #include "MathMLElementFactory.h"
186 #include "MathMLNames.h"
189 #if ENABLE(FULLSCREEN_API)
190 #include "RenderFullScreen.h"
193 #if ENABLE(REQUEST_ANIMATION_FRAME)
194 #include "RequestAnimationFrameCallback.h"
195 #include "ScriptedAnimationController.h"
198 #if ENABLE(MICRODATA)
199 #include "MicroDataItemList.h"
200 #include "NodeRareData.h"
205 using namespace Unicode;
209 using namespace HTMLNames;
211 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
213 static const unsigned cMaxWriteRecursionDepth = 21;
215 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
216 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
218 static const int cLayoutScheduleThreshold = 250;
220 // DOM Level 2 says (letters added):
222 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
223 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
224 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
225 // 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.
226 // 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.
227 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
228 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
229 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
230 // i) Characters ':' and '_' are allowed as name-start characters.
231 // j) Characters '-' and '.' are allowed as name characters.
233 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
235 static inline bool isValidNameStart(UChar32 c)
238 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
242 if (c == ':' || c == '_')
245 // rules (a) and (f) above
246 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
247 if (!(Unicode::category(c) & nameStartMask))
251 if (c >= 0xF900 && c < 0xFFFE)
255 DecompositionType decompType = decompositionType(c);
256 if (decompType == DecompositionFont || decompType == DecompositionCompat)
262 static inline bool isValidNamePart(UChar32 c)
264 // rules (a), (e), and (i) above
265 if (isValidNameStart(c))
268 // rules (g) and (h) above
269 if (c == 0x00B7 || c == 0x0387)
273 if (c == '-' || c == '.')
276 // rules (b) and (f) above
277 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
278 if (!(Unicode::category(c) & otherNamePartMask))
282 if (c >= 0xF900 && c < 0xFFFE)
286 DecompositionType decompType = decompositionType(c);
287 if (decompType == DecompositionFont || decompType == DecompositionCompat)
293 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
295 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
297 // If a Document has the address "about:blank"
298 // The origin of the Document is the origin it was assigned when its browsing context was created.
300 // Note: We generalize this to all "about" URLs and invalid URLs because we
301 // treat all of these URLs as about:blank.
303 return !url.isValid() || url.protocolIs("about");
306 static Widget* widgetForNode(Node* focusedNode)
310 RenderObject* renderer = focusedNode->renderer();
311 if (!renderer || !renderer->isWidget())
313 return toRenderWidget(renderer)->widget();
316 static bool acceptsEditingFocus(Node* node)
319 ASSERT(node->rendererIsEditable());
321 Node* root = node->rootEditableElement();
322 Frame* frame = node->document()->frame();
326 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
329 static bool disableRangeMutation(Page* page)
331 // This check is made on super-hot code paths, so we only want this on Leopard.
332 #ifdef TARGETING_LEOPARD
333 // Disable Range mutation on document modifications in Leopard Mail.
334 // See <rdar://problem/5865171>
335 return page && page->settings()->needsLeopardMailQuirks();
342 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
344 class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
346 static PassRefPtr<DocumentWeakReference> create(Document* document)
348 return adoptRef(new DocumentWeakReference(document));
353 ASSERT(isMainThread());
359 ASSERT(isMainThread());
364 DocumentWeakReference(Document* document)
365 : m_document(document)
367 ASSERT(isMainThread());
370 Document* m_document;
373 uint64_t Document::s_globalTreeVersion = 0;
375 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
378 , m_compatibilityMode(NoQuirksMode)
379 , m_compatibilityModeLocked(false)
380 , m_domTreeVersion(++s_globalTreeVersion)
381 #if ENABLE(MUTATION_OBSERVERS)
382 , m_subtreeMutationObserverTypes(0)
384 , m_styleSheets(StyleSheetList::create(this))
385 , m_readyState(Complete)
386 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
387 , m_pendingStyleRecalcShouldForce(false)
388 , m_frameElementsShouldIgnoreScrolling(false)
389 , m_containsValidityStyleRules(false)
390 , m_updateFocusAppearanceRestoresSelection(false)
391 , m_ignoreDestructiveWriteCount(0)
392 , m_titleSetExplicitly(false)
393 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
394 , m_loadEventFinished(false)
395 , m_startTime(currentTime())
396 , m_overMinimumLayoutThreshold(false)
397 , m_scriptRunner(ScriptRunner::create(this))
398 , m_xmlVersion("1.0")
399 , m_xmlStandalone(false)
401 , m_designMode(inherit)
402 #if ENABLE(DASHBOARD_SUPPORT)
403 , m_hasDashboardRegions(false)
404 , m_dashboardRegionsDirty(false)
406 , m_createRenderers(true)
407 , m_inPageCache(false)
408 , m_accessKeyMapValid(false)
409 , m_useSecureKeyboardEntryWhenActive(false)
412 , m_isViewSource(false)
413 , m_sawElementsInKnownNamespaces(false)
414 , m_usingGeolocation(false)
415 , m_eventQueue(DocumentEventQueue::create(this))
416 , m_weakReference(DocumentWeakReference::create(this))
417 , m_idAttributeName(idAttr)
418 #if ENABLE(FULLSCREEN_API)
419 , m_areKeysEnabledInFullScreen(0)
420 , m_fullScreenRenderer(0)
421 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
422 , m_isAnimatingFullScreen(false)
424 , m_loadEventDelayCount(0)
425 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
426 , m_referrerPolicy(SecurityPolicy::ReferrerPolicyDefault)
427 , m_directionSetOnDocumentElement(false)
428 , m_writingModeSetOnDocumentElement(false)
429 , m_writeRecursionIsTooDeep(false)
430 , m_writeRecursionDepth(0)
431 , m_wheelEventHandlerCount(0)
435 m_pageGroupUserSheetCacheValid = false;
438 m_paginatedForScreen = false;
440 m_ignoreAutofocus = false;
444 // We depend on the url getting immediately set in subframes, but we
445 // also depend on the url NOT getting immediately set in opened windows.
446 // See fast/dom/early-frame-url.html
447 // and fast/dom/location-new-window-no-crash.html, respectively.
448 // FIXME: Can/should we unify this behavior?
449 if ((frame && frame->ownerElement()) || !url.isEmpty())
454 m_markers = adoptPtr(new DocumentMarkerController);
456 m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
458 m_visuallyOrdered = false;
460 m_wellFormed = false;
462 m_textColor = Color::black;
465 m_inStyleRecalc = false;
466 m_closeAfterStyleRecalc = false;
468 m_usesSiblingRules = false;
469 m_usesSiblingRulesOverride = false;
470 m_usesFirstLineRules = false;
471 m_usesFirstLetterRules = false;
472 m_usesBeforeAfterRules = false;
473 m_usesBeforeAfterRulesOverride = false;
474 m_usesRemUnits = false;
475 m_usesLinkRules = false;
477 m_gotoAnchorNeededAfterStylesheetsLoad = false;
479 m_didCalculateStyleSelector = false;
480 m_hasDirtyStyleSelector = false;
481 m_pendingStylesheets = 0;
482 m_ignorePendingStylesheets = false;
483 m_hasNodesWithPlaceholderStyle = false;
484 m_pendingSheetLayout = NoLayoutWithPendingSheets;
489 resetVisitedLinkColor();
490 resetActiveLinkColor();
492 m_processingLoadEvent = false;
494 initSecurityContext();
497 static int docID = 0;
501 #if PLATFORM(CHROMIUM)
502 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
504 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
505 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
506 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
507 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
508 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
509 PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
513 Document::~Document()
516 ASSERT(!m_inPageCache);
517 ASSERT(!m_savedRenderer);
518 ASSERT(m_ranges.isEmpty());
519 ASSERT(!m_styleRecalcTimer.isActive());
520 ASSERT(!m_parentTreeScope);
521 ASSERT(!m_guardRefCount);
523 m_scriptRunner.clear();
525 #if PLATFORM(CHROMIUM)
526 histogramMutationEventUsage(m_listenerTypes);
529 removeAllEventListeners();
531 // Currently we believe that Document can never outlive the parser.
532 // Although the Document may be replaced synchronously, DocumentParsers
533 // generally keep at least one reference to an Element which would in turn
534 // has a reference to the Document. If you hit this ASSERT, then that
535 // assumption is wrong. DocumentParser::detach() should ensure that even
536 // if the DocumentParser outlives the Document it won't cause badness.
537 ASSERT(!m_parser || m_parser->refCount() == 1);
540 m_cachedResourceLoader.clear();
542 m_renderArena.clear();
544 clearAXObjectCache();
548 for (size_t i = 0; i < m_nameCollectionInfo.size(); ++i)
549 deleteAllValues(m_nameCollectionInfo[i]);
552 m_styleSheets->documentDestroyed();
555 m_elemSheet->clearOwnerNode();
556 if (m_mappedElementSheet)
557 m_mappedElementSheet->clearOwnerNode();
559 m_pageUserSheet->clearOwnerNode();
560 if (m_pageGroupUserSheets) {
561 for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
562 (*m_pageGroupUserSheets)[i]->clearOwnerNode();
565 for (size_t i = 0; i < m_userSheets->size(); ++i)
566 (*m_userSheets)[i]->clearOwnerNode();
571 m_weakReference->clear();
573 if (m_mediaQueryMatcher)
574 m_mediaQueryMatcher->documentDestroyed();
577 void Document::removedLastRef()
579 ASSERT(!m_deletionHasBegun);
580 if (m_guardRefCount) {
581 // If removing a child removes the last self-only ref, we don't
582 // want the scope to be destructed until after
583 // removeAllChildren returns, so we guard ourselves with an
584 // extra self-only ref.
587 // We must make sure not to be retaining any of our children through
588 // these extra pointers or we will create a reference cycle.
594 m_documentElement = 0;
595 #if ENABLE(FULLSCREEN_API)
596 m_fullScreenElement = 0;
599 // removeAllChildren() doesn't always unregister IDs,
600 // so tear down scope information upfront to avoid having stale references in the map.
601 destroyTreeScopeData();
608 m_cssCanvasElements.clear();
610 #if ENABLE(REQUEST_ANIMATION_FRAME)
611 // FIXME: consider using ActiveDOMObject.
612 m_scriptedAnimationController = nullptr;
616 m_inRemovedLastRefFunction = false;
622 m_deletionHasBegun = true;
628 Element* Document::getElementById(const AtomicString& id) const
630 return TreeScope::getElementById(id);
633 Element* Document::getElementByAccessKey(const String& key)
637 if (!m_accessKeyMapValid) {
638 buildAccessKeyMap(this);
639 m_accessKeyMapValid = true;
641 return m_elementsByAccessKey.get(key.impl());
644 void Document::buildAccessKeyMap(TreeScope* root)
646 for (Node* n = root; n; n = n->traverseNextNode(root)) {
647 if (!n->isElementNode())
649 Element* element = static_cast<Element*>(n);
650 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
651 if (!accessKey.isEmpty())
652 m_elementsByAccessKey.set(accessKey.impl(), element);
653 buildAccessKeyMap(element->shadowRoot());
657 void Document::invalidateAccessKeyMap()
659 m_accessKeyMapValid = false;
660 m_elementsByAccessKey.clear();
663 MediaQueryMatcher* Document::mediaQueryMatcher()
665 if (!m_mediaQueryMatcher)
666 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
667 return m_mediaQueryMatcher.get();
670 void Document::setCompatibilityMode(CompatibilityMode mode)
672 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
674 ASSERT(!m_styleSheets->length());
675 bool wasInQuirksMode = inQuirksMode();
676 m_compatibilityMode = mode;
677 if (inQuirksMode() != wasInQuirksMode) {
678 // All user stylesheets have to reparse using the different mode.
679 clearPageUserSheet();
680 clearPageGroupUserSheets();
684 String Document::compatMode() const
686 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
689 void Document::resetLinkColor()
691 m_linkColor = Color(0, 0, 238);
694 void Document::resetVisitedLinkColor()
696 m_visitedLinkColor = Color(85, 26, 139);
699 void Document::resetActiveLinkColor()
701 m_activeLinkColor.setNamedColor("red");
704 void Document::setDocType(PassRefPtr<DocumentType> docType)
706 // This should never be called more than once.
707 ASSERT(!m_docType || !docType);
710 m_docType->setTreeScopeRecursively(this);
713 DOMImplementation* Document::implementation()
715 if (!m_implementation)
716 m_implementation = DOMImplementation::create(this);
717 return m_implementation.get();
720 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
722 TreeScope::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
724 // Invalidate the document element we have cached in case it was replaced.
725 m_documentElement = 0;
728 void Document::cacheDocumentElement() const
730 ASSERT(!m_documentElement);
731 m_documentElement = firstElementChild(this);
734 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
736 if (!isValidName(name)) {
737 ec = INVALID_CHARACTER_ERR;
742 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
744 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
747 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
749 return DocumentFragment::create(document());
752 PassRefPtr<Text> Document::createTextNode(const String& data)
754 return Text::create(this, data);
757 PassRefPtr<Comment> Document::createComment(const String& data)
759 return Comment::create(this, data);
762 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
764 if (isHTMLDocument()) {
765 ec = NOT_SUPPORTED_ERR;
768 return CDATASection::create(this, data);
771 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
773 if (!isValidName(target)) {
774 ec = INVALID_CHARACTER_ERR;
777 if (isHTMLDocument()) {
778 ec = NOT_SUPPORTED_ERR;
781 return ProcessingInstruction::create(this, target, data);
784 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
786 if (!isValidName(name)) {
787 ec = INVALID_CHARACTER_ERR;
790 if (isHTMLDocument()) {
791 ec = NOT_SUPPORTED_ERR;
794 return EntityReference::create(this, name);
797 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
799 return EditingText::create(this, text);
802 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
804 return CSSMutableStyleDeclaration::create();
807 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
812 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
813 || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
816 ec = NOT_SUPPORTED_ERR;
820 switch (importedNode->nodeType()) {
822 return createTextNode(importedNode->nodeValue());
823 case CDATA_SECTION_NODE:
824 return createCDATASection(importedNode->nodeValue(), ec);
825 case ENTITY_REFERENCE_NODE:
826 return createEntityReference(importedNode->nodeName(), ec);
827 case PROCESSING_INSTRUCTION_NODE:
828 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
830 return createComment(importedNode->nodeValue());
832 Element* oldElement = static_cast<Element*>(importedNode);
833 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
838 NamedNodeMap* attrs = oldElement->attributes(true);
840 unsigned length = attrs->length();
841 for (unsigned i = 0; i < length; i++) {
842 Attribute* attr = attrs->attributeItem(i);
843 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
849 newElement->copyNonAttributeProperties(oldElement);
852 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
853 RefPtr<Node> newChild = importNode(oldChild, true, ec);
856 newElement->appendChild(newChild.release(), ec);
862 return newElement.release();
865 return Attr::create(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
866 case DOCUMENT_FRAGMENT_NODE: {
867 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
868 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
870 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
871 RefPtr<Node> newChild = importNode(oldChild, true, ec);
874 newFragment->appendChild(newChild.release(), ec);
880 return newFragment.release();
884 // 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.
885 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
887 case DOCUMENT_TYPE_NODE:
888 case XPATH_NAMESPACE_NODE:
889 case SHADOW_ROOT_NODE:
890 // ShadowRoot nodes should not be explicitly importable.
891 // Either they are imported along with their host node, or created implicitly.
894 ec = NOT_SUPPORTED_ERR;
899 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
902 ec = NOT_SUPPORTED_ERR;
906 if (source->isReadOnlyNode()) {
907 ec = NO_MODIFICATION_ALLOWED_ERR;
911 EventQueueScope scope;
913 switch (source->nodeType()) {
917 case DOCUMENT_TYPE_NODE:
918 case XPATH_NAMESPACE_NODE:
919 ec = NOT_SUPPORTED_ERR;
921 case ATTRIBUTE_NODE: {
922 Attr* attr = static_cast<Attr*>(source.get());
923 if (attr->ownerElement())
924 attr->ownerElement()->removeAttributeNode(attr, ec);
925 attr->setSpecified(true);
929 if (source->hasTagName(iframeTag)) {
930 HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
931 if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
932 ec = HIERARCHY_REQUEST_ERR;
935 iframe->setRemainsAliveOnRemovalFromTree(attached() && source->attached() && iframe->canRemainAliveOnRemovalFromTree());
938 if (source->parentNode())
939 source->parentNode()->removeChild(source.get(), ec);
942 source->setTreeScopeRecursively(this);
947 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
949 // These checks are from DOM Core Level 2, createElementNS
950 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
951 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
953 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
956 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
957 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
958 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
959 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
965 // FIXME: This should really be in a possible ElementFactory class
966 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
970 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
971 if (qName.namespaceURI() == xhtmlNamespaceURI)
972 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
974 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
975 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
978 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
979 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
983 m_sawElementsInKnownNamespaces = true;
985 e = Element::create(qName, document());
987 // <image> uses imgTag so we need a special rule.
988 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
993 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
995 String prefix, localName;
996 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
999 QualifiedName qName(prefix, localName, namespaceURI);
1000 if (hasPrefixNamespaceMismatch(qName)) {
1005 return createElement(qName, false);
1008 String Document::readyState() const
1010 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1011 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1012 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1014 switch (m_readyState) {
1023 ASSERT_NOT_REACHED();
1027 void Document::setReadyState(ReadyState readyState)
1029 if (readyState == m_readyState)
1032 switch (readyState) {
1034 if (!m_documentTiming.domLoading)
1035 m_documentTiming.domLoading = currentTime();
1038 if (!m_documentTiming.domInteractive)
1039 m_documentTiming.domInteractive = currentTime();
1042 if (!m_documentTiming.domComplete)
1043 m_documentTiming.domComplete = currentTime();
1047 m_readyState = readyState;
1048 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1051 String Document::encoding() const
1053 if (TextResourceDecoder* d = decoder())
1054 return d->encoding().domName();
1058 String Document::defaultCharset() const
1060 if (Settings* settings = this->settings())
1061 return settings->defaultTextEncodingName();
1065 void Document::setCharset(const String& charset)
1069 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1072 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1074 if (!implementation()->hasFeature("XML", String())) {
1075 ec = NOT_SUPPORTED_ERR;
1079 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1080 ec = NOT_SUPPORTED_ERR;
1084 m_xmlVersion = version;
1087 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1089 if (!implementation()->hasFeature("XML", String())) {
1090 ec = NOT_SUPPORTED_ERR;
1094 m_xmlStandalone = standalone;
1097 void Document::setDocumentURI(const String& uri)
1099 m_documentURI = uri;
1103 KURL Document::baseURI() const
1108 void Document::setContent(const String& content)
1111 m_parser->append(content);
1115 String Document::suggestedMIMEType() const
1117 if (m_document->isXHTMLDocument())
1118 return "application/xhtml+xml";
1119 if (m_document->isSVGDocument())
1120 return "image/svg+xml";
1121 if (m_document->xmlStandalone())
1123 if (m_document->isHTMLDocument())
1126 if (DocumentLoader* documentLoader = loader())
1127 return documentLoader->responseMIMEType();
1131 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1132 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1133 // * making it receive the expading size of each direction separately,
1134 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1135 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping) const
1137 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1140 Frame* frame = this->frame();
1143 FrameView* frameView = frame->view();
1147 float zoomFactor = frame->pageZoomFactor();
1148 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1150 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1152 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1154 type |= HitTestRequest::IgnoreClipping;
1155 else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1158 HitTestRequest request(type);
1160 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1161 // we special handle this case in order to return a valid NodeList.
1162 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1163 HitTestResult result(point);
1164 return handleZeroPadding(request, result);
1167 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1168 renderView()->layer()->hitTest(request, result);
1170 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1173 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1175 renderView()->layer()->hitTest(request, result);
1177 Node* node = result.innerNode();
1181 node = node->shadowAncestorNode();
1182 ListHashSet<RefPtr<Node> > list;
1184 return StaticHashSetNodeList::adopt(list);
1187 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1191 FrameView* frameView = frame->view();
1195 float zoomFactor = frame->pageZoomFactor();
1196 IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1198 if (!frameView->visibleContentRect().contains(point))
1201 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1202 HitTestResult result(point);
1203 renderView->layer()->hitTest(request, result);
1206 *localPoint = result.localPoint();
1208 return result.innerNode();
1211 Element* Document::elementFromPoint(int x, int y) const
1215 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1216 while (node && !node->isElementNode())
1217 node = node->parentNode();
1219 node = node->shadowAncestorNode();
1220 return static_cast<Element*>(node);
1223 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1227 LayoutPoint localPoint;
1228 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1232 Node* shadowAncestorNode = node->shadowAncestorNode();
1233 if (shadowAncestorNode != node) {
1234 unsigned offset = shadowAncestorNode->nodeIndex();
1235 ContainerNode* container = shadowAncestorNode->parentNode();
1236 return Range::create(this, container, offset, container, offset);
1239 RenderObject* renderer = node->renderer();
1242 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1243 if (visiblePosition.isNull())
1246 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1247 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1251 * Performs three operations:
1252 * 1. Convert control characters to spaces
1253 * 2. Trim leading and trailing spaces
1254 * 3. Collapse internal whitespace.
1256 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1258 const String& title = titleWithDirection.string();
1259 const UChar* characters = title.characters();
1260 unsigned length = title.length();
1263 StringBuffer<UChar> buffer(length);
1264 unsigned builderIndex = 0;
1266 // Skip leading spaces and leading characters that would convert to spaces
1267 for (i = 0; i < length; ++i) {
1268 UChar c = characters[i];
1269 if (!(c <= 0x20 || c == 0x7F))
1274 return StringWithDirection();
1276 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1277 bool previousCharWasWS = false;
1278 for (; i < length; ++i) {
1279 UChar c = characters[i];
1280 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1281 if (previousCharWasWS)
1283 buffer[builderIndex++] = ' ';
1284 previousCharWasWS = true;
1286 buffer[builderIndex++] = c;
1287 previousCharWasWS = false;
1291 // Strip trailing spaces
1292 while (builderIndex > 0) {
1294 if (buffer[builderIndex] != ' ')
1298 if (!builderIndex && buffer[builderIndex] == ' ')
1299 return StringWithDirection();
1301 buffer.shrink(builderIndex + 1);
1303 // Replace the backslashes with currency symbols if the encoding requires it.
1304 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1306 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1309 void Document::updateTitle(const StringWithDirection& title)
1311 if (m_rawTitle == title)
1315 m_title = canonicalizedTitle(this, m_rawTitle);
1316 if (Frame* f = frame())
1317 f->loader()->setTitle(m_title);
1320 void Document::setTitle(const String& title)
1322 // Title set by JavaScript -- overrides any title elements.
1323 m_titleSetExplicitly = true;
1324 if (!isHTMLDocument() && !isXHTMLDocument())
1326 else if (!m_titleElement) {
1327 if (HTMLElement* headElement = head()) {
1328 m_titleElement = createElement(titleTag, false);
1329 ExceptionCode ec = 0;
1330 headElement->appendChild(m_titleElement, ec);
1335 // The DOM API has no method of specifying direction, so assume LTR.
1336 updateTitle(StringWithDirection(title, LTR));
1338 if (m_titleElement) {
1339 ASSERT(m_titleElement->hasTagName(titleTag));
1340 if (m_titleElement->hasTagName(titleTag))
1341 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1345 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1347 if (titleElement != m_titleElement) {
1348 if (m_titleElement || m_titleSetExplicitly)
1349 // Only allow the first title element to change the title -- others have no effect.
1351 m_titleElement = titleElement;
1357 void Document::removeTitle(Element* titleElement)
1359 if (m_titleElement != titleElement)
1363 m_titleSetExplicitly = false;
1365 // Update title based on first title element in the head, if one exists.
1366 if (HTMLElement* headElement = head()) {
1367 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1368 if (e->hasTagName(titleTag)) {
1369 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1370 setTitleElement(titleElement->textWithDirection(), titleElement);
1375 if (!m_titleElement)
1376 updateTitle(StringWithDirection());
1379 #if ENABLE(PAGE_VISIBILITY_API)
1380 PageVisibilityState Document::visibilityState() const
1382 // The visibility of the document is inherited from the visibility of the
1383 // page. If there is no page associated with the document, we will assume
1384 // that the page is visible i.e. invisibility has to be explicitly
1385 // specified by the embedder.
1386 if (!m_frame || !m_frame->page())
1387 return PageVisibilityStateVisible;
1388 return m_frame->page()->visibilityState();
1391 String Document::webkitVisibilityState() const
1393 return pageVisibilityStateString(visibilityState());
1396 bool Document::webkitHidden() const
1398 return visibilityState() != PageVisibilityStateVisible;
1401 void Document::dispatchVisibilityStateChangeEvent()
1403 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1407 String Document::nodeName() const
1412 Node::NodeType Document::nodeType() const
1414 return DOCUMENT_NODE;
1417 FrameView* Document::view() const
1419 return m_frame ? m_frame->view() : 0;
1422 Page* Document::page() const
1424 return m_frame ? m_frame->page() : 0;
1427 Settings* Document::settings() const
1429 return m_frame ? m_frame->settings() : 0;
1432 PassRefPtr<Range> Document::createRange()
1434 return Range::create(this);
1437 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1438 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1441 ec = NOT_SUPPORTED_ERR;
1444 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1447 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1448 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1451 ec = NOT_SUPPORTED_ERR;
1454 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1457 void Document::scheduleForcedStyleRecalc()
1459 m_pendingStyleRecalcShouldForce = true;
1460 scheduleStyleRecalc();
1463 void Document::scheduleStyleRecalc()
1465 if (m_styleRecalcTimer.isActive() || inPageCache())
1468 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1470 if (!documentsThatNeedStyleRecalc)
1471 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1472 documentsThatNeedStyleRecalc->add(this);
1474 // FIXME: Why on earth is this here? This is clearly misplaced.
1475 invalidateAccessKeyMap();
1477 m_styleRecalcTimer.startOneShot(0);
1479 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1482 void Document::unscheduleStyleRecalc()
1484 ASSERT(!childNeedsStyleRecalc());
1486 if (documentsThatNeedStyleRecalc)
1487 documentsThatNeedStyleRecalc->remove(this);
1489 m_styleRecalcTimer.stop();
1490 m_pendingStyleRecalcShouldForce = false;
1493 bool Document::isPendingStyleRecalc() const
1495 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1498 void Document::styleRecalcTimerFired(Timer<Document>*)
1500 updateStyleIfNeeded();
1503 bool Document::childNeedsAndNotInStyleRecalc()
1505 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1508 void Document::recalcStyle(StyleChange change)
1510 // we should not enter style recalc while painting
1511 if (view() && view()->isPainting()) {
1512 ASSERT(!view()->isPainting());
1516 if (m_inStyleRecalc)
1517 return; // Guard against re-entrancy. -dwh
1519 if (m_hasDirtyStyleSelector)
1520 recalcStyleSelector();
1522 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1524 m_inStyleRecalc = true;
1525 suspendPostAttachCallbacks();
1526 RenderWidget::suspendWidgetHierarchyUpdates();
1528 RefPtr<FrameView> frameView = view();
1530 frameView->pauseScheduledEvents();
1531 frameView->beginDeferredRepaints();
1534 ASSERT(!renderer() || renderArena());
1535 if (!renderer() || !renderArena())
1538 if (m_pendingStyleRecalcShouldForce)
1541 if (change == Force) {
1542 // style selector may set this again during recalc
1543 m_hasNodesWithPlaceholderStyle = false;
1545 RefPtr<RenderStyle> documentStyle = CSSStyleSelector::styleForDocument(this);
1546 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1548 renderer()->setStyle(documentStyle.release());
1551 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1552 if (!n->isElementNode())
1554 Element* element = static_cast<Element*>(n);
1555 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1556 element->recalcStyle(change);
1559 #if USE(ACCELERATED_COMPOSITING)
1561 bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1562 // If we didn't update compositing layers because of layout(), we need to do so here.
1564 view()->updateCompositingLayers();
1569 clearNeedsStyleRecalc();
1570 clearChildNeedsStyleRecalc();
1571 unscheduleStyleRecalc();
1573 m_inStyleRecalc = false;
1575 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1576 if (m_styleSelector) {
1577 m_usesSiblingRules = m_styleSelector->usesSiblingRules();
1578 m_usesFirstLineRules = m_styleSelector->usesFirstLineRules();
1579 m_usesBeforeAfterRules = m_styleSelector->usesBeforeAfterRules();
1580 m_usesLinkRules = m_styleSelector->usesLinkRules();
1584 frameView->resumeScheduledEvents();
1585 frameView->endDeferredRepaints();
1587 RenderWidget::resumeWidgetHierarchyUpdates();
1588 resumePostAttachCallbacks();
1590 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1591 if (m_closeAfterStyleRecalc) {
1592 m_closeAfterStyleRecalc = false;
1596 InspectorInstrumentation::didRecalculateStyle(cookie);
1599 void Document::updateStyleIfNeeded()
1601 ASSERT(isMainThread());
1602 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1604 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1608 m_frame->animation()->beginAnimationUpdate();
1610 recalcStyle(NoChange);
1612 // Tell the animation controller that updateStyleIfNeeded is finished and it can do any post-processing
1614 m_frame->animation()->endAnimationUpdate();
1617 void Document::updateStyleForAllDocuments()
1619 ASSERT(isMainThread());
1620 if (!documentsThatNeedStyleRecalc)
1623 while (documentsThatNeedStyleRecalc->size()) {
1624 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1625 Document* doc = *it;
1626 documentsThatNeedStyleRecalc->remove(doc);
1627 doc->updateStyleIfNeeded();
1631 void Document::updateLayout()
1633 ASSERT(isMainThread());
1634 if (Element* oe = ownerElement())
1635 oe->document()->updateLayout();
1637 updateStyleIfNeeded();
1639 // Only do a layout if changes have occurred that make it necessary.
1640 FrameView* v = view();
1641 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1645 // FIXME: This is a bad idea and needs to be removed eventually.
1646 // Other browsers load stylesheets before they continue parsing the web page.
1647 // Since we don't, we can run JavaScript code that needs answers before the
1648 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1649 // lets us get reasonable answers. The long term solution to this problem is
1650 // to instead suspend JavaScript execution.
1651 void Document::updateLayoutIgnorePendingStylesheets()
1653 bool oldIgnore = m_ignorePendingStylesheets;
1655 if (!haveStylesheetsLoaded()) {
1656 m_ignorePendingStylesheets = true;
1657 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1658 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1659 // with accurate style information. (Our suppression involves blanking the whole page at the
1660 // moment. If it were more refined, we might be able to do something better.)
1661 // It's worth noting though that this entire method is a hack, since what we really want to do is
1662 // suspend JS instead of doing a layout with inaccurate information.
1663 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1664 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1665 styleSelectorChanged(RecalcStyleImmediately);
1666 } else if (m_hasNodesWithPlaceholderStyle)
1667 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1668 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1669 // but here we need up-to-date style immediately.
1675 m_ignorePendingStylesheets = oldIgnore;
1678 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1680 ASSERT_ARG(element, element->document() == this);
1682 bool oldIgnore = m_ignorePendingStylesheets;
1683 m_ignorePendingStylesheets = true;
1684 RefPtr<RenderStyle> style = styleSelector()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1685 m_ignorePendingStylesheets = oldIgnore;
1686 return style.release();
1689 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1691 RefPtr<RenderStyle> style = styleSelector()->styleForPage(pageIndex);
1692 return style.release();
1695 void Document::registerCustomFont(FontData* fontData)
1697 m_customFonts.append(adoptPtr(fontData));
1700 void Document::deleteCustomFonts()
1702 size_t size = m_customFonts.size();
1703 for (size_t i = 0; i < size; ++i)
1704 GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
1706 m_customFonts.clear();
1709 bool Document::isPageBoxVisible(int pageIndex)
1711 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1712 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1715 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1717 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1719 int width = pageSize.width();
1720 int height = pageSize.height();
1721 switch (style->pageSizeType()) {
1722 case PAGE_SIZE_AUTO:
1724 case PAGE_SIZE_AUTO_LANDSCAPE:
1726 std::swap(width, height);
1728 case PAGE_SIZE_AUTO_PORTRAIT:
1730 std::swap(width, height);
1732 case PAGE_SIZE_RESOLVED: {
1733 LengthSize size = style->pageSize();
1734 ASSERT(size.width().isFixed());
1735 ASSERT(size.height().isFixed());
1736 width = size.width().calcValue(0);
1737 height = size.height().calcValue(0);
1741 ASSERT_NOT_REACHED();
1743 pageSize = IntSize(width, height);
1745 // The percentage is calculated with respect to the width even for margin top and bottom.
1746 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1747 marginTop = style->marginTop().isAuto() ? marginTop : style->marginTop().calcValue(width);
1748 marginRight = style->marginRight().isAuto() ? marginRight : style->marginRight().calcValue(width);
1749 marginBottom = style->marginBottom().isAuto() ? marginBottom : style->marginBottom().calcValue(width);
1750 marginLeft = style->marginLeft().isAuto() ? marginLeft : style->marginLeft().calcValue(width);
1753 PassRefPtr<CSSValuePool> Document::cssValuePool() const
1755 if (!m_cssValuePool)
1756 m_cssValuePool = CSSValuePool::create();
1757 return m_cssValuePool;
1760 void Document::setIsViewSource(bool isViewSource)
1762 m_isViewSource = isViewSource;
1763 if (!m_isViewSource)
1766 setSecurityOrigin(SecurityOrigin::createUnique());
1769 void Document::createStyleSelector()
1771 bool matchAuthorAndUserStyles = true;
1772 if (Settings* docSettings = settings())
1773 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1774 m_styleSelector = adoptPtr(new CSSStyleSelector(this, m_styleSheets.get(), m_mappedElementSheet.get(), pageUserSheet(), pageGroupUserSheets(), m_userSheets.get(),
1775 !inQuirksMode(), matchAuthorAndUserStyles));
1776 // 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).
1777 m_usesSiblingRules = m_usesSiblingRules || m_styleSelector->usesSiblingRules();
1778 m_usesFirstLineRules = m_usesFirstLineRules || m_styleSelector->usesFirstLineRules();
1779 m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleSelector->usesBeforeAfterRules();
1780 m_usesLinkRules = m_usesLinkRules || m_styleSelector->usesLinkRules();
1783 void Document::attach()
1785 ASSERT(!attached());
1786 ASSERT(!m_inPageCache);
1787 ASSERT(!m_axObjectCache || this != topDocument());
1790 m_renderArena = adoptPtr(new RenderArena);
1792 // Create the rendering tree
1793 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
1794 #if USE(ACCELERATED_COMPOSITING)
1795 renderView()->didMoveOnscreen();
1800 RenderObject* render = renderer();
1803 TreeScope::attach();
1805 setRenderer(render);
1808 void Document::detach()
1811 ASSERT(!m_inPageCache);
1813 if (this == topDocument())
1814 clearAXObjectCache();
1816 stopActiveDOMObjects();
1817 m_eventQueue->close();
1818 #if ENABLE(FULLSCREEN_API)
1819 m_fullScreenChangeEventTargetQueue.clear();
1822 #if ENABLE(REQUEST_ANIMATION_FRAME)
1823 // FIXME: consider using ActiveDOMObject.
1824 m_scriptedAnimationController = nullptr;
1827 RenderObject* render = renderer();
1829 // Send out documentWillBecomeInactive() notifications to registered elements,
1830 // in order to stop media elements
1831 documentWillBecomeInactive();
1833 #if ENABLE(SHARED_WORKERS)
1834 SharedWorkerRepository::documentDetached(this);
1838 FrameView* view = m_frame->view();
1840 view->detachCustomScrollbars();
1844 // indicate destruction mode, i.e. attached() but renderer == 0
1847 #if ENABLE(FULLSCREEN_API)
1848 if (m_fullScreenRenderer)
1849 setFullScreenRenderer(0);
1856 TreeScope::detach();
1858 unscheduleStyleRecalc();
1863 // This is required, as our Frame might delete itself as soon as it detaches
1864 // us. However, this violates Node::detach() semantics, as it's never
1865 // possible to re-attach. Eventually Document::detach() should be renamed,
1866 // or this setting of the frame to 0 could be made explicit in each of the
1867 // callers of Document::detach().
1869 m_renderArena.clear();
1872 void Document::removeAllEventListeners()
1874 EventTarget::removeAllEventListeners();
1876 if (DOMWindow* domWindow = this->domWindow())
1877 domWindow->removeAllEventListeners();
1878 for (Node* node = firstChild(); node; node = node->traverseNextNode())
1879 node->removeAllEventListeners();
1882 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
1884 ScriptExecutionContext::suspendActiveDOMObjects(why);
1886 #if ENABLE(DEVICE_ORIENTATION)
1890 if (page()->deviceMotionController())
1891 page()->deviceMotionController()->suspendEventsForAllListeners(domWindow());
1892 if (page()->deviceOrientationController())
1893 page()->deviceOrientationController()->suspendEventsForAllListeners(domWindow());
1897 void Document::resumeActiveDOMObjects()
1899 ScriptExecutionContext::resumeActiveDOMObjects();
1901 #if ENABLE(DEVICE_ORIENTATION)
1905 if (page()->deviceMotionController())
1906 page()->deviceMotionController()->resumeEventsForAllListeners(domWindow());
1907 if (page()->deviceOrientationController())
1908 page()->deviceOrientationController()->resumeEventsForAllListeners(domWindow());
1912 RenderView* Document::renderView() const
1914 return toRenderView(renderer());
1917 void Document::clearAXObjectCache()
1919 // clear cache in top document
1920 if (m_axObjectCache) {
1921 // Clear the cache member variable before calling delete because attempts
1922 // are made to access it during destruction.
1923 AXObjectCache* axObjectCache = m_axObjectCache;
1924 m_axObjectCache = 0;
1925 delete axObjectCache;
1929 // ask the top-level document to clear its cache
1930 Document* doc = topDocument();
1932 doc->clearAXObjectCache();
1935 bool Document::axObjectCacheExists() const
1937 if (m_axObjectCache)
1940 Document* doc = topDocument();
1942 return doc->axObjectCacheExists();
1947 AXObjectCache* Document::axObjectCache() const
1949 // The only document that actually has a AXObjectCache is the top-level
1950 // document. This is because we need to be able to get from any WebCoreAXObject
1951 // to any other WebCoreAXObject on the same page. Using a single cache allows
1952 // lookups across nested webareas (i.e. multiple documents).
1954 if (m_axObjectCache) {
1955 // return already known top-level cache
1956 if (!ownerElement())
1957 return m_axObjectCache;
1959 // In some pages with frames, the cache is created before the sub-webarea is
1960 // inserted into the tree. Here, we catch that case and just toss the old
1961 // cache and start over.
1962 // NOTE: This recovery may no longer be needed. I have been unable to trigger
1963 // it again. See rdar://5794454
1964 // FIXME: Can this be fixed when inserting the subframe instead of now?
1965 // FIXME: If this function was called to get the cache in order to remove
1966 // an AXObject, we are now deleting the cache as a whole and returning a
1967 // new empty cache that does not contain the AXObject! That should actually
1968 // be OK. I am concerned about other cases like this where accessing the
1969 // cache blows away the AXObject being operated on.
1970 delete m_axObjectCache;
1971 m_axObjectCache = 0;
1974 // ask the top-level document for its cache
1975 Document* doc = topDocument();
1977 return doc->axObjectCache();
1979 // this is the top-level document, so install a new cache
1980 m_axObjectCache = new AXObjectCache(this);
1981 return m_axObjectCache;
1984 void Document::setVisuallyOrdered()
1986 m_visuallyOrdered = true;
1988 renderer()->style()->setRTLOrdering(VisualOrder);
1991 PassRefPtr<DocumentParser> Document::createParser()
1993 // FIXME: this should probably pass the frame instead
1995 return NewXMLDocumentParser::create(this);
1997 return XMLDocumentParser::create(this, view());
2001 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2003 return parser() ? parser()->asScriptableDocumentParser() : 0;
2006 void Document::open(Document* ownerDocument)
2008 if (ownerDocument) {
2009 setURL(ownerDocument->url());
2010 m_cookieURL = ownerDocument->cookieURL();
2011 setSecurityOrigin(ownerDocument->securityOrigin());
2015 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2016 if (parser->isParsing()) {
2017 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2018 if (parser->isExecutingScript())
2021 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2026 if (m_frame->loader()->state() == FrameStateProvisional)
2027 m_frame->loader()->stopAllLoaders();
2030 removeAllEventListeners();
2032 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2033 parser->setWasCreatedByScript(true);
2035 if (DOMWindow* domWindow = this->domWindow())
2036 domWindow->removeAllEventListeners();
2039 m_frame->loader()->didExplicitOpen();
2042 void Document::detachParser()
2050 void Document::cancelParsing()
2055 // We have to clear the parser to avoid possibly triggering
2056 // the onload handler when closing as a side effect of a cancel-style
2057 // change, such as opening a new document or closing the window while
2063 void Document::implicitOpen()
2069 setCompatibilityMode(NoQuirksMode);
2071 m_parser = createParser();
2073 setReadyState(Loading);
2075 // If we reload, the animation controller sticks around and has
2076 // a stale animation time. We need to update it here.
2077 if (m_frame && m_frame->animation())
2078 m_frame->animation()->beginAnimationUpdate();
2081 HTMLElement* Document::body() const
2083 Node* de = documentElement();
2087 // try to prefer a FRAMESET element over BODY
2089 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2090 if (i->hasTagName(framesetTag))
2091 return toHTMLElement(i);
2093 if (i->hasTagName(bodyTag) && !body)
2096 return toHTMLElement(body);
2099 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2101 RefPtr<HTMLElement> newBody = prpNewBody;
2103 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2104 ec = HIERARCHY_REQUEST_ERR;
2108 if (newBody->document() && newBody->document() != this) {
2110 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2114 newBody = toHTMLElement(node.get());
2117 HTMLElement* b = body();
2119 documentElement()->appendChild(newBody.release(), ec);
2121 documentElement()->replaceChild(newBody.release(), b, ec);
2124 HTMLHeadElement* Document::head()
2126 Node* de = documentElement();
2130 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2131 if (e->hasTagName(headTag))
2132 return static_cast<HTMLHeadElement*>(e);
2137 void Document::close()
2139 // FIXME: We should follow the specification more closely:
2140 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2142 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2148 void Document::explicitClose()
2154 // Because we have no frame, we don't know if all loading has completed,
2155 // so we just call implicitClose() immediately. FIXME: This might fire
2156 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2161 m_frame->loader()->checkCompleted();
2164 void Document::implicitClose()
2166 // 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.
2167 if (m_inStyleRecalc) {
2168 m_closeAfterStyleRecalc = true;
2172 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2173 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2178 m_processingLoadEvent = true;
2180 ScriptableDocumentParser* parser = scriptableDocumentParser();
2181 m_wellFormed = parser && parser->wellFormed();
2183 // We have to clear the parser, in case someone document.write()s from the
2184 // onLoad event handler, as in Radar 3206524.
2187 // Parser should have picked up all preloads by now
2188 m_cachedResourceLoader->clearPreloads();
2190 // FIXME: We kick off the icon loader when the Document is done parsing.
2191 // There are earlier opportunities we could start it:
2192 // -When the <head> finishes parsing
2193 // -When any new HTMLLinkElement is inserted into the document
2194 // But those add a dynamic component to the favicon that has UI
2195 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2198 f->loader()->icon()->startLoader();
2199 f->animation()->resumeAnimationsForDocument(this);
2202 ImageLoader::dispatchPendingBeforeLoadEvents();
2203 ImageLoader::dispatchPendingLoadEvents();
2204 dispatchWindowLoadEvent();
2205 enqueuePageshowEvent(PageshowEventNotPersisted);
2206 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2209 f->loader()->handledOnloadEvents();
2210 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2211 if (!ownerElement())
2212 printf("onload fired at %d\n", elapsedTime());
2215 m_processingLoadEvent = false;
2217 // An event handler may have removed the frame
2221 // Make sure both the initial layout and reflow happen after the onload
2222 // fires. This will improve onload scores, and other browsers do it.
2223 // If they wanna cheat, we can too. -dwh
2225 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2226 // Just bail out. Before or during the onload we were shifted to another page.
2227 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2228 view()->unscheduleRelayout();
2232 frame()->loader()->checkCallImplicitClose();
2233 RenderObject* renderObject = renderer();
2235 // We used to force a synchronous display and flush here. This really isn't
2236 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2237 // (if your platform is syncing flushes and limiting them to 60fps).
2238 m_overMinimumLayoutThreshold = true;
2239 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2240 updateStyleIfNeeded();
2242 // Always do a layout after loading if needed.
2243 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2247 // If painting and compositing layer updates were suppressed pending the load event, do these actions now.
2248 if (renderer() && settings() && settings()->suppressIncrementalRendering()) {
2249 #if USE(ACCELERATED_COMPOSITING)
2250 view()->updateCompositingLayers();
2252 renderer()->repaint();
2255 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2256 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2257 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2258 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2259 // exists in the cache (we ignore the return value because we don't need it here). This is
2260 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2261 axObjectCache()->getOrCreate(renderObject);
2262 if (this == topDocument())
2263 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2265 // AXLoadComplete can only be posted on the top document, so if it's a document
2266 // in an iframe that just finished loading, post a notification on the iframe
2268 ScrollView* scrollView = frame()->view();
2269 if (scrollView && scrollView->isFrameView()) {
2270 HTMLFrameOwnerElement* owner = static_cast<FrameView*>(scrollView)->frame()->ownerElement();
2271 if (owner && owner->renderer()) {
2272 AccessibilityObject* axIFrame = axObjectCache()->getOrCreate(owner->renderer());
2273 axObjectCache()->postNotification(axIFrame, axIFrame->document(), AXObjectCache::AXLayoutComplete, true);
2281 // FIXME: Officially, time 0 is when the outermost <svg> receives its
2282 // SVGLoad event, but we don't implement those yet. This is close enough
2283 // for now. In some cases we should have fired earlier.
2284 if (svgExtensions())
2285 accessSVGExtensions()->startAnimations();
2289 void Document::setParsing(bool b)
2292 if (!m_bParsing && view())
2293 view()->scheduleRelayout();
2295 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2296 if (!ownerElement() && !m_bParsing)
2297 printf("Parsing finished at %d\n", elapsedTime());
2301 bool Document::shouldScheduleLayout()
2303 // This function will only be called when FrameView thinks a layout is needed.
2304 // This enforces a couple extra rules.
2306 // (a) Only schedule a layout once the stylesheets are loaded.
2307 // (b) Only schedule layout once we have a body element.
2309 return (haveStylesheetsLoaded() && body())
2310 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2313 bool Document::isLayoutTimerActive()
2315 return view() && view()->layoutPending() && !minimumLayoutDelay();
2318 int Document::minimumLayoutDelay()
2320 if (m_overMinimumLayoutThreshold)
2323 int elapsed = elapsedTime();
2324 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2326 // We'll want to schedule the timer to fire at the minimum layout threshold.
2327 return max(0, cLayoutScheduleThreshold - elapsed);
2330 int Document::elapsedTime() const
2332 return static_cast<int>((currentTime() - m_startTime) * 1000);
2335 void Document::write(const SegmentedString& text, Document* ownerDocument)
2337 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2339 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2340 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2342 if (m_writeRecursionIsTooDeep)
2345 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2346 if (!ownerElement())
2347 printf("Beginning a document.write at %d\n", elapsedTime());
2350 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2351 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2354 if (!hasInsertionPoint)
2355 open(ownerDocument);
2358 m_parser->insert(text);
2360 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2361 if (!ownerElement())
2362 printf("Ending a document.write at %d\n", elapsedTime());
2366 void Document::write(const String& text, Document* ownerDocument)
2368 write(SegmentedString(text), ownerDocument);
2371 void Document::writeln(const String& text, Document* ownerDocument)
2373 write(text, ownerDocument);
2374 write("\n", ownerDocument);
2377 const KURL& Document::virtualURL() const
2382 KURL Document::virtualCompleteURL(const String& url) const
2384 return completeURL(url);
2387 double Document::minimumTimerInterval() const
2391 return ScriptExecutionContext::minimumTimerInterval();
2392 return p->settings()->minDOMTimerInterval();
2395 EventTarget* Document::errorEventTarget()
2400 void Document::logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
2402 addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, lineNumber, sourceURL, callStack);
2405 void Document::setURL(const KURL& url)
2407 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2408 if (newURL == m_url)
2412 m_documentURI = m_url.string();
2416 void Document::updateBaseURL()
2418 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2419 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2420 // from the Document interface otherwise.
2421 if (!m_baseElementURL.isEmpty())
2422 m_baseURL = m_baseElementURL;
2423 else if (!m_baseURLOverride.isEmpty())
2424 m_baseURL = m_baseURLOverride;
2426 // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
2427 // so we use a null base URL.
2428 m_baseURL = KURL(KURL(), documentURI());
2431 if (!m_baseURL.isValid())
2435 m_elemSheet->setFinalURL(m_baseURL);
2436 if (m_mappedElementSheet)
2437 m_mappedElementSheet->setFinalURL(m_baseURL);
2440 void Document::setBaseURLOverride(const KURL& url)
2442 m_baseURLOverride = url;
2446 void Document::processBaseElement()
2448 // Find the first href attribute in a base element and the first target attribute in a base element.
2449 const AtomicString* href = 0;
2450 const AtomicString* target = 0;
2451 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2452 if (node->hasTagName(baseTag)) {
2454 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2455 if (!value.isNull())
2459 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2460 if (!value.isNull())
2466 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2467 KURL baseElementURL;
2469 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2470 if (!strippedHref.isEmpty())
2471 baseElementURL = KURL(url(), strippedHref);
2473 if (m_baseElementURL != baseElementURL) {
2474 m_baseElementURL = baseElementURL;
2478 m_baseTarget = target ? *target : nullAtom;
2481 String Document::userAgent(const KURL& url) const
2483 return frame() ? frame()->loader()->userAgent(url) : String();
2486 void Document::disableEval()
2491 frame()->script()->disableEval();
2494 CSSStyleSheet* Document::pageUserSheet()
2496 if (m_pageUserSheet)
2497 return m_pageUserSheet.get();
2499 Page* owningPage = page();
2503 String userSheetText = owningPage->userStyleSheet();
2504 if (userSheetText.isEmpty())
2507 // Parse the sheet and cache it.
2508 m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2509 m_pageUserSheet->setIsUserStyleSheet(true);
2510 m_pageUserSheet->parseString(userSheetText, !inQuirksMode());
2511 return m_pageUserSheet.get();
2514 void Document::clearPageUserSheet()
2516 if (m_pageUserSheet) {
2517 m_pageUserSheet = 0;
2518 styleSelectorChanged(DeferRecalcStyle);
2522 void Document::updatePageUserSheet()
2524 clearPageUserSheet();
2525 if (pageUserSheet())
2526 styleSelectorChanged(RecalcStyleImmediately);
2529 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2531 if (m_pageGroupUserSheetCacheValid)
2532 return m_pageGroupUserSheets.get();
2534 m_pageGroupUserSheetCacheValid = true;
2536 Page* owningPage = page();
2540 const PageGroup& pageGroup = owningPage->group();
2541 const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2545 UserStyleSheetMap::const_iterator end = sheetsMap->end();
2546 for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2547 const UserStyleSheetVector* sheets = it->second;
2548 for (unsigned i = 0; i < sheets->size(); ++i) {
2549 const UserStyleSheet* sheet = sheets->at(i).get();
2550 if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2552 if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2554 RefPtr<CSSStyleSheet> parsedSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2555 parsedSheet->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
2556 parsedSheet->parseString(sheet->source(), !inQuirksMode());
2557 if (!m_pageGroupUserSheets)
2558 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2559 m_pageGroupUserSheets->append(parsedSheet.release());
2563 return m_pageGroupUserSheets.get();
2566 void Document::clearPageGroupUserSheets()
2568 m_pageGroupUserSheetCacheValid = false;
2569 if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
2570 m_pageGroupUserSheets->clear();
2571 styleSelectorChanged(DeferRecalcStyle);
2575 void Document::updatePageGroupUserSheets()
2577 clearPageGroupUserSheets();
2578 if (pageGroupUserSheets() && pageGroupUserSheets()->size())
2579 styleSelectorChanged(RecalcStyleImmediately);
2582 void Document::addUserSheet(PassRefPtr<CSSStyleSheet> userSheet)
2585 m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2586 m_userSheets->append(userSheet);
2587 styleSelectorChanged(RecalcStyleImmediately);
2590 CSSStyleSheet* Document::elementSheet()
2593 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2594 return m_elemSheet.get();
2597 CSSStyleSheet* Document::mappedElementSheet()
2599 if (!m_mappedElementSheet)
2600 m_mappedElementSheet = CSSStyleSheet::createInline(this, m_baseURL);
2601 return m_mappedElementSheet.get();
2604 int Document::nodeAbsIndex(Node *node)
2606 ASSERT(node->document() == this);
2609 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2614 Node* Document::nodeWithAbsIndex(int absIndex)
2617 for (int i = 0; n && (i < absIndex); i++)
2618 n = n->traverseNextNode();
2622 void Document::processHttpEquiv(const String& equiv, const String& content)
2624 ASSERT(!equiv.isNull() && !content.isNull());
2626 Frame* frame = this->frame();
2628 if (equalIgnoringCase(equiv, "default-style")) {
2629 // The preferred style set has been overridden as per section
2630 // 14.3.2 of the HTML4.0 specification. We need to update the
2631 // sheet used variable and then update our style selector.
2632 // For more info, see the test at:
2633 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2635 m_selectedStylesheetSet = content;
2636 m_preferredStylesheetSet = content;
2637 styleSelectorChanged(DeferRecalcStyle);
2638 } else if (equalIgnoringCase(equiv, "refresh")) {
2641 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2643 url = m_url.string();
2645 url = completeURL(url).string();
2646 frame->navigationScheduler()->scheduleRedirect(delay, url);
2648 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2649 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2650 if (isHTMLDocument()) {
2651 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
2652 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
2654 } else if (equalIgnoringCase(equiv, "content-language"))
2655 setContentLanguage(content);
2656 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2657 parseDNSPrefetchControlHeader(content);
2658 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2660 FrameLoader* frameLoader = frame->loader();
2661 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
2662 frameLoader->stopAllLoaders();
2663 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
2665 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
2666 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
2669 } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2670 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
2671 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2672 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
2675 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2676 static bool isSeparator(UChar c)
2678 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2681 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2683 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2684 int keyBegin, keyEnd;
2685 int valueBegin, valueEnd;
2688 int length = features.length();
2689 String buffer = features.lower();
2690 while (i < length) {
2691 // skip to first non-separator, but don't skip past the end of the string
2692 while (isSeparator(buffer[i])) {
2699 // skip to first separator
2700 while (!isSeparator(buffer[i]))
2704 // skip to first '=', but don't skip past a ',' or the end of the string
2705 while (buffer[i] != '=') {
2706 if (buffer[i] == ',' || i >= length)
2711 // skip to first non-separator, but don't skip past a ',' or the end of the string
2712 while (isSeparator(buffer[i])) {
2713 if (buffer[i] == ',' || i >= length)
2719 // skip to first separator
2720 while (!isSeparator(buffer[i]))
2724 ASSERT(i <= length);
2726 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2727 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2728 callback(keyString, valueString, this, data);
2732 void Document::processViewport(const String& features)
2734 ASSERT(!features.isNull());
2736 m_viewportArguments = ViewportArguments(ViewportArguments::ViewportMeta);
2737 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2739 Frame* frame = this->frame();
2740 if (!frame || !frame->page())
2743 frame->page()->updateViewportArguments();
2746 void Document::processReferrerPolicy(const String& policy)
2748 ASSERT(!policy.isNull());
2750 m_referrerPolicy = SecurityPolicy::ReferrerPolicyDefault;
2752 if (equalIgnoringCase(policy, "never"))
2753 m_referrerPolicy = SecurityPolicy::ReferrerPolicyNever;
2754 else if (equalIgnoringCase(policy, "always"))
2755 m_referrerPolicy = SecurityPolicy::ReferrerPolicyAlways;
2756 else if (equalIgnoringCase(policy, "origin"))
2757 m_referrerPolicy = SecurityPolicy::ReferrerPolicyOrigin;
2760 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2762 ASSERT(!renderer() || renderer()->isRenderView());
2765 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
2767 HitTestResult result(documentPoint);
2768 renderView()->layer()->hitTest(request, result);
2770 if (!request.readOnly())
2771 updateStyleIfNeeded();
2773 return MouseEventWithHitTestResults(event, result);
2776 // DOM Section 1.1.1
2777 bool Document::childTypeAllowed(NodeType type) const
2780 case ATTRIBUTE_NODE:
2781 case CDATA_SECTION_NODE:
2782 case DOCUMENT_FRAGMENT_NODE:
2785 case ENTITY_REFERENCE_NODE:
2788 case XPATH_NAMESPACE_NODE:
2789 case SHADOW_ROOT_NODE:
2792 case PROCESSING_INSTRUCTION_NODE:
2794 case DOCUMENT_TYPE_NODE:
2796 // Documents may contain no more than one of each of these.
2797 // (One Element and one DocumentType.)
2798 for (Node* c = firstChild(); c; c = c->nextSibling())
2799 if (c->nodeType() == type)
2806 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2809 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2812 if (oldChild->nodeType() == newChild->nodeType())
2815 int numDoctypes = 0;
2816 int numElements = 0;
2818 // First, check how many doctypes and elements we have, not counting
2819 // the child we're about to remove.
2820 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2824 switch (c->nodeType()) {
2825 case DOCUMENT_TYPE_NODE:
2836 // Then, see how many doctypes and elements might be added by the new child.
2837 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2838 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2839 switch (c->nodeType()) {
2840 case ATTRIBUTE_NODE:
2841 case CDATA_SECTION_NODE:
2842 case DOCUMENT_FRAGMENT_NODE:
2845 case ENTITY_REFERENCE_NODE:
2848 case XPATH_NAMESPACE_NODE:
2851 case PROCESSING_INSTRUCTION_NODE:
2853 case DOCUMENT_TYPE_NODE:
2859 case SHADOW_ROOT_NODE:
2860 ASSERT_NOT_REACHED();
2865 switch (newChild->nodeType()) {
2866 case ATTRIBUTE_NODE:
2867 case CDATA_SECTION_NODE:
2868 case DOCUMENT_FRAGMENT_NODE:
2871 case ENTITY_REFERENCE_NODE:
2874 case XPATH_NAMESPACE_NODE:
2875 case SHADOW_ROOT_NODE:
2878 case PROCESSING_INSTRUCTION_NODE:
2880 case DOCUMENT_TYPE_NODE:
2889 if (numElements > 1 || numDoctypes > 1)
2895 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2897 // Spec says cloning Document nodes is "implementation dependent"
2898 // so we do not support it...
2902 StyleSheetList* Document::styleSheets()
2904 return m_styleSheets.get();
2907 String Document::preferredStylesheetSet() const
2909 return m_preferredStylesheetSet;
2912 String Document::selectedStylesheetSet() const
2914 return m_selectedStylesheetSet;
2917 void Document::setSelectedStylesheetSet(const String& aString)
2919 m_selectedStylesheetSet = aString;
2920 styleSelectorChanged(DeferRecalcStyle);
2923 // This method is called whenever a top-level stylesheet has finished loading.
2924 void Document::removePendingSheet()
2926 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2927 ASSERT(m_pendingStylesheets > 0);
2929 m_pendingStylesheets--;
2931 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2932 if (!ownerElement())
2933 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2936 if (m_pendingStylesheets)
2939 styleSelectorChanged(RecalcStyleImmediately);
2941 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2942 parser->executeScriptsWaitingForStylesheets();
2944 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2945 view()->scrollToFragment(m_url);
2948 void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
2950 // Don't bother updating, since we haven't loaded all our style info yet
2951 // and haven't calculated the style selector for the first time.
2952 if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
2955 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2956 if (!ownerElement())
2957 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2960 recalcStyleSelector();
2962 if (updateFlag == DeferRecalcStyle) {
2963 scheduleForcedStyleRecalc();
2967 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
2968 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2970 renderer()->repaint();
2973 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
2974 // make sure animations get the correct update time
2976 m_frame->animation()->beginAnimationUpdate();
2979 m_frame->animation()->endAnimationUpdate();
2981 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2982 if (!ownerElement())
2983 printf("Finished update of style selector at time %d\n", elapsedTime());
2987 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
2989 view()->scheduleRelayout();
2992 if (m_mediaQueryMatcher)
2993 m_mediaQueryMatcher->styleSelectorChanged();
2996 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
2998 if (!node->inDocument())
3001 // Until the <body> exists, we have no choice but to compare document positions,
3002 // since styles outside of the body and head continue to be shunted into the head
3003 // (and thus can shift to end up before dynamically added DOM content that is also
3004 // outside the body).
3005 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3006 m_styleSheetCandidateNodes.add(node);
3010 // Determine an appropriate insertion point.
3011 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3012 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3013 StyleSheetCandidateListHashSet::iterator it = end;
3014 Node* followingNode = 0;
3018 unsigned short position = n->compareDocumentPosition(node);
3019 if (position == DOCUMENT_POSITION_FOLLOWING) {
3020 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3024 } while (it != begin);
3026 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3029 void Document::removeStyleSheetCandidateNode(Node* node)
3031 m_styleSheetCandidateNodes.remove(node);
3034 void Document::recalcStyleSelector()
3036 if (m_inStyleRecalc) {
3037 // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3038 // https://bugs.webkit.org/show_bug.cgi?id=54344
3039 // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3040 m_hasDirtyStyleSelector = true;
3041 scheduleForcedStyleRecalc();
3044 if (!renderer() || !attached())
3047 StyleSheetVector sheets;
3049 bool matchAuthorAndUserStyles = true;
3050 if (Settings* settings = this->settings())
3051 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
3053 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3054 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3055 if (!matchAuthorAndUserStyles)
3057 for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3060 StyleSheet* sheet = 0;
3062 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3063 // Processing instruction (XML documents only).
3064 // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3065 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3066 sheet = pi->sheet();
3068 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3069 if (pi->isXSL() && !transformSourceDocument()) {
3070 // Don't apply XSL transforms until loading is finished.
3072 applyXSLTransform(pi);
3076 } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3078 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3081 Element* e = static_cast<Element*>(n);
3082 AtomicString title = e->getAttribute(titleAttr);
3083 bool enabledViaScript = false;
3084 if (e->hasLocalName(linkTag)) {
3086 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3087 if (linkElement->isDisabled())
3089 enabledViaScript = linkElement->isEnabledViaScript();
3090 if (linkElement->isLoading()) {
3091 // it is loading but we should still decide which style sheet set to use
3092 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3093 const AtomicString& rel = e->getAttribute(relAttr);
3094 if (!rel.contains("alternate")) {
3095 m_preferredStylesheetSet = title;
3096 m_selectedStylesheetSet = title;
3101 if (!linkElement->sheet())
3105 // Get the current preferred styleset. This is the
3106 // set of sheets that will be enabled.
3108 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3109 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3112 if (e->hasLocalName(linkTag))
3113 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3116 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3118 // Check to see if this sheet belongs to a styleset
3119 // (thus making it PREFERRED or ALTERNATE rather than
3121 if (!enabledViaScript && !title.isEmpty()) {
3122 // Yes, we have a title.
3123 if (m_preferredStylesheetSet.isEmpty()) {
3124 // No preferred set has been established. If
3125 // we are NOT an alternate sheet, then establish
3126 // us as the preferred set. Otherwise, just ignore
3128 AtomicString rel = e->getAttribute(relAttr);
3129 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3130 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3133 if (title != m_preferredStylesheetSet)
3139 sheets.append(sheet);
3142 m_styleSheets->swap(sheets);
3144 m_styleSelector.clear();
3145 m_didCalculateStyleSelector = true;
3146 m_hasDirtyStyleSelector = false;
3149 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3151 m_hoverNode = newHoverNode;
3154 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3156 m_activeNode = newActiveNode;
3159 void Document::focusedNodeRemoved()
3164 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3166 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3169 bool nodeInSubtree = false;
3170 if (amongChildrenOnly)
3171 nodeInSubtree = m_focusedNode->isDescendantOf(node);
3173 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
3176 document()->focusedNodeRemoved();
3179 void Document::hoveredNodeDetached(Node* node)
3181 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3184 m_hoverNode = node->parentNode();
3185 while (m_hoverNode && !m_hoverNode->renderer())
3186 m_hoverNode = m_hoverNode->parentNode();
3188 frame()->eventHandler()->scheduleHoverStateUpdate();
3191 void Document::activeChainNodeDetached(Node* node)
3193 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3196 m_activeNode = node->parentNode();
3197 while (m_activeNode && !m_activeNode->renderer())
3198 m_activeNode = m_activeNode->parentNode();
3201 #if ENABLE(DASHBOARD_SUPPORT)
3202 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
3204 return m_dashboardRegions;
3207 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
3209 m_dashboardRegions = regions;
3210 setDashboardRegionsDirty(false);
3214 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3216 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3218 // Make sure newFocusedNode is actually in this document
3219 if (newFocusedNode && (newFocusedNode->document() != this))
3222 if (m_focusedNode == newFocusedNode)
3228 bool focusChangeBlocked = false;
3229 RefPtr<Node> oldFocusedNode = m_focusedNode;
3232 // Remove focus from the existing focus node (if any)
3233 if (oldFocusedNode && !oldFocusedNode->inDetach()) {
3234 if (oldFocusedNode->active())
3235 oldFocusedNode->setActive(false);
3237 oldFocusedNode->setFocus(false);
3239 // Dispatch a change event for text fields or textareas that have been edited
3240 if (oldFocusedNode->isElementNode()) {
3241 Element* element = static_cast<Element*>(oldFocusedNode.get());
3242 if (element->wasChangedSinceLastFormControlChangeEvent())
3243 element->dispatchFormControlChangeEvent();
3246 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3247 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3249 if (m_focusedNode) {
3250 // handler shifted focus
3251 focusChangeBlocked = true;
3255 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3256 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3257 // on it, probably when <rdar://problem/8503958> is resolved.
3258 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3260 if (m_focusedNode) {
3261 // handler shifted focus
3262 focusChangeBlocked = true;
3265 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3268 if (oldFocusedNode == oldFocusedNode->rootEditableElement())
3269 frame()->editor()->didEndEditing();
3272 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3274 oldWidget->setFocus(false);
3276 view()->setFocus(false);
3280 if (newFocusedNode) {
3281 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3282 // delegate blocks focus change
3283 focusChangeBlocked = true;
3284 goto SetFocusedNodeDone;
3286 // Set focus on the new node
3287 m_focusedNode = newFocusedNode;
3289 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3290 m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3292 if (m_focusedNode != newFocusedNode) {
3293 // handler shifted focus
3294 focusChangeBlocked = true;
3295 goto SetFocusedNodeDone;
3298 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3299 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3300 // on it, probably when <rdar://problem/8503958> is m.
3301 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3303 if (m_focusedNode != newFocusedNode) {
3304 // handler shifted focus
3305 focusChangeBlocked = true;
3306 goto SetFocusedNodeDone;
3308 m_focusedNode->setFocus(true);
3310 if (m_focusedNode == m_focusedNode->rootEditableElement())
3311 frame()->editor()->didBeginEditing();
3313 // eww, I suck. set the qt focus correctly
3314 // ### find a better place in the code for this
3316 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3318 // Make sure a widget has the right size before giving it focus.
3319 // Otherwise, we are testing edge cases of the Widget code.
3320 // Specifically, in WebCore this does not work well for text fields.
3322 // Re-get the widget in case updating the layout changed things.
3323 focusWidget = widgetForNode(m_focusedNode.get());
3326 focusWidget->setFocus(true);
3328 view()->setFocus(true);
3332 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3333 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
3334 RenderObject* oldFocusedRenderer = 0;
3335 RenderObject* newFocusedRenderer = 0;
3338 oldFocusedRenderer = oldFocusedNode->renderer();
3340 newFocusedRenderer = newFocusedNode->renderer();
3342 axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
3345 if (!focusChangeBlocked)
3346 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3349 updateStyleIfNeeded();
3350 return !focusChangeBlocked;
3353 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3357 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3358 if (node->isFocusable())
3363 void Document::setCSSTarget(Element* n)
3366 m_cssTarget->setNeedsStyleRecalc();
3369 n->setNeedsStyleRecalc();
3372 void Document::attachNodeIterator(NodeIterator* ni)
3374 m_nodeIterators.add(ni);
3377 void Document::detachNodeIterator(NodeIterator* ni)
3379 // The node iterator can be detached without having been attached if its root node didn't have a document
3380 // when the iterator was created, but has it now.
3381 m_nodeIterators.remove(ni);
3384 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3386 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3387 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3388 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3389 if ((*it)->root() == node) {
3390 detachNodeIterator(*it);
3391 newDocument->attachNodeIterator(*it);
3396 void Document::nodeChildrenChanged(ContainerNode* container)
3398 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3399 HashSet<Range*>::const_iterator end = m_ranges.end();
3400 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3401 (*it)->nodeChildrenChanged(container);
3405 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3407 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3408 HashSet<Range*>::const_iterator end = m_ranges.end();
3409 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3410 (*it)->nodeChildrenWillBeRemoved(container);
3413 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3414 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3415 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3416 (*it)->nodeWillBeRemoved(n);
3419 if (Frame* frame = this->frame()) {
3420 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3421 frame->eventHandler()->nodeWillBeRemoved(n);
3422 frame->selection()->nodeWillBeRemoved(n);
3423 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3428 void Document::nodeWillBeRemoved(Node* n)
3430 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3431 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3432 (*it)->nodeWillBeRemoved(n);
3434 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3435 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3436 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3437 (*it)->nodeWillBeRemoved(n);
3440 if (Frame* frame = this->frame()) {
3441 frame->eventHandler()->nodeWillBeRemoved(n);
3442 frame->selection()->nodeWillBeRemoved(n);
3443 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3447 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3449 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3450 HashSet<Range*>::const_iterator end = m_ranges.end();
3451 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3452 (*it)->textInserted(text, offset, length);
3455 // Update the markers for spelling and grammar checking.
3456 m_markers->shiftMarkers(text, offset, length);
3459 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3461 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3462 HashSet<Range*>::const_iterator end = m_ranges.end();
3463 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3464 (*it)->textRemoved(text, offset, length);
3467 // Update the markers for spelling and grammar checking.
3468 m_markers->removeMarkers(text, offset, length);
3469 m_markers->shiftMarkers(text, offset + length, 0 - length);
3472 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3474 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3475 NodeWithIndex oldNodeWithIndex(oldNode);
3476 HashSet<Range*>::const_iterator end = m_ranges.end();
3477 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3478 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3481 // FIXME: This should update markers for spelling and grammar checking.
3484 void Document::textNodeSplit(Text* oldNode)
3486 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3487 HashSet<Range*>::const_iterator end = m_ranges.end();
3488 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3489 (*it)->textNodeSplit(oldNode);
3492 // FIXME: This should update markers for spelling and grammar checking.
3495 // FIXME: eventually, this should return a DOMWindow stored in the document.
3496 DOMWindow* Document::domWindow() const
3501 // The m_frame pointer is not (not always?) zeroed out when the document is put into b/f cache, so the frame can hold an unrelated document/window pair.
3502 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
3503 if (m_frame->document() != this)
3506 return frame()->domWindow();
3509 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3511 DOMWindow* domWindow = this->domWindow();
3514 domWindow->setAttributeEventListener(eventType, listener);
3517 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3519 DOMWindow* domWindow = this->domWindow();
3522 return domWindow->getAttributeEventListener(eventType);
3525 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3527 ASSERT(!eventDispatchForbidden());
3528 DOMWindow* domWindow = this->domWindow();
3531 domWindow->dispatchEvent(event, target);
3534 void Document::dispatchWindowLoadEvent()
3536 ASSERT(!eventDispatchForbidden());
3537 DOMWindow* domWindow = this->domWindow();
3540 domWindow->dispatchLoadEvent();
3541 m_loadEventFinished = true;
3544 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3546 event->setTarget(domWindow());
3547 m_eventQueue->enqueueEvent(event);
3550 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
3552 event->setTarget(this);
3553 m_eventQueue->enqueueEvent(event);
3556 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
3558 RefPtr<Event> event = EventFactory::create(eventType);
3560 return event.release();
3562 ec = NOT_SUPPORTED_ERR;
3566 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3568 if (eventType == eventNames().DOMSubtreeModifiedEvent)
3569 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
3570 else if (eventType == eventNames().DOMNodeInsertedEvent)
3571 addListenerType(DOMNODEINSERTED_LISTENER);
3572 else if (eventType == eventNames().DOMNodeRemovedEvent)
3573 addListenerType(DOMNODEREMOVED_LISTENER);
3574 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
3575 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3576 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
3577 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3578 else if (eventType == eventNames().DOMAttrModifiedEvent)
3579 addListenerType(DOMATTRMODIFIED_LISTENER);
3580 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
3581 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
3582 else if (eventType == eventNames().overflowchangedEvent)
3583 addListenerType(OVERFLOWCHANGED_LISTENER);
3584 else if (eventType == eventNames().webkitAnimationStartEvent)
3585 addListenerType(ANIMATIONSTART_LISTENER);
3586 else if (eventType == eventNames().webkitAnimationEndEvent)
3587 addListenerType(ANIMATIONEND_LISTENER);
3588 else if (eventType == eventNames().webkitAnimationIterationEvent)
3589 addListenerType(ANIMATIONITERATION_LISTENER);
3590 else if (eventType == eventNames().webkitTransitionEndEvent)
3591 addListenerType(TRANSITIONEND_LISTENER);
3592 else if (eventType == eventNames().beforeloadEvent)
3593 addListenerType(BEFORELOAD_LISTENER);
3594 #if ENABLE(TOUCH_EVENTS)
3595 else if (eventType == eventNames().touchstartEvent
3596 || eventType == eventNames().touchmoveEvent
3597 || eventType == eventNames().touchendEvent
3598 || eventType == eventNames().touchcancelEvent) {
3599 addListenerType(TOUCH_LISTENER);
3600 if (Page* page = this->page())
3601 page->chrome()->client()->needTouchEvents(true);
3604 else if (eventType == eventNames().scrollEvent)
3605 addListenerType(SCROLL_LISTENER);
3608 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3613 HTMLFrameOwnerElement* Document::ownerElement() const
3617 return frame()->ownerElement();
3620 String Document::cookie(ExceptionCode& ec) const
3622 if (page() && !page()->cookieEnabled())
3625 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3626 // INVALID_STATE_ERR exception on getting if the Document has no
3627 // browsing context.
3629 if (!securityOrigin()->canAccessCookies()) {
3634 KURL cookieURL = this->cookieURL();
3635 if (cookieURL.isEmpty())
3638 return cookies(this, cookieURL);
3641 void Document::setCookie(const String& value, ExceptionCode& ec)
3643 if (page() && !page()->cookieEnabled())
3646 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3647 // INVALID_STATE_ERR exception on setting if the Document has no
3648 // browsing context.
3650 if (!securityOrigin()->canAccessCookies()) {
3655 KURL cookieURL = this->cookieURL();
3656 if (cookieURL.isEmpty())
3659 setCookies(this, cookieURL, value);
3662 String Document::referrer() const
3665 return frame()->loader()->referrer();
3669 String Document::domain() const
3671 return securityOrigin()->domain();
3674 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
3676 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3681 // Both NS and IE specify that changing the domain is only allowed when
3682 // the new domain is a suffix of the old domain.
3684 // FIXME: We should add logging indicating why a domain was not allowed.
3686 // If the new domain is the same as the old domain, still call
3687 // securityOrigin()->setDomainForDOM. This will change the
3688 // security check behavior. For example, if a page loaded on port 8000
3689 // assigns its current domain using document.domain, the page will
3690 // allow other pages loaded on different ports in the same domain that
3691 // have also assigned to access this page.
3692 if (equalIgnoringCase(domain(), newDomain)) {
3693 securityOrigin()->setDomainFromDOM(newDomain);
3695 m_frame->script()->updateSecurityOrigin();
3699 int oldLength = domain().length();
3700 int newLength = newDomain.length();
3701 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
3702 if (newLength >= oldLength) {
3707 String test = domain();
3708 // Check that it's a subdomain, not e.g. "ebkit.org"
3709 if (test[oldLength - newLength - 1] != '.') {
3714 // Now test is "webkit.org" from domain()
3715 // and we check that it's the same thing as newDomain
3716 test.remove(0, oldLength - newLength);
3717 if (test != newDomain) {
3722 securityOrigin()->setDomainFromDOM(newDomain);
3724 m_frame->script()->updateSecurityOrigin();
3727 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3728 String Document::lastModified() const
3730 DateComponents date;
3731 bool foundDate = false;
3733 String httpLastModified;
3734 if (DocumentLoader* documentLoader = loader())
3735 httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3736 if (!httpLastModified.isEmpty()) {
3737 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3741 // FIXME: If this document came from the file system, the HTML5
3742 // specificiation tells us to read the last modification date from the file
3745 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3746 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3749 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3754 U16_NEXT(characters, i, length, c)
3755 if (!isValidNameStart(c))
3758 while (i < length) {
3759 U16_NEXT(characters, i, length, c)
3760 if (!isValidNamePart(c))
3767 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
3769 UChar c = characters[0];
3770 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3773 for (unsigned i = 1; i < length; ++i) {
3775 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3782 bool Document::isValidName(const String& name)
3784 unsigned length = name.length();
3788 const UChar* characters = name.characters();
3789 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3792 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3794 unsigned length = qualifiedName.length();
3797 ec = INVALID_CHARACTER_ERR;
3801 bool nameStart = true;
3802 bool sawColon = false;
3805 const UChar* s = qualifiedName.characters();
3806 for (unsigned i = 0; i < length;) {
3808 U16_NEXT(s, i, length, c)
3812 return false; // multiple colons: not allowed
3817 } else if (nameStart) {
3818 if (!isValidNameStart(c)) {
3819 ec = INVALID_CHARACTER_ERR;
3824 if (!isValidNamePart(c)) {
3825 ec = INVALID_CHARACTER_ERR;
3833 localName = qualifiedName;
3835 prefix = qualifiedName.substring(0, colonPos);
3836 if (prefix.isEmpty()) {
3840 localName = qualifiedName.substring(colonPos + 1);
3843 if (localName.isEmpty()) {
3851 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3853 m_decoder = decoder;
3856 KURL Document::completeURL(const String& url) const
3858 // Always return a null URL when passed a null string.
3859 // FIXME: Should we change the KURL constructor to have this behavior?
3860 // See also [CSS]StyleSheet::completeURL(const String&)
3863 const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
3865 return KURL(baseURL, url);
3866 return KURL(baseURL, url, m_decoder->encoding());
3869 void Document::setInPageCache(bool flag)
3871 if (m_inPageCache == flag)
3874 m_inPageCache = flag;
3876 FrameView* v = view();
3878 ASSERT(!m_savedRenderer);
3879 m_savedRenderer = renderer();
3881 v->cacheCurrentScrollPosition();
3882 if (page() && page()->mainFrame() == m_frame)
3883 v->resetScrollbarsAndClearContentsSize();
3885 v->resetScrollbars();
3887 m_styleRecalcTimer.stop();
3889 ASSERT(!renderer() || renderer() == m_savedRenderer);
3890 ASSERT(m_renderArena);
3891 setRenderer(m_savedRenderer);
3892 m_savedRenderer = 0;
3894 if (frame() && frame()->page())
3895 frame()->page()->updateViewportArguments();
3897 if (childNeedsStyleRecalc())
3898 scheduleStyleRecalc();
3902 void Document::documentWillBecomeInactive()
3904 #if USE(ACCELERATED_COMPOSITING)
3906 renderView()->willMoveOffscreen();
3909 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3910 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3911 (*i)->documentWillBecomeInactive();
3914 void Document::documentDidBecomeActive()
3916 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3917 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3918 (*i)->documentDidBecomeActive();
3920 #if USE(ACCELERATED_COMPOSITING)
3922 renderView()->didMoveOnscreen();
3925 if (FrameView* frameView = view())
3926 frameView->setAnimatorsAreActive();
3929 m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
3932 void Document::registerForDocumentActivationCallbacks(Element* e)
3934 m_documentActivationCallbackElements.add(e);
3937 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3939 m_documentActivationCallbackElements.remove(e);
3942 void Document::mediaVolumeDidChange()
3944 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3945 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3946 (*i)->mediaVolumeDidChange();
3949 void Document::registerForMediaVolumeCallbacks(Element* e)
3951 m_mediaVolumeCallbackElements.add(e);
3954 void Document::unregisterForMediaVolumeCallbacks(Element* e)
3956 m_mediaVolumeCallbackElements.remove(e);
3959 void Document::privateBrowsingStateDidChange()
3961 HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
3962 for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
3963 (*it)->privateBrowsingStateDidChange();
3966 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
3968 m_privateBrowsingStateChangedElements.add(e);
3971 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
3973 m_privateBrowsingStateChangedElements.remove(e);
3976 void Document::setShouldCreateRenderers(bool f)
3978 m_createRenderers = f;
3981 bool Document::shouldCreateRenderers()
3983 return m_createRenderers;
3986 // Support for Javascript execCommand, and related methods
3988 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
3990 Frame* frame = document->frame();
3991 if (!frame || frame->document() != document)
3992 return Editor::Command();
3994 document->updateStyleIfNeeded();
3996 return frame->editor()->command(commandName,
3997 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4000 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4002 return command(this, commandName, userInterface).execute(value);
4005 bool Document::queryCommandEnabled(const String& commandName)
4007 return command(this, commandName).isEnabled();
4010 bool Document::queryCommandIndeterm(const String& commandName)
4012 return command(this, commandName).state() == MixedTriState;
4015 bool Document::queryCommandState(const String& commandName)
4017 return command(this, commandName).state() == TrueTriState;
4020 bool Document::queryCommandSupported(const String& commandName)
4022 return command(this, commandName).isSupported();
4025 String Document::queryCommandValue(const String& commandName)
4027 return command(this, commandName).value();
4030 KURL Document::openSearchDescriptionURL()
4032 static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
4033 static const char* const openSearchRelation = "search";
4035 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4036 if (!frame() || frame()->tree()->parent())
4039 // FIXME: Why do we need to wait for FrameStateComplete?
4040 if (frame()->loader()->state() != FrameStateComplete)
4046 RefPtr<HTMLCollection> children = head()->children();
4047 for (Node* child = children->firstItem(); child; child = children->nextItem()) {
4048 if (!child->hasTagName(linkTag))
4050 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4051 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4053 if (linkElement->href().isEmpty())
4055 return linkElement->href();
4063 void Document::applyXSLTransform(ProcessingInstruction* pi)
4065 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4066 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
4067 String resultMIMEType;
4069 String resultEncoding;
4070 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4072 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4073 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
4076 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4078 m_transformSource = source;
4083 void Document::setDesignMode(InheritedBool value)
4085 m_designMode = value;
4086 for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
4087 frame->document()->scheduleForcedStyleRecalc();
4090 Document::InheritedBool Document::getDesignMode() const
4092 return m_designMode;
4095 bool Document::inDesignMode() const
4097 for (const Document* d = this; d; d = d->parentDocument()) {
4098 if (d->m_designMode != inherit)
4099 return d->m_designMode;
4104 Document* Document::parentDocument() const
4108 Frame* parent = m_frame->tree()->parent();
4111 return parent->document();
4114 Document* Document::topDocument() const
4116 Document* doc = const_cast<Document *>(this);
4118 while ((element = doc->ownerElement()))
4119 doc = element->document();
4124 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
4126 return createAttributeNS(String(), name, ec, true);
4129 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
4131 String prefix, localName;
4132 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
4135 QualifiedName qName(prefix, localName, namespaceURI);
4136 if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
4141 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
4142 if (!shouldIgnoreNamespaceChecks && qName.localName() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
4147 // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
4148 // documents if we're wrong.
4149 return Attr::create(0, this, Attribute::createMapped(qName, StringImpl::empty()));
4153 const SVGDocumentExtensions* Document::svgExtensions()
4155 return m_svgExtensions.get();
4158 SVGDocumentExtensions* Document::accessSVGExtensions()
4160 if (!m_svgExtensions)
4161 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4162 return m_svgExtensions.get();
4165 bool Document::hasSVGRootNode() const
4167 return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
4171 PassRefPtr<HTMLCollection> Document::images()
4173 return HTMLCollection::create(this, DocImages);
4176 PassRefPtr<HTMLCollection> Document::applets()
4178 return HTMLCollection::create(this, DocApplets);
4181 PassRefPtr<HTMLCollection> Document::embeds()
4183 return HTMLCollection::create(this, DocEmbeds);
4186 PassRefPtr<HTMLCollection> Document::plugins()
4188 // This is an alias for embeds() required for the JS DOM bindings.
4189 return HTMLCollection::create(this, DocEmbeds);
4192 PassRefPtr<HTMLCollection> Document::objects()
4194 return HTMLCollection::create(this, DocObjects);
4197 PassRefPtr<HTMLCollection> Document::scripts()
4199 return HTMLCollection::create(this, DocScripts);
4202 PassRefPtr<HTMLCollection> Document::links()
4204 return HTMLCollection::create(this, DocLinks);
4207 PassRefPtr<HTMLCollection> Document::forms()
4209 return HTMLCollection::create(this, DocForms);
4212 PassRefPtr<HTMLCollection> Document::anchors()
4214 return HTMLCollection::create(this, DocAnchors);
4217 PassRefPtr<HTMLAllCollection> Document::all()
4219 return HTMLAllCollection::create(this);
4222 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
4224 return HTMLNameCollection::create(this, WindowNamedItems, name);
4227 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
4229 return HTMLNameCollection::create(this, DocumentNamedItems, name);
4232 CollectionCache* Document::nameCollectionInfo(CollectionType type, const AtomicString& name)
4234 ASSERT(type >= FirstNamedDocumentCachedType);
4235 unsigned index = type - FirstNamedDocumentCachedType;
4236 ASSERT(index < NumNamedDocumentCachedTypes);
4238 NamedCollectionMap& map = m_nameCollectionInfo[index];
4239 NamedCollectionMap::iterator iter = map.find(name.impl());
4240 if (iter == map.end())
4241 iter = map.add(name.impl(), new CollectionCache).first;
4242 iter->second->checkConsistency();
4243 return iter->second;
4246 void Document::finishedParsing()
4248 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4249 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4251 if (!m_documentTiming.domContentLoadedEventStart)
4252 m_documentTiming.domContentLoadedEventStart = currentTime();
4253 dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
4254 if (!m_documentTiming.domContentLoadedEventEnd)
4255 m_documentTiming.domContentLoadedEventEnd = currentTime();
4257 if (RefPtr<Frame> f = frame()) {
4258 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4259 // resource loads are complete. HTMLObjectElements can start loading their resources from
4260 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4261 // tag and then reach the end of the document without updating styles, we might not have yet
4262 // started the resource load and might fire the window load event too early. To avoid this
4263 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4264 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4265 updateStyleIfNeeded();
4267 f->loader()->finishedParsing();
4269 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4273 Vector<String> Document::formElementsState() const
4275 Vector<String> stateVector;
4276 stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
4277 typedef FormElementListHashSet::const_iterator Iterator;
4278 Iterator end = m_formElementsWithState.end();
4279 for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
4280 Element* elementWithState = *it;
4282 if (!elementWithState->shouldSaveAndRestoreFormControlState())
4284 if (!elementWithState->saveFormControlState(value))
4286 stateVector.append(elementWithState->formControlName().string());
4287 stateVector.append(elementWithState->formControlType().string());
4288 stateVector.append(value);
4293 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
4294 XPathNSResolver* resolver,
4297 if (!m_xpathEvaluator)
4298 m_xpathEvaluator = XPathEvaluator::create();
4299 return m_xpathEvaluator->createExpression(expression, resolver, ec);
4302 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
4304 if (!m_xpathEvaluator)
4305 m_xpathEvaluator = XPathEvaluator::create();
4306 return m_xpathEvaluator->createNSResolver(nodeResolver);
4309 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
4311 XPathNSResolver* resolver,
4312 unsigned short type,
4313 XPathResult* result,