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) {
1186 // Empty out these lists as a performance optimization, since detaching
1187 // all the individual render objects will cause all the RenderImage
1188 // objects to remove themselves from the lists.
1189 m_imageLoadEventDispatchSoonList.clear();
1190 m_imageLoadEventDispatchingList.clear();
1192 NodeBaseImpl::detach();
1197 if (m_paintDevice == m_view)
1202 delete m_renderArena;
1208 KWQAccObjectCache* DocumentImpl::getOrCreateAccObjectCache()
1211 m_accCache = new KWQAccObjectCache;
1216 void DocumentImpl::setVisuallyOrdered()
1218 visuallyOrdered = true;
1220 m_render->style()->setVisuallyOrdered(true);
1223 void DocumentImpl::updateSelection()
1228 RenderCanvas *canvas = static_cast<RenderCanvas*>(m_render);
1229 Selection s = part()->selection();
1231 canvas->clearSelection();
1233 if (KWQAccObjectCache::accessibilityEnabled())
1234 getOrCreateAccObjectCache()->postNotification(renderer(), "AXSelectedTextChanged");
1238 Position startPos = VisiblePosition(s.start(), UPSTREAM).deepEquivalent();
1239 Position endPos = VisiblePosition(s.end(), DOWNSTREAM).deepEquivalent();
1240 if (startPos.isNotNull() && endPos.isNotNull()) {
1241 RenderObject *startRenderer = startPos.node()->renderer();
1242 RenderObject *endRenderer = endPos.node()->renderer();
1243 static_cast<RenderCanvas*>(m_render)->setSelection(startRenderer, startPos.offset(), endRenderer, endPos.offset());
1245 if (KWQAccObjectCache::accessibilityEnabled())
1246 getOrCreateAccObjectCache()->postNotification(renderer(), "AXSelectedTextChanged");
1252 Tokenizer *DocumentImpl::createTokenizer()
1254 return newXMLTokenizer(docPtr(), m_view);
1257 void DocumentImpl::setPaintDevice( QPaintDevice *dev )
1259 if (m_paintDevice == dev) {
1262 m_paintDevice = dev;
1263 delete m_paintDeviceMetrics;
1264 m_paintDeviceMetrics = dev ? new QPaintDeviceMetrics( dev ) : 0;
1267 void DocumentImpl::open( )
1269 if (parsing()) return;
1275 m_tokenizer = createTokenizer();
1276 connect(m_tokenizer,SIGNAL(finishedParsing()),this,SIGNAL(finishedParsing()));
1278 if (m_view && m_view->part()->jScript()) {
1279 m_view->part()->jScript()->setSourceFile(m_url,""); //fixme
1283 HTMLElementImpl* DocumentImpl::body()
1285 NodeImpl *de = documentElement();
1289 // try to prefer a FRAMESET element over BODY
1291 for (NodeImpl* i = de->firstChild(); i; i = i->nextSibling()) {
1292 if (i->id() == ID_FRAMESET)
1293 return static_cast<HTMLElementImpl*>(i);
1295 if (i->id() == ID_BODY)
1298 return static_cast<HTMLElementImpl *>(body);
1301 void DocumentImpl::close()
1303 // First fire the onload.
1305 bool wasLocationChangePending = part() && part()->isScheduledLocationChangePending();
1306 bool doload = !parsing() && m_tokenizer && !m_processingLoadEvent && !wasLocationChangePending;
1308 if (body() && doload) {
1309 m_processingLoadEvent = true;
1310 // We have to clear the tokenizer, in case someone document.write()s from the
1311 // onLoad event handler, as in Radar 3206524
1314 dispatchImageLoadEventsNow();
1315 body()->dispatchWindowEvent(EventImpl::LOAD_EVENT, false, false);
1317 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1318 if (!ownerElement())
1319 printf("onload fired at %d\n", elapsedTime());
1321 m_processingLoadEvent = false;
1324 // Make sure both the initial layout and reflow happen after the onload
1325 // fires. This will improve onload scores, and other browsers do it.
1326 // If they wanna cheat, we can too. -dwh
1328 bool isLocationChangePending = part() && part()->isScheduledLocationChangePending();
1330 if (doload && isLocationChangePending && m_startTime.elapsed() < cLayoutScheduleThreshold) {
1331 // Just bail out. Before or during the onload we were shifted to another page.
1332 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
1335 view()->unscheduleRelayout();
1339 // The initial layout happens here.
1340 DocumentImpl::closeInternal(!doload);
1342 // Now do our painting/layout, but only if we aren't in a subframe or if we're in a subframe
1343 // that has been sized already. Otherwise, our view size would be incorrect, so doing any
1344 // layout/painting now would be pointless.
1346 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
1349 // Always do a layout after loading if needed.
1350 if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
1354 if (renderer() && KWQAccObjectCache::accessibilityEnabled())
1355 getOrCreateAccObjectCache()->postNotification(renderer(), "AXLoadComplete");
1360 void DocumentImpl::closeInternal( bool checkTokenizer )
1362 if (parsing() || (checkTokenizer && !m_tokenizer)) return;
1364 // on an explicit document.close(), the tokenizer might still be waiting on scripts,
1365 // and in that case we don't want to destroy it because that will prevent the
1366 // scripts from getting processed.
1367 if (m_tokenizer && !m_tokenizer->isWaitingForScripts()) {
1373 m_view->part()->checkEmitLoadEvent();
1376 void DocumentImpl::setParsing(bool b)
1379 if (!m_bParsing && view())
1380 view()->scheduleRelayout();
1382 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1383 if (!ownerElement() && !m_bParsing)
1384 printf("Parsing finished at %d\n", elapsedTime());
1388 bool DocumentImpl::shouldScheduleLayout()
1390 // We can update layout if:
1391 // (a) we actually need a layout
1392 // (b) our stylesheets are all loaded
1393 // (c) we have a <body>
1394 return (renderer() && renderer()->needsLayout() && haveStylesheetsLoaded() &&
1395 documentElement() && documentElement()->renderer() &&
1396 (documentElement()->id() != ID_HTML || body()));
1399 int DocumentImpl::minimumLayoutDelay()
1401 if (m_overMinimumLayoutThreshold)
1404 int elapsed = m_startTime.elapsed();
1405 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
1407 // We'll want to schedule the timer to fire at the minimum layout threshold.
1408 return kMax(0, cLayoutScheduleThreshold - elapsed);
1411 int DocumentImpl::elapsedTime() const
1413 return m_startTime.elapsed();
1416 void DocumentImpl::write( const DOMString &text )
1418 write(text.string());
1421 void DocumentImpl::write( const QString &text )
1423 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1424 if (!ownerElement())
1425 printf("Beginning a document.write at %d\n", elapsedTime());
1430 write(QString::fromLatin1("<html>"));
1432 m_tokenizer->write(text, false);
1434 if (m_view && m_view->part()->jScript())
1435 m_view->part()->jScript()->appendSourceFile(m_url,text);
1437 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1438 if (!ownerElement())
1439 printf("Ending a document.write at %d\n", elapsedTime());
1443 void DocumentImpl::writeln( const DOMString &text )
1446 write(DOMString("\n"));
1449 void DocumentImpl::finishParsing()
1451 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1452 if (!ownerElement())
1453 printf("Received all data at %d\n", elapsedTime());
1456 // Let the tokenizer go through as much data as it can. There will be three possible outcomes after
1457 // finish() is called:
1458 // (1) All remaining data is parsed, document isn't loaded yet
1459 // (2) All remaining data is parsed, document is loaded, tokenizer gets deleted
1460 // (3) Data is still remaining to be parsed.
1462 m_tokenizer->finish();
1465 void DocumentImpl::clear()
1471 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
1472 for (; it.current();)
1473 m_windowEventListeners.removeRef(it.current());
1476 void DocumentImpl::setURL(const QString& url)
1479 if (m_styleSelector)
1480 m_styleSelector->setEncodedURL(m_url);
1483 void DocumentImpl::setStyleSheet(const DOMString &url, const DOMString &sheet)
1485 // kdDebug( 6030 ) << "HTMLDocument::setStyleSheet()" << endl;
1486 m_sheet = new CSSStyleSheetImpl(this, url);
1488 m_sheet->parseString(sheet);
1489 m_loadingSheet = false;
1491 updateStyleSelector();
1494 void DocumentImpl::setUserStyleSheet( const QString& sheet )
1496 if ( m_usersheet != sheet ) {
1497 m_usersheet = sheet;
1498 updateStyleSelector();
1502 CSSStyleSheetImpl* DocumentImpl::elementSheet()
1505 m_elemSheet = new CSSStyleSheetImpl(this, baseURL() );
1511 void DocumentImpl::determineParseMode( const QString &/*str*/ )
1513 // For XML documents use strict parse mode. HTML docs will override this method to
1514 // determine their parse mode.
1517 kdDebug(6020) << " using strict parseMode" << endl;
1520 // Please see if there`s a possibility to merge that code
1521 // with the next function and getElementByID().
1522 NodeImpl *DocumentImpl::findElement( Id id )
1524 QPtrStack<NodeImpl> nodeStack;
1525 NodeImpl *current = _first;
1531 if(nodeStack.isEmpty()) break;
1532 current = nodeStack.pop();
1533 current = current->nextSibling();
1537 if(current->id() == id)
1540 NodeImpl *child = current->firstChild();
1543 nodeStack.push(current);
1548 current = current->nextSibling();
1556 NodeImpl *DocumentImpl::nextFocusNode(NodeImpl *fromNode)
1558 unsigned short fromTabIndex;
1561 // No starting node supplied; begin with the top of the document
1564 int lowestTabIndex = 65535;
1565 for (n = this; n != 0; n = n->traverseNextNode()) {
1566 if (n->isKeyboardFocusable()) {
1567 if ((n->tabIndex() > 0) && (n->tabIndex() < lowestTabIndex))
1568 lowestTabIndex = n->tabIndex();
1572 if (lowestTabIndex == 65535)
1575 // Go to the first node in the document that has the desired tab index
1576 for (n = this; n != 0; n = n->traverseNextNode()) {
1577 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestTabIndex))
1584 fromTabIndex = fromNode->tabIndex();
1587 if (fromTabIndex == 0) {
1588 // Just need to find the next selectable node after fromNode (in document order) that doesn't have a tab index
1589 NodeImpl *n = fromNode->traverseNextNode();
1590 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1591 n = n->traverseNextNode();
1595 // Find the lowest tab index out of all the nodes except fromNode, that is greater than or equal to fromNode's
1596 // tab index. For nodes with the same tab index as fromNode, we are only interested in those that come after
1597 // fromNode in document order.
1598 // If we don't find a suitable tab index, the next focus node will be one with a tab index of 0.
1599 unsigned short lowestSuitableTabIndex = 65535;
1602 bool reachedFromNode = false;
1603 for (n = this; n != 0; n = n->traverseNextNode()) {
1604 if (n->isKeyboardFocusable() &&
1605 ((reachedFromNode && (n->tabIndex() >= fromTabIndex)) ||
1606 (!reachedFromNode && (n->tabIndex() > fromTabIndex))) &&
1607 (n->tabIndex() < lowestSuitableTabIndex) &&
1610 // We found a selectable node with a tab index at least as high as fromNode's. Keep searching though,
1611 // as there may be another node which has a lower tab index but is still suitable for use.
1612 lowestSuitableTabIndex = n->tabIndex();
1616 reachedFromNode = true;
1619 if (lowestSuitableTabIndex == 65535) {
1620 // No next node with a tab index -> just take first node with tab index of 0
1622 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1623 n = n->traverseNextNode();
1627 // Search forwards from fromNode
1628 for (n = fromNode->traverseNextNode(); n != 0; n = n->traverseNextNode()) {
1629 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1633 // The next node isn't after fromNode, start from the beginning of the document
1634 for (n = this; n != fromNode; n = n->traverseNextNode()) {
1635 if (n->isKeyboardFocusable() && (n->tabIndex() == lowestSuitableTabIndex))
1639 assert(false); // should never get here
1644 NodeImpl *DocumentImpl::previousFocusNode(NodeImpl *fromNode)
1646 NodeImpl *lastNode = this;
1647 while (lastNode->lastChild())
1648 lastNode = lastNode->lastChild();
1651 // No starting node supplied; begin with the very last node in the document
1654 int highestTabIndex = 0;
1655 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1656 if (n->isKeyboardFocusable()) {
1657 if (n->tabIndex() == 0)
1659 else if (n->tabIndex() > highestTabIndex)
1660 highestTabIndex = n->tabIndex();
1664 // No node with a tab index of 0; just go to the last node with the highest tab index
1665 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1666 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1673 unsigned short fromTabIndex = fromNode->tabIndex();
1675 if (fromTabIndex == 0) {
1676 // Find the previous selectable node before fromNode (in document order) that doesn't have a tab index
1677 NodeImpl *n = fromNode->traversePreviousNode();
1678 while (n && !(n->isKeyboardFocusable() && n->tabIndex() == 0))
1679 n = n->traversePreviousNode();
1683 // No previous nodes with a 0 tab index, go to the last node in the document that has the highest tab index
1684 int highestTabIndex = 0;
1685 for (n = this; n != 0; n = n->traverseNextNode()) {
1686 if (n->isKeyboardFocusable() && (n->tabIndex() > highestTabIndex))
1687 highestTabIndex = n->tabIndex();
1690 if (highestTabIndex == 0)
1693 for (n = lastNode; n != 0; n = n->traversePreviousNode()) {
1694 if (n->isKeyboardFocusable() && (n->tabIndex() == highestTabIndex))
1698 assert(false); // should never get here
1702 // Find the lowest tab index out of all the nodes except fromNode, that is less than or equal to fromNode's
1703 // tab index. For nodes with the same tab index as fromNode, we are only interested in those before
1705 // If we don't find a suitable tab index, then there will be no previous focus node.
1706 unsigned short highestSuitableTabIndex = 0;
1709 bool reachedFromNode = false;
1710 for (n = this; n != 0; n = n->traverseNextNode()) {
1711 if (n->isKeyboardFocusable() &&
1712 ((!reachedFromNode && (n->tabIndex() <= fromTabIndex)) ||
1713 (reachedFromNode && (n->tabIndex() < fromTabIndex))) &&
1714 (n->tabIndex() > highestSuitableTabIndex) &&
1717 // We found a selectable node with a tab index no higher than fromNode's. Keep searching though, as
1718 // there may be another node which has a higher tab index but is still suitable for use.
1719 highestSuitableTabIndex = n->tabIndex();
1723 reachedFromNode = true;
1726 if (highestSuitableTabIndex == 0) {
1727 // No previous node with a tab index. Since the order specified by HTML is nodes with tab index > 0
1728 // first, this means that there is no previous node.
1732 // Search backwards from fromNode
1733 for (n = fromNode->traversePreviousNode(); n != 0; n = n->traversePreviousNode()) {
1734 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1737 // The previous node isn't before fromNode, start from the end of the document
1738 for (n = lastNode; n != fromNode; n = n->traversePreviousNode()) {
1739 if (n->isKeyboardFocusable() && (n->tabIndex() == highestSuitableTabIndex))
1743 assert(false); // should never get here
1749 int DocumentImpl::nodeAbsIndex(NodeImpl *node)
1751 assert(node->getDocument() == this);
1754 for (NodeImpl *n = node; n && n != this; n = n->traversePreviousNode())
1759 NodeImpl *DocumentImpl::nodeWithAbsIndex(int absIndex)
1762 for (int i = 0; n && (i < absIndex); i++) {
1763 n = n->traverseNextNode();
1768 void DocumentImpl::processHttpEquiv(const DOMString &equiv, const DOMString &content)
1770 assert(!equiv.isNull() && !content.isNull());
1772 KHTMLPart *part = getDocument()->part();
1774 if (strcasecmp(equiv, "default-style") == 0) {
1775 // The preferred style set has been overridden as per section
1776 // 14.3.2 of the HTML4.0 specification. We need to update the
1777 // sheet used variable and then update our style selector.
1778 // For more info, see the test at:
1779 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
1781 part->d->m_sheetUsed = content.string();
1782 m_preferredStylesheetSet = content;
1783 updateStyleSelector();
1785 else if(strcasecmp(equiv, "refresh") == 0 && part->metaRefreshEnabled())
1787 // get delay and url
1788 QString str = content.string().stripWhiteSpace();
1789 int pos = str.find(QRegExp("[;,]"));
1791 pos = str.find(QRegExp("[ \t]"));
1793 if (pos == -1) // There can be no url (David)
1797 delay = str.toInt(&ok);
1799 // We want a new history item if the refresh timeout > 1 second
1800 if(ok && part) part->scheduleRedirection(delay, part->url().url(), delay <= 1);
1802 if(ok && part) part->scheduleRedirection(delay, part->url().url() );
1807 delay = str.left(pos).stripWhiteSpace().toDouble(&ok);
1810 while(pos < (int)str.length() && str[pos].isSpace()) pos++;
1812 if(str.find("url", 0, false ) == 0) str = str.mid(3);
1813 str = str.stripWhiteSpace();
1814 if ( str.length() && str[0] == '=' ) str = str.mid( 1 ).stripWhiteSpace();
1815 str = parseURL( DOMString(str) ).string();
1818 // We want a new history item if the refresh timeout > 1 second
1819 part->scheduleRedirection(delay, getDocument()->completeURL( str ), delay <= 1);
1821 part->scheduleRedirection(delay, getDocument()->completeURL( str ));
1825 else if(strcasecmp(equiv, "expires") == 0)
1827 QString str = content.string().stripWhiteSpace();
1828 time_t expire_date = str.toLong();
1830 m_docLoader->setExpireDate(expire_date);
1832 else if(strcasecmp(equiv, "pragma") == 0 || strcasecmp(equiv, "cache-control") == 0 && part)
1834 QString str = content.string().lower().stripWhiteSpace();
1835 KURL url = part->url();
1836 if ((str == "no-cache") && url.protocol().startsWith("http"))
1838 KIO::http_update_cache(url, true, 0);
1841 else if( (strcasecmp(equiv, "set-cookie") == 0))
1843 // ### make setCookie work on XML documents too; e.g. in case of <html:meta .....>
1844 HTMLDocumentImpl *d = static_cast<HTMLDocumentImpl *>(this);
1845 d->setCookie(content);
1849 bool DocumentImpl::prepareMouseEvent( bool readonly, int _x, int _y, MouseEvent *ev )
1852 assert(m_render->isCanvas());
1853 RenderObject::NodeInfo renderInfo(readonly, ev->type == MousePress);
1854 bool isInside = m_render->layer()->hitTest(renderInfo, _x, _y);
1855 ev->innerNode = renderInfo.innerNode();
1857 if (renderInfo.URLElement()) {
1858 assert(renderInfo.URLElement()->isElementNode());
1859 ElementImpl* e = static_cast<ElementImpl*>(renderInfo.URLElement());
1860 DOMString href = khtml::parseURL(e->getAttribute(ATTR_HREF));
1861 DOMString target = e->getAttribute(ATTR_TARGET);
1863 if (!target.isNull() && !href.isNull()) {
1864 ev->target = target;
1869 // qDebug("url: *%s*", ev->url.string().latin1());
1882 // DOM Section 1.1.1
1883 bool DocumentImpl::childAllowed( NodeImpl *newChild )
1885 // Documents may contain a maximum of one Element child
1886 if (newChild->nodeType() == Node::ELEMENT_NODE) {
1888 for (c = firstChild(); c; c = c->nextSibling()) {
1889 if (c->nodeType() == Node::ELEMENT_NODE)
1894 // Documents may contain a maximum of one DocumentType child
1895 if (newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
1897 for (c = firstChild(); c; c = c->nextSibling()) {
1898 if (c->nodeType() == Node::DOCUMENT_TYPE_NODE)
1903 return childTypeAllowed(newChild->nodeType());
1906 bool DocumentImpl::childTypeAllowed( unsigned short type )
1909 case Node::ELEMENT_NODE:
1910 case Node::PROCESSING_INSTRUCTION_NODE:
1911 case Node::COMMENT_NODE:
1912 case Node::DOCUMENT_TYPE_NODE:
1919 NodeImpl *DocumentImpl::cloneNode ( bool /*deep*/ )
1921 // Spec says cloning Document nodes is "implementation dependent"
1922 // so we do not support it...
1926 NodeImpl::Id DocumentImpl::attrId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
1928 // Each document maintains a mapping of attrname -> id for every attr name
1929 // encountered in the document.
1930 // For attrnames without a prefix (no qualified element name) and without matching
1931 // namespace, the value defined in misc/htmlattrs.h is used.
1932 NodeImpl::Id id = 0;
1934 // First see if it's a HTML attribute name
1935 QConstString n(_name->s, _name->l);
1936 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
1937 // we're in HTML namespace if we know the tag.
1938 // xhtml is lower case - case sensitive, easy to implement
1939 if ( htmlMode() == XHtml && (id = getAttrID(n.string().ascii(), _name->l)) )
1941 // compatibility: upper case - case insensitive
1942 if ( htmlMode() != XHtml && (id = getAttrID(n.string().lower().ascii(), _name->l )) )
1945 // ok, the fast path didn't work out, we need the full check
1948 // now lets find out the namespace
1949 Q_UINT16 ns = noNamespace;
1950 if (_namespaceURI) {
1951 DOMString nsU(_namespaceURI);
1952 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
1954 ns = (Q_UINT16)nsID;
1957 // Look in the m_attrNames array for the name
1958 // ### yeah, this is lame. use a dictionary / map instead
1959 DOMString nme(n.string());
1960 // compatibility mode has to store upper case
1961 if (htmlMode() != XHtml) nme = nme.upper();
1962 for (id = 0; id < m_attrNameCount; id++)
1963 if (DOMString(m_attrNames[id]) == nme)
1964 return makeId(ns, ATTR_LAST_ATTR+id);
1967 if (readonly) return 0;
1969 // Name not found in m_attrNames, so let's add it
1970 // ### yeah, this is lame. use a dictionary / map instead
1971 if (m_attrNameCount+1 > m_attrNameAlloc) {
1972 m_attrNameAlloc += 100;
1973 DOMStringImpl **newNames = new DOMStringImpl* [m_attrNameAlloc];
1976 for (i = 0; i < m_attrNameCount; i++)
1977 newNames[i] = m_attrNames[i];
1978 delete [] m_attrNames;
1980 m_attrNames = newNames;
1983 id = m_attrNameCount++;
1984 m_attrNames[id] = nme.implementation();
1985 m_attrNames[id]->ref();
1987 return makeId(ns, ATTR_LAST_ATTR+id);
1990 DOMString DocumentImpl::attrName(NodeImpl::Id _id) const
1993 if (localNamePart(_id) >= ATTR_LAST_ATTR)
1994 result = m_attrNames[localNamePart(_id)-ATTR_LAST_ATTR];
1996 result = getAttrName(_id);
1998 // Attribute names are always lowercase in the DOM for both
2000 if (getDocument()->isHTMLDocument() ||
2001 getDocument()->htmlMode() == DocumentImpl::XHtml)
2002 return result.lower();
2007 NodeImpl::Id DocumentImpl::tagId(DOMStringImpl* _namespaceURI, DOMStringImpl *_name, bool readonly)
2009 if (!_name) return 0;
2010 // Each document maintains a mapping of tag name -> id for every tag name encountered
2012 NodeImpl::Id id = 0;
2014 // First see if it's a HTML element name
2015 QConstString n(_name->s, _name->l);
2016 if (!_namespaceURI || !strcasecmp(_namespaceURI, XHTML_NAMESPACE)) {
2017 // we're in HTML namespace if we know the tag.
2018 // xhtml is lower case - case sensitive, easy to implement
2019 if ( htmlMode() == XHtml && (id = getTagID(n.string().ascii(), _name->l)) )
2021 // compatibility: upper case - case insensitive
2022 if ( htmlMode() != XHtml && (id = getTagID(n.string().lower().ascii(), _name->l )) )
2025 // ok, the fast path didn't work out, we need the full check
2028 // now lets find out the namespace
2029 Q_UINT16 ns = noNamespace;
2030 if (_namespaceURI) {
2031 DOMString nsU(_namespaceURI);
2032 int nsID = XmlNamespaceTable::getNamespaceID(nsU, readonly);
2034 ns = (Q_UINT16)nsID;
2037 // Look in the m_elementNames array for the name
2038 // ### yeah, this is lame. use a dictionary / map instead
2039 DOMString nme(n.string());
2040 // compatibility mode has to store upper case
2041 if (htmlMode() != XHtml) nme = nme.upper();
2042 for (id = 0; id < m_elementNameCount; id++)
2043 if (DOMString(m_elementNames[id]) == nme)
2044 return makeId(ns, ID_LAST_TAG+id);
2047 if (readonly) return 0;
2049 // Name not found in m_elementNames, so let's add it
2050 if (m_elementNameCount+1 > m_elementNameAlloc) {
2051 m_elementNameAlloc += 100;
2052 DOMStringImpl **newNames = new DOMStringImpl* [m_elementNameAlloc];
2053 // ### yeah, this is lame. use a dictionary / map instead
2054 if (m_elementNames) {
2056 for (i = 0; i < m_elementNameCount; i++)
2057 newNames[i] = m_elementNames[i];
2058 delete [] m_elementNames;
2060 m_elementNames = newNames;
2063 id = m_elementNameCount++;
2064 m_elementNames[id] = nme.implementation();
2065 m_elementNames[id]->ref();
2067 return makeId(ns, ID_LAST_TAG+id);
2070 DOMString DocumentImpl::tagName(NodeImpl::Id _id) const
2072 if (localNamePart(_id) >= ID_LAST_TAG)
2073 return m_elementNames[localNamePart(_id)-ID_LAST_TAG];
2075 // ### put them in a cache
2076 if (getDocument()->htmlMode() == DocumentImpl::XHtml)
2077 return getTagName(_id).lower();
2079 return getTagName(_id);
2084 DOMStringImpl* DocumentImpl::namespaceURI(NodeImpl::Id _id) const
2086 if (_id < ID_LAST_TAG)
2087 return htmlMode() == XHtml ? XmlNamespaceTable::getNamespaceURI(xhtmlNamespace).implementation() : 0;
2089 unsigned short ns = _id >> 16;
2093 return XmlNamespaceTable::getNamespaceURI(ns).implementation();
2096 StyleSheetListImpl* DocumentImpl::styleSheets()
2098 return m_styleSheets;
2102 DocumentImpl::preferredStylesheetSet()
2104 return m_preferredStylesheetSet;
2108 DocumentImpl::selectedStylesheetSet()
2110 return view() ? view()->part()->d->m_sheetUsed : DOMString();
2114 DocumentImpl::setSelectedStylesheetSet(const DOMString& aString)
2117 view()->part()->d->m_sheetUsed = aString.string();
2118 updateStyleSelector();
2120 renderer()->repaint();
2124 // This method is called whenever a top-level stylesheet has finished loading.
2125 void DocumentImpl::stylesheetLoaded()
2127 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2128 assert(m_pendingStylesheets > 0);
2130 m_pendingStylesheets--;
2132 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2133 if (!ownerElement())
2134 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2137 updateStyleSelector();
2140 void DocumentImpl::updateStyleSelector()
2142 // Don't bother updating, since we haven't loaded all our style info yet.
2143 if (!haveStylesheetsLoaded())
2146 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2147 if (!ownerElement())
2148 printf("Beginning update of style selector at time %d.\n", elapsedTime());
2151 recalcStyleSelector();
2155 m_styleSelectorDirty = true;
2158 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2159 if (!ownerElement())
2160 printf("Finished update of style selector at time %d\n", elapsedTime());
2164 renderer()->setNeedsLayoutAndMinMaxRecalc();
2166 view()->scheduleRelayout();
2171 QStringList DocumentImpl::availableStyleSheets() const
2173 return m_availableSheets;
2176 void DocumentImpl::recalcStyleSelector()
2178 if ( !m_render || !attached() ) return;
2180 QPtrList<StyleSheetImpl> oldStyleSheets = m_styleSheets->styleSheets;
2181 m_styleSheets->styleSheets.clear();
2182 m_availableSheets.clear();
2184 for (n = this; n; n = n->traverseNextNode()) {
2185 StyleSheetImpl *sheet = 0;
2187 if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
2189 // Processing instruction (XML documents only)
2190 ProcessingInstructionImpl* pi = static_cast<ProcessingInstructionImpl*>(n);
2191 sheet = pi->sheet();
2194 applyXSLTransform(pi);
2198 if (!sheet && !pi->localHref().isEmpty())
2200 // Processing instruction with reference to an element in this document - e.g.
2201 // <?xml-stylesheet href="#mystyle">, with the element
2202 // <foo id="mystyle">heading { color: red; }</foo> at some location in
2204 ElementImpl* elem = getElementById(pi->localHref());
2206 DOMString sheetText("");
2208 for (c = elem->firstChild(); c; c = c->nextSibling()) {
2209 if (c->nodeType() == Node::TEXT_NODE || c->nodeType() == Node::CDATA_SECTION_NODE)
2210 sheetText += c->nodeValue();
2213 CSSStyleSheetImpl *cssSheet = new CSSStyleSheetImpl(this);
2214 cssSheet->parseString(sheetText);
2215 pi->setStyleSheet(cssSheet);
2221 else if (n->isHTMLElement() && (n->id() == ID_LINK || n->id() == ID_STYLE)) {
2222 ElementImpl *e = static_cast<ElementImpl *>(n);
2223 QString title = e->getAttribute( ATTR_TITLE ).string();
2224 bool enabledViaScript = false;
2225 if (n->id() == ID_LINK) {
2227 HTMLLinkElementImpl* l = static_cast<HTMLLinkElementImpl*>(n);
2228 if (l->isLoading() || l->isDisabled())
2231 title = QString::null;
2232 enabledViaScript = l->isEnabledViaScript();
2235 // Get the current preferred styleset. This is the
2236 // set of sheets that will be enabled.
2237 if ( n->id() == ID_LINK )
2238 sheet = static_cast<HTMLLinkElementImpl*>(n)->sheet();
2241 sheet = static_cast<HTMLStyleElementImpl*>(n)->sheet();
2243 // Check to see if this sheet belongs to a styleset
2244 // (thus making it PREFERRED or ALTERNATE rather than
2246 if (!enabledViaScript && !title.isEmpty()) {
2247 // Yes, we have a title.
2248 if (m_preferredStylesheetSet.isEmpty()) {
2249 // No preferred set has been established. If
2250 // we are NOT an alternate sheet, then establish
2251 // us as the preferred set. Otherwise, just ignore
2253 QString rel = e->getAttribute( ATTR_REL ).string();
2254 if (n->id() == ID_STYLE || !rel.contains("alternate"))
2255 m_preferredStylesheetSet = view()->part()->d->m_sheetUsed = title;
2258 if (!m_availableSheets.contains( title ) )
2259 m_availableSheets.append( title );
2261 if (title != m_preferredStylesheetSet)
2268 m_styleSheets->styleSheets.append(sheet);
2271 // For HTML documents, stylesheets are not allowed within/after the <BODY> tag. So we
2272 // can stop searching here.
2273 if (isHTMLDocument() && n->id() == ID_BODY)
2277 // De-reference all the stylesheets in the old list
2278 QPtrListIterator<StyleSheetImpl> it(oldStyleSheets);
2279 for (; it.current(); ++it)
2280 it.current()->deref();
2282 // Create a new style selector
2283 delete m_styleSelector;
2284 QString usersheet = m_usersheet;
2285 if ( m_view && m_view->mediaType() == "print" )
2286 usersheet += m_printSheet;
2287 m_styleSelector = new CSSStyleSelector(this, usersheet, m_styleSheets, !inCompatMode());
2288 m_styleSelector->setEncodedURL(m_url);
2289 m_styleSelectorDirty = false;
2292 void DocumentImpl::setHoverNode(NodeImpl* newHoverNode)
2294 if (m_hoverNode != newHoverNode) {
2296 m_hoverNode->deref();
2297 m_hoverNode = newHoverNode;
2305 bool DocumentImpl::relinquishesEditingFocus(NodeImpl *node)
2308 assert(node->isContentEditable());
2310 NodeImpl *rootImpl = node->rootEditableElement();
2311 if (!part() || !rootImpl)
2314 Node root(rootImpl);
2315 Range range(root, 0, root, rootImpl->childNodeCount());
2316 return part()->shouldEndEditing(range);
2319 bool DocumentImpl::acceptsEditingFocus(NodeImpl *node)
2322 assert(node->isContentEditable());
2324 NodeImpl *rootImpl = node->rootEditableElement();
2325 if (!part() || !rootImpl)
2328 Node root(rootImpl);
2329 Range range(root, 0, root, rootImpl->childNodeCount());
2330 return part()->shouldBeginEditing(range);
2333 const QValueList<DashboardRegionValue> & DocumentImpl::dashboardRegions() const
2335 return m_dashboardRegions;
2338 void DocumentImpl::setDashboardRegions (const QValueList<DashboardRegionValue>& regions)
2340 m_dashboardRegions = regions;
2341 setDashboardRegionsDirty (false);
2346 bool DocumentImpl::setFocusNode(NodeImpl *newFocusNode)
2348 // Make sure newFocusNode is actually in this document
2349 if (newFocusNode && (newFocusNode->getDocument() != this))
2352 if (m_focusNode == newFocusNode)
2356 if (m_focusNode && m_focusNode->isContentEditable() && !relinquishesEditingFocus(m_focusNode))
2360 bool focusChangeBlocked = false;
2361 NodeImpl *oldFocusNode = m_focusNode;
2364 // Remove focus from the existing focus node (if any)
2366 // This goes hand in hand with the Qt focus setting below.
2367 if (!newFocusNode && getDocument()->view()) {
2368 getDocument()->view()->setFocus();
2371 if (oldFocusNode->active())
2372 oldFocusNode->setActive(false);
2374 oldFocusNode->setFocus(false);
2375 oldFocusNode->dispatchHTMLEvent(EventImpl::BLUR_EVENT, false, false);
2376 if (m_focusNode != 0) {
2377 // handler shifted focus
2378 focusChangeBlocked = true;
2381 oldFocusNode->dispatchUIEvent(EventImpl::DOMFOCUSOUT_EVENT);
2382 if (m_focusNode != 0) {
2383 // handler shifted focus
2384 focusChangeBlocked = true;
2387 if ((oldFocusNode == this) && oldFocusNode->hasOneRef()) {
2388 oldFocusNode->deref(); // deletes this
2392 oldFocusNode->deref();
2396 // Clear the selection when changing the focus node to null or to a node that is not
2397 // contained by the current selection.
2399 NodeImpl *startContainer = part()->selection().start().node();
2400 if (!newFocusNode || (startContainer && startContainer != newFocusNode && !startContainer->isAncestor(newFocusNode)))
2401 part()->clearSelection();
2406 if (newFocusNode->isContentEditable() && !acceptsEditingFocus(newFocusNode)) {
2407 // delegate blocks focus change
2408 focusChangeBlocked = true;
2409 goto SetFocusNodeDone;
2412 // Set focus on the new node
2413 m_focusNode = newFocusNode;
2415 m_focusNode->dispatchHTMLEvent(EventImpl::FOCUS_EVENT, false, false);
2416 if (m_focusNode != newFocusNode) {
2417 // handler shifted focus
2418 focusChangeBlocked = true;
2419 goto SetFocusNodeDone;
2421 m_focusNode->dispatchUIEvent(EventImpl::DOMFOCUSIN_EVENT);
2422 if (m_focusNode != newFocusNode) {
2423 // handler shifted focus
2424 focusChangeBlocked = true;
2425 goto SetFocusNodeDone;
2427 m_focusNode->setFocus();
2428 // eww, I suck. set the qt focus correctly
2429 // ### find a better place in the code for this
2430 if (getDocument()->view()) {
2431 if (!m_focusNode->renderer() || !m_focusNode->renderer()->isWidget())
2432 getDocument()->view()->setFocus();
2433 else if (static_cast<RenderWidget*>(m_focusNode->renderer())->widget())
2434 static_cast<RenderWidget*>(m_focusNode->renderer())->widget()->setFocus();
2439 if (!focusChangeBlocked && KWQAccObjectCache::accessibilityEnabled())
2440 getOrCreateAccObjectCache()->postNotification(renderer(), "AXFocusedUIElementChanged");
2445 return !focusChangeBlocked;
2448 void DocumentImpl::setCSSTarget(NodeImpl* n)
2451 m_cssTarget->setChanged();
2457 NodeImpl* DocumentImpl::getCSSTarget()
2462 void DocumentImpl::attachNodeIterator(NodeIteratorImpl *ni)
2464 m_nodeIterators.append(ni);
2467 void DocumentImpl::detachNodeIterator(NodeIteratorImpl *ni)
2469 m_nodeIterators.remove(ni);
2472 void DocumentImpl::notifyBeforeNodeRemoval(NodeImpl *n)
2474 QPtrListIterator<NodeIteratorImpl> it(m_nodeIterators);
2475 for (; it.current(); ++it)
2476 it.current()->notifyBeforeNodeRemoval(n);
2479 AbstractViewImpl *DocumentImpl::defaultView() const
2481 return m_defaultView;
2484 EventImpl *DocumentImpl::createEvent(const DOMString &eventType, int &exceptioncode)
2486 if (eventType == "UIEvents")
2487 return new UIEventImpl();
2488 else if (eventType == "MouseEvents")
2489 return new MouseEventImpl();
2490 else if (eventType == "MutationEvents")
2491 return new MutationEventImpl();
2492 else if (eventType == "KeyboardEvents")
2493 return new KeyboardEventImpl();
2494 else if (eventType == "HTMLEvents")
2495 return new EventImpl();
2497 exceptioncode = DOMException::NOT_SUPPORTED_ERR;
2502 CSSStyleDeclarationImpl *DocumentImpl::getOverrideStyle(ElementImpl */*elt*/, DOMStringImpl */*pseudoElt*/)
2507 void DocumentImpl::defaultEventHandler(EventImpl *evt)
2509 // if any html event listeners are registered on the window, then dispatch them here
2510 QPtrList<RegisteredEventListener> listenersCopy = m_windowEventListeners;
2511 QPtrListIterator<RegisteredEventListener> it(listenersCopy);
2513 for (; it.current(); ++it) {
2514 if (it.current()->id == evt->id()) {
2515 it.current()->listener->handleEvent(ev, true);
2520 if (evt->id()==EventImpl::KEYDOWN_EVENT) {
2521 KeyboardEventImpl *kevt = static_cast<KeyboardEventImpl *>(evt);
2522 if (kevt->ctrlKey()) {
2523 QString key = kevt->qKeyEvent()->unmodifiedText().lower();
2524 ElementImpl *elem = getElementByAccessKey(key);
2526 elem->accessKeyAction();
2527 evt->setDefaultHandled();
2533 void DocumentImpl::setHTMLWindowEventListener(int id, EventListener *listener)
2535 // If we already have it we don't want removeWindowEventListener to delete it
2538 removeHTMLWindowEventListener(id);
2540 addWindowEventListener(id, listener, false);
2545 EventListener *DocumentImpl::getHTMLWindowEventListener(int id)
2547 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2548 for (; it.current(); ++it) {
2549 if (it.current()->id == id &&
2550 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2551 return it.current()->listener;
2558 void DocumentImpl::removeHTMLWindowEventListener(int id)
2560 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2561 for (; it.current(); ++it) {
2562 if (it.current()->id == id &&
2563 it.current()->listener->eventListenerType() == "_khtml_HTMLEventListener") {
2564 m_windowEventListeners.removeRef(it.current());
2570 void DocumentImpl::addWindowEventListener(int id, EventListener *listener, const bool useCapture)
2574 // remove existing identical listener set with identical arguments - the DOM2
2575 // spec says that "duplicate instances are discarded" in this case.
2576 removeWindowEventListener(id,listener,useCapture);
2578 RegisteredEventListener *rl = new RegisteredEventListener(static_cast<EventImpl::EventId>(id), listener, useCapture);
2579 m_windowEventListeners.append(rl);
2584 void DocumentImpl::removeWindowEventListener(int id, EventListener *listener, bool useCapture)
2586 RegisteredEventListener rl(static_cast<EventImpl::EventId>(id),listener,useCapture);
2588 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2589 for (; it.current(); ++it)
2590 if (*(it.current()) == rl) {
2591 m_windowEventListeners.removeRef(it.current());
2596 bool DocumentImpl::hasWindowEventListener(int id)
2598 QPtrListIterator<RegisteredEventListener> it(m_windowEventListeners);
2599 for (; it.current(); ++it) {
2600 if (it.current()->id == id) {
2608 EventListener *DocumentImpl::createHTMLEventListener(QString code)
2611 return part()->createHTMLEventListener(code);
2617 void DocumentImpl::dispatchImageLoadEventSoon(HTMLImageLoader *image)
2619 m_imageLoadEventDispatchSoonList.append(image);
2620 if (!m_imageLoadEventTimer) {
2621 m_imageLoadEventTimer = startTimer(0);
2625 void DocumentImpl::removeImage(HTMLImageLoader* image)
2627 // Remove instances of this image from both lists.
2628 // Use loops because we allow multiple instances to get into the lists.
2629 while (m_imageLoadEventDispatchSoonList.removeRef(image)) { }
2630 while (m_imageLoadEventDispatchingList.removeRef(image)) { }
2631 if (m_imageLoadEventDispatchSoonList.isEmpty() && m_imageLoadEventTimer) {
2632 killTimer(m_imageLoadEventTimer);
2633 m_imageLoadEventTimer = 0;
2637 void DocumentImpl::dispatchImageLoadEventsNow()
2639 // need to avoid re-entering this function; if new dispatches are
2640 // scheduled before the parent finishes processing the list, they
2641 // will set a timer and eventually be processed
2642 if (!m_imageLoadEventDispatchingList.isEmpty()) {
2646 if (m_imageLoadEventTimer) {
2647 killTimer(m_imageLoadEventTimer);
2648 m_imageLoadEventTimer = 0;
2651 m_imageLoadEventDispatchingList = m_imageLoadEventDispatchSoonList;
2652 m_imageLoadEventDispatchSoonList.clear();
2653 for (QPtrListIterator<HTMLImageLoader> it(m_imageLoadEventDispatchingList); it.current(); ) {
2654 HTMLImageLoader* image = it.current();
2655 // Must advance iterator *before* dispatching call.
2656 // Otherwise, it might be advanced automatically if dispatching the call had a side effect
2657 // of destroying the current HTMLImageLoader, and then we would advance past the *next* item,
2658 // missing one altogether.
2660 image->dispatchLoadEvent();
2662 m_imageLoadEventDispatchingList.clear();
2665 void DocumentImpl::timerEvent(QTimerEvent *)
2667 dispatchImageLoadEventsNow();
2670 ElementImpl *DocumentImpl::ownerElement()
2672 KHTMLView *childView = view();
2675 KHTMLPart *childPart = childView->part();
2678 KHTMLPart *parent = childPart->parentPart();
2681 ChildFrame *childFrame = parent->childFrame(childPart);
2684 RenderPart *renderPart = childFrame->m_frame;
2687 return static_cast<ElementImpl *>(renderPart->element());
2690 DOMString DocumentImpl::domain() const
2692 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2693 m_domain = KURL(URL()).host(); // Initially set to the host
2697 void DocumentImpl::setDomain(const DOMString &newDomain, bool force /*=false*/)
2700 m_domain = newDomain;
2703 if ( m_domain.isEmpty() ) // not set yet (we set it on demand to save time and space)
2704 m_domain = KURL(URL()).host(); // Initially set to the host
2706 // Both NS and IE specify that changing the domain is only allowed when
2707 // the new domain is a suffix of the old domain.
2708 int oldLength = m_domain.length();
2709 int newLength = newDomain.length();
2710 if ( newLength < oldLength ) // e.g. newDomain=kde.org (7) and m_domain=www.kde.org (11)
2712 DOMString test = m_domain.copy();
2713 if ( test[oldLength - newLength - 1] == '.' ) // Check that it's a subdomain, not e.g. "de.org"
2715 test.remove( 0, oldLength - newLength ); // now test is "kde.org" from m_domain
2716 if ( test == newDomain ) // and we check that it's the same thing as newDomain
2717 m_domain = newDomain;
2722 bool DocumentImpl::isValidName(const DOMString &name)
2724 static const char validFirstCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz";
2725 static const char validSubsequentCharacter[] = "ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz0123456789-_:.";
2726 const unsigned length = name.length();
2729 const QChar * const characters = name.unicode();
2730 const char fc = characters[0];
2733 if (strchr(validFirstCharacter, fc) == 0)
2735 for (unsigned i = 1; i < length; ++i) {
2736 const char sc = characters[i];
2739 if (strchr(validSubsequentCharacter, sc) == 0)
2745 void DocumentImpl::addImageMap(HTMLMapElementImpl *imageMap)
2747 // Add the image map, unless there's already another with that name.
2748 // "First map wins" is the rule other browsers seem to implement.
2749 QString name = imageMap->getName().string();
2750 if (!m_imageMapsByName.contains(name))
2751 m_imageMapsByName.insert(name, imageMap);
2754 void DocumentImpl::removeImageMap(HTMLMapElementImpl *imageMap)
2756 // Remove the image map by name.
2757 // But don't remove some other image map that just happens to have the same name.
2758 QString name = imageMap->getName().string();
2759 QMapIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(name);
2760 if (it != m_imageMapsByName.end() && *it == imageMap)
2761 m_imageMapsByName.remove(it);
2764 HTMLMapElementImpl *DocumentImpl::getImageMap(const DOMString &URL) const
2770 QString s = URL.string();
2771 int hashPos = s.find('#');
2773 s = s.mid(hashPos + 1);
2775 QMapConstIterator<QString, HTMLMapElementImpl *> it = m_imageMapsByName.find(s);
2776 if (it == m_imageMapsByName.end())
2783 void DocumentImpl::setDecoder(Decoder *decoder)
2789 m_decoder = decoder;
2792 QString DocumentImpl::completeURL(const QString &URL)
2794 return KURL(baseURL(), URL, m_decoder ? m_decoder->codec() : 0).url();
2797 bool DocumentImpl::inPageCache()
2799 return m_inPageCache;
2802 void DocumentImpl::setInPageCache(bool flag)
2804 if (m_inPageCache == flag)
2807 m_inPageCache = flag;
2809 assert(m_savedRenderer == 0);
2810 m_savedRenderer = m_render;
2812 m_view->resetScrollBars();
2815 assert(m_render == 0 || m_render == m_savedRenderer);
2816 m_render = m_savedRenderer;
2817 m_savedRenderer = 0;
2821 void DocumentImpl::passwordFieldAdded()
2826 void DocumentImpl::passwordFieldRemoved()
2828 assert(m_passwordFields > 0);
2832 bool DocumentImpl::hasPasswordField() const
2834 return m_passwordFields > 0;
2837 void DocumentImpl::secureFormAdded()
2842 void DocumentImpl::secureFormRemoved()
2844 assert(m_secureForms > 0);
2848 bool DocumentImpl::hasSecureForm() const
2850 return m_secureForms > 0;
2853 void DocumentImpl::setShouldCreateRenderers(bool f)
2855 m_createRenderers = f;
2858 bool DocumentImpl::shouldCreateRenderers()
2860 return m_createRenderers;
2863 DOMString DocumentImpl::toString() const
2867 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
2868 result += child->toString();
2874 #endif // APPLE_CHANGES
2876 // ----------------------------------------------------------------------------
2877 // Support for Javascript execCommand, and related methods
2879 JSEditor *DocumentImpl::jsEditor()
2882 m_jsEditor = new JSEditor(this);
2886 bool DocumentImpl::execCommand(const DOMString &command, bool userInterface, const DOMString &value)
2888 return jsEditor()->execCommand(command, userInterface, value);
2891 bool DocumentImpl::queryCommandEnabled(const DOMString &command)
2893 return jsEditor()->queryCommandEnabled(command);
2896 bool DocumentImpl::queryCommandIndeterm(const DOMString &command)
2898 return jsEditor()->queryCommandIndeterm(command);
2901 bool DocumentImpl::queryCommandState(const DOMString &command)
2903 return jsEditor()->queryCommandState(command);
2906 bool DocumentImpl::queryCommandSupported(const DOMString &command)
2908 return jsEditor()->queryCommandSupported(command);
2911 DOMString DocumentImpl::queryCommandValue(const DOMString &command)
2913 return jsEditor()->queryCommandValue(command);
2916 // ----------------------------------------------------------------------------
2918 void DocumentImpl::addMarker(Range range, DocumentMarker::MarkerType type)
2920 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2921 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2922 Range textPiece = markedText.range();
2923 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
2924 addMarker(textPiece.startContainer().handle(), marker);
2928 void DocumentImpl::removeMarker(Range range, DocumentMarker::MarkerType type)
2930 // Use a TextIterator to visit the potentially multiple nodes the range covers.
2931 for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
2932 Range textPiece = markedText.range();
2933 DocumentMarker marker = {type, textPiece.startOffset(), textPiece.endOffset()};
2934 removeMarker(textPiece.startContainer().handle(), marker);
2938 // FIXME: We don't deal with markers of more than one type yet
2940 // Markers are stored in order sorted by their location. They do not overlap each other, as currently
2941 // required by the drawing code in render_text.cpp.
2943 void DocumentImpl::addMarker(NodeImpl *node, DocumentMarker newMarker)
2945 assert(newMarker.endOffset >= newMarker.startOffset);
2946 if (newMarker.endOffset == newMarker.startOffset) {
2947 return; // zero length markers are a NOP
2950 QValueList <DocumentMarker> *markers = m_markers.find(node);
2952 markers = new QValueList <DocumentMarker>();
2953 markers->append(newMarker);
2954 m_markers.insert(node, markers);
2956 QValueListIterator<DocumentMarker> it;
2957 for (it = markers->begin(); it != markers->end(); ) {
2958 DocumentMarker marker = *it;
2960 if (newMarker.endOffset < marker.startOffset+1) {
2961 // This is the first marker that is completely after newMarker, and disjoint from it.
2962 // We found our insertion point.
\10
2964 } else if (newMarker.startOffset > marker.endOffset) {
2965 // maker is before newMarker, and disjoint from it. Keep scanning.
2967 } else if (newMarker == marker) {
2968 // already have this one, NOP
2971 // marker and newMarker intersect or touch - merge them into newMarker
2972 newMarker.startOffset = kMin(newMarker.startOffset, marker.startOffset);
2973 newMarker.endOffset = kMax(newMarker.endOffset, marker.endOffset);
2974 // remove old one, we'll add newMarker later
2975 it = markers->remove(it);
2976 // it points to the next marker to consider
2979 // at this point it points to the node before which we want to insert
2980 markers->insert(it, newMarker);
2983 // repaint the affected node
2984 if (node->renderer())
2985 node->renderer()->repaint();
2988 void DocumentImpl::removeMarker(NodeImpl *node, DocumentMarker target)
2990 assert(target.endOffset >= target.startOffset);
2991 if (target.endOffset == target.startOffset) {
2992 return; // zero length markers are a NOP
2995 QValueList <DocumentMarker> *markers = m_markers.find(node);
3000 bool docDirty = false;
3001 QValueListIterator<DocumentMarker> it;
3002 for (it = markers->begin(); it != markers->end(); ) {
3003 DocumentMarker marker = *it;
3005 if (target.endOffset <= marker.startOffset) {
3006 // This is the first marker that is completely after target. All done.
3008 } else if (target.startOffset >= marker.endOffset) {
3009 // marker is before target. Keep scanning.
3012 // at this point we know that marker and target intersect in some way
3015 // pitch the old marker
3016 it = markers->remove(it);
3017 // it now points to the next node
3019 // add either of the resulting slices that are left after removing target
3020 if (target.startOffset > marker.startOffset) {
3021 DocumentMarker newLeft = marker;
3022 newLeft.endOffset = target.startOffset;
3023 markers->insert(it, newLeft);
3025 if (marker.endOffset > target.endOffset) {
3026 DocumentMarker newRight = marker;
3027 newRight.startOffset = target.endOffset;
3028 markers->insert(it, newRight);
3033 // repaint the affected node
3034 if (docDirty && node->renderer())
3035 node->renderer()->repaint();
3038 QValueList<DocumentMarker> DocumentImpl::markersForNode(NodeImpl *node)
3040 QValueList <DocumentMarker> *markers = m_markers.find(node);
3044 return QValueList <DocumentMarker> ();
3048 void DocumentImpl::removeAllMarkers(NodeImpl *node, ulong startOffset, long length)
3050 // FIXME - yet another cheat that relies on us only having one marker type
3051 DocumentMarker marker = {DocumentMarker::Spelling, startOffset, startOffset+length};
3052 removeMarker(node, marker);
3055 void DocumentImpl::removeAllMarkers(NodeImpl *node)
3057 QValueList <DocumentMarker> *markers = m_markers.find(node);
3062 void DocumentImpl::removeAllMarkers()
3067 void DocumentImpl::shiftMarkers(NodeImpl *node, ulong startOffset, long delta)
3069 if (m_markers.isEmpty())
3072 QValueList <DocumentMarker> *markers = m_markers.find(node);
3076 bool docDirty = false;
3077 QValueListIterator<DocumentMarker> it;
3078 for (it = markers->begin(); it != markers->end(); ++it) {
3079 DocumentMarker &marker = *it;
3080 if (marker.startOffset >= startOffset) {
3081 assert((int)marker.startOffset + delta >= 0);
3082 marker.startOffset += delta;
3083 marker.endOffset += delta;
3088 // repaint the affected node
3089 if (docDirty && node->renderer())
3090 node->renderer()->repaint();
3094 void DocumentImpl::applyXSLTransform(ProcessingInstructionImpl* pi)
3096 // Ref ourselves to keep from being destroyed.
3097 XSLTProcessorImpl processor(static_cast<XSLStyleSheetImpl*>(pi->sheet()), this);
3098 processor.transformDocument(this);
3100 // FIXME: If the transform failed we should probably report an error (like Mozilla does) in this
3104 void DocumentImpl::setTransformSourceDocument(DocumentImpl* doc)
3106 if (m_transformSourceDocument)
3107 m_transformSourceDocument->deref();
3108 m_transformSourceDocument = doc;
3115 void DocumentImpl::setDesignMode(InheritedBool value)
3117 m_designMode = value;
3120 DocumentImpl::InheritedBool DocumentImpl::getDesignMode() const
3122 return m_designMode;
3125 bool DocumentImpl::inDesignMode() const
3127 for (const DocumentImpl* d = this; d; d = d->parentDocument()) {
3128 if (d->m_designMode != inherit)
3129 return d->m_designMode;
3134 DocumentImpl *DocumentImpl::parentDocument() const
3136 KHTMLPart *childPart = part();
3139 KHTMLPart *parent = childPart->parentPart();
3142 return parent->xmlDocImpl();
3145 // ----------------------------------------------------------------------------
3147 DocumentFragmentImpl::DocumentFragmentImpl(DocumentPtr *doc) : NodeBaseImpl(doc)
3151 DOMString DocumentFragmentImpl::nodeName() const
3153 return "#document-fragment";
3156 unsigned short DocumentFragmentImpl::nodeType() const
3158 return Node::DOCUMENT_FRAGMENT_NODE;
3161 // DOM Section 1.1.1
3162 bool DocumentFragmentImpl::childTypeAllowed( unsigned short type )
3165 case Node::ELEMENT_NODE:
3166 case Node::PROCESSING_INSTRUCTION_NODE:
3167 case Node::COMMENT_NODE:
3168 case Node::TEXT_NODE:
3169 case Node::CDATA_SECTION_NODE:
3170 case Node::ENTITY_REFERENCE_NODE:
3177 DOMString DocumentFragmentImpl::toString() const
3181 for (NodeImpl *child = firstChild(); child != NULL; child = child->nextSibling()) {
3182 result += child->toString();
3189 NodeImpl *DocumentFragmentImpl::cloneNode ( bool deep )
3191 DocumentFragmentImpl *clone = new DocumentFragmentImpl( docPtr() );
3193 cloneChildNodes(clone);
3198 // ----------------------------------------------------------------------------
3200 DocumentTypeImpl::DocumentTypeImpl(DOMImplementationImpl *implementation, DocumentPtr *doc,
3201 const DOMString &qualifiedName, const DOMString &publicId,
3202 const DOMString &systemId)
3203 : NodeImpl(doc), m_implementation(implementation),
3204 m_qualifiedName(qualifiedName), m_publicId(publicId), m_systemId(systemId)
3206 if (m_implementation)
3207 m_implementation->ref();
3212 // if doc is 0, it is not attached to a document and / or
3213 // therefore does not provide entities or notations. (DOM Level 3)
3216 DocumentTypeImpl::~DocumentTypeImpl()
3218 if (m_implementation)
3219 m_implementation->deref();
3221 m_entities->deref();
3223 m_notations->deref();
3226 void DocumentTypeImpl::copyFrom(const DocumentTypeImpl& other)
3228 m_qualifiedName = other.m_qualifiedName;
3229 m_publicId = other.m_publicId;
3230 m_systemId = other.m_systemId;
3231 m_subset = other.m_subset;
3234 DOMString DocumentTypeImpl::toString() const
3237 if (m_qualifiedName.isEmpty()) {
3240 result = "<!DOCTYPE ";
3241 result += m_qualifiedName;
3243 if (!m_publicId.isEmpty()) {
3244 result += " PUBLIC \"";
3245 result += m_publicId;
3247 result += m_systemId;
3249 } else if (!m_systemId.isEmpty()) {
3250 result += " SYSTEM \"";
3251 result += m_systemId;
3254 if (!m_subset.isEmpty()) {
3263 DOMString DocumentTypeImpl::nodeName() const
3268 unsigned short DocumentTypeImpl::nodeType() const
3270 return Node::DOCUMENT_TYPE_NODE;
3273 // DOM Section 1.1.1
3274 bool DocumentTypeImpl::childTypeAllowed( unsigned short /*type*/ )
3279 NodeImpl *DocumentTypeImpl::cloneNode ( bool /*deep*/ )
3281 // Spec says cloning Document nodes is "implementation dependent"
3282 // so we do not support it...
3286 #include "dom_docimpl.moc"