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 "CSSPrimitiveValueCache.h"
36 #include "CSSStyleSelector.h"
37 #include "CSSStyleSheet.h"
38 #include "CSSValueKeywords.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 #if ENABLE(TIZEN_SMART_FOCUSING)
1197 // 1. Apply every outter frames' scroll value (x, y) to the point
1198 IntPoint convertedPointWithOutterFrames = frameView->convertFromContainingWindow(IntPoint(x, y));
1199 // 2. Apply zoom scale value and current frame's scroll value (x,y) to convertedPointWithOutterFrames
1200 // convertedPointWithOutterFrames.x() * zoomFactor + frameView->scrollX()
1201 // convertedPointWithOutterFrames.y() * zoomFactor + frameView->scrollY()
1202 // 3. Finally, round the point value
1203 IntPoint pointForHittedFrame = roundedIntPoint(FloatPoint(convertedPointWithOutterFrames.x() * zoomFactor + frameView->scrollX(),
1204 convertedPointWithOutterFrames.y() * zoomFactor + frameView->scrollY()));
1206 if (!frameView->visibleContentRect().contains(pointForHittedFrame))
1209 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1210 HitTestResult result(pointForHittedFrame);
1212 IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1214 if (!frameView->visibleContentRect().contains(point))
1217 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1218 HitTestResult result(point);
1221 renderView->layer()->hitTest(request, result);
1224 *localPoint = result.localPoint();
1226 return result.innerNode();
1229 Element* Document::elementFromPoint(int x, int y) const
1233 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1234 while (node && !node->isElementNode())
1235 node = node->parentNode();
1237 node = node->shadowAncestorNode();
1238 return static_cast<Element*>(node);
1241 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1245 LayoutPoint localPoint;
1246 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1250 Node* shadowAncestorNode = node->shadowAncestorNode();
1251 if (shadowAncestorNode != node) {
1252 unsigned offset = shadowAncestorNode->nodeIndex();
1253 ContainerNode* container = shadowAncestorNode->parentNode();
1254 return Range::create(this, container, offset, container, offset);
1257 RenderObject* renderer = node->renderer();
1260 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1261 if (visiblePosition.isNull())
1264 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1265 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1269 * Performs three operations:
1270 * 1. Convert control characters to spaces
1271 * 2. Trim leading and trailing spaces
1272 * 3. Collapse internal whitespace.
1274 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1276 const String& title = titleWithDirection.string();
1277 const UChar* characters = title.characters();
1278 unsigned length = title.length();
1281 StringBuffer<UChar> buffer(length);
1282 unsigned builderIndex = 0;
1284 // Skip leading spaces and leading characters that would convert to spaces
1285 for (i = 0; i < length; ++i) {
1286 UChar c = characters[i];
1287 if (!(c <= 0x20 || c == 0x7F))
1292 return StringWithDirection();
1294 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1295 bool previousCharWasWS = false;
1296 for (; i < length; ++i) {
1297 UChar c = characters[i];
1298 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1299 if (previousCharWasWS)
1301 buffer[builderIndex++] = ' ';
1302 previousCharWasWS = true;
1304 buffer[builderIndex++] = c;
1305 previousCharWasWS = false;
1309 // Strip trailing spaces
1310 while (builderIndex > 0) {
1312 if (buffer[builderIndex] != ' ')
1316 if (!builderIndex && buffer[builderIndex] == ' ')
1317 return StringWithDirection();
1319 buffer.shrink(builderIndex + 1);
1321 // Replace the backslashes with currency symbols if the encoding requires it.
1322 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1324 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1327 void Document::updateTitle(const StringWithDirection& title)
1329 if (m_rawTitle == title)
1333 m_title = canonicalizedTitle(this, m_rawTitle);
1334 if (Frame* f = frame())
1335 f->loader()->setTitle(m_title);
1338 void Document::setTitle(const String& title)
1340 // Title set by JavaScript -- overrides any title elements.
1341 m_titleSetExplicitly = true;
1342 if (!isHTMLDocument() && !isXHTMLDocument())
1344 else if (!m_titleElement) {
1345 if (HTMLElement* headElement = head()) {
1346 m_titleElement = createElement(titleTag, false);
1347 ExceptionCode ec = 0;
1348 headElement->appendChild(m_titleElement, ec);
1353 // The DOM API has no method of specifying direction, so assume LTR.
1354 updateTitle(StringWithDirection(title, LTR));
1356 if (m_titleElement) {
1357 ASSERT(m_titleElement->hasTagName(titleTag));
1358 if (m_titleElement->hasTagName(titleTag))
1359 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1363 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1365 if (titleElement != m_titleElement) {
1366 if (m_titleElement || m_titleSetExplicitly)
1367 // Only allow the first title element to change the title -- others have no effect.
1369 m_titleElement = titleElement;
1375 void Document::removeTitle(Element* titleElement)
1377 if (m_titleElement != titleElement)
1381 m_titleSetExplicitly = false;
1383 // Update title based on first title element in the head, if one exists.
1384 if (HTMLElement* headElement = head()) {
1385 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1386 if (e->hasTagName(titleTag)) {
1387 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1388 setTitleElement(titleElement->textWithDirection(), titleElement);
1393 if (!m_titleElement)
1394 updateTitle(StringWithDirection());
1397 #if ENABLE(PAGE_VISIBILITY_API)
1398 PageVisibilityState Document::visibilityState() const
1400 // The visibility of the document is inherited from the visibility of the
1401 // page. If there is no page associated with the document, we will assume
1402 // that the page is visible i.e. invisibility has to be explicitly
1403 // specified by the embedder.
1404 if (!m_frame || !m_frame->page())
1405 return PageVisibilityStateVisible;
1406 return m_frame->page()->visibilityState();
1409 String Document::webkitVisibilityState() const
1411 return pageVisibilityStateString(visibilityState());
1414 bool Document::webkitHidden() const
1416 return visibilityState() != PageVisibilityStateVisible;
1419 void Document::dispatchVisibilityStateChangeEvent()
1421 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1425 String Document::nodeName() const
1430 Node::NodeType Document::nodeType() const
1432 return DOCUMENT_NODE;
1435 FrameView* Document::view() const
1437 return m_frame ? m_frame->view() : 0;
1440 Page* Document::page() const
1442 return m_frame ? m_frame->page() : 0;
1445 Settings* Document::settings() const
1447 return m_frame ? m_frame->settings() : 0;
1450 PassRefPtr<Range> Document::createRange()
1452 return Range::create(this);
1455 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1456 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1459 ec = NOT_SUPPORTED_ERR;
1462 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1465 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1466 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1469 ec = NOT_SUPPORTED_ERR;
1472 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1475 void Document::scheduleForcedStyleRecalc()
1477 m_pendingStyleRecalcShouldForce = true;
1478 scheduleStyleRecalc();
1481 void Document::scheduleStyleRecalc()
1483 if (m_styleRecalcTimer.isActive() || inPageCache())
1486 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1488 if (!documentsThatNeedStyleRecalc)
1489 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1490 documentsThatNeedStyleRecalc->add(this);
1492 // FIXME: Why on earth is this here? This is clearly misplaced.
1493 invalidateAccessKeyMap();
1495 m_styleRecalcTimer.startOneShot(0);
1497 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1500 void Document::unscheduleStyleRecalc()
1502 ASSERT(!childNeedsStyleRecalc());
1504 if (documentsThatNeedStyleRecalc)
1505 documentsThatNeedStyleRecalc->remove(this);
1507 m_styleRecalcTimer.stop();
1508 m_pendingStyleRecalcShouldForce = false;
1511 bool Document::isPendingStyleRecalc() const
1513 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1516 void Document::styleRecalcTimerFired(Timer<Document>*)
1518 updateStyleIfNeeded();
1521 bool Document::childNeedsAndNotInStyleRecalc()
1523 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1526 void Document::recalcStyle(StyleChange change)
1528 // we should not enter style recalc while painting
1529 if (view() && view()->isPainting()) {
1530 ASSERT(!view()->isPainting());
1534 if (m_inStyleRecalc)
1535 return; // Guard against re-entrancy. -dwh
1537 if (m_hasDirtyStyleSelector)
1538 recalcStyleSelector();
1540 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1542 m_inStyleRecalc = true;
1543 suspendPostAttachCallbacks();
1544 RenderWidget::suspendWidgetHierarchyUpdates();
1546 RefPtr<FrameView> frameView = view();
1548 frameView->pauseScheduledEvents();
1549 frameView->beginDeferredRepaints();
1552 ASSERT(!renderer() || renderArena());
1553 if (!renderer() || !renderArena())
1556 if (m_pendingStyleRecalcShouldForce)
1559 if (change == Force) {
1560 // style selector may set this again during recalc
1561 m_hasNodesWithPlaceholderStyle = false;
1563 RefPtr<RenderStyle> documentStyle = CSSStyleSelector::styleForDocument(this);
1564 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1566 renderer()->setStyle(documentStyle.release());
1569 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1570 if (!n->isElementNode())
1572 Element* element = static_cast<Element*>(n);
1573 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1574 element->recalcStyle(change);
1577 #if USE(ACCELERATED_COMPOSITING)
1579 bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1580 // If we didn't update compositing layers because of layout(), we need to do so here.
1582 view()->updateCompositingLayers();
1587 clearNeedsStyleRecalc();
1588 clearChildNeedsStyleRecalc();
1589 unscheduleStyleRecalc();
1591 m_inStyleRecalc = false;
1593 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1594 if (m_styleSelector) {
1595 m_usesSiblingRules = m_styleSelector->usesSiblingRules();
1596 m_usesFirstLineRules = m_styleSelector->usesFirstLineRules();
1597 m_usesBeforeAfterRules = m_styleSelector->usesBeforeAfterRules();
1598 m_usesLinkRules = m_styleSelector->usesLinkRules();
1602 frameView->resumeScheduledEvents();
1603 frameView->endDeferredRepaints();
1605 RenderWidget::resumeWidgetHierarchyUpdates();
1606 resumePostAttachCallbacks();
1608 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1609 if (m_closeAfterStyleRecalc) {
1610 m_closeAfterStyleRecalc = false;
1614 InspectorInstrumentation::didRecalculateStyle(cookie);
1617 void Document::updateStyleIfNeeded()
1619 ASSERT(isMainThread());
1620 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1622 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1626 m_frame->animation()->beginAnimationUpdate();
1628 recalcStyle(NoChange);
1630 // Tell the animation controller that updateStyleIfNeeded is finished and it can do any post-processing
1632 m_frame->animation()->endAnimationUpdate();
1635 void Document::updateStyleForAllDocuments()
1637 ASSERT(isMainThread());
1638 if (!documentsThatNeedStyleRecalc)
1641 while (documentsThatNeedStyleRecalc->size()) {
1642 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1643 Document* doc = *it;
1644 documentsThatNeedStyleRecalc->remove(doc);
1645 doc->updateStyleIfNeeded();
1649 void Document::updateLayout()
1651 ASSERT(isMainThread());
1652 if (Element* oe = ownerElement())
1653 oe->document()->updateLayout();
1655 updateStyleIfNeeded();
1657 // Only do a layout if changes have occurred that make it necessary.
1658 FrameView* v = view();
1659 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1663 // FIXME: This is a bad idea and needs to be removed eventually.
1664 // Other browsers load stylesheets before they continue parsing the web page.
1665 // Since we don't, we can run JavaScript code that needs answers before the
1666 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1667 // lets us get reasonable answers. The long term solution to this problem is
1668 // to instead suspend JavaScript execution.
1669 void Document::updateLayoutIgnorePendingStylesheets()
1671 bool oldIgnore = m_ignorePendingStylesheets;
1673 if (!haveStylesheetsLoaded()) {
1674 m_ignorePendingStylesheets = true;
1675 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1676 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1677 // with accurate style information. (Our suppression involves blanking the whole page at the
1678 // moment. If it were more refined, we might be able to do something better.)
1679 // It's worth noting though that this entire method is a hack, since what we really want to do is
1680 // suspend JS instead of doing a layout with inaccurate information.
1681 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1682 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1683 styleSelectorChanged(RecalcStyleImmediately);
1684 } else if (m_hasNodesWithPlaceholderStyle)
1685 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1686 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1687 // but here we need up-to-date style immediately.
1693 m_ignorePendingStylesheets = oldIgnore;
1696 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1698 ASSERT_ARG(element, element->document() == this);
1700 bool oldIgnore = m_ignorePendingStylesheets;
1701 m_ignorePendingStylesheets = true;
1702 RefPtr<RenderStyle> style = styleSelector()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1703 m_ignorePendingStylesheets = oldIgnore;
1704 return style.release();
1707 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1709 RefPtr<RenderStyle> style = styleSelector()->styleForPage(pageIndex);
1710 return style.release();
1713 void Document::registerCustomFont(FontData* fontData)
1715 m_customFonts.append(adoptPtr(fontData));
1718 void Document::deleteCustomFonts()
1720 size_t size = m_customFonts.size();
1721 for (size_t i = 0; i < size; ++i)
1722 GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
1724 m_customFonts.clear();
1727 bool Document::isPageBoxVisible(int pageIndex)
1729 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1730 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1733 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1735 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1737 int width = pageSize.width();
1738 int height = pageSize.height();
1739 switch (style->pageSizeType()) {
1740 case PAGE_SIZE_AUTO:
1742 case PAGE_SIZE_AUTO_LANDSCAPE:
1744 std::swap(width, height);
1746 case PAGE_SIZE_AUTO_PORTRAIT:
1748 std::swap(width, height);
1750 case PAGE_SIZE_RESOLVED: {
1751 LengthSize size = style->pageSize();
1752 ASSERT(size.width().isFixed());
1753 ASSERT(size.height().isFixed());
1754 width = size.width().calcValue(0);
1755 height = size.height().calcValue(0);
1759 ASSERT_NOT_REACHED();
1761 pageSize = IntSize(width, height);
1763 // The percentage is calculated with respect to the width even for margin top and bottom.
1764 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1765 marginTop = style->marginTop().isAuto() ? marginTop : style->marginTop().calcValue(width);
1766 marginRight = style->marginRight().isAuto() ? marginRight : style->marginRight().calcValue(width);
1767 marginBottom = style->marginBottom().isAuto() ? marginBottom : style->marginBottom().calcValue(width);
1768 marginLeft = style->marginLeft().isAuto() ? marginLeft : style->marginLeft().calcValue(width);
1771 PassRefPtr<CSSPrimitiveValueCache> Document::cssPrimitiveValueCache() const
1773 if (!m_cssPrimitiveValueCache)
1774 m_cssPrimitiveValueCache = CSSPrimitiveValueCache::create();
1775 return m_cssPrimitiveValueCache;
1778 void Document::setIsViewSource(bool isViewSource)
1780 m_isViewSource = isViewSource;
1781 if (!m_isViewSource)
1784 setSecurityOrigin(SecurityOrigin::createUnique());
1787 void Document::createStyleSelector()
1789 bool matchAuthorAndUserStyles = true;
1790 if (Settings* docSettings = settings())
1791 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1792 m_styleSelector = adoptPtr(new CSSStyleSelector(this, m_styleSheets.get(), m_mappedElementSheet.get(), pageUserSheet(), pageGroupUserSheets(), m_userSheets.get(),
1793 !inQuirksMode(), matchAuthorAndUserStyles));
1794 // 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).
1795 m_usesSiblingRules = m_usesSiblingRules || m_styleSelector->usesSiblingRules();
1796 m_usesFirstLineRules = m_usesFirstLineRules || m_styleSelector->usesFirstLineRules();
1797 m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleSelector->usesBeforeAfterRules();
1798 m_usesLinkRules = m_usesLinkRules || m_styleSelector->usesLinkRules();
1801 void Document::attach()
1803 ASSERT(!attached());
1804 ASSERT(!m_inPageCache);
1805 ASSERT(!m_axObjectCache || this != topDocument());
1808 m_renderArena = adoptPtr(new RenderArena);
1810 // Create the rendering tree
1811 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
1812 #if USE(ACCELERATED_COMPOSITING)
1813 renderView()->didMoveOnscreen();
1818 RenderObject* render = renderer();
1821 TreeScope::attach();
1823 setRenderer(render);
1826 void Document::detach()
1829 ASSERT(!m_inPageCache);
1831 if (this == topDocument())
1832 clearAXObjectCache();
1834 stopActiveDOMObjects();
1835 m_eventQueue->close();
1836 #if ENABLE(FULLSCREEN_API)
1837 m_fullScreenChangeEventTargetQueue.clear();
1840 #if ENABLE(REQUEST_ANIMATION_FRAME)
1841 // FIXME: consider using ActiveDOMObject.
1842 m_scriptedAnimationController = nullptr;
1845 RenderObject* render = renderer();
1847 // Send out documentWillBecomeInactive() notifications to registered elements,
1848 // in order to stop media elements
1849 documentWillBecomeInactive();
1851 #if ENABLE(SHARED_WORKERS)
1852 SharedWorkerRepository::documentDetached(this);
1856 FrameView* view = m_frame->view();
1858 view->detachCustomScrollbars();
1862 // indicate destruction mode, i.e. attached() but renderer == 0
1865 #if ENABLE(FULLSCREEN_API)
1866 if (m_fullScreenRenderer)
1867 setFullScreenRenderer(0);
1874 TreeScope::detach();
1876 unscheduleStyleRecalc();
1881 // This is required, as our Frame might delete itself as soon as it detaches
1882 // us. However, this violates Node::detach() semantics, as it's never
1883 // possible to re-attach. Eventually Document::detach() should be renamed,
1884 // or this setting of the frame to 0 could be made explicit in each of the
1885 // callers of Document::detach().
1887 m_renderArena.clear();
1890 void Document::removeAllEventListeners()
1892 EventTarget::removeAllEventListeners();
1894 if (DOMWindow* domWindow = this->domWindow())
1895 domWindow->removeAllEventListeners();
1896 for (Node* node = firstChild(); node; node = node->traverseNextNode())
1897 node->removeAllEventListeners();
1900 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
1902 ScriptExecutionContext::suspendActiveDOMObjects(why);
1904 #if ENABLE(DEVICE_ORIENTATION)
1908 if (page()->deviceMotionController())
1909 page()->deviceMotionController()->suspendEventsForAllListeners(domWindow());
1910 if (page()->deviceOrientationController())
1911 page()->deviceOrientationController()->suspendEventsForAllListeners(domWindow());
1915 void Document::resumeActiveDOMObjects()
1917 ScriptExecutionContext::resumeActiveDOMObjects();
1919 #if ENABLE(DEVICE_ORIENTATION)
1923 if (page()->deviceMotionController())
1924 page()->deviceMotionController()->resumeEventsForAllListeners(domWindow());
1925 if (page()->deviceOrientationController())
1926 page()->deviceOrientationController()->resumeEventsForAllListeners(domWindow());
1930 RenderView* Document::renderView() const
1932 return toRenderView(renderer());
1935 void Document::clearAXObjectCache()
1937 // clear cache in top document
1938 if (m_axObjectCache) {
1939 // Clear the cache member variable before calling delete because attempts
1940 // are made to access it during destruction.
1941 AXObjectCache* axObjectCache = m_axObjectCache;
1942 m_axObjectCache = 0;
1943 delete axObjectCache;
1947 // ask the top-level document to clear its cache
1948 Document* doc = topDocument();
1950 doc->clearAXObjectCache();
1953 bool Document::axObjectCacheExists() const
1955 if (m_axObjectCache)
1958 Document* doc = topDocument();
1960 return doc->axObjectCacheExists();
1965 AXObjectCache* Document::axObjectCache() const
1967 // The only document that actually has a AXObjectCache is the top-level
1968 // document. This is because we need to be able to get from any WebCoreAXObject
1969 // to any other WebCoreAXObject on the same page. Using a single cache allows
1970 // lookups across nested webareas (i.e. multiple documents).
1972 if (m_axObjectCache) {
1973 // return already known top-level cache
1974 if (!ownerElement())
1975 return m_axObjectCache;
1977 // In some pages with frames, the cache is created before the sub-webarea is
1978 // inserted into the tree. Here, we catch that case and just toss the old
1979 // cache and start over.
1980 // NOTE: This recovery may no longer be needed. I have been unable to trigger
1981 // it again. See rdar://5794454
1982 // FIXME: Can this be fixed when inserting the subframe instead of now?
1983 // FIXME: If this function was called to get the cache in order to remove
1984 // an AXObject, we are now deleting the cache as a whole and returning a
1985 // new empty cache that does not contain the AXObject! That should actually
1986 // be OK. I am concerned about other cases like this where accessing the
1987 // cache blows away the AXObject being operated on.
1988 delete m_axObjectCache;
1989 m_axObjectCache = 0;
1992 // ask the top-level document for its cache
1993 Document* doc = topDocument();
1995 return doc->axObjectCache();
1997 // this is the top-level document, so install a new cache
1998 m_axObjectCache = new AXObjectCache(this);
1999 return m_axObjectCache;
2002 void Document::setVisuallyOrdered()
2004 m_visuallyOrdered = true;
2006 renderer()->style()->setRTLOrdering(VisualOrder);
2009 PassRefPtr<DocumentParser> Document::createParser()
2011 // FIXME: this should probably pass the frame instead
2013 return NewXMLDocumentParser::create(this);
2015 return XMLDocumentParser::create(this, view());
2019 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2021 return parser() ? parser()->asScriptableDocumentParser() : 0;
2024 void Document::open(Document* ownerDocument)
2026 if (ownerDocument) {
2027 setURL(ownerDocument->url());
2028 m_cookieURL = ownerDocument->cookieURL();
2029 setSecurityOrigin(ownerDocument->securityOrigin());
2033 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2034 if (parser->isParsing()) {
2035 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2036 if (parser->isExecutingScript())
2039 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2044 if (m_frame->loader()->state() == FrameStateProvisional)
2045 m_frame->loader()->stopAllLoaders();
2048 removeAllEventListeners();
2050 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2051 parser->setWasCreatedByScript(true);
2053 if (DOMWindow* domWindow = this->domWindow())
2054 domWindow->removeAllEventListeners();
2057 m_frame->loader()->didExplicitOpen();
2060 void Document::detachParser()
2068 void Document::cancelParsing()
2073 // We have to clear the parser to avoid possibly triggering
2074 // the onload handler when closing as a side effect of a cancel-style
2075 // change, such as opening a new document or closing the window while
2081 void Document::implicitOpen()
2087 setCompatibilityMode(NoQuirksMode);
2089 m_parser = createParser();
2091 setReadyState(Loading);
2093 // If we reload, the animation controller sticks around and has
2094 // a stale animation time. We need to update it here.
2095 if (m_frame && m_frame->animation())
2096 m_frame->animation()->beginAnimationUpdate();
2099 HTMLElement* Document::body() const
2101 Node* de = documentElement();
2105 // try to prefer a FRAMESET element over BODY
2107 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2108 if (i->hasTagName(framesetTag))
2109 return toHTMLElement(i);
2111 if (i->hasTagName(bodyTag) && !body)
2114 return toHTMLElement(body);
2117 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2119 RefPtr<HTMLElement> newBody = prpNewBody;
2121 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2122 ec = HIERARCHY_REQUEST_ERR;
2126 if (newBody->document() && newBody->document() != this) {
2128 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2132 newBody = toHTMLElement(node.get());
2135 HTMLElement* b = body();
2137 documentElement()->appendChild(newBody.release(), ec);
2139 documentElement()->replaceChild(newBody.release(), b, ec);
2142 HTMLHeadElement* Document::head()
2144 Node* de = documentElement();
2148 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2149 if (e->hasTagName(headTag))
2150 return static_cast<HTMLHeadElement*>(e);
2155 void Document::close()
2157 // FIXME: We should follow the specification more closely:
2158 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2160 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2166 void Document::explicitClose()
2172 // Because we have no frame, we don't know if all loading has completed,
2173 // so we just call implicitClose() immediately. FIXME: This might fire
2174 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2179 m_frame->loader()->checkCompleted();
2182 void Document::implicitClose()
2184 // 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.
2185 if (m_inStyleRecalc) {
2186 m_closeAfterStyleRecalc = true;
2190 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2191 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2196 m_processingLoadEvent = true;
2198 ScriptableDocumentParser* parser = scriptableDocumentParser();
2199 m_wellFormed = parser && parser->wellFormed();
2201 // We have to clear the parser, in case someone document.write()s from the
2202 // onLoad event handler, as in Radar 3206524.
2205 // Parser should have picked up all preloads by now
2206 m_cachedResourceLoader->clearPreloads();
2208 // FIXME: We kick off the icon loader when the Document is done parsing.
2209 // There are earlier opportunities we could start it:
2210 // -When the <head> finishes parsing
2211 // -When any new HTMLLinkElement is inserted into the document
2212 // But those add a dynamic component to the favicon that has UI
2213 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2216 f->loader()->icon()->startLoader();
2217 f->animation()->resumeAnimationsForDocument(this);
2220 ImageLoader::dispatchPendingBeforeLoadEvents();
2221 ImageLoader::dispatchPendingLoadEvents();
2222 dispatchWindowLoadEvent();
2223 enqueuePageshowEvent(PageshowEventNotPersisted);
2224 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2227 f->loader()->handledOnloadEvents();
2228 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2229 if (!ownerElement())
2230 printf("onload fired at %d\n", elapsedTime());
2233 m_processingLoadEvent = false;
2235 // An event handler may have removed the frame
2239 // Make sure both the initial layout and reflow happen after the onload
2240 // fires. This will improve onload scores, and other browsers do it.
2241 // If they wanna cheat, we can too. -dwh
2243 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2244 // Just bail out. Before or during the onload we were shifted to another page.
2245 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2246 view()->unscheduleRelayout();
2250 frame()->loader()->checkCallImplicitClose();
2251 RenderObject* renderObject = renderer();
2253 // We used to force a synchronous display and flush here. This really isn't
2254 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2255 // (if your platform is syncing flushes and limiting them to 60fps).
2256 m_overMinimumLayoutThreshold = true;
2257 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2258 updateStyleIfNeeded();
2260 // Always do a layout after loading if needed.
2261 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2265 // If painting and compositing layer updates were suppressed pending the load event, do these actions now.
2266 if (renderer() && settings() && settings()->suppressIncrementalRendering()) {
2267 #if USE(ACCELERATED_COMPOSITING)
2268 view()->updateCompositingLayers();
2270 renderer()->repaint();
2273 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2274 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2275 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2276 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2277 // exists in the cache (we ignore the return value because we don't need it here). This is
2278 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2279 axObjectCache()->getOrCreate(renderObject);
2280 if (this == topDocument())
2281 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2283 // AXLoadComplete can only be posted on the top document, so if it's a document
2284 // in an iframe that just finished loading, post a notification on the iframe
2286 ScrollView* scrollView = frame()->view();
2287 if (scrollView && scrollView->isFrameView()) {
2288 HTMLFrameOwnerElement* owner = static_cast<FrameView*>(scrollView)->frame()->ownerElement();
2289 if (owner && owner->renderer()) {
2290 AccessibilityObject* axIFrame = axObjectCache()->getOrCreate(owner->renderer());
2291 axObjectCache()->postNotification(axIFrame, axIFrame->document(), AXObjectCache::AXLayoutComplete, true);
2299 // FIXME: Officially, time 0 is when the outermost <svg> receives its
2300 // SVGLoad event, but we don't implement those yet. This is close enough
2301 // for now. In some cases we should have fired earlier.
2302 if (svgExtensions())
2303 accessSVGExtensions()->startAnimations();
2307 void Document::setParsing(bool b)
2310 if (!m_bParsing && view())
2311 view()->scheduleRelayout();
2313 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2314 if (!ownerElement() && !m_bParsing)
2315 printf("Parsing finished at %d\n", elapsedTime());
2319 bool Document::shouldScheduleLayout()
2321 // This function will only be called when FrameView thinks a layout is needed.
2322 // This enforces a couple extra rules.
2324 // (a) Only schedule a layout once the stylesheets are loaded.
2325 // (b) Only schedule layout once we have a body element.
2327 return (haveStylesheetsLoaded() && body())
2328 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2331 bool Document::isLayoutTimerActive()
2333 return view() && view()->layoutPending() && !minimumLayoutDelay();
2336 int Document::minimumLayoutDelay()
2338 if (m_overMinimumLayoutThreshold)
2341 int elapsed = elapsedTime();
2342 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2344 // We'll want to schedule the timer to fire at the minimum layout threshold.
2345 return max(0, cLayoutScheduleThreshold - elapsed);
2348 int Document::elapsedTime() const
2350 return static_cast<int>((currentTime() - m_startTime) * 1000);
2353 void Document::write(const SegmentedString& text, Document* ownerDocument)
2355 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2357 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2358 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2360 if (m_writeRecursionIsTooDeep)
2363 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2364 if (!ownerElement())
2365 printf("Beginning a document.write at %d\n", elapsedTime());
2368 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2369 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2372 if (!hasInsertionPoint)
2373 open(ownerDocument);
2376 m_parser->insert(text);
2378 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2379 if (!ownerElement())
2380 printf("Ending a document.write at %d\n", elapsedTime());
2384 void Document::write(const String& text, Document* ownerDocument)
2386 write(SegmentedString(text), ownerDocument);
2389 void Document::writeln(const String& text, Document* ownerDocument)
2391 write(text, ownerDocument);
2392 write("\n", ownerDocument);
2395 const KURL& Document::virtualURL() const
2400 KURL Document::virtualCompleteURL(const String& url) const
2402 return completeURL(url);
2405 double Document::minimumTimerInterval() const
2409 return ScriptExecutionContext::minimumTimerInterval();
2410 return p->settings()->minDOMTimerInterval();
2413 EventTarget* Document::errorEventTarget()
2418 void Document::logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
2420 addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, lineNumber, sourceURL, callStack);
2423 void Document::setURL(const KURL& url)
2425 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2426 if (newURL == m_url)
2430 m_documentURI = m_url.string();
2434 void Document::updateBaseURL()
2436 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2437 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2438 // from the Document interface otherwise.
2439 if (!m_baseElementURL.isEmpty())
2440 m_baseURL = m_baseElementURL;
2441 else if (!m_baseURLOverride.isEmpty())
2442 m_baseURL = m_baseURLOverride;
2444 // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
2445 // so we use a null base URL.
2446 m_baseURL = KURL(KURL(), documentURI());
2449 if (!m_baseURL.isValid())
2453 m_elemSheet->setFinalURL(m_baseURL);
2454 if (m_mappedElementSheet)
2455 m_mappedElementSheet->setFinalURL(m_baseURL);
2458 void Document::setBaseURLOverride(const KURL& url)
2460 m_baseURLOverride = url;
2464 void Document::processBaseElement()
2466 // Find the first href attribute in a base element and the first target attribute in a base element.
2467 const AtomicString* href = 0;
2468 const AtomicString* target = 0;
2469 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2470 if (node->hasTagName(baseTag)) {
2472 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2473 if (!value.isNull())
2477 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2478 if (!value.isNull())
2484 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2485 KURL baseElementURL;
2487 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2488 if (!strippedHref.isEmpty())
2489 baseElementURL = KURL(url(), strippedHref);
2491 if (m_baseElementURL != baseElementURL) {
2492 m_baseElementURL = baseElementURL;
2496 m_baseTarget = target ? *target : nullAtom;
2499 String Document::userAgent(const KURL& url) const
2501 return frame() ? frame()->loader()->userAgent(url) : String();
2504 void Document::disableEval()
2509 frame()->script()->disableEval();
2512 CSSStyleSheet* Document::pageUserSheet()
2514 if (m_pageUserSheet)
2515 return m_pageUserSheet.get();
2517 Page* owningPage = page();
2521 String userSheetText = owningPage->userStyleSheet();
2522 if (userSheetText.isEmpty())
2525 // Parse the sheet and cache it.
2526 m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2527 m_pageUserSheet->setIsUserStyleSheet(true);
2528 m_pageUserSheet->parseString(userSheetText, !inQuirksMode());
2529 return m_pageUserSheet.get();
2532 void Document::clearPageUserSheet()
2534 if (m_pageUserSheet) {
2535 m_pageUserSheet = 0;
2536 styleSelectorChanged(DeferRecalcStyle);
2540 void Document::updatePageUserSheet()
2542 clearPageUserSheet();
2543 if (pageUserSheet())
2544 styleSelectorChanged(RecalcStyleImmediately);
2547 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2549 if (m_pageGroupUserSheetCacheValid)
2550 return m_pageGroupUserSheets.get();
2552 m_pageGroupUserSheetCacheValid = true;
2554 Page* owningPage = page();
2558 const PageGroup& pageGroup = owningPage->group();
2559 const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2563 UserStyleSheetMap::const_iterator end = sheetsMap->end();
2564 for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2565 const UserStyleSheetVector* sheets = it->second;
2566 for (unsigned i = 0; i < sheets->size(); ++i) {
2567 const UserStyleSheet* sheet = sheets->at(i).get();
2568 if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2570 if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2572 RefPtr<CSSStyleSheet> parsedSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2573 parsedSheet->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
2574 parsedSheet->parseString(sheet->source(), !inQuirksMode());
2575 if (!m_pageGroupUserSheets)
2576 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2577 m_pageGroupUserSheets->append(parsedSheet.release());
2581 return m_pageGroupUserSheets.get();
2584 void Document::clearPageGroupUserSheets()
2586 m_pageGroupUserSheetCacheValid = false;
2587 if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
2588 m_pageGroupUserSheets->clear();
2589 styleSelectorChanged(DeferRecalcStyle);
2593 void Document::updatePageGroupUserSheets()
2595 clearPageGroupUserSheets();
2596 if (pageGroupUserSheets() && pageGroupUserSheets()->size())
2597 styleSelectorChanged(RecalcStyleImmediately);
2600 void Document::addUserSheet(PassRefPtr<CSSStyleSheet> userSheet)
2603 m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2604 m_userSheets->append(userSheet);
2605 styleSelectorChanged(RecalcStyleImmediately);
2608 CSSStyleSheet* Document::elementSheet()
2611 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2612 return m_elemSheet.get();
2615 CSSStyleSheet* Document::mappedElementSheet()
2617 if (!m_mappedElementSheet)
2618 m_mappedElementSheet = CSSStyleSheet::createInline(this, m_baseURL);
2619 return m_mappedElementSheet.get();
2622 int Document::nodeAbsIndex(Node *node)
2624 ASSERT(node->document() == this);
2627 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2632 Node* Document::nodeWithAbsIndex(int absIndex)
2635 for (int i = 0; n && (i < absIndex); i++)
2636 n = n->traverseNextNode();
2640 void Document::processHttpEquiv(const String& equiv, const String& content)
2642 ASSERT(!equiv.isNull() && !content.isNull());
2644 Frame* frame = this->frame();
2646 if (equalIgnoringCase(equiv, "default-style")) {
2647 // The preferred style set has been overridden as per section
2648 // 14.3.2 of the HTML4.0 specification. We need to update the
2649 // sheet used variable and then update our style selector.
2650 // For more info, see the test at:
2651 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2653 m_selectedStylesheetSet = content;
2654 m_preferredStylesheetSet = content;
2655 styleSelectorChanged(DeferRecalcStyle);
2656 } else if (equalIgnoringCase(equiv, "refresh")) {
2659 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2661 url = m_url.string();
2663 url = completeURL(url).string();
2664 frame->navigationScheduler()->scheduleRedirect(delay, url);
2666 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2667 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2668 if (isHTMLDocument()) {
2669 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
2670 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
2672 } else if (equalIgnoringCase(equiv, "content-language"))
2673 setContentLanguage(content);
2674 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2675 parseDNSPrefetchControlHeader(content);
2676 else if (equalIgnoringCase(equiv, "x-frame-options")) {
2678 FrameLoader* frameLoader = frame->loader();
2679 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
2680 frameLoader->stopAllLoaders();
2681 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
2683 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
2684 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
2687 } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2688 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
2689 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2690 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
2693 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2694 static bool isSeparator(UChar c)
2696 #if ENABLE(TIZEN_SUPPORT_VIEWPORT)
2697 // Some websites are using seprator of viewport meta tag with ';'.
2698 // For example, facebook.
2699 // However, the ';' is not correct sperator in viewport specification.
2700 // I report this problem to webkit. WebKit guy said that facebook should
2701 // fix this wrong usage. For now, our browser needs to support ';' until facebook fixes this problem. - Gyuyoung Kim
2702 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0' || c == ';';
2704 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2708 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2710 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2711 int keyBegin, keyEnd;
2712 int valueBegin, valueEnd;
2715 int length = features.length();
2716 String buffer = features.lower();
2717 while (i < length) {
2718 // skip to first non-separator, but don't skip past the end of the string
2719 while (isSeparator(buffer[i])) {
2726 // skip to first separator
2727 while (!isSeparator(buffer[i]))
2731 // skip to first '=', but don't skip past a ',' or the end of the string
2732 while (buffer[i] != '=') {
2733 if (buffer[i] == ',' || i >= length)
2738 // skip to first non-separator, but don't skip past a ',' or the end of the string
2739 while (isSeparator(buffer[i])) {
2740 if (buffer[i] == ',' || i >= length)
2746 // skip to first separator
2747 while (!isSeparator(buffer[i]))
2751 ASSERT(i <= length);
2753 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2754 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2755 callback(keyString, valueString, this, data);
2759 void Document::processViewport(const String& features)
2761 ASSERT(!features.isNull());
2763 m_viewportArguments = ViewportArguments(ViewportArguments::ViewportMeta);
2764 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2766 Frame* frame = this->frame();
2767 if (!frame || !frame->page())
2770 frame->page()->updateViewportArguments();
2773 #if ENABLE(TIZEN_DAILY_UPVERSIONING)
2774 void Document::processReferrerPolicy(const String& policy)
2776 ASSERT(!policy.isNull());
2778 m_referrerPolicy = SecurityPolicy::ReferrerPolicyDefault;
2780 if (equalIgnoringCase(policy, "never"))
2781 m_referrerPolicy = SecurityPolicy::ReferrerPolicyNever;
2782 else if (equalIgnoringCase(policy, "always"))
2783 m_referrerPolicy = SecurityPolicy::ReferrerPolicyAlways;
2784 else if (equalIgnoringCase(policy, "origin"))
2785 m_referrerPolicy = SecurityPolicy::ReferrerPolicyOrigin;
2788 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
2789 void Document::processMobileWebAppCapable(const String& content)
2791 ASSERT(!content.isNull());
2793 Frame* frame = this->frame();
2794 if (!frame || !frame->page() || !frame->page()->chrome() || !frame->page()->chrome()->client())
2797 frame->page()->chrome()->client()->setMobileWebAppCapableState(content);
2800 void Document::processMobileWebAppStatusBarStyle(const String& content)
2802 ASSERT(!content.isNull());
2804 Frame* frame = this->frame();
2805 if (!frame || !frame->page() || !frame->page()->chrome() || !frame->page()->chrome()->client())
2808 frame->page()->chrome()->client()->setMobileWebAppStatusBarStyle(content);
2812 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2814 ASSERT(!renderer() || renderer()->isRenderView());
2817 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
2819 HitTestResult result(documentPoint);
2820 renderView()->layer()->hitTest(request, result);
2822 if (!request.readOnly())
2823 updateStyleIfNeeded();
2825 return MouseEventWithHitTestResults(event, result);
2828 // DOM Section 1.1.1
2829 bool Document::childTypeAllowed(NodeType type) const
2832 case ATTRIBUTE_NODE:
2833 case CDATA_SECTION_NODE:
2834 case DOCUMENT_FRAGMENT_NODE:
2837 case ENTITY_REFERENCE_NODE:
2840 case XPATH_NAMESPACE_NODE:
2841 case SHADOW_ROOT_NODE:
2844 case PROCESSING_INSTRUCTION_NODE:
2846 case DOCUMENT_TYPE_NODE:
2848 // Documents may contain no more than one of each of these.
2849 // (One Element and one DocumentType.)
2850 for (Node* c = firstChild(); c; c = c->nextSibling())
2851 if (c->nodeType() == type)
2858 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2861 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2864 if (oldChild->nodeType() == newChild->nodeType())
2867 int numDoctypes = 0;
2868 int numElements = 0;
2870 // First, check how many doctypes and elements we have, not counting
2871 // the child we're about to remove.
2872 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2876 switch (c->nodeType()) {
2877 case DOCUMENT_TYPE_NODE:
2888 // Then, see how many doctypes and elements might be added by the new child.
2889 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2890 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2891 switch (c->nodeType()) {
2892 case ATTRIBUTE_NODE:
2893 case CDATA_SECTION_NODE:
2894 case DOCUMENT_FRAGMENT_NODE:
2897 case ENTITY_REFERENCE_NODE:
2900 case XPATH_NAMESPACE_NODE:
2903 case PROCESSING_INSTRUCTION_NODE:
2905 case DOCUMENT_TYPE_NODE:
2911 case SHADOW_ROOT_NODE:
2912 ASSERT_NOT_REACHED();
2917 switch (newChild->nodeType()) {
2918 case ATTRIBUTE_NODE:
2919 case CDATA_SECTION_NODE:
2920 case DOCUMENT_FRAGMENT_NODE:
2923 case ENTITY_REFERENCE_NODE:
2926 case XPATH_NAMESPACE_NODE:
2927 case SHADOW_ROOT_NODE:
2930 case PROCESSING_INSTRUCTION_NODE:
2932 case DOCUMENT_TYPE_NODE:
2941 if (numElements > 1 || numDoctypes > 1)
2947 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2949 // Spec says cloning Document nodes is "implementation dependent"
2950 // so we do not support it...
2954 StyleSheetList* Document::styleSheets()
2956 return m_styleSheets.get();
2959 String Document::preferredStylesheetSet() const
2961 return m_preferredStylesheetSet;
2964 String Document::selectedStylesheetSet() const
2966 return m_selectedStylesheetSet;
2969 void Document::setSelectedStylesheetSet(const String& aString)
2971 m_selectedStylesheetSet = aString;
2972 styleSelectorChanged(DeferRecalcStyle);
2975 // This method is called whenever a top-level stylesheet has finished loading.
2976 void Document::removePendingSheet()
2978 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2979 ASSERT(m_pendingStylesheets > 0);
2981 m_pendingStylesheets--;
2983 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2984 if (!ownerElement())
2985 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2988 if (m_pendingStylesheets)
2991 styleSelectorChanged(RecalcStyleImmediately);
2993 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2994 parser->executeScriptsWaitingForStylesheets();
2996 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2997 view()->scrollToFragment(m_url);
3000 void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
3002 // Don't bother updating, since we haven't loaded all our style info yet
3003 // and haven't calculated the style selector for the first time.
3004 if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
3007 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3008 if (!ownerElement())
3009 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3012 recalcStyleSelector();
3014 if (updateFlag == DeferRecalcStyle) {
3015 scheduleForcedStyleRecalc();
3019 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
3020 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3022 renderer()->repaint();
3025 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3026 // make sure animations get the correct update time
3028 m_frame->animation()->beginAnimationUpdate();
3031 m_frame->animation()->endAnimationUpdate();
3033 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3034 if (!ownerElement())
3035 printf("Finished update of style selector at time %d\n", elapsedTime());
3039 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3041 view()->scheduleRelayout();
3044 if (m_mediaQueryMatcher)
3045 m_mediaQueryMatcher->styleSelectorChanged();
3048 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
3050 if (!node->inDocument())
3053 // Until the <body> exists, we have no choice but to compare document positions,
3054 // since styles outside of the body and head continue to be shunted into the head
3055 // (and thus can shift to end up before dynamically added DOM content that is also
3056 // outside the body).
3057 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3058 m_styleSheetCandidateNodes.add(node);
3062 // Determine an appropriate insertion point.
3063 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3064 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3065 StyleSheetCandidateListHashSet::iterator it = end;
3066 Node* followingNode = 0;
3070 unsigned short position = n->compareDocumentPosition(node);
3071 if (position == DOCUMENT_POSITION_FOLLOWING) {
3072 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3076 } while (it != begin);
3078 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3081 void Document::removeStyleSheetCandidateNode(Node* node)
3083 m_styleSheetCandidateNodes.remove(node);
3086 void Document::recalcStyleSelector()
3088 if (m_inStyleRecalc) {
3089 // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3090 // https://bugs.webkit.org/show_bug.cgi?id=54344
3091 // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3092 m_hasDirtyStyleSelector = true;
3093 scheduleForcedStyleRecalc();
3096 if (!renderer() || !attached())
3099 StyleSheetVector sheets;
3101 bool matchAuthorAndUserStyles = true;
3102 if (Settings* settings = this->settings())
3103 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
3105 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3106 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3107 if (!matchAuthorAndUserStyles)
3109 for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3112 StyleSheet* sheet = 0;
3114 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3115 // Processing instruction (XML documents only).
3116 // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3117 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3118 sheet = pi->sheet();
3120 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3121 if (pi->isXSL() && !transformSourceDocument()) {
3122 // Don't apply XSL transforms until loading is finished.
3124 applyXSLTransform(pi);
3128 } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3130 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3133 Element* e = static_cast<Element*>(n);
3134 AtomicString title = e->getAttribute(titleAttr);
3135 bool enabledViaScript = false;
3136 if (e->hasLocalName(linkTag)) {
3138 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3139 if (linkElement->isDisabled())
3141 enabledViaScript = linkElement->isEnabledViaScript();
3142 if (linkElement->isLoading()) {
3143 // it is loading but we should still decide which style sheet set to use
3144 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3145 const AtomicString& rel = e->getAttribute(relAttr);
3146 if (!rel.contains("alternate")) {
3147 m_preferredStylesheetSet = title;
3148 m_selectedStylesheetSet = title;
3153 if (!linkElement->sheet())
3157 // Get the current preferred styleset. This is the
3158 // set of sheets that will be enabled.
3160 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3161 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3164 if (e->hasLocalName(linkTag))
3165 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3168 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3170 // Check to see if this sheet belongs to a styleset
3171 // (thus making it PREFERRED or ALTERNATE rather than
3173 if (!enabledViaScript && !title.isEmpty()) {
3174 // Yes, we have a title.
3175 if (m_preferredStylesheetSet.isEmpty()) {
3176 // No preferred set has been established. If
3177 // we are NOT an alternate sheet, then establish
3178 // us as the preferred set. Otherwise, just ignore
3180 AtomicString rel = e->getAttribute(relAttr);
3181 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3182 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3185 if (title != m_preferredStylesheetSet)
3191 sheets.append(sheet);
3194 m_styleSheets->swap(sheets);
3196 m_styleSelector.clear();
3197 m_didCalculateStyleSelector = true;
3198 m_hasDirtyStyleSelector = false;
3201 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3203 m_hoverNode = newHoverNode;
3206 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3208 m_activeNode = newActiveNode;
3211 void Document::focusedNodeRemoved()
3216 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3218 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3221 bool nodeInSubtree = false;
3222 if (amongChildrenOnly)
3223 nodeInSubtree = m_focusedNode->isDescendantOf(node);
3225 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
3228 document()->focusedNodeRemoved();
3231 void Document::hoveredNodeDetached(Node* node)
3233 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3236 m_hoverNode = node->parentNode();
3237 while (m_hoverNode && !m_hoverNode->renderer())
3238 m_hoverNode = m_hoverNode->parentNode();
3240 frame()->eventHandler()->scheduleHoverStateUpdate();
3243 void Document::activeChainNodeDetached(Node* node)
3245 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3248 m_activeNode = node->parentNode();
3249 while (m_activeNode && !m_activeNode->renderer())
3250 m_activeNode = m_activeNode->parentNode();
3253 #if ENABLE(DASHBOARD_SUPPORT)
3254 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
3256 return m_dashboardRegions;
3259 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
3261 m_dashboardRegions = regions;
3262 setDashboardRegionsDirty(false);
3266 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3268 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3270 // Make sure newFocusedNode is actually in this document
3271 if (newFocusedNode && (newFocusedNode->document() != this))
3274 if (m_focusedNode == newFocusedNode)
3280 bool focusChangeBlocked = false;
3281 RefPtr<Node> oldFocusedNode = m_focusedNode;
3284 // Remove focus from the existing focus node (if any)
3285 if (oldFocusedNode && !oldFocusedNode->inDetach()) {
3286 if (oldFocusedNode->active())
3287 oldFocusedNode->setActive(false);
3289 oldFocusedNode->setFocus(false);
3291 // Dispatch a change event for text fields or textareas that have been edited
3292 if (oldFocusedNode->isElementNode()) {
3293 Element* element = static_cast<Element*>(oldFocusedNode.get());
3294 if (element->wasChangedSinceLastFormControlChangeEvent())
3295 element->dispatchFormControlChangeEvent();
3298 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3299 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3301 if (m_focusedNode) {
3302 // handler shifted focus
3303 focusChangeBlocked = true;
3307 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3308 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3309 // on it, probably when <rdar://problem/8503958> is resolved.
3310 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3312 if (m_focusedNode) {
3313 // handler shifted focus
3314 focusChangeBlocked = true;
3317 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3320 if (oldFocusedNode == oldFocusedNode->rootEditableElement())
3321 frame()->editor()->didEndEditing();
3324 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3326 oldWidget->setFocus(false);
3328 view()->setFocus(false);
3332 if (newFocusedNode) {
3333 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3334 // delegate blocks focus change
3335 focusChangeBlocked = true;
3336 goto SetFocusedNodeDone;
3338 // Set focus on the new node
3339 m_focusedNode = newFocusedNode;
3341 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3342 m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3344 if (m_focusedNode != newFocusedNode) {
3345 // handler shifted focus
3346 focusChangeBlocked = true;
3347 goto SetFocusedNodeDone;
3350 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3351 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3352 // on it, probably when <rdar://problem/8503958> is m.
3353 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3355 if (m_focusedNode != newFocusedNode) {
3356 // handler shifted focus
3357 focusChangeBlocked = true;
3358 goto SetFocusedNodeDone;
3360 m_focusedNode->setFocus(true);
3362 if (m_focusedNode == m_focusedNode->rootEditableElement())
3363 frame()->editor()->didBeginEditing();
3365 // eww, I suck. set the qt focus correctly
3366 // ### find a better place in the code for this
3368 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3370 // Make sure a widget has the right size before giving it focus.
3371 // Otherwise, we are testing edge cases of the Widget code.
3372 // Specifically, in WebCore this does not work well for text fields.
3374 // Re-get the widget in case updating the layout changed things.
3375 focusWidget = widgetForNode(m_focusedNode.get());
3378 focusWidget->setFocus(true);
3380 view()->setFocus(true);
3384 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3385 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
3386 RenderObject* oldFocusedRenderer = 0;
3387 RenderObject* newFocusedRenderer = 0;
3390 oldFocusedRenderer = oldFocusedNode->renderer();
3392 newFocusedRenderer = newFocusedNode->renderer();
3394 axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
3397 if (!focusChangeBlocked)
3398 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3401 updateStyleIfNeeded();
3402 return !focusChangeBlocked;
3405 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3409 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3410 if (node->isFocusable())
3415 void Document::setCSSTarget(Element* n)
3418 m_cssTarget->setNeedsStyleRecalc();
3421 n->setNeedsStyleRecalc();
3424 void Document::attachNodeIterator(NodeIterator* ni)
3426 m_nodeIterators.add(ni);
3429 void Document::detachNodeIterator(NodeIterator* ni)
3431 // The node iterator can be detached without having been attached if its root node didn't have a document
3432 // when the iterator was created, but has it now.
3433 m_nodeIterators.remove(ni);
3436 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3438 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3439 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3440 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3441 if ((*it)->root() == node) {
3442 detachNodeIterator(*it);
3443 newDocument->attachNodeIterator(*it);
3448 void Document::nodeChildrenChanged(ContainerNode* container)
3450 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3451 HashSet<Range*>::const_iterator end = m_ranges.end();
3452 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3453 (*it)->nodeChildrenChanged(container);
3457 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3459 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3460 HashSet<Range*>::const_iterator end = m_ranges.end();
3461 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3462 (*it)->nodeChildrenWillBeRemoved(container);
3465 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3466 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3467 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3468 (*it)->nodeWillBeRemoved(n);
3471 if (Frame* frame = this->frame()) {
3472 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3473 frame->eventHandler()->nodeWillBeRemoved(n);
3474 frame->selection()->nodeWillBeRemoved(n);
3475 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3480 void Document::nodeWillBeRemoved(Node* n)
3482 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3483 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3484 (*it)->nodeWillBeRemoved(n);
3486 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3487 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3488 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3489 (*it)->nodeWillBeRemoved(n);
3492 if (Frame* frame = this->frame()) {
3493 frame->eventHandler()->nodeWillBeRemoved(n);
3494 frame->selection()->nodeWillBeRemoved(n);
3495 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3499 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3501 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3502 HashSet<Range*>::const_iterator end = m_ranges.end();
3503 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3504 (*it)->textInserted(text, offset, length);
3507 // Update the markers for spelling and grammar checking.
3508 m_markers->shiftMarkers(text, offset, length);
3511 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3513 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3514 HashSet<Range*>::const_iterator end = m_ranges.end();
3515 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3516 (*it)->textRemoved(text, offset, length);
3519 // Update the markers for spelling and grammar checking.
3520 m_markers->removeMarkers(text, offset, length);
3521 m_markers->shiftMarkers(text, offset + length, 0 - length);
3524 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3526 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3527 NodeWithIndex oldNodeWithIndex(oldNode);
3528 HashSet<Range*>::const_iterator end = m_ranges.end();
3529 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3530 (*it)->textNodesMerged(oldNodeWithIndex, offset);
3533 // FIXME: This should update markers for spelling and grammar checking.
3536 void Document::textNodeSplit(Text* oldNode)
3538 if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3539 HashSet<Range*>::const_iterator end = m_ranges.end();
3540 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3541 (*it)->textNodeSplit(oldNode);
3544 // FIXME: This should update markers for spelling and grammar checking.
3547 // FIXME: eventually, this should return a DOMWindow stored in the document.
3548 DOMWindow* Document::domWindow() const
3553 // 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.
3554 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
3555 if (m_frame->document() != this)
3558 return frame()->domWindow();
3561 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3563 DOMWindow* domWindow = this->domWindow();
3566 domWindow->setAttributeEventListener(eventType, listener);
3569 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3571 DOMWindow* domWindow = this->domWindow();
3574 return domWindow->getAttributeEventListener(eventType);
3577 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3579 ASSERT(!eventDispatchForbidden());
3580 DOMWindow* domWindow = this->domWindow();
3583 domWindow->dispatchEvent(event, target);
3586 void Document::dispatchWindowLoadEvent()
3588 ASSERT(!eventDispatchForbidden());
3589 DOMWindow* domWindow = this->domWindow();
3592 domWindow->dispatchLoadEvent();
3593 m_loadEventFinished = true;
3596 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3598 event->setTarget(domWindow());
3599 m_eventQueue->enqueueEvent(event);
3602 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
3604 event->setTarget(this);
3605 m_eventQueue->enqueueEvent(event);
3608 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
3610 RefPtr<Event> event = EventFactory::create(eventType);
3612 return event.release();
3614 ec = NOT_SUPPORTED_ERR;
3618 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3620 if (eventType == eventNames().DOMSubtreeModifiedEvent)
3621 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
3622 else if (eventType == eventNames().DOMNodeInsertedEvent)
3623 addListenerType(DOMNODEINSERTED_LISTENER);
3624 else if (eventType == eventNames().DOMNodeRemovedEvent)
3625 addListenerType(DOMNODEREMOVED_LISTENER);
3626 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
3627 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3628 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
3629 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3630 else if (eventType == eventNames().DOMAttrModifiedEvent)
3631 addListenerType(DOMATTRMODIFIED_LISTENER);
3632 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
3633 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
3634 else if (eventType == eventNames().overflowchangedEvent)
3635 addListenerType(OVERFLOWCHANGED_LISTENER);
3636 else if (eventType == eventNames().webkitAnimationStartEvent)
3637 addListenerType(ANIMATIONSTART_LISTENER);
3638 else if (eventType == eventNames().webkitAnimationEndEvent)
3639 addListenerType(ANIMATIONEND_LISTENER);
3640 else if (eventType == eventNames().webkitAnimationIterationEvent)
3641 addListenerType(ANIMATIONITERATION_LISTENER);
3642 else if (eventType == eventNames().webkitTransitionEndEvent)
3643 addListenerType(TRANSITIONEND_LISTENER);
3644 else if (eventType == eventNames().beforeloadEvent)
3645 addListenerType(BEFORELOAD_LISTENER);
3646 #if ENABLE(TOUCH_EVENTS)
3647 else if (eventType == eventNames().touchstartEvent
3648 || eventType == eventNames().touchmoveEvent
3649 || eventType == eventNames().touchendEvent
3650 || eventType == eventNames().touchcancelEvent) {
3651 addListenerType(TOUCH_LISTENER);
3652 if (Page* page = this->page())
3653 page->chrome()->client()->needTouchEvents(true);
3656 else if (eventType == eventNames().scrollEvent)
3657 addListenerType(SCROLL_LISTENER);
3660 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3665 HTMLFrameOwnerElement* Document::ownerElement() const
3669 return frame()->ownerElement();
3672 String Document::cookie(ExceptionCode& ec) const
3674 if (page() && !page()->cookieEnabled())
3677 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3678 // INVALID_STATE_ERR exception on getting if the Document has no
3679 // browsing context.
3681 if (!securityOrigin()->canAccessCookies()) {
3686 KURL cookieURL = this->cookieURL();
3687 if (cookieURL.isEmpty())
3690 return cookies(this, cookieURL);
3693 void Document::setCookie(const String& value, ExceptionCode& ec)
3695 if (page() && !page()->cookieEnabled())
3698 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3699 // INVALID_STATE_ERR exception on setting if the Document has no
3700 // browsing context.
3702 if (!securityOrigin()->canAccessCookies()) {
3707 KURL cookieURL = this->cookieURL();
3708 if (cookieURL.isEmpty())
3711 setCookies(this, cookieURL, value);
3714 String Document::referrer() const
3717 return frame()->loader()->referrer();
3721 String Document::domain() const
3723 return securityOrigin()->domain();
3726 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
3728 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3733 // Both NS and IE specify that changing the domain is only allowed when
3734 // the new domain is a suffix of the old domain.
3736 // FIXME: We should add logging indicating why a domain was not allowed.
3738 // If the new domain is the same as the old domain, still call
3739 // securityOrigin()->setDomainForDOM. This will change the
3740 // security check behavior. For example, if a page loaded on port 8000
3741 // assigns its current domain using document.domain, the page will
3742 // allow other pages loaded on different ports in the same domain that
3743 // have also assigned to access this page.
3744 if (equalIgnoringCase(domain(), newDomain)) {
3745 securityOrigin()->setDomainFromDOM(newDomain);
3747 m_frame->script()->updateSecurityOrigin();
3751 int oldLength = domain().length();
3752 int newLength = newDomain.length();
3753 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
3754 if (newLength >= oldLength) {
3759 String test = domain();
3760 // Check that it's a subdomain, not e.g. "ebkit.org"
3761 if (test[oldLength - newLength - 1] != '.') {
3766 // Now test is "webkit.org" from domain()
3767 // and we check that it's the same thing as newDomain
3768 test.remove(0, oldLength - newLength);
3769 if (test != newDomain) {
3774 securityOrigin()->setDomainFromDOM(newDomain);
3776 m_frame->script()->updateSecurityOrigin();
3779 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3780 String Document::lastModified() const
3782 DateComponents date;
3783 bool foundDate = false;
3785 String httpLastModified;
3786 if (DocumentLoader* documentLoader = loader())
3787 httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3788 if (!httpLastModified.isEmpty()) {
3789 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3793 // FIXME: If this document came from the file system, the HTML5
3794 // specificiation tells us to read the last modification date from the file
3797 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3798 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3801 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3806 U16_NEXT(characters, i, length, c)
3807 if (!isValidNameStart(c))
3810 while (i < length) {
3811 U16_NEXT(characters, i, length, c)
3812 if (!isValidNamePart(c))
3819 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
3821 UChar c = characters[0];
3822 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3825 for (unsigned i = 1; i < length; ++i) {
3827 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3834 bool Document::isValidName(const String& name)
3836 unsigned length = name.length();
3840 const UChar* characters = name.characters();
3841 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3844 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3846 unsigned length = qualifiedName.length();
3849 ec = INVALID_CHARACTER_ERR;
3853 bool nameStart = true;
3854 bool sawColon = false;
3857 const UChar* s = qualifiedName.characters();
3858 for (unsigned i = 0; i < length;) {
3860 U16_NEXT(s, i, length, c)
3864 return false; // multiple colons: not allowed
3869 } else if (nameStart) {
3870 if (!isValidNameStart(c)) {
3871 ec = INVALID_CHARACTER_ERR;
3876 if (!isValidNamePart(c)) {
3877 ec = INVALID_CHARACTER_ERR;
3885 localName = qualifiedName;
3887 prefix = qualifiedName.substring(0, colonPos);
3888 if (prefix.isEmpty()) {
3892 localName = qualifiedName.substring(colonPos + 1);
3895 if (localName.isEmpty()) {
3903 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3905 m_decoder = decoder;
3908 KURL Document::completeURL(const String& url) const
3910 // Always return a null URL when passed a null string.
3911 // FIXME: Should we change the KURL constructor to have this behavior?
3912 // See also [CSS]StyleSheet::completeURL(const String&)
3915 const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
3917 return KURL(baseURL, url);
3918 return KURL(baseURL, url, m_decoder->encoding());
3921 void Document::setInPageCache(bool flag)
3923 if (m_inPageCache == flag)
3926 m_inPageCache = flag;
3928 FrameView* v = view();
3930 ASSERT(!m_savedRenderer);
3931 m_savedRenderer = renderer();
3933 v->cacheCurrentScrollPosition();
3934 if (page() && page()->mainFrame() == m_frame)
3935 v->resetScrollbarsAndClearContentsSize();
3937 v->resetScrollbars();
3939 m_styleRecalcTimer.stop();
3941 ASSERT(!renderer() || renderer() == m_savedRenderer);
3942 ASSERT(m_renderArena);
3943 setRenderer(m_savedRenderer);
3944 m_savedRenderer = 0;
3946 if (frame() && frame()->page())
3947 frame()->page()->updateViewportArguments();
3949 if (childNeedsStyleRecalc())
3950 scheduleStyleRecalc();
3954 void Document::documentWillBecomeInactive()
3956 #if USE(ACCELERATED_COMPOSITING)
3958 renderView()->willMoveOffscreen();
3961 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3962 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3963 (*i)->documentWillBecomeInactive();
3966 void Document::documentDidBecomeActive()
3968 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3969 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3970 (*i)->documentDidBecomeActive();
3972 #if USE(ACCELERATED_COMPOSITING)
3974 renderView()->didMoveOnscreen();
3977 if (FrameView* frameView = view())
3978 frameView->setAnimatorsAreActive();
3981 m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
3984 void Document::registerForDocumentActivationCallbacks(Element* e)
3986 m_documentActivationCallbackElements.add(e);
3989 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3991 m_documentActivationCallbackElements.remove(e);
3994 void Document::mediaVolumeDidChange()
3996 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3997 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3998 (*i)->mediaVolumeDidChange();
4001 void Document::registerForMediaVolumeCallbacks(Element* e)
4003 m_mediaVolumeCallbackElements.add(e);
4006 void Document::unregisterForMediaVolumeCallbacks(Element* e)
4008 m_mediaVolumeCallbackElements.remove(e);
4011 void Document::privateBrowsingStateDidChange()
4013 HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
4014 for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
4015 (*it)->privateBrowsingStateDidChange();
4018 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
4020 m_privateBrowsingStateChangedElements.add(e);
4023 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
4025 m_privateBrowsingStateChangedElements.remove(e);
4028 void Document::setShouldCreateRenderers(bool f)
4030 m_createRenderers = f;
4033 bool Document::shouldCreateRenderers()
4035 return m_createRenderers;
4038 // Support for Javascript execCommand, and related methods
4040 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4042 Frame* frame = document->frame();
4043 if (!frame || frame->document() != document)
4044 return Editor::Command();
4046 document->updateStyleIfNeeded();
4048 return frame->editor()->command(commandName,
4049 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4052 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4054 return command(this, commandName, userInterface).execute(value);
4057 bool Document::queryCommandEnabled(const String& commandName)
4059 return command(this, commandName).isEnabled();
4062 bool Document::queryCommandIndeterm(const String& commandName)
4064 return command(this, commandName).state() == MixedTriState;
4067 bool Document::queryCommandState(const String& commandName)
4069 return command(this, commandName).state() == TrueTriState;
4072 bool Document::queryCommandSupported(const String& commandName)
4074 return command(this, commandName).isSupported();
4077 String Document::queryCommandValue(const String& commandName)
4079 return command(this, commandName).value();
4082 KURL Document::openSearchDescriptionURL()
4084 static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
4085 static const char* const openSearchRelation = "search";
4087 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4088 if (!frame() || frame()->tree()->parent())
4091 // FIXME: Why do we need to wait for FrameStateComplete?
4092 if (frame()->loader()->state() != FrameStateComplete)
4098 RefPtr<HTMLCollection> children = head()->children();
4099 for (Node* child = children->firstItem(); child; child = children->nextItem()) {
4100 if (!child->hasTagName(linkTag))
4102 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4103 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4105 if (linkElement->href().isEmpty())
4107 return linkElement->href();
4115 void Document::applyXSLTransform(ProcessingInstruction* pi)
4117 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4118 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
4119 String resultMIMEType;
4121 String resultEncoding;
4122 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4124 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4125 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
4128 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4130 m_transformSource = source;
4135 void Document::setDesignMode(InheritedBool value)
4137 m_designMode = value;
4138 for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
4139 frame->document()->scheduleForcedStyleRecalc();
4142 Document::InheritedBool Document::getDesignMode() const
4144 return m_designMode;
4147 bool Document::inDesignMode() const
4149 for (const Document* d = this; d; d = d->parentDocument()) {
4150 if (d->m_designMode != inherit)
4151 return d->m_designMode;
4156 Document* Document::parentDocument() const
4160 Frame* parent = m_frame->tree()->parent();
4163 return parent->document();
4166 Document* Document::topDocument() const
4168 Document* doc = const_cast<Document *>(this);
4170 while ((element = doc->ownerElement()))
4171 doc = element->document();
4176 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
4178 return createAttributeNS(String(), name, ec, true);
4181 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
4183 String prefix, localName;
4184 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
4187 QualifiedName qName(prefix, localName, namespaceURI);
4188 if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
4193 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
4194 if (!shouldIgnoreNamespaceChecks && qName.localName() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
4199 // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
4200 // documents if we're wrong.
4201 return Attr::create(0, this, Attribute::createMapped(qName, StringImpl::empty()));
4205 const SVGDocumentExtensions* Document::svgExtensions()
4207 return m_svgExtensions.get();
4210 SVGDocumentExtensions* Document::accessSVGExtensions()
4212 if (!m_svgExtensions)
4213 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4214 return m_svgExtensions.get();
4217 bool Document::hasSVGRootNode() const
4219 return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
4223 PassRefPtr<HTMLCollection> Document::images()
4225 return HTMLCollection::create(this, DocImages);
4228 PassRefPtr<HTMLCollection> Document::applets()
4230 return HTMLCollection::create(this, DocApplets);
4233 PassRefPtr<HTMLCollection> Document::embeds()
4235 return HTMLCollection::create(this, DocEmbeds);
4238 PassRefPtr<HTMLCollection> Document::plugins()
4240 // This is an alias for embeds() required for the JS DOM bindings.
4241 return HTMLCollection::create(this, DocEmbeds);
4244 PassRefPtr<HTMLCollection> Document::objects()
4246 return HTMLCollection::create(this, DocObjects);
4249 PassRefPtr<HTMLCollection> Document::scripts()
4251 return HTMLCollection::create(this, DocScripts);
4254 PassRefPtr<HTMLCollection> Document::links()
4256 return HTMLCollection::create(this, DocLinks);
4259 PassRefPtr<HTMLCollection> Document::forms()
4261 return HTMLCollection::create(this, DocForms);
4264 PassRefPtr<HTMLCollection> Document::anchors()
4266 return HTMLCollection::create(this, DocAnchors);
4269 PassRefPtr<HTMLAllCollection> Document::all()
4271 return HTMLAllCollection::create(this);
4274 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
4276 return HTMLNameCollection::create(this, WindowNamedItems, name);
4279 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
4281 return HTMLNameCollection::create(this, DocumentNamedItems, name);
4284 CollectionCache* Document::nameCollectionInfo(CollectionType type, const AtomicString& name)
4286 ASSERT(type >= FirstNamedDocumentCachedType);
4287 unsigned index = type - FirstNamedDocumentCachedType;
4288 ASSERT(index < NumNamedDocumentCachedTypes);
4290 NamedCollectionMap& map = m_nameCollectionInfo[index];
4291 NamedCollectionMap::iterator iter = map.find(name.impl());
4292 if (iter == map.end())
4293 iter = map.add(name.impl(), new CollectionCache).first;
4294 iter->second->checkConsistency();
4295 return iter->second;
4298 void Document::finishedParsing()
4300 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4301 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4303 if (!m_documentTiming.domContentLoadedEventStart)
4304 m_documentTiming.domContentLoadedEventStart = currentTime();
4305 dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
4306 if (!m_documentTiming.domContentLoadedEventEnd)
4307 m_documentTiming.domContentLoadedEventEnd = currentTime();
4309 if (RefPtr<Frame> f = frame()) {
4310 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4311 // resource loads are complete. HTMLObjectElements can start loading their resources from
4312 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4313 // tag and then reach the end of the document without updating styles, we might not have yet
4314 // started the resource load and might fire the window load event too early. To avoid this
4315 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4316 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4317 updateStyleIfNeeded();
4319 f->loader()->finishedParsing();
4321 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4325 Vector<String> Document::formElementsState() const
4327 Vector<String> stateVector;
4328 stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
4329 typedef FormElementListHashSet::const_iterator Iterator;
4330 Iterator end = m_formElementsWithState.end();
4331 for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
4332 Element* elementWithState = *it;
4334 if (!elementWithState->shouldSaveAndRestoreFormControlState())
4336 if (!elementWithState->saveFormControlState(value))
4338 stateVector.append(elementWithState->formControlName().string());
4339 stateVector.append(elementWithState->formControlType().string());
4340 stateVector.append(value);
4345 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
4346 XPathNSResolver* resolver,
4349 if (!m_xpathEvaluator)
4350 m_xpathEvaluator = XPathEvaluator::create();
4351 return m_xpathEvaluator->createExpression(expression, resolver, ec);
4354 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
4356 if (!m_xpathEvaluator)
4357 m_xpathEvaluator = XPathEvaluator::create();
4358 return m_xpathEvaluator->createNSResolver(nodeResolver);
4361 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
4363 XPathNSResolver* resolver,
4364 unsigned short type,
4365 XPathResult* result,
4368 if (!m_xpathEvaluator)
4369 m_xpathEvaluator = XPathEvaluator::create();
4370 return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
4373 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
4375 // Walk the state vector backwards so that the value to use for each
4376 // name/type pair first is the one at the end of each individual vector
4377 // in the FormElementStateMap. We're using them like stacks.
4378 typedef FormElementStateMap::iterator Iterator;
4379 m_formElementsWithState.clear();
4380 for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
4381 AtomicString a = stateVector[i - 3];
4382 AtomicString b = stateVector[i - 2];
4383 const String& c = stateVector[i - 1];
4384 FormElementKey key(a.impl(), b.impl());
4385 Iterator it = m_stateForNewFormElements.find(key);
4386 if (it != m_stateForNewFormElements.end())
4387 it->second.append(c);
4389 Vector<String> v(1);
4391 m_stateForNewFormElements.set(key, v);
4396 bool Document::hasStateForNewFormElements() const
4398 return !m_stateForNewFormElements.isEmpty();
4401 bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
4403 typedef FormElementStateMap::iterator Iterator;
4404 Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
4405 if (it == m_stateForNewFormElements.end())
4407 ASSERT(it->second.size());
4408 state = it->second.last();
4409 if (it->second.size() > 1)
4410 it->second.removeLast();
4412 m_stateForNewFormElements.remove(it);
4416 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
4417 : m_name(name), m_type(type)
4422 FormElementKey::~FormElementKey()
4427 FormElementKey::FormElementKey(const FormElementKey& other)
4428 : m_name(other.name()), m_type(other.type())
4433 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
4437 m_name = other.name();
4438 m_type = other.type();
4442 void FormElementKey::ref() const
4450 void FormElementKey::deref() const
4458 unsigned FormElementKeyHash::hash(const FormElementKey& key)
4460 return StringHasher::hashMemory<sizeof(FormElementKey)>(&key);
4463 const Vector<IconURL>& Document::iconURLs() const
4468 void Document::addIconURL(const String& url, const String& mimeType, const String& sizes, IconType iconType)
4473 // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "mimeType"
4474 IconURL newURL(KURL(ParsedURLString, url), sizes, mimeType, iconType);
4475 m_iconURLs.append(newURL);
4477 if (Frame* f = frame()) {
4478 IconURL iconURL = f->loader()->icon()->iconURL(iconType);
4479 if (iconURL == newURL)
4480 f->loader()->didChangeIcons(iconType);
4484 void Document::registerFormElementWithFormAttribute(FormAssociatedElement* element)
4486 ASSERT(toHTMLElement(element)->fastHasAttribute(formAttr));
4487 m_formElementsWithFormAttribute.add(element);
4490 void Document::unregisterFormElementWithFormAttribute(FormAssociatedElement* element)
4492 m_formElementsWithFormAttribute.remove(element);
4495 void Document::resetFormElementsOwner()
4497 typedef FormAssociatedElementListHashSet::iterator Iterator;
4498 Iterator end = m_formElementsWithFormAttribute.end();
4499 for (Iterator it = m_formElementsWithFormAttribute.begin(); it != end; ++it)
4500 (*it)->resetFormOwner();
4503 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4505 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4508 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4509 m_frame->selection()->updateSecureKeyboardEntryIfActive();
4512 bool Document::useSecureKeyboardEntryWhenActive() const
4514 return m_useSecureKeyboardEntryWhenActive;
4517 void Document::initSecurityContext()
4519 if (haveInitializedSecurityOrigin()) {
4520 ASSERT(securityOrigin());
4525 // No source for a security context.
4526 // This can occur via document.implementation.createDocument().
4527 m_cookieURL = KURL(ParsedURLString, "");
4528 setSecurityOrigin(SecurityOrigin::createUnique());
4529 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4533 // In the common case, create the security context from the currently
4534 // loading URL with a fresh content security policy.
4535 m_cookieURL = m_url;
4536 enforceSandboxFlags(m_frame->loader()->effectiveSandboxFlags());
4537 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4538 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4540 if (SecurityPolicy::allowSubstituteDataAccessToLocal()) {
4541 // If this document was loaded with substituteData, then the document can
4542 // load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
4543 // and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
4546 DocumentLoader* documentLoader = loader();
4547 if (documentLoader && documentLoader->substituteData().isValid())
4548 securityOrigin()->grantLoadLocalResources();
4551 if (Settings* settings = this->settings()) {
4552 if (!settings->isWebSecurityEnabled()) {
4553 // Web security is turned off. We should let this document access every
4554 // other document. This is used primary by testing harnesses for web
4556 securityOrigin()->grantUniversalAccess();
4558 } else if (settings->allowUniversalAccessFromFileURLs() && securityOrigin()->isLocal()) {
4559 // Some clients want file:// URLs to have universal access, but that
4560 // setting is dangerous for other clients.
4561 securityOrigin()->grantUniversalAccess();
4562 } else if (!settings->allowFileAccessFromFileURLs() && securityOrigin()->isLocal()) {
4563 // Some clients want file:// URLs to have even tighter restrictions by
4564 // default, and not be able to access other local files.
4565 securityOrigin()->enforceFilePathSeparation();
4569 if (!shouldInheritSecurityOriginFromOwner(m_url))
4572 // If we do not obtain a meaningful origin from the URL, then we try to
4573 // find one via the frame hierarchy.
4575 Frame* ownerFrame = m_frame->tree()->parent();
4577 ownerFrame = m_frame->loader()->opener();
4580 didFailToInitializeSecurityOrigin();
4584 m_cookieURL = ownerFrame->document()->cookieURL();
4585 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4586 // https://bugs.webkit.org/show_bug.cgi?id=15313
4587 setSecurityOrigin(ownerFrame->document()->securityOrigin());
4588 setContentSecurityPolicy(ownerFrame->document()->contentSecurityPolicy());
4591 void Document::setSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4593 SecurityContext::setSecurityOrigin(origin);
4596 #if ENABLE(SQL_DATABASE)
4598 bool Document::allowDatabaseAccess() const
4600 if (!page() || (page()->settings()->privateBrowsingEnabled() && !SchemeRegistry::allowsDatabaseAccessInPrivateBrowsing(securityOrigin()->protocol())))
4605 void Document::databaseExceededQuota(const String& name)
4607 Page* currentPage = page();
4609 currentPage->chrome()->client()->exceededDatabaseQuota(document()->frame(), name);
4614 bool Document::isContextThread() const
4616 return isMainThread();
4619 void Document::updateURLForPushOrReplaceState(const KURL& url)
4626 f->loader()->setOutgoingReferrer(url);
4628 if (DocumentLoader* documentLoader = loader())
4629 documentLoader->replaceRequestURLForSameDocumentNavigation(url);
4632 void Document::statePopped(SerializedScriptValue* stateObject)
4637 // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
4638 // defer firing of popstate until we're in the complete state.
4639 if (m_readyState == Complete)
4640 enqueuePopstateEvent(stateObject);
4642 m_pendingStateObject = stateObject;
4645 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4647 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4648 if (!m_updateFocusAppearanceTimer.isActive())
4649 m_updateFocusAppearanceTimer.startOneShot(0);
4652 void Document::cancelFocusAppearanceUpdate()
4654 m_updateFocusAppearanceTimer.stop();
4657 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4659 Node* node = focusedNode();
4662 if (!node->isElementNode())
4667 Element* element = static_cast<Element*>(node);
4668 if (element->isFocusable())
4669 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4672 // FF method for accessing the selection added for compatibility.
4673 DOMSelection* Document::getSelection() const
4675 return frame() ? frame()->domWindow()->getSelection() : 0;
4678 void Document::attachRange(Range* range)
4680 ASSERT(!m_ranges.contains(range));
4681 m_ranges.add(range);
4684 void Document::detachRange(Range* range)
4686 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4687 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4688 m_ranges.remove(range);
4691 CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
4693 HTMLCanvasElement* result = getCSSCanvasElement(name);
4696 result->setSize(IntSize(width, height));
4697 return result->getContext(type);
4700 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
4702 RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
4704 result = HTMLCanvasElement::create(this);
4705 m_cssCanvasElements.set(name, result);
4707 return result.get();
4710 void Document::initDNSPrefetch()
4712 Settings* settings = this->settings();
4714 m_haveExplicitlyDisabledDNSPrefetch = false;
4715 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4717 // Inherit DNS prefetch opt-out from parent frame
4718 if (Document* parent = parentDocument()) {
4719 if (!parent->isDNSPrefetchEnabled())
4720 m_isDNSPrefetchEnabled = false;
4724 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4726 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4727 m_isDNSPrefetchEnabled = true;
4731 m_isDNSPrefetchEnabled = false;
4732 m_haveExplicitlyDisabledDNSPrefetch = true;
4735 void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
4737 if (!isContextThread()) {
4738 postTask(AddConsoleMessageTask::create(source, type, level, message));
4742 if (DOMWindow* window = domWindow())
4743 window->console()->addMessage(source, type, level, message, lineNumber, sourceURL, callStack);
4746 struct PerformTaskContext {
4747 WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
4749 PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
4750 : documentReference(documentReference)
4755 RefPtr<DocumentWeakReference> documentReference;
4756 OwnPtr<ScriptExecutionContext::Task> task;
4759 static void performTask(void* ctx)
4761 ASSERT(isMainThread());
4763 PerformTaskContext* context = reinterpret_cast<PerformTaskContext*>(ctx);
4766 if (Document* document = context->documentReference->document())
4767 context->task->performTask(document);
4772 void Document::postTask(PassOwnPtr<Task> task)
4774 callOnMainThread(performTask, new PerformTaskContext(m_weakReference, task));
4777 void Document::suspendScriptedAnimationControllerCallbacks()
4779 #if ENABLE(REQUEST_ANIMATION_FRAME)
4780 if (m_scriptedAnimationController)
4781 m_scriptedAnimationController->suspend();
4785 void Document::resumeScriptedAnimationControllerCallbacks()
4787 #if ENABLE(REQUEST_ANIMATION_FRAME)
4788 if (m_scriptedAnimationController)
4789 m_scriptedAnimationController->resume();
4793 void Document::windowScreenDidChange(PlatformDisplayID displayID)
4795 #if ENABLE(REQUEST_ANIMATION_FRAME)
4796 if (m_scriptedAnimationController)
4797 m_scriptedAnimationController->windowScreenDidChange(displayID);
4802 String Document::displayStringModifiedByEncoding(const String& str) const
4805 return m_decoder->encoding().displayString(str.impl());
4809 PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
4812 return m_decoder->encoding().displayString(str);
4816 void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
4819 m_decoder->encoding().displayBuffer(buffer, len);
4822 void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
4824 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
4825 dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
4828 void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
4830 enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
4833 void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
4835 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
4836 dispatchWindowEvent(PopStateEvent::create(stateObject));
4839 void Document::addMediaCanStartListener(MediaCanStartListener* listener)
4841 ASSERT(!m_mediaCanStartListeners.contains(listener));
4842 m_mediaCanStartListeners.add(listener);
4845 void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
4847 ASSERT(m_mediaCanStartListeners.contains(listener));
4848 m_mediaCanStartListeners.remove(listener);
4851 MediaCanStartListener* Document::takeAnyMediaCanStartListener()
4853 HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
4854 if (slot == m_mediaCanStartListeners.end())
4856 MediaCanStartListener* listener = *slot;
4857 m_mediaCanStartListeners.remove(slot);
4861 #if ENABLE(FULLSCREEN_API)
4862 bool Document::fullScreenIsAllowedForElement(Element* element) const
4865 while (HTMLFrameOwnerElement* ownerElement = element->document()->ownerElement()) {
4866 if (!ownerElement->isFrameElementBase())
4869 if (!static_cast<HTMLFrameElementBase*>(ownerElement)->allowFullScreen())
4871 element = ownerElement;
4876 void Document::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
4878 if (!page() || !page()->settings()->fullScreenEnabled())
4882 element = documentElement();
4884 if (checkType == EnforceIFrameAllowFulScreenRequirement && !fullScreenIsAllowedForElement(element))
4887 if (!ScriptController::processingUserGesture())
4890 if (!page()->chrome()->client()->supportsFullScreenForElement(element, flags & Element::ALLOW_KEYBOARD_INPUT))
4893 m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
4894 page()->chrome()->client()->enterFullScreenForElement(element);
4897 void Document::webkitCancelFullScreen()
4899 if (!page() || !m_fullScreenElement)
4902 page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
4905 void Document::webkitWillEnterFullScreenForElement(Element* element)
4908 ASSERT(page() && page()->settings()->fullScreenEnabled());
4910 if (m_fullScreenRenderer)
4911 m_fullScreenRenderer->unwrapRenderer();
4913 m_fullScreenElement = element;
4915 // Create a placeholder block for a the full-screen element, to keep the page from reflowing
4916 // when the element is removed from the normal flow. Only do this for a RenderBox, as only
4917 // a box will have a frameRect. The placeholder will be created in setFullScreenRenderer()
4919 RenderObject* renderer = m_fullScreenElement->renderer();
4920 bool shouldCreatePlaceholder = renderer && renderer->isBox();
4921 if (shouldCreatePlaceholder) {
4922 m_savedPlaceholderFrameRect = toRenderBox(renderer)->frameRect();
4923 m_savedPlaceholderRenderStyle = RenderStyle::clone(renderer->style());
4926 if (m_fullScreenElement != documentElement())
4927 RenderFullScreen::wrapRenderer(renderer, this);
4929 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
4933 if (m_fullScreenRenderer) {
4934 setAnimatingFullScreen(true);
4935 #if USE(ACCELERATED_COMPOSITING)
4936 view()->updateCompositingLayers();
4937 if (m_fullScreenRenderer->layer() && m_fullScreenRenderer->layer()->isComposited())
4938 page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
4943 void Document::webkitDidEnterFullScreenForElement(Element*)
4945 m_fullScreenElement->didBecomeFullscreenElement();
4947 if (m_fullScreenRenderer) {
4948 setAnimatingFullScreen(false);
4949 #if USE(ACCELERATED_COMPOSITING)
4950 view()->updateCompositingLayers();
4951 page()->chrome()->client()->setRootFullScreenLayer(0);
4954 m_fullScreenChangeEventTargetQueue.append(m_fullScreenElement);
4955 m_fullScreenChangeDelayTimer.startOneShot(0);
4958 void Document::webkitWillExitFullScreenForElement(Element*)
4960 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
4962 m_fullScreenElement->willStopBeingFullscreenElement();
4964 if (m_fullScreenRenderer) {
4965 setAnimatingFullScreen(true);
4966 #if USE(ACCELERATED_COMPOSITING)
4967 view()->updateCompositingLayers();
4968 if (m_fullScreenRenderer->layer() && m_fullScreenRenderer->layer()->isComposited())
4969 page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
4974 void Document::webkitDidExitFullScreenForElement(Element*)
4976 m_areKeysEnabledInFullScreen = false;
4977 setAnimatingFullScreen(false);
4979 if (m_fullScreenRenderer)
4980 m_fullScreenRenderer->unwrapRenderer();
4982 m_fullScreenChangeEventTargetQueue.append(m_fullScreenElement.release());
4983 #if USE(ACCELERATED_COMPOSITING)
4984 page()->chrome()->client()->setRootFullScreenLayer(0);
4986 scheduleForcedStyleRecalc();
4988 m_fullScreenChangeDelayTimer.startOneShot(0);
4991 void Document::setFullScreenRenderer(RenderFullScreen* renderer)
4993 if (renderer == m_fullScreenRenderer)
4996 if (renderer && m_savedPlaceholderRenderStyle)
4997 renderer->createPlaceholder(m_savedPlaceholderRenderStyle.release(), m_savedPlaceholderFrameRect);
4998 else if (renderer && m_fullScreenRenderer && m_fullScreenRenderer->placeholder()) {
4999 RenderBlock* placeholder = m_fullScreenRenderer->placeholder();
5000 renderer->createPlaceholder(RenderStyle::clone(placeholder->style()), placeholder->frameRect());
5003 if (m_fullScreenRenderer)
5004 m_fullScreenRenderer->destroy();
5005 ASSERT(!m_fullScreenRenderer);
5007 m_fullScreenRenderer = renderer;
5009 // This notification can come in after the page has been destroyed.
5011 page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
5014 void Document::fullScreenRendererDestroyed()
5016 m_fullScreenRenderer = 0;
5019 page()->chrome()->client()->fullScreenRendererChanged(0);
5022 void Document::setFullScreenRendererSize(const IntSize& size)
5024 ASSERT(m_fullScreenRenderer);
5025 if (!m_fullScreenRenderer)
5028 if (m_fullScreenRenderer) {
5029 RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5030 newStyle->setWidth(Length(size.width(), WebCore::Fixed));
5031 newStyle->setHeight(Length(size.height(), WebCore::Fixed));
5032 newStyle->setTop(Length(0, WebCore::Fixed));
5033 newStyle->setLeft(Length(0, WebCore::Fixed));
5034 m_fullScreenRenderer->setStyle(newStyle);
5039 void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
5041 if (!m_fullScreenRenderer)
5044 RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5045 newStyle->setBackgroundColor(backgroundColor);
5046 m_fullScreenRenderer->setStyle(newStyle);
5049 void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
5051 while (!m_fullScreenChangeEventTargetQueue.isEmpty()) {
5052 RefPtr<Element> element = m_fullScreenChangeEventTargetQueue.takeFirst();
5054 element = documentElement();
5056 // If the element was removed from our tree, also message the documentElement.
5057 if (!contains(element.get()))
5058 m_fullScreenChangeEventTargetQueue.append(documentElement());
5060 element->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
5064 void Document::fullScreenElementRemoved()
5066 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
5067 webkitCancelFullScreen();
5070 void Document::removeFullScreenElementOfSubtree(Node* node, bool amongChildrenOnly)
5072 if (!m_fullScreenElement)
5075 bool elementInSubtree = false;
5076 if (amongChildrenOnly)
5077 elementInSubtree = m_fullScreenElement->isDescendantOf(node);
5079 elementInSubtree = (m_fullScreenElement == node) || m_fullScreenElement->isDescendantOf(node);
5081 if (elementInSubtree)
5082 fullScreenElementRemoved();
5085 bool Document::isAnimatingFullScreen() const
5087 return m_isAnimatingFullScreen;
5090 void Document::setAnimatingFullScreen(bool flag)
5092 if (m_isAnimatingFullScreen == flag)
5094 m_isAnimatingFullScreen = flag;
5096 if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(this)) {
5097 m_fullScreenElement->setNeedsStyleRecalc();
5098 scheduleForcedStyleRecalc();
5101 #if USE(ACCELERATED_COMPOSITING)
5102 if (m_fullScreenRenderer && m_fullScreenRenderer->layer()) {
5103 m_fullScreenRenderer->layer()->contentChanged(RenderLayer::FullScreenChanged);
5104 // Clearing the layer's backing will force the compositor to reparent
5105 // the layer the next time layers are synchronized.
5106 m_fullScreenRenderer->layer()->clearBacking();
5112 void Document::decrementLoadEventDelayCount()
5114 ASSERT(m_loadEventDelayCount);
5115 --m_loadEventDelayCount;
5117 if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
5118 m_loadEventDelayTimer.startOneShot(0);
5121 void Document::loadEventDelayTimerFired(Timer<Document>*)
5124 frame()->loader()->checkCompleted();
5127 #if ENABLE(REQUEST_ANIMATION_FRAME)
5128 int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* animationElement)
5130 if (!m_scriptedAnimationController)
5131 m_scriptedAnimationController = ScriptedAnimationController::create(this, page()->displayID());
5133 return m_scriptedAnimationController->registerCallback(callback, animationElement);
5136 void Document::webkitCancelRequestAnimationFrame(int id)
5138 if (!m_scriptedAnimationController)
5140 m_scriptedAnimationController->cancelCallback(id);
5143 void Document::serviceScriptedAnimations(DOMTimeStamp time)
5145 if (!m_scriptedAnimationController)
5147 m_scriptedAnimationController->serviceScriptedAnimations(time);
5151 #if ENABLE(TOUCH_EVENTS)
5152 PassRefPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force, ExceptionCode&) const
5154 // FIXME: It's not clear from the documentation at
5155 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5156 // when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
5157 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5158 // Ditto for the createTouchList method below.
5159 Frame* frame = window ? window->frame() : this->frame();
5160 return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
5163 PassRefPtr<TouchList> Document::createTouchList(ExceptionCode&) const
5165 return TouchList::create();
5169 void Document::didAddWheelEventHandler()
5171 ++m_wheelEventHandlerCount;
5172 Frame* mainFrame = page() ? page()->mainFrame() : 0;
5174 mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
5177 void Document::didRemoveWheelEventHandler()
5179 ASSERT(m_wheelEventHandlerCount > 0);
5180 --m_wheelEventHandlerCount;
5181 Frame* mainFrame = page() ? page()->mainFrame() : 0;
5183 mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
5186 bool Document::visualUpdatesAllowed() const
5189 || !settings()->suppressIncrementalRendering()
5190 || loadEventFinished();
5193 DocumentLoader* Document::loader() const
5198 DocumentLoader* loader = m_frame->loader()->documentLoader();
5202 if (m_frame->document() != this)
5208 #if ENABLE(MICRODATA)
5209 PassRefPtr<NodeList> Document::getItems(const String& typeNames)
5211 NodeRareData* data = ensureRareData();
5212 if (!data->nodeLists()) {
5213 data->setNodeLists(NodeListsNodeData::create());
5214 treeScope()->addNodeListCache();
5217 // Since documet.getItem() is allowed for microdata, typeNames will be null string.
5218 // In this case we need to create an unique string identifier to map such request in the cache.
5219 String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
5221 pair<NodeListsNodeData::MicroDataItemListCache::iterator, bool> result = data->nodeLists()->m_microDataItemListCache.add(localTypeNames, 0);
5223 return PassRefPtr<NodeList>(result.first->second);
5225 RefPtr<MicroDataItemList> list = MicroDataItemList::create(this, typeNames);
5226 result.first->second = list.get();
5227 return list.release();
5230 void Document::removeCachedMicroDataItemList(MicroDataItemList* list, const String& typeNames)
5233 ASSERT(rareData()->nodeLists());
5234 ASSERT_UNUSED(list, list->hasOwnCaches());
5236 NodeListsNodeData* data = rareData()->nodeLists();
5238 String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
5239 ASSERT_UNUSED(list, list == data->m_microDataItemListCache.get(localTypeNames));
5240 data->m_microDataItemListCache.remove(localTypeNames);
5244 } // namespace WebCore