xref: /trunk/main/unoxml/source/dom/node.cxx (revision 5fa645724935a9615af828516cbb0e5d1d9ee0db)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 #include <node.hxx>
25 
26 #include <stdio.h>
27 #include <string.h>
28 
29 #include <libxml/xmlstring.h>
30 
31 #include <algorithm>
32 
33 #include <boost/bind.hpp>
34 
35 #include <rtl/uuid.h>
36 #include <rtl/instance.hxx>
37 #include <osl/mutex.hxx>
38 
39 #include <com/sun/star/xml/sax/FastToken.hpp>
40 
41 #include <document.hxx>
42 #include <attr.hxx>
43 #include <childlist.hxx>
44 
45 #include "../events/eventdispatcher.hxx"
46 #include "../events/mutationevent.hxx"
47 
48 
49 
50 using namespace ::com::sun::star;
51 
52 
53 namespace {
54     struct UnoTunnelId
55         : public ::rtl::StaticWithInit< Sequence<sal_Int8>, UnoTunnelId >
56     {
operator ()__anon2a610bde0111::UnoTunnelId57         Sequence<sal_Int8> operator() ()
58         {
59             Sequence<sal_Int8> ret(16);
60             rtl_createUuid(
61                 reinterpret_cast<sal_uInt8*>(ret.getArray()), 0, sal_True);
62             return ret;
63         }
64     };
65 }
66 
67 namespace DOM
68 {
pushContext(Context & io_rContext)69     void pushContext(Context& io_rContext)
70     {
71         io_rContext.maNamespaces.push_back(
72             io_rContext.maNamespaces.back());
73     }
74 
popContext(Context & io_rContext)75     void popContext(Context& io_rContext)
76     {
77         io_rContext.maNamespaces.pop_back();
78     }
79 
addNamespaces(Context & io_rContext,xmlNodePtr pNode)80     void addNamespaces(Context& io_rContext, xmlNodePtr pNode)
81     {
82         // add node's namespaces to current context
83         for (xmlNsPtr pNs = pNode->nsDef; pNs != 0; pNs = pNs->next) {
84             const xmlChar *pPrefix = pNs->prefix;
85             OString prefix(reinterpret_cast<const sal_Char*>(pPrefix),
86                            strlen(reinterpret_cast<const char*>(pPrefix)));
87             const xmlChar *pHref = pNs->href;
88             OUString val(reinterpret_cast<const sal_Char*>(pHref),
89                 strlen(reinterpret_cast<const char*>(pHref)),
90                 RTL_TEXTENCODING_UTF8);
91 
92             OSL_TRACE("Trying to add namespace %s (prefix %s)",
93                       (const char*)pHref, (const char*)pPrefix);
94 
95             Context::NamespaceMapType::iterator aIter=
96                 io_rContext.maNamespaceMap.find(val);
97             if( aIter != io_rContext.maNamespaceMap.end() )
98             {
99                 Context::Namespace aNS;
100                 aNS.maPrefix = prefix;
101                 aNS.mnToken = aIter->second;
102                 aNS.maNamespaceURL = val;
103 
104                 io_rContext.maNamespaces.back().push_back(aNS);
105 
106                 OSL_TRACE("Added with token 0x%x", aIter->second);
107             }
108         }
109     }
110 
getToken(const Context & rContext,const sal_Char * pToken)111     sal_Int32 getToken( const Context& rContext, const sal_Char* pToken )
112     {
113         const Sequence<sal_Int8> aSeq( (sal_Int8*)pToken, strlen( pToken ) );
114         return rContext.mxTokenHandler->getTokenFromUTF8( aSeq );
115     }
116 
getTokenWithPrefix(const Context & rContext,const sal_Char * pPrefix,const sal_Char * pName)117     sal_Int32 getTokenWithPrefix( const Context& rContext, const sal_Char* pPrefix, const sal_Char* pName )
118     {
119         sal_Int32 nNamespaceToken = FastToken::DONTKNOW;
120         OString prefix(pPrefix,
121                        strlen(reinterpret_cast<const char*>(pPrefix)));
122 
123         OSL_TRACE("getTokenWithPrefix(): prefix %s, name %s",
124                   (const char*)pPrefix, (const char*)pName);
125 
126         Context::NamespaceVectorType::value_type::const_iterator aIter;
127         if( (aIter=std::find_if(rContext.maNamespaces.back().begin(),
128                                 rContext.maNamespaces.back().end(),
129                                 boost::bind(std::equal_to<OString>(),
130                                             boost::bind(&Context::Namespace::getPrefix,
131                                                         _1),
132                                             boost::cref(prefix)))) != rContext.maNamespaces.back().end() )
133         {
134             nNamespaceToken = aIter->mnToken;
135             sal_Int32 nNameToken = getToken( rContext, pName );
136             if( nNameToken != FastToken::DONTKNOW )
137                 nNamespaceToken |= nNameToken;
138         }
139 
140         return nNamespaceToken;
141     }
142 
143 
CNode(CDocument const & rDocument,::osl::Mutex const & rMutex,NodeType const & reNodeType,xmlNodePtr const & rpNode)144     CNode::CNode(CDocument const& rDocument, ::osl::Mutex const& rMutex,
145                 NodeType const& reNodeType, xmlNodePtr const& rpNode)
146         :   m_bUnlinked(false)
147         ,   m_aNodeType(reNodeType)
148         ,   m_aNodePtr(rpNode)
149         // keep containing document alive
150         // (but not if this is a document; that would create a leak!)
151         ,   m_xDocument( (m_aNodePtr->type != XML_DOCUMENT_NODE)
152                 ? &const_cast<CDocument&>(rDocument) : 0 )
153         ,   m_rMutex(const_cast< ::osl::Mutex & >(rMutex))
154     {
155         OSL_ASSERT(m_aNodePtr);
156     }
157 
invalidate()158     void CNode::invalidate()
159     {
160         //remove from list if this wrapper goes away
161         if (m_aNodePtr != 0 && m_xDocument.is()) {
162             m_xDocument->RemoveCNode(m_aNodePtr, this);
163         }
164         // #i113663#: unlinked nodes will not be freed by xmlFreeDoc
165         if (m_bUnlinked) {
166             xmlFreeNode(m_aNodePtr);
167         }
168         m_aNodePtr = 0;
169     }
170 
~CNode()171     CNode::~CNode()
172     {
173         // if this is the document itself, the mutex is already freed!
174         if (NodeType_DOCUMENT_NODE == m_aNodeType) {
175             invalidate();
176         } else {
177             ::osl::MutexGuard const g(m_rMutex);
178             invalidate(); // other nodes are still alive so must lock mutex
179         }
180     }
181 
182     CNode *
GetImplementation(uno::Reference<uno::XInterface> const & xNode)183     CNode::GetImplementation(uno::Reference<uno::XInterface> const& xNode)
184     {
185         uno::Reference<lang::XUnoTunnel> const xUnoTunnel(xNode, UNO_QUERY);
186         if (!xUnoTunnel.is()) { return 0; }
187         CNode *const pCNode( reinterpret_cast< CNode* >(
188                         ::sal::static_int_cast< sal_IntPtr >(
189                             xUnoTunnel->getSomething(UnoTunnelId::get()))));
190         return pCNode;
191     }
192 
GetOwnerDocument()193     CDocument & CNode::GetOwnerDocument()
194     {
195         OSL_ASSERT(m_xDocument.is());
196         return *m_xDocument; // needs overriding in CDocument!
197     }
198 
199 
lcl_nsexchange(xmlNodePtr const aNode,xmlNsPtr const oldNs,xmlNsPtr const newNs)200     static void lcl_nsexchange(
201             xmlNodePtr const aNode, xmlNsPtr const oldNs, xmlNsPtr const newNs)
202     {
203         // recursively exchange any references to oldNs with references to newNs
204         xmlNodePtr cur = aNode;
205         while (cur != 0)
206         {
207             if (cur->ns == oldNs)
208                 cur->ns = newNs;
209             if (cur->type == XML_ELEMENT_NODE)
210             {
211                 xmlAttrPtr curAttr = cur->properties;
212                 while(curAttr != 0)
213                 {
214                     if (curAttr->ns == oldNs)
215                         curAttr->ns = newNs;
216                     curAttr = curAttr->next;
217                 }
218                 lcl_nsexchange(cur->children, oldNs, newNs);
219             }
220             cur = cur->next;
221         }
222     }
223 
nscleanup(const xmlNodePtr aNode,const xmlNodePtr aParent)224     /*static*/ void nscleanup(const xmlNodePtr aNode, const xmlNodePtr aParent)
225     {
226         xmlNodePtr cur = aNode;
227 
228         //handle attributes
229         if (cur != NULL && cur->type == XML_ELEMENT_NODE)
230         {
231             xmlAttrPtr curAttr = cur->properties;
232             while(curAttr != 0)
233             {
234                 if (curAttr->ns != NULL)
235                 {
236                     xmlNsPtr ns = xmlSearchNs(cur->doc, aParent, curAttr->ns->prefix);
237                     if (ns != NULL)
238                         curAttr->ns = ns;
239                 }
240                 curAttr = curAttr->next;
241             }
242         }
243 
244         while (cur != NULL)
245         {
246             nscleanup(cur->children, cur);
247             if (cur->ns != NULL)
248             {
249                 xmlNsPtr ns = xmlSearchNs(cur->doc, aParent, cur->ns->prefix);
250                 if (ns != NULL && ns != cur->ns && strcmp((char*)ns->href, (char*)cur->ns->href)==0)
251                 {
252                     xmlNsPtr curDef = cur->nsDef;
253                     xmlNsPtr *refp = &(cur->nsDef); // insert point
254                     while (curDef != NULL)
255                     {
256                         ns = xmlSearchNs(cur->doc, aParent, curDef->prefix);
257                         if (ns != NULL && ns != curDef && strcmp((char*)ns->href, (char*)curDef->href)==0)
258                         {
259                             // reconnect ns pointers in sub-tree to newly found ns before
260                             // removing redundant nsdecl to prevent dangling pointers.
261                             lcl_nsexchange(cur, curDef, ns);
262                             *refp = curDef->next;
263                             xmlFreeNs(curDef);
264                             curDef = *refp;
265                         } else {
266                             refp = &(curDef->next);
267                             curDef = curDef->next;
268                         }
269                     }
270                 }
271             }
272             cur = cur->next;
273         }
274     }
275 
saxify(const Reference<XDocumentHandler> & i_xHandler)276     void CNode::saxify(const Reference< XDocumentHandler >& i_xHandler)
277     {
278         if (!i_xHandler.is()) throw RuntimeException();
279         // default: do nothing
280     }
281 
fastSaxify(Context & io_rContext)282     void CNode::fastSaxify(Context& io_rContext)
283     {
284         if (!io_rContext.mxDocHandler.is()) throw RuntimeException();
285         // default: do nothing
286     }
287 
IsChildTypeAllowed(NodeType const)288     bool CNode::IsChildTypeAllowed(NodeType const /*nodeType*/)
289     {
290         // default: no children allowed
291         return false;
292     }
293 
294     /**
295     Adds the node newChild to the end of the list of children of this node.
296     */
appendChild(Reference<XNode> const & xNewChild)297     Reference< XNode > SAL_CALL CNode::appendChild(
298             Reference< XNode > const& xNewChild)
299     {
300         ::osl::ClearableMutexGuard guard(m_rMutex);
301 
302         if (0 == m_aNodePtr) { return 0; }
303 
304         CNode *const pNewChild(CNode::GetImplementation(xNewChild));
305         if (!pNewChild) { throw RuntimeException(); }
306         xmlNodePtr const cur = pNewChild->GetNodePtr();
307         if (!cur) { throw RuntimeException(); }
308 
309         // error checks:
310         // from other document
311         if (cur->doc != m_aNodePtr->doc) {
312             DOMException e;
313             e.Code = DOMExceptionType_WRONG_DOCUMENT_ERR;
314             throw e;
315         }
316         // same node
317         if (cur == m_aNodePtr) {
318             DOMException e;
319             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
320             throw e;
321         }
322         if (cur->parent != NULL) {
323             DOMException e;
324             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
325             throw e;
326         }
327         if (!IsChildTypeAllowed(pNewChild->m_aNodeType)) {
328             DOMException e;
329             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
330             throw e;
331         }
332 
333         // check whether this is an attribute node; it needs special handling
334         xmlNodePtr res = NULL;
335         if (cur->type == XML_ATTRIBUTE_NODE)
336         {
337             xmlChar const*const pChildren((cur->children)
338                     ? cur->children->content
339                     : reinterpret_cast<xmlChar const*>(""));
340             CAttr *const pCAttr(dynamic_cast<CAttr *>(pNewChild));
341             if (!pCAttr) { throw RuntimeException(); }
342             xmlNsPtr const pNs( pCAttr->GetNamespace(m_aNodePtr) );
343             if (pNs) {
344                 res = reinterpret_cast<xmlNodePtr>(
345                         xmlNewNsProp(m_aNodePtr, pNs, cur->name, pChildren));
346             } else {
347                 res = reinterpret_cast<xmlNodePtr>(
348                         xmlNewProp(m_aNodePtr, cur->name, pChildren));
349             }
350         }
351         else
352         {
353             res = xmlAddChild(m_aNodePtr, cur);
354 
355             // libxml can do optimization when appending nodes.
356             // if res != cur, something was optimized and the newchild-wrapper
357             // should be updated
358             if (res && (cur != res)) {
359                 pNewChild->m_bUnlinked = false; // else invalidate() frees cur again
360                 pNewChild->invalidate(); // cur has been freed
361             }
362         }
363 
364         if (!res) { return 0; }
365 
366         // use custom ns cleanup instead of
367         // xmlReconciliateNs(m_aNodePtr->doc, m_aNodePtr);
368         // because that will not remove unneeded ns decls
369         nscleanup(res, m_aNodePtr);
370 
371         ::rtl::Reference<CNode> const pNode = GetOwnerDocument().GetCNode(res);
372 
373         if (!pNode.is()) { return 0; }
374 
375         // dispatch DOMNodeInserted event, target is the new node
376         // this node is the related node
377         // does bubble
378         pNode->m_bUnlinked = false; // will be deleted by xmlFreeDoc
379         Reference< XDocumentEvent > docevent(getOwnerDocument(), UNO_QUERY);
380         Reference< XMutationEvent > event(docevent->createEvent(
381             OUString::createFromAscii("DOMNodeInserted")), UNO_QUERY);
382         event->initMutationEvent(OUString::createFromAscii("DOMNodeInserted")
383             , sal_True, sal_False,
384             this,
385             OUString(), OUString(), OUString(), (AttrChangeType)0 );
386 
387         // the following dispatch functions use only UNO interfaces
388         // and call event listeners, so release mutex to prevent deadlocks.
389         guard.clear();
390 
391         dispatchEvent(Reference< XEvent >(event, UNO_QUERY));
392         // dispatch subtree modified for this node
393         dispatchSubtreeModified();
394 
395         return pNode.get();
396     }
397 
398     /**
399     Returns a duplicate of this node, i.e., serves as a generic copy
400     constructor for nodes.
401     */
cloneNode(sal_Bool bDeep)402     Reference< XNode > SAL_CALL CNode::cloneNode(sal_Bool bDeep)
403     {
404         ::osl::MutexGuard const g(m_rMutex);
405 
406         if (0 == m_aNodePtr) {
407             return 0;
408         }
409         ::rtl::Reference<CNode> const pNode = GetOwnerDocument().GetCNode(
410             xmlCopyNode(m_aNodePtr, (bDeep) ? 1 : 0));
411         if (!pNode.is()) { return 0; }
412         pNode->m_bUnlinked = true; // not linked yet
413         return pNode.get();
414     }
415 
416     /**
417     A NamedNodeMap containing the attributes of this node (if it is an Element)
418     or null otherwise.
419     */
getAttributes()420     Reference< XNamedNodeMap > SAL_CALL CNode::getAttributes()
421     {
422         // return empty reference; only element node may override this impl
423         return Reference< XNamedNodeMap>();
424     }
425 
426     /**
427     A NodeList that contains all children of this node.
428     */
getChildNodes()429     Reference< XNodeList > SAL_CALL CNode::getChildNodes()
430     {
431         ::osl::MutexGuard const g(m_rMutex);
432 
433         if (0 == m_aNodePtr) {
434             return 0;
435         }
436         Reference< XNodeList > const xNodeList(new CChildList(this, m_rMutex));
437         return xNodeList;
438     }
439 
440     /**
441     The first child of this node.
442     */
getFirstChild()443     Reference< XNode > SAL_CALL CNode::getFirstChild()
444     {
445         ::osl::MutexGuard const g(m_rMutex);
446 
447         if (0 == m_aNodePtr) {
448             return 0;
449         }
450         Reference< XNode > const xNode(
451                 GetOwnerDocument().GetCNode(m_aNodePtr->children).get());
452         return xNode;
453     }
454 
455     /**
456     The last child of this node.
457     */
getLastChild()458     Reference< XNode > SAL_CALL CNode::getLastChild()
459     {
460         ::osl::MutexGuard const g(m_rMutex);
461 
462         if (0 == m_aNodePtr) {
463             return 0;
464         }
465         Reference< XNode > const xNode(
466             GetOwnerDocument().GetCNode(xmlGetLastChild(m_aNodePtr)).get());
467         return xNode;
468     }
469 
470     /**
471     Returns the local part of the qualified name of this node.
472     */
getLocalName()473     OUString SAL_CALL CNode::getLocalName()
474     {
475         // see CElement/CAttr
476         return ::rtl::OUString();
477     }
478 
479 
480     /**
481     The namespace URI of this node, or null if it is unspecified.
482     */
getNamespaceURI()483     OUString SAL_CALL CNode::getNamespaceURI()
484     {
485         ::osl::MutexGuard const g(m_rMutex);
486 
487         OUString aURI;
488         if (m_aNodePtr != NULL &&
489             (m_aNodePtr->type == XML_ELEMENT_NODE || m_aNodePtr->type == XML_ATTRIBUTE_NODE) &&
490             m_aNodePtr->ns != NULL)
491         {
492             const xmlChar* xHref = m_aNodePtr->ns->href;
493             aURI = OUString((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);
494         }
495         return aURI;
496     }
497 
498     /**
499     The node immediately following this node.
500     */
getNextSibling()501     Reference< XNode > SAL_CALL CNode::getNextSibling()
502     {
503         ::osl::MutexGuard const g(m_rMutex);
504 
505         if (0 == m_aNodePtr) {
506             return 0;
507         }
508         Reference< XNode > const xNode(
509                 GetOwnerDocument().GetCNode(m_aNodePtr->next).get());
510         return xNode;
511     }
512 
513     /**
514     The name of this node, depending on its type; see the table above.
515     */
getNodeName()516     OUString SAL_CALL CNode::getNodeName()
517     {
518         /*
519         Interface        nodeName               nodeValue                       attributes
520         --------------------------------------------------------------------------------------
521         Attr             name of attribute      value of attribute              null
522         CDATASection     "#cdata-section"       content of the CDATA Section    null
523         Comment          "#comment"             content of the comment          null
524         Document         "#document"            null                            null
525         DocumentFragment "#document-fragment"   null                            null
526         DocumentType     document type name     null                            null
527         Element          tag name               null                            NamedNodeMap
528         Entity           entity name            null                            null
529         EntityReference  name of entity         null                            null
530                          referenced
531         Notation         notation name          null                            null
532         Processing\      target                 entire content excluding        null
533         Instruction                             the target
534         Text             "#text"                content of the text node        null
535         */
536         OUString aName;
537         return aName;
538     }
539 
540     /**
541     A code representing the type of the underlying object, as defined above.
542     */
getNodeType()543     NodeType SAL_CALL CNode::getNodeType()
544     {
545         ::osl::MutexGuard const g(m_rMutex);
546 
547         return m_aNodeType;
548     }
549 
550     /**
551     The value of this node, depending on its type; see the table above.
552     */
getNodeValue()553     OUString SAL_CALL CNode::getNodeValue()
554     {
555         OUString aValue;
556         return aValue;
557     }
558 
559     /**
560     The Document object associated with this node.
561     */
getOwnerDocument()562     Reference< XDocument > SAL_CALL CNode::getOwnerDocument()
563     {
564         ::osl::MutexGuard const g(m_rMutex);
565 
566         if (0 == m_aNodePtr) {
567             return 0;
568         }
569         Reference< XDocument > const xDoc(& GetOwnerDocument());
570         return xDoc;
571     }
572 
573     /**
574     The parent of this node.
575     */
getParentNode()576     Reference< XNode > SAL_CALL CNode::getParentNode()
577     {
578         ::osl::MutexGuard const g(m_rMutex);
579 
580         if (0 == m_aNodePtr) {
581             return 0;
582         }
583         Reference< XNode > const xNode(
584                 GetOwnerDocument().GetCNode(m_aNodePtr->parent).get());
585         return xNode;
586     }
587 
588     /**
589     The namespace prefix of this node, or null if it is unspecified.
590     */
getPrefix()591     OUString SAL_CALL CNode::getPrefix()
592     {
593         ::osl::MutexGuard const g(m_rMutex);
594 
595         OUString aPrefix;
596         if (m_aNodePtr != NULL &&
597             (m_aNodePtr->type == XML_ELEMENT_NODE || m_aNodePtr->type == XML_ATTRIBUTE_NODE) &&
598             m_aNodePtr->ns != NULL)
599         {
600             const xmlChar* xPrefix = m_aNodePtr->ns->prefix;
601             if( xPrefix != NULL )
602                 aPrefix = OUString((sal_Char*)xPrefix, strlen((char*)xPrefix), RTL_TEXTENCODING_UTF8);
603         }
604         return aPrefix;
605 
606     }
607 
608     /**
609     The node immediately preceding this node.
610     */
getPreviousSibling()611     Reference< XNode > SAL_CALL CNode::getPreviousSibling()
612     {
613         ::osl::MutexGuard const g(m_rMutex);
614 
615         if (0 == m_aNodePtr) {
616             return 0;
617         }
618         Reference< XNode > const xNode(
619                 GetOwnerDocument().GetCNode(m_aNodePtr->prev).get());
620         return xNode;
621     }
622 
623     /**
624     Returns whether this node (if it is an element) has any attributes.
625     */
hasAttributes()626     sal_Bool SAL_CALL CNode::hasAttributes()
627     {
628         ::osl::MutexGuard const g(m_rMutex);
629 
630         return (m_aNodePtr != NULL && m_aNodePtr->properties != NULL);
631     }
632 
633     /**
634     Returns whether this node has any children.
635     */
hasChildNodes()636     sal_Bool SAL_CALL CNode::hasChildNodes()
637     {
638         ::osl::MutexGuard const g(m_rMutex);
639 
640         return (m_aNodePtr != NULL && m_aNodePtr->children != NULL);
641     }
642 
643     /**
644     Inserts the node newChild before the existing child node refChild.
645     */
insertBefore(const Reference<XNode> & newChild,const Reference<XNode> & refChild)646     Reference< XNode > SAL_CALL CNode::insertBefore(
647             const Reference< XNode >& newChild, const Reference< XNode >& refChild)
648     {
649         if (!newChild.is() || !refChild.is()) { throw RuntimeException(); }
650 
651         if (newChild->getOwnerDocument() != getOwnerDocument()) {
652             DOMException e;
653             e.Code = DOMExceptionType_WRONG_DOCUMENT_ERR;
654             throw e;
655         }
656         if (refChild->getParentNode() != Reference< XNode >(this)) {
657             DOMException e;
658             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
659             throw e;
660         }
661 
662         ::osl::ClearableMutexGuard guard(m_rMutex);
663 
664         CNode *const pNewNode(CNode::GetImplementation(newChild));
665         CNode *const pRefNode(CNode::GetImplementation(refChild));
666         if (!pNewNode || !pRefNode) { throw RuntimeException(); }
667         xmlNodePtr const pNewChild(pNewNode->GetNodePtr());
668         xmlNodePtr const pRefChild(pRefNode->GetNodePtr());
669         if (!pNewChild || !pRefChild) { throw RuntimeException(); }
670 
671         if (pNewChild == m_aNodePtr) {
672             DOMException e;
673             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
674             throw e;
675         }
676         // already has parent
677         if (pNewChild->parent != NULL)
678         {
679             DOMException e;
680             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
681             throw e;
682         }
683         if (!IsChildTypeAllowed(pNewNode->m_aNodeType)) {
684             DOMException e;
685             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
686             throw e;
687         }
688 
689         // attributes are unordered anyway, so just do appendChild
690         if (XML_ATTRIBUTE_NODE == pNewChild->type) {
691             guard.clear();
692             return appendChild(newChild);
693         }
694 
695         xmlNodePtr cur = m_aNodePtr->children;
696 
697         //search child before which to insert
698         while (cur != NULL)
699         {
700             if (cur == pRefChild) {
701                 // insert before
702                 pNewChild->next = cur;
703                 pNewChild->prev = cur->prev;
704                 cur->prev = pNewChild;
705                 if (pNewChild->prev != NULL) {
706                     pNewChild->prev->next = pNewChild;
707                 }
708                 pNewChild->parent = cur->parent;
709                 if (pNewChild->parent->children == cur) {
710                     pNewChild->parent->children = pNewChild;
711                 }
712                 // do not update parent->last here!
713                 pNewNode->m_bUnlinked = false; // will be deleted by xmlFreeDoc
714                 break;
715             }
716             cur = cur->next;
717         }
718         return refChild;
719     }
720 
721     /**
722     Tests whether the DOM implementation implements a specific feature and
723     that feature is supported by this node.
724     */
isSupported(const OUString &,const OUString &)725   sal_Bool SAL_CALL CNode::isSupported(const OUString& /*feature*/, const OUString& /*ver*/)
726     {
727         OSL_ENSURE(false, "CNode::isSupported: not implemented (#i113683#)");
728         return sal_False;
729     }
730 
731     /**
732     Puts all Text nodes in the full depth of the sub-tree underneath this
733     Node, including attribute nodes, into a "normal" form where only structure
734     (e.g., elements, comments, processing instructions, CDATA sections, and
735     entity references) separates Text nodes, i.e., there are neither adjacent
736     Text nodes nor empty Text nodes.
737     */
normalize()738     void SAL_CALL CNode::normalize()
739     {
740         //XXX combine adjacent text nodes and remove empty ones
741         OSL_ENSURE(false, "CNode::normalize: not implemented (#i113683#)");
742     }
743 
744     /**
745     Removes the child node indicated by oldChild from the list of children,
746     and returns it.
747     */
748     Reference< XNode > SAL_CALL
removeChild(const Reference<XNode> & xOldChild)749     CNode::removeChild(const Reference< XNode >& xOldChild)
750     {
751         if (!xOldChild.is()) {
752             throw RuntimeException();
753         }
754 
755         if (xOldChild->getOwnerDocument() != getOwnerDocument()) {
756             DOMException e;
757             e.Code = DOMExceptionType_WRONG_DOCUMENT_ERR;
758             throw e;
759         }
760         if (xOldChild->getParentNode() != Reference< XNode >(this)) {
761             DOMException e;
762             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
763             throw e;
764         }
765 
766         ::osl::ClearableMutexGuard guard(m_rMutex);
767 
768         if (!m_aNodePtr) { throw RuntimeException(); }
769 
770         Reference<XNode> xReturn( xOldChild );
771 
772         ::rtl::Reference<CNode> const pOld(CNode::GetImplementation(xOldChild));
773         if (!pOld.is()) { throw RuntimeException(); }
774         xmlNodePtr const old = pOld->GetNodePtr();
775         if (!old) { throw RuntimeException(); }
776 
777         if( old->type == XML_ATTRIBUTE_NODE )
778         {
779             xmlAttrPtr pAttr = reinterpret_cast<xmlAttrPtr>(old);
780             xmlRemoveProp( pAttr );
781             pOld->invalidate(); // freed by xmlRemoveProp
782             xReturn.clear();
783         }
784         else
785         {
786             xmlUnlinkNode(old);
787             pOld->m_bUnlinked = true;
788         }
789 
790         /*DOMNodeRemoved
791          * Fired when a node is being removed from its parent node.
792          * This event is dispatched before the node is removed from the tree.
793          * The target of this event is the node being removed.
794          *   Bubbles: Yes
795          *   Cancelable: No
796          *   Context Info: relatedNode holds the parent node
797          */
798         Reference< XDocumentEvent > docevent(getOwnerDocument(), UNO_QUERY);
799         Reference< XMutationEvent > event(docevent->createEvent(
800             OUString::createFromAscii("DOMNodeRemoved")), UNO_QUERY);
801         event->initMutationEvent(OUString::createFromAscii("DOMNodeRemoved"),
802             sal_True,
803             sal_False,
804             this,
805             OUString(), OUString(), OUString(), (AttrChangeType)0 );
806 
807         // the following dispatch functions use only UNO interfaces
808         // and call event listeners, so release mutex to prevent deadlocks.
809         guard.clear();
810 
811         dispatchEvent(Reference< XEvent >(event, UNO_QUERY));
812         // subtree modified for this node
813         dispatchSubtreeModified();
814 
815         return xReturn;
816     }
817 
818     /**
819     Replaces the child node oldChild with newChild in the list of children,
820     and returns the oldChild node.
821     */
replaceChild(Reference<XNode> const & xNewChild,Reference<XNode> const & xOldChild)822     Reference< XNode > SAL_CALL CNode::replaceChild(
823             Reference< XNode > const& xNewChild,
824             Reference< XNode > const& xOldChild)
825     {
826         if (!xOldChild.is() || !xNewChild.is()) {
827             throw RuntimeException();
828         }
829 
830         if (xNewChild->getOwnerDocument() != getOwnerDocument()) {
831             DOMException e;
832             e.Code = DOMExceptionType_WRONG_DOCUMENT_ERR;
833             throw e;
834         }
835         if (xOldChild->getParentNode() != Reference< XNode >(this)) {
836             DOMException e;
837             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
838             throw e;
839         }
840 
841         ::osl::ClearableMutexGuard guard(m_rMutex);
842 
843 /*
844         Reference< XNode > aNode = removeChild(oldChild);
845         appendChild(newChild);
846 */
847         ::rtl::Reference<CNode> const pOldNode(
848                 CNode::GetImplementation(xOldChild));
849         ::rtl::Reference<CNode> const pNewNode(
850                 CNode::GetImplementation(xNewChild));
851         if (!pOldNode.is() || !pNewNode.is()) { throw RuntimeException(); }
852         xmlNodePtr const pOld = pOldNode->GetNodePtr();
853         xmlNodePtr const pNew = pNewNode->GetNodePtr();
854         if (!pOld || !pNew) { throw RuntimeException(); }
855 
856         if (pNew == m_aNodePtr) {
857             DOMException e;
858             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
859             throw e;
860         }
861         // already has parent
862         if (pNew->parent != NULL) {
863             DOMException e;
864             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
865             throw e;
866         }
867         if (!IsChildTypeAllowed(pNewNode->m_aNodeType)) {
868             DOMException e;
869             e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
870             throw e;
871         }
872 
873         if( pOld->type == XML_ATTRIBUTE_NODE )
874         {
875             // can only replace attribute with attribute
876             if ( pOld->type != pNew->type )
877             {
878                 DOMException e;
879                 e.Code = DOMExceptionType_HIERARCHY_REQUEST_ERR;
880                 throw e;
881             }
882 
883             xmlAttrPtr pAttr = (xmlAttrPtr)pOld;
884             xmlRemoveProp( pAttr );
885             pOldNode->invalidate(); // freed by xmlRemoveProp
886             appendChild(xNewChild);
887         }
888         else
889         {
890 
891         xmlNodePtr cur = m_aNodePtr->children;
892         //find old node in child list
893         while (cur != NULL)
894         {
895             if(cur == pOld)
896             {
897                 // exchange nodes
898                 pNew->prev = pOld->prev;
899                 if (pNew->prev != NULL)
900                     pNew->prev->next = pNew;
901                 pNew->next = pOld->next;
902                 if (pNew->next != NULL)
903                     pNew->next->prev = pNew;
904                 pNew->parent = pOld->parent;
905                 if(pNew->parent->children == pOld)
906                     pNew->parent->children = pNew;
907                 if(pNew->parent->last == pOld)
908                     pNew->parent->last = pNew;
909                 pOld->next = NULL;
910                 pOld->prev = NULL;
911                 pOld->parent = NULL;
912                 pOldNode->m_bUnlinked = true;
913                 pNewNode->m_bUnlinked = false; // will be deleted by xmlFreeDoc
914             }
915             cur = cur->next;
916         }
917         }
918 
919         guard.clear(); // release for calling event handlers
920         dispatchSubtreeModified();
921 
922         return xOldChild;
923     }
924 
dispatchSubtreeModified()925     void CNode::dispatchSubtreeModified()
926     {
927         // only uses UNO interfaces => needs no mutex
928 
929         // dispatch DOMSubtreeModified
930         // target is _this_ node
931         Reference< XDocumentEvent > docevent(getOwnerDocument(), UNO_QUERY);
932         Reference< XMutationEvent > event(docevent->createEvent(
933             OUString::createFromAscii("DOMSubtreeModified")), UNO_QUERY);
934         event->initMutationEvent(
935             OUString::createFromAscii("DOMSubtreeModified"), sal_True,
936             sal_False, Reference< XNode >(),
937             OUString(), OUString(), OUString(), (AttrChangeType)0 );
938         dispatchEvent(Reference< XEvent >(event, UNO_QUERY));
939     }
940 
941     /**
942     The value of this node, depending on its type; see the table above.
943     */
setNodeValue(const OUString &)944     void SAL_CALL CNode::setNodeValue(const OUString& /*nodeValue*/)
945     {
946         // use specific node implementation
947         // if we end up down here, something went wrong
948         DOMException e;
949         e.Code = DOMExceptionType_NO_MODIFICATION_ALLOWED_ERR;
950         throw e;
951     }
952 
953     /**
954     The namespace prefix of this node, or null if it is unspecified.
955     */
setPrefix(const OUString & prefix)956     void SAL_CALL CNode::setPrefix(const OUString& prefix)
957     {
958         ::osl::MutexGuard const g(m_rMutex);
959 
960         if ((0 == m_aNodePtr) ||
961             ((m_aNodePtr->type != XML_ELEMENT_NODE) &&
962              (m_aNodePtr->type != XML_ATTRIBUTE_NODE)))
963         {
964             DOMException e;
965             e.Code = DOMExceptionType_NO_MODIFICATION_ALLOWED_ERR;
966             throw e;
967         }
968         OString o1 = OUStringToOString(prefix, RTL_TEXTENCODING_UTF8);
969         xmlChar *pBuf = (xmlChar*)o1.getStr();
970         if (m_aNodePtr != NULL && m_aNodePtr->ns != NULL)
971         {
972             xmlFree(const_cast<xmlChar *>(m_aNodePtr->ns->prefix));
973             m_aNodePtr->ns->prefix = xmlStrdup(pBuf);
974         }
975 
976     }
977 
978         // --- XEventTarget
addEventListener(const OUString & eventType,const Reference<com::sun::star::xml::dom::events::XEventListener> & listener,sal_Bool useCapture)979     void SAL_CALL CNode::addEventListener(const OUString& eventType,
980         const Reference< com::sun::star::xml::dom::events::XEventListener >& listener,
981         sal_Bool useCapture)
982     {
983         ::osl::MutexGuard const g(m_rMutex);
984 
985         CDocument & rDocument(GetOwnerDocument());
986         events::CEventDispatcher & rDispatcher(rDocument.GetEventDispatcher());
987         rDispatcher.addListener(m_aNodePtr, eventType, listener, useCapture);
988     }
989 
removeEventListener(const OUString & eventType,const Reference<com::sun::star::xml::dom::events::XEventListener> & listener,sal_Bool useCapture)990     void SAL_CALL CNode::removeEventListener(const OUString& eventType,
991         const Reference< com::sun::star::xml::dom::events::XEventListener >& listener,
992         sal_Bool useCapture)
993     {
994         ::osl::MutexGuard const g(m_rMutex);
995 
996         CDocument & rDocument(GetOwnerDocument());
997         events::CEventDispatcher & rDispatcher(rDocument.GetEventDispatcher());
998         rDispatcher.removeListener(m_aNodePtr, eventType, listener, useCapture);
999     }
1000 
dispatchEvent(const Reference<XEvent> & evt)1001     sal_Bool SAL_CALL CNode::dispatchEvent(const Reference< XEvent >& evt)
1002     {
1003         CDocument * pDocument;
1004         events::CEventDispatcher * pDispatcher;
1005         xmlNodePtr pNode;
1006         {
1007             ::osl::MutexGuard const g(m_rMutex);
1008 
1009             pDocument = & GetOwnerDocument();
1010             pDispatcher = & pDocument->GetEventDispatcher();
1011             pNode = m_aNodePtr;
1012         }
1013         // this calls event listeners, do not call with locked mutex
1014         pDispatcher->dispatchEvent(*pDocument, m_rMutex, pNode, this, evt);
1015         return sal_True;
1016     }
1017 
1018     ::sal_Int64 SAL_CALL
getSomething(Sequence<::sal_Int8> const & rId)1019     CNode::getSomething(Sequence< ::sal_Int8 > const& rId)
1020     {
1021         if ((rId.getLength() == 16) &&
1022             (0 == rtl_compareMemory(UnoTunnelId::get().getConstArray(),
1023                                     rId.getConstArray(), 16)))
1024         {
1025             return ::sal::static_int_cast< sal_Int64 >(
1026                     reinterpret_cast< sal_IntPtr >(this) );
1027         }
1028         return 0;
1029     }
1030 }
1031