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 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved.
8 * http://www.torchmobile.com/
9 * Copyright (C) 2008 David Levin (levin@chromium.org)
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
30 #include "AnimationController.h"
31 #include "AXObjectCache.h"
32 #include "CDATASection.h"
33 #include "CSSHelper.h"
34 #include "CSSStyleSelector.h"
35 #include "CSSStyleSheet.h"
36 #include "CSSValueKeywords.h"
38 #include "CachedCSSStyleSheet.h"
41 #include "CookieJar.h"
42 #include "DOMImplementation.h"
44 #include "DOMWindow.h"
45 #include "DocLoader.h"
46 #include "DocumentFragment.h"
47 #include "DocumentLoader.h"
48 #include "DocumentType.h"
49 #include "EditingText.h"
51 #include "EntityReference.h"
53 #include "EventHandler.h"
54 #include "EventListener.h"
55 #include "EventNames.h"
56 #include "ExceptionCode.h"
57 #include "FocusController.h"
59 #include "FrameLoader.h"
60 #include "FrameTree.h"
61 #include "FrameView.h"
62 #include "HTMLBodyElement.h"
63 #include "HTMLCanvasElement.h"
64 #include "HTMLDocument.h"
65 #include "HTMLElementFactory.h"
66 #include "HTMLFrameOwnerElement.h"
67 #include "HTMLHeadElement.h"
68 #include "HTMLInputElement.h"
69 #include "HTMLLinkElement.h"
70 #include "HTMLMapElement.h"
71 #include "HTMLNameCollection.h"
72 #include "HTMLNames.h"
73 #include "HTMLStyleElement.h"
74 #include "HTMLTitleElement.h"
75 #include "HTTPParsers.h"
76 #include "HistoryItem.h"
77 #include "HitTestRequest.h"
78 #include "HitTestResult.h"
79 #include "ImageLoader.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 "RegularExpression.h"
97 #include "RenderArena.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 "SystemTime.h"
107 #include "TextEvent.h"
108 #include "TextIterator.h"
109 #include "TextResourceDecoder.h"
110 #include "TreeWalker.h"
113 #include "WebKitAnimationEvent.h"
114 #include "WebKitTransitionEvent.h"
115 #include "WheelEvent.h"
116 #include "XMLHttpRequest.h"
117 #include "XMLNames.h"
118 #include "XMLTokenizer.h"
119 #include "JSDOMBinding.h"
120 #include "ScriptController.h"
121 #include <wtf/MainThread.h>
122 #include <wtf/StdLibExtras.h>
123 #include <wtf/PassRefPtr.h>
126 #include "Database.h"
127 #include "DatabaseThread.h"
131 #include "XPathEvaluator.h"
132 #include "XPathExpression.h"
133 #include "XPathNSResolver.h"
134 #include "XPathResult.h"
138 #include "XSLTProcessor.h"
142 #include "XBLBindingManager.h"
146 #include "SVGDocumentExtensions.h"
147 #include "SVGElementFactory.h"
148 #include "SVGZoomEvent.h"
149 #include "SVGStyleElement.h"
153 #include "WMLDocument.h"
154 #include "WMLElement.h"
155 #include "WMLElementFactory.h"
156 #include "WMLNames.h"
161 using namespace Unicode;
165 using namespace HTMLNames;
167 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
169 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
170 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
172 static const int cLayoutScheduleThreshold = 250;
174 // Use 1 to represent the document's default form.
175 static HTMLFormElement* const defaultForm = reinterpret_cast<HTMLFormElement*>(1);
177 // Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
178 static const unsigned PHI = 0x9e3779b9U;
180 // DOM Level 2 says (letters added):
182 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
183 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
184 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
185 // 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.
186 // 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.
187 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
188 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
189 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
190 // i) Characters ':' and '_' are allowed as name-start characters.
191 // j) Characters '-' and '.' are allowed as name characters.
193 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
195 static inline bool isValidNameStart(UChar32 c)
198 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
202 if (c == ':' || c == '_')
205 // rules (a) and (f) above
206 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
207 if (!(Unicode::category(c) & nameStartMask))
211 if (c >= 0xF900 && c < 0xFFFE)
215 DecompositionType decompType = decompositionType(c);
216 if (decompType == DecompositionFont || decompType == DecompositionCompat)
222 static inline bool isValidNamePart(UChar32 c)
224 // rules (a), (e), and (i) above
225 if (isValidNameStart(c))
228 // rules (g) and (h) above
229 if (c == 0x00B7 || c == 0x0387)
233 if (c == '-' || c == '.')
236 // rules (b) and (f) above
237 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
238 if (!(Unicode::category(c) & otherNamePartMask))
242 if (c >= 0xF900 && c < 0xFFFE)
246 DecompositionType decompType = decompositionType(c);
247 if (decompType == DecompositionFont || decompType == DecompositionCompat)
253 static Widget* widgetForNode(Node* focusedNode)
257 RenderObject* renderer = focusedNode->renderer();
258 if (!renderer || !renderer->isWidget())
260 return static_cast<RenderWidget*>(renderer)->widget();
263 static bool acceptsEditingFocus(Node *node)
266 ASSERT(node->isContentEditable());
268 Node *root = node->rootEditableElement();
269 Frame* frame = node->document()->frame();
273 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
276 static HashSet<Document*>* changedDocuments = 0;
278 Document::Document(Frame* frame, bool isXHTML)
280 , m_domtree_version(0)
281 , m_styleSheets(StyleSheetList::create(this))
283 , m_titleSetExplicitly(false)
284 , m_imageLoadEventTimer(this, &Document::imageLoadEventTimerFired)
285 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
287 , m_transformSource(0)
289 , m_xmlVersion("1.0")
290 , m_xmlStandalone(false)
292 , m_bindingManager(new XBLBindingManager(this))
296 , m_designMode(inherit)
297 , m_selfOnlyRefCount(0)
301 #if ENABLE(DASHBOARD_SUPPORT)
302 , m_hasDashboardRegions(false)
303 , m_dashboardRegionsDirty(false)
305 , m_accessKeyMapValid(false)
306 , m_createRenderers(true)
307 , m_inPageCache(false)
308 , m_useSecureKeyboardEntryWhenActive(false)
310 , m_numNodeListCaches(0)
312 , m_hasOpenDatabases(false)
314 , m_usingGeolocation(false)
315 #if USE(LOW_BANDWIDTH_DISPLAY)
316 , m_inLowBandwidthDisplay(false)
319 m_document.resetSkippingRef(this);
323 m_ignoreAutofocus = false;
330 m_docLoader = new DocLoader(this);
332 visuallyOrdered = false;
334 m_docChanged = false;
336 m_wellFormed = false;
338 setParseMode(Strict);
340 m_textColor = Color::black;
343 m_inStyleRecalc = false;
344 m_closeAfterStyleRecalc = false;
345 m_usesDescendantRules = false;
346 m_usesSiblingRules = false;
347 m_usesFirstLineRules = false;
348 m_usesFirstLetterRules = false;
349 m_gotoAnchorNeededAfterStylesheetsLoad = false;
352 m_didCalculateStyleSelector = false;
353 m_pendingStylesheets = 0;
354 m_ignorePendingStylesheets = false;
355 m_hasNodesWithPlaceholderStyle = false;
356 m_pendingSheetLayout = NoLayoutWithPendingSheets;
361 resetVisitedLinkColor();
362 resetActiveLinkColor();
364 m_processingLoadEvent = false;
365 m_startTime = currentTime();
366 m_overMinimumLayoutThreshold = false;
368 initSecurityContext();
371 static int docID = 0;
375 void Document::removedLastRef()
377 ASSERT(!m_deletionHasBegun);
378 if (m_selfOnlyRefCount) {
379 // If removing a child removes the last self-only ref, we don't
380 // want the document to be destructed until after
381 // removeAllChildren returns, so we guard ourselves with an
382 // extra self-only ref.
384 DocPtr<Document> guard(this);
386 // We must make sure not to be retaining any of our children through
387 // these extra pointers or we will create a reference cycle.
393 m_documentElement = 0;
397 deleteAllValues(m_markers);
403 m_cssCanvasElements.clear();
406 m_inRemovedLastRefFunction = false;
410 m_deletionHasBegun = true;
416 Document::~Document()
419 ASSERT(!m_inPageCache);
420 ASSERT(!m_savedRenderer);
421 ASSERT(m_ranges.isEmpty());
423 removeAllEventListeners();
425 forgetAllDOMNodesForDocument(this);
427 if (m_docChanged && changedDocuments)
428 changedDocuments->remove(this);
430 m_document.resetSkippingRef(0);
431 delete m_styleSelector;
435 delete m_renderArena;
440 xmlFreeDoc((xmlDocPtr)m_transformSource);
444 delete m_bindingManager;
447 deleteAllValues(m_markers);
449 clearAXObjectCache();
453 unsigned count = sizeof(m_nameCollectionInfo) / sizeof(m_nameCollectionInfo[0]);
454 for (unsigned i = 0; i < count; i++)
455 deleteAllValues(m_nameCollectionInfo[i]);
458 if (m_databaseThread) {
459 ASSERT(m_databaseThread->terminationRequested());
460 m_databaseThread = 0;
465 m_styleSheets->documentDestroyed();
470 void Document::resetLinkColor()
472 m_linkColor = Color(0, 0, 238);
475 void Document::resetVisitedLinkColor()
477 m_visitedLinkColor = Color(85, 26, 139);
480 void Document::resetActiveLinkColor()
482 m_activeLinkColor.setNamedColor("red");
485 void Document::setDocType(PassRefPtr<DocumentType> docType)
487 // This should never be called more than once.
488 // Note: This is not a public DOM method and can only be called by the parser.
489 ASSERT(!m_docType || !docType);
490 if (m_docType && docType)
494 m_docType->setDocument(this);
495 determineParseMode();
498 DOMImplementation* Document::implementation() const
500 if (!m_implementation)
501 m_implementation = DOMImplementation::create();
502 return m_implementation.get();
505 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
507 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
509 // Invalidate the document element we have cached in case it was replaced.
510 m_documentElement = 0;
513 Element* Document::documentElement() const
515 if (!m_documentElement) {
516 Node* n = firstChild();
517 while (n && !n->isElementNode())
518 n = n->nextSibling();
519 m_documentElement = static_cast<Element*>(n);
522 return m_documentElement.get();
525 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
527 if (!isValidName(name)) {
528 ec = INVALID_CHARACTER_ERR;
533 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
535 return createElement(QualifiedName(nullAtom, name, nullAtom), false, ec);
538 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
540 return new DocumentFragment(document());
543 PassRefPtr<Text> Document::createTextNode(const String& data)
545 return new Text(this, data);
548 PassRefPtr<Comment> Document::createComment(const String& data)
550 return new Comment(this, data);
553 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
555 if (isHTMLDocument()) {
556 ec = NOT_SUPPORTED_ERR;
559 return new CDATASection(this, data);
562 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
564 if (!isValidName(target)) {
565 ec = INVALID_CHARACTER_ERR;
568 if (isHTMLDocument()) {
569 ec = NOT_SUPPORTED_ERR;
572 return new ProcessingInstruction(this, target, data);
575 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
577 if (!isValidName(name)) {
578 ec = INVALID_CHARACTER_ERR;
581 if (isHTMLDocument()) {
582 ec = NOT_SUPPORTED_ERR;
585 return new EntityReference(this, name);
588 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
590 return new EditingText(this, text);
593 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
595 return CSSMutableStyleDeclaration::create();
598 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
603 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
604 || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
607 ec = NOT_SUPPORTED_ERR;
611 switch (importedNode->nodeType()) {
613 return createTextNode(importedNode->nodeValue());
614 case CDATA_SECTION_NODE:
615 return createCDATASection(importedNode->nodeValue(), ec);
616 case ENTITY_REFERENCE_NODE:
617 return createEntityReference(importedNode->nodeName(), ec);
618 case PROCESSING_INSTRUCTION_NODE:
619 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
621 return createComment(importedNode->nodeValue());
623 Element* oldElement = static_cast<Element*>(importedNode);
624 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
629 NamedAttrMap* attrs = oldElement->attributes(true);
631 unsigned length = attrs->length();
632 for (unsigned i = 0; i < length; i++) {
633 Attribute* attr = attrs->attributeItem(i);
634 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
640 newElement->copyNonAttributeProperties(oldElement);
643 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
644 RefPtr<Node> newChild = importNode(oldChild, true, ec);
647 newElement->appendChild(newChild.release(), ec);
653 return newElement.release();
655 case ATTRIBUTE_NODE: {
656 RefPtr<Attr> newAttr = new Attr(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
657 newAttr->createTextChild();
658 return newAttr.release();
660 case DOCUMENT_FRAGMENT_NODE: {
661 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
662 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
664 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
665 RefPtr<Node> newChild = importNode(oldChild, true, ec);
668 newFragment->appendChild(newChild.release(), ec);
674 return newFragment.release();
678 // 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.
679 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
681 case DOCUMENT_TYPE_NODE:
682 case XPATH_NAMESPACE_NODE:
686 ec = NOT_SUPPORTED_ERR;
691 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
694 ec = NOT_SUPPORTED_ERR;
698 if (source->isReadOnlyNode()) {
699 ec = NO_MODIFICATION_ALLOWED_ERR;
703 switch (source->nodeType()) {
707 case DOCUMENT_TYPE_NODE:
708 case XPATH_NAMESPACE_NODE:
709 ec = NOT_SUPPORTED_ERR;
711 case ATTRIBUTE_NODE: {
712 Attr* attr = static_cast<Attr*>(source.get());
713 if (attr->ownerElement())
714 attr->ownerElement()->removeAttributeNode(attr, ec);
715 attr->setSpecified(true);
719 if (source->parentNode())
720 source->parentNode()->removeChild(source.get(), ec);
723 for (Node* node = source.get(); node; node = node->traverseNextNode(source.get()))
724 node->setDocument(this);
729 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
731 DEFINE_STATIC_LOCAL(const AtomicString, xmlnsNamespaceURI, ("http://www.w3.org/2000/xmlns/"));
732 DEFINE_STATIC_LOCAL(const AtomicString, xmlns, ("xmlns"));
733 DEFINE_STATIC_LOCAL(const AtomicString, xml, ("xml"));
735 // These checks are from DOM Core Level 2, createElementNS
736 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
737 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
739 if (qName.prefix() == xml && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
742 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
743 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
744 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
745 if ((qName.prefix() == xmlns && qName.namespaceURI() != xmlnsNamespaceURI) || (qName.prefix() != xmlns && qName.namespaceURI() == xmlnsNamespaceURI))
751 // FIXME: This should really be in a possible ElementFactory class
752 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser, ExceptionCode& ec)
756 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
757 if (qName.namespaceURI() == xhtmlNamespaceURI)
758 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
760 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
761 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
764 else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI || isWMLDocument())
765 e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
769 e = new Element(qName, document());
771 // FIXME: The element factories should be fixed to not ignore qName.prefix()
772 // Instead they should pass the entire qName into element creation so we don't
773 // need to manually set the prefix after creation.
774 // Then this code can become ASSERT(qName == e.qname());
775 // and Document::createElement can stop taking ExceptionCode& as well.
776 if (e && !qName.prefix().isNull()) {
778 e->setPrefix(qName.prefix(), ec);
786 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
788 String prefix, localName;
789 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
792 QualifiedName qName(prefix, localName, namespaceURI);
793 if (hasPrefixNamespaceMismatch(qName)) {
798 return createElement(qName, false, ec);
801 Element* Document::getElementById(const AtomicString& elementId) const
803 if (elementId.isEmpty())
806 Element* element = m_elementsById.get(elementId.impl());
810 if (m_duplicateIds.contains(elementId.impl())) {
811 // We know there's at least one node with this id, but we don't know what the first one is.
812 for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
813 if (n->isElementNode()) {
814 element = static_cast<Element*>(n);
815 if (element->hasID() && element->getAttribute(idAttr) == elementId) {
816 m_duplicateIds.remove(elementId.impl());
817 m_elementsById.set(elementId.impl(), element);
822 ASSERT_NOT_REACHED();
827 String Document::readyState() const
829 if (Frame* f = frame()) {
830 if (f->loader()->isComplete())
835 // FIXME: What does "interactive" mean?
836 // FIXME: Missing support for "uninitialized".
841 String Document::inputEncoding() const
843 if (TextResourceDecoder* d = decoder())
844 return d->encoding().name();
848 String Document::defaultCharset() const
850 if (Settings* settings = this->settings())
851 return settings->defaultTextEncodingName();
855 void Document::setCharset(const String& charset)
859 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
862 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
864 if (!implementation()->hasFeature("XML", String())) {
865 ec = NOT_SUPPORTED_ERR;
869 // FIXME: Also raise NOT_SUPPORTED_ERR if the version is set to a value that is not supported by this Document.
871 m_xmlVersion = version;
874 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
876 if (!implementation()->hasFeature("XML", String())) {
877 ec = NOT_SUPPORTED_ERR;
881 m_xmlStandalone = standalone;
884 void Document::setDocumentURI(const String& uri)
890 KURL Document::baseURI() const
895 Element* Document::elementFromPoint(int x, int y) const
900 HitTestRequest request(true, true);
901 HitTestResult result(IntPoint(x, y));
902 renderer()->layer()->hitTest(request, result);
904 Node* n = result.innerNode();
905 while (n && !n->isElementNode())
908 n = n->shadowAncestorNode();
909 return static_cast<Element*>(n);
912 void Document::addElementById(const AtomicString& elementId, Element* element)
914 typedef HashMap<AtomicStringImpl*, Element*>::iterator iterator;
915 if (!m_duplicateIds.contains(elementId.impl())) {
916 // Fast path. The ID is not already in m_duplicateIds, so we assume that it's
917 // also not already in m_elementsById and do an add. If that add succeeds, we're done.
918 pair<iterator, bool> addResult = m_elementsById.add(elementId.impl(), element);
919 if (addResult.second)
921 // The add failed, so this ID was already cached in m_elementsById.
922 // There are multiple elements with this ID. Remove the m_elementsById
923 // cache for this ID so getElementById searches for it next time it is called.
924 m_elementsById.remove(addResult.first);
925 m_duplicateIds.add(elementId.impl());
927 // There are multiple elements with this ID. If it exists, remove the m_elementsById
928 // cache for this ID so getElementById searches for it next time it is called.
929 iterator cachedItem = m_elementsById.find(elementId.impl());
930 if (cachedItem != m_elementsById.end()) {
931 m_elementsById.remove(cachedItem);
932 m_duplicateIds.add(elementId.impl());
935 m_duplicateIds.add(elementId.impl());
938 void Document::removeElementById(const AtomicString& elementId, Element* element)
940 if (m_elementsById.get(elementId.impl()) == element)
941 m_elementsById.remove(elementId.impl());
943 m_duplicateIds.remove(elementId.impl());
946 Element* Document::getElementByAccessKey(const String& key) const
950 if (!m_accessKeyMapValid) {
951 for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
952 if (!n->isElementNode())
954 Element* element = static_cast<Element*>(n);
955 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
956 if (!accessKey.isEmpty())
957 m_elementsByAccessKey.set(accessKey.impl(), element);
959 m_accessKeyMapValid = true;
961 return m_elementsByAccessKey.get(key.impl());
964 void Document::updateTitle()
966 if (Frame* f = frame())
967 f->loader()->setTitle(m_title);
970 void Document::setTitle(const String& title, Element* titleElement)
973 // Title set by JavaScript -- overrides any title elements.
974 m_titleSetExplicitly = true;
975 if (!isHTMLDocument())
977 else if (!m_titleElement) {
978 if (HTMLElement* headElement = head()) {
979 ExceptionCode ec = 0;
980 m_titleElement = createElement("title", ec);
982 headElement->appendChild(m_titleElement, ec);
986 } else if (titleElement != m_titleElement) {
987 if (m_titleElement || m_titleSetExplicitly)
988 // Only allow the first title element to change the title -- others have no effect.
990 m_titleElement = titleElement;
993 if (m_title == title)
999 if (m_titleSetExplicitly && m_titleElement && m_titleElement->hasTagName(titleTag))
1000 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(m_title);
1003 void Document::removeTitle(Element* titleElement)
1005 if (m_titleElement != titleElement)
1009 m_titleSetExplicitly = false;
1011 // Update title based on first title element in the head, if one exists.
1012 if (HTMLElement* headElement = head()) {
1013 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1014 if (e->hasTagName(titleTag)) {
1015 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1016 setTitle(titleElement->text(), titleElement);
1021 if (!m_titleElement && !m_title.isEmpty()) {
1027 String Document::nodeName() const
1032 Node::NodeType Document::nodeType() const
1034 return DOCUMENT_NODE;
1037 FrameView* Document::view() const
1039 return m_frame ? m_frame->view() : 0;
1042 Page* Document::page() const
1044 return m_frame ? m_frame->page() : 0;
1047 Settings* Document::settings() const
1049 return m_frame ? m_frame->settings() : 0;
1052 PassRefPtr<Range> Document::createRange()
1054 return Range::create(this);
1057 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1058 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1061 ec = NOT_SUPPORTED_ERR;
1064 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1067 PassRefPtr<TreeWalker> Document::createTreeWalker(Node *root, unsigned whatToShow,
1068 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1071 ec = NOT_SUPPORTED_ERR;
1074 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1077 void Document::setDocumentChanged(bool b)
1080 if (!m_docChanged) {
1081 if (!changedDocuments)
1082 changedDocuments = new HashSet<Document*>;
1083 changedDocuments->add(this);
1085 if (m_accessKeyMapValid) {
1086 m_accessKeyMapValid = false;
1087 m_elementsByAccessKey.clear();
1090 if (m_docChanged && changedDocuments)
1091 changedDocuments->remove(this);
1097 void Document::recalcStyle(StyleChange change)
1099 // we should not enter style recalc while painting
1100 if (frame() && frame()->view() && frame()->view()->isPainting()) {
1101 ASSERT(!frame()->view()->isPainting());
1105 if (m_inStyleRecalc)
1106 return; // Guard against re-entrancy. -dwh
1108 m_inStyleRecalc = true;
1109 suspendPostAttachCallbacks();
1111 ASSERT(!renderer() || renderArena());
1112 if (!renderer() || !renderArena())
1115 if (change == Force) {
1116 // style selector may set this again during recalc
1117 m_hasNodesWithPlaceholderStyle = false;
1119 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1120 documentStyle->setDisplay(BLOCK);
1121 documentStyle->setVisuallyOrdered(visuallyOrdered);
1122 documentStyle->setZoom(frame()->pageZoomFactor());
1123 m_styleSelector->setStyle(documentStyle);
1125 FontDescription fontDescription;
1126 fontDescription.setUsePrinterFont(printing());
1127 if (Settings* settings = this->settings()) {
1128 fontDescription.setRenderingMode(settings->fontRenderingMode());
1129 if (printing() && !settings->shouldPrintBackgrounds())
1130 documentStyle->setForceBackgroundsToWhite(true);
1131 const AtomicString& stdfont = settings->standardFontFamily();
1132 if (!stdfont.isEmpty()) {
1133 fontDescription.firstFamily().setFamily(stdfont);
1134 fontDescription.firstFamily().appendFamily(0);
1136 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1137 m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSSValueMedium, inCompatMode(), false));
1140 documentStyle->setFontDescription(fontDescription);
1141 documentStyle->font().update(m_styleSelector->fontSelector());
1143 documentStyle->setHtmlHacks(true); // enable html specific rendering tricks
1145 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1146 if (renderer() && ch != NoChange)
1147 renderer()->setStyle(documentStyle.release());
1148 if (change != Force)
1152 for (Node* n = firstChild(); n; n = n->nextSibling())
1153 if (change >= Inherit || n->hasChangedChild() || n->changed())
1154 n->recalcStyle(change);
1156 if (changed() && view())
1160 setChanged(NoStyleChange);
1161 setHasChangedChild(false);
1162 setDocumentChanged(false);
1164 resumePostAttachCallbacks();
1165 m_inStyleRecalc = false;
1167 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1168 if (m_closeAfterStyleRecalc) {
1169 m_closeAfterStyleRecalc = false;
1174 void Document::updateRendering()
1176 if (hasChangedChild() && !inPageCache())
1177 recalcStyle(NoChange);
1179 // Tell the animation controller that the style is available and it can start animations
1181 m_frame->animation()->styleAvailable();
1184 void Document::updateDocumentsRendering()
1186 if (!changedDocuments)
1189 while (changedDocuments->size()) {
1190 HashSet<Document*>::iterator it = changedDocuments->begin();
1191 Document* doc = *it;
1192 changedDocuments->remove(it);
1194 doc->m_docChanged = false;
1195 doc->updateRendering();
1199 void Document::updateLayout()
1201 if (Element* oe = ownerElement())
1202 oe->document()->updateLayout();
1204 // FIXME: Dave Hyatt's pretty sure we can remove this because layout calls recalcStyle as needed.
1207 // Only do a layout if changes have occurred that make it necessary.
1208 FrameView* v = view();
1209 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1213 // FIXME: This is a bad idea and needs to be removed eventually.
1214 // Other browsers load stylesheets before they continue parsing the web page.
1215 // Since we don't, we can run JavaScript code that needs answers before the
1216 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1217 // lets us get reasonable answers. The long term solution to this problem is
1218 // to instead suspend JavaScript execution.
1219 void Document::updateLayoutIgnorePendingStylesheets()
1221 bool oldIgnore = m_ignorePendingStylesheets;
1223 if (!haveStylesheetsLoaded()) {
1224 m_ignorePendingStylesheets = true;
1225 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1226 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1227 // with accurate style information. (Our suppression involves blanking the whole page at the
1228 // moment. If it were more refined, we might be able to do something better.)
1229 // It's worth noting though that this entire method is a hack, since what we really want to do is
1230 // suspend JS instead of doing a layout with inaccurate information.
1231 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1232 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1233 updateStyleSelector();
1234 } else if (m_hasNodesWithPlaceholderStyle)
1235 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1236 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1237 // but here we need up-to-date style immediatly.
1243 m_ignorePendingStylesheets = oldIgnore;
1246 void Document::attach()
1248 ASSERT(!attached());
1249 ASSERT(!m_inPageCache);
1250 ASSERT(!m_axObjectCache);
1253 m_renderArena = new RenderArena();
1255 // Create the rendering tree
1256 setRenderer(new (m_renderArena) RenderView(this, view()));
1258 if (!m_styleSelector) {
1259 bool matchAuthorAndUserStyles = true;
1260 if (Settings* docSettings = settings())
1261 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1262 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
1267 RenderObject* render = renderer();
1270 ContainerNode::attach();
1272 setRenderer(render);
1275 void Document::detach()
1278 ASSERT(!m_inPageCache);
1280 clearAXObjectCache();
1282 RenderObject* render = renderer();
1284 // indicate destruction mode, i.e. attached() but renderer == 0
1287 // Empty out these lists as a performance optimization, since detaching
1288 // all the individual render objects will cause all the RenderImage
1289 // objects to remove themselves from the lists.
1290 m_imageLoadEventDispatchSoonList.clear();
1291 m_imageLoadEventDispatchingList.clear();
1297 ContainerNode::detach();
1302 // This is required, as our Frame might delete itself as soon as it detaches
1303 // us. However, this violates Node::detach() symantics, as it's never
1304 // possible to re-attach. Eventually Document::detach() should be renamed
1305 // or this call made explicit in each of the callers of Document::detach().
1306 clearFramePointer();
1308 if (m_renderArena) {
1309 delete m_renderArena;
1314 void Document::clearFramePointer()
1319 void Document::removeAllEventListenersFromAllNodes()
1321 m_windowEventListeners.clear();
1322 removeAllDisconnectedNodeEventListeners();
1323 for (Node *n = this; n; n = n->traverseNextNode()) {
1324 if (!n->isEventTargetNode())
1326 EventTargetNodeCast(n)->removeAllEventListeners();
1330 void Document::registerDisconnectedNodeWithEventListeners(Node* node)
1332 m_disconnectedNodesWithEventListeners.add(node);
1335 void Document::unregisterDisconnectedNodeWithEventListeners(Node* node)
1337 m_disconnectedNodesWithEventListeners.remove(node);
1340 void Document::removeAllDisconnectedNodeEventListeners()
1342 HashSet<Node*>::iterator end = m_disconnectedNodesWithEventListeners.end();
1343 for (HashSet<Node*>::iterator i = m_disconnectedNodesWithEventListeners.begin(); i != end; ++i)
1344 EventTargetNodeCast(*i)->removeAllEventListeners();
1345 m_disconnectedNodesWithEventListeners.clear();
1348 void Document::clearAXObjectCache()
1350 // clear cache in top document
1351 if (m_axObjectCache) {
1352 delete m_axObjectCache;
1353 m_axObjectCache = 0;
1357 // ask the top-level document to clear its cache
1358 Document* doc = topDocument();
1360 doc->clearAXObjectCache();
1363 AXObjectCache* Document::axObjectCache() const
1365 // The only document that actually has a AXObjectCache is the top-level
1366 // document. This is because we need to be able to get from any WebCoreAXObject
1367 // to any other WebCoreAXObject on the same page. Using a single cache allows
1368 // lookups across nested webareas (i.e. multiple documents).
1370 if (m_axObjectCache) {
1371 // return already known top-level cache
1372 if (!ownerElement())
1373 return m_axObjectCache;
1375 // In some pages with frames, the cache is created before the sub-webarea is
1376 // inserted into the tree. Here, we catch that case and just toss the old
1377 // cache and start over.
1378 // NOTE: This recovery may no longer be needed. I have been unable to trigger
1379 // it again. See rdar://5794454
1380 // FIXME: Can this be fixed when inserting the subframe instead of now?
1381 // FIXME: If this function was called to get the cache in order to remove
1382 // an AXObject, we are now deleting the cache as a whole and returning a
1383 // new empty cache that does not contain the AXObject! That should actually
1384 // be OK. I am concerned about other cases like this where accessing the
1385 // cache blows away the AXObject being operated on.
1386 delete m_axObjectCache;
1387 m_axObjectCache = 0;
1390 // ask the top-level document for its cache
1391 Document* doc = topDocument();
1393 return doc->axObjectCache();
1395 // this is the top-level document, so install a new cache
1396 m_axObjectCache = new AXObjectCache;
1397 return m_axObjectCache;
1400 void Document::setVisuallyOrdered()
1402 visuallyOrdered = true;
1404 renderer()->style()->setVisuallyOrdered(true);
1407 Tokenizer* Document::createTokenizer()
1409 // FIXME: this should probably pass the frame instead
1410 return new XMLTokenizer(this, view());
1413 void Document::open(Document* ownerDocument)
1415 if (ownerDocument) {
1416 setURL(ownerDocument->url());
1417 m_cookieURL = ownerDocument->cookieURL();
1418 ScriptExecutionContext::setSecurityOrigin(ownerDocument->securityOrigin());
1422 if (m_frame->loader()->isLoadingMainResource() || (tokenizer() && tokenizer()->executingScript()))
1425 if (m_frame->loader()->state() == FrameStateProvisional)
1426 m_frame->loader()->stopAllLoaders();
1432 m_frame->loader()->didExplicitOpen();
1435 void Document::cancelParsing()
1438 // We have to clear the tokenizer to avoid possibly triggering
1439 // the onload handler when closing as a side effect of a cancel-style
1440 // change, such as opening a new document or closing the window while
1448 void Document::implicitOpen()
1453 m_tokenizer = createTokenizer();
1457 HTMLElement* Document::body()
1459 Node* de = documentElement();
1463 // try to prefer a FRAMESET element over BODY
1465 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
1466 if (i->hasTagName(framesetTag))
1467 return static_cast<HTMLElement*>(i);
1469 if (i->hasTagName(bodyTag) && !body)
1472 return static_cast<HTMLElement*>(body);
1475 void Document::setBody(PassRefPtr<HTMLElement> newBody, ExceptionCode& ec)
1477 if (!newBody || !documentElement()) {
1478 ec = HIERARCHY_REQUEST_ERR;
1482 HTMLElement* b = body();
1484 documentElement()->appendChild(newBody, ec);
1486 documentElement()->replaceChild(newBody, b, ec);
1489 HTMLHeadElement* Document::head()
1491 Node* de = documentElement();
1495 for (Node* e = de->firstChild(); e; e = e->nextSibling())
1496 if (e->hasTagName(headTag))
1497 return static_cast<HTMLHeadElement*>(e);
1502 void Document::close()
1504 Frame* frame = this->frame();
1506 // This code calls implicitClose() if all loading has completed.
1507 FrameLoader* frameLoader = frame->loader();
1508 frameLoader->endIfNotLoadingMainResource();
1509 frameLoader->checkCompleted();
1511 // Because we have no frame, we don't know if all loading has completed,
1512 // so we just call implicitClose() immediately. FIXME: This might fire
1513 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
1518 void Document::implicitClose()
1520 // 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.
1521 if (m_inStyleRecalc) {
1522 m_closeAfterStyleRecalc = true;
1526 bool wasLocationChangePending = frame() && frame()->loader()->isScheduledLocationChangePending();
1527 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1532 m_processingLoadEvent = true;
1534 m_wellFormed = m_tokenizer && m_tokenizer->wellFormed();
1536 // We have to clear the tokenizer, in case someone document.write()s from the
1537 // onLoad event handler, as in Radar 3206524.
1541 // Parser should have picked up all preloads by now
1542 m_docLoader->clearPreloads();
1544 // Create a body element if we don't already have one. See Radar 3758785.
1545 if (!this->body() && isHTMLDocument()) {
1546 if (Node* documentElement = this->documentElement()) {
1547 ExceptionCode ec = 0;
1548 documentElement->appendChild(new HTMLBodyElement(bodyTag, this), ec);
1553 // FIXME: We kick off the icon loader when the Document is done parsing.
1554 // There are earlier opportunities we could start it:
1555 // -When the <head> finishes parsing
1556 // -When any new HTMLLinkElement is inserted into the document
1557 // But those add a dynamic component to the favicon that has UI
1558 // ramifications, and we need to decide what is the Right Thing To Do(tm)
1561 f->loader()->startIconLoader();
1563 // Resume the animations (or start them)
1565 f->animation()->resumeAnimations(this);
1567 dispatchImageLoadEventsNow();
1568 this->dispatchWindowEvent(eventNames().loadEvent, false, false);
1570 f->loader()->handledOnloadEvents();
1571 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1572 if (!ownerElement())
1573 printf("onload fired at %d\n", elapsedTime());
1576 m_processingLoadEvent = false;
1578 // An event handler may have removed the frame
1582 // Make sure both the initial layout and reflow happen after the onload
1583 // fires. This will improve onload scores, and other browsers do it.
1584 // If they wanna cheat, we can too. -dwh
1586 if (frame()->loader()->isScheduledLocationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
1587 // Just bail out. Before or during the onload we were shifted to another page.
1588 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1589 view()->unscheduleRelayout();
1593 frame()->loader()->checkCallImplicitClose();
1595 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1596 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1597 // layout/painting now would be pointless.
1598 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1601 // Always do a layout after loading if needed.
1602 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1605 // Paint immediately after the document is ready. We do this to ensure that any timers set by the
1606 // onload don't have a chance to fire before we would have painted. To avoid over-flushing we only
1607 // worry about this for the top-level document. For platforms that use native widgets for ScrollViews, this
1608 // call does nothing (Mac, wx).
1609 // FIXME: This causes a timing issue with the dispatchDidFinishLoad delegate callback on Mac, so think
1610 // before enabling it, even if Mac becomes viewless later.
1611 // See <rdar://problem/5092361>
1612 if (view() && !ownerElement())
1613 view()->hostWindow()->paint();
1617 if (f && renderer() && this == topDocument() && AXObjectCache::accessibilityEnabled())
1618 axObjectCache()->postNotificationToElement(renderer(), "AXLoadComplete");
1622 // FIXME: Officially, time 0 is when the outermost <svg> receives its
1623 // SVGLoad event, but we don't implement those yet. This is close enough
1624 // for now. In some cases we should have fired earlier.
1625 if (svgExtensions())
1626 accessSVGExtensions()->startAnimations();
1630 void Document::setParsing(bool b)
1633 if (!m_bParsing && view())
1634 view()->scheduleRelayout();
1636 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1637 if (!ownerElement() && !m_bParsing)
1638 printf("Parsing finished at %d\n", elapsedTime());
1642 bool Document::shouldScheduleLayout()
1644 // This function will only be called when FrameView thinks a layout is needed.
1645 // This enforces a couple extra rules.
1647 // (a) Only schedule a layout once the stylesheets are loaded.
1648 // (b) Only schedule layout once we have a body element.
1650 return haveStylesheetsLoaded()
1651 && body() || (documentElement() && !documentElement()->hasTagName(htmlTag));
1654 int Document::minimumLayoutDelay()
1656 if (m_overMinimumLayoutThreshold)
1659 int elapsed = elapsedTime();
1660 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1662 // We'll want to schedule the timer to fire at the minimum layout threshold.
1663 return max(0, cLayoutScheduleThreshold - elapsed);
1666 int Document::elapsedTime() const
1668 return static_cast<int>((currentTime() - m_startTime) * 1000);
1671 void Document::write(const String& text, Document* ownerDocument)
1673 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1674 if (!ownerElement())
1675 printf("Beginning a document.write at %d\n", elapsedTime());
1679 open(ownerDocument);
1680 ASSERT(m_tokenizer);
1683 write("<html>", ownerDocument);
1685 m_tokenizer->write(text, false);
1687 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1688 if (!ownerElement())
1689 printf("Ending a document.write at %d\n", elapsedTime());
1693 void Document::writeln(const String& text, Document* ownerDocument)
1695 write(text, ownerDocument);
1696 write("\n", ownerDocument);
1699 void Document::finishParsing()
1701 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1702 if (!ownerElement())
1703 printf("Received all data at %d\n", elapsedTime());
1706 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1707 // finish() is called:
1708 // (1) All remaining data is parsed, document isn't loaded yet
1709 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1710 // (3) Data is still remaining to be parsed.
1712 m_tokenizer->finish();
1715 void Document::clear()
1722 m_windowEventListeners.clear();
1725 const KURL& Document::virtualURL() const
1730 void Document::setURL(const KURL& url)
1732 const KURL& newURL = url.isEmpty() ? blankURL() : url;
1733 if (newURL == m_url)
1737 m_documentURI = m_url.string();
1741 void Document::setBaseElementURL(const KURL& baseElementURL)
1743 m_baseElementURL = baseElementURL;
1747 void Document::updateBaseURL()
1749 m_baseURL = m_baseElementURL.isEmpty() ? KURL(documentURI()) : m_baseElementURL;
1750 if (!m_baseURL.isValid())
1754 m_elemSheet->setHref(m_baseURL.string());
1755 if (m_mappedElementSheet)
1756 m_mappedElementSheet->setHref(m_baseURL.string());
1759 void Document::setCSSStyleSheet(const String& url, const String& charset, const CachedCSSStyleSheet* sheet)
1761 m_sheet = CSSStyleSheet::create(this, url, charset);
1762 m_sheet->parseString(sheet->sheetText());
1764 updateStyleSelector();
1767 #if FRAME_LOADS_USER_STYLESHEET
1768 void Document::setUserStyleSheet(const String& sheet)
1770 if (m_usersheet != sheet) {
1771 m_usersheet = sheet;
1772 updateStyleSelector();
1777 String Document::userStyleSheet() const
1779 #if FRAME_LOADS_USER_STYLESHEET
1782 Page* page = this->page();
1785 return page->userStyleSheet();
1789 CSSStyleSheet* Document::elementSheet()
1792 m_elemSheet = CSSStyleSheet::create(this, m_baseURL.string());
1793 return m_elemSheet.get();
1796 CSSStyleSheet* Document::mappedElementSheet()
1798 if (!m_mappedElementSheet)
1799 m_mappedElementSheet = CSSStyleSheet::create(this, m_baseURL.string());
1800 return m_mappedElementSheet.get();
1803 static Node* nextNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1805 // Search is inclusive of start
1806 for (Node* n = start; n; n = n->traverseNextNode())
1807 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1813 static Node* previousNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1815 // Search is inclusive of start
1816 for (Node* n = start; n; n = n->traversePreviousNode())
1817 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1823 static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1825 // Search is inclusive of start
1826 int winningTabIndex = SHRT_MAX + 1;
1828 for (Node* n = start; n; n = n->traverseNextNode())
1829 if (n->isKeyboardFocusable(event) && n->tabIndex() > tabIndex && n->tabIndex() < winningTabIndex) {
1831 winningTabIndex = n->tabIndex();
1837 static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1839 // Search is inclusive of start
1840 int winningTabIndex = 0;
1842 for (Node* n = start; n; n = n->traversePreviousNode())
1843 if (n->isKeyboardFocusable(event) && n->tabIndex() < tabIndex && n->tabIndex() > winningTabIndex) {
1845 winningTabIndex = n->tabIndex();
1851 Node* Document::nextFocusableNode(Node* start, KeyboardEvent* event)
1854 // If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
1855 if (start->tabIndex() < 0) {
1856 for (Node* n = start->traverseNextNode(); n; n = n->traverseNextNode())
1857 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1861 // First try to find a node with the same tabindex as start that comes after start in the document.
1862 if (Node* winner = nextNodeWithExactTabIndex(start->traverseNextNode(), start->tabIndex(), event))
1865 if (start->tabIndex() == 0)
1866 // We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
1870 // Look for the first node in the document that:
1871 // 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
1872 // 2) comes first in the document, if there's a tie.
1873 if (Node* winner = nextNodeWithGreaterTabIndex(this, start ? start->tabIndex() : 0, event))
1876 // There are no nodes with a tabindex greater than start's tabindex,
1877 // so find the first node with a tabindex of 0.
1878 return nextNodeWithExactTabIndex(this, 0, event);
1881 Node* Document::previousFocusableNode(Node* start, KeyboardEvent* event)
1884 for (last = this; last->lastChild(); last = last->lastChild())
1887 // First try to find the last node in the document that comes before start and has the same tabindex as start.
1888 // If start is null, find the last node in the document with a tabindex of 0.
1890 int startingTabIndex;
1892 startingNode = start->traversePreviousNode();
1893 startingTabIndex = start->tabIndex();
1895 startingNode = last;
1896 startingTabIndex = 0;
1899 // However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
1900 if (startingTabIndex < 0) {
1901 for (Node* n = startingNode; n; n = n->traversePreviousNode())
1902 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1906 if (Node* winner = previousNodeWithExactTabIndex(startingNode, startingTabIndex, event))
1909 // There are no nodes before start with the same tabindex as start, so look for a node that:
1910 // 1) has the highest non-zero tabindex (that is less than start's tabindex), and
1911 // 2) comes last in the document, if there's a tie.
1912 startingTabIndex = (start && start->tabIndex()) ? start->tabIndex() : SHRT_MAX;
1913 return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
1916 int Document::nodeAbsIndex(Node *node)
1918 ASSERT(node->document() == this);
1921 for (Node *n = node; n && n != this; n = n->traversePreviousNode())
1926 Node *Document::nodeWithAbsIndex(int absIndex)
1929 for (int i = 0; n && (i < absIndex); i++) {
1930 n = n->traverseNextNode();
1935 void Document::processHttpEquiv(const String &equiv, const String &content)
1937 ASSERT(!equiv.isNull() && !content.isNull());
1939 Frame *frame = this->frame();
1941 if (equalIgnoringCase(equiv, "default-style")) {
1942 // The preferred style set has been overridden as per section
1943 // 14.3.2 of the HTML4.0 specification. We need to update the
1944 // sheet used variable and then update our style selector.
1945 // For more info, see the test at:
1946 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1948 m_selectedStylesheetSet = content;
1949 m_preferredStylesheetSet = content;
1950 updateStyleSelector();
1951 } else if (equalIgnoringCase(equiv, "refresh")) {
1954 if (frame && parseHTTPRefresh(content, true, delay, url)) {
1956 url = frame->loader()->url().string();
1958 url = completeURL(url).string();
1959 frame->loader()->scheduleHTTPRedirection(delay, url);
1961 } else if (equalIgnoringCase(equiv, "set-cookie")) {
1962 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
1963 if (isHTMLDocument())
1964 static_cast<HTMLDocument*>(this)->setCookie(content);
1965 } else if (equalIgnoringCase(equiv, "content-language"))
1966 setContentLanguage(content);
1967 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
1968 parseDNSPrefetchControlHeader(content);
1971 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const IntPoint& documentPoint, const PlatformMouseEvent& event)
1973 ASSERT(!renderer() || renderer()->isRenderView());
1976 return MouseEventWithHitTestResults(event, HitTestResult(IntPoint()));
1978 HitTestResult result(documentPoint);
1979 renderer()->layer()->hitTest(request, result);
1981 if (!request.readonly)
1984 return MouseEventWithHitTestResults(event, result);
1987 // DOM Section 1.1.1
1988 bool Document::childTypeAllowed(NodeType type)
1991 case ATTRIBUTE_NODE:
1992 case CDATA_SECTION_NODE:
1993 case DOCUMENT_FRAGMENT_NODE:
1996 case ENTITY_REFERENCE_NODE:
1999 case XPATH_NAMESPACE_NODE:
2002 case PROCESSING_INSTRUCTION_NODE:
2004 case DOCUMENT_TYPE_NODE:
2006 // Documents may contain no more than one of each of these.
2007 // (One Element and one DocumentType.)
2008 for (Node* c = firstChild(); c; c = c->nextSibling())
2009 if (c->nodeType() == type)
2016 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2019 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2022 if (oldChild->nodeType() == newChild->nodeType())
2025 int numDoctypes = 0;
2026 int numElements = 0;
2028 // First, check how many doctypes and elements we have, not counting
2029 // the child we're about to remove.
2030 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2034 switch (c->nodeType()) {
2035 case DOCUMENT_TYPE_NODE:
2046 // Then, see how many doctypes and elements might be added by the new child.
2047 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2048 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2049 switch (c->nodeType()) {
2050 case ATTRIBUTE_NODE:
2051 case CDATA_SECTION_NODE:
2052 case DOCUMENT_FRAGMENT_NODE:
2055 case ENTITY_REFERENCE_NODE:
2058 case XPATH_NAMESPACE_NODE:
2061 case PROCESSING_INSTRUCTION_NODE:
2063 case DOCUMENT_TYPE_NODE:
2072 switch (newChild->nodeType()) {
2073 case ATTRIBUTE_NODE:
2074 case CDATA_SECTION_NODE:
2075 case DOCUMENT_FRAGMENT_NODE:
2078 case ENTITY_REFERENCE_NODE:
2081 case XPATH_NAMESPACE_NODE:
2084 case PROCESSING_INSTRUCTION_NODE:
2086 case DOCUMENT_TYPE_NODE:
2095 if (numElements > 1 || numDoctypes > 1)
2101 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2103 // Spec says cloning Document nodes is "implementation dependent"
2104 // so we do not support it...
2108 StyleSheetList* Document::styleSheets()
2110 return m_styleSheets.get();
2113 String Document::preferredStylesheetSet() const
2115 return m_preferredStylesheetSet;
2118 String Document::selectedStylesheetSet() const
2120 return m_selectedStylesheetSet;
2123 void Document::setSelectedStylesheetSet(const String& aString)
2125 m_selectedStylesheetSet = aString;
2126 updateStyleSelector();
2128 renderer()->repaint();
2131 // This method is called whenever a top-level stylesheet has finished loading.
2132 void Document::removePendingSheet()
2134 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2135 ASSERT(m_pendingStylesheets > 0);
2137 m_pendingStylesheets--;
2139 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2140 if (!ownerElement())
2141 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2144 updateStyleSelector();
2146 if (!m_pendingStylesheets && m_tokenizer)
2147 m_tokenizer->executeScriptsWaitingForStylesheets();
2149 if (!m_pendingStylesheets && m_gotoAnchorNeededAfterStylesheetsLoad && m_frame)
2150 m_frame->loader()->gotoAnchor();
2153 void Document::updateStyleSelector()
2155 // Don't bother updating, since we haven't loaded all our style info yet
2156 // and haven't calculated the style selector for the first time.
2157 if (!m_didCalculateStyleSelector && !haveStylesheetsLoaded())
2160 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
2161 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2163 renderer()->repaint();
2166 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2167 if (!ownerElement())
2168 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2171 recalcStyleSelector();
2174 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2175 if (!ownerElement())
2176 printf("Finished update of style selector at time %d\n", elapsedTime());
2180 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
2182 view()->scheduleRelayout();
2186 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
2188 // Until the <body> exists, we have no choice but to compare document positions,
2189 // since styles outside of the body and head continue to be shunted into the head
2190 // (and thus can shift to end up before dynamically added DOM content that is also
2191 // outside the body).
2192 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
2193 m_styleSheetCandidateNodes.add(node);
2197 // Determine an appropriate insertion point.
2198 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2199 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2200 ListHashSet<Node*>::iterator it = end;
2201 Node* followingNode = 0;
2205 unsigned short position = n->compareDocumentPosition(node);
2206 if (position == DOCUMENT_POSITION_FOLLOWING) {
2207 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2211 } while (it != begin);
2213 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2216 void Document::removeStyleSheetCandidateNode(Node* node)
2218 m_styleSheetCandidateNodes.remove(node);
2221 void Document::recalcStyleSelector()
2223 if (!renderer() || !attached())
2226 StyleSheetVector sheets;
2228 bool matchAuthorAndUserStyles = true;
2229 if (Settings* settings = this->settings())
2230 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
2232 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2233 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2234 if (!matchAuthorAndUserStyles)
2236 for (ListHashSet<Node*>::iterator it = begin; it != end; ++it) {
2239 StyleSheet* sheet = 0;
2241 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
2242 // Processing instruction (XML documents only)
2243 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
2244 sheet = pi->sheet();
2246 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
2247 if (pi->isXSL() && !transformSourceDocument()) {
2248 // Don't apply XSL transforms until loading is finished.
2250 applyXSLTransform(pi);
2254 if (!sheet && !pi->localHref().isEmpty()) {
2255 // Processing instruction with reference to an element in this document - e.g.
2256 // <?xml-stylesheet href="#mystyle">, with the element
2257 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2259 Element* elem = getElementById(pi->localHref().impl());
2261 String sheetText("");
2262 for (Node* c = elem->firstChild(); c; c = c->nextSibling()) {
2263 if (c->nodeType() == TEXT_NODE || c->nodeType() == CDATA_SECTION_NODE)
2264 sheetText += c->nodeValue();
2267 RefPtr<CSSStyleSheet> cssSheet = CSSStyleSheet::create(this);
2268 cssSheet->parseString(sheetText);
2269 pi->setCSSStyleSheet(cssSheet);
2270 sheet = cssSheet.get();
2273 } else if (n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))
2275 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2278 Element* e = static_cast<Element*>(n);
2279 AtomicString title = e->getAttribute(titleAttr);
2280 bool enabledViaScript = false;
2281 if (e->hasLocalName(linkTag)) {
2283 HTMLLinkElement* l = static_cast<HTMLLinkElement*>(n);
2284 if (l->isDisabled())
2286 enabledViaScript = l->isEnabledViaScript();
2287 if (l->isLoading()) {
2288 // it is loading but we should still decide which style sheet set to use
2289 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
2290 const AtomicString& rel = e->getAttribute(relAttr);
2291 if (!rel.contains("alternate")) {
2292 m_preferredStylesheetSet = title;
2293 m_selectedStylesheetSet = title;
2302 // Get the current preferred styleset. This is the
2303 // set of sheets that will be enabled.
2305 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2306 sheet = static_cast<SVGStyleElement*>(n)->sheet();
2309 if (e->hasLocalName(linkTag))
2310 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
2313 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
2315 // Check to see if this sheet belongs to a styleset
2316 // (thus making it PREFERRED or ALTERNATE rather than
2318 if (!enabledViaScript && !title.isEmpty()) {
2319 // Yes, we have a title.
2320 if (m_preferredStylesheetSet.isEmpty()) {
2321 // No preferred set has been established. If
2322 // we are NOT an alternate sheet, then establish
2323 // us as the preferred set. Otherwise, just ignore
2325 AtomicString rel = e->getAttribute(relAttr);
2326 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
2327 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
2330 if (title != m_preferredStylesheetSet)
2336 sheets.append(sheet);
2339 m_styleSheets->swap(sheets);
2341 // Create a new style selector
2342 delete m_styleSelector;
2343 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
2344 m_didCalculateStyleSelector = true;
2347 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
2349 m_hoverNode = newHoverNode;
2352 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
2354 m_activeNode = newActiveNode;
2357 void Document::focusedNodeRemoved()
2362 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
2364 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
2367 bool nodeInSubtree = false;
2368 if (amongChildrenOnly)
2369 nodeInSubtree = m_focusedNode->isDescendantOf(node);
2371 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
2374 document()->focusedNodeRemoved();
2377 void Document::hoveredNodeDetached(Node* node)
2379 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parent())))
2382 m_hoverNode = node->parent();
2383 while (m_hoverNode && !m_hoverNode->renderer())
2384 m_hoverNode = m_hoverNode->parent();
2386 frame()->eventHandler()->scheduleHoverStateUpdate();
2389 void Document::activeChainNodeDetached(Node* node)
2391 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parent())))
2394 m_activeNode = node->parent();
2395 while (m_activeNode && !m_activeNode->renderer())
2396 m_activeNode = m_activeNode->parent();
2399 #if ENABLE(DASHBOARD_SUPPORT)
2400 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
2402 return m_dashboardRegions;
2405 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
2407 m_dashboardRegions = regions;
2408 setDashboardRegionsDirty(false);
2412 bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
2414 // Make sure newFocusedNode is actually in this document
2415 if (newFocusedNode && (newFocusedNode->document() != this))
2418 if (m_focusedNode == newFocusedNode)
2424 bool focusChangeBlocked = false;
2425 RefPtr<Node> oldFocusedNode = m_focusedNode;
2428 // Remove focus from the existing focus node (if any)
2429 if (oldFocusedNode && !oldFocusedNode->m_inDetach) {
2430 if (oldFocusedNode->active())
2431 oldFocusedNode->setActive(false);
2433 oldFocusedNode->setFocus(false);
2435 // Dispatch a change event for text fields or textareas that have been edited
2436 RenderObject* r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer());
2437 if (r && (r->isTextArea() || r->isTextField()) && r->isEdited()) {
2438 EventTargetNodeCast(oldFocusedNode.get())->dispatchEventForType(eventNames().changeEvent, true, false);
2439 if ((r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer())))
2440 r->setEdited(false);
2443 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
2444 EventTargetNodeCast(oldFocusedNode.get())->dispatchBlurEvent();
2446 if (m_focusedNode) {
2447 // handler shifted focus
2448 focusChangeBlocked = true;
2451 EventTargetNodeCast(oldFocusedNode.get())->dispatchUIEvent(eventNames().DOMFocusOutEvent);
2452 if (m_focusedNode) {
2453 // handler shifted focus
2454 focusChangeBlocked = true;
2457 if ((oldFocusedNode.get() == this) && oldFocusedNode->hasOneRef())
2460 if (oldFocusedNode.get() == oldFocusedNode->rootEditableElement())
2461 frame()->editor()->didEndEditing();
2464 if (newFocusedNode) {
2465 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
2466 // delegate blocks focus change
2467 focusChangeBlocked = true;
2468 goto SetFocusedNodeDone;
2470 // Set focus on the new node
2471 m_focusedNode = newFocusedNode.get();
2473 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
2474 EventTargetNodeCast(m_focusedNode.get())->dispatchFocusEvent();
2476 if (m_focusedNode != newFocusedNode) {
2477 // handler shifted focus
2478 focusChangeBlocked = true;
2479 goto SetFocusedNodeDone;
2481 EventTargetNodeCast(m_focusedNode.get())->dispatchUIEvent(eventNames().DOMFocusInEvent);
2482 if (m_focusedNode != newFocusedNode) {
2483 // handler shifted focus
2484 focusChangeBlocked = true;
2485 goto SetFocusedNodeDone;
2487 m_focusedNode->setFocus();
2489 if (m_focusedNode.get() == m_focusedNode->rootEditableElement())
2490 frame()->editor()->didBeginEditing();
2492 // eww, I suck. set the qt focus correctly
2493 // ### find a better place in the code for this
2495 Widget *focusWidget = widgetForNode(m_focusedNode.get());
2497 // Make sure a widget has the right size before giving it focus.
2498 // Otherwise, we are testing edge cases of the Widget code.
2499 // Specifically, in WebCore this does not work well for text fields.
2501 // Re-get the widget in case updating the layout changed things.
2502 focusWidget = widgetForNode(m_focusedNode.get());
2505 focusWidget->setFocus();
2512 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
2513 axObjectCache()->handleFocusedUIElementChanged();
2518 return !focusChangeBlocked;
2521 void Document::setCSSTarget(Node* n)
2524 m_cssTarget->setChanged();
2530 Node* Document::getCSSTarget() const
2535 void Document::attachNodeIterator(NodeIterator *ni)
2537 m_nodeIterators.add(ni);
2540 void Document::detachNodeIterator(NodeIterator *ni)
2542 m_nodeIterators.remove(ni);
2545 void Document::nodeChildrenChanged(ContainerNode* container)
2547 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2548 HashSet<Range*>::const_iterator end = m_ranges.end();
2549 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2550 (*it)->nodeChildrenChanged(container);
2554 void Document::nodeWillBeRemoved(Node* n)
2556 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
2557 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
2558 (*it)->nodeWillBeRemoved(n);
2560 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2561 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
2562 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
2563 (*it)->nodeWillBeRemoved(n);
2566 if (Frame* frame = this->frame()) {
2567 frame->selection()->nodeWillBeRemoved(n);
2568 frame->dragCaretController()->nodeWillBeRemoved(n);
2572 void Document::textInserted(Node* text, unsigned offset, unsigned length)
2574 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2575 HashSet<Range*>::const_iterator end = m_ranges.end();
2576 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2577 (*it)->textInserted(text, offset, length);
2580 // Update the markers for spelling and grammar checking.
2581 shiftMarkers(text, offset, length);
2584 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
2586 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2587 HashSet<Range*>::const_iterator end = m_ranges.end();
2588 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2589 (*it)->textRemoved(text, offset, length);
2592 // Update the markers for spelling and grammar checking.
2593 removeMarkers(text, offset, length);
2594 shiftMarkers(text, offset + length, 0 - length);
2597 void Document::textNodesMerged(Text* oldNode, unsigned offset)
2599 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2600 NodeWithIndex oldNodeWithIndex(oldNode);
2601 HashSet<Range*>::const_iterator end = m_ranges.end();
2602 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2603 (*it)->textNodesMerged(oldNodeWithIndex, offset);
2606 // FIXME: This should update markers for spelling and grammar checking.
2609 void Document::textNodeSplit(Text* oldNode)
2611 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2612 HashSet<Range*>::const_iterator end = m_ranges.end();
2613 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2614 (*it)->textNodeSplit(oldNode);
2617 // FIXME: This should update markers for spelling and grammar checking.
2620 // FIXME: eventually, this should return a DOMWindow stored in the document.
2621 DOMWindow* Document::domWindow() const
2625 return frame()->domWindow();
2628 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
2630 if (eventType == "UIEvents" || eventType == "UIEvent")
2631 return UIEvent::create();
2632 if (eventType == "MouseEvents" || eventType == "MouseEvent")
2633 return MouseEvent::create();
2634 if (eventType == "MutationEvents" || eventType == "MutationEvent")
2635 return MutationEvent::create();
2636 if (eventType == "KeyboardEvents" || eventType == "KeyboardEvent")
2637 return KeyboardEvent::create();
2638 if (eventType == "HTMLEvents" || eventType == "Event" || eventType == "Events")
2639 return Event::create();
2640 if (eventType == "ProgressEvent")
2641 return ProgressEvent::create();
2642 if (eventType == "TextEvent")
2643 return TextEvent::create();
2644 if (eventType == "OverflowEvent")
2645 return OverflowEvent::create();
2646 if (eventType == "WheelEvent")
2647 return WheelEvent::create();
2649 if (eventType == "SVGEvents")
2650 return Event::create();
2651 if (eventType == "SVGZoomEvents")
2652 return SVGZoomEvent::create();
2654 if (eventType == "MessageEvent")
2655 return MessageEvent::create();
2656 if (eventType == "WebKitAnimationEvent")
2657 return WebKitAnimationEvent::create();
2658 if (eventType == "WebKitTransitionEvent")
2659 return WebKitTransitionEvent::create();
2660 ec = NOT_SUPPORTED_ERR;
2664 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
2666 if (eventType == eventNames().DOMSubtreeModifiedEvent)
2667 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
2668 else if (eventType == eventNames().DOMNodeInsertedEvent)
2669 addListenerType(DOMNODEINSERTED_LISTENER);
2670 else if (eventType == eventNames().DOMNodeRemovedEvent)
2671 addListenerType(DOMNODEREMOVED_LISTENER);
2672 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
2673 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
2674 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
2675 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
2676 else if (eventType == eventNames().DOMAttrModifiedEvent)
2677 addListenerType(DOMATTRMODIFIED_LISTENER);
2678 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
2679 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
2680 else if (eventType == eventNames().overflowchangedEvent)
2681 addListenerType(OVERFLOWCHANGED_LISTENER);
2682 else if (eventType == eventNames().webkitAnimationStartEvent)
2683 addListenerType(ANIMATIONSTART_LISTENER);
2684 else if (eventType == eventNames().webkitAnimationEndEvent)
2685 addListenerType(ANIMATIONEND_LISTENER);
2686 else if (eventType == eventNames().webkitAnimationIterationEvent)
2687 addListenerType(ANIMATIONITERATION_LISTENER);
2688 else if (eventType == eventNames().webkitTransitionEndEvent)
2689 addListenerType(TRANSITIONEND_LISTENER);
2692 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
2697 void Document::handleWindowEvent(Event* evt, bool useCapture)
2699 if (m_windowEventListeners.isEmpty())
2702 // if any html event listeners are registered on the window, then dispatch them here
2703 RegisteredEventListenerList listenersCopy = m_windowEventListeners;
2704 RegisteredEventListenerList::iterator it = listenersCopy.begin();
2706 for (; it != listenersCopy.end(); ++it)
2707 if ((*it)->eventType() == evt->type() && (*it)->useCapture() == useCapture && !(*it)->removed())
2708 (*it)->listener()->handleEvent(evt, true);
2711 void Document::setWindowInlineEventListenerForType(const AtomicString& eventType, PassRefPtr<EventListener> listener)
2713 // If we already have it we don't want removeWindowEventListener to delete it
2714 removeWindowInlineEventListenerForType(eventType);
2716 addWindowEventListener(eventType, listener, false);
2719 EventListener* Document::windowInlineEventListenerForType(const AtomicString& eventType)
2721 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2722 for (; it != m_windowEventListeners.end(); ++it) {
2723 if ((*it)->eventType() == eventType && (*it)->listener()->isInline())
2724 return (*it)->listener();
2729 void Document::removeWindowInlineEventListenerForType(const AtomicString& eventType)
2731 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2732 for (; it != m_windowEventListeners.end(); ++it) {
2733 if ((*it)->eventType() == eventType && (*it)->listener()->isInline()) {
2734 if (eventType == eventNames().unloadEvent)
2735 removePendingFrameUnloadEventCount();
2736 else if (eventType == eventNames().beforeunloadEvent)
2737 removePendingFrameBeforeUnloadEventCount();
2738 m_windowEventListeners.remove(it);
2744 void Document::addWindowEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2746 if (eventType == eventNames().unloadEvent)
2747 addPendingFrameUnloadEventCount();
2748 else if (eventType == eventNames().beforeunloadEvent)
2749 addPendingFrameBeforeUnloadEventCount();
2750 // Remove existing identical listener set with identical arguments.
2751 // The DOM 2 spec says that "duplicate instances are discarded" in this case.
2752 removeWindowEventListener(eventType, listener.get(), useCapture);
2753 addListenerTypeIfNeeded(eventType);
2754 m_windowEventListeners.append(RegisteredEventListener::create(eventType, listener, useCapture));
2757 void Document::removeWindowEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2759 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2760 for (; it != m_windowEventListeners.end(); ++it) {
2761 RegisteredEventListener& r = **it;
2762 if (r.eventType() == eventType && r.listener() == listener && r.useCapture() == useCapture) {
2763 if (eventType == eventNames().unloadEvent)
2764 removePendingFrameUnloadEventCount();
2765 else if (eventType == eventNames().beforeunloadEvent)
2766 removePendingFrameBeforeUnloadEventCount();
2767 m_windowEventListeners.remove(it);
2773 bool Document::hasWindowEventListener(const AtomicString& eventType)
2775 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2776 for (; it != m_windowEventListeners.end(); ++it)
2777 if ((*it)->eventType() == eventType)
2782 void Document::addPendingFrameUnloadEventCount()
2785 m_frame->eventHandler()->addPendingFrameUnloadEventCount();
2788 void Document::removePendingFrameUnloadEventCount()
2791 m_frame->eventHandler()->removePendingFrameUnloadEventCount();
2794 void Document::addPendingFrameBeforeUnloadEventCount()
2797 m_frame->eventHandler()->addPendingFrameBeforeUnloadEventCount();
2800 void Document::removePendingFrameBeforeUnloadEventCount()
2803 m_frame->eventHandler()->removePendingFrameBeforeUnloadEventCount();
2806 PassRefPtr<EventListener> Document::createEventListener(const String& functionName, const String& code, Node* node)
2808 Frame* frm = frame();
2809 if (!frm || !frm->script()->isEnabled())
2813 if (node ? node->isSVGElement() : isSVGDocument())
2814 return frm->script()->createSVGEventHandler(functionName, code, node);
2817 // We may want to treat compound document event handlers in a different way, in future.
2818 return frm->script()->createInlineEventListener(functionName, code, node);
2821 void Document::setWindowInlineEventListenerForTypeAndAttribute(const AtomicString& eventType, Attribute* attr)
2823 setWindowInlineEventListenerForType(eventType, createEventListener(attr->localName().string(), attr->value(), 0));
2826 void Document::dispatchImageLoadEventSoon(ImageLoader* image)
2828 m_imageLoadEventDispatchSoonList.append(image);
2829 if (!m_imageLoadEventTimer.isActive())
2830 m_imageLoadEventTimer.startOneShot(0);
2833 void Document::removeImage(ImageLoader* image)
2835 // Remove instances of this image from both lists.
2836 // Use loops because we allow multiple instances to get into the lists.
2837 while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
2838 while (m_imageLoadEventDispatchingList.removeRef(image)) { }
2839 if (m_imageLoadEventDispatchSoonList.isEmpty())
2840 m_imageLoadEventTimer.stop();
2843 void Document::dispatchImageLoadEventsNow()
2845 // need to avoid re-entering this function; if new dispatches are
2846 // scheduled before the parent finishes processing the list, they
2847 // will set a timer and eventually be processed
2848 if (!m_imageLoadEventDispatchingList.isEmpty())
2851 m_imageLoadEventTimer.stop();
2853 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2854 m_imageLoadEventDispatchSoonList.clear();
2855 for (DeprecatedPtrListIterator<ImageLoader> it(m_imageLoadEventDispatchingList); it.current();) {
2856 ImageLoader* image = it.current();
2857 // Must advance iterator *before* dispatching call.
2858 // Otherwise, it might be advanced automatically if dispatching the call had a side effect
2859 // of destroying the current ImageLoader, and then we would advance past the *next* item,
2860 // missing one altogether.
2862 image->dispatchLoadEvent();
2864 m_imageLoadEventDispatchingList.clear();
2867 void Document::imageLoadEventTimerFired(Timer<Document>*)
2869 dispatchImageLoadEventsNow();
2872 Element* Document::ownerElement() const
2876 return frame()->ownerElement();
2879 String Document::cookie() const
2881 if (page() && !page()->cookieEnabled())
2884 return cookies(this, cookieURL());
2887 void Document::setCookie(const String& value)
2889 if (page() && !page()->cookieEnabled())
2892 setCookies(this, cookieURL(), policyBaseURL(), value);
2895 String Document::referrer() const
2898 return frame()->loader()->referrer();
2902 String Document::domain() const
2904 return securityOrigin()->domain();
2907 void Document::setDomain(const String& newDomain)
2909 // Both NS and IE specify that changing the domain is only allowed when
2910 // the new domain is a suffix of the old domain.
2912 // FIXME: We should add logging indicating why a domain was not allowed.
2914 // If the new domain is the same as the old domain, still call
2915 // securityOrigin()->setDomainForDOM. This will change the
2916 // security check behavior. For example, if a page loaded on port 8000
2917 // assigns its current domain using document.domain, the page will
2918 // allow other pages loaded on different ports in the same domain that
2919 // have also assigned to access this page.
2920 if (equalIgnoringCase(domain(), newDomain)) {
2921 securityOrigin()->setDomainFromDOM(newDomain);
2923 m_frame->script()->updateSecurityOrigin();
2927 int oldLength = domain().length();
2928 int newLength = newDomain.length();
2929 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
2930 if (newLength >= oldLength)
2933 String test = domain();
2934 // Check that it's a subdomain, not e.g. "ebkit.org"
2935 if (test[oldLength - newLength - 1] != '.')
2938 // Now test is "webkit.org" from domain()
2939 // and we check that it's the same thing as newDomain
2940 test.remove(0, oldLength - newLength);
2941 if (test != newDomain)
2944 securityOrigin()->setDomainFromDOM(newDomain);
2946 m_frame->script()->updateSecurityOrigin();
2949 String Document::lastModified() const
2954 DocumentLoader* loader = f->loader()->documentLoader();
2957 return loader->response().httpHeaderField("Last-Modified");
2960 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
2965 U16_NEXT(characters, i, length, c)
2966 if (!isValidNameStart(c))
2969 while (i < length) {
2970 U16_NEXT(characters, i, length, c)
2971 if (!isValidNamePart(c))
2978 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
2980 UChar c = characters[0];
2981 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
2984 for (unsigned i = 1; i < length; ++i) {
2986 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
2993 bool Document::isValidName(const String& name)
2995 unsigned length = name.length();
2999 const UChar* characters = name.characters();
3000 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3003 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3005 unsigned length = qualifiedName.length();
3008 ec = INVALID_CHARACTER_ERR;
3012 bool nameStart = true;
3013 bool sawColon = false;
3016 const UChar* s = qualifiedName.characters();
3017 for (unsigned i = 0; i < length;) {
3019 U16_NEXT(s, i, length, c)
3023 return false; // multiple colons: not allowed
3028 } else if (nameStart) {
3029 if (!isValidNameStart(c)) {
3030 ec = INVALID_CHARACTER_ERR;
3035 if (!isValidNamePart(c)) {
3036 ec = INVALID_CHARACTER_ERR;
3044 localName = qualifiedName;
3046 prefix = qualifiedName.substring(0, colonPos);
3047 if (prefix.isEmpty()) {
3051 localName = qualifiedName.substring(colonPos + 1);
3054 if (localName.isEmpty()) {
3062 void Document::addImageMap(HTMLMapElement* imageMap)
3064 const AtomicString& name = imageMap->getName();
3068 // Add the image map, unless there's already another with that name.
3069 // "First map wins" is the rule other browsers seem to implement.
3070 m_imageMapsByName.add(name.impl(), imageMap);
3073 void Document::removeImageMap(HTMLMapElement* imageMap)
3075 // Remove the image map by name.
3076 // But don't remove some other image map that just happens to have the same name.
3077 // FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
3078 // once a map has been removed.
3079 const AtomicString& name = imageMap->getName();
3083 ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
3084 if (it != m_imageMapsByName.end() && it->second == imageMap)
3085 m_imageMapsByName.remove(it);
3088 HTMLMapElement *Document::getImageMap(const String& url) const
3092 int hashPos = url.find('#');
3093 String name = (hashPos < 0 ? url : url.substring(hashPos + 1)).impl();
3094 AtomicString mapName = isHTMLDocument() ? name.lower() : name;
3095 return m_imageMapsByName.get(mapName.impl());
3098 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3100 m_decoder = decoder;
3103 UChar Document::backslashAsCurrencySymbol() const
3107 return m_decoder->encoding().backslashAsCurrencySymbol();
3110 KURL Document::completeURL(const String& url) const
3112 // Always return a null URL when passed a null string.
3113 // FIXME: Should we change the KURL constructor to have this behavior?
3117 return KURL(m_baseURL, url);
3118 return KURL(m_baseURL, url, m_decoder->encoding());
3121 bool Document::inPageCache()
3123 return m_inPageCache;
3126 void Document::setInPageCache(bool flag)
3128 if (m_inPageCache == flag)
3131 m_inPageCache = flag;
3133 ASSERT(m_savedRenderer == 0);
3134 m_savedRenderer = renderer();
3135 if (FrameView* v = view())
3136 v->resetScrollbars();
3138 ASSERT(renderer() == 0 || renderer() == m_savedRenderer);
3139 ASSERT(m_renderArena);
3140 setRenderer(m_savedRenderer);
3141 m_savedRenderer = 0;
3145 void Document::documentWillBecomeInactive()
3147 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3148 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3149 (*i)->documentWillBecomeInactive();
3152 void Document::documentDidBecomeActive()
3154 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3155 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3156 (*i)->documentDidBecomeActive();
3159 void Document::registerForDocumentActivationCallbacks(Element* e)
3161 m_documentActivationCallbackElements.add(e);
3164 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3166 m_documentActivationCallbackElements.remove(e);
3169 void Document::mediaVolumeDidChange()
3171 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3172 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3173 (*i)->mediaVolumeDidChange();
3176 void Document::registerForMediaVolumeCallbacks(Element* e)
3178 m_mediaVolumeCallbackElements.add(e);
3181 void Document::unregisterForMediaVolumeCallbacks(Element* e)
3183 m_mediaVolumeCallbackElements.remove(e);
3186 void Document::setShouldCreateRenderers(bool f)
3188 m_createRenderers = f;
3191 bool Document::shouldCreateRenderers()
3193 return m_createRenderers;
3196 // Support for Javascript execCommand, and related methods
3198 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
3200 Frame* frame = document->frame();
3201 if (!frame || frame->document() != document)
3202 return Editor::Command();
3203 return frame->editor()->command(commandName,
3204 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
3207 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
3209 return command(this, commandName, userInterface).execute(value);
3212 bool Document::queryCommandEnabled(const String& commandName)
3214 return command(this, commandName).isEnabled();
3217 bool Document::queryCommandIndeterm(const String& commandName)
3219 return command(this, commandName).state() == MixedTriState;
3222 bool Document::queryCommandState(const String& commandName)
3224 return command(this, commandName).state() != FalseTriState;
3227 bool Document::queryCommandSupported(const String& commandName)
3229 return command(this, commandName).isSupported();
3232 String Document::queryCommandValue(const String& commandName)
3234 return command(this, commandName).value();
3237 static IntRect placeholderRectForMarker()
3239 return IntRect(-1, -1, -1, -1);
3242 void Document::addMarker(Range *range, DocumentMarker::MarkerType type, String description)
3244 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3245 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3246 RefPtr<Range> textPiece = markedText.range();
3248 DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception), description};
3249 addMarker(textPiece->startContainer(exception), marker);
3253 void Document::removeMarkers(Range* range, DocumentMarker::MarkerType markerType)
3255 if (m_markers.isEmpty())
3258 ExceptionCode ec = 0;
3259 Node* startContainer = range->startContainer(ec);
3260 Node* endContainer = range->endContainer(ec);
3262 Node* pastLastNode = range->pastLastNode();
3263 for (Node* node = range->firstNode(); node != pastLastNode; node = node->traverseNextNode()) {
3264 int startOffset = node == startContainer ? range->startOffset(ec) : 0;
3265 int endOffset = node == endContainer ? range->endOffset(ec) : INT_MAX;
3266 int length = endOffset - startOffset;
3267 removeMarkers(node, startOffset, length, markerType);
3271 // Markers are stored in order sorted by their start offset.
3272 // Markers of the same type do not overlap each other.
3274 void Document::addMarker(Node* node, DocumentMarker newMarker)
3276 ASSERT(newMarker.endOffset >= newMarker.startOffset);
3277 if (newMarker.endOffset == newMarker.startOffset)
3280 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3283 vectorPair = new MarkerMapVectorPair;
3284 vectorPair->first.append(newMarker);
3285 vectorPair->second.append(placeholderRectForMarker());
3286 m_markers.set(node, vectorPair);
3288 Vector<DocumentMarker>& markers = vectorPair->first;
3289 Vector<IntRect>& rects = vectorPair->second;
3290 size_t numMarkers = markers.size();
3291 ASSERT(numMarkers == rects.size());
3293 // Iterate over all markers whose start offset is less than or equal to the new marker's.
3294 // If one of them is of the same type as the new marker and touches it or intersects with it
3295 // (there is at most one), remove it and adjust the new marker's start offset to encompass it.
3296 for (i = 0; i < numMarkers; ++i) {
3297 DocumentMarker marker = markers[i];
3298 if (marker.startOffset > newMarker.startOffset)
3300 if (marker.type == newMarker.type && marker.endOffset >= newMarker.startOffset) {
3301 newMarker.startOffset = marker.startOffset;
3309 // Iterate over all markers whose end offset is less than or equal to the new marker's,
3310 // removing markers of the same type as the new marker which touch it or intersect with it,
3311 // adjusting the new marker's end offset to cover them if necessary.
3312 while (j < numMarkers) {
3313 DocumentMarker marker = markers[j];
3314 if (marker.startOffset > newMarker.endOffset)
3316 if (marker.type == newMarker.type) {
3319 if (newMarker.endOffset <= marker.endOffset) {
3320 newMarker.endOffset = marker.endOffset;
3327 // At this point i points to the node before which we want to insert.
3328 markers.insert(i, newMarker);
3329 rects.insert(i, placeholderRectForMarker());
3332 // repaint the affected node
3333 if (node->renderer())
3334 node->renderer()->repaint();
3337 // copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
3338 // useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
3339 void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
3344 MarkerMapVectorPair* vectorPair = m_markers.get(srcNode);
3348 ASSERT(vectorPair->first.size() == vectorPair->second.size());
3350 bool docDirty = false;
3351 unsigned endOffset = startOffset + length - 1;
3352 Vector<DocumentMarker>& markers = vectorPair->first;
3353 for (size_t i = 0; i != markers.size(); ++i) {
3354 DocumentMarker marker = markers[i];
3356 // stop if we are now past the specified range
3357 if (marker.startOffset > endOffset)
3360 // skip marker that is before the specified range or is the wrong type
3361 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
3364 // pin the marker to the specified range and apply the shift delta
3366 if (marker.startOffset < startOffset)
3367 marker.startOffset = startOffset;
3368 if (marker.endOffset > endOffset)
3369 marker.endOffset = endOffset;
3370 marker.startOffset += delta;
3371 marker.endOffset += delta;
3373 addMarker(dstNode, marker);
3376 // repaint the affected node
3377 if (docDirty && dstNode->renderer())
3378 dstNode->renderer()->repaint();
3381 void Document::removeMarkers(Node* node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
3386 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3390 Vector<DocumentMarker>& markers = vectorPair->first;
3391 Vector<IntRect>& rects = vectorPair->second;
3392 ASSERT(markers.size() == rects.size());
3393 bool docDirty = false;
3394 unsigned endOffset = startOffset + length;
3395 for (size_t i = 0; i < markers.size();) {
3396 DocumentMarker marker = markers[i];
3398 // markers are returned in order, so stop if we are now past the specified range
3399 if (marker.startOffset >= endOffset)
3402 // skip marker that is wrong type or before target
3403 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
3408 // at this point we know that marker and target intersect in some way
3411 // pitch the old marker and any associated rect
3415 // add either of the resulting slices that are left after removing target
3416 if (startOffset > marker.startOffset) {
3417 DocumentMarker newLeft = marker;
3418 newLeft.endOffset = startOffset;
3419 markers.insert(i, newLeft);
3420 rects.insert(i, placeholderRectForMarker());
3421 // i now points to the newly-inserted node, but we want to skip that one
3424 if (marker.endOffset > endOffset) {
3425 DocumentMarker newRight = marker;
3426 newRight.startOffset = endOffset;
3427 markers.insert(i, newRight);
3428 rects.insert(i, placeholderRectForMarker());
3429 // i now points to the newly-inserted node, but we want to skip that one
3434 if (markers.isEmpty()) {
3435 ASSERT(rects.isEmpty());
3436 m_markers.remove(node);
3440 // repaint the affected node
3441 if (docDirty && node->renderer())
3442 node->renderer()->repaint();
3445 DocumentMarker* Document::markerContainingPoint(const IntPoint& point, DocumentMarker::MarkerType markerType)
3447 // outer loop: process each node that contains any markers
3448 MarkerMap::iterator end = m_markers.end();
3449 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3450 // inner loop; process each marker in this node
3451 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3452 Vector<DocumentMarker>& markers = vectorPair->first;
3453 Vector<IntRect>& rects = vectorPair->second;
3454 ASSERT(markers.size() == rects.size());
3455 unsigned markerCount = markers.size();
3456 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3457 DocumentMarker& marker = markers[markerIndex];
3459 // skip marker that is wrong type
3460 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3463 IntRect& r = rects[markerIndex];
3465 // skip placeholder rects
3466 if (r == placeholderRectForMarker())
3469 if (r.contains(point))
3477 Vector<DocumentMarker> Document::markersForNode(Node* node)
3479 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3481 return vectorPair->first;
3482 return Vector<DocumentMarker>();
3485 Vector<IntRect> Document::renderedRectsForMarkers(DocumentMarker::MarkerType markerType)
3487 Vector<IntRect> result;
3489 // outer loop: process each node
3490 MarkerMap::iterator end = m_markers.end();
3491 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3492 // inner loop; process each marker in this node
3493 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3494 Vector<DocumentMarker>& markers = vectorPair->first;
3495 Vector<IntRect>& rects = vectorPair->second;
3496 ASSERT(markers.size() == rects.size());
3497 unsigned markerCount = markers.size();
3498 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3499 DocumentMarker marker = markers[markerIndex];
3501 // skip marker that is wrong type
3502 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3505 IntRect r = rects[markerIndex];
3506 // skip placeholder rects
3507 if (r == placeholderRectForMarker())
3517 void Document::removeMarkers(Node* node)
3519 MarkerMap::iterator i = m_markers.find(node);
3520 if (i != m_markers.end()) {
3522 m_markers.remove(i);
3523 if (RenderObject* renderer = node->renderer())
3524 renderer->repaint();
3528 void Document::removeMarkers(DocumentMarker::MarkerType markerType)
3530 // outer loop: process each markered node in the document
3531 MarkerMap markerMapCopy = m_markers;
3532 MarkerMap::iterator end = markerMapCopy.end();
3533 for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
3534 Node* node = i->first.get();
3535 bool nodeNeedsRepaint = false;
3537 // inner loop: process each marker in the current node
3538 MarkerMapVectorPair* vectorPair = i->second;
3539 Vector<DocumentMarker>& markers = vectorPair->first;
3540 Vector<IntRect>& rects = vectorPair->second;
3541 ASSERT(markers.size() == rects.size());
3542 for (size_t i = 0; i != markers.size();) {
3543 DocumentMarker marker = markers[i];
3545 // skip nodes that are not of the specified type
3546 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
3551 // pitch the old marker
3554 nodeNeedsRepaint = true;
3555 // markerIterator now points to the next node
3558 // Redraw the node if it changed. Do this before the node is removed from m_markers, since
3559 // m_markers might contain the last reference to the node.
3560 if (nodeNeedsRepaint) {
3561 RenderObject* renderer = node->renderer();
3563 renderer->repaint();
3566 // delete the node's list if it is now empty
3567 if (markers.isEmpty()) {
3568 ASSERT(rects.isEmpty());
3569 m_markers.remove(node);
3575 void Document::repaintMarkers(DocumentMarker::MarkerType markerType)
3577 // outer loop: process each markered node in the document
3578 MarkerMap::iterator end = m_markers.end();
3579 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3580 Node* node = i->first.get();
3582 // inner loop: process each marker in the current node
3583 MarkerMapVectorPair* vectorPair = i->second;
3584 Vector<DocumentMarker>& markers = vectorPair->first;
3585 bool nodeNeedsRepaint = false;
3586 for (size_t i = 0; i != markers.size(); ++i) {
3587 DocumentMarker marker = markers[i];
3589 // skip nodes that are not of the specified type
3590 if (marker.type == markerType || markerType == DocumentMarker::AllMarkers) {
3591 nodeNeedsRepaint = true;
3596 if (!nodeNeedsRepaint)
3599 // cause the node to be redrawn
3600 if (RenderObject* renderer = node->renderer())
3601 renderer->repaint();
3605 void Document::setRenderedRectForMarker(Node* node, DocumentMarker marker, const IntRect& r)
3607 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3609 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3613 Vector<DocumentMarker>& markers = vectorPair->first;
3614 ASSERT(markers.size() == vectorPair->second.size());
3615 unsigned markerCount = markers.size();
3616 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3617 DocumentMarker m = markers[markerIndex];
3619 vectorPair->second[markerIndex] = r;
3624 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3627 void Document::invalidateRenderedRectsForMarkersInRect(const IntRect& r)
3629 // outer loop: process each markered node in the document
3630 MarkerMap::iterator end = m_markers.end();
3631 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3633 // inner loop: process each rect in the current node
3634 MarkerMapVectorPair* vectorPair = i->second;
3635 Vector<IntRect>& rects = vectorPair->second;
3637 unsigned rectCount = rects.size();
3638 for (unsigned rectIndex = 0; rectIndex < rectCount; ++rectIndex)
3639 if (rects[rectIndex].intersects(r))
3640 rects[rectIndex] = placeholderRectForMarker();
3644 void Document::shiftMarkers(Node *node, unsigned startOffset, int delta, DocumentMarker::MarkerType markerType)
3646 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3650 Vector<DocumentMarker>& markers = vectorPair->first;
3651 Vector<IntRect>& rects = vectorPair->second;
3652 ASSERT(markers.size() == rects.size());
3654 bool docDirty = false;
3655 for (size_t i = 0; i != markers.size(); ++i) {
3656 DocumentMarker &marker = markers[i];
3657 if (marker.startOffset >= startOffset && (markerType == DocumentMarker::AllMarkers || marker.type == markerType)) {
3658 ASSERT((int)marker.startOffset + delta >= 0);
3659 marker.startOffset += delta;
3660 marker.endOffset += delta;
3663 // Marker moved, so previously-computed rendered rectangle is now invalid
3664 rects[i] = placeholderRectForMarker();
3668 // repaint the affected node
3669 if (docDirty && node->renderer())
3670 node->renderer()->repaint();
3675 void Document::applyXSLTransform(ProcessingInstruction* pi)
3677 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
3678 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
3679 String resultMIMEType;
3681 String resultEncoding;
3682 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
3684 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
3685 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
3688 void Document::setTransformSource(void* doc)
3690 if (doc == m_transformSource)
3693 xmlFreeDoc((xmlDocPtr)m_transformSource);
3694 m_transformSource = doc;
3699 void Document::setDesignMode(InheritedBool value)
3701 m_designMode = value;
3704 Document::InheritedBool Document::getDesignMode() const
3706 return m_designMode;
3709 bool Document::inDesignMode() const
3711 for (const Document* d = this; d; d = d->parentDocument()) {
3712 if (d->m_designMode != inherit)
3713 return d->m_designMode;
3718 Document *Document::parentDocument() const
3720 Frame *childPart = frame();
3723 Frame *parent = childPart->tree()->parent();
3726 return parent->document();
3729 Document *Document::topDocument() const
3731 Document *doc = const_cast<Document *>(this);
3733 while ((element = doc->ownerElement()))
3734 doc = element->document();
3739 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
3741 String prefix, localName;
3742 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
3745 QualifiedName qName(prefix, localName, namespaceURI);
3746 if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
3751 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
3752 if (!shouldIgnoreNamespaceChecks && qName.localName() == "xmlns" && qName.namespaceURI() != "http://www.w3.org/2000/xmlns/") {
3757 // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
3758 // documents if we're wrong.
3759 return new Attr(0, this, MappedAttribute::create(qName, StringImpl::empty()));
3763 const SVGDocumentExtensions* Document::svgExtensions()
3765 return m_svgExtensions.get();
3768 SVGDocumentExtensions* Document::accessSVGExtensions()
3770 if (!m_svgExtensions)
3771 m_svgExtensions.set(new SVGDocumentExtensions(this));
3772 return m_svgExtensions.get();
3776 PassRefPtr<HTMLCollection> Document::images()
3778 return HTMLCollection::create(this, HTMLCollection::DocImages);
3781 PassRefPtr<HTMLCollection> Document::applets()
3783 return HTMLCollection::create(this, HTMLCollection::DocApplets);
3786 PassRefPtr<HTMLCollection> Document::embeds()
3788 return HTMLCollection::create(this, HTMLCollection::DocEmbeds);
3791 PassRefPtr<HTMLCollection> Document::plugins()
3793 // This is an alias for embeds() required for the JS DOM bindings.
3794 return HTMLCollection::create(this, HTMLCollection::DocEmbeds);
3797 PassRefPtr<HTMLCollection> Document::objects()
3799 return HTMLCollection::create(this, HTMLCollection::DocObjects);
3802 PassRefPtr<HTMLCollection> Document::scripts()
3804 return HTMLCollection::create(this, HTMLCollection::DocScripts);
3807 PassRefPtr<HTMLCollection> Document::links()
3809 return HTMLCollection::create(this, HTMLCollection::DocLinks);
3812 PassRefPtr<HTMLCollection> Document::forms()
3814 return HTMLCollection::create(this, HTMLCollection::DocForms);
3817 PassRefPtr<HTMLCollection> Document::anchors()
3819 return HTMLCollection::create(this, HTMLCollection::DocAnchors);
3822 PassRefPtr<HTMLCollection> Document::all()
3824 return HTMLCollection::create(this, HTMLCollection::DocAll);
3827 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
3829 return HTMLNameCollection::create(this, HTMLCollection::WindowNamedItems, name);
3832 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
3834 return HTMLNameCollection::create(this, HTMLCollection::DocumentNamedItems, name);
3837 HTMLCollection::CollectionInfo* Document::nameCollectionInfo(HTMLCollection::Type type, const AtomicString& name)
3839 ASSERT(type >= HTMLCollection::FirstNamedDocumentCachedType);
3840 unsigned index = type - HTMLCollection::FirstNamedDocumentCachedType;
3841 ASSERT(index < HTMLCollection::NumNamedDocumentCachedTypes);
3843 NamedCollectionMap& map = m_nameCollectionInfo[index];
3844 NamedCollectionMap::iterator iter = map.find(name.impl());
3845 if (iter == map.end())
3846 iter = map.add(name.impl(), new HTMLCollection::CollectionInfo).first;
3847 return iter->second;
3850 void Document::finishedParsing()
3854 ExceptionCode ec = 0;
3855 dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false), ec);
3857 if (Frame* f = frame())
3858 f->loader()->finishedParsing();
3861 Vector<String> Document::formElementsState() const
3863 Vector<String> stateVector;
3864 stateVector.reserveCapacity(m_formElementsWithState.size() * 3);
3865 typedef ListHashSet<HTMLFormControlElementWithState*>::const_iterator Iterator;
3866 Iterator end = m_formElementsWithState.end();
3867 for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
3868 HTMLFormControlElementWithState* e = *it;
3870 if (e->saveState(value)) {
3871 stateVector.append(e->name().string());
3872 stateVector.append(e->type().string());
3873 stateVector.append(value);
3881 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
3882 XPathNSResolver* resolver,
3885 if (!m_xpathEvaluator)
3886 m_xpathEvaluator = XPathEvaluator::create();
3887 return m_xpathEvaluator->createExpression(expression, resolver, ec);
3890 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
3892 if (!m_xpathEvaluator)
3893 m_xpathEvaluator = XPathEvaluator::create();
3894 return m_xpathEvaluator->createNSResolver(nodeResolver);
3897 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
3899 XPathNSResolver* resolver,
3900 unsigned short type,
3901 XPathResult* result,
3904 if (!m_xpathEvaluator)
3905 m_xpathEvaluator = XPathEvaluator::create();
3906 return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
3909 #endif // ENABLE(XPATH)
3911 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
3913 // Walk the state vector backwards so that the value to use for each
3914 // name/type pair first is the one at the end of each individual vector
3915 // in the FormElementStateMap. We're using them like stacks.
3916 typedef FormElementStateMap::iterator Iterator;
3917 m_formElementsWithState.clear();
3918 for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
3919 AtomicString a = stateVector[i - 3];
3920 AtomicString b = stateVector[i - 2];
3921 const String& c = stateVector[i - 1];
3922 FormElementKey key(a.impl(), b.impl());
3923 Iterator it = m_stateForNewFormElements.find(key);
3924 if (it != m_stateForNewFormElements.end())
3925 it->second.append(c);
3927 Vector<String> v(1);
3929 m_stateForNewFormElements.set(key, v);
3934 bool Document::hasStateForNewFormElements() const
3936 return !m_stateForNewFormElements.isEmpty();
3939 bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
3941 typedef FormElementStateMap::iterator Iterator;
3942 Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
3943 if (it == m_stateForNewFormElements.end())
3945 ASSERT(it->second.size());
3946 state = it->second.last();
3947 if (it->second.size() > 1)
3948 it->second.removeLast();
3950 m_stateForNewFormElements.remove(it);
3954 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
3955 : m_name(name), m_type(type)
3960 FormElementKey::~FormElementKey()
3965 FormElementKey::FormElementKey(const FormElementKey& other)
3966 : m_name(other.name()), m_type(other.type())
3971 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
3975 m_name = other.name();
3976 m_type = other.type();
3980 void FormElementKey::ref() const
3988 void FormElementKey::deref() const
3996 unsigned FormElementKeyHash::hash(const FormElementKey& k)
3998 ASSERT(sizeof(k) % (sizeof(uint16_t) * 2) == 0);
4000 unsigned l = sizeof(k) / (sizeof(uint16_t) * 2);
4001 const uint16_t* s = reinterpret_cast<const uint16_t*>(&k);
4002 uint32_t hash = PHI;
4005 for (; l > 0; l--) {
4007 uint32_t tmp = (s[1] << 11) ^ hash;
4008 hash = (hash << 16) ^ tmp;
4013 // Force "avalanching" of final 127 bits
4020 // this avoids ever returning a hash code of 0, since that is used to
4021 // signal "hash not computed yet", using a value that is likely to be
4022 // effectively the same as 0 when the low bits are masked
4029 void Document::setIconURL(const String& iconURL, const String& type)
4031 // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "type"
4032 if (m_iconURL.isEmpty())
4033 m_iconURL = iconURL;
4034 else if (!type.isEmpty())
4035 m_iconURL = iconURL;
4038 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4040 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4043 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4044 m_frame->updateSecureKeyboardEntryIfActive();
4047 bool Document::useSecureKeyboardEntryWhenActive() const
4049 return m_useSecureKeyboardEntryWhenActive;
4052 void Document::initSecurityContext()
4054 if (securityOrigin() && !securityOrigin()->isEmpty())
4055 return; // m_securityOrigin has already been initialized.
4058 // No source for a security context.
4059 // This can occur via document.implementation.createDocument().
4060 m_cookieURL = KURL("");
4061 ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::createEmpty());
4065 // In the common case, create the security context from the currently
4067 const KURL& url = m_frame->loader()->url();
4069 ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::create(url));
4071 if (FrameLoader::allowSubstituteDataAccessToLocal()) {
4072 // If this document was loaded with substituteData, then the document can
4073 // load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
4074 // and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
4076 DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
4077 if (documentLoader && documentLoader->substituteData().isValid())
4078 securityOrigin()->grantLoadLocalResources();
4081 if (!securityOrigin()->isEmpty())
4084 // If we do not obtain a meaningful origin from the URL, then we try to
4085 // find one via the frame hierarchy.
4087 Frame* ownerFrame = m_frame->tree()->parent();
4089 ownerFrame = m_frame->loader()->opener();
4091 if (ownerFrame && ownerFrame->document()) {
4092 m_cookieURL = ownerFrame->document()->cookieURL();
4093 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4094 // https://bugs.webkit.org/show_bug.cgi?id=15313
4095 ScriptExecutionContext::setSecurityOrigin(ownerFrame->document()->securityOrigin());
4099 void Document::setSecurityOrigin(SecurityOrigin* securityOrigin)
4101 ScriptExecutionContext::setSecurityOrigin(securityOrigin);
4102 // FIXME: Find a better place to enable DNS prefetch, which is a loader concept,
4103 // not applicable to arbitrary documents.
4107 void Document::updateFocusAppearanceSoon()
4109 if (!m_updateFocusAppearanceTimer.isActive())
4110 m_updateFocusAppearanceTimer.startOneShot(0);
4113 void Document::cancelFocusAppearanceUpdate()
4115 m_updateFocusAppearanceTimer.stop();
4118 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4120 Node* node = focusedNode();
4123 if (!node->isElementNode())
4128 Element* element = static_cast<Element*>(node);
4129 if (element->isFocusable())
4130 element->updateFocusAppearance(false);
4133 // FF method for accessing the selection added for compatability.
4134 DOMSelection* Document::getSelection() const
4136 return frame() ? frame()->domWindow()->getSelection() : 0;
4139 #if ENABLE(DATABASE)
4141 void Document::addOpenDatabase(Database* database)
4143 if (!m_openDatabaseSet)
4144 m_openDatabaseSet.set(new DatabaseSet);
4146 ASSERT(!m_openDatabaseSet->contains(database));
4147 m_openDatabaseSet->add(database);
4150 void Document::removeOpenDatabase(Database* database)
4152 ASSERT(m_openDatabaseSet && m_openDatabaseSet->contains(database));
4153 if (!m_openDatabaseSet)
4156 m_openDatabaseSet->remove(database);
4159 DatabaseThread* Document::databaseThread()
4161 if (!m_databaseThread && !m_hasOpenDatabases) {
4162 // Create the database thread on first request - but not if at least one database was already opened,
4163 // because in that case we already had a database thread and terminated it and should not create another.
4164 m_databaseThread = DatabaseThread::create(this);
4165 if (!m_databaseThread->start())
4166 m_databaseThread = 0;
4169 return m_databaseThread.get();
4172 void Document::stopDatabases()
4174 if (m_openDatabaseSet) {
4175 DatabaseSet::iterator i = m_openDatabaseSet->begin();
4176 DatabaseSet::iterator end = m_openDatabaseSet->end();
4177 for (; i != end; ++i) {
4179 if (m_databaseThread)
4180 m_databaseThread->unscheduleDatabaseTasks(*i);
4184 if (m_databaseThread)
4185 m_databaseThread->requestTermination();
4191 void Document::resetWMLPageState()
4193 if (WMLPageState* pageState = wmlPageStateForDocument(this))
4198 void Document::attachRange(Range* range)
4200 ASSERT(!m_ranges.contains(range));
4201 m_ranges.add(range);
4204 void Document::detachRange(Range* range)
4206 ASSERT(m_ranges.contains(range));
4207 m_ranges.remove(range);
4210 CanvasRenderingContext2D* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
4212 HTMLCanvasElement* result = getCSSCanvasElement(name);
4215 result->setSize(IntSize(width, height));
4216 return result->getContext(type);
4219 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
4221 RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
4223 result = new HTMLCanvasElement(canvasTag, this);
4224 m_cssCanvasElements.set(name, result);
4226 return result.get();
4229 void Document::initDNSPrefetch()
4231 m_haveExplicitlyDisabledDNSPrefetch = false;
4232 m_isDNSPrefetchEnabled = securityOrigin()->protocol() == "http";
4234 // Inherit DNS prefetch opt-out from parent frame
4235 if (Document* parent = parentDocument()) {
4236 if (!parent->isDNSPrefetchEnabled())
4237 m_isDNSPrefetchEnabled = false;
4241 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4243 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4244 m_isDNSPrefetchEnabled = true;
4248 m_isDNSPrefetchEnabled = false;
4249 m_haveExplicitlyDisabledDNSPrefetch = true;
4252 void Document::addTimeout(int timeoutId, DOMTimer* timer)
4254 ASSERT(!m_timeouts.get(timeoutId));
4255 m_timeouts.set(timeoutId, timer);
4258 void Document::removeTimeout(int timeoutId)
4260 DOMTimer* timer = m_timeouts.take(timeoutId);
4264 DOMTimer* Document::findTimeout(int timeoutId)
4266 return m_timeouts.get(timeoutId);
4269 void Document::reportException(const String& errorMessage, int lineNumber, const String& sourceURL)
4271 if (DOMWindow* window = domWindow())
4272 window->console()->addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, lineNumber, sourceURL);
4275 class ScriptExecutionContextTaskTimer : public TimerBase {
4277 ScriptExecutionContextTaskTimer(PassRefPtr<Document> context, PassRefPtr<ScriptExecutionContext::Task> task)
4278 : m_context(context)
4284 virtual void fired()
4286 m_task->performTask(m_context.get());
4290 RefPtr<Document> m_context;
4291 RefPtr<ScriptExecutionContext::Task> m_task;
4294 struct PerformTaskContext {
4295 PerformTaskContext(ScriptExecutionContext* scriptExecutionContext, PassRefPtr<ScriptExecutionContext::Task> task)
4296 : scriptExecutionContext(scriptExecutionContext)
4301 ScriptExecutionContext* scriptExecutionContext; // The context should exist until task execution.
4302 RefPtr<ScriptExecutionContext::Task> task;
4305 static void performTask(void* ctx)
4307 PerformTaskContext* ptctx = reinterpret_cast<PerformTaskContext*>(ctx);
4308 ptctx->task->performTask(ptctx->scriptExecutionContext);
4312 void Document::postTask(PassRefPtr<Task> task)
4314 if (isMainThread()) {
4315 ScriptExecutionContextTaskTimer* timer = new ScriptExecutionContextTaskTimer(static_cast<Document*>(this), task);
4316 timer->startOneShot(0);
4318 callOnMainThread(performTask, new PerformTaskContext(this, task));
4322 } // namespace WebCore