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 NodeBaseImpl::detach();
1199 if (m_paintDevice == m_view)
1204 delete m_renderArena;
1210 KWQAccObjectCache* DocumentImpl::getAccObjectCache()
1212 // The only document that actually has a KWQAccObjectCache is the top-level
1213 // document. This is because we need to be able to get from any KWQAccObject
1214 // to any other KWQAccObject on the same page. Using a single cache allows
1215 // lookups across nested webareas (i.e. multiple documents).
1218 // return already known top-level cache
1219 if (!ownerElement())
1222 // In some pages with frames, the cache is created before the sub-webarea is
1223 // inserted into the tree. Here, we catch that case and just toss the old
1224 // cache and start over.
1229 // look for top-level document
1230 ElementImpl *element = ownerElement();
1234 doc = element->getDocument();
1235 element = doc->ownerElement();
1238 // ask the top-level document for its cache
1239 return doc->getAccObjectCache();
1242 // this is the top-level document, so install a new cache
1243 m_accCache = new KWQAccObjectCache;
1248 void DocumentImpl::setVisuallyOrdered()
1250 visuallyOrdered = true;
1252 m_render->style()->setVisuallyOrdered(true);
1255 void DocumentImpl::updateSelection()
1260 RenderCanvas *canvas = static_cast<RenderCanvas*>(m_render);
1261 Selection s = part()->selection();
1263 canvas->clearSelection();
1265 if (KWQAccObjectCache::accessibilityEnabled())
1266 getAccObjectCache()->postNotificationToTopWebArea(renderer(), "AXSelectedTextChanged");
1270 Position startPos = VisiblePosition(s.start(), s.startAffinity(), khtml::VisiblePosition::INIT_UP).deepEquivalent();
1271 Position endPos = VisiblePosition(s.end(), s.endAffinity(), khtml::VisiblePosition::INIT_DOWN).deepEquivalent();
1272 if (startPos.isNotNull() && endPos.isNotNull()) {
1273 RenderObject *startRenderer = startPos.node()->renderer();
1274 RenderObject *endRenderer = endPos.node()->renderer();
1275 static_cast<RenderCanvas*>(m_render)->setSelection(startRenderer, startPos.offset(), endRenderer, endPos.offset());
1277 if (KWQAccObjectCache::accessibilityEnabled()) {
1278 getAccObjectCache()->postNotificationToTopWebArea(renderer(), "AXSelectedTextChanged");
1285 Tokenizer *DocumentImpl::createTokenizer()
1287 return newXMLTokenizer(docPtr(), m_view);
1290 void DocumentImpl::setPaintDevice( QPaintDevice *dev )
1292 if (m_paintDevice == dev) {
1295 m_paintDevice = dev;
1296 delete m_paintDeviceMetrics;
1297 m_paintDeviceMetrics = dev ? new QPaintDeviceMetrics( dev ) : 0;
1300 void DocumentImpl::open( )
1302 if (parsing()) return;
1308 m_tokenizer = createTokenizer();
1309 connect(m_tokenizer,SIGNAL(finishedParsing()),this,SIGNAL(finishedParsing()));
1311 if (m_view && m_view->part()->jScript()) {
1312 m_view->part()->jScript()->setSourceFile(m_url,""); //fixme
1316 HTMLElementImpl* DocumentImpl::body()
1318 NodeImpl *de = documentElement();
1322 // try to prefer a FRAMESET element over BODY
1324 for (NodeImpl* i = de->firstChild(); i; i = i->nextSibling()) {
1325 if (i->id() == ID_FRAMESET)
1326 return static_cast<HTMLElementImpl*>(i);
1328 if (i->id() == ID_BODY)
1331 return static_cast<HTMLElementImpl *>(body);
1334 void DocumentImpl::close()
1336 // First fire the onload.
1338 bool wasLocationChangePending = part() && part()->isScheduledLocationChangePending();
1339 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1342 m_processingLoadEvent = true;
1344 // We have to clear the tokenizer, in case someone document.write()s from the
1345 // onLoad event handler, as in Radar 3206524
1349 // Create a body element if we don't already have one.
1350 // In the case of Radar 3758785, the window.onload was set in some javascript, but never fired because there was no body.
1351 // This behavior now matches Firefox and IE.
1352 HTMLElementImpl *body = this->body();
1354 NodeImpl *de = documentElement();
1356 body = new HTMLBodyElementImpl(docPtr());
1357 int exceptionCode = 0;
1358 de->appendChild(body, exceptionCode);
1359 if (exceptionCode != 0)
1365 dispatchImageLoadEventsNow();
1366 body->dispatchWindowEvent(EventImpl::LOAD_EVENT, false, false);
1369 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1370 if (!ownerElement())
1371 printf("onload fired at %d\n", elapsedTime());
1374 m_processingLoadEvent = false;
1377 // Make sure both the initial layout and reflow happen after the onload
1378 // fires. This will improve onload scores, and other browsers do it.
1379 // If they wanna cheat, we can too. -dwh
1381 bool isLocationChangePending = part() && part()->isScheduledLocationChangePending();
1383 if (doload && isLocationChangePending && m_startTime.elapsed() < cLayoutScheduleThreshold) {
1384 // Just bail out. Before or during the onload we were shifted to another page.
1385 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1388 view()->unscheduleRelayout();
1392 // The initial layout happens here.
1393 DocumentImpl::closeInternal(!doload);
1395 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1396 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1397 // layout/painting now would be pointless.
1399 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1402 // Always do a layout after loading if needed.
1403 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1407 if (renderer() && KWQAccObjectCache::accessibilityEnabled())
1408 getAccObjectCache()->postNotification(renderer(), "AXLoadComplete");
1413 void DocumentImpl::closeInternal( bool checkTokenizer )
1415 if (parsing() || (checkTokenizer && !m_tokenizer)) return;
1417 // on an explicit document.close(), the tokenizer might still be waiting on scripts,
1418 // and in that case we don't want to destroy it because that will prevent the
1419 // scripts from getting processed.
1420 if (m_tokenizer && !m_tokenizer->isWaitingForScripts()) {
1426 m_view->part()->checkEmitLoadEvent();
1429 void DocumentImpl::setParsing(bool b)
1432 if (!m_bParsing && view())
1433 view()->scheduleRelayout();
1435 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1436 if (!ownerElement() && !m_bParsing)
1437 printf("Parsing finished at %d\n", elapsedTime());
1441 bool DocumentImpl::shouldScheduleLayout()
1443 // We can update layout if:
1444 // (a) we actually need a layout
1445 // (b) our stylesheets are all loaded
1446 // (c) we have a <body>
1447 return (renderer() && renderer()->needsLayout() && haveStylesheetsLoaded() &&
1448 documentElement() && documentElement()->renderer() &&
1449 (documentElement()->id() != ID_HTML || body()));
1452 int DocumentImpl::minimumLayoutDelay()
1454 if (m_overMinimumLayoutThreshold)
1457 int elapsed = m_startTime.elapsed();
1458 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1460 // We'll want to schedule the timer to fire at the minimum layout threshold.
1461 return kMax(0, cLayoutScheduleThreshold - elapsed);
1464 int DocumentImpl::elapsedTime() const
1466 return m_startTime.elapsed();
1469 void DocumentImpl::write( const DOMString &text )
1471 write(text.string());
1474 void DocumentImpl::write( const QString &text )
1476 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1477 if (!ownerElement())
1478 printf("Beginning a document.write at %d\n", elapsedTime());
1483 write(QString::fromLatin1("<html>"));
1485 m_tokenizer->write(text, false);
1487 if (m_view && m_view->part()->jScript())
1488 m_view->part()->jScript()->appendSourceFile(m_url,text);
1490 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1491 if (!ownerElement())
1492 printf("Ending a document.write at %d\n", elapsedTime());
1496 void DocumentImpl::writeln( const DOMString &text )
1499 write(DOMString("\n"));
1502 void DocumentImpl::finishParsing()
1504 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1505 if (!ownerElement())
1506 printf("Received all data at %d\n", elapsedTime());
1509 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1510 // finish() is called:
1511 // (1) All remaining data is parsed, document isn't loaded yet
1512 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1513 // (3) Data is still remaining to be parsed.
1515 m_tokenizer->finish();
1518 void DocumentImpl::clear()
1524 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
1525 for (; it.current();)
1526 m_windowEventListeners.removeRef(it.current());
1529 void DocumentImpl::setURL(const QString& url)
1532 if (m_styleSelector)
1533 m_styleSelector->setEncodedURL(m_url);
1536 void DocumentImpl::setStyleSheet(const DOMString &url, const DOMString &sheet)
1538 // kdDebug( 6030 ) << "HTMLDocument::setStyleSheet()" << endl;
1539 m_sheet = new CSSStyleSheetImpl(this, url);
1541 m_sheet->parseString(sheet);
1542 m_loadingSheet = false;
1544 updateStyleSelector();
1547 void DocumentImpl::setUserStyleSheet( const QString& sheet )
1549 if ( m_usersheet != sheet ) {
1550 m_usersheet = sheet;
1551 updateStyleSelector();
1555 CSSStyleSheetImpl* DocumentImpl::elementSheet()
1558 m_elemSheet = new CSSStyleSheetImpl(this, baseURL() );
1564 void DocumentImpl::determineParseMode( const QString &/*str*/ )
1566 // For XML documents use strict parse mode. HTML docs will override this method to
1567 // determine their parse mode.
1570 kdDebug(6020) << " using strict parseMode" << endl;
1573 // Please see if there`s a possibility to merge that code
1574 // with the next function and getElementByID().
1575 NodeImpl *DocumentImpl::findElement( Id id )
1577 QPtrStack<NodeImpl> nodeStack;
1578 NodeImpl *current = _first;
1584 if(nodeStack.isEmpty()) break;
1585 current = nodeStack.pop();
1586 current = current->nextSibling();
1590 if(current->id() == id)
1593 NodeImpl *child = current->firstChild();
1596 nodeStack.push(current);
1601 current = current->nextSibling();
1609 NodeImpl *DocumentImpl::nextFocusNode(NodeImpl *fromNode)
1611 unsigned short fromTabIndex;
1614 // No starting node supplied; begin with the top of the document
1617 int lowestTabIndex = 65535;
1618 for (n = this; n != 0; n = n->traverseNextNode()) {
1619 if (n->isKeyboardFocusable()) {
1620 if ((n->tabIndex() > 0) && (n->tabIndex() < lowestTabIndex))
1621 lowestTabIndex = n->tabIndex();
1625 if (lowestTabIndex == 65535)
1628 // Go to the first node in the document that has the desired tab index
1629 for (n = this; n != 0; n = n->traverseNextNode()) {
1630 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestTabIndex))
1637 fromTabIndex = fromNode->tabIndex();
1640 if (fromTabIndex == 0) {
1641 // Just need to find the next selectable node after fromNode (in document order) that doesn't have a tab index
1642 NodeImpl *n = fromNode->traverseNextNode();
1643 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1644 n = n->traverseNextNode();
1648 // Find the lowest tab index out of all the nodes except fromNode, that is greater than or equal to fromNode's
1649 // tab index. For nodes with the same tab index as fromNode, we are only interested in those that come after
1650 // fromNode in document order.
1651 // If we don't find a suitable tab index, the next focus node will be one with a tab index of 0.
1652 unsigned short lowestSuitableTabIndex = 65535;
1655 bool reachedFromNode = false;
1656 for (n = this; n != 0; n = n->traverseNextNode()) {
1657 if (n->isKeyboardFocusable() &&
1658 ((reachedFromNode && (n->tabIndex() >= fromTabIndex)) ||
1659 (!reachedFromNode && (n->tabIndex() > fromTabIndex))) &&
1660 (n->tabIndex() < lowestSuitableTabIndex) &&
1663 // We found a selectable node with a tab index at least as high as fromNode's. Keep searching though,
1664 // as there may be another node which has a lower tab index but is still suitable for use.
1665 lowestSuitableTabIndex = n->tabIndex();
1669 reachedFromNode = true;
1672 if (lowestSuitableTabIndex == 65535) {
1673 // No next node with a tab index -> just take first node with tab index of 0
1675 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1676 n = n->traverseNextNode();
1680 // Search forwards from fromNode
1681 for (n = fromNode->traverseNextNode(); n != 0; n = n->traverseNextNode()) {
1682 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1686 // The next node isn't after fromNode, start from the beginning of the document
1687 for (n = this; n != fromNode; n = n->traverseNextNode()) {
1688 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1692 assert(false); // should never get here
1697 NodeImpl *DocumentImpl::previousFocusNode(NodeImpl *fromNode)
1699 NodeImpl *lastNode = this;
1700 while (lastNode->lastChild())
1701 lastNode = lastNode->lastChild();
1704 // No starting node supplied; begin with the very last node in the document
1707 int highestTabIndex = 0;
1708 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1709 if (n->isKeyboardFocusable()) {
1710 if (n->tabIndex() == 0)
1712 else if (n->tabIndex() > highestTabIndex)
1713 highestTabIndex = n->tabIndex();
1717 // No node with a tab index of 0; just go to the last node with the highest tab index
1718 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1719 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1726 unsigned short fromTabIndex = fromNode->tabIndex();
1728 if (fromTabIndex == 0) {
1729 // Find the previous selectable node before fromNode (in document order) that doesn't have a tab index
1730 NodeImpl *n = fromNode->traversePreviousNode();
1731 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1732 n = n->traversePreviousNode();
1736 // No previous nodes with a 0 tab index, go to the last node in the document that has the highest tab index
1737 int highestTabIndex = 0;
1738 for (n = this; n != 0; n = n->traverseNextNode()) {
1739 if (n->isKeyboardFocusable() && (n->tabIndex() > highestTabIndex))
1740 highestTabIndex = n->tabIndex();
1743 if (highestTabIndex == 0)
1746 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1747 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1751 assert(false); // should never get here
1755 // Find the lowest tab index out of all the nodes except fromNode, that is less than or equal to fromNode's
1756 // tab index. For nodes with the same tab index as fromNode, we are only interested in those before
1758 // If we don't find a suitable tab index, then there will be no previous focus node.
1759 unsigned short highestSuitableTabIndex = 0;
1762 bool reachedFromNode = false;
1763 for (n = this; n != 0; n = n->traverseNextNode()) {
1764 if (n->isKeyboardFocusable() &&
1765 ((!reachedFromNode && (n->tabIndex() <= fromTabIndex)) ||
1766 (reachedFromNode && (n->tabIndex() < fromTabIndex))) &&
1767 (n->tabIndex() > highestSuitableTabIndex) &&
1770 // We found a selectable node with a tab index no higher than fromNode's. Keep searching though, as
1771 // there may be another node which has a higher tab index but is still suitable for use.
1772 highestSuitableTabIndex = n->tabIndex();
1776 reachedFromNode = true;
1779 if (highestSuitableTabIndex == 0) {
1780 // No previous node with a tab index. Since the order specified by HTML is nodes with tab index > 0
1781 // first, this means that there is no previous node.
1785 // Search backwards from fromNode
1786 for (n = fromNode->traversePreviousNode(); n != 0; n = n->traversePreviousNode()) {
1787 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1790 // The previous node isn't before fromNode, start from the end of the document
1791 for (n = lastNode; n != fromNode; n = n->traversePreviousNode()) {
1792 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1796 assert(false); // should never get here
1802 int DocumentImpl::nodeAbsIndex(NodeImpl *node)
1804 assert(node->getDocument() == this);
1807 for (NodeImpl *n = node; n && n != this; n = n->traversePreviousNode())
1812 NodeImpl *DocumentImpl::nodeWithAbsIndex(int absIndex)
1815 for (int i = 0; n && (i < absIndex); i++) {
1816 n = n->traverseNextNode();
1821 void DocumentImpl::processHttpEquiv(const DOMString &equiv, const DOMString &content)
1823 assert(!equiv.isNull() && !content.isNull());
1825 KHTMLPart *part = getDocument()->part();
1827 if (strcasecmp(equiv, "default-style") == 0) {
1828 // The preferred style set has been overridden as per section
1829 // 14.3.2 of the HTML4.0 specification. We need to update the
1830 // sheet used variable and then update our style selector.
1831 // For more info, see the test at:
1832 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1834 part->d->m_sheetUsed = content.string();
1835 m_preferredStylesheetSet = content;
1836 updateStyleSelector();
1838 else if(strcasecmp(equiv, "refresh") == 0 && part->metaRefreshEnabled())
1840 // get delay and url
1841 QString str = content.string().stripWhiteSpace();
1842 int pos = str.find(QRegExp("[;,]"));
1844 pos = str.find(QRegExp("[ \t]"));
1846 if (pos == -1) // There can be no url (David)
1850 delay = str.toInt(&ok);
1852 // We want a new history item if the refresh timeout > 1 second
1853 if(ok && part) part->scheduleRedirection(delay, part->url().url(), delay <= 1);
1855 if(ok && part) part->scheduleRedirection(delay, part->url().url() );
1860 delay = str.left(pos).stripWhiteSpace().toDouble(&ok);
1863 while(pos < (int)str.length() && str[pos].isSpace()) pos++;
1865 if(str.find("url", 0, false ) == 0) str = str.mid(3);
1866 str = str.stripWhiteSpace();
1867 if ( str.length() && str[0] == '=' ) str = str.mid( 1 ).stripWhiteSpace();
1868 str = parseURL( DOMString(str) ).string();
1871 // We want a new history item if the refresh timeout > 1 second
1872 part->scheduleRedirection(delay, getDocument()->completeURL( str ), delay <= 1);
1874 part->scheduleRedirection(delay, getDocument()->completeURL( str ));
1878 else if(strcasecmp(equiv, "expires") == 0)
1880 QString str = content.string().stripWhiteSpace();
1881 time_t expire_date = str.toLong();
1883 m_docLoader->setExpireDate(expire_date);
1885 else if(strcasecmp(equiv, "pragma") == 0 || strcasecmp(equiv, "cache-control") == 0 && part)
1887 QString str = content.string().lower().stripWhiteSpace();
1888 KURL url = part->url();
1889 if ((str == "no-cache") && url.protocol().startsWith("http"))
1891 KIO::http_update_cache(url, true, 0);
1894 else if( (strcasecmp(equiv, "set-cookie") == 0))
1896 // ### make setCookie work on XML documents too; e.g. in case of <html:meta .....>
1897 HTMLDocumentImpl *d = static_cast<HTMLDocumentImpl *>(this);
1898 d->setCookie(content);
1902 bool DocumentImpl::prepareMouseEvent( bool readonly, int _x, int _y, MouseEvent *ev )
1905 assert(m_render->isCanvas());
1906 RenderObject::NodeInfo renderInfo(readonly, ev->type == MousePress);
1907 bool isInside = m_render->layer()->hitTest(renderInfo, _x, _y);
1908 ev->innerNode = renderInfo.innerNode();
1910 if (renderInfo.URLElement()) {
1911 assert(renderInfo.URLElement()->isElementNode());
1912 ElementImpl* e = static_cast<ElementImpl*>(renderInfo.URLElement());
1913 DOMString href = khtml::parseURL(e->getAttribute(ATTR_HREF));
1914 DOMString target = e->getAttribute(ATTR_TARGET);
1916 if (!target.isNull() && !href.isNull()) {
1917 ev->target = target;
1922 // qDebug("url: *%s*", ev->url.string().latin1());
1935 // DOM Section 1.1.1
1936 bool DocumentImpl::childAllowed( NodeImpl *newChild )
1938 // Documents may contain a maximum of one Element child
1939 if (newChild->nodeType() == Node::ELEMENT_NODE) {
1941 for (c = firstChild(); c; c = c->nextSibling()) {
1942 if (c->nodeType() == Node::ELEMENT_NODE)
1947 // Documents may contain a maximum of one DocumentType child
1948 if (newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
1950 for (c = firstChild(); c; c = c->nextSibling()) {
1951 if (c->nodeType() == Node::DOCUMENT_TYPE_NODE)
1956 return childTypeAllowed(newChild->nodeType());
1959 bool DocumentImpl::childTypeAllowed( unsigned short type )
1962 case Node::ELEMENT_NODE:
1963 case Node::PROCESSING_INSTRUCTION_NODE:
1964 case Node::COMMENT_NODE:
1965 case Node::DOCUMENT_TYPE_NODE:
1972 NodeImpl *DocumentImpl::cloneNode ( bool /*deep*/ )
1974 // Spec says cloning Document nodes is "implementation dependent"
1975 // so we do not support it...
1979 NodeImpl::Id DocumentImpl::attrId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
1981 // Each document maintains a mapping of attrname -> id for every attr name
1982 // encountered in the document.
1983 // For attrnames without a prefix (no qualified element name) and without matching
1984 // namespace, the value defined in misc/htmlattrs.h is used.
1985 NodeImpl::Id id = 0;
1987 // First see if it's a HTML attribute name
1988 QConstString n(_name->s, _name->l);
1989 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
1990 // we're in HTML namespace if we know the tag.
1991 // xhtml is lower case - case sensitive, easy to implement
1992 if ( htmlMode() == XHtml && (id = getAttrID(n.string().ascii(), _name->l)) )
1994 // compatibility: upper case - case insensitive
1995 if ( htmlMode() != XHtml && (id = getAttrID(n.string().lower().ascii(), _name->l )) )
1998 // ok, the fast path didn't work out, we need the full check
2001 // now lets find out the namespace
2002 Q_UINT16 ns = noNamespace;
2003 if (_namespaceURI) {
2004 DOMString nsU(_namespaceURI);
2005 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
2007 ns = (Q_UINT16)nsID;
2010 // Look in the m_attrNames array for the name
2011 // ### yeah, this is lame. use a dictionary / map instead
2012 DOMString nme(n.string());
2013 // compatibility mode has to store upper case
2014 if (htmlMode() != XHtml) nme = nme.upper();
2015 for (id = 0; id < m_attrNameCount; id++)
2016 if (DOMString(m_attrNames[id]) == nme)
2017 return makeId(ns, ATTR_LAST_ATTR+id);
2020 if (readonly) return 0;
2022 // Name not found in m_attrNames, so let's add it
2023 // ### yeah, this is lame. use a dictionary / map instead
2024 if (m_attrNameCount+1 > m_attrNameAlloc) {
2025 m_attrNameAlloc += 100;
2026 DOMStringImpl **newNames = new DOMStringImpl* [m_attrNameAlloc];
2029 for (i = 0; i < m_attrNameCount; i++)
2030 newNames[i] = m_attrNames[i];
2031 delete [] m_attrNames;
2033 m_attrNames = newNames;
2036 id = m_attrNameCount++;
2037 m_attrNames[id] = nme.implementation();
2038 m_attrNames[id]->ref();
2040 return makeId(ns, ATTR_LAST_ATTR+id);
2043 DOMString DocumentImpl::attrName(NodeImpl::Id _id) const
2046 if (localNamePart(_id) >= ATTR_LAST_ATTR)
2047 result = m_attrNames[localNamePart(_id)-ATTR_LAST_ATTR];
2049 result = getAttrName(_id);
2051 // Attribute names are always lowercase in the DOM for both
2053 if (getDocument()->isHTMLDocument() ||
2054 getDocument()->htmlMode() == DocumentImpl::XHtml)
2055 return result.lower();
2060 NodeImpl::Id DocumentImpl::tagId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
2062 if (!_name) return 0;
2063 // Each document maintains a mapping of tag name -> id for every tag name encountered
2065 NodeImpl::Id id = 0;
2067 // First see if it's a HTML element name
2068 QConstString n(_name->s, _name->l);
2069 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
2070 // we're in HTML namespace if we know the tag.
2071 // xhtml is lower case - case sensitive, easy to implement
2072 if ( htmlMode() == XHtml && (id = getTagID(n.string().ascii(), _name->l)) )
2074 // compatibility: upper case - case insensitive
2075 if ( htmlMode() != XHtml && (id = getTagID(n.string().lower().ascii(), _name->l )) )
2078 // ok, the fast path didn't work out, we need the full check
2081 // now lets find out the namespace
2082 Q_UINT16 ns = noNamespace;
2083 if (_namespaceURI) {
2084 DOMString nsU(_namespaceURI);
2085 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
2087 ns = (Q_UINT16)nsID;
2090 // Look in the m_elementNames array for the name
2091 // ### yeah, this is lame. use a dictionary / map instead
2092 DOMString nme(n.string());
2093 // compatibility mode has to store upper case
2094 if (htmlMode() != XHtml) nme = nme.upper();
2095 for (id = 0; id < m_elementNameCount; id++)
2096 if (DOMString(m_elementNames[id]) == nme)
2097 return makeId(ns, ID_LAST_TAG + 1 + id);
2100 if (readonly) return 0;
2102 // Name not found in m_elementNames, so let's add it
2103 if (m_elementNameCount+1 > m_elementNameAlloc) {
2104 m_elementNameAlloc += 100;
2105 DOMStringImpl **newNames = new DOMStringImpl* [m_elementNameAlloc];
2106 // ### yeah, this is lame. use a dictionary / map instead
2107 if (m_elementNames) {
2109 for (i = 0; i < m_elementNameCount; i++)
2110 newNames[i] = m_elementNames[i];
2111 delete [] m_elementNames;
2113 m_elementNames = newNames;
2116 id = m_elementNameCount++;
2117 m_elementNames[id] = nme.implementation();
2118 m_elementNames[id]->ref();
2120 return makeId(ns, ID_LAST_TAG + 1 + id);
2123 DOMString DocumentImpl::tagName(NodeImpl::Id _id) const
2125 if (localNamePart(_id) > ID_LAST_TAG)
2126 return m_elementNames[localNamePart(_id) - (ID_LAST_TAG + 1)];
2128 // ### put them in a cache
2129 if (getDocument()->htmlMode() == DocumentImpl::XHtml)
2130 return getTagName(_id).lower();
2132 return getTagName(_id);
2137 DOMStringImpl* DocumentImpl::namespaceURI(NodeImpl::Id _id) const
2139 if (_id <= ID_LAST_TAG)
2140 return htmlMode() == XHtml ? XmlNamespaceTable::getNamespaceURI(xhtmlNamespace).implementation() : 0;
2142 unsigned short ns = _id >> 16;
2146 return XmlNamespaceTable::getNamespaceURI(ns).implementation();
2149 StyleSheetListImpl* DocumentImpl::styleSheets()
2151 return m_styleSheets;
2155 DocumentImpl::preferredStylesheetSet()
2157 return m_preferredStylesheetSet;
2161 DocumentImpl::selectedStylesheetSet()
2163 return view() ? view()->part()->d->m_sheetUsed : DOMString();
2167 DocumentImpl::setSelectedStylesheetSet(const DOMString& aString)
2170 view()->part()->d->m_sheetUsed = aString.string();
2171 updateStyleSelector();
2173 renderer()->repaint();
2177 // This method is called whenever a top-level stylesheet has finished loading.
2178 void DocumentImpl::stylesheetLoaded()
2180 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2181 assert(m_pendingStylesheets > 0);
2183 m_pendingStylesheets--;
2185 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2186 if (!ownerElement())
2187 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2190 updateStyleSelector();
2193 void DocumentImpl::updateStyleSelector()
2195 // Don't bother updating, since we haven't loaded all our style info yet.
2196 if (!haveStylesheetsLoaded())
2199 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2200 if (!ownerElement())
2201 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2204 recalcStyleSelector();
2208 m_styleSelectorDirty = true;
2211 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2212 if (!ownerElement())
2213 printf("Finished update of style selector at time %d\n", elapsedTime());
2217 renderer()->setNeedsLayoutAndMinMaxRecalc();
2219 view()->scheduleRelayout();
2224 QStringList DocumentImpl::availableStyleSheets() const
2226 return m_availableSheets;
2229 void DocumentImpl::recalcStyleSelector()
2231 if ( !m_render || !attached() ) return;
2233 QPtrList<StyleSheetImpl> oldStyleSheets = m_styleSheets->styleSheets;
2234 m_styleSheets->styleSheets.clear();
2235 m_availableSheets.clear();
2237 for (n = this; n; n = n->traverseNextNode()) {
2238 StyleSheetImpl *sheet = 0;
2240 if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
2242 // Processing instruction (XML documents only)
2243 ProcessingInstructionImpl* pi = static_cast<ProcessingInstructionImpl*>(n);
2244 sheet = pi->sheet();
2247 applyXSLTransform(pi);
2251 if (!sheet && !pi->localHref().isEmpty())
2253 // Processing instruction with reference to an element in this document - e.g.
2254 // <?xml-stylesheet href="#mystyle">, with the element
2255 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2257 ElementImpl* elem = getElementById(pi->localHref());
2259 DOMString sheetText("");
2261 for (c = elem->firstChild(); c; c = c->nextSibling()) {
2262 if (c->nodeType() == Node::TEXT_NODE || c->nodeType() == Node::CDATA_SECTION_NODE)
2263 sheetText += c->nodeValue();
2266 CSSStyleSheetImpl *cssSheet = new CSSStyleSheetImpl(this);
2267 cssSheet->parseString(sheetText);
2268 pi->setStyleSheet(cssSheet);
2274 else if (n->isHTMLElement() && (n->id() == ID_LINK || n->id() == ID_STYLE)) {
2275 ElementImpl *e = static_cast<ElementImpl *>(n);
2276 QString title = e->getAttribute( ATTR_TITLE ).string();
2277 bool enabledViaScript = false;
2278 if (n->id() == ID_LINK) {
2280 HTMLLinkElementImpl* l = static_cast<HTMLLinkElementImpl*>(n);
2281 if (l->isLoading() || l->isDisabled())
2284 title = QString::null;
2285 enabledViaScript = l->isEnabledViaScript();
2288 // Get the current preferred styleset. This is the
2289 // set of sheets that will be enabled.
2290 if ( n->id() == ID_LINK )
2291 sheet = static_cast<HTMLLinkElementImpl*>(n)->sheet();
2294 sheet = static_cast<HTMLStyleElementImpl*>(n)->sheet();
2296 // Check to see if this sheet belongs to a styleset
2297 // (thus making it PREFERRED or ALTERNATE rather than
2299 if (!enabledViaScript && !title.isEmpty()) {
2300 // Yes, we have a title.
2301 if (m_preferredStylesheetSet.isEmpty()) {
2302 // No preferred set has been established. If
2303 // we are NOT an alternate sheet, then establish
2304 // us as the preferred set. Otherwise, just ignore
2306 QString rel = e->getAttribute( ATTR_REL ).string();
2307 if (n->id() == ID_STYLE || !rel.contains("alternate"))
2308 m_preferredStylesheetSet = view()->part()->d->m_sheetUsed = title;
2311 if (!m_availableSheets.contains( title ) )
2312 m_availableSheets.append( title );
2314 if (title != m_preferredStylesheetSet)
2321 m_styleSheets->styleSheets.append(sheet);
2324 // For HTML documents, stylesheets are not allowed within/after the <BODY> tag. So we
2325 // can stop searching here.
2326 if (isHTMLDocument() && n->id() == ID_BODY)
2330 // De-reference all the stylesheets in the old list
2331 QPtrListIterator<StyleSheetImpl> it(oldStyleSheets);
2332 for (; it.current(); ++it)
2333 it.current()->deref();
2335 // Create a new style selector
2336 delete m_styleSelector;
2337 QString usersheet = m_usersheet;
2338 if ( m_view && m_view->mediaType() == "print" )
2339 usersheet += m_printSheet;
2340 m_styleSelector = new CSSStyleSelector(this, usersheet, m_styleSheets, !inCompatMode());
2341 m_styleSelector->setEncodedURL(m_url);
2342 m_styleSelectorDirty = false;
2345 void DocumentImpl::setHoverNode(NodeImpl* newHoverNode)
2347 if (m_hoverNode != newHoverNode) {
2349 m_hoverNode->deref();
2350 m_hoverNode = newHoverNode;
2358 bool DocumentImpl::relinquishesEditingFocus(NodeImpl *node)
2361 assert(node->isContentEditable());
2363 NodeImpl *rootImpl = node->rootEditableElement();
2364 if (!part() || !rootImpl)
2367 Node root(rootImpl);
2368 Range range(root, 0, root, rootImpl->childNodeCount());
2369 return part()->shouldEndEditing(range);
2372 bool DocumentImpl::acceptsEditingFocus(NodeImpl *node)
2375 assert(node->isContentEditable());
2377 NodeImpl *rootImpl = node->rootEditableElement();
2378 if (!part() || !rootImpl)
2381 Node root(rootImpl);
2382 Range range(root, 0, root, rootImpl->childNodeCount());
2383 return part()->shouldBeginEditing(range);
2386 const QValueList<DashboardRegionValue> & DocumentImpl::dashboardRegions() const
2388 return m_dashboardRegions;
2391 void DocumentImpl::setDashboardRegions (const QValueList<DashboardRegionValue>& regions)
2393 m_dashboardRegions = regions;
2394 setDashboardRegionsDirty (false);
2399 bool DocumentImpl::setFocusNode(NodeImpl *newFocusNode)
2401 // Make sure newFocusNode is actually in this document
2402 if (newFocusNode && (newFocusNode->getDocument() != this))
2405 if (m_focusNode == newFocusNode)
2409 if (m_focusNode && m_focusNode->isContentEditable() && !relinquishesEditingFocus(m_focusNode))
2413 bool focusChangeBlocked = false;
2414 NodeImpl *oldFocusNode = m_focusNode;
2417 // Remove focus from the existing focus node (if any)
2419 // This goes hand in hand with the Qt focus setting below.
2420 if (!newFocusNode && getDocument()->view()) {
2421 getDocument()->view()->setFocus();
2424 if (oldFocusNode->active())
2425 oldFocusNode->setActive(false);
2427 oldFocusNode->setFocus(false);
2428 oldFocusNode->dispatchHTMLEvent(EventImpl::BLUR_EVENT, false, false);
2429 if (m_focusNode != 0) {
2430 // handler shifted focus
2431 focusChangeBlocked = true;
2434 oldFocusNode->dispatchUIEvent(EventImpl::DOMFOCUSOUT_EVENT);
2435 if (m_focusNode != 0) {
2436 // handler shifted focus
2437 focusChangeBlocked = true;
2440 if ((oldFocusNode == this) && oldFocusNode->hasOneRef()) {
2441 oldFocusNode->deref(); // deletes this
2445 oldFocusNode->deref();
2449 // Clear the selection when changing the focus node to null or to a node that is not
2450 // contained by the current selection.
2452 NodeImpl *startContainer = part()->selection().start().node();
2453 if (!newFocusNode || (startContainer && startContainer != newFocusNode && !startContainer->isAncestor(newFocusNode)))
2454 part()->clearSelection();
2459 if (newFocusNode->isContentEditable() && !acceptsEditingFocus(newFocusNode)) {
2460 // delegate blocks focus change
2461 focusChangeBlocked = true;
2462 goto SetFocusNodeDone;
2465 // Set focus on the new node
2466 m_focusNode = newFocusNode;
2468 m_focusNode->dispatchHTMLEvent(EventImpl::FOCUS_EVENT, false, false);
2469 if (m_focusNode != newFocusNode) {
2470 // handler shifted focus
2471 focusChangeBlocked = true;
2472 goto SetFocusNodeDone;
2474 m_focusNode->dispatchUIEvent(EventImpl::DOMFOCUSIN_EVENT);
2475 if (m_focusNode != newFocusNode) {
2476 // handler shifted focus
2477 focusChangeBlocked = true;
2478 goto SetFocusNodeDone;
2480 m_focusNode->setFocus();
2481 // eww, I suck. set the qt focus correctly
2482 // ### find a better place in the code for this
2483 if (getDocument()->view()) {
2484 if (!m_focusNode->renderer() || !m_focusNode->renderer()->isWidget())
2485 getDocument()->view()->setFocus();
2486 else if (static_cast<RenderWidget*>(m_focusNode->renderer())->widget()) {
2487 // Make sure a widget has the right size before giving it focus.
2488 // Otherwise, we are testing edge cases of the QWidget code.
2489 // Specifically, in WebCore this does not work well for text fields.
2490 getDocument()->updateLayout();
2491 static_cast<RenderWidget*>(m_focusNode->renderer())->widget()->setFocus();
2497 if (!focusChangeBlocked && m_focusNode && KWQAccObjectCache::accessibilityEnabled())
2498 getAccObjectCache()->handleFocusedUIElementChanged();
2503 return !focusChangeBlocked;
2506 void DocumentImpl::setCSSTarget(NodeImpl* n)
2509 m_cssTarget->setChanged();
2515 NodeImpl* DocumentImpl::getCSSTarget()
2520 void DocumentImpl::attachNodeIterator(NodeIteratorImpl *ni)
2522 m_nodeIterators.append(ni);
2525 void DocumentImpl::detachNodeIterator(NodeIteratorImpl *ni)
2527 m_nodeIterators.remove(ni);
2530 void DocumentImpl::notifyBeforeNodeRemoval(NodeImpl *n)
2532 QPtrListIterator<NodeIteratorImpl> it(m_nodeIterators);
2533 for (; it.current(); ++it)
2534 it.current()->notifyBeforeNodeRemoval(n);
2537 AbstractViewImpl *DocumentImpl::defaultView() const
2539 return m_defaultView;
2542 EventImpl *DocumentImpl::createEvent(const DOMString &eventType, int &exceptioncode)
2544 if (eventType == "UIEvents")
2545 return new UIEventImpl();
2546 else if (eventType == "MouseEvents")
2547 return new MouseEventImpl();
2548 else if (eventType == "MutationEvents")
2549 return new MutationEventImpl();
2550 else if (eventType == "KeyboardEvents")
2551 return new KeyboardEventImpl();
2552 else if (eventType == "HTMLEvents")
2553 return new EventImpl();
2555 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
2560 CSSStyleDeclarationImpl *DocumentImpl::getOverrideStyle(ElementImpl */*elt*/, DOMStringImpl */*pseudoElt*/)
2565 void DocumentImpl::defaultEventHandler(EventImpl *evt)
2567 // if any html event listeners are registered on the window, then dispatch them here
2568 QPtrList<RegisteredEventListener> listenersCopy = m_windowEventListeners;
2569 QPtrListIterator<RegisteredEventListener> it(listenersCopy);
2571 for (; it.current(); ++it) {
2572 if (it.current()->id == evt->id()) {
2573 it.current()->listener->handleEvent(ev, true);
2578 if (evt->id()==EventImpl::KEYDOWN_EVENT) {
2579 KeyboardEventImpl *kevt = static_cast<KeyboardEventImpl *>(evt);
2580 if (kevt->ctrlKey()) {
2581 QString key = kevt->qKeyEvent()->unmodifiedText().lower();
2582 ElementImpl *elem = getElementByAccessKey(key);
2584 elem->accessKeyAction();
2585 evt->setDefaultHandled();
2591 void DocumentImpl::setHTMLWindowEventListener(int id, EventListener *listener)
2593 // If we already have it we don't want removeWindowEventListener to delete it
2596 removeHTMLWindowEventListener(id);
2598 addWindowEventListener(id, listener, false);
2603 EventListener *DocumentImpl::getHTMLWindowEventListener(int id)
2605 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2606 for (; it.current(); ++it) {
2607 if (it.current()->id == id &&
2608 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2609 return it.current()->listener;
2616 void DocumentImpl::removeHTMLWindowEventListener(int id)
2618 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2619 for (; it.current(); ++it) {
2620 if (it.current()->id == id &&
2621 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2622 m_windowEventListeners.removeRef(it.current());
2628 void DocumentImpl::addWindowEventListener(int id, EventListener *listener, const bool useCapture)
2632 // remove existing identical listener set with identical arguments - the DOM2
2633 // spec says that "duplicate instances are discarded" in this case.
2634 removeWindowEventListener(id,listener,useCapture);
2636 RegisteredEventListener *rl = new RegisteredEventListener(static_cast<EventImpl::EventId>(id), listener, useCapture);
2637 m_windowEventListeners.append(rl);
2642 void DocumentImpl::removeWindowEventListener(int id, EventListener *listener, bool useCapture)
2644 RegisteredEventListener rl(static_cast<EventImpl::EventId>(id),listener,useCapture);
2646 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2647 for (; it.current(); ++it)
2648 if (*(it.current()) == rl) {
2649 m_windowEventListeners.removeRef(it.current());
2654 bool DocumentImpl::hasWindowEventListener(int id)
2656 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2657 for (; it.current(); ++it) {
2658 if (it.current()->id == id) {
2666 EventListener *DocumentImpl::createHTMLEventListener(QString code)
2669 return part()->createHTMLEventListener(code);
2675 void DocumentImpl::dispatchImageLoadEventSoon(HTMLImageLoader *image)
2677 m_imageLoadEventDispatchSoonList.append(image);
2678 if (!m_imageLoadEventTimer) {
2679 m_imageLoadEventTimer = startTimer(0);
2683 void DocumentImpl::removeImage(HTMLImageLoader* image)
2685 // Remove instances of this image from both lists.
2686 // Use loops because we allow multiple instances to get into the lists.
2687 while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
2688 while (m_imageLoadEventDispatchingList.removeRef(image)) { }
2689 if (m_imageLoadEventDispatchSoonList.isEmpty() && m_imageLoadEventTimer) {
2690 killTimer(m_imageLoadEventTimer);
2691 m_imageLoadEventTimer = 0;
2695 void DocumentImpl::dispatchImageLoadEventsNow()
2697 // need to avoid re-entering this function; if new dispatches are
2698 // scheduled before the parent finishes processing the list, they
2699 // will set a timer and eventually be processed
2700 if (!m_imageLoadEventDispatchingList.isEmpty()) {
2704 if (m_imageLoadEventTimer) {
2705 killTimer(m_imageLoadEventTimer);
2706 m_imageLoadEventTimer = 0;
2709 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2710 m_imageLoadEventDispatchSoonList.clear();
2711 for (QPtrListIterator<HTMLImageLoader> it(m_imageLoadEventDispatchingList); it.current(); ) {
2712 HTMLImageLoader* image = it.current();
2713 // Must advance iterator *before* dispatching call.
2714 // Otherwise, it might be advanced automatically if dispatching the call had a side effect
2715 // of destroying the current HTMLImageLoader, and then we would advance past the *next* item,
2716 // missing one altogether.
2718 image->dispatchLoadEvent();
2720 m_imageLoadEventDispatchingList.clear();
2723 void DocumentImpl::timerEvent(QTimerEvent *)
2725 dispatchImageLoadEventsNow();
2728 ElementImpl *DocumentImpl::ownerElement()
2730 KHTMLView *childView = view();
2733 KHTMLPart *childPart = childView->part();
2736 KHTMLPart *parent = childPart->parentPart();
2739 ChildFrame *childFrame = parent->childFrame(childPart);
2742 RenderPart *renderPart = childFrame->m_frame;
2745 return static_cast<ElementImpl *>(renderPart->element());
2748 DOMString DocumentImpl::domain() const
2750 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2751 m_domain = KURL(URL()).host(); // Initially set to the host
2755 void DocumentImpl::setDomain(const DOMString &newDomain, bool force /*=false*/)
2758 m_domain = newDomain;
2761 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2762 m_domain = KURL(URL()).host(); // Initially set to the host
2764 // Both NS and IE specify that changing the domain is only allowed when
2765 // the new domain is a suffix of the old domain.
2766 int oldLength = m_domain.length();
2767 int newLength = newDomain.length();
2768 if ( newLength < oldLength ) // e.g. newDomain=kde.org (7) and m_domain=www.kde.org (11)
2770 DOMString test = m_domain.copy();
2771 if ( test[oldLength - newLength - 1] == '.' ) // Check that it's a subdomain, not e.g. "de.org"
2773 test.remove( 0, oldLength - newLength ); // now test is "kde.org" from m_domain
2774 if ( test == newDomain ) // and we check that it's the same thing as newDomain
2775 m_domain = newDomain;
2780 bool DocumentImpl::isValidName(const DOMString &name)
2782 static const char validFirstCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz";
2783 static const char validSubsequentCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz0123456789-_:.";
2784 const unsigned length = name.length();
2787 const QChar * const characters = name.unicode();
2788 const char fc = characters[0];
2791 if (strchr(validFirstCharacter, fc) == 0)
2793 for (unsigned i = 1; i < length; ++i) {
2794 const char sc = characters[i];
2797 if (strchr(validSubsequentCharacter, sc) == 0)
2803 void DocumentImpl::addImageMap(HTMLMapElementImpl *imageMap)
2805 // Add the image map, unless there's already another with that name.
2806 // "First map wins" is the rule other browsers seem to implement.
2807 QString name = imageMap->getName().string();
2808 if (!m_imageMapsByName.contains(name))
2809 m_imageMapsByName.insert(name, imageMap);
2812 void DocumentImpl::removeImageMap(HTMLMapElementImpl *imageMap)
2814 // Remove the image map by name.
2815 // But don't remove some other image map that just happens to have the same name.
2816 QString name = imageMap->getName().string();
2817 QMapIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(name);
2818 if (it != m_imageMapsByName.end() && *it == imageMap)
2819 m_imageMapsByName.remove(it);
2822 HTMLMapElementImpl *DocumentImpl::getImageMap(const DOMString &URL) const
2828 QString s = URL.string();
2829 int hashPos = s.find('#');
2831 s = s.mid(hashPos + 1);
2833 QMapConstIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(s);
2834 if (it == m_imageMapsByName.end())
2841 void DocumentImpl::setDecoder(Decoder *decoder)
2847 m_decoder = decoder;
2850 QString DocumentImpl::completeURL(const QString &URL)
2852 return KURL(baseURL(), URL, m_decoder ? m_decoder->codec() : 0).url();
2855 bool DocumentImpl::inPageCache()
2857 return m_inPageCache;
2860 void DocumentImpl::setInPageCache(bool flag)
2862 if (m_inPageCache == flag)
2865 m_inPageCache = flag;
2867 assert(m_savedRenderer == 0);
2868 m_savedRenderer = m_render;
2870 m_view->resetScrollBars();
2873 assert(m_render == 0 || m_render == m_savedRenderer);
2874 m_render = m_savedRenderer;
2875 m_savedRenderer = 0;
2879 void DocumentImpl::passwordFieldAdded()
2884 void DocumentImpl::passwordFieldRemoved()
2886 assert(m_passwordFields > 0);
2890 bool DocumentImpl::hasPasswordField() const
2892 return m_passwordFields > 0;
2895 void DocumentImpl::secureFormAdded()
2900 void DocumentImpl::secureFormRemoved()
2902 assert(m_secureForms > 0);
2906 bool DocumentImpl::hasSecureForm() const
2908 return m_secureForms > 0;
2911 void DocumentImpl::setShouldCreateRenderers(bool f)
2913 m_createRenderers = f;
2916 bool DocumentImpl::shouldCreateRenderers()
2918 return m_createRenderers;
2921 DOMString DocumentImpl::toString() const
2925 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
2926 result += child->toString();
2932 #endif // APPLE_CHANGES
2934 // ----------------------------------------------------------------------------
2935 // Support for Javascript execCommand, and related methods
2937 JSEditor *DocumentImpl::jsEditor()
2940 m_jsEditor = new JSEditor(this);
2944 bool DocumentImpl::execCommand(const DOMString &command, bool userInterface, const DOMString &value)
2946 return jsEditor()->execCommand(command, userInterface, value);
2949 bool DocumentImpl::queryCommandEnabled(const DOMString &command)
2951 return jsEditor()->queryCommandEnabled(command);
2954 bool DocumentImpl::queryCommandIndeterm(const DOMString &command)
2956 return jsEditor()->queryCommandIndeterm(command);
2959 bool DocumentImpl::queryCommandState(const DOMString &command)
2961 return jsEditor()->queryCommandState(command);
2964 bool DocumentImpl::queryCommandSupported(const DOMString &command)
2966 return jsEditor()->queryCommandSupported(command);
2969 DOMString DocumentImpl::queryCommandValue(const DOMString &command)
2971 return jsEditor()->queryCommandValue(command);
2974 // ----------------------------------------------------------------------------
2976 void DocumentImpl::addMarker(Range range, DocumentMarker::MarkerType type)
2978 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2979 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2980 Range textPiece = markedText.range();
2981 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
2982 addMarker(textPiece.startContainer().handle(), marker);
2986 void DocumentImpl::removeMarker(Range range, DocumentMarker::MarkerType type)
2988 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2989 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2990 Range textPiece = markedText.range();
2991 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
2992 removeMarker(textPiece.startContainer().handle(), marker);
2996 // FIXME: We don't deal with markers of more than one type yet
2998 // Markers are stored in order sorted by their location. They do not overlap each other, as currently
2999 // required by the drawing code in render_text.cpp.
3001 void DocumentImpl::addMarker(NodeImpl *node, DocumentMarker newMarker)
3003 assert(newMarker.endOffset >= newMarker.startOffset);
3004 if (newMarker.endOffset == newMarker.startOffset) {
3005 return; // zero length markers are a NOP
3008 QValueList <DocumentMarker> *markers = m_markers.find(node);
3010 markers = new QValueList <DocumentMarker>();
3011 markers->append(newMarker);
3012 m_markers.insert(node, markers);
3014 QValueListIterator<DocumentMarker> it;
3015 for (it = markers->begin(); it != markers->end(); ) {
3016 DocumentMarker marker = *it;
3018 if (newMarker.endOffset < marker.startOffset+1) {
3019 // This is the first marker that is completely after newMarker, and disjoint from it.
3020 // We found our insertion point.
\10
3022 } else if (newMarker.startOffset > marker.endOffset) {
3023 // maker is before newMarker, and disjoint from it. Keep scanning.
3025 } else if (newMarker == marker) {
3026 // already have this one, NOP
3029 // marker and newMarker intersect or touch - merge them into newMarker
3030 newMarker.startOffset = kMin(newMarker.startOffset, marker.startOffset);
3031 newMarker.endOffset = kMax(newMarker.endOffset, marker.endOffset);
3032 // remove old one, we'll add newMarker later
3033 it = markers->remove(it);
3034 // it points to the next marker to consider
3037 // at this point it points to the node before which we want to insert
3038 markers->insert(it, newMarker);
3041 // repaint the affected node
3042 if (node->renderer())
3043 node->renderer()->repaint();
3046 void DocumentImpl::removeMarker(NodeImpl *node, DocumentMarker target)
3048 assert(target.endOffset >= target.startOffset);
3049 if (target.endOffset == target.startOffset) {
3050 return; // zero length markers are a NOP
3053 QValueList <DocumentMarker> *markers = m_markers.find(node);
3058 bool docDirty = false;
3059 QValueListIterator<DocumentMarker> it;
3060 for (it = markers->begin(); it != markers->end(); ) {
3061 DocumentMarker marker = *it;
3063 if (target.endOffset <= marker.startOffset) {
3064 // This is the first marker that is completely after target. All done.
3066 } else if (target.startOffset >= marker.endOffset) {
3067 // marker is before target. Keep scanning.
3070 // at this point we know that marker and target intersect in some way
3073 // pitch the old marker
3074 it = markers->remove(it);
3075 // it now points to the next node
3077 // add either of the resulting slices that are left after removing target
3078 if (target.startOffset > marker.startOffset) {
3079 DocumentMarker newLeft = marker;
3080 newLeft.endOffset = target.startOffset;
3081 markers->insert(it, newLeft);
3083 if (marker.endOffset > target.endOffset) {
3084 DocumentMarker newRight = marker;
3085 newRight.startOffset = target.endOffset;
3086 markers->insert(it, newRight);
3091 // repaint the affected node
3092 if (docDirty && node->renderer())
3093 node->renderer()->repaint();
3096 QValueList<DocumentMarker> DocumentImpl::markersForNode(NodeImpl *node)
3098 QValueList <DocumentMarker> *markers = m_markers.find(node);
3102 return QValueList <DocumentMarker> ();
3106 void DocumentImpl::removeAllMarkers(NodeImpl *node, ulong startOffset, long length)
3108 // FIXME - yet another cheat that relies on us only having one marker type
3109 DocumentMarker marker = {DocumentMarker::Spelling, startOffset, startOffset+length};
3110 removeMarker(node, marker);
3113 void DocumentImpl::removeAllMarkers(NodeImpl *node)
3115 QValueList <DocumentMarker> *markers = m_markers.find(node);
3120 void DocumentImpl::removeAllMarkers()
3125 void DocumentImpl::shiftMarkers(NodeImpl *node, ulong startOffset, long delta)
3127 if (m_markers.isEmpty())
3130 QValueList <DocumentMarker> *markers = m_markers.find(node);
3134 bool docDirty = false;
3135 QValueListIterator<DocumentMarker> it;
3136 for (it = markers->begin(); it != markers->end(); ++it) {
3137 DocumentMarker &marker = *it;
3138 if (marker.startOffset >= startOffset) {
3139 assert((int)marker.startOffset + delta >= 0);
3140 marker.startOffset += delta;
3141 marker.endOffset += delta;
3146 // repaint the affected node
3147 if (docDirty && node->renderer())
3148 node->renderer()->repaint();
3152 void DocumentImpl::applyXSLTransform(ProcessingInstructionImpl* pi)
3154 // Ref ourselves to keep from being destroyed.
3155 XSLTProcessorImpl processor(static_cast<XSLStyleSheetImpl*>(pi->sheet()), this);
3156 processor.transformDocument(this);
3158 // FIXME: If the transform failed we should probably report an error (like Mozilla does) in this
3162 void DocumentImpl::setTransformSourceDocument(DocumentImpl* doc)
3164 if (m_transformSourceDocument)
3165 m_transformSourceDocument->deref();
3166 m_transformSourceDocument = doc;
3173 void DocumentImpl::setDesignMode(InheritedBool value)
3175 m_designMode = value;
3178 DocumentImpl::InheritedBool DocumentImpl::getDesignMode() const
3180 return m_designMode;
3183 bool DocumentImpl::inDesignMode() const
3185 for (const DocumentImpl* d = this; d; d = d->parentDocument()) {
3186 if (d->m_designMode != inherit)
3187 return d->m_designMode;
3192 DocumentImpl *DocumentImpl::parentDocument() const
3194 KHTMLPart *childPart = part();
3197 KHTMLPart *parent = childPart->parentPart();
3200 return parent->xmlDocImpl();
3203 DocumentImpl *DocumentImpl::topDocument() const
3205 DocumentImpl *doc = const_cast<DocumentImpl *>(this);
3206 ElementImpl *element;
3207 while ((element = doc->ownerElement()) != 0) {
3208 doc = element->getDocument();
3209 element = doc ? doc->ownerElement() : 0;
3215 // ----------------------------------------------------------------------------
3217 DocumentFragmentImpl::DocumentFragmentImpl(DocumentPtr *doc) : NodeBaseImpl(doc)
3221 DOMString DocumentFragmentImpl::nodeName() const
3223 return "#document-fragment";
3226 unsigned short DocumentFragmentImpl::nodeType() const
3228 return Node::DOCUMENT_FRAGMENT_NODE;
3231 // DOM Section 1.1.1
3232 bool DocumentFragmentImpl::childTypeAllowed( unsigned short type )
3235 case Node::ELEMENT_NODE:
3236 case Node::PROCESSING_INSTRUCTION_NODE:
3237 case Node::COMMENT_NODE:
3238 case Node::TEXT_NODE:
3239 case Node::CDATA_SECTION_NODE:
3240 case Node::ENTITY_REFERENCE_NODE:
3247 DOMString DocumentFragmentImpl::toString() const
3251 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
3252 result += child->toString();
3259 NodeImpl *DocumentFragmentImpl::cloneNode ( bool deep )
3261 DocumentFragmentImpl *clone = new DocumentFragmentImpl( docPtr() );
3263 cloneChildNodes(clone);
3268 // ----------------------------------------------------------------------------
3270 DocumentTypeImpl::DocumentTypeImpl(DOMImplementationImpl *implementation, DocumentPtr *doc,
3271 const DOMString &qualifiedName, const DOMString &publicId,
3272 const DOMString &systemId)
3273 : NodeImpl(doc), m_implementation(implementation),
3274 m_qualifiedName(qualifiedName), m_publicId(publicId), m_systemId(systemId)
3276 if (m_implementation)
3277 m_implementation->ref();
3282 // if doc is 0, it is not attached to a document and / or
3283 // therefore does not provide entities or notations. (DOM Level 3)
3286 DocumentTypeImpl::~DocumentTypeImpl()
3288 if (m_implementation)
3289 m_implementation->deref();
3291 m_entities->deref();
3293 m_notations->deref();
3296 void DocumentTypeImpl::copyFrom(const DocumentTypeImpl& other)
3298 m_qualifiedName = other.m_qualifiedName;
3299 m_publicId = other.m_publicId;
3300 m_systemId = other.m_systemId;
3301 m_subset = other.m_subset;
3304 DOMString DocumentTypeImpl::toString() const
3307 if (m_qualifiedName.isEmpty()) {
3310 result = "<!DOCTYPE ";
3311 result += m_qualifiedName;
3313 if (!m_publicId.isEmpty()) {
3314 result += " PUBLIC \"";
3315 result += m_publicId;
3317 result += m_systemId;
3319 } else if (!m_systemId.isEmpty()) {
3320 result += " SYSTEM \"";
3321 result += m_systemId;
3324 if (!m_subset.isEmpty()) {
3333 DOMString DocumentTypeImpl::nodeName() const
3338 unsigned short DocumentTypeImpl::nodeType() const
3340 return Node::DOCUMENT_TYPE_NODE;
3343 // DOM Section 1.1.1
3344 bool DocumentTypeImpl::childTypeAllowed( unsigned short /*type*/ )
3349 NodeImpl *DocumentTypeImpl::cloneNode ( bool /*deep*/ )
3351 // Spec says cloning Document nodes is "implementation dependent"
3352 // so we do not support it...
3356 #include "dom_docimpl.moc"