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 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008 David Levin (levin@chromium.org)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
29 #include "AnimationController.h"
30 #include "AXObjectCache.h"
31 #include "CDATASection.h"
32 #include "CSSHelper.h"
33 #include "CSSStyleSelector.h"
34 #include "CSSStyleSheet.h"
35 #include "CSSValueKeywords.h"
37 #include "CachedCSSStyleSheet.h"
40 #include "CookieJar.h"
41 #include "DOMImplementation.h"
42 #include "DOMWindow.h"
43 #include "DocLoader.h"
44 #include "DocumentFragment.h"
45 #include "DocumentLoader.h"
46 #include "DocumentType.h"
47 #include "EditingText.h"
49 #include "EntityReference.h"
51 #include "EventHandler.h"
52 #include "EventListener.h"
53 #include "EventNames.h"
54 #include "ExceptionCode.h"
55 #include "FocusController.h"
57 #include "FrameLoader.h"
58 #include "FrameTree.h"
59 #include "FrameView.h"
60 #include "HTMLAnchorElement.h"
61 #include "HTMLBodyElement.h"
62 #include "HTMLCanvasElement.h"
63 #include "HTMLDocument.h"
64 #include "HTMLElementFactory.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "HTMLHeadElement.h"
67 #include "HTMLInputElement.h"
68 #include "HTMLLinkElement.h"
69 #include "HTMLMapElement.h"
70 #include "HTMLNameCollection.h"
71 #include "HTMLNames.h"
72 #include "HTMLStyleElement.h"
73 #include "HTMLTitleElement.h"
74 #include "HTTPParsers.h"
75 #include "HistoryItem.h"
76 #include "HitTestRequest.h"
77 #include "HitTestResult.h"
78 #include "ImageLoader.h"
79 #include "InspectorController.h"
80 #include "KeyboardEvent.h"
82 #include "MessageEvent.h"
83 #include "MouseEvent.h"
84 #include "MouseEventWithHitTestResults.h"
85 #include "MutationEvent.h"
86 #include "NameNodeList.h"
87 #include "NodeFilter.h"
88 #include "NodeIterator.h"
89 #include "NodeWithIndex.h"
90 #include "OverflowEvent.h"
92 #include "PlatformKeyboardEvent.h"
93 #include "ProcessingInstruction.h"
94 #include "ProgressEvent.h"
95 #include "RegisteredEventListener.h"
96 #include "RenderArena.h"
97 #include "RenderTextControl.h"
98 #include "RenderView.h"
99 #include "RenderWidget.h"
100 #include "ScriptController.h"
101 #include "SecurityOrigin.h"
102 #include "SegmentedString.h"
103 #include "SelectionController.h"
104 #include "Settings.h"
105 #include "StyleSheetList.h"
106 #include "TextEvent.h"
107 #include "TextIterator.h"
108 #include "TextResourceDecoder.h"
109 #include "TreeWalker.h"
112 #include "WebKitAnimationEvent.h"
113 #include "WebKitTransitionEvent.h"
114 #include "WheelEvent.h"
115 #include "XMLHttpRequest.h"
116 #include "XMLNames.h"
117 #include "XMLTokenizer.h"
118 #include "JSDOMBinding.h"
119 #include "ScriptController.h"
120 #include <wtf/CurrentTime.h>
121 #include <wtf/HashFunctions.h>
122 #include <wtf/MainThread.h>
123 #include <wtf/StdLibExtras.h>
124 #include <wtf/PassRefPtr.h>
127 #include "Database.h"
128 #include "DatabaseThread.h"
131 #if ENABLE(DOM_STORAGE)
132 #include "StorageEvent.h"
136 #include "XPathEvaluator.h"
137 #include "XPathExpression.h"
138 #include "XPathNSResolver.h"
139 #include "XPathResult.h"
143 #include "XSLTProcessor.h"
147 #include "XBLBindingManager.h"
151 #include "SVGDocumentExtensions.h"
152 #include "SVGElementFactory.h"
153 #include "SVGZoomEvent.h"
154 #include "SVGStyleElement.h"
158 #include "WMLDocument.h"
159 #include "WMLElement.h"
160 #include "WMLElementFactory.h"
161 #include "WMLNames.h"
166 using namespace Unicode;
170 using namespace HTMLNames;
172 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
174 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
175 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
177 static const int cLayoutScheduleThreshold = 250;
179 // Use 1 to represent the document's default form.
180 static HTMLFormElement* const defaultForm = reinterpret_cast<HTMLFormElement*>(1);
182 // DOM Level 2 says (letters added):
184 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
185 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
186 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
187 // 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.
188 // 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.
189 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
190 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
191 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
192 // i) Characters ':' and '_' are allowed as name-start characters.
193 // j) Characters '-' and '.' are allowed as name characters.
195 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
197 static inline bool isValidNameStart(UChar32 c)
200 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
204 if (c == ':' || c == '_')
207 // rules (a) and (f) above
208 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
209 if (!(Unicode::category(c) & nameStartMask))
213 if (c >= 0xF900 && c < 0xFFFE)
217 DecompositionType decompType = decompositionType(c);
218 if (decompType == DecompositionFont || decompType == DecompositionCompat)
224 static inline bool isValidNamePart(UChar32 c)
226 // rules (a), (e), and (i) above
227 if (isValidNameStart(c))
230 // rules (g) and (h) above
231 if (c == 0x00B7 || c == 0x0387)
235 if (c == '-' || c == '.')
238 // rules (b) and (f) above
239 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
240 if (!(Unicode::category(c) & otherNamePartMask))
244 if (c >= 0xF900 && c < 0xFFFE)
248 DecompositionType decompType = decompositionType(c);
249 if (decompType == DecompositionFont || decompType == DecompositionCompat)
255 static Widget* widgetForNode(Node* focusedNode)
259 RenderObject* renderer = focusedNode->renderer();
260 if (!renderer || !renderer->isWidget())
262 return static_cast<RenderWidget*>(renderer)->widget();
265 static bool acceptsEditingFocus(Node *node)
268 ASSERT(node->isContentEditable());
270 Node *root = node->rootEditableElement();
271 Frame* frame = node->document()->frame();
275 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
278 static bool disableRangeMutation(Page* page)
281 // Disable Range mutation on document modifications in Tiger and Leopard Mail
282 // See <rdar://problem/5865171>
283 return page && (page->settings()->needsLeopardMailQuirks() || page->settings()->needsTigerMailQuirks());
289 static HashSet<Document*>* changedDocuments = 0;
291 Document::Document(Frame* frame, bool isXHTML)
293 , m_domtree_version(0)
294 , m_styleSheets(StyleSheetList::create(this))
295 , m_frameElementsShouldIgnoreScrolling(false)
297 , m_titleSetExplicitly(false)
298 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
300 , m_transformSource(0)
302 , m_xmlVersion("1.0")
303 , m_xmlStandalone(false)
305 , m_bindingManager(new XBLBindingManager(this))
309 , m_designMode(inherit)
310 , m_selfOnlyRefCount(0)
314 #if ENABLE(DASHBOARD_SUPPORT)
315 , m_hasDashboardRegions(false)
316 , m_dashboardRegionsDirty(false)
318 , m_accessKeyMapValid(false)
319 , m_createRenderers(true)
320 , m_inPageCache(false)
321 , m_useSecureKeyboardEntryWhenActive(false)
323 , m_numNodeListCaches(0)
325 , m_hasOpenDatabases(false)
327 , m_usingGeolocation(false)
329 m_document.resetSkippingRef(this);
333 m_ignoreAutofocus = false;
340 m_docLoader = new DocLoader(this);
342 visuallyOrdered = false;
344 m_docChanged = false;
346 m_wellFormed = false;
348 setParseMode(Strict);
350 m_textColor = Color::black;
353 m_inStyleRecalc = false;
354 m_closeAfterStyleRecalc = false;
355 m_usesDescendantRules = false;
356 m_usesSiblingRules = false;
357 m_usesFirstLineRules = false;
358 m_usesFirstLetterRules = false;
359 m_usesBeforeAfterRules = false;
360 m_gotoAnchorNeededAfterStylesheetsLoad = false;
363 m_didCalculateStyleSelector = false;
364 m_pendingStylesheets = 0;
365 m_ignorePendingStylesheets = false;
366 m_hasNodesWithPlaceholderStyle = false;
367 m_pendingSheetLayout = NoLayoutWithPendingSheets;
372 resetVisitedLinkColor();
373 resetActiveLinkColor();
375 m_processingLoadEvent = false;
376 m_startTime = currentTime();
377 m_overMinimumLayoutThreshold = false;
379 initSecurityContext();
382 static int docID = 0;
386 void Document::removedLastRef()
388 ASSERT(!m_deletionHasBegun);
389 if (m_selfOnlyRefCount) {
390 // If removing a child removes the last self-only ref, we don't
391 // want the document to be destructed until after
392 // removeAllChildren returns, so we guard ourselves with an
393 // extra self-only ref.
395 DocPtr<Document> guard(this);
397 // We must make sure not to be retaining any of our children through
398 // these extra pointers or we will create a reference cycle.
404 m_documentElement = 0;
408 deleteAllValues(m_markers);
414 m_cssCanvasElements.clear();
417 m_inRemovedLastRefFunction = false;
421 m_deletionHasBegun = true;
427 Document::~Document()
430 ASSERT(!m_inPageCache);
431 ASSERT(!m_savedRenderer);
432 ASSERT(m_ranges.isEmpty());
434 removeAllEventListeners();
436 forgetAllDOMNodesForDocument(this);
438 if (m_docChanged && changedDocuments)
439 changedDocuments->remove(this);
441 m_document.resetSkippingRef(0);
442 delete m_styleSelector;
446 delete m_renderArena;
451 xmlFreeDoc((xmlDocPtr)m_transformSource);
455 delete m_bindingManager;
458 deleteAllValues(m_markers);
460 clearAXObjectCache();
464 unsigned count = sizeof(m_nameCollectionInfo) / sizeof(m_nameCollectionInfo[0]);
465 for (unsigned i = 0; i < count; i++)
466 deleteAllValues(m_nameCollectionInfo[i]);
469 if (m_databaseThread) {
470 ASSERT(m_databaseThread->terminationRequested());
471 m_databaseThread = 0;
476 m_styleSheets->documentDestroyed();
481 void Document::resetLinkColor()
483 m_linkColor = Color(0, 0, 238);
486 void Document::resetVisitedLinkColor()
488 m_visitedLinkColor = Color(85, 26, 139);
491 void Document::resetActiveLinkColor()
493 m_activeLinkColor.setNamedColor("red");
496 void Document::setDocType(PassRefPtr<DocumentType> docType)
498 // This should never be called more than once.
499 // Note: This is not a public DOM method and can only be called by the parser.
500 ASSERT(!m_docType || !docType);
501 if (m_docType && docType)
505 m_docType->setDocument(this);
506 determineParseMode();
509 DOMImplementation* Document::implementation() const
511 if (!m_implementation)
512 m_implementation = DOMImplementation::create();
513 return m_implementation.get();
516 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
518 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
520 // Invalidate the document element we have cached in case it was replaced.
521 m_documentElement = 0;
524 void Document::cacheDocumentElement() const
526 ASSERT(!m_documentElement);
527 Node* n = firstChild();
528 while (n && !n->isElementNode())
529 n = n->nextSibling();
530 m_documentElement = static_cast<Element*>(n);
533 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
535 if (!isValidName(name)) {
536 ec = INVALID_CHARACTER_ERR;
541 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
543 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
546 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
548 return new DocumentFragment(document());
551 PassRefPtr<Text> Document::createTextNode(const String& data)
553 return new Text(this, data);
556 PassRefPtr<Comment> Document::createComment(const String& data)
558 return new Comment(this, data);
561 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
563 if (isHTMLDocument()) {
564 ec = NOT_SUPPORTED_ERR;
567 return new CDATASection(this, data);
570 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
572 if (!isValidName(target)) {
573 ec = INVALID_CHARACTER_ERR;
576 if (isHTMLDocument()) {
577 ec = NOT_SUPPORTED_ERR;
580 return new ProcessingInstruction(this, target, data);
583 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
585 if (!isValidName(name)) {
586 ec = INVALID_CHARACTER_ERR;
589 if (isHTMLDocument()) {
590 ec = NOT_SUPPORTED_ERR;
593 return new EntityReference(this, name);
596 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
598 return new EditingText(this, text);
601 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
603 return CSSMutableStyleDeclaration::create();
606 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
611 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
612 || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
615 ec = NOT_SUPPORTED_ERR;
619 switch (importedNode->nodeType()) {
621 return createTextNode(importedNode->nodeValue());
622 case CDATA_SECTION_NODE:
623 return createCDATASection(importedNode->nodeValue(), ec);
624 case ENTITY_REFERENCE_NODE:
625 return createEntityReference(importedNode->nodeName(), ec);
626 case PROCESSING_INSTRUCTION_NODE:
627 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
629 return createComment(importedNode->nodeValue());
631 Element* oldElement = static_cast<Element*>(importedNode);
632 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
637 NamedAttrMap* attrs = oldElement->attributes(true);
639 unsigned length = attrs->length();
640 for (unsigned i = 0; i < length; i++) {
641 Attribute* attr = attrs->attributeItem(i);
642 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
648 newElement->copyNonAttributeProperties(oldElement);
651 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
652 RefPtr<Node> newChild = importNode(oldChild, true, ec);
655 newElement->appendChild(newChild.release(), ec);
661 return newElement.release();
663 case ATTRIBUTE_NODE: {
664 RefPtr<Attr> newAttr = new Attr(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
665 newAttr->createTextChild();
666 return newAttr.release();
668 case DOCUMENT_FRAGMENT_NODE: {
669 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
670 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
672 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
673 RefPtr<Node> newChild = importNode(oldChild, true, ec);
676 newFragment->appendChild(newChild.release(), ec);
682 return newFragment.release();
686 // 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.
687 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
689 case DOCUMENT_TYPE_NODE:
690 case XPATH_NAMESPACE_NODE:
694 ec = NOT_SUPPORTED_ERR;
699 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
702 ec = NOT_SUPPORTED_ERR;
706 if (source->isReadOnlyNode()) {
707 ec = NO_MODIFICATION_ALLOWED_ERR;
711 switch (source->nodeType()) {
715 case DOCUMENT_TYPE_NODE:
716 case XPATH_NAMESPACE_NODE:
717 ec = NOT_SUPPORTED_ERR;
719 case ATTRIBUTE_NODE: {
720 Attr* attr = static_cast<Attr*>(source.get());
721 if (attr->ownerElement())
722 attr->ownerElement()->removeAttributeNode(attr, ec);
723 attr->setSpecified(true);
727 if (source->parentNode())
728 source->parentNode()->removeChild(source.get(), ec);
731 for (Node* node = source.get(); node; node = node->traverseNextNode(source.get()))
732 node->setDocument(this);
737 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
739 DEFINE_STATIC_LOCAL(const AtomicString, xmlnsNamespaceURI, ("http://www.w3.org/2000/xmlns/"));
740 DEFINE_STATIC_LOCAL(const AtomicString, xmlns, ("xmlns"));
741 DEFINE_STATIC_LOCAL(const AtomicString, xml, ("xml"));
743 // These checks are from DOM Core Level 2, createElementNS
744 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
745 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
747 if (qName.prefix() == xml && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
750 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
751 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
752 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
753 if ((qName.prefix() == xmlns && qName.namespaceURI() != xmlnsNamespaceURI) || (qName.prefix() != xmlns && qName.namespaceURI() == xmlnsNamespaceURI))
759 // FIXME: This should really be in a possible ElementFactory class
760 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
764 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
765 if (qName.namespaceURI() == xhtmlNamespaceURI)
766 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
768 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
769 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
772 else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI || isWMLDocument())
773 e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
777 e = new Element(qName, document());
779 // <image> uses imgTag so we need a special rule.
780 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
785 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
787 String prefix, localName;
788 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
791 QualifiedName qName(prefix, localName, namespaceURI);
792 if (hasPrefixNamespaceMismatch(qName)) {
797 return createElement(qName, false);
800 Element* Document::getElementById(const AtomicString& elementId) const
802 if (elementId.isEmpty())
805 Element* element = m_elementsById.get(elementId.impl());
809 if (m_duplicateIds.contains(elementId.impl())) {
810 // We know there's at least one node with this id, but we don't know what the first one is.
811 for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
812 if (n->isElementNode()) {
813 element = static_cast<Element*>(n);
814 if (element->hasID() && element->getAttribute(idAttr) == elementId) {
815 m_duplicateIds.remove(elementId.impl());
816 m_elementsById.set(elementId.impl(), element);
821 ASSERT_NOT_REACHED();
826 String Document::readyState() const
828 if (Frame* f = frame()) {
829 if (f->loader()->isComplete())
834 // FIXME: What does "interactive" mean?
835 // FIXME: Missing support for "uninitialized".
840 String Document::encoding() const
842 if (TextResourceDecoder* d = decoder())
843 return d->encoding().name();
847 String Document::defaultCharset() const
849 if (Settings* settings = this->settings())
850 return settings->defaultTextEncodingName();
854 void Document::setCharset(const String& charset)
858 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
861 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
863 if (!implementation()->hasFeature("XML", String())) {
864 ec = NOT_SUPPORTED_ERR;
868 // FIXME: Also raise NOT_SUPPORTED_ERR if the version is set to a value that is not supported by this Document.
870 m_xmlVersion = version;
873 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
875 if (!implementation()->hasFeature("XML", String())) {
876 ec = NOT_SUPPORTED_ERR;
880 m_xmlStandalone = standalone;
883 void Document::setDocumentURI(const String& uri)
889 KURL Document::baseURI() const
894 Element* Document::elementFromPoint(int x, int y) const
899 HitTestRequest request(HitTestRequest::ReadOnly |
900 HitTestRequest::Active);
902 float zoomFactor = frame() ? frame()->pageZoomFactor() : 1.0f;
904 HitTestResult result(roundedIntPoint(FloatPoint(x * zoomFactor, y * zoomFactor)));
905 renderView()->layer()->hitTest(request, result);
907 Node* n = result.innerNode();
908 while (n && !n->isElementNode())
911 n = n->shadowAncestorNode();
912 return static_cast<Element*>(n);
915 void Document::addElementById(const AtomicString& elementId, Element* element)
917 typedef HashMap<AtomicStringImpl*, Element*>::iterator iterator;
918 if (!m_duplicateIds.contains(elementId.impl())) {
919 // Fast path. The ID is not already in m_duplicateIds, so we assume that it's
920 // also not already in m_elementsById and do an add. If that add succeeds, we're done.
921 pair<iterator, bool> addResult = m_elementsById.add(elementId.impl(), element);
922 if (addResult.second)
924 // The add failed, so this ID was already cached in m_elementsById.
925 // There are multiple elements with this ID. Remove the m_elementsById
926 // cache for this ID so getElementById searches for it next time it is called.
927 m_elementsById.remove(addResult.first);
928 m_duplicateIds.add(elementId.impl());
930 // There are multiple elements with this ID. If it exists, remove the m_elementsById
931 // cache for this ID so getElementById searches for it next time it is called.
932 iterator cachedItem = m_elementsById.find(elementId.impl());
933 if (cachedItem != m_elementsById.end()) {
934 m_elementsById.remove(cachedItem);
935 m_duplicateIds.add(elementId.impl());
938 m_duplicateIds.add(elementId.impl());
941 void Document::removeElementById(const AtomicString& elementId, Element* element)
943 if (m_elementsById.get(elementId.impl()) == element)
944 m_elementsById.remove(elementId.impl());
946 m_duplicateIds.remove(elementId.impl());
949 Element* Document::getElementByAccessKey(const String& key) const
953 if (!m_accessKeyMapValid) {
954 for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
955 if (!n->isElementNode())
957 Element* element = static_cast<Element*>(n);
958 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
959 if (!accessKey.isEmpty())
960 m_elementsByAccessKey.set(accessKey.impl(), element);
962 m_accessKeyMapValid = true;
964 return m_elementsByAccessKey.get(key.impl());
967 void Document::updateTitle()
969 if (Frame* f = frame())
970 f->loader()->setTitle(m_title);
973 void Document::setTitle(const String& title, Element* titleElement)
976 // Title set by JavaScript -- overrides any title elements.
977 m_titleSetExplicitly = true;
978 if (!isHTMLDocument())
980 else if (!m_titleElement) {
981 if (HTMLElement* headElement = head()) {
982 m_titleElement = createElement(titleTag, false);
983 ExceptionCode ec = 0;
984 headElement->appendChild(m_titleElement, ec);
988 } else if (titleElement != m_titleElement) {
989 if (m_titleElement || m_titleSetExplicitly)
990 // Only allow the first title element to change the title -- others have no effect.
992 m_titleElement = titleElement;
995 if (m_title == title)
1001 if (m_titleSetExplicitly && m_titleElement && m_titleElement->hasTagName(titleTag))
1002 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(m_title);
1005 void Document::removeTitle(Element* titleElement)
1007 if (m_titleElement != titleElement)
1011 m_titleSetExplicitly = false;
1013 // Update title based on first title element in the head, if one exists.
1014 if (HTMLElement* headElement = head()) {
1015 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1016 if (e->hasTagName(titleTag)) {
1017 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1018 setTitle(titleElement->text(), titleElement);
1023 if (!m_titleElement && !m_title.isEmpty()) {
1029 String Document::nodeName() const
1034 Node::NodeType Document::nodeType() const
1036 return DOCUMENT_NODE;
1039 FrameView* Document::view() const
1041 return m_frame ? m_frame->view() : 0;
1044 Page* Document::page() const
1046 return m_frame ? m_frame->page() : 0;
1049 Settings* Document::settings() const
1051 return m_frame ? m_frame->settings() : 0;
1054 PassRefPtr<Range> Document::createRange()
1056 return Range::create(this);
1059 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1060 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1063 ec = NOT_SUPPORTED_ERR;
1066 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1069 PassRefPtr<TreeWalker> Document::createTreeWalker(Node *root, unsigned whatToShow,
1070 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1073 ec = NOT_SUPPORTED_ERR;
1076 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1079 void Document::setDocumentChanged(bool b)
1082 if (!m_docChanged) {
1083 if (!changedDocuments)
1084 changedDocuments = new HashSet<Document*>;
1085 changedDocuments->add(this);
1087 if (m_accessKeyMapValid) {
1088 m_accessKeyMapValid = false;
1089 m_elementsByAccessKey.clear();
1092 if (m_docChanged && changedDocuments)
1093 changedDocuments->remove(this);
1099 void Document::recalcStyle(StyleChange change)
1101 // we should not enter style recalc while painting
1102 if (view() && view()->isPainting()) {
1103 ASSERT(!view()->isPainting());
1107 if (m_inStyleRecalc)
1108 return; // Guard against re-entrancy. -dwh
1110 m_inStyleRecalc = true;
1111 suspendPostAttachCallbacks();
1113 view()->pauseScheduledEvents();
1115 ASSERT(!renderer() || renderArena());
1116 if (!renderer() || !renderArena())
1119 if (change == Force) {
1120 // style selector may set this again during recalc
1121 m_hasNodesWithPlaceholderStyle = false;
1123 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1124 documentStyle->setDisplay(BLOCK);
1125 documentStyle->setVisuallyOrdered(visuallyOrdered);
1126 documentStyle->setZoom(frame()->pageZoomFactor());
1127 m_styleSelector->setStyle(documentStyle);
1129 FontDescription fontDescription;
1130 fontDescription.setUsePrinterFont(printing());
1131 if (Settings* settings = this->settings()) {
1132 fontDescription.setRenderingMode(settings->fontRenderingMode());
1133 if (printing() && !settings->shouldPrintBackgrounds())
1134 documentStyle->setForceBackgroundsToWhite(true);
1135 const AtomicString& stdfont = settings->standardFontFamily();
1136 if (!stdfont.isEmpty()) {
1137 fontDescription.firstFamily().setFamily(stdfont);
1138 fontDescription.firstFamily().appendFamily(0);
1140 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1141 m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSSValueMedium, inCompatMode(), false));
1144 documentStyle->setFontDescription(fontDescription);
1145 documentStyle->font().update(m_styleSelector->fontSelector());
1147 documentStyle->setHtmlHacks(true); // enable html specific rendering tricks
1149 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1150 if (renderer() && ch != NoChange)
1151 renderer()->setStyle(documentStyle.release());
1154 for (Node* n = firstChild(); n; n = n->nextSibling())
1155 if (change >= Inherit || n->hasChangedChild() || n->changed())
1156 n->recalcStyle(change);
1161 #if USE(ACCELERATED_COMPOSITING)
1163 // If we didn't update compositing layers because of layout(), we need to do so here.
1164 view()->updateCompositingLayers();
1170 setChanged(NoStyleChange);
1171 setHasChangedChild(false);
1172 setDocumentChanged(false);
1175 view()->resumeScheduledEvents();
1176 resumePostAttachCallbacks();
1177 m_inStyleRecalc = false;
1179 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1180 if (m_closeAfterStyleRecalc) {
1181 m_closeAfterStyleRecalc = false;
1186 void Document::updateRendering()
1188 if (!hasChangedChild() || inPageCache())
1192 m_frame->animation()->beginAnimationUpdate();
1194 recalcStyle(NoChange);
1196 // Tell the animation controller that updateRendering is finished and it can do any post-processing
1198 m_frame->animation()->endAnimationUpdate();
1201 void Document::updateDocumentsRendering()
1203 if (!changedDocuments)
1206 while (changedDocuments->size()) {
1207 HashSet<Document*>::iterator it = changedDocuments->begin();
1208 Document* doc = *it;
1209 changedDocuments->remove(it);
1211 doc->m_docChanged = false;
1212 doc->updateRendering();
1216 void Document::updateLayout()
1218 if (Element* oe = ownerElement())
1219 oe->document()->updateLayout();
1223 // Only do a layout if changes have occurred that make it necessary.
1224 FrameView* v = view();
1225 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1229 // FIXME: This is a bad idea and needs to be removed eventually.
1230 // Other browsers load stylesheets before they continue parsing the web page.
1231 // Since we don't, we can run JavaScript code that needs answers before the
1232 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1233 // lets us get reasonable answers. The long term solution to this problem is
1234 // to instead suspend JavaScript execution.
1235 void Document::updateLayoutIgnorePendingStylesheets()
1237 bool oldIgnore = m_ignorePendingStylesheets;
1239 if (!haveStylesheetsLoaded()) {
1240 m_ignorePendingStylesheets = true;
1241 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1242 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1243 // with accurate style information. (Our suppression involves blanking the whole page at the
1244 // moment. If it were more refined, we might be able to do something better.)
1245 // It's worth noting though that this entire method is a hack, since what we really want to do is
1246 // suspend JS instead of doing a layout with inaccurate information.
1247 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1248 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1249 updateStyleSelector();
1250 } else if (m_hasNodesWithPlaceholderStyle)
1251 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1252 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1253 // but here we need up-to-date style immediatly.
1259 m_ignorePendingStylesheets = oldIgnore;
1262 void Document::attach()
1264 ASSERT(!attached());
1265 ASSERT(!m_inPageCache);
1266 ASSERT(!m_axObjectCache);
1269 m_renderArena = new RenderArena();
1271 // Create the rendering tree
1272 setRenderer(new (m_renderArena) RenderView(this, view()));
1273 #if USE(ACCELERATED_COMPOSITING)
1274 renderView()->didMoveOnscreen();
1277 if (!m_styleSelector) {
1278 bool matchAuthorAndUserStyles = true;
1279 if (Settings* docSettings = settings())
1280 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1281 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
1286 RenderObject* render = renderer();
1289 ContainerNode::attach();
1291 setRenderer(render);
1294 void Document::detach()
1297 ASSERT(!m_inPageCache);
1299 clearAXObjectCache();
1300 stopActiveDOMObjects();
1302 RenderObject* render = renderer();
1304 // Send out documentWillBecomeInactive() notifications to registered elements,
1305 // in order to stop media elements
1306 documentWillBecomeInactive();
1308 // indicate destruction mode, i.e. attached() but renderer == 0
1315 ContainerNode::detach();
1320 // This is required, as our Frame might delete itself as soon as it detaches
1321 // us. However, this violates Node::detach() symantics, as it's never
1322 // possible to re-attach. Eventually Document::detach() should be renamed
1323 // or this call made explicit in each of the callers of Document::detach().
1324 clearFramePointer();
1326 if (m_renderArena) {
1327 delete m_renderArena;
1332 void Document::clearFramePointer()
1337 void Document::removeAllEventListenersFromAllNodes()
1339 size_t size = m_windowEventListeners.size();
1340 for (size_t i = 0; i < size; ++i)
1341 m_windowEventListeners[i]->setRemoved(true);
1342 m_windowEventListeners.clear();
1343 removeAllDisconnectedNodeEventListeners();
1344 for (Node* node = this; node; node = node->traverseNextNode())
1345 node->removeAllEventListeners();
1348 void Document::registerDisconnectedNodeWithEventListeners(Node* node)
1350 m_disconnectedNodesWithEventListeners.add(node);
1353 void Document::unregisterDisconnectedNodeWithEventListeners(Node* node)
1355 m_disconnectedNodesWithEventListeners.remove(node);
1358 void Document::removeAllDisconnectedNodeEventListeners()
1360 HashSet<Node*>::iterator end = m_disconnectedNodesWithEventListeners.end();
1361 for (HashSet<Node*>::iterator i = m_disconnectedNodesWithEventListeners.begin(); i != end; ++i)
1362 (*i)->removeAllEventListeners();
1363 m_disconnectedNodesWithEventListeners.clear();
1366 RenderView* Document::renderView() const
1368 return toRenderView(renderer());
1371 void Document::clearAXObjectCache()
1373 // clear cache in top document
1374 if (m_axObjectCache) {
1375 delete m_axObjectCache;
1376 m_axObjectCache = 0;
1380 // ask the top-level document to clear its cache
1381 Document* doc = topDocument();
1383 doc->clearAXObjectCache();
1386 AXObjectCache* Document::axObjectCache() const
1388 // The only document that actually has a AXObjectCache is the top-level
1389 // document. This is because we need to be able to get from any WebCoreAXObject
1390 // to any other WebCoreAXObject on the same page. Using a single cache allows
1391 // lookups across nested webareas (i.e. multiple documents).
1393 if (m_axObjectCache) {
1394 // return already known top-level cache
1395 if (!ownerElement())
1396 return m_axObjectCache;
1398 // In some pages with frames, the cache is created before the sub-webarea is
1399 // inserted into the tree. Here, we catch that case and just toss the old
1400 // cache and start over.
1401 // NOTE: This recovery may no longer be needed. I have been unable to trigger
1402 // it again. See rdar://5794454
1403 // FIXME: Can this be fixed when inserting the subframe instead of now?
1404 // FIXME: If this function was called to get the cache in order to remove
1405 // an AXObject, we are now deleting the cache as a whole and returning a
1406 // new empty cache that does not contain the AXObject! That should actually
1407 // be OK. I am concerned about other cases like this where accessing the
1408 // cache blows away the AXObject being operated on.
1409 delete m_axObjectCache;
1410 m_axObjectCache = 0;
1413 // ask the top-level document for its cache
1414 Document* doc = topDocument();
1416 return doc->axObjectCache();
1418 // this is the top-level document, so install a new cache
1419 m_axObjectCache = new AXObjectCache;
1420 return m_axObjectCache;
1423 void Document::setVisuallyOrdered()
1425 visuallyOrdered = true;
1427 renderer()->style()->setVisuallyOrdered(true);
1430 Tokenizer* Document::createTokenizer()
1432 // FIXME: this should probably pass the frame instead
1433 return new XMLTokenizer(this, view());
1436 void Document::open(Document* ownerDocument)
1438 if (ownerDocument) {
1439 setURL(ownerDocument->url());
1440 m_cookieURL = ownerDocument->cookieURL();
1441 ScriptExecutionContext::setSecurityOrigin(ownerDocument->securityOrigin());
1445 if (m_frame->loader()->isLoadingMainResource() || (tokenizer() && tokenizer()->executingScript()))
1448 if (m_frame->loader()->state() == FrameStateProvisional)
1449 m_frame->loader()->stopAllLoaders();
1455 m_frame->loader()->didExplicitOpen();
1458 void Document::cancelParsing()
1461 // We have to clear the tokenizer to avoid possibly triggering
1462 // the onload handler when closing as a side effect of a cancel-style
1463 // change, such as opening a new document or closing the window while
1471 void Document::implicitOpen()
1476 m_tokenizer = createTokenizer();
1480 HTMLElement* Document::body() const
1482 Node* de = documentElement();
1486 // try to prefer a FRAMESET element over BODY
1488 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
1489 if (i->hasTagName(framesetTag))
1490 return static_cast<HTMLElement*>(i);
1492 if (i->hasTagName(bodyTag) && !body)
1495 return static_cast<HTMLElement*>(body);
1498 void Document::setBody(PassRefPtr<HTMLElement> newBody, ExceptionCode& ec)
1500 if (!newBody || !documentElement()) {
1501 ec = HIERARCHY_REQUEST_ERR;
1505 HTMLElement* b = body();
1507 documentElement()->appendChild(newBody, ec);
1509 documentElement()->replaceChild(newBody, b, ec);
1512 HTMLHeadElement* Document::head()
1514 Node* de = documentElement();
1518 for (Node* e = de->firstChild(); e; e = e->nextSibling())
1519 if (e->hasTagName(headTag))
1520 return static_cast<HTMLHeadElement*>(e);
1525 void Document::close()
1527 Frame* frame = this->frame();
1529 // This code calls implicitClose() if all loading has completed.
1530 FrameLoader* frameLoader = frame->loader();
1531 frameLoader->endIfNotLoadingMainResource();
1532 frameLoader->checkCompleted();
1534 // Because we have no frame, we don't know if all loading has completed,
1535 // so we just call implicitClose() immediately. FIXME: This might fire
1536 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
1541 void Document::implicitClose()
1543 // 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.
1544 if (m_inStyleRecalc) {
1545 m_closeAfterStyleRecalc = true;
1549 bool wasLocationChangePending = frame() && frame()->loader()->isScheduledLocationChangePending();
1550 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1555 m_processingLoadEvent = true;
1557 m_wellFormed = m_tokenizer && m_tokenizer->wellFormed();
1559 // We have to clear the tokenizer, in case someone document.write()s from the
1560 // onLoad event handler, as in Radar 3206524.
1564 // Parser should have picked up all preloads by now
1565 m_docLoader->clearPreloads();
1567 // Create a body element if we don't already have one. See Radar 3758785.
1568 if (!this->body() && isHTMLDocument()) {
1569 if (Node* documentElement = this->documentElement()) {
1570 ExceptionCode ec = 0;
1571 documentElement->appendChild(new HTMLBodyElement(bodyTag, this), ec);
1576 // FIXME: We kick off the icon loader when the Document is done parsing.
1577 // There are earlier opportunities we could start it:
1578 // -When the <head> finishes parsing
1579 // -When any new HTMLLinkElement is inserted into the document
1580 // But those add a dynamic component to the favicon that has UI
1581 // ramifications, and we need to decide what is the Right Thing To Do(tm)
1584 f->loader()->startIconLoader();
1586 // Resume the animations (or start them)
1588 f->animation()->resumeAnimations(this);
1590 ImageLoader::dispatchPendingLoadEvents();
1591 dispatchWindowEvent(eventNames().loadEvent, false, false);
1593 f->loader()->handledOnloadEvents();
1594 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1595 if (!ownerElement())
1596 printf("onload fired at %d\n", elapsedTime());
1599 m_processingLoadEvent = false;
1601 // An event handler may have removed the frame
1605 // Make sure both the initial layout and reflow happen after the onload
1606 // fires. This will improve onload scores, and other browsers do it.
1607 // If they wanna cheat, we can too. -dwh
1609 if (frame()->loader()->isScheduledLocationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
1610 // Just bail out. Before or during the onload we were shifted to another page.
1611 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1612 view()->unscheduleRelayout();
1616 frame()->loader()->checkCallImplicitClose();
1618 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1619 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1620 // layout/painting now would be pointless.
1621 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1624 // Always do a layout after loading if needed.
1625 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1628 // Paint immediately after the document is ready. We do this to ensure that any timers set by the
1629 // onload don't have a chance to fire before we would have painted. To avoid over-flushing we only
1630 // worry about this for the top-level document. For platforms that use native widgets for ScrollViews, this
1631 // call does nothing (Mac, wx).
1632 // FIXME: This causes a timing issue with the dispatchDidFinishLoad delegate callback on Mac, so think
1633 // before enabling it, even if Mac becomes viewless later.
1634 // See <rdar://problem/5092361>
1635 if (view() && !ownerElement())
1636 view()->hostWindow()->paint();
1640 if (f && renderer() && this == topDocument() && AXObjectCache::accessibilityEnabled())
1641 axObjectCache()->postNotificationToElement(renderer(), "AXLoadComplete");
1645 // FIXME: Officially, time 0 is when the outermost <svg> receives its
1646 // SVGLoad event, but we don't implement those yet. This is close enough
1647 // for now. In some cases we should have fired earlier.
1648 if (svgExtensions())
1649 accessSVGExtensions()->startAnimations();
1653 void Document::setParsing(bool b)
1656 if (!m_bParsing && view())
1657 view()->scheduleRelayout();
1659 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1660 if (!ownerElement() && !m_bParsing)
1661 printf("Parsing finished at %d\n", elapsedTime());
1665 bool Document::shouldScheduleLayout()
1667 // This function will only be called when FrameView thinks a layout is needed.
1668 // This enforces a couple extra rules.
1670 // (a) Only schedule a layout once the stylesheets are loaded.
1671 // (b) Only schedule layout once we have a body element.
1673 return (haveStylesheetsLoaded() && body()) ||
1674 (documentElement() && !documentElement()->hasTagName(htmlTag));
1677 int Document::minimumLayoutDelay()
1679 if (m_overMinimumLayoutThreshold)
1682 int elapsed = elapsedTime();
1683 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1685 // We'll want to schedule the timer to fire at the minimum layout threshold.
1686 return max(0, cLayoutScheduleThreshold - elapsed);
1689 int Document::elapsedTime() const
1691 return static_cast<int>((currentTime() - m_startTime) * 1000);
1694 void Document::write(const SegmentedString& text, Document* ownerDocument)
1696 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1697 if (!ownerElement())
1698 printf("Beginning a document.write at %d\n", elapsedTime());
1702 open(ownerDocument);
1704 ASSERT(m_tokenizer);
1705 m_tokenizer->write(text, false);
1707 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1708 if (!ownerElement())
1709 printf("Ending a document.write at %d\n", elapsedTime());
1713 void Document::write(const String& text, Document* ownerDocument)
1715 write(SegmentedString(text), ownerDocument);
1718 void Document::writeln(const String& text, Document* ownerDocument)
1720 write(text, ownerDocument);
1721 write("\n", ownerDocument);
1724 void Document::finishParsing()
1726 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1727 if (!ownerElement())
1728 printf("Received all data at %d\n", elapsedTime());
1731 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1732 // finish() is called:
1733 // (1) All remaining data is parsed, document isn't loaded yet
1734 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1735 // (3) Data is still remaining to be parsed.
1737 m_tokenizer->finish();
1740 void Document::clear()
1747 size_t size = m_windowEventListeners.size();
1748 for (size_t i = 0; i < size; ++i)
1749 m_windowEventListeners[i]->setRemoved(true);
1750 m_windowEventListeners.clear();
1753 const KURL& Document::virtualURL() const
1758 KURL Document::virtualCompleteURL(const String& url) const
1760 return completeURL(url);
1763 void Document::setURL(const KURL& url)
1765 const KURL& newURL = url.isEmpty() ? blankURL() : url;
1766 if (newURL == m_url)
1770 m_documentURI = m_url.string();
1774 void Document::setBaseElementURL(const KURL& baseElementURL)
1776 m_baseElementURL = baseElementURL;
1780 void Document::updateBaseURL()
1782 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
1783 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
1784 // from the Document interface otherwise.
1785 if (m_baseElementURL.isEmpty()) {
1786 // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
1787 // so we use a null base URL.
1788 m_baseURL = KURL(KURL(), documentURI());
1790 m_baseURL = m_baseElementURL;
1791 if (!m_baseURL.isValid())
1795 m_elemSheet->setHref(m_baseURL.string());
1796 if (m_mappedElementSheet)
1797 m_mappedElementSheet->setHref(m_baseURL.string());
1800 String Document::userAgent(const KURL& url) const
1802 return frame() ? frame()->loader()->userAgent(url) : String();
1805 void Document::setCSSStyleSheet(const String& url, const String& charset, const CachedCSSStyleSheet* sheet)
1807 m_sheet = CSSStyleSheet::create(this, url, charset);
1808 m_sheet->parseString(sheet->sheetText());
1810 updateStyleSelector();
1813 #if FRAME_LOADS_USER_STYLESHEET
1814 void Document::setUserStyleSheet(const String& sheet)
1816 if (m_usersheet != sheet) {
1817 m_usersheet = sheet;
1818 updateStyleSelector();
1823 String Document::userStyleSheet() const
1825 #if FRAME_LOADS_USER_STYLESHEET
1828 Page* page = this->page();
1831 return page->userStyleSheet();
1835 CSSStyleSheet* Document::elementSheet()
1838 m_elemSheet = CSSStyleSheet::create(this, m_baseURL.string());
1839 return m_elemSheet.get();
1842 CSSStyleSheet* Document::mappedElementSheet()
1844 if (!m_mappedElementSheet)
1845 m_mappedElementSheet = CSSStyleSheet::create(this, m_baseURL.string());
1846 return m_mappedElementSheet.get();
1849 static Node* nextNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1851 // Search is inclusive of start
1852 for (Node* n = start; n; n = n->traverseNextNode())
1853 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1859 static Node* previousNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1861 // Search is inclusive of start
1862 for (Node* n = start; n; n = n->traversePreviousNode())
1863 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1869 static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1871 // Search is inclusive of start
1872 int winningTabIndex = SHRT_MAX + 1;
1874 for (Node* n = start; n; n = n->traverseNextNode())
1875 if (n->isKeyboardFocusable(event) && n->tabIndex() > tabIndex && n->tabIndex() < winningTabIndex) {
1877 winningTabIndex = n->tabIndex();
1883 static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1885 // Search is inclusive of start
1886 int winningTabIndex = 0;
1888 for (Node* n = start; n; n = n->traversePreviousNode())
1889 if (n->isKeyboardFocusable(event) && n->tabIndex() < tabIndex && n->tabIndex() > winningTabIndex) {
1891 winningTabIndex = n->tabIndex();
1897 Node* Document::nextFocusableNode(Node* start, KeyboardEvent* event)
1900 // If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
1901 if (start->tabIndex() < 0) {
1902 for (Node* n = start->traverseNextNode(); n; n = n->traverseNextNode())
1903 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1907 // First try to find a node with the same tabindex as start that comes after start in the document.
1908 if (Node* winner = nextNodeWithExactTabIndex(start->traverseNextNode(), start->tabIndex(), event))
1911 if (start->tabIndex() == 0)
1912 // We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
1916 // Look for the first node in the document that:
1917 // 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
1918 // 2) comes first in the document, if there's a tie.
1919 if (Node* winner = nextNodeWithGreaterTabIndex(this, start ? start->tabIndex() : 0, event))
1922 // There are no nodes with a tabindex greater than start's tabindex,
1923 // so find the first node with a tabindex of 0.
1924 return nextNodeWithExactTabIndex(this, 0, event);
1927 Node* Document::previousFocusableNode(Node* start, KeyboardEvent* event)
1930 for (last = this; last->lastChild(); last = last->lastChild())
1933 // First try to find the last node in the document that comes before start and has the same tabindex as start.
1934 // If start is null, find the last node in the document with a tabindex of 0.
1936 int startingTabIndex;
1938 startingNode = start->traversePreviousNode();
1939 startingTabIndex = start->tabIndex();
1941 startingNode = last;
1942 startingTabIndex = 0;
1945 // However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
1946 if (startingTabIndex < 0) {
1947 for (Node* n = startingNode; n; n = n->traversePreviousNode())
1948 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1952 if (Node* winner = previousNodeWithExactTabIndex(startingNode, startingTabIndex, event))
1955 // There are no nodes before start with the same tabindex as start, so look for a node that:
1956 // 1) has the highest non-zero tabindex (that is less than start's tabindex), and
1957 // 2) comes last in the document, if there's a tie.
1958 startingTabIndex = (start && start->tabIndex()) ? start->tabIndex() : SHRT_MAX;
1959 return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
1962 int Document::nodeAbsIndex(Node *node)
1964 ASSERT(node->document() == this);
1967 for (Node *n = node; n && n != this; n = n->traversePreviousNode())
1972 Node *Document::nodeWithAbsIndex(int absIndex)
1975 for (int i = 0; n && (i < absIndex); i++) {
1976 n = n->traverseNextNode();
1981 void Document::processHttpEquiv(const String &equiv, const String &content)
1983 ASSERT(!equiv.isNull() && !content.isNull());
1985 Frame *frame = this->frame();
1987 if (equalIgnoringCase(equiv, "default-style")) {
1988 // The preferred style set has been overridden as per section
1989 // 14.3.2 of the HTML4.0 specification. We need to update the
1990 // sheet used variable and then update our style selector.
1991 // For more info, see the test at:
1992 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1994 m_selectedStylesheetSet = content;
1995 m_preferredStylesheetSet = content;
1996 updateStyleSelector();
1997 } else if (equalIgnoringCase(equiv, "refresh")) {
2000 if (frame && parseHTTPRefresh(content, true, delay, url)) {
2002 url = frame->loader()->url().string();
2004 url = completeURL(url).string();
2005 frame->loader()->scheduleHTTPRedirection(delay, url);
2007 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2008 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2009 if (isHTMLDocument())
2010 static_cast<HTMLDocument*>(this)->setCookie(content);
2011 } else if (equalIgnoringCase(equiv, "content-language"))
2012 setContentLanguage(content);
2013 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2014 parseDNSPrefetchControlHeader(content);
2017 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const IntPoint& documentPoint, const PlatformMouseEvent& event)
2019 ASSERT(!renderer() || renderer()->isRenderView());
2022 return MouseEventWithHitTestResults(event, HitTestResult(IntPoint()));
2024 HitTestResult result(documentPoint);
2025 renderView()->layer()->hitTest(request, result);
2027 if (!request.readOnly())
2030 return MouseEventWithHitTestResults(event, result);
2033 // DOM Section 1.1.1
2034 bool Document::childTypeAllowed(NodeType type)
2037 case ATTRIBUTE_NODE:
2038 case CDATA_SECTION_NODE:
2039 case DOCUMENT_FRAGMENT_NODE:
2042 case ENTITY_REFERENCE_NODE:
2045 case XPATH_NAMESPACE_NODE:
2048 case PROCESSING_INSTRUCTION_NODE:
2050 case DOCUMENT_TYPE_NODE:
2052 // Documents may contain no more than one of each of these.
2053 // (One Element and one DocumentType.)
2054 for (Node* c = firstChild(); c; c = c->nextSibling())
2055 if (c->nodeType() == type)
2062 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2065 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2068 if (oldChild->nodeType() == newChild->nodeType())
2071 int numDoctypes = 0;
2072 int numElements = 0;
2074 // First, check how many doctypes and elements we have, not counting
2075 // the child we're about to remove.
2076 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2080 switch (c->nodeType()) {
2081 case DOCUMENT_TYPE_NODE:
2092 // Then, see how many doctypes and elements might be added by the new child.
2093 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2094 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2095 switch (c->nodeType()) {
2096 case ATTRIBUTE_NODE:
2097 case CDATA_SECTION_NODE:
2098 case DOCUMENT_FRAGMENT_NODE:
2101 case ENTITY_REFERENCE_NODE:
2104 case XPATH_NAMESPACE_NODE:
2107 case PROCESSING_INSTRUCTION_NODE:
2109 case DOCUMENT_TYPE_NODE:
2118 switch (newChild->nodeType()) {
2119 case ATTRIBUTE_NODE:
2120 case CDATA_SECTION_NODE:
2121 case DOCUMENT_FRAGMENT_NODE:
2124 case ENTITY_REFERENCE_NODE:
2127 case XPATH_NAMESPACE_NODE:
2130 case PROCESSING_INSTRUCTION_NODE:
2132 case DOCUMENT_TYPE_NODE:
2141 if (numElements > 1 || numDoctypes > 1)
2147 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2149 // Spec says cloning Document nodes is "implementation dependent"
2150 // so we do not support it...
2154 StyleSheetList* Document::styleSheets()
2156 return m_styleSheets.get();
2159 String Document::preferredStylesheetSet() const
2161 return m_preferredStylesheetSet;
2164 String Document::selectedStylesheetSet() const
2166 return m_selectedStylesheetSet;
2169 void Document::setSelectedStylesheetSet(const String& aString)
2171 m_selectedStylesheetSet = aString;
2172 updateStyleSelector();
2174 renderer()->repaint();
2177 // This method is called whenever a top-level stylesheet has finished loading.
2178 void Document::removePendingSheet()
2180 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2181 ASSERT(m_pendingStylesheets > 0);
2183 m_pendingStylesheets--;
2185 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2186 if (!ownerElement())
2187 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2190 updateStyleSelector();
2192 if (!m_pendingStylesheets && m_tokenizer)
2193 m_tokenizer->executeScriptsWaitingForStylesheets();
2195 if (!m_pendingStylesheets && m_gotoAnchorNeededAfterStylesheetsLoad && m_frame)
2196 m_frame->loader()->gotoAnchor();
2199 void Document::updateStyleSelector()
2201 // Don't bother updating, since we haven't loaded all our style info yet
2202 // and haven't calculated the style selector for the first time.
2203 if (!m_didCalculateStyleSelector && !haveStylesheetsLoaded())
2206 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
2207 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2209 renderer()->repaint();
2212 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2213 if (!ownerElement())
2214 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2217 recalcStyleSelector();
2220 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2221 if (!ownerElement())
2222 printf("Finished update of style selector at time %d\n", elapsedTime());
2226 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
2228 view()->scheduleRelayout();
2232 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
2234 // Until the <body> exists, we have no choice but to compare document positions,
2235 // since styles outside of the body and head continue to be shunted into the head
2236 // (and thus can shift to end up before dynamically added DOM content that is also
2237 // outside the body).
2238 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
2239 m_styleSheetCandidateNodes.add(node);
2243 // Determine an appropriate insertion point.
2244 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2245 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2246 ListHashSet<Node*>::iterator it = end;
2247 Node* followingNode = 0;
2251 unsigned short position = n->compareDocumentPosition(node);
2252 if (position == DOCUMENT_POSITION_FOLLOWING) {
2253 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2257 } while (it != begin);
2259 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2262 void Document::removeStyleSheetCandidateNode(Node* node)
2264 m_styleSheetCandidateNodes.remove(node);
2267 void Document::recalcStyleSelector()
2269 if (!renderer() || !attached())
2272 StyleSheetVector sheets;
2274 bool matchAuthorAndUserStyles = true;
2275 if (Settings* settings = this->settings())
2276 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
2278 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2279 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2280 if (!matchAuthorAndUserStyles)
2282 for (ListHashSet<Node*>::iterator it = begin; it != end; ++it) {
2285 StyleSheet* sheet = 0;
2287 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
2288 // Processing instruction (XML documents only)
2289 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
2290 sheet = pi->sheet();
2292 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
2293 if (pi->isXSL() && !transformSourceDocument()) {
2294 // Don't apply XSL transforms until loading is finished.
2296 applyXSLTransform(pi);
2300 if (!sheet && !pi->localHref().isEmpty()) {
2301 // Processing instruction with reference to an element in this document - e.g.
2302 // <?xml-stylesheet href="#mystyle">, with the element
2303 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2305 Element* elem = getElementById(pi->localHref().impl());
2307 String sheetText("");
2308 for (Node* c = elem->firstChild(); c; c = c->nextSibling()) {
2309 if (c->nodeType() == TEXT_NODE || c->nodeType() == CDATA_SECTION_NODE)
2310 sheetText += c->nodeValue();
2313 RefPtr<CSSStyleSheet> cssSheet = CSSStyleSheet::create(this);
2314 cssSheet->parseString(sheetText);
2315 pi->setCSSStyleSheet(cssSheet);
2316 sheet = cssSheet.get();
2319 } else if (n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))
2321 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2324 Element* e = static_cast<Element*>(n);
2325 AtomicString title = e->getAttribute(titleAttr);
2326 bool enabledViaScript = false;
2327 if (e->hasLocalName(linkTag)) {
2329 HTMLLinkElement* l = static_cast<HTMLLinkElement*>(n);
2330 if (l->isDisabled())
2332 enabledViaScript = l->isEnabledViaScript();
2333 if (l->isLoading()) {
2334 // it is loading but we should still decide which style sheet set to use
2335 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
2336 const AtomicString& rel = e->getAttribute(relAttr);
2337 if (!rel.contains("alternate")) {
2338 m_preferredStylesheetSet = title;
2339 m_selectedStylesheetSet = title;
2348 // Get the current preferred styleset. This is the
2349 // set of sheets that will be enabled.
2351 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2352 sheet = static_cast<SVGStyleElement*>(n)->sheet();
2355 if (e->hasLocalName(linkTag))
2356 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
2359 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
2361 // Check to see if this sheet belongs to a styleset
2362 // (thus making it PREFERRED or ALTERNATE rather than
2364 if (!enabledViaScript && !title.isEmpty()) {
2365 // Yes, we have a title.
2366 if (m_preferredStylesheetSet.isEmpty()) {
2367 // No preferred set has been established. If
2368 // we are NOT an alternate sheet, then establish
2369 // us as the preferred set. Otherwise, just ignore
2371 AtomicString rel = e->getAttribute(relAttr);
2372 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
2373 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
2376 if (title != m_preferredStylesheetSet)
2382 sheets.append(sheet);
2385 m_styleSheets->swap(sheets);
2387 // Create a new style selector
2388 delete m_styleSelector;
2389 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
2390 m_didCalculateStyleSelector = true;
2393 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
2395 m_hoverNode = newHoverNode;
2398 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
2400 m_activeNode = newActiveNode;
2403 void Document::focusedNodeRemoved()
2408 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
2410 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
2413 bool nodeInSubtree = false;
2414 if (amongChildrenOnly)
2415 nodeInSubtree = m_focusedNode->isDescendantOf(node);
2417 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
2420 document()->focusedNodeRemoved();
2423 void Document::hoveredNodeDetached(Node* node)
2425 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parent())))
2428 m_hoverNode = node->parent();
2429 while (m_hoverNode && !m_hoverNode->renderer())
2430 m_hoverNode = m_hoverNode->parent();
2432 frame()->eventHandler()->scheduleHoverStateUpdate();
2435 void Document::activeChainNodeDetached(Node* node)
2437 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parent())))
2440 m_activeNode = node->parent();
2441 while (m_activeNode && !m_activeNode->renderer())
2442 m_activeNode = m_activeNode->parent();
2445 #if ENABLE(DASHBOARD_SUPPORT)
2446 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
2448 return m_dashboardRegions;
2451 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
2453 m_dashboardRegions = regions;
2454 setDashboardRegionsDirty(false);
2458 bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
2460 // Make sure newFocusedNode is actually in this document
2461 if (newFocusedNode && (newFocusedNode->document() != this))
2464 if (m_focusedNode == newFocusedNode)
2470 bool focusChangeBlocked = false;
2471 RefPtr<Node> oldFocusedNode = m_focusedNode;
2474 // Remove focus from the existing focus node (if any)
2475 if (oldFocusedNode && !oldFocusedNode->m_inDetach) {
2476 if (oldFocusedNode->active())
2477 oldFocusedNode->setActive(false);
2479 oldFocusedNode->setFocus(false);
2481 // Dispatch a change event for text fields or textareas that have been edited
2482 RenderObject* r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer());
2483 if (r && r->isTextControl() && toRenderTextControl(r)->isEdited()) {
2484 oldFocusedNode->dispatchEventForType(eventNames().changeEvent, true, false);
2485 if ((r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer()))) {
2486 if (r->isTextControl())
2487 toRenderTextControl(r)->setEdited(false);
2491 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
2492 oldFocusedNode->dispatchBlurEvent();
2494 if (m_focusedNode) {
2495 // handler shifted focus
2496 focusChangeBlocked = true;
2499 oldFocusedNode->dispatchUIEvent(eventNames().DOMFocusOutEvent);
2500 if (m_focusedNode) {
2501 // handler shifted focus
2502 focusChangeBlocked = true;
2505 if ((oldFocusedNode.get() == this) && oldFocusedNode->hasOneRef())
2508 if (oldFocusedNode.get() == oldFocusedNode->rootEditableElement())
2509 frame()->editor()->didEndEditing();
2512 if (newFocusedNode) {
2513 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
2514 // delegate blocks focus change
2515 focusChangeBlocked = true;
2516 goto SetFocusedNodeDone;
2518 // Set focus on the new node
2519 m_focusedNode = newFocusedNode.get();
2521 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
2522 m_focusedNode->dispatchFocusEvent();
2524 if (m_focusedNode != newFocusedNode) {
2525 // handler shifted focus
2526 focusChangeBlocked = true;
2527 goto SetFocusedNodeDone;
2529 m_focusedNode->dispatchUIEvent(eventNames().DOMFocusInEvent);
2530 if (m_focusedNode != newFocusedNode) {
2531 // handler shifted focus
2532 focusChangeBlocked = true;
2533 goto SetFocusedNodeDone;
2535 m_focusedNode->setFocus();
2537 if (m_focusedNode.get() == m_focusedNode->rootEditableElement())
2538 frame()->editor()->didBeginEditing();
2540 // eww, I suck. set the qt focus correctly
2541 // ### find a better place in the code for this
2543 Widget *focusWidget = widgetForNode(m_focusedNode.get());
2545 // Make sure a widget has the right size before giving it focus.
2546 // Otherwise, we are testing edge cases of the Widget code.
2547 // Specifically, in WebCore this does not work well for text fields.
2549 // Re-get the widget in case updating the layout changed things.
2550 focusWidget = widgetForNode(m_focusedNode.get());
2553 focusWidget->setFocus();
2560 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
2561 axObjectCache()->handleFocusedUIElementChanged();
2566 return !focusChangeBlocked;
2569 void Document::setCSSTarget(Element* n)
2572 m_cssTarget->setChanged();
2578 void Document::attachNodeIterator(NodeIterator *ni)
2580 m_nodeIterators.add(ni);
2583 void Document::detachNodeIterator(NodeIterator *ni)
2585 m_nodeIterators.remove(ni);
2588 void Document::nodeChildrenChanged(ContainerNode* container)
2590 if (!disableRangeMutation(page())) {
2591 HashSet<Range*>::const_iterator end = m_ranges.end();
2592 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2593 (*it)->nodeChildrenChanged(container);
2597 void Document::nodeWillBeRemoved(Node* n)
2599 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
2600 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
2601 (*it)->nodeWillBeRemoved(n);
2603 if (!disableRangeMutation(page())) {
2604 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
2605 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
2606 (*it)->nodeWillBeRemoved(n);
2609 if (Frame* frame = this->frame()) {
2610 frame->selection()->nodeWillBeRemoved(n);
2611 frame->dragCaretController()->nodeWillBeRemoved(n);
2615 void Document::textInserted(Node* text, unsigned offset, unsigned length)
2617 if (!disableRangeMutation(page())) {
2618 HashSet<Range*>::const_iterator end = m_ranges.end();
2619 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2620 (*it)->textInserted(text, offset, length);
2623 // Update the markers for spelling and grammar checking.
2624 shiftMarkers(text, offset, length);
2627 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
2629 if (!disableRangeMutation(page())) {
2630 HashSet<Range*>::const_iterator end = m_ranges.end();
2631 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2632 (*it)->textRemoved(text, offset, length);
2635 // Update the markers for spelling and grammar checking.
2636 removeMarkers(text, offset, length);
2637 shiftMarkers(text, offset + length, 0 - length);
2640 void Document::textNodesMerged(Text* oldNode, unsigned offset)
2642 if (!disableRangeMutation(page())) {
2643 NodeWithIndex oldNodeWithIndex(oldNode);
2644 HashSet<Range*>::const_iterator end = m_ranges.end();
2645 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2646 (*it)->textNodesMerged(oldNodeWithIndex, offset);
2649 // FIXME: This should update markers for spelling and grammar checking.
2652 void Document::textNodeSplit(Text* oldNode)
2654 if (!disableRangeMutation(page())) {
2655 HashSet<Range*>::const_iterator end = m_ranges.end();
2656 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2657 (*it)->textNodeSplit(oldNode);
2660 // FIXME: This should update markers for spelling and grammar checking.
2663 // FIXME: eventually, this should return a DOMWindow stored in the document.
2664 DOMWindow* Document::domWindow() const
2668 return frame()->domWindow();
2671 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
2673 if (eventType == "Event" || eventType == "Events" || eventType == "HTMLEvents")
2674 return Event::create();
2675 if (eventType == "KeyboardEvent" || eventType == "KeyboardEvents")
2676 return KeyboardEvent::create();
2677 if (eventType == "MessageEvent")
2678 return MessageEvent::create();
2679 if (eventType == "MouseEvent" || eventType == "MouseEvents")
2680 return MouseEvent::create();
2681 if (eventType == "MutationEvent" || eventType == "MutationEvents")
2682 return MutationEvent::create();
2683 if (eventType == "OverflowEvent")
2684 return OverflowEvent::create();
2685 if (eventType == "ProgressEvent")
2686 return ProgressEvent::create();
2687 #if ENABLE(DOM_STORAGE)
2688 if (eventType == "StorageEvent")
2689 return StorageEvent::create();
2691 if (eventType == "TextEvent")
2692 return TextEvent::create();
2693 if (eventType == "UIEvent" || eventType == "UIEvents")
2694 return UIEvent::create();
2695 if (eventType == "WebKitAnimationEvent")
2696 return WebKitAnimationEvent::create();
2697 if (eventType == "WebKitTransitionEvent")
2698 return WebKitTransitionEvent::create();
2699 if (eventType == "WheelEvent")
2700 return WheelEvent::create();
2702 if (eventType == "SVGEvents")
2703 return Event::create();
2704 if (eventType == "SVGZoomEvents")
2705 return SVGZoomEvent::create();
2707 ec = NOT_SUPPORTED_ERR;
2711 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
2713 if (eventType == eventNames().DOMSubtreeModifiedEvent)
2714 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
2715 else if (eventType == eventNames().DOMNodeInsertedEvent)
2716 addListenerType(DOMNODEINSERTED_LISTENER);
2717 else if (eventType == eventNames().DOMNodeRemovedEvent)
2718 addListenerType(DOMNODEREMOVED_LISTENER);
2719 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
2720 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
2721 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
2722 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
2723 else if (eventType == eventNames().DOMAttrModifiedEvent)
2724 addListenerType(DOMATTRMODIFIED_LISTENER);
2725 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
2726 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
2727 else if (eventType == eventNames().overflowchangedEvent)
2728 addListenerType(OVERFLOWCHANGED_LISTENER);
2729 else if (eventType == eventNames().webkitAnimationStartEvent)
2730 addListenerType(ANIMATIONSTART_LISTENER);
2731 else if (eventType == eventNames().webkitAnimationEndEvent)
2732 addListenerType(ANIMATIONEND_LISTENER);
2733 else if (eventType == eventNames().webkitAnimationIterationEvent)
2734 addListenerType(ANIMATIONITERATION_LISTENER);
2735 else if (eventType == eventNames().webkitTransitionEndEvent)
2736 addListenerType(TRANSITIONEND_LISTENER);
2739 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
2744 void Document::handleWindowEvent(Event* event, bool useCapture)
2746 if (m_windowEventListeners.isEmpty())
2749 // If any HTML event listeners are registered on the window, dispatch them here.
2750 RegisteredEventListenerVector listenersCopy = m_windowEventListeners;
2751 size_t size = listenersCopy.size();
2752 for (size_t i = 0; i < size; ++i) {
2753 RegisteredEventListener& r = *listenersCopy[i];
2754 if (r.eventType() == event->type() && r.useCapture() == useCapture && !r.removed())
2755 r.listener()->handleEvent(event, true);
2759 void Document::setWindowInlineEventListenerForType(const AtomicString& eventType, PassRefPtr<EventListener> listener)
2761 // If we already have it we don't want removeWindowEventListener to delete it
2762 removeWindowInlineEventListenerForType(eventType);
2764 addWindowEventListener(eventType, listener, false);
2767 EventListener* Document::windowInlineEventListenerForType(const AtomicString& eventType)
2769 size_t size = m_windowEventListeners.size();
2770 for (size_t i = 0; i < size; ++i) {
2771 RegisteredEventListener& r = *m_windowEventListeners[i];
2772 if (r.eventType() == eventType && r.listener()->isInline())
2773 return r.listener();
2778 void Document::removeWindowInlineEventListenerForType(const AtomicString& eventType)
2780 size_t size = m_windowEventListeners.size();
2781 for (size_t i = 0; i < size; ++i) {
2782 RegisteredEventListener& r = *m_windowEventListeners[i];
2783 if (r.eventType() == eventType && r.listener()->isInline()) {
2784 if (eventType == eventNames().unloadEvent)
2785 removePendingFrameUnloadEventCount();
2786 else if (eventType == eventNames().beforeunloadEvent)
2787 removePendingFrameBeforeUnloadEventCount();
2789 m_windowEventListeners.remove(i);
2795 void Document::addWindowEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2797 if (eventType == eventNames().unloadEvent)
2798 addPendingFrameUnloadEventCount();
2799 else if (eventType == eventNames().beforeunloadEvent)
2800 addPendingFrameBeforeUnloadEventCount();
2801 // Remove existing identical listener set with identical arguments.
2802 // The DOM 2 spec says that "duplicate instances are discarded" in this case.
2803 removeWindowEventListener(eventType, listener.get(), useCapture);
2804 addListenerTypeIfNeeded(eventType);
2805 m_windowEventListeners.append(RegisteredEventListener::create(eventType, listener, useCapture));
2808 void Document::removeWindowEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2810 size_t size = m_windowEventListeners.size();
2811 for (size_t i = 0; i < size; ++i) {
2812 RegisteredEventListener& r = *m_windowEventListeners[i];
2813 if (r.eventType() == eventType && r.listener() == listener && r.useCapture() == useCapture) {
2814 if (eventType == eventNames().unloadEvent)
2815 removePendingFrameUnloadEventCount();
2816 else if (eventType == eventNames().beforeunloadEvent)
2817 removePendingFrameBeforeUnloadEventCount();
2819 m_windowEventListeners.remove(i);
2825 bool Document::hasWindowEventListener(const AtomicString& eventType)
2827 size_t size = m_windowEventListeners.size();
2828 for (size_t i = 0; i < size; ++i) {
2829 if (m_windowEventListeners[i]->eventType() == eventType)
2835 void Document::addPendingFrameUnloadEventCount()
2838 m_frame->eventHandler()->addPendingFrameUnloadEventCount();
2841 void Document::removePendingFrameUnloadEventCount()
2844 m_frame->eventHandler()->removePendingFrameUnloadEventCount();
2847 void Document::addPendingFrameBeforeUnloadEventCount()
2850 m_frame->eventHandler()->addPendingFrameBeforeUnloadEventCount();
2853 void Document::removePendingFrameBeforeUnloadEventCount()
2856 m_frame->eventHandler()->removePendingFrameBeforeUnloadEventCount();
2859 PassRefPtr<EventListener> Document::createEventListener(const String& functionName, const String& code, Node* node)
2861 Frame* frm = frame();
2862 if (!frm || !frm->script()->isEnabled())
2866 if (node ? node->isSVGElement() : isSVGDocument())
2867 return frm->script()->createSVGEventHandler(functionName, code, node);
2870 // We may want to treat compound document event handlers in a different way, in future.
2871 return frm->script()->createInlineEventListener(functionName, code, node);
2874 void Document::setWindowInlineEventListenerForTypeAndAttribute(const AtomicString& eventType, Attribute* attr)
2876 setWindowInlineEventListenerForType(eventType, createEventListener(attr->localName().string(), attr->value(), 0));
2879 Element* Document::ownerElement() const
2883 return frame()->ownerElement();
2886 String Document::cookie() const
2888 if (page() && !page()->cookieEnabled())
2891 KURL cookieURL = this->cookieURL();
2892 if (cookieURL.isEmpty())
2895 return cookies(this, cookieURL);
2898 void Document::setCookie(const String& value)
2900 if (page() && !page()->cookieEnabled())
2903 KURL cookieURL = this->cookieURL();
2904 if (cookieURL.isEmpty())
2907 setCookies(this, cookieURL, policyBaseURL(), value);
2910 String Document::referrer() const
2913 return frame()->loader()->referrer();
2917 String Document::domain() const
2919 return securityOrigin()->domain();
2922 void Document::setDomain(const String& newDomain)
2924 // Both NS and IE specify that changing the domain is only allowed when
2925 // the new domain is a suffix of the old domain.
2927 // FIXME: We should add logging indicating why a domain was not allowed.
2929 // If the new domain is the same as the old domain, still call
2930 // securityOrigin()->setDomainForDOM. This will change the
2931 // security check behavior. For example, if a page loaded on port 8000
2932 // assigns its current domain using document.domain, the page will
2933 // allow other pages loaded on different ports in the same domain that
2934 // have also assigned to access this page.
2935 if (equalIgnoringCase(domain(), newDomain)) {
2936 securityOrigin()->setDomainFromDOM(newDomain);
2938 m_frame->script()->updateSecurityOrigin();
2942 int oldLength = domain().length();
2943 int newLength = newDomain.length();
2944 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
2945 if (newLength >= oldLength)
2948 String test = domain();
2949 // Check that it's a subdomain, not e.g. "ebkit.org"
2950 if (test[oldLength - newLength - 1] != '.')
2953 // Now test is "webkit.org" from domain()
2954 // and we check that it's the same thing as newDomain
2955 test.remove(0, oldLength - newLength);
2956 if (test != newDomain)
2959 securityOrigin()->setDomainFromDOM(newDomain);
2961 m_frame->script()->updateSecurityOrigin();
2964 String Document::lastModified() const
2969 DocumentLoader* loader = f->loader()->documentLoader();
2972 return loader->response().httpHeaderField("Last-Modified");
2975 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
2980 U16_NEXT(characters, i, length, c)
2981 if (!isValidNameStart(c))
2984 while (i < length) {
2985 U16_NEXT(characters, i, length, c)
2986 if (!isValidNamePart(c))
2993 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
2995 UChar c = characters[0];
2996 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
2999 for (unsigned i = 1; i < length; ++i) {
3001 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3008 bool Document::isValidName(const String& name)
3010 unsigned length = name.length();
3014 const UChar* characters = name.characters();
3015 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3018 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3020 unsigned length = qualifiedName.length();
3023 ec = INVALID_CHARACTER_ERR;
3027 bool nameStart = true;
3028 bool sawColon = false;
3031 const UChar* s = qualifiedName.characters();
3032 for (unsigned i = 0; i < length;) {
3034 U16_NEXT(s, i, length, c)
3038 return false; // multiple colons: not allowed
3043 } else if (nameStart) {
3044 if (!isValidNameStart(c)) {
3045 ec = INVALID_CHARACTER_ERR;
3050 if (!isValidNamePart(c)) {
3051 ec = INVALID_CHARACTER_ERR;
3059 localName = qualifiedName;
3061 prefix = qualifiedName.substring(0, colonPos);
3062 if (prefix.isEmpty()) {
3066 localName = qualifiedName.substring(colonPos + 1);
3069 if (localName.isEmpty()) {
3077 void Document::addImageMap(HTMLMapElement* imageMap)
3079 const AtomicString& name = imageMap->getName();
3083 // Add the image map, unless there's already another with that name.
3084 // "First map wins" is the rule other browsers seem to implement.
3085 m_imageMapsByName.add(name.impl(), imageMap);
3088 void Document::removeImageMap(HTMLMapElement* imageMap)
3090 // Remove the image map by name.
3091 // But don't remove some other image map that just happens to have the same name.
3092 // FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
3093 // once a map has been removed.
3094 const AtomicString& name = imageMap->getName();
3098 ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
3099 if (it != m_imageMapsByName.end() && it->second == imageMap)
3100 m_imageMapsByName.remove(it);
3103 HTMLMapElement *Document::getImageMap(const String& url) const
3107 int hashPos = url.find('#');
3108 String name = (hashPos < 0 ? url : url.substring(hashPos + 1)).impl();
3109 AtomicString mapName = isHTMLDocument() ? name.lower() : name;
3110 return m_imageMapsByName.get(mapName.impl());
3113 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3115 m_decoder = decoder;
3118 KURL Document::completeURL(const String& url) const
3120 // Always return a null URL when passed a null string.
3121 // FIXME: Should we change the KURL constructor to have this behavior?
3122 // See also [CSS]StyleSheet::completeURL(const String&)
3125 const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
3127 return KURL(baseURL, url);
3128 return KURL(baseURL, url, m_decoder->encoding());
3131 void Document::setInPageCache(bool flag)
3133 if (m_inPageCache == flag)
3136 m_inPageCache = flag;
3138 ASSERT(m_savedRenderer == 0);
3139 m_savedRenderer = renderer();
3140 if (FrameView* v = view())
3141 v->resetScrollbars();
3143 ASSERT(renderer() == 0 || renderer() == m_savedRenderer);
3144 ASSERT(m_renderArena);
3145 setRenderer(m_savedRenderer);
3146 m_savedRenderer = 0;
3150 void Document::documentWillBecomeInactive()
3152 #if USE(ACCELERATED_COMPOSITING)
3154 renderView()->willMoveOffscreen();
3157 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3158 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3159 (*i)->documentWillBecomeInactive();
3162 void Document::documentDidBecomeActive()
3164 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3165 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3166 (*i)->documentDidBecomeActive();
3168 #if USE(ACCELERATED_COMPOSITING)
3170 renderView()->didMoveOnscreen();
3174 void Document::registerForDocumentActivationCallbacks(Element* e)
3176 m_documentActivationCallbackElements.add(e);
3179 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3181 m_documentActivationCallbackElements.remove(e);
3184 void Document::mediaVolumeDidChange()
3186 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3187 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3188 (*i)->mediaVolumeDidChange();
3191 void Document::registerForMediaVolumeCallbacks(Element* e)
3193 m_mediaVolumeCallbackElements.add(e);
3196 void Document::unregisterForMediaVolumeCallbacks(Element* e)
3198 m_mediaVolumeCallbackElements.remove(e);
3201 void Document::setShouldCreateRenderers(bool f)
3203 m_createRenderers = f;
3206 bool Document::shouldCreateRenderers()
3208 return m_createRenderers;
3211 // Support for Javascript execCommand, and related methods
3213 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
3215 Frame* frame = document->frame();
3216 if (!frame || frame->document() != document)
3217 return Editor::Command();
3218 return frame->editor()->command(commandName,
3219 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
3222 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
3224 return command(this, commandName, userInterface).execute(value);
3227 bool Document::queryCommandEnabled(const String& commandName)
3229 return command(this, commandName).isEnabled();
3232 bool Document::queryCommandIndeterm(const String& commandName)
3234 return command(this, commandName).state() == MixedTriState;
3237 bool Document::queryCommandState(const String& commandName)
3239 return command(this, commandName).state() != FalseTriState;
3242 bool Document::queryCommandSupported(const String& commandName)
3244 return command(this, commandName).isSupported();
3247 String Document::queryCommandValue(const String& commandName)
3249 return command(this, commandName).value();
3252 static IntRect placeholderRectForMarker()
3254 return IntRect(-1, -1, -1, -1);
3257 void Document::addMarker(Range *range, DocumentMarker::MarkerType type, String description)
3259 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3260 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3261 RefPtr<Range> textPiece = markedText.range();
3263 DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception), description};
3264 addMarker(textPiece->startContainer(exception), marker);
3268 void Document::removeMarkers(Range* range, DocumentMarker::MarkerType markerType)
3270 if (m_markers.isEmpty())
3273 ExceptionCode ec = 0;
3274 Node* startContainer = range->startContainer(ec);
3275 Node* endContainer = range->endContainer(ec);
3277 Node* pastLastNode = range->pastLastNode();
3278 for (Node* node = range->firstNode(); node != pastLastNode; node = node->traverseNextNode()) {
3279 int startOffset = node == startContainer ? range->startOffset(ec) : 0;
3280 int endOffset = node == endContainer ? range->endOffset(ec) : INT_MAX;
3281 int length = endOffset - startOffset;
3282 removeMarkers(node, startOffset, length, markerType);
3286 // Markers are stored in order sorted by their start offset.
3287 // Markers of the same type do not overlap each other.
3289 void Document::addMarker(Node* node, DocumentMarker newMarker)
3291 ASSERT(newMarker.endOffset >= newMarker.startOffset);
3292 if (newMarker.endOffset == newMarker.startOffset)
3295 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3298 vectorPair = new MarkerMapVectorPair;
3299 vectorPair->first.append(newMarker);
3300 vectorPair->second.append(placeholderRectForMarker());
3301 m_markers.set(node, vectorPair);
3303 Vector<DocumentMarker>& markers = vectorPair->first;
3304 Vector<IntRect>& rects = vectorPair->second;
3305 size_t numMarkers = markers.size();
3306 ASSERT(numMarkers == rects.size());
3308 // Iterate over all markers whose start offset is less than or equal to the new marker's.
3309 // If one of them is of the same type as the new marker and touches it or intersects with it
3310 // (there is at most one), remove it and adjust the new marker's start offset to encompass it.
3311 for (i = 0; i < numMarkers; ++i) {
3312 DocumentMarker marker = markers[i];
3313 if (marker.startOffset > newMarker.startOffset)
3315 if (marker.type == newMarker.type && marker.endOffset >= newMarker.startOffset) {
3316 newMarker.startOffset = marker.startOffset;
3324 // Iterate over all markers whose end offset is less than or equal to the new marker's,
3325 // removing markers of the same type as the new marker which touch it or intersect with it,
3326 // adjusting the new marker's end offset to cover them if necessary.
3327 while (j < numMarkers) {
3328 DocumentMarker marker = markers[j];
3329 if (marker.startOffset > newMarker.endOffset)
3331 if (marker.type == newMarker.type) {
3334 if (newMarker.endOffset <= marker.endOffset) {
3335 newMarker.endOffset = marker.endOffset;
3342 // At this point i points to the node before which we want to insert.
3343 markers.insert(i, newMarker);
3344 rects.insert(i, placeholderRectForMarker());
3347 // repaint the affected node
3348 if (node->renderer())
3349 node->renderer()->repaint();
3352 // copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
3353 // useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
3354 void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
3359 MarkerMapVectorPair* vectorPair = m_markers.get(srcNode);
3363 ASSERT(vectorPair->first.size() == vectorPair->second.size());
3365 bool docDirty = false;
3366 unsigned endOffset = startOffset + length - 1;
3367 Vector<DocumentMarker>& markers = vectorPair->first;
3368 for (size_t i = 0; i != markers.size(); ++i) {
3369 DocumentMarker marker = markers[i];
3371 // stop if we are now past the specified range
3372 if (marker.startOffset > endOffset)
3375 // skip marker that is before the specified range or is the wrong type
3376 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
3379 // pin the marker to the specified range and apply the shift delta
3381 if (marker.startOffset < startOffset)
3382 marker.startOffset = startOffset;
3383 if (marker.endOffset > endOffset)
3384 marker.endOffset = endOffset;
3385 marker.startOffset += delta;
3386 marker.endOffset += delta;
3388 addMarker(dstNode, marker);
3391 // repaint the affected node
3392 if (docDirty && dstNode->renderer())
3393 dstNode->renderer()->repaint();
3396 void Document::removeMarkers(Node* node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
3401 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3405 Vector<DocumentMarker>& markers = vectorPair->first;
3406 Vector<IntRect>& rects = vectorPair->second;
3407 ASSERT(markers.size() == rects.size());
3408 bool docDirty = false;
3409 unsigned endOffset = startOffset + length;
3410 for (size_t i = 0; i < markers.size();) {
3411 DocumentMarker marker = markers[i];
3413 // markers are returned in order, so stop if we are now past the specified range
3414 if (marker.startOffset >= endOffset)
3417 // skip marker that is wrong type or before target
3418 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
3423 // at this point we know that marker and target intersect in some way
3426 // pitch the old marker and any associated rect
3430 // add either of the resulting slices that are left after removing target
3431 if (startOffset > marker.startOffset) {
3432 DocumentMarker newLeft = marker;
3433 newLeft.endOffset = startOffset;
3434 markers.insert(i, newLeft);
3435 rects.insert(i, placeholderRectForMarker());
3436 // i now points to the newly-inserted node, but we want to skip that one
3439 if (marker.endOffset > endOffset) {
3440 DocumentMarker newRight = marker;
3441 newRight.startOffset = endOffset;
3442 markers.insert(i, newRight);
3443 rects.insert(i, placeholderRectForMarker());
3444 // i now points to the newly-inserted node, but we want to skip that one
3449 if (markers.isEmpty()) {
3450 ASSERT(rects.isEmpty());
3451 m_markers.remove(node);
3455 // repaint the affected node
3456 if (docDirty && node->renderer())
3457 node->renderer()->repaint();
3460 DocumentMarker* Document::markerContainingPoint(const IntPoint& point, DocumentMarker::MarkerType markerType)
3462 // outer loop: process each node that contains any markers
3463 MarkerMap::iterator end = m_markers.end();
3464 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3465 // inner loop; process each marker in this node
3466 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3467 Vector<DocumentMarker>& markers = vectorPair->first;
3468 Vector<IntRect>& rects = vectorPair->second;
3469 ASSERT(markers.size() == rects.size());
3470 unsigned markerCount = markers.size();
3471 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3472 DocumentMarker& marker = markers[markerIndex];
3474 // skip marker that is wrong type
3475 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3478 IntRect& r = rects[markerIndex];
3480 // skip placeholder rects
3481 if (r == placeholderRectForMarker())
3484 if (r.contains(point))
3492 Vector<DocumentMarker> Document::markersForNode(Node* node)
3494 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3496 return vectorPair->first;
3497 return Vector<DocumentMarker>();
3500 Vector<IntRect> Document::renderedRectsForMarkers(DocumentMarker::MarkerType markerType)
3502 Vector<IntRect> result;
3504 // outer loop: process each node
3505 MarkerMap::iterator end = m_markers.end();
3506 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3507 // inner loop; process each marker in this node
3508 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3509 Vector<DocumentMarker>& markers = vectorPair->first;
3510 Vector<IntRect>& rects = vectorPair->second;
3511 ASSERT(markers.size() == rects.size());
3512 unsigned markerCount = markers.size();
3513 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3514 DocumentMarker marker = markers[markerIndex];
3516 // skip marker that is wrong type
3517 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3520 IntRect r = rects[markerIndex];
3521 // skip placeholder rects
3522 if (r == placeholderRectForMarker())
3532 void Document::removeMarkers(Node* node)
3534 MarkerMap::iterator i = m_markers.find(node);
3535 if (i != m_markers.end()) {
3537 m_markers.remove(i);
3538 if (RenderObject* renderer = node->renderer())
3539 renderer->repaint();
3543 void Document::removeMarkers(DocumentMarker::MarkerType markerType)
3545 // outer loop: process each markered node in the document
3546 MarkerMap markerMapCopy = m_markers;
3547 MarkerMap::iterator end = markerMapCopy.end();
3548 for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
3549 Node* node = i->first.get();
3550 bool nodeNeedsRepaint = false;
3552 // inner loop: process each marker in the current node
3553 MarkerMapVectorPair* vectorPair = i->second;
3554 Vector<DocumentMarker>& markers = vectorPair->first;
3555 Vector<IntRect>& rects = vectorPair->second;
3556 ASSERT(markers.size() == rects.size());
3557 for (size_t i = 0; i != markers.size();) {
3558 DocumentMarker marker = markers[i];
3560 // skip nodes that are not of the specified type
3561 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
3566 // pitch the old marker
3569 nodeNeedsRepaint = true;
3570 // markerIterator now points to the next node
3573 // Redraw the node if it changed. Do this before the node is removed from m_markers, since
3574 // m_markers might contain the last reference to the node.
3575 if (nodeNeedsRepaint) {
3576 RenderObject* renderer = node->renderer();
3578 renderer->repaint();
3581 // delete the node's list if it is now empty
3582 if (markers.isEmpty()) {
3583 ASSERT(rects.isEmpty());
3584 m_markers.remove(node);
3590 void Document::repaintMarkers(DocumentMarker::MarkerType markerType)
3592 // outer loop: process each markered node in the document
3593 MarkerMap::iterator end = m_markers.end();
3594 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3595 Node* node = i->first.get();
3597 // inner loop: process each marker in the current node
3598 MarkerMapVectorPair* vectorPair = i->second;
3599 Vector<DocumentMarker>& markers = vectorPair->first;
3600 bool nodeNeedsRepaint = false;
3601 for (size_t i = 0; i != markers.size(); ++i) {
3602 DocumentMarker marker = markers[i];
3604 // skip nodes that are not of the specified type
3605 if (marker.type == markerType || markerType == DocumentMarker::AllMarkers) {
3606 nodeNeedsRepaint = true;
3611 if (!nodeNeedsRepaint)
3614 // cause the node to be redrawn
3615 if (RenderObject* renderer = node->renderer())
3616 renderer->repaint();
3620 void Document::setRenderedRectForMarker(Node* node, DocumentMarker marker, const IntRect& r)
3622 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3624 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3628 Vector<DocumentMarker>& markers = vectorPair->first;
3629 ASSERT(markers.size() == vectorPair->second.size());
3630 unsigned markerCount = markers.size();
3631 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3632 DocumentMarker m = markers[markerIndex];
3634 vectorPair->second[markerIndex] = r;
3639 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3642 void Document::invalidateRenderedRectsForMarkersInRect(const IntRect& r)
3644 // outer loop: process each markered node in the document
3645 MarkerMap::iterator end = m_markers.end();
3646 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3648 // inner loop: process each rect in the current node
3649 MarkerMapVectorPair* vectorPair = i->second;
3650 Vector<IntRect>& rects = vectorPair->second;
3652 unsigned rectCount = rects.size();
3653 for (unsigned rectIndex = 0; rectIndex < rectCount; ++rectIndex)
3654 if (rects[rectIndex].intersects(r))
3655 rects[rectIndex] = placeholderRectForMarker();
3659 void Document::shiftMarkers(Node *node, unsigned startOffset, int delta, DocumentMarker::MarkerType markerType)
3661 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3665 Vector<DocumentMarker>& markers = vectorPair->first;
3666 Vector<IntRect>& rects = vectorPair->second;
3667 ASSERT(markers.size() == rects.size());
3669 bool docDirty = false;
3670 for (size_t i = 0; i != markers.size(); ++i) {
3671 DocumentMarker &marker = markers[i];
3672 if (marker.startOffset >= startOffset && (markerType == DocumentMarker::AllMarkers || marker.type == markerType)) {
3673 ASSERT((int)marker.startOffset + delta >= 0);
3674 marker.startOffset += delta;
3675 marker.endOffset += delta;
3678 // Marker moved, so previously-computed rendered rectangle is now invalid
3679 rects[i] = placeholderRectForMarker();
3683 // repaint the affected node
3684 if (docDirty && node->renderer())
3685 node->renderer()->repaint();
3690 void Document::applyXSLTransform(ProcessingInstruction* pi)
3692 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
3693 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
3694 String resultMIMEType;
3696 String resultEncoding;
3697 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
3699 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
3700 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
3703 void Document::setTransformSource(void* doc)
3705 if (doc == m_transformSource)
3708 xmlFreeDoc((xmlDocPtr)m_transformSource);
3709 m_transformSource = doc;
3714 void Document::setDesignMode(InheritedBool value)
3716 m_designMode = value;
3719 Document::InheritedBool Document::getDesignMode() const
3721 return m_designMode;
3724 bool Document::inDesignMode() const
3726 for (const Document* d = this; d; d = d->parentDocument()) {
3727 if (d->m_designMode != inherit)
3728 return d->m_designMode;
3733 Document *Document::parentDocument() const
3735 Frame *childPart = frame();
3738 Frame *parent = childPart->tree()->parent();
3741 return parent->document();
3744 Document *Document::topDocument() const
3746 Document *doc = const_cast<Document *>(this);
3748 while ((element = doc->ownerElement()))
3749 doc = element->document();
3754 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
3756 String prefix, localName;
3757 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
3760 QualifiedName qName(prefix, localName, namespaceURI);
3761 if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
3766 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
3767 if (!shouldIgnoreNamespaceChecks && qName.localName() == "xmlns" && qName.namespaceURI() != "http://www.w3.org/2000/xmlns/") {
3772 // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
3773 // documents if we're wrong.
3774 return new Attr(0, this, MappedAttribute::create(qName, StringImpl::empty()));
3778 const SVGDocumentExtensions* Document::svgExtensions()
3780 return m_svgExtensions.get();
3783 SVGDocumentExtensions* Document::accessSVGExtensions()
3785 if (!m_svgExtensions)
3786 m_svgExtensions.set(new SVGDocumentExtensions(this));
3787 return m_svgExtensions.get();
3791 PassRefPtr<HTMLCollection> Document::images()
3793 return HTMLCollection::create(this, HTMLCollection::DocImages);
3796 PassRefPtr<HTMLCollection> Document::applets()
3798 return HTMLCollection::create(this, HTMLCollection::DocApplets);
3801 PassRefPtr<HTMLCollection> Document::embeds()
3803 return HTMLCollection::create(this, HTMLCollection::DocEmbeds);
3806 PassRefPtr<HTMLCollection> Document::plugins()
3808 // This is an alias for embeds() required for the JS DOM bindings.
3809 return HTMLCollection::create(this, HTMLCollection::DocEmbeds);
3812 PassRefPtr<HTMLCollection> Document::objects()
3814 return HTMLCollection::create(this, HTMLCollection::DocObjects);
3817 PassRefPtr<HTMLCollection> Document::scripts()
3819 return HTMLCollection::create(this, HTMLCollection::DocScripts);
3822 PassRefPtr<HTMLCollection> Document::links()
3824 return HTMLCollection::create(this, HTMLCollection::DocLinks);
3827 PassRefPtr<HTMLCollection> Document::forms()
3829 return HTMLCollection::create(this, HTMLCollection::DocForms);
3832 PassRefPtr<HTMLCollection> Document::anchors()
3834 return HTMLCollection::create(this, HTMLCollection::DocAnchors);
3837 PassRefPtr<HTMLCollection> Document::all()
3839 return HTMLCollection::create(this, HTMLCollection::DocAll);
3842 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
3844 return HTMLNameCollection::create(this, HTMLCollection::WindowNamedItems, name);
3847 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
3849 return HTMLNameCollection::create(this, HTMLCollection::DocumentNamedItems, name);
3852 HTMLCollection::CollectionInfo* Document::nameCollectionInfo(HTMLCollection::Type type, const AtomicString& name)
3854 ASSERT(type >= HTMLCollection::FirstNamedDocumentCachedType);
3855 unsigned index = type - HTMLCollection::FirstNamedDocumentCachedType;
3856 ASSERT(index < HTMLCollection::NumNamedDocumentCachedTypes);
3858 NamedCollectionMap& map = m_nameCollectionInfo[index];
3859 NamedCollectionMap::iterator iter = map.find(name.impl());
3860 if (iter == map.end())
3861 iter = map.add(name.impl(), new HTMLCollection::CollectionInfo).first;
3862 return iter->second;
3865 void Document::finishedParsing()
3869 ExceptionCode ec = 0;
3870 dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false), ec);
3872 if (Frame* f = frame())
3873 f->loader()->finishedParsing();
3876 Vector<String> Document::formElementsState() const
3878 Vector<String> stateVector;
3879 stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
3880 typedef ListHashSet<FormControlElementWithState*>::const_iterator Iterator;
3881 Iterator end = m_formElementsWithState.end();
3882 for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
3883 FormControlElementWithState* e = *it;
3885 if (e->saveState(value)) {
3886 FormControlElement* formControlElement = e->toFormControlElement();
3887 ASSERT(formControlElement);
3889 stateVector.append(formControlElement->name().string());
3890 stateVector.append(formControlElement->type().string());
3891 stateVector.append(value);
3899 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
3900 XPathNSResolver* resolver,
3903 if (!m_xpathEvaluator)
3904 m_xpathEvaluator = XPathEvaluator::create();
3905 return m_xpathEvaluator->createExpression(expression, resolver, ec);
3908 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
3910 if (!m_xpathEvaluator)
3911 m_xpathEvaluator = XPathEvaluator::create();
3912 return m_xpathEvaluator->createNSResolver(nodeResolver);
3915 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
3917 XPathNSResolver* resolver,
3918 unsigned short type,
3919 XPathResult* result,
3922 if (!m_xpathEvaluator)
3923 m_xpathEvaluator = XPathEvaluator::create();
3924 return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
3927 #endif // ENABLE(XPATH)
3929 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
3931 // Walk the state vector backwards so that the value to use for each
3932 // name/type pair first is the one at the end of each individual vector
3933 // in the FormElementStateMap. We're using them like stacks.
3934 typedef FormElementStateMap::iterator Iterator;
3935 m_formElementsWithState.clear();
3936 for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
3937 AtomicString a = stateVector[i - 3];
3938 AtomicString b = stateVector[i - 2];
3939 const String& c = stateVector[i - 1];
3940 FormElementKey key(a.impl(), b.impl());
3941 Iterator it = m_stateForNewFormElements.find(key);
3942 if (it != m_stateForNewFormElements.end())
3943 it->second.append(c);
3945 Vector<String> v(1);
3947 m_stateForNewFormElements.set(key, v);
3952 bool Document::hasStateForNewFormElements() const
3954 return !m_stateForNewFormElements.isEmpty();
3957 bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
3959 typedef FormElementStateMap::iterator Iterator;
3960 Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
3961 if (it == m_stateForNewFormElements.end())
3963 ASSERT(it->second.size());
3964 state = it->second.last();
3965 if (it->second.size() > 1)
3966 it->second.removeLast();
3968 m_stateForNewFormElements.remove(it);
3972 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
3973 : m_name(name), m_type(type)
3978 FormElementKey::~FormElementKey()
3983 FormElementKey::FormElementKey(const FormElementKey& other)
3984 : m_name(other.name()), m_type(other.type())
3989 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
3993 m_name = other.name();
3994 m_type = other.type();
3998 void FormElementKey::ref() const
4006 void FormElementKey::deref() const
4014 unsigned FormElementKeyHash::hash(const FormElementKey& k)
4016 ASSERT(sizeof(k) % (sizeof(uint16_t) * 2) == 0);
4018 unsigned l = sizeof(k) / (sizeof(uint16_t) * 2);
4019 const uint16_t* s = reinterpret_cast<const uint16_t*>(&k);
4020 uint32_t hash = WTF::stringHashingStartValue;
4023 for (; l > 0; l--) {
4025 uint32_t tmp = (s[1] << 11) ^ hash;
4026 hash = (hash << 16) ^ tmp;
4031 // Force "avalanching" of final 127 bits
4038 // this avoids ever returning a hash code of 0, since that is used to
4039 // signal "hash not computed yet", using a value that is likely to be
4040 // effectively the same as 0 when the low bits are masked
4047 void Document::setIconURL(const String& iconURL, const String& type)
4049 // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "type"
4050 if (m_iconURL.isEmpty())
4051 m_iconURL = iconURL;
4052 else if (!type.isEmpty())
4053 m_iconURL = iconURL;
4056 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4058 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4061 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4062 m_frame->updateSecureKeyboardEntryIfActive();
4065 bool Document::useSecureKeyboardEntryWhenActive() const
4067 return m_useSecureKeyboardEntryWhenActive;
4070 void Document::initSecurityContext()
4072 if (securityOrigin() && !securityOrigin()->isEmpty())
4073 return; // m_securityOrigin has already been initialized.
4076 // No source for a security context.
4077 // This can occur via document.implementation.createDocument().
4078 m_cookieURL = KURL("");
4079 ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::createEmpty());
4083 // In the common case, create the security context from the currently
4085 const KURL& url = m_frame->loader()->url();
4087 ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::create(url));
4089 if (FrameLoader::allowSubstituteDataAccessToLocal()) {
4090 // If this document was loaded with substituteData, then the document can
4091 // load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
4092 // and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
4094 DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
4095 if (documentLoader && documentLoader->substituteData().isValid())
4096 securityOrigin()->grantLoadLocalResources();
4099 if (Settings* settings = this->settings()) {
4100 if (!settings->isWebSecurityEnabled()) {
4101 // Web security is turned off. We should let this document access every
4102 // other document. This is used primary by testing harnesses for web
4104 securityOrigin()->grantUniversalAccess();
4106 } else if (settings->allowUniversalAccessFromFileURLs() && securityOrigin()->isLocal()) {
4107 // Some clients want file:// URLs to have universal access, but that
4108 // setting is dangerous for other clients.
4109 securityOrigin()->grantUniversalAccess();
4113 if (!securityOrigin()->isEmpty())
4116 // If we do not obtain a meaningful origin from the URL, then we try to
4117 // find one via the frame hierarchy.
4119 Frame* ownerFrame = m_frame->tree()->parent();
4121 ownerFrame = m_frame->loader()->opener();
4124 m_cookieURL = ownerFrame->document()->cookieURL();
4125 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4126 // https://bugs.webkit.org/show_bug.cgi?id=15313
4127 ScriptExecutionContext::setSecurityOrigin(ownerFrame->document()->securityOrigin());
4131 void Document::setSecurityOrigin(SecurityOrigin* securityOrigin)
4133 ScriptExecutionContext::setSecurityOrigin(securityOrigin);
4134 // FIXME: Find a better place to enable DNS prefetch, which is a loader concept,
4135 // not applicable to arbitrary documents.
4139 void Document::updateFocusAppearanceSoon()
4141 if (!m_updateFocusAppearanceTimer.isActive())
4142 m_updateFocusAppearanceTimer.startOneShot(0);
4145 void Document::cancelFocusAppearanceUpdate()
4147 m_updateFocusAppearanceTimer.stop();
4150 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4152 Node* node = focusedNode();
4155 if (!node->isElementNode())
4160 Element* element = static_cast<Element*>(node);
4161 if (element->isFocusable())
4162 element->updateFocusAppearance(false);
4165 // FF method for accessing the selection added for compatability.
4166 DOMSelection* Document::getSelection() const
4168 return frame() ? frame()->domWindow()->getSelection() : 0;
4171 #if ENABLE(DATABASE)
4173 void Document::addOpenDatabase(Database* database)
4175 if (!m_openDatabaseSet)
4176 m_openDatabaseSet.set(new DatabaseSet);
4178 ASSERT(!m_openDatabaseSet->contains(database));
4179 m_openDatabaseSet->add(database);
4182 void Document::removeOpenDatabase(Database* database)
4184 ASSERT(m_openDatabaseSet && m_openDatabaseSet->contains(database));
4185 if (!m_openDatabaseSet)
4188 m_openDatabaseSet->remove(database);
4191 DatabaseThread* Document::databaseThread()
4193 if (!m_databaseThread && !m_hasOpenDatabases) {
4194 // Create the database thread on first request - but not if at least one database was already opened,
4195 // because in that case we already had a database thread and terminated it and should not create another.
4196 m_databaseThread = DatabaseThread::create();
4197 if (!m_databaseThread->start())
4198 m_databaseThread = 0;
4201 return m_databaseThread.get();
4204 void Document::stopDatabases()
4206 if (m_openDatabaseSet) {
4207 DatabaseSet::iterator i = m_openDatabaseSet->begin();
4208 DatabaseSet::iterator end = m_openDatabaseSet->end();
4209 for (; i != end; ++i) {
4211 if (m_databaseThread)
4212 m_databaseThread->unscheduleDatabaseTasks(*i);
4216 if (m_databaseThread)
4217 m_databaseThread->requestTermination();
4223 void Document::resetWMLPageState()
4225 if (WMLPageState* pageState = wmlPageStateForDocument(this))
4230 void Document::attachRange(Range* range)
4232 ASSERT(!m_ranges.contains(range));
4233 m_ranges.add(range);
4236 void Document::detachRange(Range* range)
4238 ASSERT(m_ranges.contains(range));
4239 m_ranges.remove(range);
4242 CanvasRenderingContext2D* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
4244 HTMLCanvasElement* result = getCSSCanvasElement(name);
4247 result->setSize(IntSize(width, height));
4248 return result->getContext(type);
4251 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
4253 RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
4255 result = new HTMLCanvasElement(canvasTag, this);
4256 m_cssCanvasElements.set(name, result);
4258 return result.get();
4261 void Document::initDNSPrefetch()
4263 m_haveExplicitlyDisabledDNSPrefetch = false;
4264 m_isDNSPrefetchEnabled = securityOrigin()->protocol() == "http";
4266 // Inherit DNS prefetch opt-out from parent frame
4267 if (Document* parent = parentDocument()) {
4268 if (!parent->isDNSPrefetchEnabled())
4269 m_isDNSPrefetchEnabled = false;
4273 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4275 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4276 m_isDNSPrefetchEnabled = true;
4280 m_isDNSPrefetchEnabled = false;
4281 m_haveExplicitlyDisabledDNSPrefetch = true;
4284 void Document::reportException(const String& errorMessage, int lineNumber, const String& sourceURL)
4286 if (DOMWindow* window = domWindow())
4287 window->console()->addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, lineNumber, sourceURL);
4290 void Document::addMessage(MessageDestination destination, MessageSource source, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
4292 switch (destination) {
4293 case InspectorControllerDestination:
4295 page()->inspectorController()->addMessageToConsole(source, level, message, lineNumber, sourceURL);
4297 case ConsoleDestination:
4298 if (DOMWindow* window = domWindow())
4299 window->console()->addMessage(source, level, message, lineNumber, sourceURL);
4302 ASSERT_NOT_REACHED();
4305 void Document::resourceRetrievedByXMLHttpRequest(unsigned long identifier, const ScriptString& sourceString)
4308 page()->inspectorController()->resourceRetrievedByXMLHttpRequest(identifier, sourceString);
4311 void Document::scriptImported(unsigned long identifier, const String& sourceString)
4314 page()->inspectorController()->scriptImported(identifier, sourceString);
4317 class ScriptExecutionContextTaskTimer : public TimerBase {
4319 ScriptExecutionContextTaskTimer(PassRefPtr<Document> context, PassRefPtr<ScriptExecutionContext::Task> task)
4320 : m_context(context)
4326 virtual void fired()
4328 m_task->performTask(m_context.get());
4332 RefPtr<Document> m_context;
4333 RefPtr<ScriptExecutionContext::Task> m_task;
4336 struct PerformTaskContext {
4337 PerformTaskContext(ScriptExecutionContext* scriptExecutionContext, PassRefPtr<ScriptExecutionContext::Task> task)
4338 : scriptExecutionContext(scriptExecutionContext)
4343 ScriptExecutionContext* scriptExecutionContext; // The context should exist until task execution.
4344 RefPtr<ScriptExecutionContext::Task> task;
4347 static void performTask(void* ctx)
4349 PerformTaskContext* ptctx = reinterpret_cast<PerformTaskContext*>(ctx);
4350 ptctx->task->performTask(ptctx->scriptExecutionContext);
4354 void Document::postTask(PassRefPtr<Task> task)
4356 if (isMainThread()) {
4357 ScriptExecutionContextTaskTimer* timer = new ScriptExecutionContextTaskTimer(static_cast<Document*>(this), task);
4358 timer->startOneShot(0);
4360 callOnMainThread(performTask, new PerformTaskContext(this, task));
4364 Element* Document::findAnchor(const String& name)
4368 if (Element* element = getElementById(name))
4370 for (Node* node = this; node; node = node->traverseNextNode()) {
4371 if (node->hasTagName(aTag)) {
4372 HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(node);
4373 if (inCompatMode()) {
4374 // Quirks mode, case insensitive comparison of names.
4375 if (equalIgnoringCase(anchor->name(), name))
4378 // Strict mode, names need to matc