2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008 David Levin (levin@chromium.org)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
29 #include "AnimationController.h"
30 #include "AXObjectCache.h"
31 #include "CDATASection.h"
32 #include "CSSHelper.h"
33 #include "CSSStyleSelector.h"
34 #include "CSSStyleSheet.h"
35 #include "CSSValueKeywords.h"
37 #include "CachedCSSStyleSheet.h"
40 #include "CookieJar.h"
41 #include "DOMImplementation.h"
42 #include "DOMWindow.h"
43 #include "DocLoader.h"
44 #include "DocumentFragment.h"
45 #include "DocumentLoader.h"
46 #include "DocumentType.h"
47 #include "EditingText.h"
49 #include "EntityReference.h"
51 #include "EventHandler.h"
52 #include "EventListener.h"
53 #include "EventNames.h"
54 #include "ExceptionCode.h"
55 #include "FocusController.h"
57 #include "FrameLoader.h"
58 #include "FrameTree.h"
59 #include "FrameView.h"
60 #include "HTMLAnchorElement.h"
61 #include "HTMLBodyElement.h"
62 #include "HTMLCanvasElement.h"
63 #include "HTMLDocument.h"
64 #include "HTMLElementFactory.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "HTMLHeadElement.h"
67 #include "HTMLInputElement.h"
68 #include "HTMLLinkElement.h"
69 #include "HTMLMapElement.h"
70 #include "HTMLNameCollection.h"
71 #include "HTMLNames.h"
72 #include "HTMLStyleElement.h"
73 #include "HTMLTitleElement.h"
74 #include "HTTPParsers.h"
75 #include "HistoryItem.h"
76 #include "HitTestRequest.h"
77 #include "HitTestResult.h"
78 #include "ImageLoader.h"
79 #include "InspectorController.h"
80 #include "KeyboardEvent.h"
82 #include "MessageEvent.h"
83 #include "MouseEvent.h"
84 #include "MouseEventWithHitTestResults.h"
85 #include "MutationEvent.h"
86 #include "NameNodeList.h"
87 #include "NodeFilter.h"
88 #include "NodeIterator.h"
89 #include "NodeWithIndex.h"
90 #include "OverflowEvent.h"
92 #include "PlatformKeyboardEvent.h"
93 #include "ProcessingInstruction.h"
94 #include "ProgressEvent.h"
95 #include "RegisteredEventListener.h"
96 #include "RenderArena.h"
97 #include "RenderTextControl.h"
98 #include "RenderView.h"
99 #include "RenderWidget.h"
100 #include "ScriptController.h"
101 #include "SecurityOrigin.h"
102 #include "SegmentedString.h"
103 #include "SelectionController.h"
104 #include "Settings.h"
105 #include "StyleSheetList.h"
106 #include "TextEvent.h"
107 #include "TextIterator.h"
108 #include "TextResourceDecoder.h"
109 #include "TreeWalker.h"
112 #include "WebKitAnimationEvent.h"
113 #include "WebKitTransitionEvent.h"
114 #include "WheelEvent.h"
115 #include "XMLHttpRequest.h"
116 #include "XMLNames.h"
117 #include "XMLTokenizer.h"
118 #include "JSDOMBinding.h"
119 #include "ScriptController.h"
120 #include <wtf/CurrentTime.h>
121 #include <wtf/HashFunctions.h>
122 #include <wtf/MainThread.h>
123 #include <wtf/StdLibExtras.h>
124 #include <wtf/PassRefPtr.h>
127 #include "Database.h"
128 #include "DatabaseThread.h"
131 #if ENABLE(DOM_STORAGE)
132 #include "StorageEvent.h"
136 #include "XPathEvaluator.h"
137 #include "XPathExpression.h"
138 #include "XPathNSResolver.h"
139 #include "XPathResult.h"
143 #include "XSLTProcessor.h"
147 #include "XBLBindingManager.h"
151 #include "SVGDocumentExtensions.h"
152 #include "SVGElementFactory.h"
153 #include "SVGZoomEvent.h"
154 #include "SVGStyleElement.h"
158 #include "WMLDocument.h"
159 #include "WMLElement.h"
160 #include "WMLElementFactory.h"
161 #include "WMLNames.h"
166 using namespace Unicode;
170 using namespace HTMLNames;
172 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
174 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
175 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
177 static const int cLayoutScheduleThreshold = 250;
179 // Use 1 to represent the document's default form.
180 static HTMLFormElement* const defaultForm = reinterpret_cast<HTMLFormElement*>(1);
182 // DOM Level 2 says (letters added):
184 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
185 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
186 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
187 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
188 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
189 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
190 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
191 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
192 // i) Characters ':' and '_' are allowed as name-start characters.
193 // j) Characters '-' and '.' are allowed as name characters.
195 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
197 static inline bool isValidNameStart(UChar32 c)
200 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
204 if (c == ':' || c == '_')
207 // rules (a) and (f) above
208 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
209 if (!(Unicode::category(c) & nameStartMask))
213 if (c >= 0xF900 && c < 0xFFFE)
217 DecompositionType decompType = decompositionType(c);
218 if (decompType == DecompositionFont || decompType == DecompositionCompat)
224 static inline bool isValidNamePart(UChar32 c)
226 // rules (a), (e), and (i) above
227 if (isValidNameStart(c))
230 // rules (g) and (h) above
231 if (c == 0x00B7 || c == 0x0387)
235 if (c == '-' || c == '.')
238 // rules (b) and (f) above
239 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
240 if (!(Unicode::category(c) & otherNamePartMask))
244 if (c >= 0xF900 && c < 0xFFFE)
248 DecompositionType decompType = decompositionType(c);
249 if (decompType == DecompositionFont || decompType == DecompositionCompat)
255 static Widget* widgetForNode(Node* focusedNode)
259 RenderObject* renderer = focusedNode->renderer();
260 if (!renderer || !renderer->isWidget())
262 return static_cast<RenderWidget*>(renderer)->widget();
265 static bool acceptsEditingFocus(Node *node)
268 ASSERT(node->isContentEditable());
270 Node *root = node->rootEditableElement();
271 Frame* frame = node->document()->frame();
275 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
278 static bool disableRangeMutation(Page* page)
281 // Disable Range mutation on document modifications in Tiger and Leopard Mail
282 // See <rdar://problem/5865171>
283 return page && (page->settings()->needsLeopardMailQuirks() || page->settings()->needsTigerMailQuirks());
289 static HashSet<Document*>* changedDocuments = 0;
291 Document::Document(Frame* frame, bool isXHTML)
293 , m_domtree_version(0)
294 , m_styleSheets(StyleSheetList::create(this))
295 , m_frameElementsShouldIgnoreScrolling(false)
297 , m_titleSetExplicitly(false)
298 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
300 , m_transformSource(0)
302 , m_xmlVersion("1.0")
303 , m_xmlStandalone(false)
305 , m_bindingManager(new XBLBindingManager(this))
309 , m_designMode(inherit)
310 , m_selfOnlyRefCount(0)
314 #if ENABLE(DASHBOARD_SUPPORT)
315 , m_hasDashboardRegions(false)
316 , m_dashboardRegionsDirty(false)
318 , m_accessKeyMapValid(false)
319 , m_createRenderers(true)
320 , m_inPageCache(false)
321 , m_useSecureKeyboardEntryWhenActive(false)
323 , m_numNodeListCaches(0)
325 , m_hasOpenDatabases(false)
327 , m_usingGeolocation(false)
329 m_document.resetSkippingRef(this);
333 m_ignoreAutofocus = false;
340 m_docLoader = new DocLoader(this);
342 visuallyOrdered = false;
344 m_docChanged = false;
346 m_wellFormed = false;
348 setParseMode(Strict);
350 m_textColor = Color::black;
353 m_inStyleRecalc = false;
354 m_closeAfterStyleRecalc = false;
355 m_usesDescendantRules = false;
356 m_usesSiblingRules = false;
357 m_usesFirstLineRules = false;
358 m_usesFirstLetterRules = false;
359 m_usesBeforeAfterRules = false;
360 m_gotoAnchorNeededAfterStylesheetsLoad = false;
363 m_didCalculateStyleSelector = false;
364 m_pendingStylesheets = 0;
365 m_ignorePendingStylesheets = false;
366 m_hasNodesWithPlaceholderStyle = false;
367 m_pendingSheetLayout = NoLayoutWithPendingSheets;
372 resetVisitedLinkColor();
373 resetActiveLinkColor();
375 m_processingLoadEvent = false;
376 m_startTime = currentTime();
377 m_overMinimumLayoutThreshold = false;
379 initSecurityContext();
382 static int docID = 0;
386 void Document::removedLastRef()
388 ASSERT(!m_deletionHasBegun);
389 if (m_selfOnlyRefCount) {
390 // If removing a child removes the last self-only ref, we don't
391 // want the document to be destructed until after
392 // removeAllChildren returns, so we guard ourselves with an
393 // extra self-only ref.
395 DocPtr<Document> guard(this);
397 // We must make sure not to be retaining any of our children through
398 // these extra pointers or we will create a reference cycle.
404 m_documentElement = 0;
408 deleteAllValues(m_markers);
414 m_cssCanvasElements.clear();
417 m_inRemovedLastRefFunction = false;
421 m_deletionHasBegun = true;
427 Document::~Document()
430 ASSERT(!m_inPageCache);
431 ASSERT(!m_savedRenderer);
432 ASSERT(m_ranges.isEmpty());
434 removeAllEventListeners();
436 forgetAllDOMNodesForDocument(this);
438 if (m_docChanged && changedDocuments)
439 changedDocuments->remove(this);
441 m_document.resetSkippingRef(0);
442 delete m_styleSelector;
446 delete m_renderArena;
451 xmlFreeDoc((xmlDocPtr)m_transformSource);
455 delete m_bindingManager;
458 deleteAllValues(m_markers);
460 clearAXObjectCache();
464 unsigned count = sizeof(m_nameCollectionInfo) / sizeof(m_nameCollectionInfo[0]);
465 for (unsigned i = 0; i < count; i++)
466 deleteAllValues(m_nameCollectionInfo[i]);
469 if (m_databaseThread) {
470 ASSERT(m_databaseThread->terminationRequested());
471 m_databaseThread = 0;
476 m_styleSheets->documentDestroyed();
481 void Document::resetLinkColor()
483 m_linkColor = Color(0, 0, 238);
486 void Document::resetVisitedLinkColor()
488 m_visitedLinkColor = Color(85, 26, 139);
491 void Document::resetActiveLinkColor()
493 m_activeLinkColor.setNamedColor("red");
496 void Document::setDocType(PassRefPtr<DocumentType> docType)
498 // This should never be called more than once.
499 // Note: This is not a public DOM method and can only be called by the parser.
500 ASSERT(!m_docType || !docType);
501 if (m_docType && docType)
505 m_docType->setDocument(this);
506 determineParseMode();
509 DOMImplementation* Document::implementation() const
511 if (!m_implementation)
512 m_implementation = DOMImplementation::create();
513 return m_implementation.get();
516 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
518 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
520 // Invalidate the document element we have cached in case it was replaced.
521 m_documentElement = 0;
524 void Document::cacheDocumentElement() const
526 ASSERT(!m_documentElement);
527 Node* n = firstChild();
528 while (n && !n->isElementNode())
529 n = n->nextSibling();
530 m_documentElement = static_cast<Element*>(n);
533 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
535 if (!isValidName(name)) {
536 ec = INVALID_CHARACTER_ERR;
541 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
543 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
546 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
548 return new DocumentFragment(document());
551 PassRefPtr<Text> Document::createTextNode(const String& data)
553 return new Text(this, data);
556 PassRefPtr<Comment> Document::createComment(const String& data)
558 return new Comment(this, data);
561 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
563 if (isHTMLDocument()) {
564 ec = NOT_SUPPORTED_ERR;
567 return new CDATASection(this, data);
570 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
572 if (!isValidName(target)) {
573 ec = INVALID_CHARACTER_ERR;
576 if (isHTMLDocument()) {
577 ec = NOT_SUPPORTED_ERR;
580 return new ProcessingInstruction(this, target, data);
583 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
585 if (!isValidName(name)) {
586 ec = INVALID_CHARACTER_ERR;
589 if (isHTMLDocument()) {
590 ec = NOT_SUPPORTED_ERR;
593 return new EntityReference(this, name);
596 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
598 return new EditingText(this, text);
601 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
603 return CSSMutableStyleDeclaration::create();
606 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
611 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
612 || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
615 ec = NOT_SUPPORTED_ERR;
619 switch (importedNode->nodeType()) {
621 return createTextNode(importedNode->nodeValue());
622 case CDATA_SECTION_NODE:
623 return createCDATASection(importedNode->nodeValue(), ec);
624 case ENTITY_REFERENCE_NODE:
625 return createEntityReference(importedNode->nodeName(), ec);
626 case PROCESSING_INSTRUCTION_NODE:
627 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
629 return createComment(importedNode->nodeValue());
631 Element* oldElement = static_cast<Element*>(importedNode);
632 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
637 NamedAttrMap* attrs = oldElement->attributes(true);
639 unsigned length = attrs->length();
640 for (unsigned i = 0; i < length; i++) {
641 Attribute* attr = attrs->attributeItem(i);
642 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
648 newElement->copyNonAttributeProperties(oldElement);
651 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
652 RefPtr<Node> newChild = importNode(oldChild, true, ec);
655 newElement->appendChild(newChild.release(), ec);
661 return newElement.release();
663 case ATTRIBUTE_NODE: {
664 RefPtr<Attr> newAttr = new Attr(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
665 newAttr->createTextChild();
666 return newAttr.release();
668 case DOCUMENT_FRAGMENT_NODE: {
669 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
670 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
672 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
673 RefPtr<Node> newChild = importNode(oldChild, true, ec);
676 newFragment->appendChild(newChild.release(), ec);
682 return newFragment.release();
686 // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
687 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
689 case DOCUMENT_TYPE_NODE:
690 case XPATH_NAMESPACE_NODE:
694 ec = NOT_SUPPORTED_ERR;
699 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
702 ec = NOT_SUPPORTED_ERR;
706 if (source->isReadOnlyNode()) {
707 ec = NO_MODIFICATION_ALLOWED_ERR;
711 switch (source->nodeType()) {
715 case DOCUMENT_TYPE_NODE:
716 case XPATH_NAMESPACE_NODE:
717 ec = NOT_SUPPORTED_ERR;
719 case ATTRIBUTE_NODE: {
720 Attr* attr = static_cast<Attr*>(source.get());
721 if (attr->ownerElement())
722 attr->ownerElement()->removeAttributeNode(attr, ec);
723 attr->setSpecified(true);
727 if (source->parentNode())
728 source->parentNode()->removeChild(source.get(), ec);
731 for (Node* node = source.get(); node; node = node->traverseNextNode(source.get()))
732 node->setDocument(this);
737 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
739 DEFINE_STATIC_LOCAL(const AtomicString, xmlnsNamespaceURI, ("http://www.w3.org/2000/xmlns/"));
740 DEFINE_STATIC_LOCAL(const AtomicString, xmlns, ("xmlns"));
741 DEFINE_STATIC_LOCAL(const AtomicString, xml, ("xml"));
743 // These checks are from DOM Core Level 2, createElementNS
744 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
745 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
747 if (qName.prefix() == xml && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
750 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
751 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
752 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
753 if ((qName.prefix() == xmlns && qName.namespaceURI() != xmlnsNamespaceURI) || (qName.prefix() != xmlns && qName.namespaceURI() == xmlnsNamespaceURI))
759 // FIXME: This should really be in a possible ElementFactory class
760 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
764 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
765 if (qName.namespaceURI() == xhtmlNamespaceURI)
766 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
768 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
769 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
772 else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI || isWMLDocument())
773 e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
777 e = new Element(qName, document());
779 // <image> uses imgTag so we need a special rule.
780 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
785 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
787 String prefix, localName;
788 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
791 QualifiedName qName(prefix, localName, namespaceURI);
792 if (hasPrefixNamespaceMismatch(qName)) {
797 return createElement(qName, false);
800 Element* Document::getElementById(const AtomicString& elementId) const
802 if (elementId.isEmpty())
805 Element* element = m_elementsById.get(elementId.impl());
809 if (m_duplicateIds.contains(elementId.impl())) {
810 // We know there's at least one node with this id, but we don't know what the first one is.
811 for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
812 if (n->isElementNode()) {
813 element = static_cast<Element*>(n);
814 if (element->hasID() && element->getAttribute(idAttr) == elementId) {
815 m_duplicateIds.remove(elementId.impl());
816 m_elementsById.set(elementId.impl(), element);
821 ASSERT_NOT_REACHED();
826 String Document::readyState() const
828 if (Frame* f = frame()) {
829 if (f->loader()->isComplete())
834 // FIXME: What does "interactive" mean?
835 // FIXME: Missing support for "uninitialized".
840 String Document::encoding() const
842 if (TextResourceDecoder* d = decoder())
843 return d->encoding().name();
847 String Document::defaultCharset() const
849 if (Settings* settings = this->settings())
850 return settings->defaultTextEncodingName();
854 void Document::setCharset(const String& charset)
858 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
861 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
863 if (!implementation()->hasFeature("XML", String())) {
864 ec = NOT_SUPPORTED_ERR;
868 // FIXME: Also raise NOT_SUPPORTED_ERR if the version is set to a value that is not supported by this Document.
870 m_xmlVersion = version;
873 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
875 if (!implementation()->hasFeature("XML", String())) {
876 ec = NOT_SUPPORTED_ERR;
880 m_xmlStandalone = standalone;
883 void Document::setDocumentURI(const String& uri)
889 KURL Document::baseURI() const
894 Element* Document::elementFromPoint(int x, int y) const
899 HitTestRequest request(HitTestRequest::ReadOnly |
900 HitTestRequest::Active);
902 float zoomFactor = frame() ? frame()->pageZoomFactor() : 1.0f;
904 HitTestResult result(roundedIntPoint(FloatPoint(x * zoomFactor, y * zoomFactor)));
905 renderView()->layer()->hitTest(request, result);
907 Node* n = result.innerNode();
908 while (n && !n->isElementNode())
911 n = n->shadowAncestorNode();
912 return static_cast<Element*>(n);
915 void Document::addElementById(const AtomicString& elementId, Element* element)
917 typedef HashMap<AtomicStringImpl*, Element*>::iterator iterator;
918 if (!m_duplicateIds.contains(elementId.impl())) {
919 // Fast path. The ID is not already in m_duplicateIds, so we assume that it's
920 // also not already in m_elementsById and do an add. If that add succeeds, we're done.
921 pair<iterator, bool> addResult = m_elementsById.add(elementId.impl(), element);
922 if (addResult.second)
924 // The add failed, so this ID was already cached in m_elementsById.
925 // There are multiple elements with this ID. Remove the m_elementsById
926 // cache for this ID so getElementById searches for it next time it is called.
927 m_elementsById.remove(addResult.first);
928 m_duplicateIds.add(elementId.impl());
930 // There are multiple elements with this ID. If it exists, remove the m_elementsById
931 // cache for this ID so getElementById searches for it next time it is called.
932 iterator cachedItem = m_elementsById.find(elementId.impl());
933 if (cachedItem != m_elementsById.end()) {
934 m_elementsById.remove(cachedItem);
935 m_duplicateIds.add(elementId.impl());
938 m_duplicateIds.add(elementId.impl());
941 void Document::removeElementById(const AtomicString& elementId, Element* element)
943 if (m_elementsById.get(elementId.impl()) == element)
944 m_elementsById.remove(elementId.impl());
946 m_duplicateIds.remove(elementId.impl());
949 Element* Document::getElementByAccessKey(const String& key) const
953 if (!m_accessKeyMapValid) {
954 for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
955 if (!n->isElementNode())
957 Element* element = static_cast<Element*>(n);
958 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
959 if (!accessKey.isEmpty())
960 m_elementsByAccessKey.set(accessKey.impl(), element);
962 m_accessKeyMapValid = true;
964 return m_elementsByAccessKey.get(key.impl());
967 void Document::updateTitle()
969 if (Frame* f = frame())
970 f->loader()->setTitle(m_title);
973 void Document::setTitle(const String& title, Element* titleElement)
976 // Title set by JavaScript -- overrides any title elements.
977 m_titleSetExplicitly = true;
978 if (!isHTMLDocument())
980 else if (!m_titleElement) {
981 if (HTMLElement* headElement = head()) {
982 m_titleElement = createElement(titleTag, false);
983 ExceptionCode ec = 0;
984 headElement->appendChild(m_titleElement, ec);
988 } else if (titleElement != m_titleElement) {
989 if (m_titleElement || m_titleSetExplicitly)
990 // Only allow the first title element to change the title -- others have no effect.
992 m_titleElement = titleElement;
995 if (m_title == title)
1001 if (m_titleSetExplicitly && m_titleElement && m_titleElement->hasTagName(titleTag))
1002 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(m_title);
1005 void Document::removeTitle(Element* titleElement)
1007 if (m_titleElement != titleElement)
1011 m_titleSetExplicitly = false;
1013 // Update title based on first title element in the head, if one exists.
1014 if (HTMLElement* headElement = head()) {
1015 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1016 if (e->hasTagName(titleTag)) {
1017 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1018 setTitle(titleElement->text(), titleElement);
1023 if (!m_titleElement && !m_title.isEmpty()) {
1029 String Document::nodeName() const
1034 Node::NodeType Document::nodeType() const
1036 return DOCUMENT_NODE;
1039 FrameView* Document::view() const
1041 return m_frame ? m_frame->view() : 0;
1044 Page* Document::page() const
1046 return m_frame ? m_frame->page() : 0;
1049 Settings* Document::settings() const
1051 return m_frame ? m_frame->settings() : 0;
1054 PassRefPtr<Range> Document::createRange()
1056 return Range::create(this);
1059 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1060 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1063 ec = NOT_SUPPORTED_ERR;
1066 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1069 PassRefPtr<TreeWalker> Document::createTreeWalker(Node *root, unsigned whatToShow,
1070 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1073 ec = NOT_SUPPORTED_ERR;
1076 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1079 void Document::setDocumentChanged(bool b)
1082 if (!m_docChanged) {
1083 if (!changedDocuments)
1084 changedDocuments = new HashSet<Document*>;
1085 changedDocuments->add(this);
1087 if (m_accessKeyMapValid) {
1088 m_accessKeyMapValid = false;
1089 m_elementsByAccessKey.clear();
1092 if (m_docChanged && changedDocuments)
1093 changedDocuments->remove(this);
1099 void Document::recalcStyle(StyleChange change)
1101 // we should not enter style recalc while painting
1102 if (view() && view()->isPainting()) {
1103 ASSERT(!view()->isPainting());
1107 if (m_inStyleRecalc)
1108 return; // Guard against re-entrancy. -dwh
1110 m_inStyleRecalc = true;
1111 suspendPostAttachCallbacks();
1113 view()->pauseScheduledEvents();
1115 ASSERT(!renderer() || renderArena());
1116 if (!renderer() || !renderArena())
1119 if (change == Force) {
1120 // style selector may set this again during recalc
1121 m_hasNodesWithPlaceholderStyle = false;
1123 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1124 documentStyle->setDisplay(BLOCK);
1125 documentStyle->setVisuallyOrdered(visuallyOrdered);
1126 documentStyle->setZoom(frame()->pageZoomFactor());
1127 m_styleSelector->setStyle(documentStyle);
1129 FontDescription fontDescription;
1130 fontDescription.setUsePrinterFont(printing());
1131 if (Settings* settings = this->settings()) {
1132 fontDescription.setRenderingMode(settings->fontRenderingMode());
1133 if (printing() && !settings->shouldPrintBackgrounds())
1134 documentStyle->setForceBackgroundsToWhite(true);
1135 const AtomicString& stdfont = settings->standardFontFamily();
1136 if (!stdfont.isEmpty()) {
1137 fontDescription.firstFamily().setFamily(stdfont);
1138 fontDescription.firstFamily().appendFamily(0);
1140 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1141 m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSSValueMedium, inCompatMode(), false));
1144 documentStyle->setFontDescription(fontDescription);
1145 documentStyle->font().update(m_styleSelector->fontSelector());
1147 documentStyle->setHtmlHacks(true); // enable html specific rendering tricks
1149 StyleChange ch = diff(documentStyle.get(), renderer()->style());
1150 if (renderer() && ch != NoChange)
1151 renderer()->setStyle(documentStyle.release());
1154 for (Node* n = firstChild(); n; n = n->nextSibling())
1155 if (change >= Inherit || n->hasChangedChild() || n->changed())
1156 n->recalcStyle(change);
1161 #if USE(ACCELERATED_COMPOSITING)
1163 // If we didn't update compositing layers because of layout(), we need to do so here.
1164 view()->updateCompositingLayers();
1170 setChanged(NoStyleChange);
1171 setHasChangedChild(false);
1172 setDocumentChanged(false);
1175 view()->resumeScheduledEvents();
1176 resumePostAttachCallbacks();
1177 m_inStyleRecalc = false;
1179 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1180 if (m_closeAfterStyleRecalc) {
1181 m_closeAfterStyleRecalc = false;
1186 void Document::updateRendering()
1188 if (!hasChangedChild() || inPageCache())
1192 m_frame->animation()->beginAnimationUpdate();
1194 recalcStyle(NoChange);
1196 // Tell the animation controller that updateRendering is finished and it can do any post-processing
1198 m_frame->animation()->endAnimationUpdate();
1201 void Document::updateDocumentsRendering()
1203 if (!changedDocuments)
1206 while (changedDocuments->size()) {
1207 HashSet<Document*>::iterator it = changedDocuments->begin();
1208 Document* doc = *it;
1209 changedDocuments->remove(it);
1211 doc->m_docChanged = false;
1212 doc->updateRendering();
1216 void Document::updateLayout()
1218 if (Element* oe = ownerElement())
1219 oe->document()->updateLayout();
1223 // Only do a layout if changes have occurred that make it necessary.
1224 FrameView* v = view();
1225 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1229 // FIXME: This is a bad idea and needs to be removed eventually.
1230 // Other browsers load stylesheets before they continue parsing the web page.
1231 // Since we don't, we can run JavaScript code that needs answers before the
1232 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1233 // lets us get reasonable answers. The long term solution to this problem is
1234 // to instead suspend JavaScript execution.
1235 void Document::updateLayoutIgnorePendingStylesheets()
1237 bool oldIgnore = m_ignorePendingStylesheets;
1239 if (!haveStylesheetsLoaded()) {
1240 m_ignorePendingStylesheets = true;
1241 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1242 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1243 // with accurate style information. (Our suppression involves blanking the whole page at the
1244 // moment. If it were more refined, we might be able to do something better.)
1245 // It's worth noting though that this entire method is a hack, since what we really want to do is
1246 // suspend JS instead of doing a layout with inaccurate information.
1247 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1248 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1249 updateStyleSelector();
1250 } else if (m_hasNodesWithPlaceholderStyle)
1251 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1252 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1253 // but here we need up-to-date style immediatly.
1259 m_ignorePendingStylesheets = oldIgnore;
1262 void Document::attach()
1264 ASSERT(!attached());
1265 ASSERT(!m_inPageCache);
1266 ASSERT(!m_axObjectCache);
1269 m_renderArena = new RenderArena();
1271 // Create the rendering tree
1272 setRenderer(new (m_renderArena) RenderView(this, view()));
1273 #if USE(ACCELERATED_COMPOSITING)
1274 renderView()->didMoveOnscreen();
1277 if (!m_styleSelector) {
1278 bool matchAuthorAndUserStyles = true;
1279 if (Settings* docSettings = settings())
1280 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1281 m_styleSelector = new CSSStyleSelector(this, userStyleSheet(), m_styleSheets.get(), m_mappedElementSheet.get(), !inCompatMode(), matchAuthorAndUserStyles);
1286 RenderObject* render = renderer();
1289 ContainerNode::attach();
1291 setRenderer(render);
1294 void Document::detach()
1297 ASSERT(!m_inPageCache);
1299 clearAXObjectCache();
1300 stopActiveDOMObjects();
1302 RenderObject* render = renderer();
1304 // Send out documentWillBecomeInactive() notifications to registered elements,
1305 // in order to stop media elements
1306 documentWillBecomeInactive();
1308 // indicate destruction mode, i.e. attached() but renderer == 0
1315 ContainerNode::detach();
1320 // This is required, as our Frame might delete itself as soon as it detaches
1321 // us. However, this violates Node::detach() symantics, as it's never
1322 // possible to re-attach. Eventually Document::detach() should be renamed,
1323 // or this setting of the frame to 0 could be made explicit in each of the
1324 // callers of Document::detach().
1327 if (m_renderArena) {
1328 delete m_renderArena;
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 ImageLoader::dispatchPendingLoadEvents();
1587 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() && body()) ||
1670 (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);
1700 ASSERT(m_tokenizer);
1701 m_tokenizer->write(text, false);
1703 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1704 if (!ownerElement())
1705 printf("Ending a document.write at %d\n", elapsedTime());
1709 void Document::write(const String& text, Document* ownerDocument)
1711 write(SegmentedString(text), ownerDocument);
1714 void Document::writeln(const String& text, Document* ownerDocument)
1716 write(text, ownerDocument);
1717 write("\n", ownerDocument);
1720 void Document::finishParsing()
1722 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1723 if (!ownerElement())
1724 printf("Received all data at %d\n", elapsedTime());
1727 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1728 // finish() is called:
1729 // (1) All remaining data is parsed, document isn't loaded yet
1730 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1731 // (3) Data is still remaining to be parsed.
1733 m_tokenizer->finish();
1736 void Document::clear()
1743 size_t size = m_windowEventListeners.size();
1744 for (size_t i = 0; i < size; ++i)
1745 m_windowEventListeners[i]->setRemoved(true);
1746 m_windowEventListeners.clear();
1749 const KURL& Document::virtualURL() const
1754 KURL Document::virtualCompleteURL(const String& url) const
1756 return completeURL(url);
1759 void Document::setURL(const KURL& url)
1761 const KURL& newURL = url.isEmpty() ? blankURL() : url;
1762 if (newURL == m_url)
1766 m_documentURI = m_url.string();
1770 void Document::setBaseElementURL(const KURL& baseElementURL)
1772 m_baseElementURL = baseElementURL;
1776 void Document::updateBaseURL()
1778 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
1779 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
1780 // from the Document interface otherwise.
1781 if (m_baseElementURL.isEmpty()) {
1782 // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
1783 // so we use a null base URL.
1784 m_baseURL = KURL(KURL(), documentURI());
1786 m_baseURL = m_baseElementURL;
1787 if (!m_baseURL.isValid())
1791 m_elemSheet->setHref(m_baseURL.string());
1792 if (m_mappedElementSheet)
1793 m_mappedElementSheet->setHref(m_baseURL.string());
1796 String Document::userAgent(const KURL& url) const
1798 return frame() ? frame()->loader()->userAgent(url) : 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 (!disableRangeMutation(page())) {
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 (!disableRangeMutation(page())) {
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 (!disableRangeMutation(page())) {
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 (!disableRangeMutation(page())) {
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 (!disableRangeMutation(page())) {
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 (!disableRangeMutation(page())) {
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 Element* Document::ownerElement() const
2879 return frame()->ownerElement();
2882 String Document::cookie() const
2884 if (page() && !page()->cookieEnabled())
2887 KURL cookieURL = this->cookieURL();
2888 if (cookieURL.isEmpty())
2891 return cookies(this, cookieURL);
2894 void Document::setCookie(const String& value)
2896 if (page() && !page()->cookieEnabled())
2899 KURL cookieURL = this->cookieURL();
2900 if (cookieURL.isEmpty())
2903 setCookies(this, cookieURL, policyBaseURL(), value);
2906 String Document::referrer() const
2909 return frame()->loader()->referrer();
2913 String Document::domain() const
2915 return securityOrigin()->domain();
2918 void Document::setDomain(const String& newDomain)
2920 // Both NS and IE specify that changing the domain is only allowed when
2921 // the new domain is a suffix of the old domain.
2923 // FIXME: We should add logging indicating why a domain was not allowed.
2925 // If the new domain is the same as the old domain, still call
2926 // securityOrigin()->setDomainForDOM. This will change the
2927 // security check behavior. For example, if a page loaded on port 8000
2928 // assigns its current domain using document.domain, the page will
2929 // allow other pages loaded on different ports in the same domain that
2930 // have also assigned to access this page.
2931 if (equalIgnoringCase(domain(), newDomain)) {
2932 securityOrigin()->setDomainFromDOM(newDomain);
2934 m_frame->script()->updateSecurityOrigin();
2938 int oldLength = domain().length();
2939 int newLength = newDomain.length();
2940 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
2941 if (newLength >= oldLength)
2944 String test = domain();
2945 // Check that it's a subdomain, not e.g. "ebkit.org"
2946 if (test[oldLength - newLength - 1] != '.')
2949 // Now test is "webkit.org" from domain()
2950 // and we check that it's the same thing as newDomain
2951 test.remove(0, oldLength - newLength);
2952 if (test != newDomain)
2955 securityOrigin()->setDomainFromDOM(newDomain);
2957 m_frame->script()->updateSecurityOrigin();
2960 String Document::lastModified() const
2965 DocumentLoader* loader = f->loader()->documentLoader();
2968 return loader->response().httpHeaderField("Last-Modified");
2971 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
2976 U16_NEXT(characters, i, length, c)
2977 if (!isValidNameStart(c))
2980 while (i < length) {
2981 U16_NEXT(characters, i, length, c)
2982 if (!isValidNamePart(c))
2989 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
2991 UChar c = characters[0];
2992 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
2995 for (unsigned i = 1; i < length; ++i) {
2997 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3004 bool Document::isValidName(const String& name)
3006 unsigned length = name.length();
3010 const UChar* characters = name.characters();
3011 return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3014 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3016 unsigned length = qualifiedName.length();
3019 ec = INVALID_CHARACTER_ERR;
3023 bool nameStart = true;
3024 bool sawColon = false;
3027 const UChar* s = qualifiedName.characters();
3028 for (unsigned i = 0; i < length;) {
3030 U16_NEXT(s, i, length, c)
3034 return false; // multiple colons: not allowed
3039 } else if (nameStart) {
3040 if (!isValidNameStart(c)) {
3041 ec = INVALID_CHARACTER_ERR;
3046 if (!isValidNamePart(c)) {
3047 ec = INVALID_CHARACTER_ERR;
3055 localName = qualifiedName;
3057 prefix = qualifiedName.substring(0, colonPos);
3058 if (prefix.isEmpty()) {
3062 localName = qualifiedName.substring(colonPos + 1);
3065 if (localName.isEmpty()) {
3073 void Document::addImageMap(HTMLMapElement* imageMap)
3075 const AtomicString& name = imageMap->getName();
3079 // Add the image map, unless there's already another with that name.
3080 // "First map wins" is the rule other browsers seem to implement.
3081 m_imageMapsByName.add(name.impl(), imageMap);
3084 void Document::removeImageMap(HTMLMapElement* imageMap)
3086 // Remove the image map by name.
3087 // But don't remove some other image map that just happens to have the same name.
3088 // FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
3089 // once a map has been removed.
3090 const AtomicString& name = imageMap->getName();
3094 ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
3095 if (it != m_imageMapsByName.end() && it->second == imageMap)
3096 m_imageMapsByName.remove(it);
3099 HTMLMapElement *Document::getImageMap(const String& url) const
3103 int hashPos = url.find('#');
3104 String name = (hashPos < 0 ? url : url.substring(hashPos + 1)).impl();
3105 AtomicString mapName = isHTMLDocument() ? name.lower() : name;
3106 return m_imageMapsByName.get(mapName.impl());
3109 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3111 m_decoder = decoder;
3114 KURL Document::completeURL(const String& url) const
3116 // Always return a null URL when passed a null string.
3117 // FIXME: Should we change the KURL constructor to have this behavior?
3118 // See also [CSS]StyleSheet::completeURL(const String&)
3121 const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
3123 return KURL(baseURL, url);
3124 return KURL(baseURL, url, m_decoder->encoding());
3127 void Document::setInPageCache(bool flag)
3129 if (m_inPageCache == flag)
3132 m_inPageCache = flag;
3134 ASSERT(m_savedRenderer == 0);
3135 m_savedRenderer = renderer();
3136 if (FrameView* v = view())
3137 v->resetScrollbars();
3139 ASSERT(renderer() == 0 || renderer() == m_savedRenderer);
3140 ASSERT(m_renderArena);
3141 setRenderer(m_savedRenderer);
3142 m_savedRenderer = 0;
3146 void Document::documentWillBecomeInactive()
3148 #if USE(ACCELERATED_COMPOSITING)
3150 renderView()->willMoveOffscreen();
3153 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3154 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3155 (*i)->documentWillBecomeInactive();
3158 void Document::documentDidBecomeActive()
3160 HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3161 for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3162 (*i)->documentDidBecomeActive();
3164 #if USE(ACCELERATED_COMPOSITING)
3166 renderView()->didMoveOnscreen();
3170 void Document::registerForDocumentActivationCallbacks(Element* e)
3172 m_documentActivationCallbackElements.add(e);
3175 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3177 m_documentActivationCallbackElements.remove(e);
3180 void Document::mediaVolumeDidChange()
3182 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3183 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3184 (*i)->mediaVolumeDidChange();
3187 void Document::registerForMediaVolumeCallbacks(Element* e)
3189 m_mediaVolumeCallbackElements.add(e);
3192 void Document::unregisterForMediaVolumeCallbacks(Element* e)
3194 m_mediaVolumeCallbackElements.remove(e);
3197 void Document::setShouldCreateRenderers(bool f)
3199 m_createRenderers = f;
3202 bool Document::shouldCreateRenderers()
3204 return m_createRenderers;
3207 // Support for Javascript execCommand, and related methods
3209 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
3211 Frame* frame = document->frame();
3212 if (!frame || frame->document() != document)
3213 return Editor::Command();
3214 return frame->editor()->command(commandName,
3215 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
3218 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
3220 return command(this, commandName, userInterface).execute(value);
3223 bool Document::queryCommandEnabled(const String& commandName)
3225 return command(this, commandName).isEnabled();
3228 bool Document::queryCommandIndeterm(const String& commandName)
3230 return command(this, commandName).state() == MixedTriState;
3233 bool Document::queryCommandState(const String& commandName)
3235 return command(this, commandName).state() != FalseTriState;
3238 bool Document::queryCommandSupported(const String& commandName)
3240 return command(this, commandName).isSupported();
3243 String Document::queryCommandValue(const String& commandName)
3245 return command(this, commandName).value();
3248 static IntRect placeholderRectForMarker()
3250 return IntRect(-1, -1, -1, -1);
3253 void Document::addMarker(Range *range, DocumentMarker::MarkerType type, String description)
3255 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3256 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3257 RefPtr<Range> textPiece = markedText.range();
3259 DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception), description};
3260 addMarker(textPiece->startContainer(exception), marker);
3264 void Document::removeMarkers(Range* range, DocumentMarker::MarkerType markerType)
3266 if (m_markers.isEmpty())
3269 ExceptionCode ec = 0;
3270 Node* startContainer = range->startContainer(ec);
3271 Node* endContainer = range->endContainer(ec);
3273 Node* pastLastNode = range->pastLastNode();
3274 for (Node* node = range->firstNode(); node != pastLastNode; node = node->traverseNextNode()) {
3275 int startOffset = node == startContainer ? range->startOffset(ec) : 0;
3276 int endOffset = node == endContainer ? range->endOffset(ec) : INT_MAX;
3277 int length = endOffset - startOffset;
3278 removeMarkers(node, startOffset, length, markerType);
3282 // Markers are stored in order sorted by their start offset.
3283 // Markers of the same type do not overlap each other.
3285 void Document::addMarker(Node* node, DocumentMarker newMarker)
3287 ASSERT(newMarker.endOffset >= newMarker.startOffset);
3288 if (newMarker.endOffset == newMarker.startOffset)
3291 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3294 vectorPair = new MarkerMapVectorPair;
3295 vectorPair->first.append(newMarker);
3296 vectorPair->second.append(placeholderRectForMarker());
3297 m_markers.set(node, vectorPair);
3299 Vector<DocumentMarker>& markers = vectorPair->first;
3300 Vector<IntRect>& rects = vectorPair->second;
3301 size_t numMarkers = markers.size();
3302 ASSERT(numMarkers == rects.size());
3304 // Iterate over all markers whose start offset is less than or equal to the new marker's.
3305 // If one of them is of the same type as the new marker and touches it or intersects with it
3306 // (there is at most one), remove it and adjust the new marker's start offset to encompass it.
3307 for (i = 0; i < numMarkers; ++i) {
3308 DocumentMarker marker = markers[i];
3309 if (marker.startOffset > newMarker.startOffset)
3311 if (marker.type == newMarker.type && marker.endOffset >= newMarker.startOffset) {
3312 newMarker.startOffset = marker.startOffset;
3320 // Iterate over all markers whose end offset is less than or equal to the new marker's,
3321 // removing markers of the same type as the new marker which touch it or intersect with it,
3322 // adjusting the new marker's end offset to cover them if necessary.
3323 while (j < numMarkers) {
3324 DocumentMarker marker = markers[j];
3325 if (marker.startOffset > newMarker.endOffset)
3327 if (marker.type == newMarker.type) {
3330 if (newMarker.endOffset <= marker.endOffset) {
3331 newMarker.endOffset = marker.endOffset;
3338 // At this point i points to the node before which we want to insert.
3339 markers.insert(i, newMarker);
3340 rects.insert(i, placeholderRectForMarker());
3343 // repaint the affected node
3344 if (node->renderer())
3345 node->renderer()->repaint();
3348 // copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
3349 // useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
3350 void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
3355 MarkerMapVectorPair* vectorPair = m_markers.get(srcNode);
3359 ASSERT(vectorPair->first.size() == vectorPair->second.size());
3361 bool docDirty = false;
3362 unsigned endOffset = startOffset + length - 1;
3363 Vector<DocumentMarker>& markers = vectorPair->first;
3364 for (size_t i = 0; i != markers.size(); ++i) {
3365 DocumentMarker marker = markers[i];
3367 // stop if we are now past the specified range
3368 if (marker.startOffset > endOffset)
3371 // skip marker that is before the specified range or is the wrong type
3372 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
3375 // pin the marker to the specified range and apply the shift delta
3377 if (marker.startOffset < startOffset)
3378 marker.startOffset = startOffset;
3379 if (marker.endOffset > endOffset)
3380 marker.endOffset = endOffset;
3381 marker.startOffset += delta;
3382 marker.endOffset += delta;
3384 addMarker(dstNode, marker);
3387 // repaint the affected node
3388 if (docDirty && dstNode->renderer())
3389 dstNode->renderer()->repaint();
3392 void Document::removeMarkers(Node* node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
3397 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3401 Vector<DocumentMarker>& markers = vectorPair->first;
3402 Vector<IntRect>& rects = vectorPair->second;
3403 ASSERT(markers.size() == rects.size());
3404 bool docDirty = false;
3405 unsigned endOffset = startOffset + length;
3406 for (size_t i = 0; i < markers.size();) {
3407 DocumentMarker marker = markers[i];
3409 // markers are returned in order, so stop if we are now past the specified range
3410 if (marker.startOffset >= endOffset)
3413 // skip marker that is wrong type or before target
3414 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
3419 // at this point we know that marker and target intersect in some way
3422 // pitch the old marker and any associated rect
3426 // add either of the resulting slices that are left after removing target
3427 if (startOffset > marker.startOffset) {
3428 DocumentMarker newLeft = marker;
3429 newLeft.endOffset = startOffset;
3430 markers.insert(i, newLeft);
3431 rects.insert(i, placeholderRectForMarker());
3432 // i now points to the newly-inserted node, but we want to skip that one
3435 if (marker.endOffset > endOffset) {
3436 DocumentMarker newRight = marker;
3437 newRight.startOffset = endOffset;
3438 markers.insert(i, newRight);
3439 rects.insert(i, placeholderRectForMarker());
3440 // i now points to the newly-inserted node, but we want to skip that one
3445 if (markers.isEmpty()) {
3446 ASSERT(rects.isEmpty());
3447 m_markers.remove(node);
3451 // repaint the affected node
3452 if (docDirty && node->renderer())
3453 node->renderer()->repaint();
3456 DocumentMarker* Document::markerContainingPoint(const IntPoint& point, DocumentMarker::MarkerType markerType)
3458 // outer loop: process each node that contains any markers
3459 MarkerMap::iterator end = m_markers.end();
3460 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3461 // inner loop; process each marker in this node
3462 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3463 Vector<DocumentMarker>& markers = vectorPair->first;
3464 Vector<IntRect>& rects = vectorPair->second;
3465 ASSERT(markers.size() == rects.size());
3466 unsigned markerCount = markers.size();
3467 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3468 DocumentMarker& marker = markers[markerIndex];
3470 // skip marker that is wrong type
3471 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3474 IntRect& r = rects[markerIndex];
3476 // skip placeholder rects
3477 if (r == placeholderRectForMarker())
3480 if (r.contains(point))
3488 Vector<DocumentMarker> Document::markersForNode(Node* node)
3490 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3492 return vectorPair->first;
3493 return Vector<DocumentMarker>();
3496 Vector<IntRect> Document::renderedRectsForMarkers(DocumentMarker::MarkerType markerType)
3498 Vector<IntRect> result;
3500 // outer loop: process each node
3501 MarkerMap::iterator end = m_markers.end();
3502 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
3503 // inner loop; process each marker in this node
3504 MarkerMapVectorPair* vectorPair = nodeIterator->second;
3505 Vector<DocumentMarker>& markers = vectorPair->first;
3506 Vector<IntRect>& rects = vectorPair->second;
3507 ASSERT(markers.size() == rects.size());
3508 unsigned markerCount = markers.size();
3509 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3510 DocumentMarker marker = markers[markerIndex];
3512 // skip marker that is wrong type
3513 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
3516 IntRect r = rects[markerIndex];
3517 // skip placeholder rects
3518 if (r == placeholderRectForMarker())
3528 void Document::removeMarkers(Node* node)
3530 MarkerMap::iterator i = m_markers.find(node);
3531 if (i != m_markers.end()) {
3533 m_markers.remove(i);
3534 if (RenderObject* renderer = node->renderer())
3535 renderer->repaint();
3539 void Document::removeMarkers(DocumentMarker::MarkerType markerType)
3541 // outer loop: process each markered node in the document
3542 MarkerMap markerMapCopy = m_markers;
3543 MarkerMap::iterator end = markerMapCopy.end();
3544 for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
3545 Node* node = i->first.get();
3546 bool nodeNeedsRepaint = false;
3548 // inner loop: process each marker in the current node
3549 MarkerMapVectorPair* vectorPair = i->second;
3550 Vector<DocumentMarker>& markers = vectorPair->first;
3551 Vector<IntRect>& rects = vectorPair->second;
3552 ASSERT(markers.size() == rects.size());
3553 for (size_t i = 0; i != markers.size();) {
3554 DocumentMarker marker = markers[i];
3556 // skip nodes that are not of the specified type
3557 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
3562 // pitch the old marker
3565 nodeNeedsRepaint = true;
3566 // markerIterator now points to the next node
3569 // Redraw the node if it changed. Do this before the node is removed from m_markers, since
3570 // m_markers might contain the last reference to the node.
3571 if (nodeNeedsRepaint) {
3572 RenderObject* renderer = node->renderer();
3574 renderer->repaint();
3577 // delete the node's list if it is now empty
3578 if (markers.isEmpty()) {
3579 ASSERT(rects.isEmpty());
3580 m_markers.remove(node);
3586 void Document::repaintMarkers(DocumentMarker::MarkerType markerType)
3588 // outer loop: process each markered node in the document
3589 MarkerMap::iterator end = m_markers.end();
3590 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3591 Node* node = i->first.get();
3593 // inner loop: process each marker in the current node
3594 MarkerMapVectorPair* vectorPair = i->second;
3595 Vector<DocumentMarker>& markers = vectorPair->first;
3596 bool nodeNeedsRepaint = false;
3597 for (size_t i = 0; i != markers.size(); ++i) {
3598 DocumentMarker marker = markers[i];
3600 // skip nodes that are not of the specified type
3601 if (marker.type == markerType || markerType == DocumentMarker::AllMarkers) {
3602 nodeNeedsRepaint = true;
3607 if (!nodeNeedsRepaint)
3610 // cause the node to be redrawn
3611 if (RenderObject* renderer = node->renderer())
3612 renderer->repaint();
3616 void Document::setRenderedRectForMarker(Node* node, DocumentMarker marker, const IntRect& r)
3618 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3620 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3624 Vector<DocumentMarker>& markers = vectorPair->first;
3625 ASSERT(markers.size() == vectorPair->second.size());
3626 unsigned markerCount = markers.size();
3627 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3628 DocumentMarker m = markers[markerIndex];
3630 vectorPair->second[markerIndex] = r;
3635 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3638 void Document::invalidateRenderedRectsForMarkersInRect(const IntRect& r)
3640 // outer loop: process each markered node in the document
3641 MarkerMap::iterator end = m_markers.end();
3642 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3644 // inner loop: process each rect in the current node
3645 MarkerMapVectorPair* vectorPair = i->second;
3646 Vector<IntRect>& rects = vectorPair->second;
3648 unsigned rectCount = rects.size();
3649 for (unsigned rectIndex = 0; rectIndex < rectCount; ++rectIndex)
3650 if (rects[rectIndex].intersects(r))
3651 rects[rectIndex] = placeholderRectForMarker();
3655 void Document::shiftMarkers(Node *node, unsigned startOffset, int delta, DocumentMarker::MarkerType markerType)
3657 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3661 Vector<DocumentMarker>& markers = vectorPair->first;
3662 Vector<IntRect>& rects = vectorPair->second;
3663 ASSERT(markers.size() == rects.size());
3665 bool docDirty = false;
3666 for (size_t i = 0; i != markers.size(); ++i) {
3667 DocumentMarker &marker = markers[i];
3668 if (marker.startOffset >= startOffset && (markerType == DocumentMarker::AllMarkers || marker.type == markerType)) {
3669 ASSERT((int)marker.startOffset + delta >= 0);
3670 marker.startOffset += delta;