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 * Copyright (C) 2004 Apple Computer, Inc.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 * Boston, MA 02111-1307, USA.
25 #include "dom/dom_exception.h"
27 #include "xml/dom_textimpl.h"
28 #include "xml/dom_xmlimpl.h"
29 #include "xml/dom2_rangeimpl.h"
30 #include "xml/dom2_eventsimpl.h"
31 #include "xml/xml_tokenizer.h"
33 #include "xml_namespace_table.h"
35 #include "css/csshelper.h"
36 #include "css/cssstyleselector.h"
37 #include "css/css_stylesheetimpl.h"
38 #include "css/css_valueimpl.h"
39 #include "misc/htmlhashes.h"
40 #include "misc/helper.h"
41 #include "ecma/kjs_proxy.h"
42 #include "ecma/kjs_binding.h"
44 #include <qptrstack.h>
45 #include <qpaintdevicemetrics.h>
48 #include <kstaticdeleter.h>
50 #include "rendering/render_canvas.h"
51 #include "rendering/render_frames.h"
52 #include "rendering/render_image.h"
53 #include "rendering/render_object.h"
54 #include "render_arena.h"
56 #include "khtmlview.h"
57 #include "khtml_part.h"
59 #include <kglobalsettings.h>
60 #include <kstringhandler.h>
61 #include "khtml_settings.h"
62 #include "khtmlpart_p.h"
64 #include "html/html_baseimpl.h"
65 #include "html/html_blockimpl.h"
66 #include "html/html_canvasimpl.h"
67 #include "html/html_documentimpl.h"
68 #include "html/html_formimpl.h"
69 #include "html/html_headimpl.h"
70 #include "html/html_imageimpl.h"
71 #include "html/html_listimpl.h"
72 #include "html/html_miscimpl.h"
73 #include "html/html_tableimpl.h"
74 #include "html/html_objectimpl.h"
76 #include "cssvalues.h"
78 #include "editing/jsediting.h"
79 #include "editing/visible_position.h"
80 #include "editing/visible_text.h"
85 #include "xsl_stylesheetimpl.h"
86 #include "xslt_processorimpl.h"
90 #include "xbl/xbl_binding_manager.h"
91 using XBL::XBLBindingManager;
95 #include "KWQAccObjectCache.h"
96 #include "KWQLogging.h"
100 using namespace khtml;
102 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
104 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
105 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
107 const int cLayoutScheduleThreshold = 250;
109 DOMImplementationImpl *DOMImplementationImpl::m_instance = 0;
111 DOMImplementationImpl::DOMImplementationImpl()
115 DOMImplementationImpl::~DOMImplementationImpl()
119 bool DOMImplementationImpl::hasFeature ( const DOMString &feature, const DOMString &version )
121 QString lower = feature.string().lower();
122 if (lower == "core" || lower == "html" || lower == "xml")
123 return version.isEmpty() || version == "1.0" || version == "2.0";
127 || lower == "htmlevents"
128 || lower == "mouseevents"
129 || lower == "mutationevents"
131 || lower == "stylesheets"
132 || lower == "traversal"
133 || lower == "uievents"
135 return version.isEmpty() || version == "2.0";
139 DocumentTypeImpl *DOMImplementationImpl::createDocumentType( const DOMString &qualifiedName, const DOMString &publicId,
140 const DOMString &systemId, int &exceptioncode )
142 // Not mentioned in spec: throw NAMESPACE_ERR if no qualifiedName supplied
143 if (qualifiedName.isNull()) {
144 exceptioncode = DOMException::NAMESPACE_ERR;
148 // INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
149 if (!Element::khtmlValidQualifiedName(qualifiedName)) {
150 exceptioncode = DOMException::INVALID_CHARACTER_ERR;
154 // NAMESPACE_ERR: Raised if the qualifiedName is malformed.
155 if (Element::khtmlMalformedQualifiedName(qualifiedName)) {
156 exceptioncode = DOMException::NAMESPACE_ERR;
160 return new DocumentTypeImpl(this,0,qualifiedName,publicId,systemId);
163 DOMImplementationImpl* DOMImplementationImpl::getInterface(const DOMString& /*feature*/) const
169 DocumentImpl *DOMImplementationImpl::createDocument( const DOMString &namespaceURI, const DOMString &qualifiedName,
170 const DocumentType &doctype, int &exceptioncode )
174 // Not mentioned in spec: throw NAMESPACE_ERR if no qualifiedName supplied
175 if (qualifiedName.isNull()) {
176 exceptioncode = DOMException::NAMESPACE_ERR;
180 // INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
181 if (!Element::khtmlValidQualifiedName(qualifiedName)) {
182 exceptioncode = DOMException::INVALID_CHARACTER_ERR;
187 // - Raised if the qualifiedName is malformed,
188 // - if the qualifiedName has a prefix and the namespaceURI is null, or
189 // - if the qualifiedName has a prefix that is "xml" and the namespaceURI is different
190 // from "http://www.w3.org/XML/1998/namespace" [Namespaces].
193 DOMStringImpl *qname = qualifiedName.implementation();
194 for (i = 0; i < qname->l && colonpos < 0; i++) {
195 if ((*qname)[i] == ':')
199 if (Element::khtmlMalformedQualifiedName(qualifiedName) ||
200 (colonpos >= 0 && namespaceURI.isNull()) ||
201 (colonpos == 3 && qualifiedName[0] == 'x' && qualifiedName[1] == 'm' && qualifiedName[2] == 'l' &&
202 namespaceURI != "http://www.w3.org/XML/1998/namespace")) {
204 exceptioncode = DOMException::NAMESPACE_ERR;
208 DocumentTypeImpl *dtype = static_cast<DocumentTypeImpl*>(doctype.handle());
209 // WRONG_DOCUMENT_ERR: Raised if doctype has already been used with a different document or was
210 // created from a different implementation.
211 if (dtype && (dtype->getDocument() || dtype->implementation() != this)) {
212 exceptioncode = DOMException::WRONG_DOCUMENT_ERR;
216 // ### this is completely broken.. without a view it will not work (Dirk)
217 DocumentImpl *doc = new DocumentImpl(this, 0);
219 // now get the interesting parts of the doctype
220 // ### create new one if not there (currently always there)
221 if (doc->doctype() && dtype)
222 doc->doctype()->copyFrom(*dtype);
227 CSSStyleSheetImpl *DOMImplementationImpl::createCSSStyleSheet(DOMStringImpl */*title*/, DOMStringImpl *media,
228 int &/*exceptioncode*/)
230 // ### TODO : title should be set, and media could have wrong syntax, in which case we should
231 // generate an exception.
232 CSSStyleSheetImpl *parent = 0L;
233 CSSStyleSheetImpl *sheet = new CSSStyleSheetImpl(parent, DOMString());
234 sheet->setMedia(new MediaListImpl(sheet, media));
238 DocumentImpl *DOMImplementationImpl::createDocument( KHTMLView *v )
240 return new DocumentImpl(this, v);
243 HTMLDocumentImpl *DOMImplementationImpl::createHTMLDocument( KHTMLView *v )
245 return new HTMLDocumentImpl(this, v);
248 DOMImplementationImpl *DOMImplementationImpl::instance()
251 m_instance = new DOMImplementationImpl();
258 // ------------------------------------------------------------------------
260 KStaticDeleter< QPtrList<DocumentImpl> > s_changedDocumentsDeleter;
261 QPtrList<DocumentImpl> * DocumentImpl::changedDocuments = 0;
263 // KHTMLView might be 0
264 DocumentImpl::DocumentImpl(DOMImplementationImpl *_implementation, KHTMLView *v)
265 : NodeBaseImpl( new DocumentPtr() )
266 , m_domtree_version(0)
267 , m_imageLoadEventTimer(0)
269 , m_bindingManager(new XBLBindingManager(this))
272 , m_transformSource(NULL)
273 , m_transformSourceDocument(0)
276 , m_finishedParsing(this, SIGNAL(finishedParsing()))
277 , m_inPageCache(false)
279 , m_passwordFields(0)
282 , m_createRenderers(true)
283 , m_designMode(inherit)
284 , m_hasDashboardRegions(false)
285 , m_dashboardRegionsDirty(false)
288 document->doc = this;
291 m_paintDeviceMetrics = 0;
301 m_docLoader = new DocLoader(v->part(), this );
302 setPaintDevice( m_view );
305 m_docLoader = new DocLoader( 0, this );
307 visuallyOrdered = false;
308 m_loadingSheet = false;
310 m_docChanged = false;
315 // ### this should be created during parsing a <!DOCTYPE>
316 // not during construction. Not sure who added that and why (Dirk)
317 m_doctype = new DocumentTypeImpl(_implementation, document,
318 DOMString() /* qualifiedName */,
319 DOMString() /* publicId */,
320 DOMString() /* systemId */);
323 m_implementation = _implementation;
324 if (m_implementation)
325 m_implementation->ref();
328 m_textColor = Qt::black;
330 m_elementNameAlloc = 0;
331 m_elementNameCount = 0;
337 m_defaultView = new AbstractViewImpl(this);
338 m_defaultView->ref();
340 m_styleSheets = new StyleSheetListImpl;
341 m_styleSheets->ref();
343 m_styleSelectorDirty = false;
344 m_inStyleRecalc = false;
345 m_usesDescendantRules = false;
346 m_usesSiblingRules = false;
348 m_styleSelector = new CSSStyleSelector(this, m_usersheet, m_styleSheets, !inCompatMode());
349 m_windowEventListeners.setAutoDelete(true);
350 m_pendingStylesheets = 0;
351 m_ignorePendingStylesheets = false;
354 m_accessKeyDictValid = false;
357 resetVisitedLinkColor();
358 resetActiveLinkColor();
360 m_processingLoadEvent = false;
361 m_startTime.restart();
362 m_overMinimumLayoutThreshold = false;
367 DocumentImpl::~DocumentImpl()
371 assert(!m_inPageCache);
372 assert(m_savedRenderer == 0);
375 KJS::ScriptInterpreter::forgetDOMObjectsForDocument(this);
377 if (changedDocuments && m_docChanged)
378 changedDocuments->remove(this);
382 delete m_styleSelector;
384 if (m_elemSheet ) m_elemSheet->deref();
387 if (m_implementation)
388 m_implementation->deref();
389 delete m_paintDeviceMetrics;
391 if (m_elementNames) {
392 for (unsigned short id = 0; id < m_elementNameCount; id++)
393 m_elementNames[id]->deref();
394 delete [] m_elementNames;
397 for (unsigned short id = 0; id < m_attrNameCount; id++)
398 m_attrNames[id]->deref();
399 delete [] m_attrNames;
401 m_defaultView->deref();
402 m_styleSheets->deref();
405 m_focusNode->deref();
407 m_hoverNode->deref();
410 delete m_renderArena;
415 xmlFreeDoc((xmlDocPtr)m_transformSource);
416 if (m_transformSourceDocument)
417 m_transformSourceDocument->deref();
421 delete m_bindingManager;
442 void DocumentImpl::resetLinkColor()
444 m_linkColor = QColor(0, 0, 238);
447 void DocumentImpl::resetVisitedLinkColor()
449 m_visitedLinkColor = QColor(85, 26, 139);
452 void DocumentImpl::resetActiveLinkColor()
454 m_activeLinkColor.setNamedColor(QString("red"));
457 DocumentTypeImpl *DocumentImpl::doctype() const
462 DOMImplementationImpl *DocumentImpl::implementation() const
464 return m_implementation;
467 ElementImpl *DocumentImpl::documentElement() const
469 NodeImpl *n = firstChild();
470 while (n && n->nodeType() != Node::ELEMENT_NODE)
471 n = n->nextSibling();
472 return static_cast<ElementImpl*>(n);
475 ElementImpl *DocumentImpl::createElement( const DOMString &name, int &exceptioncode )
477 return new XMLElementImpl( document, name.implementation() );
480 DocumentFragmentImpl *DocumentImpl::createDocumentFragment( )
482 return new DocumentFragmentImpl( docPtr() );
485 TextImpl *DocumentImpl::createTextNode( const DOMString &data )
487 return new TextImpl( docPtr(), data);
490 CommentImpl *DocumentImpl::createComment ( const DOMString &data )
492 return new CommentImpl( docPtr(), data );
495 CDATASectionImpl *DocumentImpl::createCDATASection ( const DOMString &data )
497 return new CDATASectionImpl( docPtr(), data );
500 ProcessingInstructionImpl *DocumentImpl::createProcessingInstruction ( const DOMString &target, const DOMString &data )
502 return new ProcessingInstructionImpl( docPtr(),target,data);
505 Attr DocumentImpl::createAttribute( NodeImpl::Id id )
507 // Assume this is an HTML attribute, since createAttribute isn't namespace-aware. There's no harm to XML
508 // documents if we're wrong.
509 return new AttrImpl(0, docPtr(), new HTMLAttributeImpl(id, DOMString("").implementation()));
512 EntityReferenceImpl *DocumentImpl::createEntityReference ( const DOMString &name )
514 return new EntityReferenceImpl(docPtr(), name.implementation());
517 EditingTextImpl *DocumentImpl::createEditingTextNode(const DOMString &text)
519 return new EditingTextImpl(docPtr(), text);
522 CSSStyleDeclarationImpl *DocumentImpl::createCSSStyleDeclaration()
524 return new CSSMutableStyleDeclarationImpl;
527 NodeImpl *DocumentImpl::importNode(NodeImpl *importedNode, bool deep, int &exceptioncode)
529 NodeImpl *result = 0;
531 if(importedNode->nodeType() == Node::ELEMENT_NODE)
533 ElementImpl *tempElementImpl = createElementNS(getDocument()->namespaceURI(id()), importedNode->nodeName(), exceptioncode);
536 result = tempElementImpl;
538 if(static_cast<ElementImpl *>(importedNode)->attributes(true) && static_cast<ElementImpl *>(importedNode)->attributes(true)->length())
540 NamedNodeMapImpl *attr = static_cast<ElementImpl *>(importedNode)->attributes();
542 for(unsigned int i = 0; i < attr->length(); i++)
544 DOMString qualifiedName = attr->item(i)->nodeName();
545 DOMString value = attr->item(i)->nodeValue();
547 int colonpos = qualifiedName.find(':');
548 DOMString localName = qualifiedName;
551 localName.remove(0, colonpos + 1);
552 // ### extract and set new prefix
555 NodeImpl::Id nodeId = getDocument()->attrId(getDocument()->namespaceURI(id()), localName.implementation(), false /* allocate */);
556 tempElementImpl->setAttribute(nodeId, value.implementation(), exceptioncode);
558 if(exceptioncode != 0)
563 else if(importedNode->nodeType() == Node::TEXT_NODE)
565 result = createTextNode(importedNode->nodeValue());
568 else if(importedNode->nodeType() == Node::CDATA_SECTION_NODE)
570 result = createCDATASection(importedNode->nodeValue());
573 else if(importedNode->nodeType() == Node::ENTITY_REFERENCE_NODE)
574 result = createEntityReference(importedNode->nodeName());
575 else if(importedNode->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
577 result = createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue());
580 else if(importedNode->nodeType() == Node::COMMENT_NODE)
582 result = createComment(importedNode->nodeValue());
586 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
590 for(Node n = importedNode->firstChild(); !n.isNull(); n = n.nextSibling())
591 result->appendChild(importNode(n.handle(), true, exceptioncode), exceptioncode);
597 ElementImpl *DocumentImpl::createElementNS( const DOMString &_namespaceURI, const DOMString &_qualifiedName, int &exceptioncode)
600 QString qName = _qualifiedName.string();
601 int colonPos = qName.find(':',0);
603 if (_namespaceURI == XHTML_NAMESPACE) {
604 // User requested an element in the XHTML namespace - this means we create a HTML element
605 // (elements not in this namespace are treated as normal XML elements)
606 e = createHTMLElement(qName.mid(colonPos+1), exceptioncode);
609 if (e && colonPos >= 0) {
610 e->setPrefix(qName.left(colonPos), exceptioncode);
618 e = new XMLElementImpl( document, _qualifiedName.implementation(), _namespaceURI.implementation() );
623 ElementImpl *DocumentImpl::getElementById( const DOMString &elementId ) const
625 if (elementId.length() == 0) {
629 return m_elementsById.find(elementId.string());
633 void DocumentImpl::addElementById(const DOMString &elementId, ElementImpl *element)
635 QString qId = elementId.string();
637 if (m_elementsById.find(qId) == NULL) {
638 m_elementsById.insert(qId, element);
639 m_accessKeyDictValid = false;
643 void DocumentImpl::removeElementById(const DOMString &elementId, ElementImpl *element)
645 QString qId = elementId.string();
647 if (m_elementsById.find(qId) == element) {
648 m_elementsById.remove(qId);
649 m_accessKeyDictValid = false;
653 ElementImpl *DocumentImpl::getElementByAccessKey( const DOMString &key )
655 if (key.length() == 0)
658 QString k(key.string());
659 if (!m_accessKeyDictValid) {
660 m_elementsByAccessKey.clear();
663 for (n = this; n != 0; n = n->traverseNextNode()) {
664 if (!n->isElementNode())
666 const ElementImpl *elementImpl = static_cast<const ElementImpl *>(n);
667 DOMString accessKey(elementImpl->getAttribute(ATTR_ACCESSKEY));
668 if (!accessKey.isEmpty()) {
669 QString ak = accessKey.string().lower();
670 if (m_elementsByAccessKey.find(ak) == NULL)
671 m_elementsByAccessKey.insert(ak, elementImpl);
674 m_accessKeyDictValid = true;
676 return m_elementsByAccessKey.find(k);
679 void DocumentImpl::setTitle(DOMString _title)
687 KWQ(part())->setTitle(_title);
689 QString titleStr = m_title.string();
690 for (int i = 0; i < titleStr.length(); ++i)
691 if (titleStr[i] < ' ')
693 titleStr = titleStr.stripWhiteSpace();
695 if ( !part()->parentPart() ) {
696 if (titleStr.isNull() || titleStr.isEmpty()) {
697 // empty title... set window caption as the URL
699 url.setRef(QString::null);
700 url.setQuery(QString::null);
701 titleStr = url.url();
704 emit part()->setWindowCaption( KStringHandler::csqueeze( titleStr, 128 ) );
709 DOMString DocumentImpl::nodeName() const
714 unsigned short DocumentImpl::nodeType() const
716 return Node::DOCUMENT_NODE;
719 ElementImpl *DocumentImpl::createHTMLElement( const DOMString &name, int &exceptioncode )
721 if (!isValidName(name)) {
722 exceptioncode = DOMException::INVALID_CHARACTER_ERR;
725 return createHTMLElement(tagId(0, name.implementation(), false));
728 ElementImpl *DocumentImpl::createHTMLElement(unsigned short tagID)
733 return new HTMLHtmlElementImpl(docPtr());
735 return new HTMLHeadElementImpl(docPtr());
737 return new HTMLBodyElementImpl(docPtr());
741 return new HTMLBaseElementImpl(docPtr());
743 return new HTMLLinkElementImpl(docPtr());
745 return new HTMLMetaElementImpl(docPtr());
747 return new HTMLStyleElementImpl(docPtr());
749 return new HTMLTitleElementImpl(docPtr());
753 return new HTMLFrameElementImpl(docPtr());
755 return new HTMLFrameSetElementImpl(docPtr());
757 return new HTMLIFrameElementImpl(docPtr());
760 // ### FIXME: we need a way to set form dependency after we have made the form elements
762 return new HTMLFormElementImpl(docPtr());
764 return new HTMLButtonElementImpl(docPtr());
766 return new HTMLFieldSetElementImpl(docPtr());
768 return new HTMLInputElementImpl(docPtr());
770 return new HTMLIsIndexElementImpl(docPtr());
772 return new HTMLLabelElementImpl(docPtr());
774 return new HTMLLegendElementImpl(docPtr());
776 return new HTMLOptGroupElementImpl(docPtr());
778 return new HTMLOptionElementImpl(docPtr());
780 return new HTMLSelectElementImpl(docPtr());
782 return new HTMLTextAreaElementImpl(docPtr());
786 return new HTMLDListElementImpl(docPtr());
788 return new HTMLGenericElementImpl(docPtr(), tagID);
790 return new HTMLGenericElementImpl(docPtr(), tagID);
792 return new HTMLUListElementImpl(docPtr());
794 return new HTMLOListElementImpl(docPtr());
796 return new HTMLDirectoryElementImpl(docPtr());
798 return new HTMLMenuElementImpl(docPtr());
800 return new HTMLLIElementImpl(docPtr());
802 // formatting elements (block)
804 return new HTMLBlockquoteElementImpl(docPtr());
806 return new HTMLDivElementImpl(docPtr());
813 return new HTMLHeadingElementImpl(docPtr(), tagID);
815 return new HTMLHRElementImpl(docPtr());
817 return new HTMLParagraphElementImpl(docPtr());
821 return new HTMLPreElementImpl(docPtr(), tagID);
823 return new HTMLLayerElementImpl(docPtr());
827 return new HTMLBaseFontElementImpl(docPtr());
829 return new HTMLFontElementImpl(docPtr());
834 return new HTMLGenericElementImpl(docPtr(), tagID);
838 return new HTMLAnchorElementImpl(docPtr());
842 return new HTMLImageElementImpl(docPtr());
844 return new HTMLMapElementImpl(docPtr());
846 return new HTMLAreaElementImpl(docPtr());
848 return new HTMLCanvasElementImpl(docPtr());
850 // objects, applets and scripts
852 return new HTMLAppletElementImpl(docPtr());
854 return new HTMLEmbedElementImpl(docPtr());
856 return new HTMLObjectElementImpl(docPtr());
858 return new HTMLParamElementImpl(docPtr());
860 return new HTMLScriptElementImpl(docPtr());
864 return new HTMLTableElementImpl(docPtr());
866 return new HTMLTableCaptionElementImpl(docPtr());
869 return new HTMLTableColElementImpl(docPtr(), tagID);
871 return new HTMLTableRowElementImpl(docPtr());
874 return new HTMLTableCellElementImpl(docPtr(), tagID);
878 return new HTMLTableSectionElementImpl(docPtr(), tagID, false);
882 return new HTMLBRElementImpl(docPtr());
884 return new HTMLGenericElementImpl(docPtr(), tagID);
886 // elements with no special representation in the DOM
924 return new HTMLGenericElementImpl(docPtr(), tagID);
927 return new HTMLMarqueeElementImpl(docPtr());
931 kdDebug( 6020 ) << "Use document->createTextNode()" << endl;
938 QString DocumentImpl::nextState()
941 if (!m_state.isEmpty())
943 state = m_state.first();
944 m_state.remove(m_state.begin());
949 QStringList DocumentImpl::docState()
952 for (QPtrListIterator<NodeImpl> it(m_maintainsState); it.current(); ++it)
953 s.append(it.current()->state());
958 KHTMLPart *DocumentImpl::part() const
960 return m_view ? m_view->part() : 0;
963 RangeImpl *DocumentImpl::createRange()
965 return new RangeImpl( docPtr() );
968 NodeIteratorImpl *DocumentImpl::createNodeIterator(NodeImpl *root, unsigned long whatToShow,
969 NodeFilterImpl *filter, bool expandEntityReferences, int &exceptioncode)
972 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
975 return new NodeIteratorImpl(root, whatToShow, filter, expandEntityReferences);
978 TreeWalkerImpl *DocumentImpl::createTreeWalker(NodeImpl *root, unsigned long whatToShow,
979 NodeFilterImpl *filter, bool expandEntityReferences, int &exceptioncode)
982 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
985 return new TreeWalkerImpl(root, whatToShow, filter, expandEntityReferences);
988 void DocumentImpl::setDocumentChanged(bool b)
990 if (!changedDocuments)
991 changedDocuments = s_changedDocumentsDeleter.setObject( new QPtrList<DocumentImpl>() );
993 if (b && !m_docChanged)
994 changedDocuments->append(this);
995 else if (!b && m_docChanged)
996 changedDocuments->remove(this);
1000 m_accessKeyDictValid = false;
1003 void DocumentImpl::recalcStyle( StyleChange change )
1005 // qDebug("recalcStyle(%p)", this);
1008 if (m_inStyleRecalc)
1009 return; // Guard against re-entrancy. -dwh
1011 m_inStyleRecalc = true;
1013 if( !m_render ) goto bail_out;
1015 if ( change == Force ) {
1016 RenderStyle* oldStyle = m_render->style();
1017 if ( oldStyle ) oldStyle->ref();
1018 RenderStyle* _style = new (m_renderArena) RenderStyle();
1020 _style->setDisplay(BLOCK);
1021 _style->setVisuallyOrdered( visuallyOrdered );
1022 // ### make the font stuff _really_ work!!!!
1024 khtml::FontDef fontDef;
1025 QFont f = KGlobalSettings::generalFont();
1026 fontDef.family = *(f.firstFamily());
1027 fontDef.italic = f.italic();
1028 fontDef.weight = f.weight();
1030 bool printing = m_paintDevice && (m_paintDevice->devType() == QInternal::Printer);
1031 fontDef.usePrinterFont = printing;
1034 const KHTMLSettings *settings = m_view->part()->settings();
1036 if (printing && !settings->shouldPrintBackgrounds()) {
1037 _style->setShouldCorrectTextColor(true);
1040 QString stdfont = settings->stdFontName();
1041 if ( !stdfont.isEmpty() ) {
1042 fontDef.family.setFamily(stdfont);
1043 fontDef.family.appendFamily(0);
1045 m_styleSelector->setFontSize(fontDef, m_styleSelector->fontSizeForKeyword(CSS_VAL_MEDIUM, inCompatMode()));
1048 //kdDebug() << "DocumentImpl::attach: setting to charset " << settings->charset() << endl;
1049 _style->setFontDef(fontDef);
1050 _style->htmlFont().update( paintDeviceMetrics() );
1051 if ( inCompatMode() )
1052 _style->setHtmlHacks(true); // enable html specific rendering tricks
1054 StyleChange ch = diff( _style, oldStyle );
1055 if(m_render && ch != NoChange)
1056 m_render->setStyle(_style);
1057 if ( change != Force )
1060 _style->deref(m_renderArena);
1062 oldStyle->deref(m_renderArena);
1066 for (n = _first; n; n = n->nextSibling())
1067 if ( change>= Inherit || n->hasChangedChild() || n->changed() )
1068 n->recalcStyle( change );
1069 //kdDebug( 6020 ) << "TIME: recalcStyle() dt=" << qt.elapsed() << endl;
1071 if (changed() && m_view)
1075 setChanged( false );
1076 setHasChangedChild( false );
1077 setDocumentChanged( false );
1079 m_inStyleRecalc = false;
1082 void DocumentImpl::updateRendering()
1084 if (!hasChangedChild()) return;
1088 // kdDebug() << "UPDATERENDERING: "<<endl;
1090 StyleChange change = NoChange;
1092 if ( m_styleSelectorDirty ) {
1093 recalcStyleSelector();
1097 recalcStyle( change );
1099 // kdDebug() << "UPDATERENDERING time used="<<time.elapsed()<<endl;
1102 void DocumentImpl::updateDocumentsRendering()
1104 if (!changedDocuments)
1107 while (DocumentImpl* doc = changedDocuments->take()) {
1108 doc->m_docChanged = false;
1109 doc->updateRendering();
1113 void DocumentImpl::updateLayout()
1115 // FIXME: Dave's pretty sure we can remove this because
1116 // layout calls recalcStyle as needed.
1119 // Only do a layout if changes have occurred that make it necessary.
1120 if (m_view && renderer() && renderer()->needsLayout())
1124 // FIXME: This is a bad idea and needs to be removed eventually.
1125 // Other browsers load stylesheets before they continue parsing the web page.
1126 // Since we don't, we can run JavaScript code that needs answers before the
1127 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1128 // lets us get reasonable answers. The long term solution to this problem is
1129 // to instead suspend JavaScript execution.
1130 void DocumentImpl::updateLayoutIgnorePendingStylesheets()
1132 bool oldIgnore = m_ignorePendingStylesheets;
1134 if (!haveStylesheetsLoaded()) {
1135 m_ignorePendingStylesheets = true;
1136 updateStyleSelector();
1141 m_ignorePendingStylesheets = oldIgnore;
1144 void DocumentImpl::attach()
1146 assert(!attached());
1148 assert(!m_inPageCache);
1152 setPaintDevice( m_view );
1155 m_renderArena = new RenderArena();
1157 // Create the rendering tree
1158 m_render = new (m_renderArena) RenderCanvas(this, m_view);
1159 recalcStyle( Force );
1161 RenderObject* render = m_render;
1164 NodeBaseImpl::attach();
1168 void DocumentImpl::restoreRenderer(RenderObject* render)
1173 void DocumentImpl::detach()
1175 RenderObject* render = m_render;
1177 // indicate destruction mode, i.e. attached() but m_render == 0
1181 if (m_inPageCache) {
1183 getAccObjectCache()->detach(render);
1188 // Empty out these lists as a performance optimization, since detaching
1189 // all the individual render objects will cause all the RenderImage
1190 // objects to remove themselves from the lists.
1191 m_imageLoadEventDispatchSoonList.clear();
1192 m_imageLoadEventDispatchingList.clear();
1194 removeAllEventListenersFromAllNodes();
1196 NodeBaseImpl::detach();
1201 if (m_paintDevice == m_view)
1206 delete m_renderArena;
1211 void DocumentImpl::removeAllEventListenersFromAllNodes()
1213 m_windowEventListeners.clear();
1214 removeAllDisconnectedNodeEventListeners();
1215 for (NodeImpl *n = this; n; n = n->traverseNextNode()) {
1216 n->removeAllEventListeners();
1220 void DocumentImpl::registerDisconnectedNodeWithEventListeners(NodeImpl *node)
1222 m_disconnectedNodesWithEventListeners.insert(node, node);
1225 void DocumentImpl::unregisterDisconnectedNodeWithEventListeners(NodeImpl *node)
1227 m_disconnectedNodesWithEventListeners.remove(node);
1230 void DocumentImpl::removeAllDisconnectedNodeEventListeners()
1232 for (QPtrDictIterator<NodeImpl> iter(m_disconnectedNodesWithEventListeners);
1235 iter.current()->removeAllEventListeners();
1240 KWQAccObjectCache* DocumentImpl::getAccObjectCache()
1242 // The only document that actually has a KWQAccObjectCache is the top-level
1243 // document. This is because we need to be able to get from any KWQAccObject
1244 // to any other KWQAccObject on the same page. Using a single cache allows
1245 // lookups across nested webareas (i.e. multiple documents).
1248 // return already known top-level cache
1249 if (!ownerElement())
1252 // In some pages with frames, the cache is created before the sub-webarea is
1253 // inserted into the tree. Here, we catch that case and just toss the old
1254 // cache and start over.
1259 // look for top-level document
1260 ElementImpl *element = ownerElement();
1264 doc = element->getDocument();
1265 element = doc->ownerElement();
1268 // ask the top-level document for its cache
1269 return doc->getAccObjectCache();
1272 // this is the top-level document, so install a new cache
1273 m_accCache = new KWQAccObjectCache;
1278 void DocumentImpl::setVisuallyOrdered()
1280 visuallyOrdered = true;
1282 m_render->style()->setVisuallyOrdered(true);
1285 void DocumentImpl::updateSelection()
1290 RenderCanvas *canvas = static_cast<RenderCanvas*>(m_render);
1291 Selection s = part()->selection();
1293 canvas->clearSelection();
1295 if (KWQAccObjectCache::accessibilityEnabled())
1296 getAccObjectCache()->postNotificationToTopWebArea(renderer(), "AXSelectedTextChanged");
1300 Position startPos = VisiblePosition(s.start(), s.startAffinity(), khtml::VisiblePosition::INIT_UP).deepEquivalent();
1301 Position endPos = VisiblePosition(s.end(), s.endAffinity(), khtml::VisiblePosition::INIT_DOWN).deepEquivalent();
1302 if (startPos.isNotNull() && endPos.isNotNull()) {
1303 RenderObject *startRenderer = startPos.node()->renderer();
1304 RenderObject *endRenderer = endPos.node()->renderer();
1305 static_cast<RenderCanvas*>(m_render)->setSelection(startRenderer, startPos.offset(), endRenderer, endPos.offset());
1307 if (KWQAccObjectCache::accessibilityEnabled()) {
1308 getAccObjectCache()->postNotificationToTopWebArea(renderer(), "AXSelectedTextChanged");
1315 Tokenizer *DocumentImpl::createTokenizer()
1317 return newXMLTokenizer(docPtr(), m_view);
1320 void DocumentImpl::setPaintDevice( QPaintDevice *dev )
1322 if (m_paintDevice == dev) {
1325 m_paintDevice = dev;
1326 delete m_paintDeviceMetrics;
1327 m_paintDeviceMetrics = dev ? new QPaintDeviceMetrics( dev ) : 0;
1330 void DocumentImpl::open( )
1332 if (parsing()) return;
1336 // This is work that we should probably do in clear(), but we can't have it
1337 // happen when openInternal() is called unless we reorganize KHTMLPart code.
1339 DocumentImpl *parent = parentDocument();
1340 setBaseURL(parent ? parent->baseURL() : QString());
1343 void DocumentImpl::openInternal()
1349 m_tokenizer = createTokenizer();
1350 connect(m_tokenizer,SIGNAL(finishedParsing()),this,SIGNAL(finishedParsing()));
1352 if (m_view && m_view->part()->jScript()) {
1353 m_view->part()->jScript()->setSourceFile(m_url,""); //fixme
1357 HTMLElementImpl* DocumentImpl::body()
1359 NodeImpl *de = documentElement();
1363 // try to prefer a FRAMESET element over BODY
1365 for (NodeImpl* i = de->firstChild(); i; i = i->nextSibling()) {
1366 if (i->id() == ID_FRAMESET)
1367 return static_cast<HTMLElementImpl*>(i);
1369 if (i->id() == ID_BODY)
1372 return static_cast<HTMLElementImpl *>(body);
1375 void DocumentImpl::close()
1377 // First fire the onload.
1379 bool wasLocationChangePending = part() && part()->isScheduledLocationChangePending();
1380 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1383 m_processingLoadEvent = true;
1385 // We have to clear the tokenizer, in case someone document.write()s from the
1386 // onLoad event handler, as in Radar 3206524
1390 // Create a body element if we don't already have one.
1391 // In the case of Radar 3758785, the window.onload was set in some javascript, but never fired because there was no body.
1392 // This behavior now matches Firefox and IE.
1393 HTMLElementImpl *body = this->body();
1394 if (!body && isHTMLDocument()) {
1395 NodeImpl *de = documentElement();
1397 body = new HTMLBodyElementImpl(docPtr());
1398 int exceptionCode = 0;
1399 de->appendChild(body, exceptionCode);
1400 if (exceptionCode != 0)
1406 dispatchImageLoadEventsNow();
1407 body->dispatchWindowEvent(EventImpl::LOAD_EVENT, false, false);
1409 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1410 if (!ownerElement())
1411 printf("onload fired at %d\n", elapsedTime());
1415 m_processingLoadEvent = false;
1418 // Make sure both the initial layout and reflow happen after the onload
1419 // fires. This will improve onload scores, and other browsers do it.
1420 // If they wanna cheat, we can too. -dwh
1422 bool isLocationChangePending = part() && part()->isScheduledLocationChangePending();
1424 if (doload && isLocationChangePending && m_startTime.elapsed() < cLayoutScheduleThreshold) {
1425 // Just bail out. Before or during the onload we were shifted to another page.
1426 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1429 view()->unscheduleRelayout();
1433 // The initial layout happens here.
1434 DocumentImpl::closeInternal(!doload);
1436 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1437 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1438 // layout/painting now would be pointless.
1440 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1443 // Always do a layout after loading if needed.
1444 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1448 if (renderer() && KWQAccObjectCache::accessibilityEnabled())
1449 getAccObjectCache()->postNotification(renderer(), "AXLoadComplete");
1454 void DocumentImpl::closeInternal( bool checkTokenizer )
1456 if (parsing() || (checkTokenizer && !m_tokenizer)) return;
1458 // on an explicit document.close(), the tokenizer might still be waiting on scripts,
1459 // and in that case we don't want to destroy it because that will prevent the
1460 // scripts from getting processed.
1461 if (m_tokenizer && !m_tokenizer->isWaitingForScripts()) {
1467 m_view->part()->checkEmitLoadEvent();
1470 void DocumentImpl::setParsing(bool b)
1473 if (!m_bParsing && view())
1474 view()->scheduleRelayout();
1476 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1477 if (!ownerElement() && !m_bParsing)
1478 printf("Parsing finished at %d\n", elapsedTime());
1482 bool DocumentImpl::shouldScheduleLayout()
1484 // We can update layout if:
1485 // (a) we actually need a layout
1486 // (b) our stylesheets are all loaded
1487 // (c) we have a <body>
1488 return (renderer() && renderer()->needsLayout() && haveStylesheetsLoaded() &&
1489 documentElement() && documentElement()->renderer() &&
1490 (documentElement()->id() != ID_HTML || body()));
1493 int DocumentImpl::minimumLayoutDelay()
1495 if (m_overMinimumLayoutThreshold)
1498 int elapsed = m_startTime.elapsed();
1499 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1501 // We'll want to schedule the timer to fire at the minimum layout threshold.
1502 return kMax(0, cLayoutScheduleThreshold - elapsed);
1505 int DocumentImpl::elapsedTime() const
1507 return m_startTime.elapsed();
1510 void DocumentImpl::write( const DOMString &text )
1512 write(text.string());
1515 void DocumentImpl::write( const QString &text )
1517 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1518 if (!ownerElement())
1519 printf("Beginning a document.write at %d\n", elapsedTime());
1524 write(QString::fromLatin1("<html>"));
1526 m_tokenizer->write(text, false);
1528 if (m_view && m_view->part()->jScript())
1529 m_view->part()->jScript()->appendSourceFile(m_url,text);
1531 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1532 if (!ownerElement())
1533 printf("Ending a document.write at %d\n", elapsedTime());
1537 void DocumentImpl::writeln( const DOMString &text )
1540 write(DOMString("\n"));
1543 void DocumentImpl::finishParsing()
1545 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1546 if (!ownerElement())
1547 printf("Received all data at %d\n", elapsedTime());
1550 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1551 // finish() is called:
1552 // (1) All remaining data is parsed, document isn't loaded yet
1553 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1554 // (3) Data is still remaining to be parsed.
1556 m_tokenizer->finish();
1559 void DocumentImpl::clear()
1565 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
1566 for (; it.current();)
1567 m_windowEventListeners.removeRef(it.current());
1570 void DocumentImpl::setURL(const QString& url)
1573 if (m_styleSelector)
1574 m_styleSelector->setEncodedURL(m_url);
1577 void DocumentImpl::setStyleSheet(const DOMString &url, const DOMString &sheet)
1579 // kdDebug( 6030 ) << "HTMLDocument::setStyleSheet()" << endl;
1580 m_sheet = new CSSStyleSheetImpl(this, url);
1582 m_sheet->parseString(sheet);
1583 m_loadingSheet = false;
1585 updateStyleSelector();
1588 void DocumentImpl::setUserStyleSheet( const QString& sheet )
1590 if ( m_usersheet != sheet ) {
1591 m_usersheet = sheet;
1592 updateStyleSelector();
1596 CSSStyleSheetImpl* DocumentImpl::elementSheet()
1599 m_elemSheet = new CSSStyleSheetImpl(this, baseURL() );
1605 void DocumentImpl::determineParseMode( const QString &/*str*/ )
1607 // For XML documents use strict parse mode. HTML docs will override this method to
1608 // determine their parse mode.
1611 kdDebug(6020) << " using strict parseMode" << endl;
1614 // Please see if there`s a possibility to merge that code
1615 // with the next function and getElementByID().
1616 NodeImpl *DocumentImpl::findElement( Id id )
1618 QPtrStack<NodeImpl> nodeStack;
1619 NodeImpl *current = _first;
1625 if(nodeStack.isEmpty()) break;
1626 current = nodeStack.pop();
1627 current = current->nextSibling();
1631 if(current->id() == id)
1634 NodeImpl *child = current->firstChild();
1637 nodeStack.push(current);
1642 current = current->nextSibling();
1650 NodeImpl *DocumentImpl::nextFocusNode(NodeImpl *fromNode)
1652 unsigned short fromTabIndex;
1655 // No starting node supplied; begin with the top of the document
1658 int lowestTabIndex = 65535;
1659 for (n = this; n != 0; n = n->traverseNextNode()) {
1660 if (n->isKeyboardFocusable()) {
1661 if ((n->tabIndex() > 0) && (n->tabIndex() < lowestTabIndex))
1662 lowestTabIndex = n->tabIndex();
1666 if (lowestTabIndex == 65535)
1669 // Go to the first node in the document that has the desired tab index
1670 for (n = this; n != 0; n = n->traverseNextNode()) {
1671 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestTabIndex))
1678 fromTabIndex = fromNode->tabIndex();
1681 if (fromTabIndex == 0) {
1682 // Just need to find the next selectable node after fromNode (in document order) that doesn't have a tab index
1683 NodeImpl *n = fromNode->traverseNextNode();
1684 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1685 n = n->traverseNextNode();
1689 // Find the lowest tab index out of all the nodes except fromNode, that is greater than or equal to fromNode's
1690 // tab index. For nodes with the same tab index as fromNode, we are only interested in those that come after
1691 // fromNode in document order.
1692 // If we don't find a suitable tab index, the next focus node will be one with a tab index of 0.
1693 unsigned short lowestSuitableTabIndex = 65535;
1696 bool reachedFromNode = false;
1697 for (n = this; n != 0; n = n->traverseNextNode()) {
1698 if (n->isKeyboardFocusable() &&
1699 ((reachedFromNode && (n->tabIndex() >= fromTabIndex)) ||
1700 (!reachedFromNode && (n->tabIndex() > fromTabIndex))) &&
1701 (n->tabIndex() < lowestSuitableTabIndex) &&
1704 // We found a selectable node with a tab index at least as high as fromNode's. Keep searching though,
1705 // as there may be another node which has a lower tab index but is still suitable for use.
1706 lowestSuitableTabIndex = n->tabIndex();
1710 reachedFromNode = true;
1713 if (lowestSuitableTabIndex == 65535) {
1714 // No next node with a tab index -> just take first node with tab index of 0
1716 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1717 n = n->traverseNextNode();
1721 // Search forwards from fromNode
1722 for (n = fromNode->traverseNextNode(); n != 0; n = n->traverseNextNode()) {
1723 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1727 // The next node isn't after fromNode, start from the beginning of the document
1728 for (n = this; n != fromNode; n = n->traverseNextNode()) {
1729 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1733 assert(false); // should never get here
1738 NodeImpl *DocumentImpl::previousFocusNode(NodeImpl *fromNode)
1740 NodeImpl *lastNode = this;
1741 while (lastNode->lastChild())
1742 lastNode = lastNode->lastChild();
1745 // No starting node supplied; begin with the very last node in the document
1748 int highestTabIndex = 0;
1749 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1750 if (n->isKeyboardFocusable()) {
1751 if (n->tabIndex() == 0)
1753 else if (n->tabIndex() > highestTabIndex)
1754 highestTabIndex = n->tabIndex();
1758 // No node with a tab index of 0; just go to the last node with the highest tab index
1759 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1760 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1767 unsigned short fromTabIndex = fromNode->tabIndex();
1769 if (fromTabIndex == 0) {
1770 // Find the previous selectable node before fromNode (in document order) that doesn't have a tab index
1771 NodeImpl *n = fromNode->traversePreviousNode();
1772 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1773 n = n->traversePreviousNode();
1777 // No previous nodes with a 0 tab index, go to the last node in the document that has the highest tab index
1778 int highestTabIndex = 0;
1779 for (n = this; n != 0; n = n->traverseNextNode()) {
1780 if (n->isKeyboardFocusable() && (n->tabIndex() > highestTabIndex))
1781 highestTabIndex = n->tabIndex();
1784 if (highestTabIndex == 0)
1787 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1788 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1792 assert(false); // should never get here
1796 // Find the lowest tab index out of all the nodes except fromNode, that is less than or equal to fromNode's
1797 // tab index. For nodes with the same tab index as fromNode, we are only interested in those before
1799 // If we don't find a suitable tab index, then there will be no previous focus node.
1800 unsigned short highestSuitableTabIndex = 0;
1803 bool reachedFromNode = false;
1804 for (n = this; n != 0; n = n->traverseNextNode()) {
1805 if (n->isKeyboardFocusable() &&
1806 ((!reachedFromNode && (n->tabIndex() <= fromTabIndex)) ||
1807 (reachedFromNode && (n->tabIndex() < fromTabIndex))) &&
1808 (n->tabIndex() > highestSuitableTabIndex) &&
1811 // We found a selectable node with a tab index no higher than fromNode's. Keep searching though, as
1812 // there may be another node which has a higher tab index but is still suitable for use.
1813 highestSuitableTabIndex = n->tabIndex();
1817 reachedFromNode = true;
1820 if (highestSuitableTabIndex == 0) {
1821 // No previous node with a tab index. Since the order specified by HTML is nodes with tab index > 0
1822 // first, this means that there is no previous node.
1826 // Search backwards from fromNode
1827 for (n = fromNode->traversePreviousNode(); n != 0; n = n->traversePreviousNode()) {
1828 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1831 // The previous node isn't before fromNode, start from the end of the document
1832 for (n = lastNode; n != fromNode; n = n->traversePreviousNode()) {
1833 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1837 assert(false); // should never get here
1843 int DocumentImpl::nodeAbsIndex(NodeImpl *node)
1845 assert(node->getDocument() == this);
1848 for (NodeImpl *n = node; n && n != this; n = n->traversePreviousNode())
1853 NodeImpl *DocumentImpl::nodeWithAbsIndex(int absIndex)
1856 for (int i = 0; n && (i < absIndex); i++) {
1857 n = n->traverseNextNode();
1862 void DocumentImpl::processHttpEquiv(const DOMString &equiv, const DOMString &content)
1864 assert(!equiv.isNull() && !content.isNull());
1866 KHTMLPart *part = getDocument()->part();
1868 if (strcasecmp(equiv, "default-style") == 0) {
1869 // The preferred style set has been overridden as per section
1870 // 14.3.2 of the HTML4.0 specification. We need to update the
1871 // sheet used variable and then update our style selector.
1872 // For more info, see the test at:
1873 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1875 part->d->m_sheetUsed = content.string();
1876 m_preferredStylesheetSet = content;
1877 updateStyleSelector();
1879 else if(strcasecmp(equiv, "refresh") == 0 && part->metaRefreshEnabled())
1881 // get delay and url
1882 QString str = content.string().stripWhiteSpace();
1883 int pos = str.find(QRegExp("[;,]"));
1885 pos = str.find(QRegExp("[ \t]"));
1887 if (pos == -1) // There can be no url (David)
1891 delay = str.toInt(&ok);
1893 // We want a new history item if the refresh timeout > 1 second
1894 if(ok && part) part->scheduleRedirection(delay, part->url().url(), delay <= 1);
1896 if(ok && part) part->scheduleRedirection(delay, part->url().url() );
1901 delay = str.left(pos).stripWhiteSpace().toDouble(&ok);
1904 while(pos < (int)str.length() && str[pos].isSpace()) pos++;
1906 if(str.find("url", 0, false ) == 0) str = str.mid(3);
1907 str = str.stripWhiteSpace();
1908 if ( str.length() && str[0] == '=' ) str = str.mid( 1 ).stripWhiteSpace();
1909 str = parseURL( DOMString(str) ).string();
1912 // We want a new history item if the refresh timeout > 1 second
1913 part->scheduleRedirection(delay, getDocument()->completeURL( str ), delay <= 1);
1915 part->scheduleRedirection(delay, getDocument()->completeURL( str ));
1919 else if(strcasecmp(equiv, "expires") == 0)
1921 QString str = content.string().stripWhiteSpace();
1922 time_t expire_date = str.toLong();
1924 m_docLoader->setExpireDate(expire_date);
1926 else if(strcasecmp(equiv, "pragma") == 0 || strcasecmp(equiv, "cache-control") == 0 && part)
1928 QString str = content.string().lower().stripWhiteSpace();
1929 KURL url = part->url();
1930 if ((str == "no-cache") && url.protocol().startsWith("http"))
1932 KIO::http_update_cache(url, true, 0);
1935 else if( (strcasecmp(equiv, "set-cookie") == 0))
1937 // ### make setCookie work on XML documents too; e.g. in case of <html:meta .....>
1938 HTMLDocumentImpl *d = static_cast<HTMLDocumentImpl *>(this);
1939 d->setCookie(content);
1943 bool DocumentImpl::prepareMouseEvent( bool readonly, int _x, int _y, MouseEvent *ev )
1946 assert(m_render->isCanvas());
1947 RenderObject::NodeInfo renderInfo(readonly, ev->type == MousePress);
1948 bool isInside = m_render->layer()->hitTest(renderInfo, _x, _y);
1949 ev->innerNode = renderInfo.innerNode();
1951 if (renderInfo.URLElement()) {
1952 assert(renderInfo.URLElement()->isElementNode());
1953 ElementImpl* e = static_cast<ElementImpl*>(renderInfo.URLElement());
1954 DOMString href = khtml::parseURL(e->getAttribute(ATTR_HREF));
1955 DOMString target = e->getAttribute(ATTR_TARGET);
1957 if (!target.isNull() && !href.isNull()) {
1958 ev->target = target;
1963 // qDebug("url: *%s*", ev->url.string().latin1());
1976 // DOM Section 1.1.1
1977 bool DocumentImpl::childAllowed( NodeImpl *newChild )
1979 // Documents may contain a maximum of one Element child
1980 if (newChild->nodeType() == Node::ELEMENT_NODE) {
1982 for (c = firstChild(); c; c = c->nextSibling()) {
1983 if (c->nodeType() == Node::ELEMENT_NODE)
1988 // Documents may contain a maximum of one DocumentType child
1989 if (newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
1991 for (c = firstChild(); c; c = c->nextSibling()) {
1992 if (c->nodeType() == Node::DOCUMENT_TYPE_NODE)
1997 return childTypeAllowed(newChild->nodeType());
2000 bool DocumentImpl::childTypeAllowed( unsigned short type )
2003 case Node::ELEMENT_NODE:
2004 case Node::PROCESSING_INSTRUCTION_NODE:
2005 case Node::COMMENT_NODE:
2006 case Node::DOCUMENT_TYPE_NODE:
2013 NodeImpl *DocumentImpl::cloneNode ( bool /*deep*/ )
2015 // Spec says cloning Document nodes is "implementation dependent"
2016 // so we do not support it...
2020 NodeImpl::Id DocumentImpl::attrId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
2022 // Each document maintains a mapping of attrname -> id for every attr name
2023 // encountered in the document.
2024 // For attrnames without a prefix (no qualified element name) and without matching
2025 // namespace, the value defined in misc/htmlattrs.h is used.
2026 NodeImpl::Id id = 0;
2028 // First see if it's a HTML attribute name
2029 QConstString n(_name->s, _name->l);
2030 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
2031 // we're in HTML namespace if we know the tag.
2032 // xhtml is lower case - case sensitive, easy to implement
2033 if ( htmlMode() == XHtml && (id = getAttrID(n.string().ascii(), _name->l)) )
2035 // compatibility: upper case - case insensitive
2036 if ( htmlMode() != XHtml && (id = getAttrID(n.string().lower().ascii(), _name->l )) )
2039 // ok, the fast path didn't work out, we need the full check
2042 // now lets find out the namespace
2043 Q_UINT16 ns = noNamespace;
2044 if (_namespaceURI) {
2045 DOMString nsU(_namespaceURI);
2046 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
2048 ns = (Q_UINT16)nsID;
2051 // Look in the m_attrNames array for the name
2052 // ### yeah, this is lame. use a dictionary / map instead
2053 DOMString nme(n.string());
2054 // compatibility mode has to store upper case
2055 if (htmlMode() != XHtml) nme = nme.upper();
2056 for (id = 0; id < m_attrNameCount; id++)
2057 if (DOMString(m_attrNames[id]) == nme)
2058 return makeId(ns, ATTR_LAST_ATTR+id);
2061 if (readonly) return 0;
2063 // Name not found in m_attrNames, so let's add it
2064 // ### yeah, this is lame. use a dictionary / map instead
2065 if (m_attrNameCount+1 > m_attrNameAlloc) {
2066 m_attrNameAlloc += 100;
2067 DOMStringImpl **newNames = new DOMStringImpl* [m_attrNameAlloc];
2070 for (i = 0; i < m_attrNameCount; i++)
2071 newNames[i] = m_attrNames[i];
2072 delete [] m_attrNames;
2074 m_attrNames = newNames;
2077 id = m_attrNameCount++;
2078 m_attrNames[id] = nme.implementation();
2079 m_attrNames[id]->ref();
2081 return makeId(ns, ATTR_LAST_ATTR+id);
2084 DOMString DocumentImpl::attrName(NodeImpl::Id _id) const
2087 if (localNamePart(_id) >= ATTR_LAST_ATTR)
2088 result = m_attrNames[localNamePart(_id)-ATTR_LAST_ATTR];
2090 result = getAttrName(_id);
2092 // Attribute names are always lowercase in the DOM for both
2094 if (getDocument()->isHTMLDocument() ||
2095 getDocument()->htmlMode() == DocumentImpl::XHtml)
2096 return result.lower();
2101 NodeImpl::Id DocumentImpl::tagId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
2103 if (!_name) return 0;
2104 // Each document maintains a mapping of tag name -> id for every tag name encountered
2106 NodeImpl::Id id = 0;
2108 // First see if it's a HTML element name
2109 QConstString n(_name->s, _name->l);
2110 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
2111 // we're in HTML namespace if we know the tag.
2112 // xhtml is lower case - case sensitive, easy to implement
2113 if ( htmlMode() == XHtml && (id = getTagID(n.string().ascii(), _name->l)) )
2115 // compatibility: upper case - case insensitive
2116 if ( htmlMode() != XHtml && (id = getTagID(n.string().lower().ascii(), _name->l )) )
2119 // ok, the fast path didn't work out, we need the full check
2122 // now lets find out the namespace
2123 Q_UINT16 ns = noNamespace;
2124 if (_namespaceURI) {
2125 DOMString nsU(_namespaceURI);
2126 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
2128 ns = (Q_UINT16)nsID;
2131 // Look in the m_elementNames array for the name
2132 // ### yeah, this is lame. use a dictionary / map instead
2133 DOMString nme(n.string());
2134 // compatibility mode has to store upper case
2135 if (htmlMode() != XHtml) nme = nme.upper();
2136 for (id = 0; id < m_elementNameCount; id++)
2137 if (DOMString(m_elementNames[id]) == nme)
2138 return makeId(ns, ID_LAST_TAG + 1 + id);
2141 if (readonly) return 0;
2143 // Name not found in m_elementNames, so let's add it
2144 if (m_elementNameCount+1 > m_elementNameAlloc) {
2145 m_elementNameAlloc += 100;
2146 DOMStringImpl **newNames = new DOMStringImpl* [m_elementNameAlloc];
2147 // ### yeah, this is lame. use a dictionary / map instead
2148 if (m_elementNames) {
2150 for (i = 0; i < m_elementNameCount; i++)
2151 newNames[i] = m_elementNames[i];
2152 delete [] m_elementNames;
2154 m_elementNames = newNames;
2157 id = m_elementNameCount++;
2158 m_elementNames[id] = nme.implementation();
2159 m_elementNames[id]->ref();
2161 return makeId(ns, ID_LAST_TAG + 1 + id);
2164 DOMString DocumentImpl::tagName(NodeImpl::Id _id) const
2166 if (localNamePart(_id) > ID_LAST_TAG)
2167 return m_elementNames[localNamePart(_id) - (ID_LAST_TAG + 1)];
2169 // ### put them in a cache
2170 if (getDocument()->htmlMode() == DocumentImpl::XHtml)
2171 return getTagName(_id).lower();
2173 return getTagName(_id);
2178 DOMStringImpl* DocumentImpl::namespaceURI(NodeImpl::Id _id) const
2180 if (_id <= ID_LAST_TAG)
2181 return htmlMode() == XHtml ? XmlNamespaceTable::getNamespaceURI(xhtmlNamespace).implementation() : 0;
2183 unsigned short ns = _id >> 16;
2187 return XmlNamespaceTable::getNamespaceURI(ns).implementation();
2190 StyleSheetListImpl* DocumentImpl::styleSheets()
2192 return m_styleSheets;
2196 DocumentImpl::preferredStylesheetSet()
2198 return m_preferredStylesheetSet;
2202 DocumentImpl::selectedStylesheetSet()
2204 return view() ? view()->part()->d->m_sheetUsed : DOMString();
2208 DocumentImpl::setSelectedStylesheetSet(const DOMString& aString)
2211 view()->part()->d->m_sheetUsed = aString.string();
2212 updateStyleSelector();
2214 renderer()->repaint();
2218 // This method is called whenever a top-level stylesheet has finished loading.
2219 void DocumentImpl::stylesheetLoaded()
2221 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2222 assert(m_pendingStylesheets > 0);
2224 m_pendingStylesheets--;
2226 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2227 if (!ownerElement())
2228 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2231 updateStyleSelector();
2234 void DocumentImpl::updateStyleSelector()
2236 // Don't bother updating, since we haven't loaded all our style info yet.
2237 if (!haveStylesheetsLoaded())
2240 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2241 if (!ownerElement())
2242 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2245 recalcStyleSelector();
2249 m_styleSelectorDirty = true;
2252 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2253 if (!ownerElement())
2254 printf("Finished update of style selector at time %d\n", elapsedTime());
2258 renderer()->setNeedsLayoutAndMinMaxRecalc();
2260 view()->scheduleRelayout();
2265 QStringList DocumentImpl::availableStyleSheets() const
2267 return m_availableSheets;
2270 void DocumentImpl::recalcStyleSelector()
2272 if ( !m_render || !attached() ) return;
2274 QPtrList<StyleSheetImpl> oldStyleSheets = m_styleSheets->styleSheets;
2275 m_styleSheets->styleSheets.clear();
2276 m_availableSheets.clear();
2278 for (n = this; n; n = n->traverseNextNode()) {
2279 StyleSheetImpl *sheet = 0;
2281 if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
2283 // Processing instruction (XML documents only)
2284 ProcessingInstructionImpl* pi = static_cast<ProcessingInstructionImpl*>(n);
2285 sheet = pi->sheet();
2288 applyXSLTransform(pi);
2292 if (!sheet && !pi->localHref().isEmpty())
2294 // Processing instruction with reference to an element in this document - e.g.
2295 // <?xml-stylesheet href="#mystyle">, with the element
2296 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2298 ElementImpl* elem = getElementById(pi->localHref());
2300 DOMString sheetText("");
2302 for (c = elem->firstChild(); c; c = c->nextSibling()) {
2303 if (c->nodeType() == Node::TEXT_NODE || c->nodeType() == Node::CDATA_SECTION_NODE)
2304 sheetText += c->nodeValue();
2307 CSSStyleSheetImpl *cssSheet = new CSSStyleSheetImpl(this);
2308 cssSheet->parseString(sheetText);
2309 pi->setStyleSheet(cssSheet);
2315 else if (n->isHTMLElement() && (n->id() == ID_LINK || n->id() == ID_STYLE)) {
2316 ElementImpl *e = static_cast<ElementImpl *>(n);
2317 QString title = e->getAttribute( ATTR_TITLE ).string();
2318 bool enabledViaScript = false;
2319 if (n->id() == ID_LINK) {
2321 HTMLLinkElementImpl* l = static_cast<HTMLLinkElementImpl*>(n);
2322 if (l->isLoading() || l->isDisabled())
2325 title = QString::null;
2326 enabledViaScript = l->isEnabledViaScript();
2329 // Get the current preferred styleset. This is the
2330 // set of sheets that will be enabled.
2331 if ( n->id() == ID_LINK )
2332 sheet = static_cast<HTMLLinkElementImpl*>(n)->sheet();
2335 sheet = static_cast<HTMLStyleElementImpl*>(n)->sheet();
2337 // Check to see if this sheet belongs to a styleset
2338 // (thus making it PREFERRED or ALTERNATE rather than
2340 if (!enabledViaScript && !title.isEmpty()) {
2341 // Yes, we have a title.
2342 if (m_preferredStylesheetSet.isEmpty()) {
2343 // No preferred set has been established. If
2344 // we are NOT an alternate sheet, then establish
2345 // us as the preferred set. Otherwise, just ignore
2347 QString rel = e->getAttribute( ATTR_REL ).string();
2348 if (n->id() == ID_STYLE || !rel.contains("alternate"))
2349 m_preferredStylesheetSet = view()->part()->d->m_sheetUsed = title;
2352 if (!m_availableSheets.contains( title ) )
2353 m_availableSheets.append( title );
2355 if (title != m_preferredStylesheetSet)
2362 m_styleSheets->styleSheets.append(sheet);
2365 // For HTML documents, stylesheets are not allowed within/after the <BODY> tag. So we
2366 // can stop searching here.
2367 if (isHTMLDocument() && n->id() == ID_BODY)
2371 // De-reference all the stylesheets in the old list
2372 QPtrListIterator<StyleSheetImpl> it(oldStyleSheets);
2373 for (; it.current(); ++it)
2374 it.current()->deref();
2376 // Create a new style selector
2377 delete m_styleSelector;
2378 QString usersheet = m_usersheet;
2379 if ( m_view && m_view->mediaType() == "print" )
2380 usersheet += m_printSheet;
2381 m_styleSelector = new CSSStyleSelector(this, usersheet, m_styleSheets, !inCompatMode());
2382 m_styleSelector->setEncodedURL(m_url);
2383 m_styleSelectorDirty = false;
2386 void DocumentImpl::setHoverNode(NodeImpl* newHoverNode)
2388 if (m_hoverNode != newHoverNode) {
2390 m_hoverNode->deref();
2391 m_hoverNode = newHoverNode;
2399 bool DocumentImpl::relinquishesEditingFocus(NodeImpl *node)
2402 assert(node->isContentEditable());
2404 NodeImpl *rootImpl = node->rootEditableElement();
2405 if (!part() || !rootImpl)
2408 Node root(rootImpl);
2409 Range range(root, 0, root, rootImpl->childNodeCount());
2410 return part()->shouldEndEditing(range);
2413 bool DocumentImpl::acceptsEditingFocus(NodeImpl *node)
2416 assert(node->isContentEditable());
2418 NodeImpl *rootImpl = node->rootEditableElement();
2419 if (!part() || !rootImpl)
2422 Node root(rootImpl);
2423 Range range(root, 0, root, rootImpl->childNodeCount());
2424 return part()->shouldBeginEditing(range);
2427 const QValueList<DashboardRegionValue> & DocumentImpl::dashboardRegions() const
2429 return m_dashboardRegions;
2432 void DocumentImpl::setDashboardRegions (const QValueList<DashboardRegionValue>& regions)
2434 m_dashboardRegions = regions;
2435 setDashboardRegionsDirty (false);
2440 bool DocumentImpl::setFocusNode(NodeImpl *newFocusNode)
2442 // Make sure newFocusNode is actually in this document
2443 if (newFocusNode && (newFocusNode->getDocument() != this))
2446 if (m_focusNode == newFocusNode)
2450 if (m_focusNode && m_focusNode->isContentEditable() && !relinquishesEditingFocus(m_focusNode))
2454 bool focusChangeBlocked = false;
2455 NodeImpl *oldFocusNode = m_focusNode;
2458 // Remove focus from the existing focus node (if any)
2460 // This goes hand in hand with the Qt focus setting below.
2461 if (!newFocusNode && getDocument()->view()) {
2462 getDocument()->view()->setFocus();
2465 if (oldFocusNode->active())
2466 oldFocusNode->setActive(false);
2468 oldFocusNode->setFocus(false);
2469 oldFocusNode->dispatchHTMLEvent(EventImpl::BLUR_EVENT, false, false);
2470 if (m_focusNode != 0) {
2471 // handler shifted focus
2472 focusChangeBlocked = true;
2475 oldFocusNode->dispatchUIEvent(EventImpl::DOMFOCUSOUT_EVENT);
2476 if (m_focusNode != 0) {
2477 // handler shifted focus
2478 focusChangeBlocked = true;
2481 if ((oldFocusNode == this) && oldFocusNode->hasOneRef()) {
2482 oldFocusNode->deref(); // deletes this
2486 oldFocusNode->deref();
2490 // Clear the selection when changing the focus node to null or to a node that is not
2491 // contained by the current selection.
2493 NodeImpl *startContainer = part()->selection().start().node();
2494 if (!newFocusNode || (startContainer && startContainer != newFocusNode && !startContainer->isAncestor(newFocusNode)))
2495 part()->clearSelection();
2500 if (newFocusNode->isContentEditable() && !acceptsEditingFocus(newFocusNode)) {
2501 // delegate blocks focus change
2502 focusChangeBlocked = true;
2503 goto SetFocusNodeDone;
2506 // Set focus on the new node
2507 m_focusNode = newFocusNode;
2509 m_focusNode->dispatchHTMLEvent(EventImpl::FOCUS_EVENT, false, false);
2510 if (m_focusNode != newFocusNode) {
2511 // handler shifted focus
2512 focusChangeBlocked = true;
2513 goto SetFocusNodeDone;
2515 m_focusNode->dispatchUIEvent(EventImpl::DOMFOCUSIN_EVENT);
2516 if (m_focusNode != newFocusNode) {
2517 // handler shifted focus
2518 focusChangeBlocked = true;
2519 goto SetFocusNodeDone;
2521 m_focusNode->setFocus();
2522 // eww, I suck. set the qt focus correctly
2523 // ### find a better place in the code for this
2524 if (getDocument()->view()) {
2525 if (!m_focusNode->renderer() || !m_focusNode->renderer()->isWidget())
2526 getDocument()->view()->setFocus();
2527 else if (static_cast<RenderWidget*>(m_focusNode->renderer())->widget()) {
2528 // Make sure a widget has the right size before giving it focus.
2529 // Otherwise, we are testing edge cases of the QWidget code.
2530 // Specifically, in WebCore this does not work well for text fields.
2531 getDocument()->updateLayout();
2532 static_cast<RenderWidget*>(m_focusNode->renderer())->widget()->setFocus();
2538 if (!focusChangeBlocked && m_focusNode && KWQAccObjectCache::accessibilityEnabled())
2539 getAccObjectCache()->handleFocusedUIElementChanged();
2544 return !focusChangeBlocked;
2547 void DocumentImpl::setCSSTarget(NodeImpl* n)
2550 m_cssTarget->setChanged();
2556 NodeImpl* DocumentImpl::getCSSTarget()
2561 void DocumentImpl::attachNodeIterator(NodeIteratorImpl *ni)
2563 m_nodeIterators.append(ni);
2566 void DocumentImpl::detachNodeIterator(NodeIteratorImpl *ni)
2568 m_nodeIterators.remove(ni);
2571 void DocumentImpl::notifyBeforeNodeRemoval(NodeImpl *n)
2573 QPtrListIterator<NodeIteratorImpl> it(m_nodeIterators);
2574 for (; it.current(); ++it)
2575 it.current()->notifyBeforeNodeRemoval(n);
2578 AbstractViewImpl *DocumentImpl::defaultView() const
2580 return m_defaultView;
2583 EventImpl *DocumentImpl::createEvent(const DOMString &eventType, int &exceptioncode)
2585 if (eventType == "UIEvents")
2586 return new UIEventImpl();
2587 else if (eventType == "MouseEvents")
2588 return new MouseEventImpl();
2589 else if (eventType == "MutationEvents")
2590 return new MutationEventImpl();
2591 else if (eventType == "KeyboardEvents")
2592 return new KeyboardEventImpl();
2593 else if (eventType == "HTMLEvents")
2594 return new EventImpl();
2596 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
2601 CSSStyleDeclarationImpl *DocumentImpl::getOverrideStyle(ElementImpl */*elt*/, DOMStringImpl */*pseudoElt*/)
2606 void DocumentImpl::defaultEventHandler(EventImpl *evt)
2608 // if any html event listeners are registered on the window, then dispatch them here
2609 QPtrList<RegisteredEventListener> listenersCopy = m_windowEventListeners;
2610 QPtrListIterator<RegisteredEventListener> it(listenersCopy);
2612 for (; it.current(); ++it) {
2613 if (it.current()->id == evt->id()) {
2614 it.current()->listener->handleEvent(ev, true);
2619 if (evt->id()==EventImpl::KEYDOWN_EVENT) {
2620 KeyboardEventImpl *kevt = static_cast<KeyboardEventImpl *>(evt);
2621 if (kevt->ctrlKey()) {
2622 QString key = kevt->qKeyEvent()->unmodifiedText().lower();
2623 ElementImpl *elem = getElementByAccessKey(key);
2625 elem->accessKeyAction();
2626 evt->setDefaultHandled();
2632 void DocumentImpl::setHTMLWindowEventListener(int id, EventListener *listener)
2634 // If we already have it we don't want removeWindowEventListener to delete it
2637 removeHTMLWindowEventListener(id);
2639 addWindowEventListener(id, listener, false);
2644 EventListener *DocumentImpl::getHTMLWindowEventListener(int id)
2646 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2647 for (; it.current(); ++it) {
2648 if (it.current()->id == id &&
2649 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2650 return it.current()->listener;
2657 void DocumentImpl::removeHTMLWindowEventListener(int id)
2659 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2660 for (; it.current(); ++it) {
2661 if (it.current()->id == id &&
2662 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2663 m_windowEventListeners.removeRef(it.current());
2669 void DocumentImpl::addWindowEventListener(int id, EventListener *listener, const bool useCapture)
2673 // remove existing identical listener set with identical arguments - the DOM2
2674 // spec says that "duplicate instances are discarded" in this case.
2675 removeWindowEventListener(id,listener,useCapture);
2677 RegisteredEventListener *rl = new RegisteredEventListener(static_cast<EventImpl::EventId>(id), listener, useCapture);
2678 m_windowEventListeners.append(rl);
2683 void DocumentImpl::removeWindowEventListener(int id, EventListener *listener, bool useCapture)
2685 RegisteredEventListener rl(static_cast<EventImpl::EventId>(id),listener,useCapture);
2687 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2688 for (; it.current(); ++it)
2689 if (*(it.current()) == rl) {
2690 m_windowEventListeners.removeRef(it.current());
2695 bool DocumentImpl::hasWindowEventListener(int id)
2697 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2698 for (; it.current(); ++it) {
2699 if (it.current()->id == id) {
2707 EventListener *DocumentImpl::createHTMLEventListener(QString code)
2710 return part()->createHTMLEventListener(code);
2716 void DocumentImpl::dispatchImageLoadEventSoon(HTMLImageLoader *image)
2718 m_imageLoadEventDispatchSoonList.append(image);
2719 if (!m_imageLoadEventTimer) {
2720 m_imageLoadEventTimer = startTimer(0);
2724 void DocumentImpl::removeImage(HTMLImageLoader* image)
2726 // Remove instances of this image from both lists.
2727 // Use loops because we allow multiple instances to get into the lists.
2728 while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
2729 while (m_imageLoadEventDispatchingList.removeRef(image)) { }
2730 if (m_imageLoadEventDispatchSoonList.isEmpty() && m_imageLoadEventTimer) {
2731 killTimer(m_imageLoadEventTimer);
2732 m_imageLoadEventTimer = 0;
2736 void DocumentImpl::dispatchImageLoadEventsNow()
2738 // need to avoid re-entering this function; if new dispatches are
2739 // scheduled before the parent finishes processing the list, they
2740 // will set a timer and eventually be processed
2741 if (!m_imageLoadEventDispatchingList.isEmpty()) {
2745 if (m_imageLoadEventTimer) {
2746 killTimer(m_imageLoadEventTimer);
2747 m_imageLoadEventTimer = 0;
2750 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2751 m_imageLoadEventDispatchSoonList.clear();
2752 for (QPtrListIterator<HTMLImageLoader> it(m_imageLoadEventDispatchingList); it.current(); ) {
2753 HTMLImageLoader* image = it.current();
2754 // Must advance iterator *before* dispatching call.
2755 // Otherwise, it might be advanced automatically if dispatching the call had a side effect
2756 // of destroying the current HTMLImageLoader, and then we would advance past the *next* item,
2757 // missing one altogether.
2759 image->dispatchLoadEvent();
2761 m_imageLoadEventDispatchingList.clear();
2764 void DocumentImpl::timerEvent(QTimerEvent *)
2766 dispatchImageLoadEventsNow();
2769 ElementImpl *DocumentImpl::ownerElement()
2771 KHTMLView *childView = view();
2774 KHTMLPart *childPart = childView->part();
2777 KHTMLPart *parent = childPart->parentPart();
2780 ChildFrame *childFrame = parent->childFrame(childPart);
2783 RenderPart *renderPart = childFrame->m_frame;
2786 return static_cast<ElementImpl *>(renderPart->element());
2789 DOMString DocumentImpl::domain() const
2791 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2792 m_domain = KURL(URL()).host(); // Initially set to the host
2796 void DocumentImpl::setDomain(const DOMString &newDomain, bool force /*=false*/)
2799 m_domain = newDomain;
2802 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2803 m_domain = KURL(URL()).host(); // Initially set to the host
2805 // Both NS and IE specify that changing the domain is only allowed when
2806 // the new domain is a suffix of the old domain.
2807 int oldLength = m_domain.length();
2808 int newLength = newDomain.length();
2809 if ( newLength < oldLength ) // e.g. newDomain=kde.org (7) and m_domain=www.kde.org (11)
2811 DOMString test = m_domain.copy();
2812 if ( test[oldLength - newLength - 1] == '.' ) // Check that it's a subdomain, not e.g. "de.org"
2814 test.remove( 0, oldLength - newLength ); // now test is "kde.org" from m_domain
2815 if ( test == newDomain ) // and we check that it's the same thing as newDomain
2816 m_domain = newDomain;
2821 bool DocumentImpl::isValidName(const DOMString &name)
2823 static const char validFirstCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz";
2824 static const char validSubsequentCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz0123456789-_:.";
2825 const unsigned length = name.length();
2828 const QChar * const characters = name.unicode();
2829 const char fc = characters[0];
2832 if (strchr(validFirstCharacter, fc) == 0)
2834 for (unsigned i = 1; i < length; ++i) {
2835 const char sc = characters[i];
2838 if (strchr(validSubsequentCharacter, sc) == 0)
2844 void DocumentImpl::addImageMap(HTMLMapElementImpl *imageMap)
2846 // Add the image map, unless there's already another with that name.
2847 // "First map wins" is the rule other browsers seem to implement.
2848 QString name = imageMap->getName().string();
2849 if (!m_imageMapsByName.contains(name))
2850 m_imageMapsByName.insert(name, imageMap);
2853 void DocumentImpl::removeImageMap(HTMLMapElementImpl *imageMap)
2855 // Remove the image map by name.
2856 // But don't remove some other image map that just happens to have the same name.
2857 QString name = imageMap->getName().string();
2858 QMapIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(name);
2859 if (it != m_imageMapsByName.end() && *it == imageMap)
2860 m_imageMapsByName.remove(it);
2863 HTMLMapElementImpl *DocumentImpl::getImageMap(const DOMString &URL) const
2869 QString s = URL.string();
2870 int hashPos = s.find('#');
2872 s = s.mid(hashPos + 1);
2874 QMapConstIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(s);
2875 if (it == m_imageMapsByName.end())
2882 void DocumentImpl::setDecoder(Decoder *decoder)
2888 m_decoder = decoder;
2891 QString DocumentImpl::completeURL(const QString &URL)
2893 return KURL(baseURL(), URL, m_decoder ? m_decoder->codec() : 0).url();
2896 bool DocumentImpl::inPageCache()
2898 return m_inPageCache;
2901 void DocumentImpl::setInPageCache(bool flag)
2903 if (m_inPageCache == flag)
2906 m_inPageCache = flag;
2908 assert(m_savedRenderer == 0);
2909 m_savedRenderer = m_render;
2911 m_view->resetScrollBars();
2914 assert(m_render == 0 || m_render == m_savedRenderer);
2915 m_render = m_savedRenderer;
2916 m_savedRenderer = 0;
2920 void DocumentImpl::passwordFieldAdded()
2925 void DocumentImpl::passwordFieldRemoved()
2927 assert(m_passwordFields > 0);
2931 bool DocumentImpl::hasPasswordField() const
2933 return m_passwordFields > 0;
2936 void DocumentImpl::secureFormAdded()
2941 void DocumentImpl::secureFormRemoved()
2943 assert(m_secureForms > 0);
2947 bool DocumentImpl::hasSecureForm() const
2949 return m_secureForms > 0;
2952 void DocumentImpl::setShouldCreateRenderers(bool f)
2954 m_createRenderers = f;
2957 bool DocumentImpl::shouldCreateRenderers()
2959 return m_createRenderers;
2962 DOMString DocumentImpl::toString() const
2966 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
2967 result += child->toString();
2973 #endif // APPLE_CHANGES
2975 // ----------------------------------------------------------------------------
2976 // Support for Javascript execCommand, and related methods
2978 JSEditor *DocumentImpl::jsEditor()
2981 m_jsEditor = new JSEditor(this);
2985 bool DocumentImpl::execCommand(const DOMString &command, bool userInterface, const DOMString &value)
2987 return jsEditor()->execCommand(command, userInterface, value);
2990 bool DocumentImpl::queryCommandEnabled(const DOMString &command)
2992 return jsEditor()->queryCommandEnabled(command);
2995 bool DocumentImpl::queryCommandIndeterm(const DOMString &command)
2997 return jsEditor()->queryCommandIndeterm(command);
3000 bool DocumentImpl::queryCommandState(const DOMString &command)
3002 return jsEditor()->queryCommandState(command);
3005 bool DocumentImpl::queryCommandSupported(const DOMString &command)
3007 return jsEditor()->queryCommandSupported(command);
3010 DOMString DocumentImpl::queryCommandValue(const DOMString &command)
3012 return jsEditor()->queryCommandValue(command);
3015 // ----------------------------------------------------------------------------
3017 void DocumentImpl::addMarker(Range range, DocumentMarker::MarkerType type)
3019 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3020 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3021 Range textPiece = markedText.range();
3022 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
3023 addMarker(textPiece.startContainer().handle(), marker);
3027 void DocumentImpl::removeMarker(Range range, DocumentMarker::MarkerType type)
3029 // Use a TextIterator to visit the potentially multiple nodes the range covers.
3030 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
3031 Range textPiece = markedText.range();
3032 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
3033 removeMarker(textPiece.startContainer().handle(), marker);
3037 // FIXME: We don't deal with markers of more than one type yet
3039 // Markers are stored in order sorted by their location. They do not overlap each other, as currently
3040 // required by the drawing code in render_text.cpp.
3042 void DocumentImpl::addMarker(NodeImpl *node, DocumentMarker newMarker)
3044 assert(newMarker.endOffset >= newMarker.startOffset);
3045 if (newMarker.endOffset == newMarker.startOffset) {
3046 return; // zero length markers are a NOP
3049 QValueList <DocumentMarker> *markers = m_markers.find(node);
3051 markers = new QValueList <DocumentMarker>();
3052 markers->append(newMarker);
3053 m_markers.insert(node, markers);
3055 QValueListIterator<DocumentMarker> it;
3056 for (it = markers->begin(); it != markers->end(); ) {
3057 DocumentMarker marker = *it;
3059 if (newMarker.endOffset < marker.startOffset+1) {
3060 // This is the first marker that is completely after newMarker, and disjoint from it.
3061 // We found our insertion point.
\10
3063 } else if (newMarker.startOffset > marker.endOffset) {
3064 // maker is before newMarker, and disjoint from it. Keep scanning.
3066 } else if (newMarker == marker) {
3067 // already have this one, NOP
3070 // marker and newMarker intersect or touch - merge them into newMarker
3071 newMarker.startOffset = kMin(newMarker.startOffset, marker.startOffset);
3072 newMarker.endOffset = kMax(newMarker.endOffset, marker.endOffset);
3073 // remove old one, we'll add newMarker later
3074 it = markers->remove(it);
3075 // it points to the next marker to consider
3078 // at this point it points to the node before which we want to insert
3079 markers->insert(it, newMarker);
3082 // repaint the affected node
3083 if (node->renderer())
3084 node->renderer()->repaint();
3087 void DocumentImpl::removeMarker(NodeImpl *node, DocumentMarker target)
3089 assert(target.endOffset >= target.startOffset);
3090 if (target.endOffset == target.startOffset) {
3091 return; // zero length markers are a NOP
3094 QValueList <DocumentMarker> *markers = m_markers.find(node);
3099 bool docDirty = false;
3100 QValueListIterator<DocumentMarker> it;
3101 for (it = markers->begin(); it != markers->end(); ) {
3102 DocumentMarker marker = *it;
3104 if (target.endOffset <= marker.startOffset) {
3105 // This is the first marker that is completely after target. All done.
3107 } else if (target.startOffset >= marker.endOffset) {
3108 // marker is before target. Keep scanning.
3111 // at this point we know that marker and target intersect in some way
3114 // pitch the old marker
3115 it = markers->remove(it);
3116 // it now points to the next node
3118 // add either of the resulting slices that are left after removing target
3119 if (target.startOffset > marker.startOffset) {
3120 DocumentMarker newLeft = marker;
3121 newLeft.endOffset = target.startOffset;
3122 markers->insert(it, newLeft);
3124 if (marker.endOffset > target.endOffset) {
3125 DocumentMarker newRight = marker;
3126 newRight.startOffset = target.endOffset;
3127 markers->insert(it, newRight);
3132 // repaint the affected node
3133 if (docDirty && node->renderer())
3134 node->renderer()->repaint();
3137 QValueList<DocumentMarker> DocumentImpl::markersForNode(NodeImpl *node)
3139 QValueList <DocumentMarker> *markers = m_markers.find(node);
3143 return QValueList <DocumentMarker> ();
3147 void DocumentImpl::removeAllMarkers(NodeImpl *node, ulong startOffset, long length)
3149 // FIXME - yet another cheat that relies on us only having one marker type
3150 DocumentMarker marker = {DocumentMarker::Spelling, startOffset, startOffset+length};
3151 removeMarker(node, marker);
3154 void DocumentImpl::removeAllMarkers(NodeImpl *node)
3156 QValueList <DocumentMarker> *markers = m_markers.find(node);
3161 void DocumentImpl::removeAllMarkers()
3166 void DocumentImpl::shiftMarkers(NodeImpl *node, ulong startOffset, long delta)
3168 if (m_markers.isEmpty())
3171 QValueList <DocumentMarker> *markers = m_markers.find(node);
3175 bool docDirty = false;
3176 QValueListIterator<DocumentMarker> it;
3177 for (it = markers->begin(); it != markers->end(); ++it) {
3178 DocumentMarker &marker = *it;
3179 if (marker.startOffset >= startOffset) {
3180 assert((int)marker.startOffset + delta >= 0);
3181 marker.startOffset += delta;
3182 marker.endOffset += delta;
3187 // repaint the affected node
3188 if (docDirty && node->renderer())
3189 node->renderer()->repaint();
3193 void DocumentImpl::applyXSLTransform(ProcessingInstructionImpl* pi)
3195 // Ref ourselves to keep from being destroyed.
3196 XSLTProcessorImpl processor(static_cast<XSLStyleSheetImpl*>(pi->sheet()), this);
3197 processor.transformDocument(this);
3199 // FIXME: If the transform failed we should probably report an error (like Mozilla does) in this
3203 void DocumentImpl::setTransformSourceDocument(DocumentImpl* doc)
3205 if (m_transformSourceDocument)
3206 m_transformSourceDocument->deref();
3207 m_transformSourceDocument = doc;
3214 void DocumentImpl::setDesignMode(InheritedBool value)
3216 m_designMode = value;
3219 DocumentImpl::InheritedBool DocumentImpl::getDesignMode() const
3221 return m_designMode;
3224 bool DocumentImpl::inDesignMode() const
3226 for (const DocumentImpl* d = this; d; d = d->parentDocument()) {
3227 if (d->m_designMode != inherit)
3228 return d->m_designMode;
3233 DocumentImpl *DocumentImpl::parentDocument() const
3235 KHTMLPart *childPart = part();
3238 KHTMLPart *parent = childPart->parentPart();
3241 return parent->xmlDocImpl();
3244 DocumentImpl *DocumentImpl::topDocument() const
3246 DocumentImpl *doc = const_cast<DocumentImpl *>(this);
3247 ElementImpl *element;
3248 while ((element = doc->ownerElement()) != 0) {
3249 doc = element->getDocument();
3250 element = doc ? doc->ownerElement() : 0;
3256 // ----------------------------------------------------------------------------
3258 DocumentFragmentImpl::DocumentFragmentImpl(DocumentPtr *doc) : NodeBaseImpl(doc)
3262 DOMString DocumentFragmentImpl::nodeName() const
3264 return "#document-fragment";
3267 unsigned short DocumentFragmentImpl::nodeType() const
3269 return Node::DOCUMENT_FRAGMENT_NODE;
3272 // DOM Section 1.1.1
3273 bool DocumentFragmentImpl::childTypeAllowed( unsigned short type )
3276 case Node::ELEMENT_NODE:
3277 case Node::PROCESSING_INSTRUCTION_NODE:
3278 case Node::COMMENT_NODE:
3279 case Node::TEXT_NODE:
3280 case Node::CDATA_SECTION_NODE:
3281 case Node::ENTITY_REFERENCE_NODE:
3288 DOMString DocumentFragmentImpl::toString() const
3292 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
3293 result += child->toString();
3300 NodeImpl *DocumentFragmentImpl::cloneNode ( bool deep )
3302 DocumentFragmentImpl *clone = new DocumentFragmentImpl( docPtr() );
3304 cloneChildNodes(clone);
3309 // ----------------------------------------------------------------------------
3311 DocumentTypeImpl::DocumentTypeImpl(DOMImplementationImpl *implementation, DocumentPtr *doc,
3312 const DOMString &qualifiedName, const DOMString &publicId,
3313 const DOMString &systemId)
3314 : NodeImpl(doc), m_implementation(implementation),
3315 m_qualifiedName(qualifiedName), m_publicId(publicId), m_systemId(systemId)
3317 if (m_implementation)
3318 m_implementation->ref();
3323 // if doc is 0, it is not attached to a document and / or
3324 // therefore does not provide entities or notations. (DOM Level 3)
3327 DocumentTypeImpl::~DocumentTypeImpl()
3329 if (m_implementation)
3330 m_implementation->deref();
3332 m_entities->deref();
3334 m_notations->deref();
3337 void DocumentTypeImpl::copyFrom(const DocumentTypeImpl& other)
3339 m_qualifiedName = other.m_qualifiedName;
3340 m_publicId = other.m_publicId;
3341 m_systemId = other.m_systemId;
3342 m_subset = other.m_subset;
3345 DOMString DocumentTypeImpl::toString() const
3348 if (m_qualifiedName.isEmpty()) {
3351 result = "<!DOCTYPE ";
3352 result += m_qualifiedName;
3354 if (!m_publicId.isEmpty()) {
3355 result += " PUBLIC \"";
3356 result += m_publicId;
3358 result += m_systemId;
3360 } else if (!m_systemId.isEmpty()) {
3361 result += " SYSTEM \"";
3362 result += m_systemId;
3365 if (!m_subset.isEmpty()) {
3374 DOMString DocumentTypeImpl::nodeName() const
3379 unsigned short DocumentTypeImpl::nodeType() const
3381 return Node::DOCUMENT_TYPE_NODE;
3384 // DOM Section 1.1.1
3385 bool DocumentTypeImpl::childTypeAllowed( unsigned short /*type*/ )
3390 NodeImpl *DocumentTypeImpl::cloneNode ( bool /*deep*/ )
3392 // Spec says cloning Document nodes is "implementation dependent"
3393 // so we do not support it...
3397 #include "dom_docimpl.moc"