Version 6.1.4.1, tag libreoffice-6.1.4.1
[LibreOffice.git] / unoxml / source / dom / document.cxx
blob4e904a899d3e9cd28a4a9abdb3a6b2d8846e386b
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <com/sun/star/uno/Sequence.h>
22 #include "document.hxx"
23 #include "attr.hxx"
24 #include "element.hxx"
25 #include "cdatasection.hxx"
26 #include "documentfragment.hxx"
27 #include "text.hxx"
28 #include "comment.hxx"
29 #include "processinginstruction.hxx"
30 #include "entityreference.hxx"
31 #include "documenttype.hxx"
32 #include "elementlist.hxx"
33 #include "domimplementation.hxx"
34 #include "entity.hxx"
35 #include "notation.hxx"
37 #include <event.hxx>
38 #include <mutationevent.hxx>
39 #include <uievent.hxx>
40 #include <mouseevent.hxx>
41 #include <eventdispatcher.hxx>
43 #include <string.h>
45 #include <osl/diagnose.h>
47 #include <com/sun/star/xml/sax/FastToken.hpp>
48 #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
50 using namespace css;
51 using namespace css::io;
52 using namespace css::uno;
53 using namespace css::xml::dom;
54 using namespace css::xml::dom::events;
55 using namespace css::xml::sax;
57 namespace DOM
59 static xmlNodePtr lcl_getDocumentType(xmlDocPtr const i_pDocument)
61 // find the doc type
62 xmlNodePtr cur = i_pDocument->children;
63 while (cur != nullptr)
65 if ((cur->type == XML_DOCUMENT_TYPE_NODE) ||
66 (cur->type == XML_DTD_NODE)) {
67 return cur;
70 return nullptr;
73 /// get the pointer to the root element node of the document
74 static xmlNodePtr lcl_getDocumentRootPtr(xmlDocPtr const i_pDocument)
76 // find the document element
77 xmlNodePtr cur = i_pDocument->children;
78 while (cur != nullptr)
80 if (cur->type == XML_ELEMENT_NODE)
81 break;
82 cur = cur->next;
84 return cur;
87 CDocument::CDocument(xmlDocPtr const pDoc)
88 : CDocument_Base(*this, m_Mutex,
89 NodeType_DOCUMENT_NODE, reinterpret_cast<xmlNodePtr>(pDoc))
90 , m_aDocPtr(pDoc)
91 , m_streamListeners()
92 , m_pEventDispatcher(new events::CEventDispatcher)
96 ::rtl::Reference<CDocument> CDocument::CreateCDocument(xmlDocPtr const pDoc)
98 ::rtl::Reference<CDocument> const xDoc(new CDocument(pDoc));
99 // add the doc itself to its nodemap!
100 xDoc->m_NodeMap.emplace(
101 reinterpret_cast<xmlNodePtr>(pDoc),
102 ::std::make_pair(
103 WeakReference<XNode>(static_cast<XDocument*>(xDoc.get())),
104 xDoc.get()));
105 return xDoc;
108 CDocument::~CDocument()
110 ::osl::MutexGuard const g(m_Mutex);
111 #ifdef DBG_UTIL
112 // node map must be empty now, otherwise CDocument must not die!
113 for (nodemap_t::iterator i = m_NodeMap.begin();
114 i != m_NodeMap.end(); ++i)
116 Reference<XNode> const xNode(i->second.first);
117 OSL_ENSURE(!xNode.is(),
118 "CDocument::~CDocument(): ERROR: live node in document node map!");
120 #endif
121 xmlFreeDoc(m_aDocPtr);
125 events::CEventDispatcher & CDocument::GetEventDispatcher()
127 return *m_pEventDispatcher;
130 ::rtl::Reference< CElement > CDocument::GetDocumentElement()
132 xmlNodePtr const pNode = lcl_getDocumentRootPtr(m_aDocPtr);
133 ::rtl::Reference< CElement > const xRet(
134 dynamic_cast<CElement*>(GetCNode(pNode).get()));
135 return xRet;
138 void
139 CDocument::RemoveCNode(xmlNodePtr const pNode, CNode const*const pCNode)
141 nodemap_t::iterator const i = m_NodeMap.find(pNode);
142 if (i != m_NodeMap.end()) {
143 // #i113681# consider this scenario:
144 // T1 calls ~CNode
145 // T2 calls getCNode: lookup will find i->second->first invalid
146 // so a new CNode is created and inserted
147 // T1 calls removeCNode: i->second->second now points to a
148 // different CNode instance!
150 // check that the CNode is the right one
151 CNode *const pCurrent = i->second.second;
152 if (pCurrent == pCNode) {
153 m_NodeMap.erase(i);
158 /** NB: this is the CNode factory.
159 it is the only place where CNodes may be instantiated.
160 all CNodes must be registered at the m_NodeMap.
162 ::rtl::Reference<CNode>
163 CDocument::GetCNode(xmlNodePtr const pNode, bool const bCreate)
165 if (nullptr == pNode) {
166 return nullptr;
168 //check whether there is already an instance for this node
169 nodemap_t::const_iterator const i = m_NodeMap.find(pNode);
170 if (i != m_NodeMap.end()) {
171 // #i113681# check that the CNode is still alive
172 uno::Reference<XNode> const xNode(i->second.first);
173 if (xNode.is())
175 ::rtl::Reference<CNode> ret(i->second.second);
176 OSL_ASSERT(ret.is());
177 return ret;
181 if (!bCreate) { return nullptr; }
183 // there is not yet an instance wrapping this node,
184 // create it and store it in the map
186 ::rtl::Reference<CNode> pCNode;
187 switch (pNode->type)
189 case XML_ELEMENT_NODE:
190 // m_aNodeType = NodeType::ELEMENT_NODE;
191 pCNode = static_cast< CNode* >(
192 new CElement(*this, m_Mutex, pNode));
193 break;
194 case XML_TEXT_NODE:
195 // m_aNodeType = NodeType::TEXT_NODE;
196 pCNode = static_cast< CNode* >(
197 new CText(*this, m_Mutex, pNode));
198 break;
199 case XML_CDATA_SECTION_NODE:
200 // m_aNodeType = NodeType::CDATA_SECTION_NODE;
201 pCNode = static_cast< CNode* >(
202 new CCDATASection(*this, m_Mutex, pNode));
203 break;
204 case XML_ENTITY_REF_NODE:
205 // m_aNodeType = NodeType::ENTITY_REFERENCE_NODE;
206 pCNode = static_cast< CNode* >(
207 new CEntityReference(*this, m_Mutex, pNode));
208 break;
209 case XML_ENTITY_NODE:
210 // m_aNodeType = NodeType::ENTITY_NODE;
211 pCNode = static_cast< CNode* >(new CEntity(*this, m_Mutex,
212 reinterpret_cast<xmlEntityPtr>(pNode)));
213 break;
214 case XML_PI_NODE:
215 // m_aNodeType = NodeType::PROCESSING_INSTRUCTION_NODE;
216 pCNode = static_cast< CNode* >(
217 new CProcessingInstruction(*this, m_Mutex, pNode));
218 break;
219 case XML_COMMENT_NODE:
220 // m_aNodeType = NodeType::COMMENT_NODE;
221 pCNode = static_cast< CNode* >(
222 new CComment(*this, m_Mutex, pNode));
223 break;
224 case XML_DOCUMENT_NODE:
225 // m_aNodeType = NodeType::DOCUMENT_NODE;
226 OSL_ENSURE(false, "CDocument::GetCNode is not supposed to"
227 " create a CDocument!!!");
228 pCNode = static_cast< CNode* >(new CDocument(
229 reinterpret_cast<xmlDocPtr>(pNode)));
230 break;
231 case XML_DOCUMENT_TYPE_NODE:
232 case XML_DTD_NODE:
233 // m_aNodeType = NodeType::DOCUMENT_TYPE_NODE;
234 pCNode = static_cast< CNode* >(new CDocumentType(*this, m_Mutex,
235 reinterpret_cast<xmlDtdPtr>(pNode)));
236 break;
237 case XML_DOCUMENT_FRAG_NODE:
238 // m_aNodeType = NodeType::DOCUMENT_FRAGMENT_NODE;
239 pCNode = static_cast< CNode* >(
240 new CDocumentFragment(*this, m_Mutex, pNode));
241 break;
242 case XML_NOTATION_NODE:
243 // m_aNodeType = NodeType::NOTATION_NODE;
244 pCNode = static_cast< CNode* >(new CNotation(*this, m_Mutex,
245 reinterpret_cast<xmlNotationPtr>(pNode)));
246 break;
247 case XML_ATTRIBUTE_NODE:
248 // m_aNodeType = NodeType::ATTRIBUTE_NODE;
249 pCNode = static_cast< CNode* >(new CAttr(*this, m_Mutex,
250 reinterpret_cast<xmlAttrPtr>(pNode)));
251 break;
252 // unsupported node types
253 case XML_HTML_DOCUMENT_NODE:
254 case XML_ELEMENT_DECL:
255 case XML_ATTRIBUTE_DECL:
256 case XML_ENTITY_DECL:
257 case XML_NAMESPACE_DECL:
258 default:
259 break;
262 if (pCNode != nullptr) {
263 bool const bInserted = m_NodeMap.emplace(
264 pNode,
265 ::std::make_pair(WeakReference<XNode>(pCNode.get()), pCNode.get())
266 ).second;
267 OSL_ASSERT(bInserted);
268 if (!bInserted) {
269 // if insertion failed, delete new instance and return null
270 return nullptr;
274 OSL_ENSURE(pCNode.is(), "no node produced during CDocument::GetCNode!");
275 return pCNode;
279 CDocument & CDocument::GetOwnerDocument()
281 return *this;
284 void CDocument::saxify(const Reference< XDocumentHandler >& i_xHandler)
286 i_xHandler->startDocument();
287 for (xmlNodePtr pChild = m_aNodePtr->children;
288 pChild != nullptr; pChild = pChild->next) {
289 ::rtl::Reference<CNode> const pNode = GetCNode(pChild);
290 OSL_ENSURE(pNode != nullptr, "CNode::get returned 0");
291 pNode->saxify(i_xHandler);
293 i_xHandler->endDocument();
296 void CDocument::fastSaxify( Context& rContext )
298 rContext.mxDocHandler->startDocument();
299 for (xmlNodePtr pChild = m_aNodePtr->children;
300 pChild != nullptr; pChild = pChild->next) {
301 ::rtl::Reference<CNode> const pNode = GetCNode(pChild);
302 OSL_ENSURE(pNode != nullptr, "CNode::get returned 0");
303 pNode->fastSaxify(rContext);
305 rContext.mxDocHandler->endDocument();
308 bool CDocument::IsChildTypeAllowed(NodeType const nodeType)
310 switch (nodeType) {
311 case NodeType_PROCESSING_INSTRUCTION_NODE:
312 case NodeType_COMMENT_NODE:
313 return true;
314 case NodeType_ELEMENT_NODE:
315 // there may be only one!
316 return nullptr == lcl_getDocumentRootPtr(m_aDocPtr);
317 case NodeType_DOCUMENT_TYPE_NODE:
318 // there may be only one!
319 return nullptr == lcl_getDocumentType(m_aDocPtr);
320 default:
321 return false;
326 void SAL_CALL CDocument::addListener(const Reference< XStreamListener >& aListener )
328 ::osl::MutexGuard const g(m_Mutex);
330 m_streamListeners.insert(aListener);
333 void SAL_CALL CDocument::removeListener(const Reference< XStreamListener >& aListener )
335 ::osl::MutexGuard const g(m_Mutex);
337 m_streamListeners.erase(aListener);
340 // IO context functions for libxml2 interaction
341 typedef struct {
342 Reference< XOutputStream > stream;
343 bool allowClose;
344 } IOContext;
346 extern "C" {
347 // write callback
348 // int xmlOutputWriteCallback (void * context, const char * buffer, int len)
349 static int writeCallback(void *context, const char* buffer, int len){
350 // create a sequence and write it to the stream
351 IOContext *pContext = static_cast<IOContext*>(context);
352 Sequence<sal_Int8> bs(reinterpret_cast<const sal_Int8*>(buffer), len);
353 pContext->stream->writeBytes(bs);
354 return len;
357 // close callback
358 //int xmlOutputCloseCallback (void * context)
359 static int closeCallback(void *context)
361 IOContext *pContext = static_cast<IOContext*>(context);
362 if (pContext->allowClose) {
363 pContext->stream->closeOutput();
365 return 0;
367 } // extern "C"
369 void SAL_CALL CDocument::start()
371 listenerlist_t streamListeners;
373 ::osl::MutexGuard const g(m_Mutex);
375 if (! m_rOutputStream.is()) { throw RuntimeException(); }
376 streamListeners = m_streamListeners;
379 // notify listeners about start
380 listenerlist_t::const_iterator iter1 = streamListeners.begin();
381 while (iter1 != streamListeners.end()) {
382 Reference< XStreamListener > aListener = *iter1;
383 aListener->started();
384 ++iter1;
388 ::osl::MutexGuard const g(m_Mutex);
390 // check again! could have been reset...
391 if (! m_rOutputStream.is()) { throw RuntimeException(); }
393 // setup libxml IO and write data to output stream
394 IOContext ioctx = {m_rOutputStream, false};
395 xmlOutputBufferPtr pOut = xmlOutputBufferCreateIO(
396 writeCallback, closeCallback, &ioctx, nullptr);
397 xmlSaveFileTo(pOut, m_aNodePtr->doc, nullptr);
400 // call listeners
401 listenerlist_t::const_iterator iter2 = streamListeners.begin();
402 while (iter2 != streamListeners.end()) {
403 Reference< XStreamListener > aListener = *iter2;
404 aListener->closed();
405 ++iter2;
409 void SAL_CALL CDocument::terminate()
411 // not supported
414 void SAL_CALL CDocument::setOutputStream( const Reference< XOutputStream >& aStream )
416 ::osl::MutexGuard const g(m_Mutex);
418 m_rOutputStream = aStream;
421 Reference< XOutputStream > SAL_CALL CDocument::getOutputStream()
423 ::osl::MutexGuard const g(m_Mutex);
425 return m_rOutputStream;
428 // Creates an Attr of the given name.
429 Reference< XAttr > SAL_CALL CDocument::createAttribute(const OUString& name)
431 ::osl::MutexGuard const g(m_Mutex);
433 OString o1 = OUStringToOString(name, RTL_TEXTENCODING_UTF8);
434 xmlChar const *pName = reinterpret_cast<xmlChar const *>(o1.getStr());
435 xmlAttrPtr const pAttr = xmlNewDocProp(m_aDocPtr, pName, nullptr);
436 ::rtl::Reference< CAttr > const pCAttr(
437 dynamic_cast< CAttr* >(GetCNode(
438 reinterpret_cast<xmlNodePtr>(pAttr)).get()));
439 if (!pCAttr.is()) { throw RuntimeException(); }
440 pCAttr->m_bUnlinked = true;
441 return pCAttr.get();
444 // Creates an attribute of the given qualified name and namespace URI.
445 Reference< XAttr > SAL_CALL CDocument::createAttributeNS(
446 const OUString& ns, const OUString& qname)
448 ::osl::MutexGuard const g(m_Mutex);
450 // libxml does not allow a NS definition to be attached to an
451 // attribute node - which is a good thing, since namespaces are
452 // only defined as parts of element nodes
453 // thus the namespace data is stored in CAttr::m_pNamespace
454 sal_Int32 i = qname.indexOf(':');
455 OString oPrefix, oName, oUri;
456 if (i != -1)
458 oPrefix = OUStringToOString(qname.copy(0, i), RTL_TEXTENCODING_UTF8);
459 oName = OUStringToOString(qname.copy(i+1), RTL_TEXTENCODING_UTF8);
461 else
463 oName = OUStringToOString(qname, RTL_TEXTENCODING_UTF8);
465 oUri = OUStringToOString(ns, RTL_TEXTENCODING_UTF8);
466 xmlAttrPtr const pAttr = xmlNewDocProp(m_aDocPtr,
467 reinterpret_cast<xmlChar const*>(oName.getStr()), nullptr);
468 ::rtl::Reference< CAttr > const pCAttr(
469 dynamic_cast< CAttr* >(GetCNode(
470 reinterpret_cast<xmlNodePtr>(pAttr)).get()));
471 if (!pCAttr.is()) { throw RuntimeException(); }
472 // store the namespace data!
473 pCAttr->m_pNamespace.reset( new stringpair_t(oUri, oPrefix) );
474 pCAttr->m_bUnlinked = true;
476 return pCAttr.get();
479 // Creates a CDATASection node whose value is the specified string.
480 Reference< XCDATASection > SAL_CALL CDocument::createCDATASection(const OUString& data)
482 ::osl::MutexGuard const g(m_Mutex);
484 OString const oData(
485 OUStringToOString(data, RTL_TEXTENCODING_UTF8));
486 xmlChar const*const pData =
487 reinterpret_cast<xmlChar const*>(oData.getStr());
488 xmlNodePtr const pText =
489 xmlNewCDataBlock(m_aDocPtr, pData, oData.getLength());
490 Reference< XCDATASection > const xRet(
491 static_cast< XNode* >(GetCNode(pText).get()),
492 UNO_QUERY_THROW);
493 return xRet;
496 // Creates a Comment node given the specified string.
497 Reference< XComment > SAL_CALL CDocument::createComment(const OUString& data)
499 ::osl::MutexGuard const g(m_Mutex);
501 OString o1 = OUStringToOString(data, RTL_TEXTENCODING_UTF8);
502 xmlChar const *pData = reinterpret_cast<xmlChar const *>(o1.getStr());
503 xmlNodePtr pComment = xmlNewDocComment(m_aDocPtr, pData);
504 Reference< XComment > const xRet(
505 static_cast< XNode* >(GetCNode(pComment).get()),
506 UNO_QUERY_THROW);
507 return xRet;
510 //Creates an empty DocumentFragment object.
511 Reference< XDocumentFragment > SAL_CALL CDocument::createDocumentFragment()
513 ::osl::MutexGuard const g(m_Mutex);
515 xmlNodePtr pFrag = xmlNewDocFragment(m_aDocPtr);
516 Reference< XDocumentFragment > const xRet(
517 static_cast< XNode* >(GetCNode(pFrag).get()),
518 UNO_QUERY_THROW);
519 return xRet;
522 // Creates an element of the type specified.
523 Reference< XElement > SAL_CALL CDocument::createElement(const OUString& tagName)
525 ::osl::MutexGuard const g(m_Mutex);
527 OString o1 = OUStringToOString(tagName, RTL_TEXTENCODING_UTF8);
528 xmlChar const *pName = reinterpret_cast<xmlChar const *>(o1.getStr());
529 xmlNodePtr const pNode = xmlNewDocNode(m_aDocPtr, nullptr, pName, nullptr);
530 Reference< XElement > const xRet(
531 static_cast< XNode* >(GetCNode(pNode).get()),
532 UNO_QUERY_THROW);
533 return xRet;
536 // Creates an element of the given qualified name and namespace URI.
537 Reference< XElement > SAL_CALL CDocument::createElementNS(
538 const OUString& ns, const OUString& qname)
540 ::osl::MutexGuard const g(m_Mutex);
542 sal_Int32 i = qname.indexOf(':');
543 if (ns.isEmpty()) throw RuntimeException();
544 xmlChar const *pPrefix;
545 xmlChar const *pName;
546 OString o1, o2, o3;
547 if ( i != -1) {
548 o1 = OUStringToOString(qname.copy(0, i), RTL_TEXTENCODING_UTF8);
549 pPrefix = reinterpret_cast<xmlChar const *>(o1.getStr());
550 o2 = OUStringToOString(qname.copy(i+1), RTL_TEXTENCODING_UTF8);
551 pName = reinterpret_cast<xmlChar const *>(o2.getStr());
552 } else {
553 // default prefix
554 pPrefix = reinterpret_cast<xmlChar const *>("");
555 o2 = OUStringToOString(qname, RTL_TEXTENCODING_UTF8);
556 pName = reinterpret_cast<xmlChar const *>(o2.getStr());
558 o3 = OUStringToOString(ns, RTL_TEXTENCODING_UTF8);
559 xmlChar const *pUri = reinterpret_cast<xmlChar const *>(o3.getStr());
561 // xmlNsPtr aNsPtr = xmlNewReconciledNs?
562 // xmlNsPtr aNsPtr = xmlNewGlobalNs?
563 xmlNodePtr const pNode = xmlNewDocNode(m_aDocPtr, nullptr, pName, nullptr);
564 xmlNsPtr const pNs = xmlNewNs(pNode, pUri, pPrefix);
565 xmlSetNs(pNode, pNs);
566 Reference< XElement > const xRet(
567 static_cast< XNode* >(GetCNode(pNode).get()),
568 UNO_QUERY_THROW);
569 return xRet;
572 //Creates an EntityReference object.
573 Reference< XEntityReference > SAL_CALL CDocument::createEntityReference(const OUString& name)
575 ::osl::MutexGuard const g(m_Mutex);
577 OString o1 = OUStringToOString(name, RTL_TEXTENCODING_UTF8);
578 xmlChar const *pName = reinterpret_cast<xmlChar const *>(o1.getStr());
579 xmlNodePtr const pNode = xmlNewReference(m_aDocPtr, pName);
580 Reference< XEntityReference > const xRet(
581 static_cast< XNode* >(GetCNode(pNode).get()),
582 UNO_QUERY_THROW);
583 return xRet;
586 // Creates a ProcessingInstruction node given the specified name and
587 // data strings.
588 Reference< XProcessingInstruction > SAL_CALL CDocument::createProcessingInstruction(
589 const OUString& target, const OUString& data)
591 ::osl::MutexGuard const g(m_Mutex);
593 OString o1 = OUStringToOString(target, RTL_TEXTENCODING_UTF8);
594 xmlChar const *pTarget = reinterpret_cast<xmlChar const *>(o1.getStr());
595 OString o2 = OUStringToOString(data, RTL_TEXTENCODING_UTF8);
596 xmlChar const *pData = reinterpret_cast<xmlChar const *>(o2.getStr());
597 xmlNodePtr const pNode = xmlNewDocPI(m_aDocPtr, pTarget, pData);
598 pNode->doc = m_aDocPtr;
599 Reference< XProcessingInstruction > const xRet(
600 static_cast< XNode* >(GetCNode(pNode).get()),
601 UNO_QUERY_THROW);
602 return xRet;
605 // Creates a Text node given the specified string.
606 Reference< XText > SAL_CALL CDocument::createTextNode(const OUString& data)
608 ::osl::MutexGuard const g(m_Mutex);
610 OString o1 = OUStringToOString(data, RTL_TEXTENCODING_UTF8);
611 xmlChar const *pData = reinterpret_cast<xmlChar const *>(o1.getStr());
612 xmlNodePtr const pNode = xmlNewDocText(m_aDocPtr, pData);
613 Reference< XText > const xRet(
614 static_cast< XNode* >(GetCNode(pNode).get()),
615 UNO_QUERY_THROW);
616 return xRet;
619 // The Document Type Declaration (see DocumentType) associated with this
620 // document.
621 Reference< XDocumentType > SAL_CALL CDocument::getDoctype()
623 ::osl::MutexGuard const g(m_Mutex);
625 xmlNodePtr const pDocType(lcl_getDocumentType(m_aDocPtr));
626 Reference< XDocumentType > const xRet(
627 static_cast< XNode* >(GetCNode(pDocType).get()),
628 UNO_QUERY);
629 return xRet;
632 // This is a convenience attribute that allows direct access to the child
633 // node that is the root element of the document.
634 Reference< XElement > SAL_CALL CDocument::getDocumentElement()
636 ::osl::MutexGuard const g(m_Mutex);
638 xmlNodePtr const pNode = lcl_getDocumentRootPtr(m_aDocPtr);
639 if (!pNode) { return nullptr; }
640 Reference< XElement > const xRet(
641 static_cast< XNode* >(GetCNode(pNode).get()),
642 UNO_QUERY);
643 return xRet;
646 static xmlNodePtr
647 lcl_search_element_by_id(const xmlNodePtr cur, const xmlChar* id)
649 if (cur == nullptr)
650 return nullptr;
651 // look in current node
652 if (cur->type == XML_ELEMENT_NODE)
654 xmlAttrPtr a = cur->properties;
655 while (a != nullptr)
657 if (a->atype == XML_ATTRIBUTE_ID) {
658 if (strcmp(reinterpret_cast<char*>(a->children->content), reinterpret_cast<char const *>(id)) == 0)
659 return cur;
661 a = a->next;
664 // look in children
665 xmlNodePtr result = lcl_search_element_by_id(cur->children, id);
666 if (result != nullptr)
667 return result;
668 result = lcl_search_element_by_id(cur->next, id);
669 return result;
672 // Returns the Element whose ID is given by elementId.
673 Reference< XElement > SAL_CALL
674 CDocument::getElementById(const OUString& elementId)
676 ::osl::MutexGuard const g(m_Mutex);
678 // search the tree for an element with the given ID
679 OString o1 = OUStringToOString(elementId, RTL_TEXTENCODING_UTF8);
680 xmlChar const *pId = reinterpret_cast<xmlChar const *>(o1.getStr());
681 xmlNodePtr const pStart = lcl_getDocumentRootPtr(m_aDocPtr);
682 if (!pStart) { return nullptr; }
683 xmlNodePtr const pNode = lcl_search_element_by_id(pStart, pId);
684 Reference< XElement > const xRet(
685 static_cast< XNode* >(GetCNode(pNode).get()),
686 UNO_QUERY);
687 return xRet;
691 Reference< XNodeList > SAL_CALL
692 CDocument::getElementsByTagName(OUString const& rTagname)
694 ::osl::MutexGuard const g(m_Mutex);
696 Reference< XNodeList > const xRet(
697 new CElementList(GetDocumentElement(), m_Mutex, rTagname));
698 return xRet;
701 Reference< XNodeList > SAL_CALL CDocument::getElementsByTagNameNS(
702 OUString const& rNamespaceURI, OUString const& rLocalName)
704 ::osl::MutexGuard const g(m_Mutex);
706 Reference< XNodeList > const xRet(
707 new CElementList(GetDocumentElement(), m_Mutex,
708 rLocalName, &rNamespaceURI));
709 return xRet;
712 Reference< XDOMImplementation > SAL_CALL CDocument::getImplementation()
714 // does not need mutex currently
715 return Reference< XDOMImplementation >(CDOMImplementation::get());
718 // helper function to recursively import siblings
719 static void lcl_ImportSiblings(
720 Reference< XDocument > const& xTargetDocument,
721 Reference< XNode > const& xTargetParent,
722 Reference< XNode > const& xChild)
724 Reference< XNode > xSibling = xChild;
725 while (xSibling.is())
727 Reference< XNode > const xTmp(
728 xTargetDocument->importNode(xSibling, true));
729 xTargetParent->appendChild(xTmp);
730 xSibling = xSibling->getNextSibling();
734 static Reference< XNode >
735 lcl_ImportNode( Reference< XDocument > const& xDocument,
736 Reference< XNode > const& xImportedNode, bool deep)
738 Reference< XNode > xNode;
739 NodeType aNodeType = xImportedNode->getNodeType();
740 switch (aNodeType)
742 case NodeType_ATTRIBUTE_NODE:
744 Reference< XAttr > const xAttr(xImportedNode, UNO_QUERY_THROW);
745 Reference< XAttr > const xNew =
746 xDocument->createAttribute(xAttr->getName());
747 xNew->setValue(xAttr->getValue());
748 xNode.set(xNew, UNO_QUERY);
749 break;
751 case NodeType_CDATA_SECTION_NODE:
753 Reference< XCDATASection > const xCData(xImportedNode,
754 UNO_QUERY_THROW);
755 Reference< XCDATASection > const xNewCData =
756 xDocument->createCDATASection(xCData->getData());
757 xNode.set(xNewCData, UNO_QUERY);
758 break;
760 case NodeType_COMMENT_NODE:
762 Reference< XComment > const xComment(xImportedNode,
763 UNO_QUERY_THROW);
764 Reference< XComment > const xNewComment =
765 xDocument->createComment(xComment->getData());
766 xNode.set(xNewComment, UNO_QUERY);
767 break;
769 case NodeType_DOCUMENT_FRAGMENT_NODE:
771 Reference< XDocumentFragment > const xFrag(xImportedNode,
772 UNO_QUERY_THROW);
773 Reference< XDocumentFragment > const xNewFrag =
774 xDocument->createDocumentFragment();
775 xNode.set(xNewFrag, UNO_QUERY);
776 break;
778 case NodeType_ELEMENT_NODE:
780 Reference< XElement > const xElement(xImportedNode,
781 UNO_QUERY_THROW);
782 OUString const aNsUri = xImportedNode->getNamespaceURI();
783 OUString const aNsPrefix = xImportedNode->getPrefix();
784 OUString aQName = xElement->getTagName();
785 Reference< XElement > xNewElement;
786 if (!aNsUri.isEmpty())
788 if (!aNsPrefix.isEmpty()) {
789 aQName = aNsPrefix + ":" + aQName;
791 xNewElement = xDocument->createElementNS(aNsUri, aQName);
792 } else {
793 xNewElement = xDocument->createElement(aQName);
796 // get attributes
797 if (xElement->hasAttributes())
799 Reference< XNamedNodeMap > attribs = xElement->getAttributes();
800 for (sal_Int32 i = 0; i < attribs->getLength(); i++)
802 Reference< XAttr > const curAttr(attribs->item(i),
803 UNO_QUERY_THROW);
804 OUString const aAttrUri = curAttr->getNamespaceURI();
805 OUString const aAttrPrefix = curAttr->getPrefix();
806 OUString aAttrName = curAttr->getName();
807 OUString const sValue = curAttr->getValue();
808 if (!aAttrUri.isEmpty())
810 if (!aAttrPrefix.isEmpty()) {
811 aAttrName = aAttrPrefix + ":" + aAttrName;
813 xNewElement->setAttributeNS(
814 aAttrUri, aAttrName, sValue);
815 } else {
816 xNewElement->setAttribute(aAttrName, sValue);
820 xNode.set(xNewElement, UNO_QUERY);
821 break;
823 case NodeType_ENTITY_REFERENCE_NODE:
825 Reference< XEntityReference > const xRef(xImportedNode,
826 UNO_QUERY_THROW);
827 Reference< XEntityReference > const xNewRef(
828 xDocument->createEntityReference(xRef->getNodeName()));
829 xNode.set(xNewRef, UNO_QUERY);
830 break;
832 case NodeType_PROCESSING_INSTRUCTION_NODE:
834 Reference< XProcessingInstruction > const xPi(xImportedNode,
835 UNO_QUERY_THROW);
836 Reference< XProcessingInstruction > const xNewPi(
837 xDocument->createProcessingInstruction(
838 xPi->getTarget(), xPi->getData()));
839 xNode.set(xNewPi, UNO_QUERY);
840 break;
842 case NodeType_TEXT_NODE:
844 Reference< XText > const xText(xImportedNode, UNO_QUERY_THROW);
845 Reference< XText > const xNewText(
846 xDocument->createTextNode(xText->getData()));
847 xNode.set(xNewText, UNO_QUERY);
848 break;
850 case NodeType_ENTITY_NODE:
851 case NodeType_DOCUMENT_NODE:
852 case NodeType_DOCUMENT_TYPE_NODE:
853 case NodeType_NOTATION_NODE:
854 default:
855 // can't be imported
856 throw RuntimeException();
859 if (deep)
861 // get children and import them
862 Reference< XNode > const xChild = xImportedNode->getFirstChild();
863 if (xChild.is())
865 lcl_ImportSiblings(xDocument, xNode, xChild);
869 /* DOMNodeInsertedIntoDocument
870 * Fired when a node is being inserted into a document,
871 * either through direct insertion of the Node or insertion of a
872 * subtree in which it is contained. This event is dispatched after
873 * the insertion has taken place. The target of this event is the node
874 * being inserted. If the Node is being directly inserted the DOMNodeInserted
875 * event will fire before the DOMNodeInsertedIntoDocument event.
876 * Bubbles: No
877 * Cancelable: No
878 * Context Info: None
880 if (xNode.is())
882 Reference< XDocumentEvent > const xDocevent(xDocument, UNO_QUERY);
883 Reference< XMutationEvent > const event(xDocevent->createEvent(
884 "DOMNodeInsertedIntoDocument"), UNO_QUERY_THROW);
885 event->initMutationEvent(
886 "DOMNodeInsertedIntoDocument", true, false, Reference< XNode >(),
887 OUString(), OUString(), OUString(), AttrChangeType(0) );
888 Reference< XEventTarget > const xDocET(xDocument, UNO_QUERY);
889 xDocET->dispatchEvent(event);
892 return xNode;
895 Reference< XNode > SAL_CALL CDocument::importNode(
896 Reference< XNode > const& xImportedNode, sal_Bool deep)
898 if (!xImportedNode.is()) { throw RuntimeException(); }
900 // NB: this whole operation inherently accesses 2 distinct documents.
901 // The imported node could even be from a different DOM implementation,
902 // so this implementation cannot make any assumptions about the
903 // locking strategy of the imported node.
904 // So the import takes no lock on this document;
905 // it only calls UNO methods on this document that temporarily
906 // lock the document, and UNO methods on the imported node that
907 // may temporarily lock the other document.
908 // As a consequence, the import is not atomic with regard to
909 // concurrent modifications of either document, but it should not
910 // deadlock.
911 // To ensure that no members are accessed, the implementation is in
912 // static non-member functions.
914 Reference< XDocument > const xDocument(this);
915 // already in doc?
916 if (xImportedNode->getOwnerDocument() == xDocument) {
917 return xImportedNode;
920 Reference< XNode > const xNode(
921 lcl_ImportNode(xDocument, xImportedNode, deep) );
922 return xNode;
925 OUString SAL_CALL CDocument::getNodeName()
927 // does not need mutex currently
928 return OUString("#document");
931 OUString SAL_CALL CDocument::getNodeValue()
933 // does not need mutex currently
934 return OUString();
937 Reference< XNode > SAL_CALL CDocument::cloneNode(sal_Bool bDeep)
939 ::osl::MutexGuard const g(m_rMutex);
941 OSL_ASSERT(nullptr != m_aNodePtr);
942 if (nullptr == m_aNodePtr) {
943 return nullptr;
945 xmlDocPtr const pClone(xmlCopyDoc(m_aDocPtr, bDeep ? 1 : 0));
946 if (nullptr == pClone) { return nullptr; }
947 Reference< XNode > const xRet(
948 static_cast<CNode*>(CDocument::CreateCDocument(pClone).get()));
949 return xRet;
952 Reference< XEvent > SAL_CALL CDocument::createEvent(const OUString& aType)
954 // does not need mutex currently
955 events::CEvent *pEvent = nullptr;
956 if ( aType == "DOMSubtreeModified" || aType == "DOMNodeInserted" || aType == "DOMNodeRemoved"
957 || aType == "DOMNodeRemovedFromDocument" || aType == "DOMNodeInsertedIntoDocument" || aType == "DOMAttrModified"
958 || aType == "DOMCharacterDataModified")
960 pEvent = new events::CMutationEvent;
962 } else if ( aType == "DOMFocusIn" || aType == "DOMFocusOut" || aType == "DOMActivate")
964 pEvent = new events::CUIEvent;
965 } else if ( aType == "click" || aType == "mousedown" || aType == "mouseup"
966 || aType == "mouseover" || aType == "mousemove" || aType == "mouseout" )
968 pEvent = new events::CMouseEvent;
970 else // generic event
972 pEvent = new events::CEvent;
974 return Reference< XEvent >(pEvent);
977 // css::xml::sax::XSAXSerializable
978 void SAL_CALL CDocument::serialize(
979 const Reference< XDocumentHandler >& i_xHandler,
980 const Sequence< beans::StringPair >& i_rNamespaces)
982 ::osl::MutexGuard const g(m_Mutex);
984 // add new namespaces to root node
985 xmlNodePtr const pRoot = lcl_getDocumentRootPtr(m_aDocPtr);
986 if (nullptr != pRoot) {
987 const beans::StringPair * pSeq = i_rNamespaces.getConstArray();
988 for (const beans::StringPair *pNsDef = pSeq;
989 pNsDef < pSeq + i_rNamespaces.getLength(); ++pNsDef) {
990 OString prefix = OUStringToOString(pNsDef->First,
991 RTL_TEXTENCODING_UTF8);
992 OString href = OUStringToOString(pNsDef->Second,
993 RTL_TEXTENCODING_UTF8);
994 // this will only add the ns if it does not exist already
995 xmlNewNs(pRoot, reinterpret_cast<const xmlChar*>(href.getStr()),
996 reinterpret_cast<const xmlChar*>(prefix.getStr()));
998 // eliminate duplicate namespace declarations
999 nscleanup(pRoot->children, pRoot);
1001 saxify(i_xHandler);
1004 // css::xml::sax::XFastSAXSerializable
1005 void SAL_CALL CDocument::fastSerialize( const Reference< XFastDocumentHandler >& i_xHandler,
1006 const Reference< XFastTokenHandler >& i_xTokenHandler,
1007 const Sequence< beans::StringPair >& i_rNamespaces,
1008 const Sequence< beans::Pair< OUString, sal_Int32 > >& i_rRegisterNamespaces )
1010 ::osl::MutexGuard const g(m_Mutex);
1012 // add new namespaces to root node
1013 xmlNodePtr const pRoot = lcl_getDocumentRootPtr(m_aDocPtr);
1014 if (nullptr != pRoot) {
1015 const beans::StringPair * pSeq = i_rNamespaces.getConstArray();
1016 for (const beans::StringPair *pNsDef = pSeq;
1017 pNsDef < pSeq + i_rNamespaces.getLength(); ++pNsDef) {
1018 OString prefix = OUStringToOString(pNsDef->First,
1019 RTL_TEXTENCODING_UTF8);
1020 OString href = OUStringToOString(pNsDef->Second,
1021 RTL_TEXTENCODING_UTF8);
1022 // this will only add the ns if it does not exist already
1023 xmlNewNs(pRoot, reinterpret_cast<const xmlChar*>(href.getStr()),
1024 reinterpret_cast<const xmlChar*>(prefix.getStr()));
1026 // eliminate duplicate namespace declarations
1027 nscleanup(pRoot->children, pRoot);
1030 Context aContext(i_xHandler,
1031 i_xTokenHandler);
1033 // register namespace ids
1034 const beans::Pair<OUString,sal_Int32>* pSeq = i_rRegisterNamespaces.getConstArray();
1035 for (const beans::Pair<OUString,sal_Int32>* pNs = pSeq;
1036 pNs < pSeq + i_rRegisterNamespaces.getLength(); ++pNs)
1038 OSL_ENSURE(pNs->Second >= FastToken::NAMESPACE,
1039 "CDocument::fastSerialize(): invalid NS token id");
1040 aContext.maNamespaceMap[ pNs->First ] = pNs->Second;
1043 fastSaxify(aContext);
1047 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */