Debian Codegraph @

src/odf/element.py

raw
1 #!/usr/bin/env python
2 # Copyright (C) 2007-2010 Søren Roug, European Environment Agency
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 #
18 # Contributor(s):
19 #
20
21 # Note: This script has copied a lot of text from xml.dom.minidom.
22 # Whatever license applies to that file also applies to this file.
23 #
24
25 import xml.dom
26 from typing import TYPE_CHECKING
27 from xml.dom.minicompat import EmptyNodeList, defproperty
28
29 from . import grammar
30 from .attrconverters import AttrConverters
31 from .namespaces import nsdict
32
33 if TYPE_CHECKING:
34 from .opendocument import OpenDocument
35
36 # The following code is pasted form xml.sax.saxutils
37 # Tt makes it possible to run the code without the xml sax package installed
38 # To make it possible to have <rubbish> in your text elements, it is necessary to escape the texts
39
40
41 def _escape(data, entities={}):
42 """Escape &, <, and > in a string of data.
43
44 You can escape other strings of data by passing a dictionary as
45 the optional entities parameter. The keys and values must all be
46 strings; each key will be replaced with its corresponding value.
47 """
48 data = data.replace('&', '&amp;')
49 data = data.replace('<', '&lt;')
50 data = data.replace('>', '&gt;')
51 for chars, entity in entities.items():
52 data = data.replace(chars, entity)
53 return data
54
55
56 def _quoteattr(data, entities={}):
57 """Escape and quote an attribute value.
58
59 Escape &, <, and > in a string of data, then quote it for use as
60 an attribute value. The \" character will be escaped as well, if
61 necessary.
62
63 You can escape other strings of data by passing a dictionary as
64 the optional entities parameter. The keys and values must all be
65 strings; each key will be replaced with its corresponding value.
66 """
67 entities['\n'] = '&#10;'
68 entities['\r'] = '&#12;'
69 data = _escape(data, entities)
70 if '"' in data:
71 if "'" in data:
72 data = '"{}"'.format(data.replace('"', '&quot;'))
73 else:
74 data = f"'{data}'"
75 else:
76 data = f'"{data}"'
77 return data
78
79
80 def _nssplit(qualifiedName):
81 """Split a qualified name into namespace part and local part."""
82 fields = qualifiedName.split(':', 1)
83 if len(fields) == 2:
84 return fields
85 else:
86 return (None, fields[0])
87
88
89 def _nsassign(namespace):
90 return nsdict.setdefault(namespace, 'ns' + str(len(nsdict)))
91
92
93 # Exceptions
94
95
96 class IllegalChild(Exception):
97 """Complains if you add an element to a parent where it is not allowed"""
98
99
100 class IllegalText(Exception):
101 """Complains if you add text or cdata to an element where it is not allowed"""
102
103
104 class Node(xml.dom.Node):
105 """super class for more specific nodes"""
106
107 parentNode = None
108 nextSibling = None
109 previousSibling = None
110 childNodes: list[Node]
111 _child_node_types: tuple[int, ...]
112 tagName: str
113 ownerDocument: OpenDocument | None
114 nodeType: int
115
116 def toXml(self, level: int, f: object) -> None:
117 raise NotImplementedError
118
119 def hasChildNodes(self):
120 """Tells whether this element has any children; text nodes,
121 subelements, whatever.
122 """
123 if self.childNodes:
124 return True
125 else:
126 return False
127
128 def _get_childNodes(self):
129 return self.childNodes
130
131 def _get_firstChild(self):
132 if self.childNodes:
133 return self.childNodes[0]
134
135 def _get_lastChild(self):
136 if self.childNodes:
137 return self.childNodes[-1]
138
139 def insertBefore(self, newChild, refChild):
140 """Inserts the node newChild before the existing child node refChild.
141 If refChild is null, insert newChild at the end of the list of children.
142 """
143 if newChild.nodeType not in self._child_node_types:
144 raise IllegalChild(f'{newChild.tagName} cannot be child of {self.tagName}')
145 if newChild.parentNode is not None:
146 newChild.parentNode.removeChild(newChild)
147 if refChild is None:
148 self.appendChild(newChild)
149 else:
150 try:
151 index = self.childNodes.index(refChild)
152 except ValueError:
153 raise xml.dom.NotFoundErr()
154 self.childNodes.insert(index, newChild)
155 newChild.nextSibling = refChild
156 refChild.previousSibling = newChild
157 if index:
158 node = self.childNodes[index - 1]
159 node.nextSibling = newChild
160 newChild.previousSibling = node
161 else:
162 newChild.previousSibling = None
163 newChild.parentNode = self
164 return newChild
165
166 def appendChild(self, node):
167 """Adds the node to the end of the list of children of this node.
168 If the node is already in the tree, it is first removed.
169 """
170 newChild = node
171 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
172 for c in tuple(newChild.childNodes):
173 self.appendChild(c)
174 # The DOM does not clearly specify what to return in this case
175 return newChild
176 if newChild.nodeType not in self._child_node_types:
177 raise IllegalChild(f'<{newChild.tagName}> is not allowed in {self.tagName}')
178 if newChild.parentNode is not None:
179 newChild.parentNode.removeChild(newChild)
180 _append_child(self, newChild)
181 newChild.nextSibling = None
182 return newChild
183
184 def removeChild(self, oldChild):
185 """Removes the child node indicated by oldChild from the list of children, and returns it."""
186 # FIXME: update ownerDocument.element_dict or find other solution
187 try:
188 self.childNodes.remove(oldChild)
189 except ValueError:
190 raise xml.dom.NotFoundErr()
191 if oldChild.nextSibling is not None:
192 oldChild.nextSibling.previousSibling = oldChild.previousSibling
193 if oldChild.previousSibling is not None:
194 oldChild.previousSibling.nextSibling = oldChild.nextSibling
195 oldChild.nextSibling = oldChild.previousSibling = None
196 if self.ownerDocument:
197 self.ownerDocument.clear_caches()
198 oldChild.parentNode = None
199 return oldChild
200
201 def __unicode__(self):
202 val = []
203 for c in self.childNodes:
204 val.append(str(c))
205 return ''.join(val)
206
207 __str__ = __unicode__
208
209
210 defproperty(Node, 'firstChild', doc='First child node, or None.')
211 defproperty(Node, 'lastChild', doc='Last child node, or None.')
212
213
214 def _append_child(self, node):
215 # fast path with less checks; usable by DOM builders if careful
216 childNodes = self.childNodes
217 if childNodes:
218 last = childNodes[-1]
219 node.__dict__['previousSibling'] = last
220 last.__dict__['nextSibling'] = node
221 childNodes.append(node)
222 node.__dict__['parentNode'] = self
223
224
225 class Childless:
226 """Mixin that makes childless-ness easy to implement and avoids
227 the complexity of the Node methods that deal with children.
228 """
229
230 attributes = None
231 childNodes = EmptyNodeList()
232 tagName: str
233 firstChild = None
234 lastChild = None
235
236 def _get_firstChild(self):
237 return None
238
239 def _get_lastChild(self):
240 return None
241
242 def appendChild(self, node):
243 """Raises an error"""
244 raise xml.dom.HierarchyRequestErr(self.tagName + ' nodes cannot have children')
245
246 def hasChildNodes(self):
247 return False
248
249 def insertBefore(self, newChild, refChild):
250 """Raises an error"""
251 raise xml.dom.HierarchyRequestErr(self.tagName + ' nodes do not have children')
252
253 def removeChild(self, oldChild):
254 """Raises an error"""
255 raise xml.dom.NotFoundErr(self.tagName + ' nodes do not have children')
256
257 def replaceChild(self, newChild, oldChild):
258 """Raises an error"""
259 raise xml.dom.HierarchyRequestErr(self.tagName + ' nodes do not have children')
260
261
262 class Text(Childless, Node):
263 nodeType = Node.TEXT_NODE
264 tagName = 'Text'
265
266 def __init__(self, data):
267 self.data = data
268
269 def __str__(self):
270 return self.data
271
272 __unicode__ = __str__
273
274 def toXml(self, level, f):
275 """Write XML in UTF-8"""
276 if self.data:
277 f.write(_escape(str(self.data).encode('utf-8')))
278
279
280 class CDATASection(Text, Childless):
281 nodeType = Node.CDATA_SECTION_NODE
282
283 def toXml(self, level, f):
284 """Generate XML output of the node. If the text contains "]]>", then
285 escape it by going out of CDATA mode (]]>), then write the string
286 and then go into CDATA mode again. (<![CDATA[)
287 """
288 if self.data:
289 f.write('<![CDATA[{}]]>'.format(self.data.replace(']]>', ']]>]]><![CDATA[')))
290
291
292 class Element(Node):
293 """Creates a arbitrary element and is intended to be subclassed not used on its own.
294 This element is the base of every element it defines a class which resembles
295 a xml-element. The main advantage of this kind of implementation is that you don't
296 have to create a toXML method for every different object. Every element
297 consists of an attribute, optional subelements, optional text and optional cdata.
298 """
299
300 nodeType = Node.ELEMENT_NODE
301 namespaces = {} # Due to shallow copy this is a static variable
302
303 _child_node_types = (
304 Node.ELEMENT_NODE,
305 Node.PROCESSING_INSTRUCTION_NODE,
306 Node.COMMENT_NODE,
307 Node.TEXT_NODE,
308 Node.CDATA_SECTION_NODE,
309 Node.ENTITY_REFERENCE_NODE,
310 )
311
312 def __init__(self, attributes=None, text=None, cdata=None, qname=None, qattributes=None, check_grammar=True, **args):
313 if qname is not None:
314 self.qname = qname
315 assert hasattr(self, 'qname')
316 self.ownerDocument = None
317 self.childNodes = []
318 self.allowed_children = grammar.allowed_children.get(self.qname)
319 prefix = self.get_nsprefix(self.qname[0])
320 self.tagName = prefix + ':' + self.qname[1]
321 if text is not None:
322 self.addText(text)
323 if cdata is not None:
324 self.addCDATA(cdata)
325
326 allowed_attrs = self.allowed_attributes()
327 self.attributes: dict[tuple[str | None, str] | str, object] = {}
328 # Load the attributes from the 'attributes' argument
329 if attributes:
330 for attr, value in attributes.items():
331 self.setAttribute(attr, value)
332 # Load the qualified attributes
333 if qattributes:
334 for attr, value in qattributes.items():
335 self.setAttrNS(attr[0], attr[1], value)
336 if allowed_attrs is not None:
337 # Load the attributes from the 'args' argument
338 for arg, attrs in args.items():
339 self.setAttribute(arg, attrs)
340 else:
341 for arg, attrs in args.items(): # If any attribute is allowed
342 self.attributes[arg] = attrs
343 if not check_grammar:
344 return
345 # Test that all mandatory attributes have been added.
346 required = grammar.required_attributes.get(self.qname)
347 if required:
348 for r in required:
349 if self.getAttrNS(r[0], r[1]) is None:
350 raise AttributeError('Required attribute missing: {} in <{}>'.format(r[1].lower().replace('-', ''), self.tagName))
351
352 def get_knownns(self, prefix):
353 """Odfpy maintains a list of known namespaces. In some cases a prefix is used, and
354 we need to know which namespace it resolves to.
355 """
356 global nsdict
357 for ns, p in nsdict.items():
358 if p == prefix:
359 return ns
360 return None
361
362 def get_nsprefix(self, namespace):
363 """Odfpy maintains a list of known namespaces. In some cases we have a namespace URL,
364 and needs to look up or assign the prefix for it.
365 """
366 if namespace is None:
367 namespace = ''
368 prefix = _nsassign(namespace)
369 if namespace not in self.namespaces:
370 self.namespaces[namespace] = prefix
371 return prefix
372
373 def allowed_attributes(self):
374 return grammar.allowed_attributes.get(self.qname)
375
376 def _setOwnerDoc(self, element):
377 element.ownerDocument = self.ownerDocument
378 for child in element.childNodes:
379 self._setOwnerDoc(child)
380
381 def addElement(self, element, check_grammar=True):
382 """adds an element to an Element
383
384 Element.addElement(Element)
385 """
386 if check_grammar and self.allowed_children is not None:
387 if element.qname not in self.allowed_children:
388 raise IllegalChild(f'<{element.tagName}> is not allowed in <{self.tagName}>')
389 self.appendChild(element)
390 self._setOwnerDoc(element)
391 if self.ownerDocument:
392 self.ownerDocument.rebuild_caches(element)
393
394 def addText(self, text, check_grammar=True):
395 """Adds text to an element
396 Setting check_grammar=False turns off grammar checking
397 """
398 if check_grammar and self.qname not in grammar.allows_text:
399 raise IllegalText(f'The <{self.tagName}> element does not allow text')
400 elif text != '':
401 self.appendChild(Text(text))
402
403 def addCDATA(self, cdata, check_grammar=True):
404 """Adds CDATA to an element
405 Setting check_grammar=False turns off grammar checking
406 """
407 if check_grammar and self.qname not in grammar.allows_text:
408 raise IllegalText(f'The <{self.tagName}> element does not allow text')
409 else:
410 self.appendChild(CDATASection(cdata))
411
412 def removeAttribute(self, attr, check_grammar=True):
413 """Removes an attribute by name."""
414 allowed_attrs = self.allowed_attributes()
415 if allowed_attrs is None:
416 if isinstance(attr, tuple):
417 prefix, localname = attr
418 self.removeAttrNS(prefix, localname)
419 else:
420 raise AttributeError('Unable to add simple attribute - use (namespace, localpart)')
421 else:
422 # Construct a list of allowed arguments
423 allowed_args = [a[1].lower().replace('-', '') for a in allowed_attrs]
424 if check_grammar and attr not in allowed_args:
425 raise AttributeError(f'Attribute {attr} is not allowed in <{self.tagName}>')
426 i = allowed_args.index(attr)
427 self.removeAttrNS(allowed_attrs[i][0], allowed_attrs[i][1])
428
429 def setAttribute(self, attr, value, check_grammar=True):
430 """Add an attribute to the element
431 This is sort of a convenience method. All attributes in ODF have
432 namespaces. The library knows what attributes are legal and then allows
433 the user to provide the attribute as a keyword argument and the
434 library will add the correct namespace.
435 Must overwrite, If attribute already exists.
436 """
437 allowed_attrs = self.allowed_attributes()
438 if allowed_attrs is None:
439 if isinstance(attr, tuple):
440 prefix, localname = attr
441 self.setAttrNS(prefix, localname, value)
442 else:
443 raise AttributeError('Unable to add simple attribute - use (namespace, localpart)')
444 else:
445 # Construct a list of allowed arguments
446 allowed_args = [a[1].lower().replace('-', '') for a in allowed_attrs]
447 if check_grammar and attr not in allowed_args:
448 raise AttributeError(f'Attribute {attr} is not allowed in <{self.tagName}>')
449 i = allowed_args.index(attr)
450 self.setAttrNS(allowed_attrs[i][0], allowed_attrs[i][1], value)
451
452 def setAttrNS(self, namespace, localpart, value):
453 """Add an attribute to the element
454 In case you need to add an attribute the library doesn't know about
455 then you must provide the full qualified name
456 It will not check that the attribute is legal according to the schema.
457 Must overwrite, If attribute already exists.
458 """
459 c = AttrConverters()
460 self.attributes[(namespace, localpart)] = c.convert((namespace, localpart), value, self)
461
462 def getAttrNS(self, namespace, localpart):
463 return self.attributes.get((namespace, localpart))
464
465 def removeAttrNS(self, namespace, localpart):
466 del self.attributes[(namespace, localpart)]
467
468 def getAttribute(self, attr):
469 """Get an attribute value. The method knows which namespace the attribute is in"""
470 allowed_attrs = self.allowed_attributes()
471 if allowed_attrs is None:
472 if isinstance(attr, tuple):
473 prefix, localname = attr
474 return self.getAttrNS(prefix, localname)
475 else:
476 raise AttributeError('Unable to get simple attribute - use (namespace, localpart)')
477 else:
478 # Construct a list of allowed arguments
479 allowed_args = [a[1].lower().replace('-', '') for a in allowed_attrs]
480 i = allowed_args.index(attr)
481 return self.getAttrNS(allowed_attrs[i][0], allowed_attrs[i][1])
482
483 def write_open_tag(self, level, f):
484 f.write('<' + self.tagName)
485 if level == 0:
486 for namespace, prefix in self.namespaces.items():
487 f.write(' xmlns:' + prefix + '="' + _escape(str(namespace)) + '"')
488 for qname in self.attributes.keys():
489 prefix = self.get_nsprefix(qname[0])
490 f.write(' ' + _escape(str(prefix + ':' + qname[1])) + '=' + _quoteattr(str(self.attributes[qname]).encode('utf-8')))
491 f.write('>')
492
493 def write_close_tag(self, level, f):
494 f.write('</' + self.tagName + '>')
495
496 def toXml(self, level, f):
497 """Generate XML stream out of the tree structure"""
498 f.write('<' + self.tagName)
499 if level == 0:
500 for namespace, prefix in self.namespaces.items():
501 f.write(' xmlns:' + prefix + '="' + _escape(str(namespace)) + '"')
502 for qname in self.attributes.keys():
503 prefix = self.get_nsprefix(qname[0])
504 f.write(' ' + _escape(str(prefix + ':' + qname[1])) + '=' + _quoteattr(str(self.attributes[qname]).encode('utf-8')))
505 if self.childNodes:
506 f.write('>')
507 for element in self.childNodes:
508 element.toXml(level + 1, f)
509 f.write('</' + self.tagName + '>')
510 else:
511 f.write('/>')
512
513 def _getElementsByObj(self, obj, accumulator):
514 if self.qname == obj.qname:
515 accumulator.append(self)
516 for e in self.childNodes:
517 if isinstance(e, Element):
518 accumulator = e._getElementsByObj(obj, accumulator)
519 return accumulator
520
521 def getElementsByType(self, element):
522 """Gets elements based on the type, which is function from text.py, draw.py etc."""
523 obj = element(check_grammar=False)
524 return self._getElementsByObj(obj, [])
525
526 def isInstanceOf(self, element):
527 """This is a check to see if the object is an instance of a type"""
528 obj = element(check_grammar=False)
529 return self.qname == obj.qname