2 * This file is part of the DOM implementation for KDE.
4 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
5 * (C) 1999 Antti Koivisto (koivisto@kde.org)
6 * (C) 2001 Dirk Mueller (mueller@kde.org)
7 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
8 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
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., 59 Temple Place - Suite 330,
23 * Boston, MA 02111-1307, USA.
29 #include "AXObjectCache.h"
30 #include "CDATASection.h"
31 #include "CSSStyleSheet.h"
32 #include "CSSValueKeywords.h"
34 #include "DOMImplementation.h"
35 #include "DocLoader.h"
36 #include "DocumentFragment.h"
37 #include "DocumentLoader.h"
38 #include "DocumentType.h"
39 #include "EditingText.h"
41 #include "EditorClient.h"
42 #include "EntityReference.h"
44 #include "EventHandler.h"
45 #include "EventListener.h"
46 #include "EventNames.h"
47 #include "ExceptionCode.h"
49 #include "FrameLoader.h"
50 #include "FrameTree.h"
51 #include "FrameView.h"
52 #include "HitTestRequest.h"
53 #include "HitTestResult.h"
54 #include "HTMLBodyElement.h"
55 #include "HTMLDocument.h"
56 #include "HTMLElementFactory.h"
57 #include "HTMLImageLoader.h"
58 #include "HTMLInputElement.h"
59 #include "HTMLLinkElement.h"
60 #include "HTMLMapElement.h"
61 #include "HTMLNameCollection.h"
62 #include "HTMLNames.h"
63 #include "HTMLStyleElement.h"
64 #include "HTTPParsers.h"
66 #include "KeyboardEvent.h"
68 #include "MouseEvent.h"
69 #include "MouseEventWithHitTestResults.h"
70 #include "MutationEvent.h"
71 #include "NameNodeList.h"
72 #include "NodeFilter.h"
73 #include "NodeIterator.h"
74 #include "PlatformKeyboardEvent.h"
75 #include "ProcessingInstruction.h"
76 #include "RegisteredEventListener.h"
77 #include "RegularExpression.h"
78 #include "RenderArena.h"
79 #include "RenderView.h"
80 #include "RenderWidget.h"
81 #include "SegmentedString.h"
82 #include "SelectionController.h"
83 #include "StringHash.h"
84 #include "StyleSheetList.h"
85 #include "SystemTime.h"
86 #include "TextIterator.h"
87 #include "TextResourceDecoder.h"
88 #include "TreeWalker.h"
90 #include "XMLTokenizer.h"
91 #include "csshelper.h"
92 #include "cssstyleselector.h"
93 #include "kjs_binding.h"
94 #include "kjs_proxy.h"
95 #include "xmlhttprequest.h"
98 #include "XPathEvaluator.h"
99 #include "XPathExpression.h"
100 #include "XPathNSResolver.h"
101 #include "XPathResult.h"
105 #include "XSLTProcessor.h"
109 #include "XBLBindingManager.h"
113 #include "SVGDocumentExtensions.h"
114 #include "SVGElementFactory.h"
115 #include "SVGZoomEvent.h"
116 #include "SVGStyleElement.h"
117 #include "KSVGTimeScheduler.h"
124 using namespace EventNames;
125 using namespace HTMLNames;
127 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
129 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
130 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
132 const int cLayoutScheduleThreshold = 250;
134 // Use 1 to represent the document's default form.
135 HTMLFormElement* const defaultForm = (HTMLFormElement*) 1;
137 // Golden ratio - arbitrary start value to avoid mapping all 0's to all 0's
138 static const unsigned PHI = 0x9e3779b9U;
140 // DOM Level 2 says (letters added):
142 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
143 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
144 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
145 // 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.
146 // 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.
147 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
148 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
149 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
150 // i) Characters ':' and '_' are allowed as name-start characters.
151 // j) Characters '-' and '.' are allowed as name characters.
153 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
155 static inline bool isValidNameStart(UChar32 c)
158 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
162 if (c == ':' || c == '_')
165 // rules (a) and (f) above
166 const uint32_t nameStartMask = WTF::Unicode::Letter_Lowercase |
167 WTF::Unicode::Letter_Uppercase |
168 WTF::Unicode::Letter_Other |
169 WTF::Unicode::Letter_Titlecase |
170 WTF::Unicode::Number_Letter;
171 if (!(WTF::Unicode::category(c) & nameStartMask))
175 if (c >= 0xF900 && c < 0xFFFE)
179 WTF::Unicode::DecompositionType decompType = WTF::Unicode::decompositionType(c);
180 if (decompType == WTF::Unicode::DecompositionFont || decompType == WTF::Unicode::DecompositionCompat)
186 static inline bool isValidNamePart(UChar32 c)
188 // rules (a), (e), and (i) above
189 if (isValidNameStart(c))
192 // rules (g) and (h) above
193 if (c == 0x00B7 || c == 0x0387)
197 if (c == '-' || c == '.')
200 // rules (b) and (f) above
201 const uint32_t otherNamePartMask = WTF::Unicode::Mark_NonSpacing |
202 WTF::Unicode::Mark_Enclosing |
203 WTF::Unicode::Mark_SpacingCombining |
204 WTF::Unicode::Letter_Modifier |
205 WTF::Unicode::Number_DecimalDigit;
206 if (!(WTF::Unicode::category(c) & otherNamePartMask))
210 if (c >= 0xF900 && c < 0xFFFE)
214 WTF::Unicode::DecompositionType decompType = WTF::Unicode::decompositionType(c);
215 if (decompType == WTF::Unicode::DecompositionFont || decompType == WTF::Unicode::DecompositionCompat)
221 DeprecatedPtrList<Document> * Document::changedDocuments = 0;
223 // FrameView might be 0
224 Document::Document(DOMImplementation* impl, FrameView *v)
226 , m_implementation(impl)
227 , m_domtree_version(0)
228 , m_styleSheets(new StyleSheetList)
230 , m_titleSetExplicitly(false)
231 , m_imageLoadEventTimer(this, &Document::imageLoadEventTimerFired)
233 , m_transformSource(0)
235 , m_xmlVersion("1.0")
236 , m_xmlStandalone(false)
238 , m_bindingManager(new XBLBindingManager(this))
241 , m_passwordFields(0)
243 , m_designMode(inherit)
244 , m_selfOnlyRefCount(0)
249 , m_hasDashboardRegions(false)
250 , m_dashboardRegionsDirty(false)
252 , m_accessKeyMapValid(false)
253 , m_createRenderers(true)
254 , m_inPageCache(false)
256 m_document.resetSkippingRef(this);
265 m_docLoader = new DocLoader(v ? v->frame() : 0, this);
267 visuallyOrdered = false;
268 m_loadingSheet = false;
270 m_docChanged = false;
272 m_wellFormed = false;
276 m_textColor = Color::black;
279 m_styleSelectorDirty = false;
280 m_inStyleRecalc = false;
281 m_closeAfterStyleRecalc = false;
282 m_usesDescendantRules = false;
283 m_usesSiblingRules = false;
285 m_styleSelector = new CSSStyleSelector(this, m_usersheet, m_styleSheets.get(), !inCompatMode());
286 m_pendingStylesheets = 0;
287 m_ignorePendingStylesheets = false;
288 m_pendingSheetLayout = NoLayoutWithPendingSheets;
293 resetVisitedLinkColor();
294 resetActiveLinkColor();
296 m_processingLoadEvent = false;
297 m_startTime = currentTime();
298 m_overMinimumLayoutThreshold = false;
302 static int docID = 0;
306 void Document::removedLastRef()
308 if (m_selfOnlyRefCount) {
309 // if removing a child removes the last self-only ref, we don't
310 // want the document to be destructed until after
311 // removeAllChildren returns, so we guard ourselves with an
312 // extra self-only ref
314 DocPtr<Document> guard(this);
316 // we must make sure not to be retaining any of our children through
317 // these extra pointers or we will create a reference cycle
323 m_documentElement = 0;
327 deleteAllValues(m_markers);
336 Document::~Document()
339 assert(!m_inPageCache);
340 assert(m_savedRenderer == 0);
343 delete m_svgExtensions;
346 XMLHttpRequest::detachRequests(this);
347 KJS::ScriptInterpreter::forgetAllDOMNodesForDocument(this);
349 if (m_docChanged && changedDocuments)
350 changedDocuments->remove(this);
352 m_document.resetSkippingRef(0);
353 delete m_styleSelector;
357 delete m_renderArena;
362 xmlFreeDoc((xmlDocPtr)m_transformSource);
366 delete m_bindingManager;
369 deleteAllValues(m_markers);
371 if (m_axObjectCache) {
372 delete m_axObjectCache;
382 deleteAllValues(m_selectedRadioButtons);
385 void Document::resetLinkColor()
387 m_linkColor = Color(0, 0, 238);
390 void Document::resetVisitedLinkColor()
392 m_visitedLinkColor = Color(85, 26, 139);
395 void Document::resetActiveLinkColor()
397 m_activeLinkColor.setNamedColor("red");
400 void Document::setDocType(PassRefPtr<DocumentType> docType)
405 DocumentType *Document::doctype() const
407 return m_docType.get();
410 DOMImplementation* Document::implementation() const
412 return m_implementation.get();
415 void Document::childrenChanged()
417 // invalidate the document element we have cached in case it was replaced
418 m_documentElement = 0;
421 Element* Document::documentElement() const
423 if (!m_documentElement) {
424 Node* n = firstChild();
425 while (n && !n->isElementNode())
426 n = n->nextSibling();
427 m_documentElement = static_cast<Element*>(n);
430 return m_documentElement.get();
433 PassRefPtr<Element> Document::createElement(const String &name, ExceptionCode& ec)
435 return createElementNS(nullAtom, name, ec);
438 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
440 return new DocumentFragment(document());
443 PassRefPtr<Text> Document::createTextNode(const String &data)
445 return new Text(this, data);
448 PassRefPtr<Comment> Document::createComment (const String &data)
450 return new Comment(this, data);
453 PassRefPtr<CDATASection> Document::createCDATASection(const String &data, ExceptionCode& ec)
455 if (isHTMLDocument()) {
456 ec = NOT_SUPPORTED_ERR;
459 return new CDATASection(this, data);
462 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String &target, const String &data, ExceptionCode& ec)
464 if (!isValidName(target)) {
465 ec = INVALID_CHARACTER_ERR;
468 if (isHTMLDocument()) {
469 ec = NOT_SUPPORTED_ERR;
472 return new ProcessingInstruction(this, target, data);
475 PassRefPtr<EntityReference> Document::createEntityReference(const String &name, ExceptionCode& ec)
477 if (!isValidName(name)) {
478 ec = INVALID_CHARACTER_ERR;
481 if (isHTMLDocument()) {
482 ec = NOT_SUPPORTED_ERR;
485 return new EntityReference(this, name);
488 PassRefPtr<EditingText> Document::createEditingTextNode(const String &text)
490 return new EditingText(this, text);
493 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
495 return new CSSMutableStyleDeclaration;
498 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
503 ec = NOT_SUPPORTED_ERR;
507 switch (importedNode->nodeType()) {
509 return createTextNode(importedNode->nodeValue());
510 case CDATA_SECTION_NODE:
511 return createCDATASection(importedNode->nodeValue(), ec);
512 case ENTITY_REFERENCE_NODE:
513 return createEntityReference(importedNode->nodeName(), ec);
514 case PROCESSING_INSTRUCTION_NODE:
515 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
517 return createComment(importedNode->nodeValue());
519 Element *oldElement = static_cast<Element *>(importedNode);
520 RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
525 NamedAttrMap* attrs = oldElement->attributes(true);
527 unsigned length = attrs->length();
528 for (unsigned i = 0; i < length; i++) {
529 Attribute* attr = attrs->attributeItem(i);
530 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
536 newElement->copyNonAttributeProperties(oldElement);
539 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
540 RefPtr<Node> newChild = importNode(oldChild, true, ec);
543 newElement->appendChild(newChild.release(), ec);
549 return newElement.release();
554 case DOCUMENT_TYPE_NODE:
555 case DOCUMENT_FRAGMENT_NODE:
557 case XPATH_NAMESPACE_NODE:
561 ec = NOT_SUPPORTED_ERR;
566 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
569 ec = NOT_SUPPORTED_ERR;
573 switch (source->nodeType()) {
577 case DOCUMENT_TYPE_NODE:
578 case XPATH_NAMESPACE_NODE:
579 ec = NOT_SUPPORTED_ERR;
581 case ATTRIBUTE_NODE: {
582 Attr* attr = static_cast<Attr*>(source.get());
583 if (attr->ownerElement())
584 attr->ownerElement()->removeAttributeNode(attr, ec);
585 attr->m_specified = true;
589 if (source->parentNode())
590 source->parentNode()->removeChild(source.get(), ec);
593 for (Node* node = source.get(); node; node = node->traverseNextNode(source.get())) {
594 KJS::ScriptInterpreter::updateDOMNodeDocument(node, node->document(), this);
595 node->setDocument(this);
601 PassRefPtr<Element> Document::createElementNS(const String &_namespaceURI, const String &qualifiedName, ExceptionCode& ec)
603 // FIXME: We'd like a faster code path that skips this check for calls from inside the engine where the name is known to be valid.
604 String prefix, localName;
605 if (!parseQualifiedName(qualifiedName, prefix, localName)) {
606 ec = INVALID_CHARACTER_ERR;
611 QualifiedName qName = QualifiedName(AtomicString(prefix), AtomicString(localName), AtomicString(_namespaceURI));
613 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
614 if (_namespaceURI == xhtmlNamespaceURI) {
615 e = HTMLElementFactory::createHTMLElement(qName.localName(), this, 0, false);
616 if (e && !prefix.isNull()) {
617 e->setPrefix(qName.prefix(), ec);
623 else if (_namespaceURI == SVGNames::svgNamespaceURI)
624 e = SVGElementFactory::createSVGElement(qName, this, false);
628 e = new Element(qName, document());
633 Element *Document::getElementById(const AtomicString& elementId) const
635 if (elementId.length() == 0)
638 Element *element = m_elementsById.get(elementId.impl());
642 if (m_duplicateIds.contains(elementId.impl())) {
643 for (Node *n = traverseNextNode(); n != 0; n = n->traverseNextNode()) {
644 if (n->isElementNode()) {
645 element = static_cast<Element*>(n);
646 if (element->hasID() && element->getAttribute(idAttr) == elementId) {
647 m_duplicateIds.remove(elementId.impl());
648 m_elementsById.set(elementId.impl(), element);
657 String Document::readyState() const
659 if (Frame* f = frame()) {
660 if (f->loader()->isComplete())
665 // FIXME: What does "interactive" mean?
666 // FIXME: Missing support for "uninitialized".
671 String Document::inputEncoding() const
673 if (TextResourceDecoder* d = decoder())
674 return d->encoding().name();
678 String Document::defaultCharset() const
680 if (Frame* f = frame())
681 return f->settings()->encoding();
685 void Document::setCharset(const String& charset)
689 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
692 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
694 // FIXME: also raise NOT_SUPPORTED_ERR if the version is set to a value that is not supported by this Document.
695 if (!implementation()->hasFeature("XML", String())) {
696 ec = NOT_SUPPORTED_ERR;
700 m_xmlVersion = version;
703 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
705 if (!implementation()->hasFeature("XML", String())) {
706 ec = NOT_SUPPORTED_ERR;
710 m_xmlStandalone = standalone;
713 Element* Document::elementFromPoint(int x, int y) const
718 HitTestRequest request(true, true);
719 HitTestResult result(IntPoint(x, y));
720 renderer()->layer()->hitTest(request, result);
722 Node* n = result.innerNode();
723 while (n && !n->isElementNode())
726 n = n->shadowAncestorNode();
727 return static_cast<Element*>(n);
730 void Document::addElementById(const AtomicString& elementId, Element* element)
732 if (!m_elementsById.contains(elementId.impl()))
733 m_elementsById.set(elementId.impl(), element);
735 m_duplicateIds.add(elementId.impl());
738 void Document::removeElementById(const AtomicString& elementId, Element* element)
740 if (m_elementsById.get(elementId.impl()) == element)
741 m_elementsById.remove(elementId.impl());
743 m_duplicateIds.remove(elementId.impl());
746 Element* Document::getElementByAccessKey(const String& key) const
750 if (!m_accessKeyMapValid) {
751 for (Node* n = firstChild(); n; n = n->traverseNextNode()) {
752 if (!n->isElementNode())
754 Element* element = static_cast<Element*>(n);
755 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
756 if (!accessKey.isEmpty())
757 m_elementsByAccessKey.set(accessKey.impl(), element);
759 m_accessKeyMapValid = true;
761 return m_elementsByAccessKey.get(key.impl());
764 void Document::updateTitle()
766 if (Frame* f = frame())
767 f->loader()->setTitle(m_title);
770 void Document::setTitle(const String& title, Node* titleElement)
773 // Title set by JavaScript -- overrides any title elements.
774 m_titleSetExplicitly = true;
776 } else if (titleElement != m_titleElement) {
778 // Only allow the first title element to change the title -- others have no effect.
780 m_titleElement = titleElement;
783 if (m_title == title)
790 void Document::removeTitle(Node* titleElement)
792 if (m_titleElement != titleElement)
795 // FIXME: Ideally we might want this to search for the first remaining title element, and use it.
798 if (!m_title.isEmpty()) {
804 String Document::nodeName() const
809 Node::NodeType Document::nodeType() const
811 return DOCUMENT_NODE;
814 Frame* Document::frame() const
816 return m_view ? m_view->frame() : 0;
819 PassRefPtr<Range> Document::createRange()
821 return new Range(this);
824 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
825 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
828 ec = NOT_SUPPORTED_ERR;
831 return new NodeIterator(root, whatToShow, filter, expandEntityReferences);
834 PassRefPtr<TreeWalker> Document::createTreeWalker(Node *root, unsigned whatToShow,
835 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
838 ec = NOT_SUPPORTED_ERR;
841 return new TreeWalker(root, whatToShow, filter, expandEntityReferences);
844 void Document::setDocumentChanged(bool b)
848 if (!changedDocuments)
849 changedDocuments = new DeprecatedPtrList<Document>;
850 changedDocuments->append(this);
852 if (m_accessKeyMapValid) {
853 m_accessKeyMapValid = false;
854 m_elementsByAccessKey.clear();
857 if (m_docChanged && changedDocuments)
858 changedDocuments->remove(this);
864 void Document::recalcStyle(StyleChange change)
867 return; // Guard against re-entrancy. -dwh
869 m_inStyleRecalc = true;
871 ASSERT(!renderer() || renderArena());
872 if (!renderer() || !renderArena())
875 if (change == Force) {
876 RenderStyle* oldStyle = renderer()->style();
879 RenderStyle* _style = new (m_renderArena) RenderStyle();
881 _style->setDisplay(BLOCK);
882 _style->setVisuallyOrdered(visuallyOrdered);
883 // ### make the font stuff _really_ work!!!!
885 FontDescription fontDescription;
886 fontDescription.setUsePrinterFont(printing());
888 const Settings *settings = m_view->frame()->settings();
889 if (printing() && !settings->shouldPrintBackgrounds())
890 _style->setForceBackgroundsToWhite(true);
891 const AtomicString& stdfont = settings->stdFontName();
892 if (!stdfont.isEmpty()) {
893 fontDescription.firstFamily().setFamily(stdfont);
894 fontDescription.firstFamily().appendFamily(0);
896 fontDescription.setKeywordSize(CSS_VAL_MEDIUM - CSS_VAL_XX_SMALL + 1);
897 m_styleSelector->setFontSize(fontDescription, m_styleSelector->fontSizeForKeyword(CSS_VAL_MEDIUM, inCompatMode(), false));
900 _style->setFontDescription(fontDescription);
901 _style->font().update();
903 _style->setHtmlHacks(true); // enable html specific rendering tricks
905 StyleChange ch = diff(_style, oldStyle);
906 if (renderer() && ch != NoChange)
907 renderer()->setStyle(_style);
911 _style->deref(m_renderArena);
913 oldStyle->deref(m_renderArena);
916 for (Node* n = fastFirstChild(); n; n = n->nextSibling())
917 if (change >= Inherit || n->hasChangedChild() || n->changed())
918 n->recalcStyle(change);
920 if (changed() && m_view)
925 setHasChangedChild(false);
926 setDocumentChanged(false);
928 m_inStyleRecalc = false;
930 // If we wanted to emit the implicitClose() during recalcStyle, do so now that we're finished.
931 if (m_closeAfterStyleRecalc) {
932 m_closeAfterStyleRecalc = false;
937 void Document::updateRendering()
939 if (hasChangedChild())
940 recalcStyle(NoChange);
943 void Document::updateDocumentsRendering()
945 if (!changedDocuments)
948 while (Document* doc = changedDocuments->take()) {
949 doc->m_docChanged = false;
950 doc->updateRendering();
954 void Document::updateLayout()
956 // FIXME: Dave Hyatt's pretty sure we can remove this because layout calls recalcStyle as needed.
959 // Only do a layout if changes have occurred that make it necessary.
960 if (m_view && renderer() && (m_view->layoutPending() || renderer()->needsLayout()))
964 // FIXME: This is a bad idea and needs to be removed eventually.
965 // Other browsers load stylesheets before they continue parsing the web page.
966 // Since we don't, we can run JavaScript code that needs answers before the
967 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
968 // lets us get reasonable answers. The long term solution to this problem is
969 // to instead suspend JavaScript execution.
970 void Document::updateLayoutIgnorePendingStylesheets()
972 bool oldIgnore = m_ignorePendingStylesheets;
974 if (!haveStylesheetsLoaded()) {
975 m_ignorePendingStylesheets = true;
976 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
977 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
978 // with accurate style information. (Our suppression involves blanking the whole page at the
979 // moment. If it were more refined, we might be able to do something better.)
980 // It's worth noting though that this entire method is a hack, since what we really want to do is
981 // suspend JS instead of doing a layout with inaccurate information.
982 if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets)
983 m_pendingSheetLayout = DidLayoutWithPendingSheets;
984 updateStyleSelector();
989 m_ignorePendingStylesheets = oldIgnore;
992 void Document::attach()
995 assert(!m_inPageCache);
998 m_renderArena = new RenderArena();
1000 // Create the rendering tree
1001 setRenderer(new (m_renderArena) RenderView(this, m_view));
1005 RenderObject* render = renderer();
1008 ContainerNode::attach();
1010 setRenderer(render);
1013 void Document::detach()
1015 RenderObject* render = renderer();
1017 // indicate destruction mode, i.e. attached() but renderer == 0
1020 if (m_inPageCache) {
1022 axObjectCache()->remove(render);
1026 // Empty out these lists as a performance optimization, since detaching
1027 // all the individual render objects will cause all the RenderImage
1028 // objects to remove themselves from the lists.
1029 m_imageLoadEventDispatchSoonList.clear();
1030 m_imageLoadEventDispatchingList.clear();
1036 ContainerNode::detach();
1043 if (m_renderArena) {
1044 delete m_renderArena;
1049 void Document::removeAllEventListenersFromAllNodes()
1051 m_windowEventListeners.clear();
1052 removeAllDisconnectedNodeEventListeners();
1053 for (Node *n = this; n; n = n->traverseNextNode()) {
1054 if (!n->isEventTargetNode())
1056 EventTargetNodeCast(n)->removeAllEventListeners();
1060 void Document::registerDisconnectedNodeWithEventListeners(Node* node)
1062 m_disconnectedNodesWithEventListeners.add(node);
1065 void Document::unregisterDisconnectedNodeWithEventListeners(Node* node)
1067 m_disconnectedNodesWithEventListeners.remove(node);
1070 void Document::removeAllDisconnectedNodeEventListeners()
1072 HashSet<Node*>::iterator end = m_disconnectedNodesWithEventListeners.end();
1073 for (HashSet<Node*>::iterator i = m_disconnectedNodesWithEventListeners.begin(); i != end; ++i)
1074 EventTargetNodeCast(*i)->removeAllEventListeners();
1075 m_disconnectedNodesWithEventListeners.clear();
1078 AXObjectCache* Document::axObjectCache() const
1080 // The only document that actually has a AXObjectCache is the top-level
1081 // document. This is because we need to be able to get from any WebCoreAXObject
1082 // to any other WebCoreAXObject on the same page. Using a single cache allows
1083 // lookups across nested webareas (i.e. multiple documents).
1085 if (m_axObjectCache) {
1086 // return already known top-level cache
1087 if (!ownerElement())
1088 return m_axObjectCache;
1090 // In some pages with frames, the cache is created before the sub-webarea is
1091 // inserted into the tree. Here, we catch that case and just toss the old
1092 // cache and start over.
1093 delete m_axObjectCache;
1094 m_axObjectCache = 0;
1097 // ask the top-level document for its cache
1098 Document* doc = topDocument();
1100 return doc->axObjectCache();
1102 // this is the top-level document, so install a new cache
1103 m_axObjectCache = new AXObjectCache;
1104 return m_axObjectCache;
1107 void Document::setVisuallyOrdered()
1109 visuallyOrdered = true;
1111 renderer()->style()->setVisuallyOrdered(true);
1114 void Document::updateSelection()
1119 RenderView *canvas = static_cast<RenderView*>(renderer());
1120 Selection selection = frame()->selectionController()->selection();
1122 if (!selection.isRange())
1123 canvas->clearSelection();
1125 // Use the rightmost candidate for the start of the selection, and the leftmost candidate for the end of the selection.
1126 // Example: foo <a>bar</a>. Imagine that a line wrap occurs after 'foo', and that 'bar' is selected. If we pass [foo, 3]
1127 // as the start of the selection, the selection painting code will think that content on the line containing 'foo' is selected
1128 // and will fill the gap before 'bar'.
1129 Position startPos = selection.visibleStart().deepEquivalent();
1130 if (startPos.downstream().inRenderedContent())
1131 startPos = startPos.downstream();
1132 Position endPos = selection.visibleEnd().deepEquivalent();
1133 if (endPos.upstream().inRenderedContent())
1134 endPos = endPos.upstream();
1136 // We can get into a state where the selection endpoints map to the same VisiblePosition when a selection is deleted
1137 // because we don't yet notify the SelectionController of text removal.
1138 if (startPos.isNotNull() && endPos.isNotNull() && selection.visibleStart() != selection.visibleEnd()) {
1139 RenderObject *startRenderer = startPos.node()->renderer();
1140 RenderObject *endRenderer = endPos.node()->renderer();
1141 static_cast<RenderView*>(renderer())->setSelection(startRenderer, startPos.offset(), endRenderer, endPos.offset());
1146 // FIXME: We shouldn't post this AX notification here since updateSelection() is called far too often: every time Safari gains
1147 // or loses focus, and once for every low level change to the selection during an editing operation.
1148 // FIXME: We no longer blow away the selection before starting an editing operation, so the isNotNull checks below are no
1149 // longer a correct way to check for user-level selection changes.
1150 if (AXObjectCache::accessibilityEnabled() && selection.start().isNotNull() && selection.end().isNotNull())
1151 axObjectCache()->postNotification(selection.start().node()->renderer(), "AXSelectedTextChanged");
1155 Tokenizer *Document::createTokenizer()
1157 return newXMLTokenizer(this, m_view);
1160 void Document::open()
1162 // This is work that we should probably do in clear(), but we can't have it
1163 // happen when implicitOpen() is called unless we reorganize Frame code.
1164 if (Document *parent = parentDocument()) {
1165 setURL(parent->baseURL());
1166 setBaseURL(parent->baseURL());
1169 setURL(DeprecatedString());
1172 if ((frame() && frame()->loader()->isLoadingMainResource()) || (tokenizer() && tokenizer()->executingScript()))
1178 frame()->loader()->didExplicitOpen();
1181 void Document::cancelParsing()
1184 // We have to clear the tokenizer to avoid possibly triggering
1185 // the onload handler when closing as a side effect of a cancel-style
1186 // change, such as opening a new document or closing the window while
1194 void Document::implicitOpen()
1199 m_tokenizer = createTokenizer();
1203 HTMLElement* Document::body()
1205 Node *de = documentElement();
1209 // try to prefer a FRAMESET element over BODY
1211 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
1212 if (i->hasTagName(framesetTag))
1213 return static_cast<HTMLElement*>(i);
1215 if (i->hasTagName(bodyTag))
1218 return static_cast<HTMLElement *>(body);
1221 void Document::close()
1224 frame()->loader()->endIfNotLoading();
1228 void Document::implicitClose()
1230 // 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.
1231 if (m_inStyleRecalc) {
1232 m_closeAfterStyleRecalc = true;
1236 bool wasLocationChangePending = frame() && frame()->loader()->isScheduledLocationChangePending();
1237 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1242 m_processingLoadEvent = true;
1244 m_wellFormed = m_tokenizer && m_tokenizer->wellFormed();
1246 // We have to clear the tokenizer, in case someone document.write()s from the
1247 // onLoad event handler, as in Radar 3206524.
1251 // Create a body element if we don't already have one.
1252 // In the case of Radar 3758785, the window.onload was set in some javascript, but never fired because there was no body.
1253 // This behavior now matches Firefox and IE.
1254 HTMLElement *body = this->body();
1255 if (!body && isHTMLDocument()) {
1256 Node *de = documentElement();
1258 body = new HTMLBodyElement(this);
1259 ExceptionCode ec = 0;
1260 de->appendChild(body, ec);
1266 dispatchImageLoadEventsNow();
1267 this->dispatchWindowEvent(loadEvent, false, false);
1268 if (Frame* f = frame())
1269 f->loader()->handledOnloadEvents();
1270 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1271 if (!ownerElement())
1272 printf("onload fired at %d\n", elapsedTime());
1275 m_processingLoadEvent = false;
1277 // Make sure both the initial layout and reflow happen after the onload
1278 // fires. This will improve onload scores, and other browsers do it.
1279 // If they wanna cheat, we can too. -dwh
1281 if (frame() && frame()->loader()->isScheduledLocationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
1282 // Just bail out. Before or during the onload we were shifted to another page.
1283 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1284 view()->unscheduleRelayout();
1289 frame()->loader()->checkEmitLoadEvent();
1291 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1292 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1293 // layout/painting now would be pointless.
1294 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1297 // Always do a layout after loading if needed.
1298 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1303 if (renderer() && AXObjectCache::accessibilityEnabled())
1304 axObjectCache()->postNotificationToElement(renderer(), "AXLoadComplete");
1308 // FIXME: Officially, time 0 is when the outermost <svg> receives its
1309 // SVGLoad event, but we don't implement those yet. This is close enough
1310 // for now. In some cases we should have fired earlier.
1311 if (svgExtensions())
1312 accessSVGExtensions()->startAnimations();
1316 void Document::setParsing(bool b)
1319 if (!m_bParsing && view())
1320 view()->scheduleRelayout();
1322 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1323 if (!ownerElement() && !m_bParsing)
1324 printf("Parsing finished at %d\n", elapsedTime());
1328 bool Document::shouldScheduleLayout()
1330 // We can update layout if:
1331 // (a) we actually need a layout
1332 // (b) our stylesheets are all loaded
1333 // (c) we have a <body>
1334 return (renderer() && renderer()->needsLayout() && haveStylesheetsLoaded() &&
1335 documentElement() && documentElement()->renderer() &&
1336 (!documentElement()->hasTagName(htmlTag) || body()));
1339 int Document::minimumLayoutDelay()
1341 if (m_overMinimumLayoutThreshold)
1344 int elapsed = elapsedTime();
1345 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1347 // We'll want to schedule the timer to fire at the minimum layout threshold.
1348 return max(0, cLayoutScheduleThreshold - elapsed);
1351 int Document::elapsedTime() const
1353 return static_cast<int>((currentTime() - m_startTime) * 1000);
1356 void Document::write(const DeprecatedString& text)
1358 write(String(text));
1361 void Document::write(const String& text)
1363 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1364 if (!ownerElement())
1365 printf("Beginning a document.write at %d\n", elapsedTime());
1370 assert(m_tokenizer);
1373 write(DeprecatedString("<html>"));
1375 m_tokenizer->write(text, false);
1377 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1378 if (!ownerElement())
1379 printf("Ending a document.write at %d\n", elapsedTime());
1383 void Document::writeln(const String &text)
1386 write(String("\n"));
1389 void Document::finishParsing()
1391 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1392 if (!ownerElement())
1393 printf("Received all data at %d\n", elapsedTime());
1396 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1397 // finish() is called:
1398 // (1) All remaining data is parsed, document isn't loaded yet
1399 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1400 // (3) Data is still remaining to be parsed.
1402 m_tokenizer->finish();
1405 void Document::clear()
1412 m_windowEventListeners.clear();
1415 void Document::setURL(const DeprecatedString& url)
1418 if (m_styleSelector)
1419 m_styleSelector->setEncodedURL(m_url);
1422 void Document::setCSSStyleSheet(const String &url, const String& charset, const String &sheet)
1424 m_sheet = new CSSStyleSheet(this, url, charset);
1425 m_sheet->parseString(sheet);
1426 m_loadingSheet = false;
1428 updateStyleSelector();
1431 void Document::setUserStyleSheet(const String& sheet)
1433 if (m_usersheet != sheet) {
1434 m_usersheet = sheet;
1435 updateStyleSelector();
1439 CSSStyleSheet* Document::elementSheet()
1442 m_elemSheet = new CSSStyleSheet(this, baseURL());
1443 return m_elemSheet.get();
1446 void Document::determineParseMode(const String&)
1448 // For XML documents use strict parse mode.
1449 // HTML overrides this method to determine the parse mode.
1454 Node* Document::nextFocusedNode(Node* fromNode, KeyboardEvent* event)
1456 unsigned short fromTabIndex;
1459 // No starting node supplied; begin with the top of the document
1461 int lowestTabIndex = 65535;
1462 for (Node* n = this; n; n = n->traverseNextNode())
1463 if (n->isKeyboardFocusable(event) && n->tabIndex() > 0 && n->tabIndex() < lowestTabIndex)
1464 lowestTabIndex = n->tabIndex();
1466 if (lowestTabIndex == 65535)
1469 // Go to the first node in the document that has the desired tab index
1470 for (Node* n = this; n; n = n->traverseNextNode())
1471 if (n->isKeyboardFocusable(event) && n->tabIndex() == lowestTabIndex)
1477 fromTabIndex = fromNode->tabIndex();
1479 if (fromTabIndex == 0) {
1480 // Just need to find the next selectable node after fromNode (in document order) that has a tab index of 0
1482 for (n = fromNode->traverseNextNode(); n; n = n->traverseNextNode())
1483 if (n->isKeyboardFocusable(event) && n->tabIndex() == 0)
1489 // Find the lowest tab index out of all the nodes except fromNode, that is greater than or equal to fromNode's
1490 // tab index. For nodes with the same tab index as fromNode, we are only interested in those that come after
1491 // fromNode in document order.
1492 // If we don't find a suitable tab index, the next focus node will be one with a tab index of 0.
1493 unsigned short lowestSuitableTabIndex = 65535;
1495 bool reachedFromNode = false;
1496 for (Node* n = this; n; n = n->traverseNextNode()) {
1498 reachedFromNode = true;
1499 else if (n->isKeyboardFocusable(event)
1500 && ((reachedFromNode && n->tabIndex() >= fromTabIndex)
1501 || (!reachedFromNode && n->tabIndex() > fromTabIndex)))
1502 // We found a selectable node with a tab index at least as high as fromNode's. Keep searching though,
1503 // as there may be another node which has a lower tab index but is still suitable for use.
1504 lowestSuitableTabIndex = min(lowestSuitableTabIndex, n->tabIndex());
1507 if (lowestSuitableTabIndex == 65535) {
1508 // No next node with a tab index -> just take first node with tab index of 0
1510 for (n = this; n; n = n->traverseNextNode())
1511 if (n->isKeyboardFocusable(event) && n->tabIndex() == 0)
1517 // Search forwards from fromNode
1518 for (Node* n = fromNode->traverseNextNode(); n; n = n->traverseNextNode())
1519 if (n->isKeyboardFocusable(event) && n->tabIndex() == lowestSuitableTabIndex)
1522 // The next node isn't after fromNode, start from the beginning of the document
1523 for (Node* n = this; n != fromNode; n = n->traverseNextNode())
1524 if (n->isKeyboardFocusable(event) && n->tabIndex() == lowestSuitableTabIndex)
1527 ASSERT_NOT_REACHED();
1531 Node* Document::previousFocusedNode(Node* fromNode, KeyboardEvent* event)
1534 for (lastNode = this; lastNode->lastChild(); lastNode = lastNode->lastChild());
1537 // No starting node supplied; begin with the very last node in the document
1539 int highestTabIndex = 0;
1540 for (Node* n = lastNode; n; n = n->traversePreviousNode()) {
1541 if (n->isKeyboardFocusable(event)) {
1542 if (n->tabIndex() == 0)
1544 else if (n->tabIndex() > highestTabIndex)
1545 highestTabIndex = n->tabIndex();
1549 // No node with a tab index of 0; just go to the last node with the highest tab index
1550 for (Node* n = lastNode; n; n = n->traversePreviousNode())
1551 if (n->isKeyboardFocusable(event) && n->tabIndex() == highestTabIndex)
1557 unsigned short fromTabIndex = fromNode->tabIndex();
1559 if (fromTabIndex == 0) {
1560 // Find the previous selectable node before fromNode (in document order) that has a tab index of 0
1562 for (n = fromNode->traversePreviousNode(); n; n = n->traversePreviousNode())
1563 if (n->isKeyboardFocusable(event) && n->tabIndex() == 0)
1569 // No previous nodes with a 0 tab index, go to the last node in the document that has the highest tab index
1570 int highestTabIndex = 0;
1571 for (n = this; n; n = n->traverseNextNode())
1572 if (n->isKeyboardFocusable(event) && n->tabIndex() > highestTabIndex)
1573 highestTabIndex = n->tabIndex();
1575 if (!highestTabIndex)
1578 for (n = lastNode; n; n = n->traversePreviousNode())
1579 if (n->isKeyboardFocusable(event) && n->tabIndex() == highestTabIndex)
1582 ASSERT_NOT_REACHED();
1586 // Find the lowest tab index out of all the nodes except fromNode, that is less than or equal to fromNode's
1587 // tab index. For nodes with the same tab index as fromNode, we are only interested in those before
1589 // If we don't find a suitable tab index, then there will be no previous focus node.
1590 unsigned short highestSuitableTabIndex = 0;
1592 bool reachedFromNode = false;
1593 for (Node* n = this; n; n = n->traverseNextNode()) {
1594 if (n->isKeyboardFocusable(event) &&
1595 ((!reachedFromNode && (n->tabIndex() <= fromTabIndex)) ||
1596 (reachedFromNode && (n->tabIndex() < fromTabIndex))) &&
1597 (n->tabIndex() > highestSuitableTabIndex) &&
1600 // We found a selectable node with a tab index no higher than fromNode's. Keep searching though, as
1601 // there may be another node which has a higher tab index but is still suitable for use.
1602 highestSuitableTabIndex = n->tabIndex();
1606 reachedFromNode = true;
1609 if (highestSuitableTabIndex == 0)
1610 // No previous node with a tab index. Since the order specified by HTML is nodes with tab index > 0
1611 // first, this means that there is no previous node.
1614 // Search backwards from fromNode
1615 for (Node* n = fromNode->traversePreviousNode(); n; n = n->traversePreviousNode())
1616 if (n->isKeyboardFocusable(event) && (n->tabIndex() == highestSuitableTabIndex))
1619 // The previous node isn't before fromNode, start from the end of the document
1620 for (Node* n = lastNode; n != fromNode; n = n->traversePreviousNode())
1621 if (n->isKeyboardFocusable(event) && (n->tabIndex() == highestSuitableTabIndex))
1624 ASSERT_NOT_REACHED();
1628 int Document::nodeAbsIndex(Node *node)
1630 assert(node->document() == this);
1633 for (Node *n = node; n && n != this; n = n->traversePreviousNode())
1638 Node *Document::nodeWithAbsIndex(int absIndex)
1641 for (int i = 0; n && (i < absIndex); i++) {
1642 n = n->traverseNextNode();
1647 void Document::processHttpEquiv(const String &equiv, const String &content)
1649 assert(!equiv.isNull() && !content.isNull());
1651 Frame *frame = this->frame();
1653 if (equalIgnoringCase(equiv, "default-style")) {
1654 // The preferred style set has been overridden as per section
1655 // 14.3.2 of the HTML4.0 specification. We need to update the
1656 // sheet used variable and then update our style selector.
1657 // For more info, see the test at:
1658 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1660 m_selectedStylesheetSet = content;
1661 m_preferredStylesheetSet = content;
1662 updateStyleSelector();
1663 } else if (equalIgnoringCase(equiv, "refresh")) {
1666 if (frame && parseHTTPRefresh(content, delay, url)) {
1668 frame->loader()->scheduleRedirection(delay, frame->loader()->url().url(), delay <= 1);
1670 // We want a new history item if the refresh timeout > 1 second
1671 frame->loader()->scheduleRedirection(delay, completeURL(url), delay <= 1);
1673 } else if (equalIgnoringCase(equiv, "expires")) {
1674 String str = content.stripWhiteSpace();
1675 time_t expire_date = str.toInt();
1676 m_docLoader->setExpireDate(expire_date);
1677 } else if (equalIgnoringCase(equiv, "set-cookie")) {
1678 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
1679 if (isHTMLDocument())
1680 static_cast<HTMLDocument*>(this)->setCookie(content);
1684 MouseEventWithHitTestResults Document::prepareMouseEvent(bool readonly, bool active, bool mouseMove,
1685 const IntPoint& point, const PlatformMouseEvent& event)
1688 return MouseEventWithHitTestResults(event, 0, 0, false);
1690 assert(renderer()->isRenderView());
1691 HitTestRequest request(readonly, active, mouseMove);
1692 HitTestResult result(point);
1693 renderer()->layer()->hitTest(request, result);
1698 bool isOverLink = result.URLElement() && !result.URLElement()->getAttribute(hrefAttr).isNull();
1699 return MouseEventWithHitTestResults(event, result.innerNode(), result.scrollbar(), isOverLink);
1702 // DOM Section 1.1.1
1703 bool Document::childTypeAllowed(NodeType type)
1706 case ATTRIBUTE_NODE:
1707 case CDATA_SECTION_NODE:
1708 case DOCUMENT_FRAGMENT_NODE:
1711 case ENTITY_REFERENCE_NODE:
1714 case XPATH_NAMESPACE_NODE:
1717 case PROCESSING_INSTRUCTION_NODE:
1719 case DOCUMENT_TYPE_NODE:
1721 // Documents may contain no more than one of each of these.
1722 // (One Element and one DocumentType.)
1723 for (Node* c = firstChild(); c; c = c->nextSibling())
1724 if (c->nodeType() == type)
1731 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
1733 // Spec says cloning Document nodes is "implementation dependent"
1734 // so we do not support it...
1738 StyleSheetList* Document::styleSheets()
1740 return m_styleSheets.get();
1743 String Document::preferredStylesheetSet() const
1745 return m_preferredStylesheetSet;
1748 String Document::selectedStylesheetSet() const
1750 return m_selectedStylesheetSet;
1753 void Document::setSelectedStylesheetSet(const String& aString)
1755 m_selectedStylesheetSet = aString;
1756 updateStyleSelector();
1758 renderer()->repaint();
1761 // This method is called whenever a top-level stylesheet has finished loading.
1762 void Document::stylesheetLoaded()
1764 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
1765 assert(m_pendingStylesheets > 0);
1767 m_pendingStylesheets--;
1769 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1770 if (!ownerElement())
1771 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
1774 updateStyleSelector();
1777 void Document::updateStyleSelector()
1779 // Don't bother updating, since we haven't loaded all our style info yet.
1780 if (!haveStylesheetsLoaded())
1783 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
1784 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
1786 renderer()->repaint();
1789 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1790 if (!ownerElement())
1791 printf("Beginning update of style selector at time %d.\n", elapsedTime());
1794 recalcStyleSelector();
1797 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1798 if (!ownerElement())
1799 printf("Finished update of style selector at time %d\n", elapsedTime());
1803 renderer()->setNeedsLayoutAndMinMaxRecalc();
1805 view()->scheduleRelayout();
1809 void Document::recalcStyleSelector()
1811 if (!renderer() || !attached())
1814 DeprecatedPtrList<StyleSheet> oldStyleSheets = m_styleSheets->styleSheets;
1815 m_styleSheets->styleSheets.clear();
1817 for (n = this; n; n = n->traverseNextNode()) {
1818 StyleSheet *sheet = 0;
1820 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE)
1822 // Processing instruction (XML documents only)
1823 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
1824 sheet = pi->sheet();
1826 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
1827 if (pi->isXSL() && !transformSourceDocument()) {
1828 // Don't apply XSL transforms until loading is finished.
1830 applyXSLTransform(pi);
1834 if (!sheet && !pi->localHref().isEmpty())
1836 // Processing instruction with reference to an element in this document - e.g.
1837 // <?xml-stylesheet href="#mystyle">, with the element
1838 // <foo id="mystyle">heading { color: red; }</foo> at some location in
1840 Element* elem = getElementById(pi->localHref().impl());
1842 String sheetText("");
1844 for (c = elem->firstChild(); c; c = c->nextSibling()) {
1845 if (c->nodeType() == TEXT_NODE || c->nodeType() == CDATA_SECTION_NODE)
1846 sheetText += c->nodeValue();
1849 CSSStyleSheet *cssSheet = new CSSStyleSheet(this);
1850 cssSheet->parseString(sheetText);
1851 pi->setCSSStyleSheet(cssSheet);
1856 } else if (n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))
1858 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
1861 Element* e = static_cast<Element*>(n);
1862 DeprecatedString title = e->getAttribute(titleAttr).deprecatedString();
1863 bool enabledViaScript = false;
1864 if (e->hasLocalName(linkTag)) {
1866 HTMLLinkElement* l = static_cast<HTMLLinkElement*>(n);
1867 if (l->isLoading() || l->isDisabled())
1870 title = DeprecatedString::null;
1871 enabledViaScript = l->isEnabledViaScript();
1874 // Get the current preferred styleset. This is the
1875 // set of sheets that will be enabled.
1877 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
1878 sheet = static_cast<SVGStyleElement*>(n)->sheet();
1881 if (e->hasLocalName(linkTag))
1882 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
1885 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
1887 // Check to see if this sheet belongs to a styleset
1888 // (thus making it PREFERRED or ALTERNATE rather than
1890 if (!enabledViaScript && !title.isEmpty()) {
1891 // Yes, we have a title.
1892 if (m_preferredStylesheetSet.isEmpty()) {
1893 // No preferred set has been established. If
1894 // we are NOT an alternate sheet, then establish
1895 // us as the preferred set. Otherwise, just ignore
1897 DeprecatedString rel = e->getAttribute(relAttr).deprecatedString();
1898 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
1899 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
1902 if (title != m_preferredStylesheetSet)
1906 if (!n->isHTMLElement())
1907 title = title.replace('&', "&&");
1914 m_styleSheets->styleSheets.append(sheet);
1917 // For HTML documents, stylesheets are not allowed within/after the <BODY> tag. So we
1918 // can stop searching here.
1919 if (isHTMLDocument() && n->hasTagName(bodyTag))
1923 // De-reference all the stylesheets in the old list
1924 DeprecatedPtrListIterator<StyleSheet> it(oldStyleSheets);
1925 for (; it.current(); ++it)
1926 it.current()->deref();
1928 // Create a new style selector
1929 delete m_styleSelector;
1930 String usersheet = m_usersheet;
1931 if (m_view && m_view->mediaType() == "print")
1932 usersheet += m_printSheet;
1933 m_styleSelector = new CSSStyleSelector(this, usersheet, m_styleSheets.get(), !inCompatMode());
1934 m_styleSelector->setEncodedURL(m_url);
1935 m_styleSelectorDirty = false;
1938 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
1940 m_hoverNode = newHoverNode;
1943 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
1945 m_activeNode = newActiveNode;
1948 void Document::hoveredNodeDetached(Node* node)
1950 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parent())))
1953 m_hoverNode = node->parent();
1954 while (m_hoverNode && !m_hoverNode->renderer())
1955 m_hoverNode = m_hoverNode->parent();
1957 frame()->eventHandler()->scheduleHoverStateUpdate();
1960 void Document::activeChainNodeDetached(Node* node)
1962 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parent())))
1965 m_activeNode = node->parent();
1966 while (m_activeNode && !m_activeNode->renderer())
1967 m_activeNode = m_activeNode->parent();
1970 bool Document::relinquishesEditingFocus(Node *node)
1973 assert(node->isContentEditable());
1975 Node *root = node->rootEditableElement();
1976 if (!frame() || !root)
1979 return frame()->editor()->shouldEndEditing(rangeOfContents(root).get());
1982 bool Document::acceptsEditingFocus(Node *node)
1985 assert(node->isContentEditable());
1987 Node *root = node->rootEditableElement();
1988 if (!frame() || !root)
1991 return frame()->editor()->shouldBeginEditing(rangeOfContents(root).get());
1995 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
1997 return m_dashboardRegions;
2000 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
2002 m_dashboardRegions = regions;
2003 setDashboardRegionsDirty(false);
2007 static Widget *widgetForNode(Node *focusedNode)
2011 RenderObject *renderer = focusedNode->renderer();
2012 if (!renderer || !renderer->isWidget())
2014 return static_cast<RenderWidget*>(renderer)->widget();
2017 bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
2019 // Make sure newFocusedNode is actually in this document
2020 if (newFocusedNode && (newFocusedNode->document() != this))
2023 if (m_focusedNode == newFocusedNode)
2026 if (m_focusedNode && m_focusedNode.get() == m_focusedNode->rootEditableElement() && !relinquishesEditingFocus(m_focusedNode.get()))
2029 bool focusChangeBlocked = false;
2030 RefPtr<Node> oldFocusedNode = m_focusedNode;
2032 clearSelectionIfNeeded(newFocusedNode.get());
2034 // Remove focus from the existing focus node (if any)
2035 if (oldFocusedNode && !oldFocusedNode->m_inDetach) {
2036 if (oldFocusedNode->active())
2037 oldFocusedNode->setActive(false);
2039 oldFocusedNode->setFocus(false);
2041 // Dispatch a change event for text fields or textareas that have been edited
2042 RenderObject *r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer());
2043 if (r && (r->isTextArea() || r->isTextField()) && r->isEdited()) {
2044 EventTargetNodeCast(oldFocusedNode.get())->dispatchHTMLEvent(changeEvent, true, false);
2045 if ((r = static_cast<RenderObject*>(oldFocusedNode.get()->renderer())))
2046 r->setEdited(false);
2049 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
2050 EventTargetNodeCast(oldFocusedNode.get())->dispatchBlurEvent();
2052 if (m_focusedNode) {
2053 // handler shifted focus
2054 focusChangeBlocked = true;
2057 clearSelectionIfNeeded(newFocusedNode.get());
2058 EventTargetNodeCast(oldFocusedNode.get())->dispatchUIEvent(DOMFocusOutEvent);
2059 if (m_focusedNode) {
2060 // handler shifted focus
2061 focusChangeBlocked = true;
2064 clearSelectionIfNeeded(newFocusedNode.get());
2065 if ((oldFocusedNode.get() == this) && oldFocusedNode->hasOneRef())
2068 if (oldFocusedNode.get() == oldFocusedNode->rootEditableElement())
2069 frame()->editor()->didEndEditing();
2072 if (newFocusedNode) {
2073 if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
2074 // delegate blocks focus change
2075 focusChangeBlocked = true;
2076 goto SetFocusedNodeDone;
2078 // Set focus on the new node
2079 m_focusedNode = newFocusedNode.get();
2081 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
2082 EventTargetNodeCast(m_focusedNode.get())->dispatchFocusEvent();
2084 if (m_focusedNode != newFocusedNode) {
2085 // handler shifted focus
2086 focusChangeBlocked = true;
2087 goto SetFocusedNodeDone;
2089 EventTargetNodeCast(m_focusedNode.get())->dispatchUIEvent(DOMFocusInEvent);
2090 if (m_focusedNode != newFocusedNode) {
2091 // handler shifted focus
2092 focusChangeBlocked = true;
2093 goto SetFocusedNodeDone;
2095 m_focusedNode->setFocus();
2097 if (m_focusedNode.get() == m_focusedNode->rootEditableElement())
2098 frame()->editor()->didBeginEditing();
2100 // eww, I suck. set the qt focus correctly
2101 // ### find a better place in the code for this
2103 Widget *focusWidget = widgetForNode(m_focusedNode.get());
2105 // Make sure a widget has the right size before giving it focus.
2106 // Otherwise, we are testing edge cases of the Widget code.
2107 // Specifically, in WebCore this does not work well for text fields.
2109 // Re-get the widget in case updating the layout changed things.
2110 focusWidget = widgetForNode(m_focusedNode.get());
2113 focusWidget->setFocus();
2120 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled())
2121 axObjectCache()->handleFocusedUIElementChanged();
2126 return !focusChangeBlocked;
2129 void Document::clearSelectionIfNeeded(Node *newFocusedNode)
2134 // Clear the selection when changing the focus node to null or to a node that is not
2135 // contained by the current selection.
2136 Node *startContainer = frame()->selectionController()->start().node();
2137 if (!newFocusedNode || (startContainer && startContainer != newFocusedNode && !(startContainer->isDescendantOf(newFocusedNode)) && startContainer->shadowAncestorNode() != newFocusedNode))
2138 frame()->selectionController()->clear();
2141 void Document::setCSSTarget(Node* n)
2144 m_cssTarget->setChanged();
2150 Node* Document::getCSSTarget() const
2155 void Document::attachNodeIterator(NodeIterator *ni)
2157 m_nodeIterators.add(ni);
2160 void Document::detachNodeIterator(NodeIterator *ni)
2162 m_nodeIterators.remove(ni);
2165 void Document::notifyBeforeNodeRemoval(Node *n)
2167 if (Frame* f = frame()) {
2168 f->selectionController()->nodeWillBeRemoved(n);
2169 f->dragCaretController()->nodeWillBeRemoved(n);
2172 HashSet<NodeIterator*>::const_iterator end = m_nodeIterators.end();
2173 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != end; ++it)
2174 (*it)->notifyBeforeNodeRemoval(n);
2177 DOMWindow* Document::defaultView() const
2182 return frame()->domWindow();
2185 PassRefPtr<Event> Document::createEvent(const String &eventType, ExceptionCode& ec)
2187 if (eventType == "UIEvents" || eventType == "UIEvent")
2188 return new UIEvent();
2189 if (eventType == "MouseEvents" || eventType == "MouseEvent")
2190 return new MouseEvent();
2191 if (eventType == "MutationEvents" || eventType == "MutationEvent")
2192 return new MutationEvent();
2193 if (eventType == "KeyboardEvents" || eventType == "KeyboardEvent")
2194 return new KeyboardEvent();
2195 if (eventType == "HTMLEvents" || eventType == "Event" || eventType == "Events")
2198 if (eventType == "SVGEvents")
2200 if (eventType == "SVGZoomEvents")
2201 return new SVGZoomEvent();
2203 ec = NOT_SUPPORTED_ERR;
2207 CSSStyleDeclaration *Document::getOverrideStyle(Element */*elt*/, const String &/*pseudoElt*/)
2212 void Document::handleWindowEvent(Event *evt, bool useCapture)
2214 if (m_windowEventListeners.isEmpty())
2217 // if any html event listeners are registered on the window, then dispatch them here
2218 RegisteredEventListenerList listenersCopy = m_windowEventListeners;
2219 RegisteredEventListenerList::iterator it = listenersCopy.begin();
2221 for (; it != listenersCopy.end(); ++it)
2222 if ((*it)->eventType() == evt->type() && (*it)->useCapture() == useCapture && !(*it)->removed())
2223 (*it)->listener()->handleEvent(evt, true);
2227 void Document::defaultEventHandler(Event *evt)
2230 if (evt->type() == keydownEvent) {
2231 KeyboardEvent* kevt = static_cast<KeyboardEvent *>(evt);
2232 if (kevt->ctrlKey()) {
2233 const PlatformKeyboardEvent* ev = kevt->keyEvent();
2234 String key = (ev ? ev->unmodifiedText() : kevt->keyIdentifier()).lower();
2235 Element* elem = getElementByAccessKey(key);
2237 elem->accessKeyAction(false);
2238 evt->setDefaultHandled();
2244 void Document::setHTMLWindowEventListener(const AtomicString &eventType, PassRefPtr<EventListener> listener)
2246 // If we already have it we don't want removeWindowEventListener to delete it
2247 removeHTMLWindowEventListener(eventType);
2249 addWindowEventListener(eventType, listener, false);
2252 EventListener *Document::getHTMLWindowEventListener(const AtomicString &eventType)
2254 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2255 for (; it != m_windowEventListeners.end(); ++it)
2256 if ( (*it)->eventType() == eventType && (*it)->listener()->isHTMLEventListener())
2257 return (*it)->listener();
2261 void Document::removeHTMLWindowEventListener(const AtomicString &eventType)
2263 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2264 for (; it != m_windowEventListeners.end(); ++it)
2265 if ( (*it)->eventType() == eventType && (*it)->listener()->isHTMLEventListener()) {
2266 m_windowEventListeners.remove(it);
2271 void Document::addWindowEventListener(const AtomicString &eventType, PassRefPtr<EventListener> listener, bool useCapture)
2273 // Remove existing identical listener set with identical arguments.
2274 // The DOM 2 spec says that "duplicate instances are discarded" in this case.
2275 removeWindowEventListener(eventType, listener.get(), useCapture);
2276 m_windowEventListeners.append(new RegisteredEventListener(eventType, listener, useCapture));
2279 void Document::removeWindowEventListener(const AtomicString &eventType, EventListener *listener, bool useCapture)
2281 RegisteredEventListener rl(eventType, listener, useCapture);
2282 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2283 for (; it != m_windowEventListeners.end(); ++it)
2285 m_windowEventListeners.remove(it);
2290 bool Document::hasWindowEventListener(const AtomicString &eventType)
2292 RegisteredEventListenerList::iterator it = m_windowEventListeners.begin();
2293 for (; it != m_windowEventListeners.end(); ++it)
2294 if ((*it)->eventType() == eventType) {
2300 PassRefPtr<EventListener> Document::createHTMLEventListener(const String& functionName, const String& code, Node *node)
2302 if (Frame* frm = frame())
2303 if (KJSProxy* proxy = frm->scriptProxy())
2304 return proxy->createHTMLEventHandler(functionName, code, node);
2308 void Document::setHTMLWindowEventListener(const AtomicString& eventType, Attribute* attr)
2310 setHTMLWindowEventListener(eventType,
2311 createHTMLEventListener(attr->localName().domString(), attr->value(), 0));
2314 void Document::dispatchImageLoadEventSoon(HTMLImageLoader *image)
2316 m_imageLoadEventDispatchSoonList.append(image);
2317 if (!m_imageLoadEventTimer.isActive())
2318 m_imageLoadEventTimer.startOneShot(0);
2321 void Document::removeImage(HTMLImageLoader* image)
2323 // Remove instances of this image from both lists.
2324 // Use loops because we allow multiple instances to get into the lists.
2325 while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
2326 while (m_imageLoadEventDispatchingList.removeRef(image)) { }
2327 if (m_imageLoadEventDispatchSoonList.isEmpty())
2328 m_imageLoadEventTimer.stop();
2331 void Document::dispatchImageLoadEventsNow()
2333 // need to avoid re-entering this function; if new dispatches are
2334 // scheduled before the parent finishes processing the list, they
2335 // will set a timer and eventually be processed
2336 if (!m_imageLoadEventDispatchingList.isEmpty()) {
2340 m_imageLoadEventTimer.stop();
2342 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2343 m_imageLoadEventDispatchSoonList.clear();
2344 for (DeprecatedPtrListIterator<HTMLImageLoader> it(m_imageLoadEventDispatchingList); it.current();) {
2345 HTMLImageLoader* image = it.current();
2346 // Must advance iterator *before* dispatching call.
2347 // Otherwise, it might be advanced automatically if dispatching the call had a side effect
2348 // of destroying the current HTMLImageLoader, and then we would advance past the *next* item,
2349 // missing one altogether.
2351 image->dispatchLoadEvent();
2353 m_imageLoadEventDispatchingList.clear();
2356 void Document::imageLoadEventTimerFired(Timer<Document>*)
2358 dispatchImageLoadEventsNow();
2361 Element *Document::ownerElement() const
2365 return frame()->ownerElement();
2368 String Document::referrer() const
2371 return frame()->loader()->referrer();
2375 String Document::domain() const
2377 if (m_domain.isEmpty()) // not set yet (we set it on demand to save time and space)
2378 m_domain = KURL(URL()).host(); // Initially set to the host
2382 void Document::setDomain(const String &newDomain, bool force /*=false*/)
2385 m_domain = newDomain;
2388 if (m_domain.isEmpty()) // not set yet (we set it on demand to save time and space)
2389 m_domain = KURL(URL()).host(); // Initially set to the host
2391 // Both NS and IE specify that changing the domain is only allowed when
2392 // the new domain is a suffix of the old domain.
2393 int oldLength = m_domain.length();
2394 int newLength = newDomain.length();
2395 if (newLength < oldLength) // e.g. newDomain=kde.org (7) and m_domain=www.kde.org (11)
2397 String test = m_domain.copy();
2398 if (test[oldLength - newLength - 1] == '.') // Check that it's a subdomain, not e.g. "de.org"
2400 test.remove(0, oldLength - newLength); // now test is "kde.org" from m_domain
2401 if (test == newDomain) // and we check that it's the same thing as newDomain
2402 m_domain = newDomain;
2407 bool Document::isValidName(const String &name)
2409 const UChar* s = reinterpret_cast<const UChar*>(name.characters());
2410 unsigned length = name.length();
2418 U16_NEXT(s, i, length, c)
2419 if (!isValidNameStart(c))
2422 while (i < length) {
2423 U16_NEXT(s, i, length, c)
2424 if (!isValidNamePart(c))
2431 bool Document::parseQualifiedName(const String &qualifiedName, String &prefix, String &localName)
2433 unsigned length = qualifiedName.length();
2438 bool nameStart = true;
2439 bool sawColon = false;
2442 const UChar* s = reinterpret_cast<const UChar*>(qualifiedName.characters());
2443 for (unsigned i = 0; i < length;) {
2445 U16_NEXT(s, i, length, c)
2448 return false; // multiple colons: not allowed
2452 } else if (nameStart) {
2453 if (!isValidNameStart(c))
2457 if (!isValidNamePart(c))
2464 localName = qualifiedName.copy();
2466 prefix = qualifiedName.substring(0, colonPos);
2467 localName = qualifiedName.substring(colonPos + 1, length - (colonPos + 1));
2473 void Document::addImageMap(HTMLMapElement* imageMap)
2475 // Add the image map, unless there's already another with that name.
2476 // "First map wins" is the rule other browsers seem to implement.
2477 m_imageMapsByName.add(imageMap->getName().impl(), imageMap);
2480 void Document::removeImageMap(HTMLMapElement* imageMap)
2482 // Remove the image map by name.
2483 // But don't remove some other image map that just happens to have the same name.
2484 // FIXME: Use a HashCountedSet as we do for IDs to find the first remaining map
2485 // once a map has been removed.
2486 const AtomicString& name = imageMap->getName();
2487 ImageMapsByName::iterator it = m_imageMapsByName.find(name.impl());
2488 if (it != m_imageMapsByName.end() && it->second == imageMap)
2489 m_imageMapsByName.remove(it);
2492 HTMLMapElement *Document::getImageMap(const String& URL) const
2496 int hashPos = URL.find('#');
2497 AtomicString name = (hashPos < 0 ? URL : URL.substring(hashPos + 1)).impl();
2498 return m_imageMapsByName.get(name.impl());
2501 void Document::setDecoder(TextResourceDecoder *decoder)
2503 m_decoder = decoder;
2506 UChar Document::backslashAsCurrencySymbol() const
2510 return m_decoder->encoding().backslashAsCurrencySymbol();
2513 DeprecatedString Document::completeURL(const DeprecatedString& URL)
2515 // FIXME: This treats null URLs the same as empty URLs, unlike the String function below.
2517 // If both the URL and base URL are empty, like they are for documents
2518 // created using DOMImplementation::createDocument, just return the passed in URL.
2519 // (We do this because URL() returns "about:blank" for empty URLs.
2520 if (m_url.isEmpty() && m_baseURL.isEmpty())
2523 return KURL(baseURL(), URL).url();
2524 return KURL(baseURL(), URL, m_decoder->encoding()).url();
2527 String Document::completeURL(const String &URL)
2529 // FIXME: This always returns null when passed a null URL, unlike the String function above.
2532 return completeURL(URL.deprecatedString());
2535 bool Document::inPageCache()
2537 return m_inPageCache;
2540 void Document::setInPageCache(bool flag)
2542 if (m_inPageCache == flag)
2545 m_inPageCache = flag;
2547 ASSERT(m_savedRenderer == 0);
2548 m_savedRenderer = renderer();
2550 m_view->resetScrollbars();
2552 ASSERT(renderer() == 0 || renderer() == m_savedRenderer);
2553 ASSERT(m_renderArena);
2554 setRenderer(m_savedRenderer);
2555 m_savedRenderer = 0;
2559 void Document::passwordFieldAdded()
2564 void Document::passwordFieldRemoved()
2566 assert(m_passwordFields > 0);
2570 bool Document::hasPasswordField() const
2572 return m_passwordFields > 0;
2575 void Document::secureFormAdded()
2580 void Document::secureFormRemoved()
2582 assert(m_secureForms > 0);
2586 bool Document::hasSecureForm() const
2588 return m_secureForms > 0;
2591 void Document::setShouldCreateRenderers(bool f)
2593 m_createRenderers = f;
2596 bool Document::shouldCreateRenderers()
2598 return m_createRenderers;
2601 String Document::toString() const
2605 for (Node *child = firstChild(); child != NULL; child = child->nextSibling()) {
2606 result += child->toString();
2612 // Support for Javascript execCommand, and related methods
2614 JSEditor *Document::jsEditor()
2617 m_jsEditor = new JSEditor(this);
2621 bool Document::execCommand(const String &command, bool userInterface, const String &value)
2623 return jsEditor()->execCommand(command, userInterface, value);
2626 bool Document::queryCommandEnabled(const String &command)
2628 return jsEditor()->queryCommandEnabled(command);
2631 bool Document::queryCommandIndeterm(const String &command)
2633 return jsEditor()->queryCommandIndeterm(command);
2636 bool Document::queryCommandState(const String &command)
2638 return jsEditor()->queryCommandState(command);
2641 bool Document::queryCommandSupported(const String &command)
2643 return jsEditor()->queryCommandSupported(command);
2646 String Document::queryCommandValue(const String &command)
2648 return jsEditor()->queryCommandValue(command);
2651 static IntRect placeholderRectForMarker(void)
2653 return IntRect(-1,-1,-1,-1);
2656 void Document::addMarker(Range *range, DocumentMarker::MarkerType type, String description)
2658 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2659 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2660 RefPtr<Range> textPiece = markedText.range();
2662 DocumentMarker marker = {type, textPiece->startOffset(exception), textPiece->endOffset(exception), description};
2663 addMarker(textPiece->startContainer(exception), marker);
2667 void Document::removeMarkers(Range *range, DocumentMarker::MarkerType markerType)
2669 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2670 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2671 RefPtr<Range> textPiece = markedText.range();
2673 unsigned startOffset = textPiece->startOffset(exception);
2674 unsigned length = textPiece->endOffset(exception) - startOffset + 1;
2675 removeMarkers(textPiece->startContainer(exception), startOffset, length, markerType);
2679 // Markers are stored in order sorted by their location. They do not overlap each other, as currently
2680 // required by the drawing code in RenderText.cpp.
2682 void Document::addMarker(Node *node, DocumentMarker newMarker)
2684 assert(newMarker.endOffset >= newMarker.startOffset);
2685 if (newMarker.endOffset == newMarker.startOffset)
2688 MarkerMapVectorPair* vectorPair = m_markers.get(node);
2691 vectorPair = new MarkerMapVectorPair;
2692 vectorPair->first.append(newMarker);
2693 vectorPair->second.append(placeholderRectForMarker());
2694 m_markers.set(node, vectorPair);
2696 Vector<DocumentMarker>& markers = vectorPair->first;
2697 Vector<IntRect>& rects = vectorPair->second;
2698 ASSERT(markers.size() == rects.size());
2699 Vector<DocumentMarker>::iterator it;
2700 for (it = markers.begin(); it != markers.end();) {
2701 DocumentMarker marker = *it;
2703 if (newMarker.endOffset < marker.startOffset+1) {
2704 // This is the first marker that is completely after newMarker, and disjoint from it.
2705 // We found our insertion point.
\10
2707 } else if (newMarker.startOffset > marker.endOffset) {
2708 // maker is before newMarker, and disjoint from it. Keep scanning.
2710 } else if (newMarker == marker) {
2711 // already have this one, NOP
2714 // marker and newMarker intersect or touch - merge them into newMarker
2715 newMarker.startOffset = min(newMarker.startOffset, marker.startOffset);
2716 newMarker.endOffset = max(newMarker.endOffset, marker.endOffset);
2717 // remove old one, we'll add newMarker later
2718 unsigned removalIndex = it - markers.begin();
2719 markers.remove(removalIndex);
2720 rects.remove(removalIndex);
2721 // it points to the next marker to consider
2724 // at this point it points to the node before which we want to insert
2725 unsigned insertionIndex = it - markers.begin();
2726 markers.insert(insertionIndex, newMarker);
2727 rects.insert(insertionIndex, placeholderRectForMarker());
2730 // repaint the affected node
2731 if (node->renderer())
2732 node->renderer()->repaint();
2735 // copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
2736 // useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
2737 void Document::copyMarkers(Node *srcNode, unsigned startOffset, int length, Node *dstNode, int delta, DocumentMarker::MarkerType markerType)
2742 MarkerMapVectorPair* vectorPair = m_markers.get(srcNode);
2746 ASSERT(vectorPair->first.size() == vectorPair->second.size());
2748 bool docDirty = false;
2749 unsigned endOffset = startOffset + length - 1;
2750 Vector<DocumentMarker>::iterator it;
2751 Vector<DocumentMarker>& markers = vectorPair->first;
2752 for (it = markers.begin(); it != markers.end(); ++it) {
2753 DocumentMarker marker = *it;
2755 // stop if we are now past the specified range
2756 if (marker.startOffset > endOffset)
2759 // skip marker that is before the specified range or is the wrong type
2760 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers))
2763 // pin the marker to the specified range and apply the shift delta
2765 if (marker.startOffset < startOffset)
2766 marker.startOffset = startOffset;
2767 if (marker.endOffset > endOffset)
2768 marker.endOffset = endOffset;
2769 marker.startOffset += delta;
2770 marker.endOffset += delta;
2772 addMarker(dstNode, marker);
2775 // repaint the affected node
2776 if (docDirty && dstNode->renderer())
2777 dstNode->renderer()->repaint();
2780 void Document::removeMarkers(Node *node, unsigned startOffset, int length, DocumentMarker::MarkerType markerType)
2785 MarkerMapVectorPair* vectorPair = m_markers.get(node);
2789 Vector<DocumentMarker>& markers = vectorPair->first;
2790 Vector<IntRect>& rects = vectorPair->second;
2791 ASSERT(markers.size() == rects.size());
2792 bool docDirty = false;
2793 unsigned endOffset = startOffset + length - 1;
2794 Vector<DocumentMarker>::iterator it;
2795 for (it = markers.begin(); it < markers.end();) {
2796 DocumentMarker marker = *it;
2798 // markers are returned in order, so stop if we are now past the specified range
2799 if (marker.startOffset > endOffset)
2802 // skip marker that is wrong type or before target
2803 if (marker.endOffset < startOffset || (marker.type != markerType && markerType != DocumentMarker::AllMarkers)) {
2808 // at this point we know that marker and target intersect in some way
2811 // pitch the old marker and any associated rect
2812 unsigned removalIndex = it - markers.begin();
2813 markers.remove(removalIndex);
2814 rects.remove(removalIndex);
2815 // it now points to the next node
2817 // add either of the resulting slices that are left after removing target
2818 if (startOffset > marker.startOffset) {
2819 DocumentMarker newLeft = marker;
2820 newLeft.endOffset = startOffset;
2821 unsigned insertionIndex = it - markers.begin();
2822 markers.insert(insertionIndex, newLeft);
2823 rects.insert(insertionIndex, placeholderRectForMarker());
2824 // it now points to the newly-inserted node, but we want to skip that one
2827 if (marker.endOffset > endOffset) {
2828 DocumentMarker newRight = marker;
2829 newRight.startOffset = endOffset;
2830 unsigned insertionIndex = it - markers.begin();
2831 markers.insert(insertionIndex, newRight);
2832 rects.insert(insertionIndex, placeholderRectForMarker());
2833 // it now points to the newly-inserted node, but we want to skip that one
2838 if (markers.isEmpty()) {
2839 ASSERT(rects.isEmpty());
2840 m_markers.remove(node);
2844 // repaint the affected node
2845 if (docDirty && node->renderer())
2846 node->renderer()->repaint();
2849 DocumentMarker* Document::markerContainingPoint(const IntPoint& point, DocumentMarker::MarkerType markerType)
2851 // outer loop: process each node that contains any markers
2852 MarkerMap::iterator end = m_markers.end();
2853 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
2854 // inner loop; process each marker in this node
2855 MarkerMapVectorPair* vectorPair = nodeIterator->second;
2856 Vector<DocumentMarker>& markers = vectorPair->first;
2857 Vector<IntRect>& rects = vectorPair->second;
2858 ASSERT(markers.size() == rects.size());
2859 unsigned markerCount = markers.size();
2860 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
2861 DocumentMarker& marker = markers[markerIndex];
2863 // skip marker that is wrong type
2864 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
2867 IntRect& r = rects[markerIndex];
2869 // skip placeholder rects
2870 if (r == placeholderRectForMarker())
2873 if (r.contains(point))
2881 Vector<DocumentMarker> Document::markersForNode(Node* node)
2883 MarkerMapVectorPair* vectorPair = m_markers.get(node);
2885 return vectorPair->first;
2886 return Vector<DocumentMarker>();
2889 Vector<IntRect> Document::renderedRectsForMarkers(DocumentMarker::MarkerType markerType)
2891 Vector<IntRect> result;
2893 // outer loop: process each node
2894 MarkerMap::iterator end = m_markers.end();
2895 for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
2896 // inner loop; process each marker in this node
2897 MarkerMapVectorPair* vectorPair = nodeIterator->second;
2898 Vector<DocumentMarker>& markers = vectorPair->first;
2899 Vector<IntRect>& rects = vectorPair->second;
2900 ASSERT(markers.size() == rects.size());
2901 unsigned markerCount = markers.size();
2902 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
2903 DocumentMarker marker = markers[markerIndex];
2905 // skip marker that is wrong type
2906 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers)
2909 IntRect r = rects[markerIndex];
2910 // skip placeholder rects
2911 if (r == placeholderRectForMarker())
2922 void Document::removeMarkers(Node* node)
2924 MarkerMap::iterator i = m_markers.find(node);
2925 if (i != m_markers.end()) {
2927 m_markers.remove(i);
2928 if (RenderObject* renderer = node->renderer())
2929 renderer->repaint();
2933 void Document::removeMarkers(DocumentMarker::MarkerType markerType)
2935 // outer loop: process each markered node in the document
2936 MarkerMap markerMapCopy = m_markers;
2937 MarkerMap::iterator end = markerMapCopy.end();
2938 for (MarkerMap::iterator i = markerMapCopy.begin(); i != end; ++i) {
2939 Node* node = i->first.get();
2940 bool nodeNeedsRepaint = false;
2942 // inner loop: process each marker in the current node
2943 MarkerMapVectorPair* vectorPair = i->second;
2944 Vector<DocumentMarker>& markers = vectorPair->first;
2945 Vector<IntRect>& rects = vectorPair->second;
2946 ASSERT(markers.size() == rects.size());
2947 Vector<DocumentMarker>::iterator markerIterator;
2948 for (markerIterator = markers.begin(); markerIterator != markers.end();) {
2949 DocumentMarker marker = *markerIterator;
2951 // skip nodes that are not of the specified type
2952 if (marker.type != markerType && markerType != DocumentMarker::AllMarkers) {
2957 // pitch the old marker
2958 markers.remove(markerIterator - markers.begin());
2959 rects.remove(markerIterator - markers.begin());
2960 nodeNeedsRepaint = true;
2961 // markerIterator now points to the next node
2964 // Redraw the node if it changed. Do this before the node is removed from m_markers, since
2965 // m_markers might contain the last reference to the node.
2966 if (nodeNeedsRepaint) {
2967 RenderObject* renderer = node->renderer();
2969 renderer->repaint();
2972 // delete the node's list if it is now empty
2973 if (markers.isEmpty()) {
2974 ASSERT(rects.isEmpty());
2975 m_markers.remove(node);
2981 void Document::repaintMarkers(DocumentMarker::MarkerType markerType)
2983 // outer loop: process each markered node in the document
2984 MarkerMap::iterator end = m_markers.end();
2985 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
2986 Node* node = i->first.get();
2988 // inner loop: process each marker in the current node
2989 MarkerMapVectorPair* vectorPair = i->second;
2990 Vector<DocumentMarker>& markers = vectorPair->first;
2991 Vector<DocumentMarker>::iterator markerIterator;
2992 bool nodeNeedsRepaint = false;
2993 for (markerIterator = markers.begin(); markerIterator != markers.end(); ++markerIterator) {
2994 DocumentMarker marker = *markerIterator;
2996 // skip nodes that are not of the specified type
2997 if (marker.type == markerType || markerType == DocumentMarker::AllMarkers) {
2998 nodeNeedsRepaint = true;
3003 if (!nodeNeedsRepaint)
3006 // cause the node to be redrawn
3007 if (RenderObject* renderer = node->renderer())
3008 renderer->repaint();
3012 void Document::setRenderedRectForMarker(Node* node, DocumentMarker marker, const IntRect& r)
3014 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3016 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3020 Vector<DocumentMarker>& markers = vectorPair->first;
3021 ASSERT(markers.size() == vectorPair->second.size());
3022 unsigned markerCount = markers.size();
3023 for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
3024 DocumentMarker m = markers[markerIndex];
3026 vectorPair->second[markerIndex] = r;
3031 ASSERT_NOT_REACHED(); // shouldn't be trying to set the rect for a marker we don't already know about
3034 void Document::invalidateRenderedRectsForMarkersInRect(const IntRect& r)
3036 // outer loop: process each markered node in the document
3037 MarkerMap::iterator end = m_markers.end();
3038 for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
3040 // inner loop: process each rect in the current node
3041 MarkerMapVectorPair* vectorPair = i->second;
3042 Vector<IntRect>& rects = vectorPair->second;
3044 unsigned rectCount = rects.size();
3045 for (unsigned rectIndex = 0; rectIndex < rectCount; ++rectIndex)
3046 if (rects[rectIndex].intersects(r))
3047 rects[rectIndex] = placeholderRectForMarker();
3051 void Document::shiftMarkers(Node *node, unsigned startOffset, int delta, DocumentMarker::MarkerType markerType)
3053 MarkerMapVectorPair* vectorPair = m_markers.get(node);
3057 Vector<DocumentMarker>& markers = vectorPair->first;
3058 Vector<IntRect>& rects = vectorPair->second;
3059 ASSERT(markers.size() == rects.size());
3061 bool docDirty = false;
3062 Vector<DocumentMarker>::iterator it;
3063 for (it = markers.begin(); it != markers.end(); ++it) {
3064 DocumentMarker &marker = *it;
3065 if (marker.startOffset >= startOffset && (markerType == DocumentMarker::AllMarkers || marker.type == markerType)) {
3066 assert((int)marker.startOffset + delta >= 0);
3067 marker.startOffset += delta;
3068 marker.endOffset += delta;
3071 // Marker moved, so previously-computed rendered rectangle is now invalid
3072 rects[it - markers.begin()] = placeholderRectForMarker();
3076 // repaint the affected node
3077 if (docDirty && node->renderer())
3078 node->renderer()->repaint();
3083 void Document::applyXSLTransform(ProcessingInstruction* pi)
3085 RefPtr<XSLTProcessor> processor = new XSLTProcessor;
3086 processor->setXSLStylesheet(static_cast<XSLStyleSheet*>(pi->sheet()));
3088 DeprecatedString resultMIMEType;
3089 DeprecatedString newSource;
3090 DeprecatedString resultEncoding;
3091 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
3093 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
3094 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, view());
3099 void Document::setDesignMode(InheritedBool value)
3101 m_designMode = value;
3104 Document::InheritedBool Document::getDesignMode() const
3106 return m_designMode;
3109 bool Document::inDesignMode() const
3111 for (const Document* d = this; d; d = d->parentDocument()) {
3112 if (d->m_designMode != inherit)
3113 return d->m_designMode;
3118 Document *Document::parentDocument() const
3120 Frame *childPart = frame();
3123 Frame *parent = childPart->tree()->parent();
3126 return parent->document();
3129 Document *Document::topDocument() const
3131 Document *doc = const_cast<Document *>(this);
3133 while ((element = doc->ownerElement()) != 0)
3134 doc = element->document();
3139 PassRefPtr<Attr> Document::createAttributeNS(const String &namespaceURI, const String &qualifiedName, ExceptionCode& ec)
3141 if (qualifiedName.isNull()) {
3146 String localName = qualifiedName;
3149 if ((colonpos = qualifiedName.find(':')) >= 0) {
3150 prefix = qualifiedName.copy();
3151 localName = qualifiedName.copy();
3152 prefix.truncate(colonpos);
3153 localName.remove(0, colonpos+1);
3156 if (!isValidName(localName)) {
3157 ec = INVALID_CHARACTER_ERR;
3161 // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
3162 // documents if we're wrong.
3163 return new Attr(0, this, new MappedAttribute(QualifiedName(prefix.impl(),
3165 namespaceURI.impl()), String("").impl()));
3169 const SVGDocumentExtensions* Document::svgExtensions()
3171 return m_svgExtensions;
3174 SVGDocumentExtensions* Document::accessSVGExtensions()
3176 if (!m_svgExtensions)
3177 m_svgExtensions = new SVGDocumentExtensions(this);
3178 return m_svgExtensions;
3182 void Document::radioButtonChecked(HTMLInputElement *caller, HTMLFormElement *form)
3184 // Without a name, there is no group.
3185 if (caller->name().isEmpty())
3189 // Uncheck the currently selected item
3190 NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
3191 if (!formRadioButtons) {
3192 formRadioButtons = new NameToInputMap;
3193 m_selectedRadioButtons.set(form, formRadioButtons);
3196 HTMLInputElement* currentCheckedRadio = formRadioButtons->get(caller->name().impl());
3197 if (currentCheckedRadio && currentCheckedRadio != caller)
3198 currentCheckedRadio->setChecked(false);
3200 formRadioButtons->set(caller->name().impl(), caller);
3203 HTMLInputElement* Document::checkedRadioButtonForGroup(AtomicStringImpl* name, HTMLFormElement *form)
3207 NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
3208 if (!formRadioButtons)
3211 return formRadioButtons->get(name);
3214 void Document::removeRadioButtonGroup(AtomicStringImpl* name, HTMLFormElement *form)
3218 NameToInputMap* formRadioButtons = m_selectedRadioButtons.get(form);
3219 if (formRadioButtons) {
3220 formRadioButtons->remove(name);
3221 if (formRadioButtons->isEmpty()) {
3222 m_selectedRadioButtons.remove(form);
3223 delete formRadioButtons;
3228 PassRefPtr<HTMLCollection> Document::images()
3230 return new HTMLCollection(this, HTMLCollection::DocImages);
3233 PassRefPtr<HTMLCollection> Document::applets()
3235 return new HTMLCollection(this, HTMLCollection::DocApplets);
3238 PassRefPtr<HTMLCollection> Document::embeds()
3240 return new HTMLCollection(this, HTMLCollection::DocEmbeds);
3243 PassRefPtr<HTMLCollection> Document::objects()
3245 return new HTMLCollection(this, HTMLCollection::DocObjects);
3248 PassRefPtr<HTMLCollection> Document::scripts()
3250 return new HTMLCollection(this, HTMLCollection::DocScripts);
3253 PassRefPtr<HTMLCollection> Document::links()
3255 return new HTMLCollection(this, HTMLCollection::DocLinks);
3258 PassRefPtr<HTMLCollection> Document::forms()
3260 return new HTMLCollection(this, HTMLCollection::DocForms);
3263 PassRefPtr<HTMLCollection> Document::anchors()
3265 return new HTMLCollection(this, HTMLCollection::DocAnchors);
3268 PassRefPtr<HTMLCollection> Document::all()
3270 return new HTMLCollection(this, HTMLCollection::DocAll);
3273 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
3275 return new HTMLNameCollection(this, HTMLCollection::WindowNamedItems, name);
3278 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
3280 return new HTMLNameCollection(this, HTMLCollection::DocumentNamedItems, name);
3283 HTMLCollection::CollectionInfo* Document::nameCollectionInfo(HTMLCollection::Type type, const String& name)
3285 HashMap<AtomicStringImpl*, HTMLCollection::CollectionInfo>& map = m_nameCollectionInfo[type - HTMLCollection::UnnamedCollectionTypes];
3287 AtomicString atomicName(name);
3289 HashMap<AtomicStringImpl*, HTMLCollection::CollectionInfo>::iterator iter = map.find(atomicName.impl());
3290 if (iter == map.end())
3291 iter = map.add(atomicName.impl(), HTMLCollection::CollectionInfo()).first;
3293 return &iter->second;
3296 PassRefPtr<NameNodeList> Document::getElementsByName(const String &elementName)
3298 return new NameNodeList(this, elementName);
3301 void Document::finishedParsing()
3304 if (Frame* f = frame())
3305 f->loader()->finishedParsing();
3308 Vector<String> Document::formElementsState() const
3310 Vector<String> stateVector;
3311 stateVector.reserveCapacity(m_formElementsWithState.size() * 3);
3312 typedef HashSet<HTMLGenericFormElement*>::const_iterator Iterator;
3313 Iterator end = m_formElementsWithState.end();
3314 for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
3315 HTMLGenericFormElement* e = *it;
3316 stateVector.append(e->name().domString());
3317 stateVector.append(e->type().domString());
3318 stateVector.append(e->stateValue());
3323 #ifdef XPATH_SUPPORT
3325 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
3326 XPathNSResolver* resolver,
3329 if (!m_xpathEvaluator)
3330 m_xpathEvaluator = new XPathEvaluator;
3331 return m_xpathEvaluator->createExpression(expression, resolver, ec);
3334 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
3336 if (!m_xpathEvaluator)
3337 m_xpathEvaluator = new XPathEvaluator;
3338 return m_xpathEvaluator->createNSResolver(nodeResolver);
3341 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
3343 XPathNSResolver* resolver,
3344 unsigned short type,
3345 XPathResult* result,
3348 if (!m_xpathEvaluator)
3349 m_xpathEvaluator = new XPathEvaluator;
3350 return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
3353 #endif // XPATH_SUPPORT
3355 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
3357 // Walk the state vector backwards so that the value to use for each
3358 // name/type pair first is the one at the end of each individual vector
3359 // in the FormElementStateMap. We're using them like stacks.
3360 typedef FormElementStateMap::iterator Iterator;
3361 m_formElementsWithState.clear();
3362 for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
3363 AtomicString a = stateVector[i - 3];
3364 AtomicString b = stateVector[i - 2];
3365 const String& c = stateVector[i - 1];
3366 FormElementKey key(a.impl(), b.impl());
3367 Iterator it = m_stateForNewFormElements.find(key);
3368 if (it != m_stateForNewFormElements.end())
3369 it->second.append(c);
3371 Vector<String> v(1);
3373 m_stateForNewFormElements.set(key, v);
3378 bool Document::hasStateForNewFormElements() const
3380 return !m_stateForNewFormElements.isEmpty();
3383 bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
3385 typedef FormElementStateMap::iterator Iterator;
3386 Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
3387 if (it == m_stateForNewFormElements.end())
3389 ASSERT(it->second.size());
3390 state = it->second.last();
3391 if (it->second.size() > 1)
3392 it->second.removeLast();
3394 m_stateForNewFormElements.remove(it);
3398 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
3399 : m_name(name), m_type(type)
3404 FormElementKey::~FormElementKey()
3409 FormElementKey::FormElementKey(const FormElementKey& other)
3410 : m_name(other.name()), m_type(other.type())
3415 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
3419 m_name = other.name();
3420 m_type = other.type();
3424 void FormElementKey::ref() const
3426 if (name() && name() != HashTraits<AtomicStringImpl*>::deletedValue())
3432 void FormElementKey::deref() const
3434 if (name() && name() != HashTraits<AtomicStringImpl*>::deletedValue())
3440 unsigned FormElementKeyHash::hash(const FormElementKey& k)
3442 ASSERT(sizeof(k) % (sizeof(uint16_t) * 2) == 0);
3444 unsigned l = sizeof(k) / (sizeof(uint16_t) * 2);
3445 const uint16_t* s = reinterpret_cast<const uint16_t*>(&k);
3446 uint32_t hash = PHI;
3449 for (; l > 0; l--) {
3451 uint32_t tmp = (s[1] << 11) ^ hash;
3452 hash = (hash << 16) ^ tmp;
3457 // Force "avalanching" of final 127 bits
3464 // this avoids ever returning a hash code of 0, since that is used to
3465 // signal "hash not computed yet", using a value that is likely to be
3466 // effectively the same as 0 when the low bits are masked
3473 FormElementKey FormElementKeyHashTraits::deletedValue()
3475 return HashTraits<AtomicStringImpl*>::deletedValue();
3479 String Document::iconURL()
3484 void Document::setIconURL(const String& iconURL, const String& type)
3486 // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "type"
3487 if (m_iconURL.isEmpty())
3488 m_iconURL = iconURL;
3489 else if (!type.isEmpty())
3490 m_iconURL = iconURL;