2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008 David Levin (levin@chromium.org)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
29 #include "AnimationController.h"
30 #include "AXObjectCache.h"
31 #include "CDATASection.h"
32 #include "CSSHelper.h"
33 #include "CSSStyleSelector.h"
34 #include "CSSStyleSheet.h"
35 #include "CSSValueKeywords.h"
37 #include "CachedCSSStyleSheet.h"
40 #include "CookieJar.h"
41 #include "DOMImplementation.h"
42 #include "DOMWindow.h"
43 #include "DocLoader.h"
44 #include "DocumentFragment.h"
45 #include "DocumentLoader.h"
46 #include "DocumentType.h"
47 #include "EditingText.h"
49 #include "EntityReference.h"
51 #include "EventHandler.h"
52 #include "EventListener.h"
53 #include "EventNames.h"
54 #include "ExceptionCode.h"
55 #include "FocusController.h"
57 #include "FrameLoader.h"
58 #include "FrameTree.h"
59 #include "FrameView.h"
60 #include "HTMLAnchorElement.h"
61 #include "HTMLBodyElement.h"
62 #include "HTMLCanvasElement.h"
63 #include "HTMLDocument.h"
64 #include "HTMLElementFactory.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "HTMLHeadElement.h"
67 #include "HTMLInputElement.h"
68 #include "HTMLLinkElement.h"
69 #include "HTMLMapElement.h"
70 #include "HTMLNameCollection.h"
71 #include "HTMLNames.h"
72 #include "HTMLStyleElement.h"
73 #include "HTMLTitleElement.h"
74 #include "HTTPParsers.h"
75 #include "HistoryItem.h"
76 #include "HitTestRequest.h"
77 #include "HitTestResult.h"
78 #include "ImageLoader.h"
79 #include "InspectorController.h"
80 #include "KeyboardEvent.h"
82 #include "MessageEvent.h"
83 #include "MouseEvent.h"
84 #include "MouseEventWithHitTestResults.h"
85 #include "MutationEvent.h"
86 #include "NameNodeList.h"
87 #include "NodeFilter.h"
88 #include "NodeIterator.h"
89 #include "NodeWithIndex.h"
90 #include "OverflowEvent.h"
92 #include "PlatformKeyboardEvent.h"
93 #include "ProcessingInstruction.h"
94 #include "ProgressEvent.h"
95 #include "RegisteredEventListener.h"
96 #include "RenderArena.h"
97 #include "RenderTextControl.h"
98 #include "RenderView.h"
99 #include "RenderWidget.h"
100 #include "ScriptController.h"
101 #include "SecurityOrigin.h"
102 #include "SegmentedString.h"
103 #include "SelectionController.h"
104 #include "Settings.h"
105 #include "StyleSheetList.h"
106 #include "TextEvent.h"
107 #include "TextIterator.h"
108 #include "TextResourceDecoder.h"
109 #include "TreeWalker.h"
112 #include "WebKitAnimationEvent.h"
113 #include "WebKitTransitionEvent.h"
114 #include "WheelEvent.h"
115 #include "XMLHttpRequest.h"
116 #include "XMLNames.h"
117 #include "XMLTokenizer.h"
118 #include "JSDOMBinding.h"
119 #include "ScriptController.h"
120 #include <wtf/CurrentTime.h>
121 #include <wtf/HashFunctions.h>
122 #include <wtf/MainThread.h>
123 #include <wtf/StdLibExtras.h>
124 #include <wtf/PassRefPtr.h>
127 #include "Database.h"
128 #include "DatabaseThread.h"
131 #if ENABLE(DOM_STORAGE)
132 #include "StorageEvent.h"
136 #include "XPathEvaluator.h"
137 #include "XPathExpression.h"
138 #include "XPathNSResolver.h"
139 #include "XPathResult.h"
143 #include "XSLTProcessor.h"
147 #include "XBLBindingManager.h"
151 #include "SVGDocumentExtensions.h"
152 #include "SVGElementFactory.h"
153 #include "SVGZoomEvent.h"
154 #include "SVGStyleElement.h"
158 #include "WMLDocument.h"
159 #include "WMLElement.h"
160 #include "WMLElementFactory.h"
161 #include "WMLNames.h"
166 using namespace Unicode;
170 using namespace HTMLNames;
172 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
174 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
175 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
177 static const int cLayoutScheduleThreshold = 250;
179 // Use 1 to represent the document's default form.
180 static HTMLFormElement* const defaultForm = reinterpret_cast<HTMLFormElement*>(1);
182 // DOM Level 2 says (letters added):
184 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
185 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
186 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
187 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
188 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
189 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
190 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
191 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
192 // i) Characters ':' and '_' are allowed as name-start characters.
193 // j) Characters '-' and '.' are allowed as name characters.
195 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
197 static inline bool isValidNameStart(UChar32 c)
200 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
204 if (c == ':' || c == '_')
207 // rules (a) and (f) above
208 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
209 if (!(Unicode::category(c) & nameStartMask))
213 if (c >= 0xF900 && c < 0xFFFE)
217 DecompositionType decompType = decompositionType(c);
218 if (decompType == DecompositionFont || decompType == DecompositionCompat)
224 static inline bool isValidNamePart(UChar32 c)
226 // rules (a), (e), and (i) above
227 if (isValidNameStart(c))
230 // rules (g) and (h) above
231 if (c == 0x00B7 || c == 0x0387)
235 if (c == '-' || c == '.')
238 // rules (b) and (f) above
239 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
240 if (!(Unicode::category(c) & otherNamePartMask))
244 if (c >= 0xF900 && c < 0xFFFE)
248 DecompositionType decompType = decompositionType(c);
249 if (decompType == DecompositionFont || decompType == DecompositionCompat)
255 static Widget* widgetForNode(Node* focusedNode)
259 RenderObject* renderer = focusedNode->renderer();
260 if (!renderer || !renderer->isWidget())
262 return static_cast<RenderWidget*>(renderer)->widget();
265 static bool acceptsEditingFocus(Node *node)
268 ASSERT(node->isContentEditable());
270 Node *root = node->rootEditableElement();
271 Frame* frame = node->document()->frame();
275 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
278 static HashSet<Document*>* changedDocuments = 0;
280 Document::Document(Frame* frame, bool isXHTML)
282 , m_domtree_version(0)
283 , m_styleSheets(StyleSheetList::create(this))
284 , m_frameElementsShouldIgnoreScrolling(false)
286 , m_titleSetExplicitly(false)
287 , m_imageLoadEventTimer(this, &Document::imageLoadEventTimerFired)
288 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
290 , m_transformSource(0)
292 , m_xmlVersion("1.0")
293 , m_xmlStandalone(false)
295 , m_bindingManager(new XBLBindingManager(this))
299 , m_designMode(inherit)
300 , m_selfOnlyRefCount(0)
304 #if ENABLE(DASHBOARD_SUPPORT)
305 , m_hasDashboardRegions(false)
306 , m_dashboardRegionsDirty(false)
308 , m_accessKeyMapValid(false)
309 , m_createRenderers(true)
310 , m_inPageCache(false)
311 , m_useSecureKeyboardEntryWhenActive(false)
313 , m_numNodeListCaches(0)
315 , m_hasOpenDatabases(false)
317 , m_usingGeolocation(false)
318 #if USE(LOW_BANDWIDTH_DISPLAY)
319 , m_inLowBandwidthDisplay(false)
322 m_document.resetSkippingRef(this);
326 m_ignoreAutofocus = false;
333 m_docLoader = new DocLoader(this);
335 visuallyOrdered = false;
337 m_docChanged = false;
339 m_wellFormed = false;
341 setParseMode(Strict);
343 m_textColor = Color::black;
346 m_inStyleRecalc = false;
347 m_closeAfterStyleRecalc = false;
348 m_usesDescendantRules = false;
349 m_usesSiblingRules = false;
350 m_usesFirstLineRules = false;
351 m_usesFirstLetterRules = false;
352 m_usesBeforeAfterRules = false;
353 m_gotoAnchorNeededAfterStylesheetsLoad = false;
356 m_didCalculateStyleSelector = false;
357 m_pendingStylesheets = 0;
358 m_ignorePendingStylesheets = false;
359 m_hasNodesWithPlaceholderStyle = false;
360 m_pendingSheetLayout = NoLayoutWithPendingSheets;
365 resetVisitedLinkColor();
366 resetActiveLinkColor();
368 m_processingLoadEvent = false;
369 m_startTime = currentTime();
370 m_overMinimumLayoutThreshold = false;
372 initSecurityContext();
375 static int docID = 0;
379 void Document::removedLastRef()
381 ASSERT(!m_deletionHasBegun);
382 if (m_selfOnlyRefCount) {
383 // If removing a child removes the last self-only ref, we don't
384 // want the document to be destructed until after
385 // removeAllChildren returns, so we guard ourselves with an
386 // extra self-only ref.
388 DocPtr<Document> guard(this);
390 // We must make sure not to be retaining any of our children through
391 // these extra pointers or we will create a reference cycle.
397 m_documentElement = 0;
401 deleteAllValues(m_markers);
407 m_cssCanvasElements.clear();
410 m_inRemovedLastRefFunction = false;
414 m_deletionHasBegun = true;
420 Document::~Document()
423 ASSERT(!m_inPageCache);
424 ASSERT(!m_savedRenderer);
425 ASSERT(m_ranges.isEmpty());
427 removeAllEventListeners();
429 forgetAllDOMNodesForDocument(this);
431 if (m_docChanged && changedDocuments)
432 changedDocuments->remove(this);
434 m_document.resetSkippingRef(0);
435 delete m_styleSelector;
439 delete m_renderArena;
444 xmlFreeDoc((xmlDocPtr)m_transformSource);
448 delete m_bindingManager;
451 deleteAllValues(m_markers);
453 clearAXObjectCache();
457 unsigned count = sizeof(m_nameCollectionInfo) / sizeof(m_nameCollectionInfo[0]);
458 for (unsigned i = 0; i < count; i++)
459 deleteAllValues(m_nameCollectionInfo[i]);
462 if (m_databaseThread) {
463 ASSERT(m_databaseThread->terminationRequested());
464 m_databaseThread = 0;
469 m_styleSheets->documentDestroyed();
474 void Document::resetLinkColor()
476 m_linkColor = Color(0, 0, 238);
479 void Document::resetVisitedLinkColor()
481 m_visitedLinkColor = Color(85, 26, 139);
484 void Document::resetActiveLinkColor()
486 m_activeLinkColor.setNamedColor("red");
489 void Document::setDocType(PassRefPtr<DocumentType> docType)
491 // This should never be called more than once.
492 // Note: This is not a public DOM method and can only be called by the parser.
493 ASSERT(!m_docType || !docType);
494 if (m_docType && docType)
498 m_docType->setDocument(this);
499 determineParseMode();
502 DOMImplementation* Document::implementation() const
504 if (!m_implementation)
505 m_implementation = DOMImplementation::create();
506 return m_implementation.get();
509 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
511 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
513 // Invalidate the document element we have cached in case it was replaced.
514 m_documentElement = 0;
517 void Document::cacheDocumentElement() const
519 ASSERT(!m_documentElement);
520 Node* n = firstChild();
521 while (n && !n->isElementNode())
522 n = n->nextSibling();
523 m_documentElement = static_cast<Element*>(n);
526 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
528 if (!isValidName(name)) {
529 ec = INVALID_CHARACTER_ERR;
534 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
536 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
539 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
541 return new DocumentFragment(document());
544 PassRefPtr<Text> Document::createTextNode(const String& data)
546 return new Text(this, data);
549 PassRefPtr<Comment> Document::createComment(const String& data)
551 return new Comment(this, data);
554 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
556 if (isHTMLDocument()) {
557 ec = NOT_SUPPORTED_ERR;
560 return new CDATASection(this, data);
563 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
565 if (!isValidName(target)) {
566 ec = INVALID_CHARACTER_ERR;
569 if (isHTMLDocument()) {
570 ec = NOT_SUPPORTED_ERR;
573 return new ProcessingInstruction(this, target, data);
576 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
578 if (!isValidName(name)) {
579 ec = INVALID_CHARACTER_ERR;
582 if (isHTMLDocument()) {
583 ec = NOT_SUPPORTED_ERR;
586 return new EntityReference(this, name);
589 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
591 return new EditingText(this, text);
594 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
596 return CSSMutableStyleDeclaration::create();
599 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
604 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
605 || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
608 ec = NOT_SUPPORTED_ERR;
612 switch (importedNode->nodeType()) {
614 return createTextNode(importedNode->nodeValue());
615 case CDATA_SECTION_NODE:
616 return createCDATASection(importedNode->nodeValue(), ec);
617 case ENTITY_REFERENCE_NODE:
618 return createEntityReference(importedNode->nodeName(), ec);
619 case PROCESSING_INSTRUCTION_NODE:
620 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
622 return createComment(importedNode->nodeValue());
624 Element* oldElement = static_cast<Element*>(importedNode);
625 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
630 NamedAttrMap* attrs = oldElement->attributes(true);
632 unsigned length = attrs->length();
633 for (unsigned i = 0; i < length; i++) {
634 Attribute* attr = attrs->attributeItem(i);
635 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
641 newElement->copyNonAttributeProperties(oldElement);
644 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
645 RefPtr<Node> newChild = importNode(oldChild, true, ec);
648 newElement->appendChild(newChild.release(), ec);
654 return newElement.release();
656 case ATTRIBUTE_NODE: {
657 RefPtr<Attr> newAttr = new Attr(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
658 newAttr->createTextChild();
659 return newAttr.release();
661 case DOCUMENT_FRAGMENT_NODE: {
662 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
663 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
665 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
666 RefPtr<Node> newChild = importNode(oldChild, true, ec);
669 newFragment->appendChild(newChild.release(), ec);
675 return newFragment.release();
679 // 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.
680 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
682 case DOCUMENT_TYPE_NODE:
683 case XPATH_NAMESPACE_NODE:
687 ec = NOT_SUPPORTED_ERR;
692 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
695 ec = NOT_SUPPORTED_ERR;
699 if (source->isReadOnlyNode()) {
700 ec = NO_MODIFICATION_ALLOWED_ERR;
704 switch (source->nodeType()) {
708 case DOCUMENT_TYPE_NODE:
709 case XPATH_NAMESPACE_NODE:
710 ec = NOT_SUPPORTED_ERR;
712 case ATTRIBUTE_NODE: {
713 Attr* attr = static_cast<Attr*>(source.get());
714 if (attr->ownerElement())
715 attr->ownerElement()->removeAttributeNode(attr, ec);
716 attr->setSpecified(true);
720 if (source->parentNode())
721 source->parentNode()->removeChild(source.get(), ec);
724 for (Node* node = source.get(); node; node = node->traverseNextNode(source.get()))
725 node->setDocument(this);
730 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
732 DEFINE_STATIC_LOCAL(const AtomicString, xmlnsNamespaceURI, ("http://www.w3.org/2000/xmlns/"));
733 DEFINE_STATIC_LOCAL(const AtomicString, xmlns, ("xmlns"));
734 DEFINE_STATIC_LOCAL(const AtomicString, xml, ("xml"));
736 // These checks are from DOM Core Level 2, createElementNS
737 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
738 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
740 if (qName.prefix() == xml && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
743 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
744 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
745 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
746 if ((qName.prefix() == xmlns && qName.namespaceURI() != xmlnsNamespaceURI) || (qName.prefix() != xmlns && qName.namespaceURI() == xmlnsNamespaceURI))
752 // FIXME: This should really be in a possible ElementFactory class
753 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
757 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
758 if (qName.namespaceURI() == xhtmlNamespaceURI)
759 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
761 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
762 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
765 else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI || isWMLDocument())
766 e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
770 e = new Element(qName, document());
772 // <image> uses imgTag so we need a special rule.
773 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
778 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
780 String prefix, localName;
781 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
784 QualifiedName qName(prefix, localName, namespaceURI);
785 if (hasPrefixNamespaceMismatch(qName)) {
790 return createElement(qName, false);
793 Element* Document::getElementById(const AtomicString& elementId) const
795 if (elementId.isEmpty())
798 Element* element = m_elementsById.get(elementId.impl());
802 if (m_duplicateIds.contains(elementId.impl())) {
803 // We know there's at least one node with this id, but we don't know what the first one is.
804 for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
805 if (n->isElementNode()) {
806 element = static_cast<Element*>(n);
807 if (element->hasID() && element->getAttribute(idAttr) == elementId) {
808 m_duplicateIds.remove(elementId.impl());
809 m_elementsById.set(elementId.impl(), element);
814 ASSERT_NOT_REACHED();
819 String Document::readyState() const
821 if (Frame* f = frame()) {
822 if (f->loader()->isComplete())
827 // FIXME: What does "interactive" mean?
828 // FIXME: Missing support for "uninitialized".
833 String Document::inputEncoding() const
835 if (TextResourceDecoder* d = decoder())
836 return d->encoding().name();
840 String Document::defaultCharset() const
842 if (Settings* settings = this->settings())
843 return settings->defaultTextEncodingName();
847 void Document::setCharset(const String& charset)
851 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
854 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
856 if (!implementation()->hasFeature("XML", String())) {
857 ec = NOT_SUPPORTED_ERR;
861 // FIXME: Also raise NOT_SUPPORTED_ERR if the version is set to a value that is not supported by this Document.
863 m_xmlVersion = version;
866 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
868 if (!implementation()->hasFeature("XML", String())) {
869 ec = NOT_SUPPORTED_ERR;
873 m_xmlStandalone = standalone;
876 void Document::setDocumentURI(const String& uri)
882 KURL Document::baseURI() const
887 Element* Document::elementFromPoint(int x, int y) const
892 HitTestRequest request(HitTestRequest::ReadOnly |
893 HitTestRequest::Active);
894 HitTestResult result(IntPoint(x, y));
895 renderView()->layer()->hitTest(request, result);
897 Node* n = result.innerNode();
898 while (n && !n->isElementNode())
901 n = n->shadowAncestorNode();
902 return static_cast<Element*>(n);
905 void Document::addElementById(const AtomicString& elementId, Element* element)
907 typedef HashMap<AtomicStringImpl*, Element*>::iterator iterator;
908 if (!m_duplicateIds.contains(elementId.impl())) {
909 // Fast path. The ID is not already in m_duplicateIds, so we assume that it's
910 // also not already in m_elementsById and do an add. If that add succeeds, we're done.
911 pair<iterator, bool> addResult = m_elementsById.add(elementId.impl(), element);
912 if (addResult.second)
914 // The add failed, so this ID was already cached in m_elementsById.
915 // There are multiple elements with this ID. Remove the m_elementsById
916 // cache for this ID so getElementById searches for it next time it is called.
917 m_elementsById.remove(addResult.first);
918 m_duplicateIds.add(elementId.impl());
920 // There are multiple elements with this ID. If it exists, remove the m_elementsById
921 // cache for this ID so getElementById searches for it next time it is called.
922 iterator cachedItem = m_elementsById.find(elementId.impl());
923 if (cachedItem != m_elementsById.end()) {
924 m_elementsById.remove(cachedItem);
925 m_duplicateIds.add(elementId.impl());
928 m_duplicateIds.add(elementId.impl());
931 void Document::removeElementById(const AtomicString& elementId, Element* element)
933 if (m_elementsById.get(elementId.impl()) == element)
934 m_elementsById.remove(elementId.impl());
936 m_duplicateIds.remove(elementId.impl());
939 Element* Document::getElementByAccessKey(const String& key) const
943 if (!m_accessKeyMapValid) {
944 for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
945 if (!n->isElementNode())
947 Element* element = static_cast<Element*>(n);
948 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
949 if (!accessKey.isEmpty())
950 m_elementsByAccessKey.set(accessKey.impl(), element);
952 m_accessKeyMapValid = true;
954 return m_elementsByAccessKey.get(key.impl());
957 void Document::updateTitle()
959 if (Frame* f = frame())
960 f->loader()->setTitle(m_title);
963 void Document::setTitle(const String& title, Element* titleElement)
966 // Title set by JavaScript -- overrides any title elements.
967 m_titleSetExplicitly = true;
968 if (!isHTMLDocument())
970 else if (!m_titleElement) {
971 if (HTMLElement* headElement = head()) {
972 ExceptionCode ec = 0;
973 m_titleElement = createElement("title", ec);
975 headElement->appendChild(m_titleElement, ec);
979 } else if (titleElement != m_titleElement) {
980 if (m_titleElement || m_titleSetExplicitly)
981 // Only allow the first title element to change the title -- others have no effect.
983 m_titleElement = titleElement;
986 if (m_title == title)
992 if (m_titleSetExplicitly && m_titleElement && m_titleElement->hasTagName(titleTag))
993 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(m_title);
996 void Document::removeTitle(Element* titleElement)
998 if (m_titleElement != titleElement)
1002 m_titleSetExplicitly = false;
1004 // Update title based on first title element in the head, if one exists.
1005 if (HTMLElement* headElement = head()) {
1006 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1007 if (e->hasTagName(titleTag)) {
1008 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1009 setTitle(titleElement->text(), titleElement);
1014 if (!m_titleElement && !m_title.isEmpty()) {
1020 String Document::nodeName() const
1025 Node::NodeType Document::nodeType() const
1027 return DOCUMENT_NODE;
1030 FrameView* Document::view() const
1032 return m_frame ? m_frame->view() : 0;
1035 Page* Document::page() const
1037 return m_frame ? m_frame->page() : 0;
1040 Settings* Document::settings() const
1042 return m_frame ? m_frame->settings() : 0;
1045 PassRefPtr<Range> Document::createRange()
1047 return Range::create(this);
1050 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1051 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1054 ec = NOT_SUPPORTED_ERR;
1057 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1060 PassRefPtr<TreeWalker> Document::createTreeWalker(Node *root, unsigned whatToShow,
1061 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1064 ec = NOT_SUPPORTED_ERR;
1067 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1070 void Document::setDocumentChanged(bool b)
1073 if (!m_docChanged) {
1074 if (!changedDocuments)
1075 changedDocuments = new HashSet<Document*>;
1076 changedDocuments->add(this);
1078 if (m_accessKeyMapValid) {
1079 m_accessKeyMapValid = false;
1080 m_elementsByAccessKey.clear();
1083 if (m_docChanged && changedDocuments)
1084 changedDocuments->remove(this);
1090 void Document::recalcStyle(StyleChange change)
1092 // we should not enter style recalc while painting
1093 if (frame() && frame()->view() && frame()->view()->isPainting()) {
1094 ASSERT(!frame()->view()->isPainting());
1098 if (m_inStyleRecalc)
1099 return; // Guard against re-entrancy. -dwh
1101 m_inStyleRecalc = true;
1102 suspendPostAttachCallbacks();
1104 ASSERT(!renderer() || renderArena());
1105 if (!renderer() || !renderArena())
1108 if (change == Force) {
1109 // style selector may set this again during recalc
1110 m_hasNodesWithPlaceholderStyle = false;
1112 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1113 documentStyle->setDisplay(BLOCK);
1114 documentStyle->setVisuallyOrdered(visuallyOrdered);
1115 documentStyle->setZoom(frame()->pageZoomFactor());
1116 m_styleSelector->setStyle(documentStyle);
1118 FontDescription fontDescription;
1119 fontDescription.setUsePrinterFont(printing());
1120 if (Settings* settings = this->settings()) {
1121 fontDescription.setRenderingMode(settings->fontRenderingMode());
1122 if (printing() && !settings->shouldPrintBackgrounds())
1123 documentStyle->setForceBackgroundsToWhite(true);
1124 const AtomicString& stdfont = settings->standardFontFamily();
1125 if (!stdfont.isEmpty()) {
1126 fontDescription.firstFamily().setFamily(stdfont);
1127 fontDescription.firstFamily().appendFamily(0);
1129 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1130 m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSSValueMedium, inCompatMode(), false));
1133 documentStyle->setFontDescription(fontDescription);
1134 documentStyle->font().update(m_styleSelector->fontSelector());
1136 documentStyle->setHtmlHacks(true); // enable html specific rendering tricks
1138 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1139 if (renderer() && ch != NoChange)
1140 renderer()->setStyle(documentStyle.release());
1141 if (change != Force)
1145 for (Node* n = firstChild(); n; n = n->nextSibling())
1146 if (change >= Inherit || n->hasChangedChild() || n->changed())
1147 n->recalcStyle(change);
1152 #if USE(ACCELERATED_COMPOSITING)
1154 // If we didn't update compositing layers because of layout(), we need to do so here.
1155 view()->updateCompositingLayers();
1161 setChanged(NoStyleChange);
1162 setHasChangedChild(false);
1163 setDocumentChanged(false);
1165 resumePostAttachCallbacks();
1166 m_inStyleRecalc = false;
1168 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1169 if (m_closeAfterStyleRecalc) {
1170 m_closeAfterStyleRecalc = false;
1175 void Document::updateRendering()
1177 if (!hasChangedChild() || inPageCache())
1181 m_frame->animation()->beginAnimationUpdate();
1183 recalcStyle(NoChange);
1185 // Tell the animation controller that updateRendering is finished and it can do any post-processing
1187 m_frame->animation()->endAnimationUpdate();
1190 void Document::updateDocumentsRendering()
1192 if (!changedDocuments)
1195 while (changedDocuments->size()) {
1196 HashSet<Document*>::iterator it = changedDocuments->begin();
1197 Document* doc = *it;
1198 changedDocuments->remove(it);
1200 doc->m_docChanged = false;
1201 doc->updateRendering();
1205 void Document::updateLayout()
1207 if (Element* oe = ownerElement())
1208 oe->document()->updateLayout();
1212 // Only do a layout if changes have occurred that make it necessary.
1213 FrameView* v = view();
1214 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1218 // FIXME: This is a bad idea and needs to be removed eventually.
1219 // Other browsers load stylesheets before they continue parsing the web page.
1220 // Since we don't, we can run JavaScript code that needs answers before the
1221 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1222 // lets us get reasonable answers. The long term solution to this problem is
1223 // to instead suspend JavaScript execution.
1224 void Document::updateLayoutIgnorePendingStylesheets()
1226 bool oldIgnore = m_ignorePendingStylesheets;
1228 if (!haveStylesheetsLoaded()) {
1229 m_ignorePendingStylesheets = true;
1230 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1231 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1232 // with accurate style information. (Our suppression involves blanking the whole page at the
1233 // moment. If it were more refined, we might be able to do something better.)
1234 // It's worth noting though that this entire method is a hack, since what we really want to do is
1235 // suspend JS instead of doing a layout with inaccurate information.
1236 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1237 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1238 updateStyleSelector();
1239 } else if (m_hasNodesWithPlaceholderStyle)
1240 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1241 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1242 // but here we need up-to-date style immediatly.
1248 m_ignorePendingStylesheets = oldIgnore;
1251 void Document::attach()
1253 ASSERT(!attached());
1254 ASSERT(!m_inPageCache);
1255 ASSERT(!m_axObjectCache);
1258 m_renderArena = new RenderArena();
1260 // Create the rendering tree
1261 setRenderer(new (m_renderArena) RenderView(this, view()));
1262 #if USE(ACCELERATED_COMPOSITING)
1263 renderView()->didMoveOnscreen();
1266 if (!m_styleSelector) {
1267 bool matchAuthorAndUserStyles = true;
1268 if (Settings* docSettings = settings())
1269 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1270 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
1275 RenderObject* render = renderer();
1278 ContainerNode::attach();
1280 setRenderer(render);
1283 void Document::detach()
1286 ASSERT(!m_inPageCache);
1288 clearAXObjectCache();
1289 stopActiveDOMObjects();
1291 RenderObject* render = renderer();
1293 #if USE(ACCELERATED_COMPOSITING)
1295 renderView()->willMoveOffscreen();
1298 // indicate destruction mode, i.e. attached() but renderer == 0
1301 // Empty out these lists as a performance optimization, since detaching
1302 // all the individual render objects will cause all the RenderImage
1303 // objects to remove themselves from the lists.
1304 m_imageLoadEventDispatchSoonList.clear();
1305 m_imageLoadEventDispatchingList.clear();
1311 ContainerNode::detach();
1316 // This is required, as our Frame might delete itself as soon as it detaches
1317 // us. However, this violates Node::detach() symantics, as it's never
1318 // possible to re-attach. Eventually Document::detach() should be renamed
1319 // or this call made explicit in each of the callers of Document::detach().
1320 clearFramePointer();
1322 if (m_renderArena) {
1323 delete m_renderArena;
1328 void Document::clearFramePointer()
1333 void Document::removeAllEventListenersFromAllNodes()
1335 size_t size = m_windowEventListeners.size();
1336 for (size_t i = 0; i < size; ++i)
1337 m_windowEventListeners[i]->setRemoved(true);
1338 m_windowEventListeners.clear();
1339 removeAllDisconnectedNodeEventListeners();
1340 for (Node* node = this; node; node = node->traverseNextNode())
1341 node->removeAllEventListeners();
1344 void Document::registerDisconnectedNodeWithEventListeners(Node* node)
1346 m_disconnectedNodesWithEventListeners.add(node);
1349 void Document::unregisterDisconnectedNodeWithEventListeners(Node* node)
1351 m_disconnectedNodesWithEventListeners.remove(node);
1354 void Document::removeAllDisconnectedNodeEventListeners()
1356 HashSet<Node*>::iterator end = m_disconnectedNodesWithEventListeners.end();
1357 for (HashSet<Node*>::iterator i = m_disconnectedNodesWithEventListeners.begin(); i != end; ++i)
1358 (*i)->removeAllEventListeners();
1359 m_disconnectedNodesWithEventListeners.clear();
1362 RenderView* Document::renderView() const
1364 return toRenderView(renderer());
1367 void Document::clearAXObjectCache()
1369 // clear cache in top document
1370 if (m_axObjectCache) {
1371 delete m_axObjectCache;
1372 m_axObjectCache = 0;
1376 // ask the top-level document to clear its cache
1377 Document* doc = topDocument();
1379 doc->clearAXObjectCache();
1382 AXObjectCache* Document::axObjectCache() const
1384 // The only document that actually has a AXObjectCache is the top-level
1385 // document. This is because we need to be able to get from any WebCoreAXObject
1386 // to any other WebCoreAXObject on the same page. Using a single cache allows
1387 // lookups across nested webareas (i.e. multiple documents).
1389 if (m_axObjectCache) {
1390 // return already known top-level cache
1391 if (!ownerElement())
1392 return m_axObjectCache;
1394 // In some pages with frames, the cache is created before the sub-webarea is
1395 // inserted into the tree. Here, we catch that case and just toss the old
1396 // cache and start over.
1397 // NOTE: This recovery may no longer be needed. I have been unable to trigger
1398 // it again. See rdar://5794454
1399 // FIXME: Can this be fixed when inserting the subframe instead of now?
1400 // FIXME: If this function was called to get the cache in order to remove
1401 // an AXObject, we are now deleting the cache as a whole and returning a
1402 // new empty cache that does not contain the AXObject! That should actually
1403 // be OK. I am concerned about other cases like this where accessing the
1404 // cache blows away the AXObject being operated on.
1405 delete m_axObjectCache;
1406 m_axObjectCache = 0;
1409 // ask the top-level document for its cache
1410 Document* doc = topDocument();
1412 return doc->axObjectCache();
1414 // this is the top-level document, so install a new cache
1415 m_axObjectCache = new AXObjectCache;
1416 return m_axObjectCache;
1419 void Document::setVisuallyOrdered()
1421 visuallyOrdered = true;
1423 renderer()->style()->setVisuallyOrdered(true);
1426 Tokenizer* Document::createTokenizer()
1428 // FIXME: this should probably pass the frame instead
1429 return new XMLTokenizer(this, view());
1432 void Document::open(Document* ownerDocument)
1434 if (ownerDocument) {
1435 setURL(ownerDocument->url());
1436 m_cookieURL = ownerDocument->cookieURL();
1437 ScriptExecutionContext::setSecurityOrigin(ownerDocument->securityOrigin());
1441 if (m_frame->loader()->isLoadingMainResource() || (tokenizer() && tokenizer()->executingScript()))
1444 if (m_frame->loader()->state() == FrameStateProvisional)
1445 m_frame->loader()->stopAllLoaders();
1451 m_frame->loader()->didExplicitOpen();
1454 void Document::cancelParsing()
1457 // We have to clear the tokenizer to avoid possibly triggering
1458 // the onload handler when closing as a side effect of a cancel-style
1459 // change, such as opening a new document or closing the window while
1467 void Document::implicitOpen()
1472 m_tokenizer = createTokenizer();
1476 HTMLElement* Document::body() const
1478 Node* de = documentElement();
1482 // try to prefer a FRAMESET element over BODY
1484 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
1485 if (i->hasTagName(framesetTag))
1486 return static_cast<HTMLElement*>(i);
1488 if (i->hasTagName(bodyTag) && !body)
1491 return static_cast<HTMLElement*>(body);
1494 void Document::setBody(PassRefPtr<HTMLElement> newBody, ExceptionCode& ec)
1496 if (!newBody || !documentElement()) {
1497 ec = HIERARCHY_REQUEST_ERR;
1501 HTMLElement* b = body();
1503 documentElement()->appendChild(newBody, ec);
1505 documentElement()->replaceChild(newBody, b, ec);
1508 HTMLHeadElement* Document::head()
1510 Node* de = documentElement();
1514 for (Node* e = de->firstChild(); e; e = e->nextSibling())
1515 if (e->hasTagName(headTag))
1516 return static_cast<HTMLHeadElement*>(e);
1521 void Document::close()
1523 Frame* frame = this->frame();
1525 // This code calls implicitClose() if all loading has completed.
1526 FrameLoader* frameLoader = frame->loader();
1527 frameLoader->endIfNotLoadingMainResource();
1528 frameLoader->checkCompleted();
1530 // Because we have no frame, we don't know if all loading has completed,
1531 // so we just call implicitClose() immediately. FIXME: This might fire
1532 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
1537 void Document::implicitClose()
1539 // 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.
1540 if (m_inStyleRecalc) {
1541 m_closeAfterStyleRecalc = true;
1545 bool wasLocationChangePending = frame() && frame()->loader()->isScheduledLocationChangePending();
1546 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1551 m_processingLoadEvent = true;
1553 m_wellFormed = m_tokenizer && m_tokenizer->wellFormed();
1555 // We have to clear the tokenizer, in case someone document.write()s from the
1556 // onLoad event handler, as in Radar 3206524.
1560 // Parser should have picked up all preloads by now
1561 m_docLoader->clearPreloads();
1563 // Create a body element if we don't already have one. See Radar 3758785.
1564 if (!this->body() && isHTMLDocument()) {
1565 if (Node* documentElement = this->documentElement()) {
1566 ExceptionCode ec = 0;
1567 documentElement->appendChild(new HTMLBodyElement(bodyTag, this), ec);
1572 // FIXME: We kick off the icon loader when the Document is done parsing.
1573 // There are earlier opportunities we could start it:
1574 // -When the <head> finishes parsing
1575 // -When any new HTMLLinkElement is inserted into the document
1576 // But those add a dynamic component to the favicon that has UI
1577 // ramifications, and we need to decide what is the Right Thing To Do(tm)
1580 f->loader()->startIconLoader();
1582 // Resume the animations (or start them)
1584 f->animation()->resumeAnimations(this);
1586 dispatchImageLoadEventsNow();
1587 this->dispatchWindowEvent(eventNames().loadEvent, false, false);
1589 f->loader()->handledOnloadEvents();
1590 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1591 if (!ownerElement())
1592 printf("onload fired at %d\n", elapsedTime());
1595 m_processingLoadEvent = false;
1597 // An event handler may have removed the frame
1601 // Make sure both the initial layout and reflow happen after the onload
1602 // fires. This will improve onload scores, and other browsers do it.
1603 // If they wanna cheat, we can too. -dwh
1605 if (frame()->loader()->isScheduledLocationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
1606 // Just bail out. Before or during the onload we were shifted to another page.
1607 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1608 view()->unscheduleRelayout();
1612 frame()->loader()->checkCallImplicitClose();
1614 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1615 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1616 // layout/painting now would be pointless.
1617 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1620 // Always do a layout after loading if needed.
1621 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1624 // Paint immediately after the document is ready. We do this to ensure that any timers set by the
1625 // onload don't have a chance to fire before we would have painted. To avoid over-flushing we only
1626 // worry about this for the top-level document. For platforms that use native widgets for ScrollViews, this
1627 // call does nothing (Mac, wx).
1628 // FIXME: This causes a timing issue with the dispatchDidFinishLoad delegate callback on Mac, so think
1629 // before enabling it, even if Mac becomes viewless later.
1630 // See <rdar://problem/5092361>
1631 if (view() && !ownerElement())
1632 view()->hostWindow()->paint();
1636 if (f && renderer() && this == topDocument() && AXObjectCache::accessibilityEnabled())
1637 axObjectCache()->postNotificationToElement(renderer(), "AXLoadComplete");
1641 // FIXME: Officially, time 0 is when the outermost <svg> receives its
1642 // SVGLoad event, but we don't implement those yet. This is close enough
1643 // for now. In some cases we should have fired earlier.
1644 if (svgExtensions())
1645 accessSVGExtensions()->startAnimations();
1649 void Document::setParsing(bool b)
1652 if (!m_bParsing && view())
1653 view()->scheduleRelayout();
1655 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1656 if (!ownerElement() && !m_bParsing)
1657 printf("Parsing finished at %d\n", elapsedTime());
1661 bool Document::shouldScheduleLayout()
1663 // This function will only be called when FrameView thinks a layout is needed.
1664 // This enforces a couple extra rules.
1666 // (a) Only schedule a layout once the stylesheets are loaded.
1667 // (b) Only schedule layout once we have a body element.
1669 return haveStylesheetsLoaded()
1670 && body() || (documentElement() && !documentElement()->hasTagName(htmlTag));
1673 int Document::minimumLayoutDelay()
1675 if (m_overMinimumLayoutThreshold)
1678 int elapsed = elapsedTime();
1679 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1681 // We'll want to schedule the timer to fire at the minimum layout threshold.
1682 return max(0, cLayoutScheduleThreshold - elapsed);
1685 int Document::elapsedTime() const
1687 return static_cast<int>((currentTime() - m_startTime) * 1000);
1690 void Document::write(const SegmentedString& text, Document* ownerDocument)
1692 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1693 if (!ownerElement())
1694 printf("Beginning a document.write at %d\n", elapsedTime());
1698 open(ownerDocument);
1699 ASSERT(m_tokenizer);
1702 UChar documentPrefix[] = { '<', 'h', 't', 'm', 'l', '>' };
1703 m_tokenizer->write(SegmentedString(documentPrefix, sizeof(documentPrefix) / sizeof(documentPrefix[0])), false);
1706 m_tokenizer->write(text, false);
1708 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1709 if (!ownerElement())
1710 printf("Ending a document.write at %d\n", elapsedTime());
1714 void Document::write(const String& text, Document* ownerDocument)
1716 write(SegmentedString(text), ownerDocument);
1719 void Document::writeln(const String& text, Document* ownerDocument)
1721 write(text, ownerDocument);
1722 write("\n", ownerDocument);
1725 void Document::finishParsing()
1727 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1728 if (!ownerElement())
1729 printf("Received all data at %d\n", elapsedTime());
1732 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1733 // finish() is called:
1734 // (1) All remaining data is parsed, document isn't loaded yet
1735 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1736 // (3) Data is still remaining to be parsed.
1738 m_tokenizer->finish();
1741 void Document::clear()
1748 size_t size = m_windowEventListeners.size();
1749 for (size_t i = 0; i < size; ++i)
1750 m_windowEventListeners[i]->setRemoved(true);
1751 m_windowEventListeners.clear();
1754 const KURL& Document::virtualURL() const
1759 KURL Document::virtualCompleteURL(const String& url) const
1761 return completeURL(url);
1764 void Document::setURL(const KURL& url)
1766 const KURL& newURL = url.isEmpty() ? blankURL() : url;
1767 if (newURL == m_url)
1771 m_documentURI = m_url.string();
1775 void Document::setBaseElementURL(const KURL& baseElementURL)
1777 m_baseElementURL = baseElementURL;
1781 void Document::updateBaseURL()
1783 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
1784 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
1785 // from the Document interface otherwise.
1786 if (m_baseElementURL.isEmpty()) {
1787 // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
1788 // so we use a null base URL.
1789 m_baseURL = KURL(KURL(), documentURI());
1791 m_baseURL = m_baseElementURL;
1792 if (!m_baseURL.isValid())
1796 m_elemSheet->setHref(m_baseURL.string());
1797 if (m_mappedElementSheet)
1798 m_mappedElementSheet->setHref(m_baseURL.string());
1801 void Document::setCSSStyleSheet(const String& url, const String& charset, const CachedCSSStyleSheet* sheet)
1803 m_sheet = CSSStyleSheet::create(this, url, charset);
1804 m_sheet->parseString(sheet->sheetText());
1806 updateStyleSelector();
1809 #if FRAME_LOADS_USER_STYLESHEET
1810 void Document::setUserStyleSheet(const String& sheet)
1812 if (m_usersheet != sheet) {
1813 m_usersheet = sheet;
1814 updateStyleSelector();
1819 String Document::userStyleSheet() const
1821 #if FRAME_LOADS_USER_STYLESHEET
1824 Page* page = this->page();
1827 return page->userStyleSheet();
1831 CSSStyleSheet* Document::elementSheet()
1834 m_elemSheet = CSSStyleSheet::create(this, m_baseURL.string());
1835 return m_elemSheet.get();
1838 CSSStyleSheet* Document::mappedElementSheet()
1840 if (!m_mappedElementSheet)
1841 m_mappedElementSheet = CSSStyleSheet::create(this, m_baseURL.string());
1842 return m_mappedElementSheet.get();
1845 static Node* nextNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1847 // Search is inclusive of start
1848 for (Node* n = start; n; n = n->traverseNextNode())
1849 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1855 static Node* previousNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1857 // Search is inclusive of start
1858 for (Node* n = start; n; n = n->traversePreviousNode())
1859 if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
1865 static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1867 // Search is inclusive of start
1868 int winningTabIndex = SHRT_MAX + 1;
1870 for (Node* n = start; n; n = n->traverseNextNode())
1871 if (n->isKeyboardFocusable(event) && n->tabIndex() > tabIndex && n->tabIndex() < winningTabIndex) {
1873 winningTabIndex = n->tabIndex();
1879 static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
1881 // Search is inclusive of start
1882 int winningTabIndex = 0;
1884 for (Node* n = start; n; n = n->traversePreviousNode())
1885 if (n->isKeyboardFocusable(event) && n->tabIndex() < tabIndex && n->tabIndex() > winningTabIndex) {
1887 winningTabIndex = n->tabIndex();
1893 Node* Document::nextFocusableNode(Node* start, KeyboardEvent* event)
1896 // If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
1897 if (start->tabIndex() < 0) {
1898 for (Node* n = start->traverseNextNode(); n; n = n->traverseNextNode())
1899 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1903 // First try to find a node with the same tabindex as start that comes after start in the document.
1904 if (Node* winner = nextNodeWithExactTabIndex(start->traverseNextNode(), start->tabIndex(), event))
1907 if (start->tabIndex() == 0)
1908 // We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
1912 // Look for the first node in the document that:
1913 // 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
1914 // 2) comes first in the document, if there's a tie.
1915 if (Node* winner = nextNodeWithGreaterTabIndex(this, start ? start->tabIndex() : 0, event))
1918 // There are no nodes with a tabindex greater than start's tabindex,
1919 // so find the first node with a tabindex of 0.
1920 return nextNodeWithExactTabIndex(this, 0, event);
1923 Node* Document::previousFocusableNode(Node* start, KeyboardEvent* event)
1926 for (last = this; last->lastChild(); last = last->lastChild())
1929 // First try to find the last node in the document that comes before start and has the same tabindex as start.
1930 // If start is null, find the last node in the document with a tabindex of 0.
1932 int startingTabIndex;
1934 startingNode = start->traversePreviousNode();
1935 startingTabIndex = start->tabIndex();
1937 startingNode = last;
1938 startingTabIndex = 0;
1941 // However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
1942 if (startingTabIndex < 0) {
1943 for (Node* n = startingNode; n; n = n->traversePreviousNode())
1944 if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
1948 if (Node* winner = previousNodeWithExactTabIndex(startingNode, startingTabIndex, event))
1951 // There are no nodes before start with the same tabindex as start, so look for a node that:
1952 // 1) has the highest non-zero tabindex (that is less than start's tabindex), and
1953 // 2) comes last in the document, if there's a tie.
1954 startingTabIndex = (start && start->tabIndex()) ? start->tabIndex() : SHRT_MAX;
1955 return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
1958 int Document::nodeAbsIndex(Node *node)
1960 ASSERT(node->document() == this);
1963 for (Node *n = node; n && n != this; n = n->traversePreviousNode())
1968 Node *Document::nodeWithAbsIndex(int absIndex)
1971 for (int i = 0; n && (i < absIndex); i++) {
1972 n = n->traverseNextNode();
1977 void Document::processHttpEquiv(const String &equiv, const String &content)
1979 ASSERT(!equiv.isNull() && !content.isNull());
1981 Frame *frame = this->frame();
1983 if (equalIgnoringCase(equiv, "default-style")) {
1984 // The preferred style set has been overridden as per section
1985 // 14.3.2 of the HTML4.0 specification. We need to update the
1986 // sheet used variable and then update our style selector.
1987 // For more info, see the test at:
1988 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1990 m_selectedStylesheetSet = content;
1991 m_preferredStylesheetSet = content;
1992 updateStyleSelector();
1993 } else if (equalIgnoringCase(equiv, "refresh")) {
1996 if (frame && parseHTTPRefresh(content, true, delay, url)) {
1998 url = frame->loader()->url().string();
2000 url = completeURL(url).string();
2001 frame->loader()->scheduleHTTPRedirection(delay, url);
2003 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2004 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2005 if (isHTMLDocument())
2006 static_cast<HTMLDocument*>(this)->setCookie(content);
2007 } else if (equalIgnoringCase(equiv, "content-language"))
2008 setContentLanguage(content);
2009 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2010 parseDNSPrefetchControlHeader(content);
2013 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const IntPoint& documentPoint, const PlatformMouseEvent& event)
2015 ASSERT(!renderer() || renderer()->isRenderView());
2018 return MouseEventWithHitTestResults(event, HitTestResult(IntPoint()));
2020 HitTestResult result(documentPoint);
2021 renderView()->layer()->hitTest(request, result);
2023 if (!request.readOnly())
2026 return MouseEventWithHitTestResults(event, result);
2029 // DOM Section 1.1.1
2030 bool Document::childTypeAllowed(NodeType type)
2033 case ATTRIBUTE_NODE:
2034 case CDATA_SECTION_NODE:
2035 case DOCUMENT_FRAGMENT_NODE:
2038 case ENTITY_REFERENCE_NODE:
2041 case XPATH_NAMESPACE_NODE:
2044 case PROCESSING_INSTRUCTION_NODE:
2046 case DOCUMENT_TYPE_NODE:
2048 // Documents may contain no more than one of each of these.
2049 // (One Element and one DocumentType.)
2050 for (Node* c = firstChild(); c; c = c->nextSibling())
2051 if (c->nodeType() == type)
2058 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2061 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2064 if (oldChild->nodeType() == newChild->nodeType())
2067 int numDoctypes = 0;
2068 int numElements = 0;
2070 // First, check how many doctypes and elements we have, not counting
2071 // the child we're about to remove.
2072 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2076 switch (c->nodeType()) {
2077 case DOCUMENT_TYPE_NODE:
2088 // Then, see how many doctypes and elements might be added by the new child.
2089 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2090 for (Node* c = firstChild(); c; c = c->nextSibling()) {
2091 switch (c->nodeType()) {
2092 case ATTRIBUTE_NODE:
2093 case CDATA_SECTION_NODE:
2094 case DOCUMENT_FRAGMENT_NODE:
2097 case ENTITY_REFERENCE_NODE:
2100 case XPATH_NAMESPACE_NODE:
2103 case PROCESSING_INSTRUCTION_NODE:
2105 case DOCUMENT_TYPE_NODE:
2114 switch (newChild->nodeType()) {
2115 case ATTRIBUTE_NODE:
2116 case CDATA_SECTION_NODE:
2117 case DOCUMENT_FRAGMENT_NODE:
2120 case ENTITY_REFERENCE_NODE:
2123 case XPATH_NAMESPACE_NODE:
2126 case PROCESSING_INSTRUCTION_NODE:
2128 case DOCUMENT_TYPE_NODE:
2137 if (numElements > 1 || numDoctypes > 1)
2143 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2145 // Spec says cloning Document nodes is "implementation dependent"
2146 // so we do not support it...
2150 StyleSheetList* Document::styleSheets()
2152 return m_styleSheets.get();
2155 String Document::preferredStylesheetSet() const
2157 return m_preferredStylesheetSet;
2160 String Document::selectedStylesheetSet() const
2162 return m_selectedStylesheetSet;
2165 void Document::setSelectedStylesheetSet(const String& aString)
2167 m_selectedStylesheetSet = aString;
2168 updateStyleSelector();
2170 renderer()->repaint();
2173 // This method is called whenever a top-level stylesheet has finished loading.
2174 void Document::removePendingSheet()
2176 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2177 ASSERT(m_pendingStylesheets > 0);
2179 m_pendingStylesheets--;
2181 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2182 if (!ownerElement())
2183 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2186 updateStyleSelector();
2188 if (!m_pendingStylesheets && m_tokenizer)
2189 m_tokenizer->executeScriptsWaitingForStylesheets();
2191 if (!m_pendingStylesheets && m_gotoAnchorNeededAfterStylesheetsLoad && m_frame)
2192 m_frame->loader()->gotoAnchor();
2195 void Document::updateStyleSelector()
2197 // Don't bother updating, since we haven't loaded all our style info yet
2198 // and haven't calculated the style selector for the first time.
2199 if (!m_didCalculateStyleSelector && !haveStylesheetsLoaded())
2202 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
2203 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2205 renderer()->repaint();
2208 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2209 if (!ownerElement())
2210 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2213 recalcStyleSelector();
2216 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2217 if (!ownerElement())
2218 printf("Finished update of style selector at time %d\n", elapsedTime());
2222 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
2224 view()->scheduleRelayout();
2228 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
2230 // Until the <body> exists, we have no choice but to compare document positions,
2231 // since styles outside of the body and head continue to be shunted into the head
2232 // (and thus can shift to end up before dynamically added DOM content that is also
2233 // outside the body).
2234 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
2235 m_styleSheetCandidateNodes.add(node);
2239 // Determine an appropriate insertion point.
2240 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2241 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2242 ListHashSet<Node*>::iterator it = end;
2243 Node* followingNode = 0;
2247 unsigned short position = n->compareDocumentPosition(node);
2248 if (position == DOCUMENT_POSITION_FOLLOWING) {
2249 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2253 } while (it != begin);
2255 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
2258 void Document::removeStyleSheetCandidateNode(Node* node)
2260 m_styleSheetCandidateNodes.remove(node);
2263 void Document::recalcStyleSelector()
2265 if (!renderer() || !attached())
2268 StyleSheetVector sheets;
2270 bool matchAuthorAndUserStyles = true;
2271 if (Settings* settings = this->settings())
2272 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
2274 ListHashSet<Node*>::iterator begin = m_styleSheetCandidateNodes.begin();
2275 ListHashSet<Node*>::iterator end = m_styleSheetCandidateNodes.end();
2276 if (!matchAuthorAndUserStyles)
2278 for (ListHashSet<Node*>::iterator it = begin; it != end; ++it) {
2281 StyleSheet* sheet = 0;
2283 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
2284 // Processing instruction (XML documents only)
2285 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
2286 sheet = pi->sheet();
2288 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
2289 if (pi->isXSL() && !transformSourceDocument()) {
2290 // Don't apply XSL transforms until loading is finished.
2292 applyXSLTransform(pi);
2296 if (!sheet && !pi->localHref().isEmpty()) {
2297 // Processing instruction with reference to an element in this document - e.g.
2298 // <?xml-stylesheet href="#mystyle">, with the element
2299 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2301 Element* elem = getElementById(pi->localHref().impl());
2303 String sheetText("");
2304 for (Node* c = elem->firstChild(); c; c = c->nextSibling()) {
2305 if (c->nodeType() == TEXT_NODE || c->nodeType() == CDATA_SECTION_NODE)
2306 sheetText += c->nodeValue();
2309 RefPtr<CSSStyleSheet> cssSheet = CSSStyleSheet::create(this);
2310 cssSheet->parseString(sheetText);
2311 pi->setCSSStyleSheet(cssSheet);
2312 sheet = cssSheet.get();
2315 } else if (n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))
2317 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2320 Element* e = static_cast<Element*>(n);
2321 AtomicString title = e->getAttribute(titleAttr);
2322 bool enabledViaScript = false;
2323 if (e->hasLocalName(linkTag)) {
2325 HTMLLinkElement* l = static_cast<HTMLLinkElement*>(n);
2326 if (l->isDisabled())
2328 enabledViaScript = l->isEnabledViaScript();
2329 if (l->isLoading()) {
2330 // it is loading but we should still decide which style sheet set to use
2331 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
2332 const AtomicString& rel = e->getAttribute(relAttr);
2333 if (!rel.contains("alternate")) {
2334 m_preferredStylesheetSet = title;
2335 m_selectedStylesheetSet = title;
2344 // Get the current preferred styleset. This is the
2345 // set of sheets that will be enabled.
2347 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
2348 sheet = static_cast<SVGStyleElement*>(n)->sheet();
2351 if (e->hasLocalName(linkTag))
2352 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
2355 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
2357 // Check to see if this sheet belongs to a styleset
2358 // (thus making it PREFERRED or ALTERNATE rather than
2360 if (!enabledViaScript && !title.isEmpty()) {
2361 // Yes, we have a title.
2362 if (m_preferredStylesheetSet.isEmpty()) {
2363 // No preferred set has been established. If
2364 // we are NOT an alternate sheet, then establish
2365 // us as the preferred set. Otherwise, just ignore
2367 AtomicString rel = e->getAttribute(relAttr);
2368 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
2369 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
2372 if (title != m_preferredStylesheetSet)
2378 sheets.append(sheet);
2381 m_styleSheets->swap(sheets);
2383 // Create a new style selector
2384 delete m_styleSelector;
2385 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
2386 m_didCalculateStyleSelector = true;
2389 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
2391 m_hoverNode = newHoverNode;
2394 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
2396 m_activeNode = newActiveNode;
2399 void Document::focusedNodeRemoved()
2404 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
2406 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
2409 bool nodeInSubtree = false;
2410 if (amongChildrenOnly)
2411 nodeInSubtree = m_focusedNode->isDescendantOf(node);
2413 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
2416 document()->focusedNodeRemoved();
2419 void Document::hoveredNodeDetached(Node* node)
2421 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parent())))
2424 m_hoverNode = node->parent();
2425 while (m_hoverNode && !m_hoverNode->renderer())
2426 m_hoverNode = m_hoverNode->parent();
2428 frame()->eventHandler()->scheduleHoverStateUpdate();
2431 void Document::activeChainNodeDetached(Node* node)
2433 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parent())))
2436 m_activeNode = node->parent();
2437 while (m_activeNode && !m_activeNode->renderer())
2438 m_activeNode = m_activeNode->parent();
2441 #if ENABLE(DASHBOARD_SUPPORT)
2442 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
2444 return m_dashboardRegions;
2447 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
2449 m_dashboardRegions = regions;
2450 setDashboardRegionsDirty(false);
2454 bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
2456 // Make sure newFocusedNode is actually in this document
2457 if (newFocusedNode && (newFocusedNode->document() != this))
2460 if (m_focusedNode == newFocusedNode)
2466 bool focusChangeBlocked = false;
2467 RefPtr<Node> oldFocusedNode = m_focusedNode;
2470 // Remove focus from the existing focus node (if any)
2471 if (oldFocusedNode && !oldFocusedNode->m_inDetach) {
2472 if (oldFocusedNode->active())
2473 oldFocusedNode->setActive(false);
2475 oldFocusedNode->setFocus(false);
2477 // Dispatch a change event for text fields or textareas that have been edited
2478 RenderObject* r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer());
2479 if (r && r->isTextControl() && toRenderTextControl(r)->isEdited()) {
2480 oldFocusedNode->dispatchEventForType(eventNames().changeEvent, true, false);
2481 if ((r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer()))) {
2482 if (r->isTextControl())
2483 toRenderTextControl(r)->setEdited(false);
2487 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
2488 oldFocusedNode->dispatchBlurEvent();
2490 if (m_focusedNode) {
2491 // handler shifted focus
2492 focusChangeBlocked = true;
2495 oldFocusedNode->dispatchUIEvent(eventNames().DOMFocusOutEvent);
2496 if (m_focusedNode) {
2497 // handler shifted focus
2498 focusChangeBlocked = true;
2501 if ((oldFocusedNode.get() == this) && oldFocusedNode->hasOneRef())
2504 if (oldFocusedNode.get() == oldFocusedNode->rootEditableElement())
2505 frame()->editor()->didEndEditing();
2508 if (newFocusedNode) {
2509 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
2510 // delegate blocks focus change
2511 focusChangeBlocked = true;
2512 goto SetFocusedNodeDone;
2514 // Set focus on the new node
2515 m_focusedNode = newFocusedNode.get();
2517 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
2518 m_focusedNode->dispatchFocusEvent();
2520 if (m_focusedNode != newFocusedNode) {
2521 // handler shifted focus
2522 focusChangeBlocked = true;
2523 goto SetFocusedNodeDone;
2525 m_focusedNode->dispatchUIEvent(eventNames().DOMFocusInEvent);
2526 if (m_focusedNode != newFocusedNode) {
2527 // handler shifted focus
2528 focusChangeBlocked = true;
2529 goto SetFocusedNodeDone;
2531 m_focusedNode->setFocus();
2533 if (m_focusedNode.get() == m_focusedNode->rootEditableElement())
2534 frame()->editor()->didBeginEditing();
2536 // eww, I suck. set the qt focus correctly
2537 // ### find a better place in the code for this
2539 Widget *focusWidget = widgetForNode(m_focusedNode.get());
2541 // Make sure a widget has the right size before giving it focus.
2542 // Otherwise, we are testing edge cases of the Widget code.
2543 // Specifically, in WebCore this does not work well for text fields.
2545 // Re-get the widget in case updating the layout changed things.
2546 focusWidget = widgetForNode(m_focusedNode.get());
2549 focusWidget->setFocus();
2556 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
2557 axObjectCache()->handleFocusedUIElementChanged();
2562 return !focusChangeBlocked;
2565 void Document::setCSSTarget(Element* n)
2568 m_cssTarget->setChanged();
2574 void Document::attachNodeIterator(NodeIterator *ni)
2576 m_nodeIterators.add(ni);
2579 void Document::detachNodeIterator(NodeIterator *ni)
2581 m_nodeIterators.remove(ni);
2584 void Document::nodeChildrenChanged(ContainerNode* container)
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)->nodeChildrenChanged(container);
2593 void Document::nodeWillBeRemoved(Node* n)
2595 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
2596 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
2597 (*it)->nodeWillBeRemoved(n);
2599 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2600 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
2601 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
2602 (*it)->nodeWillBeRemoved(n);
2605 if (Frame* frame = this->frame()) {
2606 frame->selection()->nodeWillBeRemoved(n);
2607 frame->dragCaretController()->nodeWillBeRemoved(n);
2611 void Document::textInserted(Node* text, unsigned offset, unsigned length)
2613 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2614 HashSet<Range*>::const_iterator end = m_ranges.end();
2615 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2616 (*it)->textInserted(text, offset, length);
2619 // Update the markers for spelling and grammar checking.
2620 shiftMarkers(text, offset, length);
2623 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
2625 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2626 HashSet<Range*>::const_iterator end = m_ranges.end();
2627 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2628 (*it)->textRemoved(text, offset, length);
2631 // Update the markers for spelling and grammar checking.
2632 removeMarkers(text, offset, length);
2633 shiftMarkers(text, offset + length, 0 - length);
2636 void Document::textNodesMerged(Text* oldNode, unsigned offset)
2638 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2639 NodeWithIndex oldNodeWithIndex(oldNode);
2640 HashSet<Range*>::const_iterator end = m_ranges.end();
2641 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2642 (*it)->textNodesMerged(oldNodeWithIndex, offset);
2645 // FIXME: This should update markers for spelling and grammar checking.
2648 void Document::textNodeSplit(Text* oldNode)
2650 if (!page() || !page()->settings()->rangeMutationDisabledForOldAppleMail()) {
2651 HashSet<Range*>::const_iterator end = m_ranges.end();
2652 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
2653 (*it)->textNodeSplit(oldNode);
2656 // FIXME: This should update markers for spelling and grammar checking.
2659 // FIXME: eventually, this should return a DOMWindow stored in the document.
2660 DOMWindow* Document::domWindow() const
2664 return frame()->domWindow();
2667 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
2669 if (eventType == "Event" || eventType == "Events" || eventType == "HTMLEvents")
2670 return Event::create();
2671 if (eventType == "KeyboardEvent" || eventType == "KeyboardEvents")
2672 return KeyboardEvent::create();
2673 if (eventType == "MessageEvent")
2674 return MessageEvent::create();
2675 if (eventType == "MouseEvent" || eventType == "MouseEvents")
2676 return MouseEvent::create();
2677 if (eventType == "MutationEvent" || eventType == "MutationEvents")
2678 return MutationEvent::create();
2679 if (eventType == "OverflowEvent")
2680 return OverflowEvent::create();
2681 if (eventType == "ProgressEvent")
2682 return ProgressEvent::create();
2683 #if ENABLE(DOM_STORAGE)
2684 if (eventType == "StorageEvent")
2685 return StorageEvent::create();
2687 if (eventType == "TextEvent")
2688 return TextEvent::create();
2689 if (eventType == "UIEvent" || eventType == "UIEvents")
2690 return UIEvent::create();
2691 if (eventType == "WebKitAnimationEvent")
2692 return WebKitAnimationEvent::create();
2693 if (eventType == "WebKitTransitionEvent")
2694 return WebKitTransitionEvent::create();
2695 if (eventType == "WheelEvent")
2696 return WheelEvent::create();
2698 if (eventType == "SVGEvents")
2699 return Event::create();
2700 if (eventType == "SVGZoomEvents")
2701 return SVGZoomEvent::create();
2703 ec = NOT_SUPPORTED_ERR;
2707 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
2709 if (eventType == eventNames().DOMSubtreeModifiedEvent)
2710 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
2711 else if (eventType == eventNames().DOMNodeInsertedEvent)
2712 addListenerType(DOMNODEINSERTED_LISTENER);
2713 else if (eventType == eventNames().DOMNodeRemovedEvent)
2714 addListenerType(DOMNODEREMOVED_LISTENER);
2715 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
2716 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
2717 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
2718 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
2719 else if (eventType == eventNames().DOMAttrModifiedEvent)
2720 addListenerType(DOMATTRMODIFIED_LISTENER);
2721 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
2722 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
2723 else if (eventType == eventNames().overflowchangedEvent)
2724 addListenerType(OVERFLOWCHANGED_LISTENER);
2725 else if (eventType == eventNames().webkitAnimationStartEvent)
2726 addListenerType(ANIMATIONSTART_LISTENER);
2727 else if (eventType == eventNames().webkitAnimationEndEvent)
2728 addListenerType(ANIMATIONEND_LISTENER);
2729 else if (eventType == eventNames().webkitAnimationIterationEvent)
2730 addListenerType(ANIMATIONITERATION_LISTENER);
2731 else if (eventType == eventNames().webkitTransitionEndEvent)
2732 addListenerType(TRANSITIONEND_LISTENER);
2735 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
2740 void Document::handleWindowEvent(Event* event, bool useCapture)
2742 if (m_windowEventListeners.isEmpty())
2745 // If any HTML event listeners are registered on the window, dispatch them here.
2746 RegisteredEventListenerVector listenersCopy = m_windowEventListeners;
2747 size_t size = listenersCopy.size();
2748 for (size_t i = 0; i < size; ++i) {
2749 RegisteredEventListener& r = *listenersCopy[i];
2750 if (r.eventType() == event->type() && r.useCapture() == useCapture && !r.removed())
2751 r.listener()->handleEvent(event, true);
2755 void Document::setWindowInlineEventListenerForType(const AtomicString& eventType, PassRefPtr<EventListener> listener)
2757 // If we already have it we don't want removeWindowEventListener to delete it
2758 removeWindowInlineEventListenerForType(eventType);
2760 addWindowEventListener(eventType, listener, false);
2763 EventListener* Document::windowInlineEventListenerForType(const AtomicString& eventType)
2765 size_t size = m_windowEventListeners.size();
2766 for (size_t i = 0; i < size; ++i) {
2767 RegisteredEventListener& r = *m_windowEventListeners[i];
2768 if (r.eventType() == eventType && r.listener()->isInline())
2769 return r.listener();
2774 void Document::removeWindowInlineEventListenerForType(const AtomicString& eventType)
2776 size_t size = m_windowEventListeners.size();
2777 for (size_t i = 0; i < size; ++i) {
2778 RegisteredEventListener& r = *m_windowEventListeners[i];
2779 if (r.eventType() == eventType && r.listener()->isInline()) {
2780 if (eventType == eventNames().unloadEvent)
2781 removePendingFrameUnloadEventCount();
2782 else if (eventType == eventNames().beforeunloadEvent)
2783 removePendingFrameBeforeUnloadEventCount();
2785 m_windowEventListeners.remove(i);
2791 void Document::addWindowEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2793 if (eventType == eventNames().unloadEvent)
2794 addPendingFrameUnloadEventCount();
2795 else if (eventType == eventNames().beforeunloadEvent)
2796 addPendingFrameBeforeUnloadEventCount();
2797 // Remove existing identical listener set with identical arguments.
2798 // The DOM 2 spec says that "duplicate instances are discarded" in this case.
2799 removeWindowEventListener(eventType, listener.get(), useCapture);
2800 addListenerTypeIfNeeded(eventType);
2801 m_windowEventListeners.append(RegisteredEventListener::create(eventType, listener, useCapture));
2804 void Document::removeWindowEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2806 size_t size = m_windowEventListeners.size();
2807 for (size_t i = 0; i < size; ++i) {
2808 RegisteredEventListener& r = *m_windowEventListeners[i];
2809 if (r.eventType() == eventType && r.listener() == listener && r.useCapture() == useCapture) {
2810 if (eventType == eventNames().unloadEvent)
2811 removePendingFrameUnloadEventCount();
2812 else if (eventType == eventNames().beforeunloadEvent)
2813 removePendingFrameBeforeUnloadEventCount();
2815 m_windowEventListeners.remove(i);
2821 bool Document::hasWindowEventListener(const AtomicString& eventType)
2823 size_t size = m_windowEventListeners.size();
2824 for (size_t i = 0; i < size; ++i) {
2825 if (m_windowEventListeners[i]->eventType() == eventType)
2831 void Document::addPendingFrameUnloadEventCount()
2834 m_frame->eventHandler()->addPendingFrameUnloadEventCount();
2837 void Document::removePendingFrameUnloadEventCount()
2840 m_frame->eventHandler()->removePendingFrameUnloadEventCount();
2843 void Document::addPendingFrameBeforeUnloadEventCount()
2846 m_frame->eventHandler()->addPendingFrameBeforeUnloadEventCount();
2849 void Document::removePendingFrameBeforeUnloadEventCount()
2852 m_frame->eventHandler()->removePendingFrameBeforeUnloadEventCount();
2855 PassRefPtr<EventListener> Document::createEventListener(const String& functionName, const String& code, Node* node)
2857 Frame* frm = frame();
2858 if (!frm || !frm->script()->isEnabled())
2862 if (node ? node->isSVGElement() : isSVGDocument())
2863 return frm->script()->createSVGEventHandler(functionName, code, node);
2866 // We may want to treat compound document event handlers in a different way, in future.
2867 return frm->script()->createInlineEventListener(functionName, code, node);
2870 void Document::setWindowInlineEventListenerForTypeAndAttribute(const AtomicString& eventType, Attribute* attr)
2872 setWindowInlineEventListenerForType(eventType, createEventListener(attr->localName().string(), attr->value(), 0));
2875 void Document::dispatchImageLoadEventSoon(ImageLoader* image)
2877 m_imageLoadEventDispatchSoonList.append(image);
2878 if (!m_imageLoadEventTimer.isActive())
2879 m_imageLoadEventTimer.startOneShot(0);
2882 void Document::removeImage(ImageLoader* image)
2884 // Remove instances of this image from both lists.
2885 // Use loops because we allow multiple instances to get into the lists.
2886 size_t size = m_imageLoadEventDispatchSoonList.size();
2887 for (size_t i = 0; i < size; ++i) {
2888 if (m_imageLoadEventDispatchSoonList[i] == image)
2889 m_imageLoadEventDispatchSoonList[i] = 0;
2891 size = m_imageLoadEventDispatchingList.size();
2892 for (size_t i = 0; i < size; ++i) {
2893 if (m_imageLoadEventDispatchingList[i] == image)
2894 m_imageLoadEventDispatchingList[i] = 0;
2896 if (m_imageLoadEventDispatchSoonList.isEmpty())
2897 m_imageLoadEventTimer.stop();
2900 void Document::dispatchImageLoadEventsNow()
2902 // Need to avoid re-entering this function; if new dispatches are
2903 // scheduled before the parent finishes processing the list, they
2904 // will set a timer and eventually be processed.
2905 if (!m_imageLoadEventDispatchingList.isEmpty())
2908 m_imageLoadEventTimer.stop();
2910 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2911 m_imageLoadEventDispatchSoonList.clear();
2912 size_t size = m_imageLoadEventDispatchingList.size();
2913 for (size_t i = 0; i < size; ++i) {
2914 if (ImageLoader* image = m_imageLoadEventDispatchingList[i])
2915 image->dispatchLoadEvent();
2917 m_imageLoadEventDispatchingList.clear();
2920 void Document::imageLoadEventTimerFired(Timer<Document>*)
2922 dispatchImageLoadEventsNow();
2925 Element* Document::ownerElement() const
2929 return frame()->ownerElement();
2932 String Document::cookie() const
2934 if (page() && !page()->cookieEnabled())
2937 KURL cookieURL = this->cookieURL();
2938 if (cookieURL.isEmpty())
2941 return cookies(this, cookieURL);
2944 void Document::setCookie(const String& value)
2946 if (page() && !page()->cookieEnabled())
2949 KURL cookieURL = this->cookieURL();
2950 if (cookieURL.isEmpty())
2953 setCookies(this, cookieURL, policyBaseURL(), value);
2956 String Document::referrer() const
2959 return frame()->loader()->referrer();
2963 String Document::domain() const
2965 return securityOrigin()->domain();
2968 void Document::setDomain(const String& newDomain)
2970 // Both NS and IE specify that changing the domain is only allowed when
2971 // the new domain is a suffix of the old domain.
2973 // FIXME: We should add logging indicating why a domain was not allowed.
2975 // If the new domain is the same as the old domain, still call
2976 // securityOrigin()->setDomainForDOM. This will change the
2977 // security check behavior. For example, if a page loaded on port 8000
2978 // assigns its current domain using document.domain, the page will
2979 // allow other pages loaded on different ports in the same domain that
2980 // have also assigned to access this page.
2981 if (equalIgnoringCase(domain(), newDomain)) {
2982 securityOrigin()->setDomainFromDOM(newDomain);
2984 m_frame->script()->updateSecurityOrigin();
2988 int oldLength = domain().length();
2989 int newLength = newDomain.length();
2990 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
2991 if (newLength >= oldLength)
2994 String test = domain();
2995 // Check that it's a subdomain, not e.g. "ebkit.org"
2996 if (test[oldLength - newLength - 1] != '.')
2999 // Now test is "webkit.org" from domain()
3000 // and we check that it's the same thing as newDomain
3001 test.remove(0, oldLength - newLength);
3002 if (test != newDomain)
3005 securityOrigin()->setDomainFromDOM(newDomain);
3007 m_frame->script()->updateSecurityOrigin();
3010 String Document::lastModified() const
3015 DocumentLoader* loader = f->loader()->documentLoader();
3018 return loader->response().httpHeaderField("Last-Modified");
3021 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3026 U16_NEXT(characters, i, length, c)
3027 if (!isValidNameStart(c))
3030 while (i < length) {
3031 U16_NEXT(characters, i, length, c)
3032 if (!isValidNamePart(c))
3039 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
3041 UChar c = characters[0];
3042 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3045 for (unsigned i = 1; i < length; ++i) {
3047 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3054 bool Document::isValidName(const String& name)
3056 unsigned length = name.length();
3060 const UChar* characters = name.characters();
3061 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3064 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3066 unsigned length = qualifiedName.length();
3069 ec = INVALID_CHARACTER_ERR;
3073 bool nameStart = true;
3074 bool sawColon = false;
3077 const UChar* s = qualifiedName.characters();
3078 for (unsigned i = 0; i < length;) {
3080 U16_NEXT(s, i, length, c)
3084 return false; // multiple colons: not allowed
3089 } else if (nameStart) {
3090 if (!isValidNameStart(c)) {
3091 ec = INVALID_CHARACTER_ERR;
3096 if (!isValidNamePart(c)) {
3097 ec = INVALID_CHARACTER_ERR;
3105 localName = qualifiedName;
3107 prefix = qualifiedName.substring(0, colonPos);
3108 if (prefix.isEmpty()) {
3112 localName = qualifiedName.substring(colonPos + 1);
3115 if (localName.isEmpty()) {
3123 void Document::addImageMap(HTMLMapElement* imageMap)
3125 const AtomicString& name = imageMap->getName();
3129 // Add the image map, unless there's already another with that name.
3130 // "First map wins" is the rule other browsers seem to implement.
3131 m_imageMapsByName.add(name.impl(), imageMap);
3134 void Document::removeImageMap(HTMLMapElement* imageMap)
3136 // Remove the image map by name.
3137 // But don't remove some other image map that just happens to have the same name.
3138 // FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
3139 // once a map has been removed.
3140 const AtomicString& name = imageMap->getName();
3144 ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
3145 if (it != m_imageMapsByName.end() && it->second == imageMap)
3146 m_imageMapsByName.remove(it);
3149 HTMLMapElement *Document::getImageMap(const String& url) const
3153 int hashPos = url.find('#');
3154 String name = (hashPos < 0 ? url : url.substring(hashPos + 1)).impl();
3155 AtomicString mapName = isHTMLDocument() ? name.lower() : name;
3156 return m_imageMapsByName.get(mapName.impl());
3159 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3161 m_decoder = decoder;
3164 KURL Document::completeURL(const String& url) const
3166 // Always return a null URL when passed a null string.
3167 // FIXME: Should we change the KURL constructor to have this behavior?
3168 // See also [CSS]StyleSheet::completeURL(const String&)
3172 return KURL(m_baseURL, url);
3173 return KURL(m_baseURL, url, m_decoder->encoding());
3176 void Document::setInPageCache(bool flag)
3178 if (m_inPageCache == flag)
3181 m_inPageCache = flag;
3183 ASSERT(m_savedRenderer == 0);
3184 m_savedRenderer = renderer();
3185 if (FrameView* v = view())
3186 v->resetScrollbars();
3188 ASSERT(renderer() == 0 || renderer() == m_savedRenderer);
3189 ASSERT(m_renderArena);
3190 setRenderer(m_savedRenderer);
3191 m_savedRenderer = 0;
3195 void Document::documentWillBecomeInactive()
3197 #if USE(ACCELERATED_COMPOSITING)
3199 renderView()->willMoveOffscreen();
3202 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3203 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3204 (*i)->documentWillBecomeInactive();
3207 void Document::documentDidBecomeActive()
3209 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3210 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3211 (*i)->documentDidBecomeActive();
3213 #if USE(ACCELERATED_COMPOSITING)
3215 renderView()->didMoveOnscreen();
3219 void Document::registerForDocumentActivationCallbacks(Element* e)
3221 m_documentActivationCallbackElements.add(e);
3224 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3226 m_documentActivationCallbackElements.remove(e);
3229 void Document::mediaVolumeDidChange()
3231 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3232 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3233 (*i)->mediaVolumeDidChange();
3236 void Document::registerForMediaVolumeCallbacks(Element* e)
3238 m_mediaVolumeCallbackElements.add(e);
3241 void Document::unregisterForMediaVolumeCallbacks(Element* e)
3243 m_mediaVolumeCallbackElements.remove(e);
3246 void Document::setShouldCreateRenderers(bool f)
3248 m_createRenderers = f;
3251 bool Document::shouldCreateRenderers()
3253 return m_createRenderers;
3256 // Support for Javascript execCommand, and related methods
3258 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
3260 Frame* frame = document->frame();
3261 if (!frame || frame->document() != document)
3262 return Editor::Command();
3263 return frame->editor()->command(commandName,
3264 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
3267 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
3269 return command(this, commandName, userInterface).execute(value);
3272 bool Document::queryCommandEnabled(const String& commandName)
3274 return command(this, commandName).isEnabled();
3277 bool Document::queryCommandIndeterm(const String& commandName)
3279 return command(this, commandName).state() == MixedTriState;
3282 bool Document::queryCommandState(const String& commandName)
3284 return command(this, commandName).state() != FalseTriState;
3287 bool Document::queryCommandSupported(const String& commandName)
3289 return command(this, commandName).isSupported();
3292 String Document::queryCommandValue(const String& commandName)
3294 return command(this, commandName).value();
3297 static IntRect placeholderRectForMarker()
3299 return IntRect(-1, -1, -1, -1);
3302 void Document::addMarker(Range *range, DocumentMarker::MarkerType type, String description)
3304 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3305 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3306 RefPtr<Range> textPiece = markedText.range();
3308 DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception), description};
3309 addMarker(textPiece->startContainer(exception), marker);
3313 void Document::removeMarkers(Range* range, DocumentMarker::MarkerType markerType)
3315 if (m_markers.isEmpty())
3318 ExceptionCode ec = 0;
3319 Node* startContainer = range->startContainer(ec);
3320 Node* endContainer = range->endContainer(ec);
3322 Node* pastLastNode = range->pastLastNode();
3323 for (Node* node = range->firstNode(); node != pastLastNode; node = node->traverseNextNode()) {
3324 int startOffset = node == startContainer ? range->startOffset(ec) : 0;
3325 int endOffset = node == endContainer ? range->endOffset(ec) : INT_MAX;
3326 int length = endOffset - startOffset;
3327 removeMarkers(node, startOffset, length, markerType);
3331 // Markers are stored in order sorted by their start offset.
3332 // Markers of the same type do not overlap each other.
3334 void Document::addMarker(Node* node, DocumentMarker newMarker)
3336 ASSERT(newMarker.endOffset >= newMarker.startOffset);
3337 if (newMarker.endOffset == newMarker.startOffset)
3340 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3343 vectorPair = new MarkerMapVectorPair;
3344 vectorPair->first.append(newMarker);
3345 vectorPair->second.append(placeholderRectForMarker());
3346 m_markers.set(node, vectorPair);
3348 Vector<DocumentMarker>& markers = vectorPair->first;
3349 Vector<IntRect>& rects = vectorPair->second;
3350 size_t numMarkers = markers.size();
3351 ASSERT(numMarkers == rects.size());
3353 // Iterate over all markers whose start offset is less than or equal to the new marker's.
3354 // If one of them is of the same type as the new marker and touches it or intersects with it
3355 // (there is at most one), remove it and adjust the new marker's start offset to encompass it.
3356 for (i = 0; i < numMarkers; ++i) {
3357 DocumentMarker marker = markers[i];
3358 if (marker.startOffset > newMarker.startOffset)
3360 if (marker.type == newMarker.type && marker.endOffset >= newMarker.startOffset) {
3361 newMarker.startOffset = marker.startOffset;
3369 // Iterate over all markers whose end offset is less than or equal to the new marker's,
3370 // removing markers of the same type as the new marker which touch it or intersect with it,
3371 // adjusting the new marker's end offset to cover them if necessary.
3372 while (j < numMarkers) {
3373 DocumentMarker marker = markers[j];
3374 if (marker.startOffset > newMarker.endOffset)
3376 if (marker.type == newMarker.type) {
3379 if (newMarker.endOffset <= marker.endOffset) {
3380 newMarker.endOffset = marker.endOffset;
3387 // At this point i points to the node before which we want to insert.
3388 markers.insert(i, newMarker);
3389 rects.insert(i, placeholderRectForMarker());
3392 // repaint the affected node
3393 if (node->renderer())
3394 node->renderer()->repaint();
3397 // copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
3398 // useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
3399 void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
3404 MarkerMapVectorPair* vectorPair = m_markers.get(srcNode);
3408 ASSERT(vectorPair->first.size() == vectorPair->second.size());
3410 bool docDirty = false;
3411 unsigned endOffset = startOffset + length - 1;
3412 Vector<DocumentMarker>& markers = vectorPair->first;
3413 for (size_t i = 0; i != markers.size(); ++i) {
3414 DocumentMarker marker = markers[i];
3416 // stop if we are now past the specified range
3417 if (marker.startOffset > endOffset)
3420 // skip marker that is before the specified range or is the wrong type
3421 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
3424 // pin the marker to the specified range and apply the shift delta
3426 if (marker.startOffset < startOffset)
3427 marker.startOffset = startOffset;
3428 if (marker.endOffset > endOffset)
3429 marker.endOffset = endOffset;
3430 marker.startOffset += delta;
3431 marker.endOffset += delta;
3433 addMarker(dstNode, marker);
3436 // repaint the affected node
3437 if (docDirty && dstNode->renderer())
3438 dstNode->renderer()->repaint();
3441 void Document::removeMarkers(Node* node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
3446 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3450 Vector<DocumentMarker>& markers = vectorPair->first;
3451 Vector<IntRect>& rects = vectorPair->second;
3452 ASSERT(markers.size() == rects.size());
3453 bool docDirty = false;
3454 unsigned endOffset = startOffset + length;
3455 for (size_t i = 0; i < markers.size();) {
3456 DocumentMarker marker = markers[i];
3458 // markers are returned in order, so stop if we are now past the specified range
3459 if (marker.startOffset >= endOffset)
3462 // skip marker that is wrong type or before target
3463 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
3468 // at this point we know that marker and target intersect in some way
3471 // pitch the old marker and any associated rect
3475 // add either of the resulting slices that are left after removing target
3476 if (startOffset > marker.startOffset) {
3477 DocumentMarker newLeft = marker;
3478 newLeft.endOffset = startOffset;
3479 markers.insert(i, newLeft);
3480 rects.insert(i, placeholderRectForMarker());
3481 // i now points to the newly-inserted node, but we want to skip that one
3484 if (marker.endOffset > endOffset) {
3485 DocumentMarker newRight = marker;
3486 newRight.startOffset = endOffset;
3487 markers.insert(i, newRight);
3488 rects.insert(i, placeholderRectForMarker());
3489 // i now points to the newly-inserted node, but we want to skip that one
3494 if (markers.isEmpty()) {
3495 ASSERT(rects.isEmpty());
3496 m_markers.remove(node);
3500 // repaint the affected node
3501 if (docDirty && node->renderer())
3502 node->renderer()->repaint();
3505 DocumentMarker* Document::markerContainingPoint(const IntPoint& point, DocumentMarker::MarkerType markerType)
3507 // outer loop: process each node that contains any markers
3508 MarkerMap::iterator end = m_markers.end();
3509 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3510 // inner loop; process each marker in this node
3511 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3512 Vector<DocumentMarker>& markers = vectorPair->first;
3513 Vector<IntRect>& rects = vectorPair->second;
3514 ASSERT(markers.size() == rects.size());
3515 unsigned markerCount = markers.size();
3516 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3517 DocumentMarker& marker = markers[markerIndex];
3519 // skip marker that is wrong type
3520 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3523 IntRect& r = rects[markerIndex];
3525 // skip placeholder rects
3526 if (r == placeholderRectForMarker())
3529 if (r.contains(point))
3537 Vector<DocumentMarker> Document::markersForNode(Node* node)
3539 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3541 return vectorPair->first;
3542 return Vector<DocumentMarker>();
3545 Vector<IntRect> Document::renderedRectsForMarkers(DocumentMarker::MarkerType markerType)
3547 Vector<IntRect> result;
3549 // outer loop: process each node
3550 MarkerMap::iterator end = m_markers.end();
3551 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3552 // inner loop; process each marker in this node
3553 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3554 Vector<DocumentMarker>& markers = vectorPair->first;
3555 Vector<IntRect>& rects = vectorPair->second;
3556 ASSERT(markers.size() == rects.size());
3557 unsigned markerCount = markers.size();
3558 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3559 DocumentMarker marker = markers[markerIndex];
3561 // skip marker that is wrong type
3562 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3565 IntRect r = rects[markerIndex];
3566 // skip placeholder rects
3567 if (r == placeholderRectForMarker())
3577 void Document::removeMarkers(Node* node)
3579 MarkerMap::iterator i = m_markers.find(node);
3580 if (i != m_markers.end()) {
3582 m_markers.remove(i);
3583 if (RenderObject* renderer = node->renderer())
3584 renderer->repaint();
3588 void Document::removeMarkers(DocumentMarker::MarkerType markerType)
3590 // outer loop: process each markered node in the document
3591 MarkerMap markerMapCopy = m_markers;
3592 MarkerMap::iterator end = markerMapCopy.end();
3593 for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
3594 Node* node = i->first.get();
3595 bool nodeNeedsRepaint = false;
3597 // inner loop: process each marker in the current node
3598 MarkerMapVectorPair* vectorPair = i->second;
3599 Vector<DocumentMarker>& markers = vectorPair->first;
3600 Vector<IntRect>& rects = vectorPair->second;
3601 ASSERT(markers.size() == rects.size());
3602 for (size_t i = 0; i != markers.size();) {
3603 DocumentMarker marker = markers[i];
3605 // skip nodes that are not of the specified type
3606 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
3611 // pitch the old marker
3614 nodeNeedsRepaint = true;
3615 // markerIterator now points to the next node
3618 // Redraw the node if it changed. Do this before the node is removed from m_markers, since
3619 // m_markers might contain the last reference to the node.
3620 if (nodeNeedsRepaint) {
3621 RenderObject* renderer = node->renderer();
3623 renderer->repaint();
3626 // delete the node's list if it is now empty
3627 if (markers.isEmpty()) {
3628 ASSERT(rects.isEmpty());
3629 m_markers.remove(node);
3635 void Document::repaintMarkers(DocumentMarker::MarkerType markerType)
3637 // outer loop: process each markered node in the document
3638 MarkerMap::iterator end = m_markers.end();
3639 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3640 Node* node = i->first.get();
3642 // inner loop: process each marker in the current node
3643 MarkerMapVectorPair* vectorPair = i->second;
3644 Vector<DocumentMarker>& markers = vectorPair->first;
3645 bool nodeNeedsRepaint = false;
3646 for (size_t i = 0; i != markers.size(); ++i) {
3647 DocumentMarker marker = markers[i];
3649 // skip nodes that are not of the specified type
3650 if (marker.type == markerType || markerType == DocumentMarker::AllMarkers) {
3651 nodeNeedsRepaint = true;
3656 if (!nodeNeedsRepaint)
3659 // cause the node to be redrawn
3660 if (RenderObject* renderer = node->renderer())
3661 renderer->repaint();
3665 void Document::setRenderedRectForMarker(Node* node, DocumentMarker marker, const IntRect& r)
3667 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3669 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3673 Vector<DocumentMarker>&&nbs