python-pptx2 2.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. pptx2/__init__.py +152 -0
  2. pptx2/_color.py +75 -0
  3. pptx2/_slide_importer.py +597 -0
  4. pptx2/_svg.py +155 -0
  5. pptx2/_template_applier.py +292 -0
  6. pptx2/_textstyle.py +187 -0
  7. pptx2/accessibility.py +365 -0
  8. pptx2/action.py +270 -0
  9. pptx2/animation.py +2237 -0
  10. pptx2/api.py +49 -0
  11. pptx2/audit.py +258 -0
  12. pptx2/chart/__init__.py +0 -0
  13. pptx2/chart/analytics.py +381 -0
  14. pptx2/chart/axis.py +543 -0
  15. pptx2/chart/category.py +200 -0
  16. pptx2/chart/chart.py +670 -0
  17. pptx2/chart/data.py +864 -0
  18. pptx2/chart/datalabel.py +406 -0
  19. pptx2/chart/legend.py +86 -0
  20. pptx2/chart/marker.py +70 -0
  21. pptx2/chart/palettes.py +129 -0
  22. pptx2/chart/plot.py +462 -0
  23. pptx2/chart/point.py +101 -0
  24. pptx2/chart/quick_layouts.py +325 -0
  25. pptx2/chart/series.py +334 -0
  26. pptx2/chart/xlsx.py +272 -0
  27. pptx2/chart/xmlwriter.py +1845 -0
  28. pptx2/compose/__init__.py +28 -0
  29. pptx2/compose/from_spec.py +1094 -0
  30. pptx2/design/__init__.py +8 -0
  31. pptx2/design/components.py +607 -0
  32. pptx2/design/figures.py +389 -0
  33. pptx2/design/layout.py +370 -0
  34. pptx2/design/recipes.py +1967 -0
  35. pptx2/design/style.py +209 -0
  36. pptx2/design/tokens.py +915 -0
  37. pptx2/diagrams.py +754 -0
  38. pptx2/dml/__init__.py +0 -0
  39. pptx2/dml/chtfmt.py +40 -0
  40. pptx2/dml/color.py +496 -0
  41. pptx2/dml/effect.py +909 -0
  42. pptx2/dml/fill.py +691 -0
  43. pptx2/dml/line.py +287 -0
  44. pptx2/dml/picture.py +212 -0
  45. pptx2/dml/three_d.py +381 -0
  46. pptx2/enum/__init__.py +0 -0
  47. pptx2/enum/action.py +71 -0
  48. pptx2/enum/animation.py +31 -0
  49. pptx2/enum/base.py +218 -0
  50. pptx2/enum/chart.py +574 -0
  51. pptx2/enum/dml.py +740 -0
  52. pptx2/enum/lang.py +685 -0
  53. pptx2/enum/presentation.py +133 -0
  54. pptx2/enum/shapes.py +1029 -0
  55. pptx2/enum/text.py +230 -0
  56. pptx2/exc.py +42 -0
  57. pptx2/formats.py +139 -0
  58. pptx2/geometry.py +420 -0
  59. pptx2/inherit.py +109 -0
  60. pptx2/lint.py +2256 -0
  61. pptx2/math.py +177 -0
  62. pptx2/media.py +197 -0
  63. pptx2/opc/__init__.py +0 -0
  64. pptx2/opc/constants.py +332 -0
  65. pptx2/opc/oxml.py +188 -0
  66. pptx2/opc/package.py +762 -0
  67. pptx2/opc/packuri.py +109 -0
  68. pptx2/opc/serialized.py +296 -0
  69. pptx2/opc/shared.py +20 -0
  70. pptx2/opc/spec.py +45 -0
  71. pptx2/oxml/__init__.py +555 -0
  72. pptx2/oxml/action.py +53 -0
  73. pptx2/oxml/chart/__init__.py +0 -0
  74. pptx2/oxml/chart/axis.py +337 -0
  75. pptx2/oxml/chart/chart.py +481 -0
  76. pptx2/oxml/chart/datalabel.py +253 -0
  77. pptx2/oxml/chart/legend.py +72 -0
  78. pptx2/oxml/chart/marker.py +61 -0
  79. pptx2/oxml/chart/plot.py +365 -0
  80. pptx2/oxml/chart/series.py +425 -0
  81. pptx2/oxml/chart/shared.py +220 -0
  82. pptx2/oxml/coreprops.py +288 -0
  83. pptx2/oxml/dml/__init__.py +0 -0
  84. pptx2/oxml/dml/color.py +135 -0
  85. pptx2/oxml/dml/effect.py +213 -0
  86. pptx2/oxml/dml/fill.py +316 -0
  87. pptx2/oxml/dml/line.py +12 -0
  88. pptx2/oxml/dml/three_d.py +110 -0
  89. pptx2/oxml/ns.py +135 -0
  90. pptx2/oxml/presentation.py +313 -0
  91. pptx2/oxml/shapes/__init__.py +19 -0
  92. pptx2/oxml/shapes/autoshape.py +467 -0
  93. pptx2/oxml/shapes/connector.py +107 -0
  94. pptx2/oxml/shapes/graphfrm.py +347 -0
  95. pptx2/oxml/shapes/groupshape.py +329 -0
  96. pptx2/oxml/shapes/picture.py +270 -0
  97. pptx2/oxml/shapes/shared.py +577 -0
  98. pptx2/oxml/simpletypes.py +1027 -0
  99. pptx2/oxml/slide.py +563 -0
  100. pptx2/oxml/table.py +650 -0
  101. pptx2/oxml/text.py +815 -0
  102. pptx2/oxml/theme.py +36 -0
  103. pptx2/oxml/xmlchemy.py +717 -0
  104. pptx2/package.py +222 -0
  105. pptx2/parts/__init__.py +0 -0
  106. pptx2/parts/chart.py +95 -0
  107. pptx2/parts/coreprops.py +167 -0
  108. pptx2/parts/diagram.py +37 -0
  109. pptx2/parts/embeddedpackage.py +93 -0
  110. pptx2/parts/image.py +275 -0
  111. pptx2/parts/media.py +37 -0
  112. pptx2/parts/presentation.py +136 -0
  113. pptx2/parts/slide.py +371 -0
  114. pptx2/presentation.py +408 -0
  115. pptx2/py.typed +0 -0
  116. pptx2/render.py +586 -0
  117. pptx2/section.py +272 -0
  118. pptx2/shapes/__init__.py +26 -0
  119. pptx2/shapes/autoshape.py +442 -0
  120. pptx2/shapes/base.py +1078 -0
  121. pptx2/shapes/connector.py +297 -0
  122. pptx2/shapes/freeform.py +337 -0
  123. pptx2/shapes/graphfrm.py +316 -0
  124. pptx2/shapes/group.py +264 -0
  125. pptx2/shapes/picture.py +422 -0
  126. pptx2/shapes/placeholder.py +468 -0
  127. pptx2/shapes/shapetree.py +2027 -0
  128. pptx2/shared.py +82 -0
  129. pptx2/skill/SKILL.md +450 -0
  130. pptx2/skill/__init__.py +78 -0
  131. pptx2/skill/__main__.py +64 -0
  132. pptx2/skill/references/animations.md +189 -0
  133. pptx2/skill/references/basics.md +421 -0
  134. pptx2/skill/references/charts.md +254 -0
  135. pptx2/skill/references/compose.md +234 -0
  136. pptx2/skill/references/design.md +366 -0
  137. pptx2/skill/references/effects.md +249 -0
  138. pptx2/skill/references/end-to-end-deck.md +231 -0
  139. pptx2/skill/references/geometry-and-arrows.md +334 -0
  140. pptx2/skill/references/lint.md +275 -0
  141. pptx2/skill/references/math.md +86 -0
  142. pptx2/skill/references/picture-effects.md +129 -0
  143. pptx2/skill/references/render.md +151 -0
  144. pptx2/skill/references/smart-art.md +75 -0
  145. pptx2/skill/references/space-aware-authoring.md +249 -0
  146. pptx2/skill/references/tables.md +244 -0
  147. pptx2/skill/references/theme.md +127 -0
  148. pptx2/skill/references/three-d.md +109 -0
  149. pptx2/skill/references/transitions.md +100 -0
  150. pptx2/slide.py +1244 -0
  151. pptx2/smart_art.py +220 -0
  152. pptx2/spec.py +633 -0
  153. pptx2/table.py +1181 -0
  154. pptx2/table_styles.py +184 -0
  155. pptx2/templates/default.pptx +0 -0
  156. pptx2/templates/docx-icon.emf +0 -0
  157. pptx2/templates/generic-icon.emf +0 -0
  158. pptx2/templates/notes.xml +23 -0
  159. pptx2/templates/notesMaster.xml +352 -0
  160. pptx2/templates/pptx-icon.emf +0 -0
  161. pptx2/templates/theme.xml +321 -0
  162. pptx2/templates/xlsx-icon.emf +0 -0
  163. pptx2/text/__init__.py +0 -0
  164. pptx2/text/fonts.py +482 -0
  165. pptx2/text/layout.py +374 -0
  166. pptx2/text/text.py +1272 -0
  167. pptx2/theme.py +721 -0
  168. pptx2/types.py +36 -0
  169. pptx2/util.py +263 -0
  170. python_pptx2-2.13.0.dist-info/METADATA +351 -0
  171. python_pptx2-2.13.0.dist-info/RECORD +175 -0
  172. python_pptx2-2.13.0.dist-info/WHEEL +5 -0
  173. python_pptx2-2.13.0.dist-info/entry_points.txt +3 -0
  174. python_pptx2-2.13.0.dist-info/licenses/LICENSE +22 -0
  175. python_pptx2-2.13.0.dist-info/top_level.txt +1 -0
pptx2/oxml/xmlchemy.py ADDED
@@ -0,0 +1,717 @@
1
+ """Base and meta classes enabling declarative definition of custom element classes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Callable, Iterable, Protocol, Sequence, Type, cast
7
+
8
+ from lxml import etree
9
+ from lxml.etree import ElementBase, _Element # pyright: ignore[reportPrivateUsage]
10
+
11
+ from pptx2.exc import InvalidXmlError
12
+ from pptx2.oxml import oxml_parser
13
+ from pptx2.oxml.ns import NamespacePrefixedTag, _nsmap, qn # pyright: ignore[reportPrivateUsage]
14
+ from pptx2.util import lazyproperty
15
+
16
+
17
+ class AttributeType(Protocol):
18
+ """Interface for an object that can act as an attribute type.
19
+
20
+ An attribute-type specifies how values are transformed to and from the XML "string" value of the
21
+ attribute.
22
+ """
23
+
24
+ @classmethod
25
+ def from_xml(cls, xml_value: str) -> Any:
26
+ """Transform an attribute value to a Python value."""
27
+ ...
28
+
29
+ @classmethod
30
+ def to_xml(cls, value: Any) -> str:
31
+ """Transform a Python value to a str value suitable to this XML attribute."""
32
+ ...
33
+
34
+
35
+ def OxmlElement(nsptag_str: str, nsmap: dict[str, str] | None = None) -> BaseOxmlElement:
36
+ """Return a "loose" lxml element having the tag specified by `nsptag_str`.
37
+
38
+ `nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is
39
+ an instance of the custom element class for this tag name if one is defined.
40
+ """
41
+ nsptag = NamespacePrefixedTag(nsptag_str)
42
+ nsmap = nsmap if nsmap is not None else nsptag.nsmap
43
+ return oxml_parser.makeelement(nsptag.clark_name, nsmap=nsmap)
44
+
45
+
46
+ def serialize_for_reading(element: ElementBase):
47
+ """
48
+ Serialize *element* to human-readable XML suitable for tests. No XML
49
+ declaration.
50
+ """
51
+ xml = etree.tostring(element, encoding="unicode", pretty_print=True)
52
+ return XmlString(xml)
53
+
54
+
55
+ class XmlString(str):
56
+ """Provides string comparison override suitable for serialized XML; useful for tests."""
57
+
58
+ # ' <w:xyz xmlns:a="http://ns/decl/a" attr_name="val">text</w:xyz>'
59
+ # | | || |
60
+ # +----------+------------------------------------------++-----------+
61
+ # front attrs | text
62
+ # close
63
+
64
+ _xml_elm_line_patt = re.compile(r"( *</?[\w:]+)(.*?)(/?>)([^<]*</[\w:]+>)?")
65
+
66
+ def __eq__(self, other: object) -> bool:
67
+ if not isinstance(other, str):
68
+ return False
69
+ lines = self.splitlines()
70
+ lines_other = other.splitlines()
71
+ if len(lines) != len(lines_other):
72
+ return False
73
+ for line, line_other in zip(lines, lines_other):
74
+ if not self._eq_elm_strs(line, line_other):
75
+ return False
76
+ return True
77
+
78
+ def __ne__(self, other: object) -> bool:
79
+ return not self.__eq__(other)
80
+
81
+ def _attr_seq(self, attrs: str) -> list[str]:
82
+ """Return a sequence of attribute strings parsed from *attrs*.
83
+
84
+ Each attribute string is stripped of whitespace on both ends.
85
+ """
86
+ attrs = attrs.strip()
87
+ attr_lst = attrs.split()
88
+ return sorted(attr_lst)
89
+
90
+ def _eq_elm_strs(self, line: str, line_2: str) -> bool:
91
+ """True if the element in `line_2` is XML-equivalent to the element in `line`.
92
+
93
+ In particular, the order of attributes in XML is not significant.
94
+ """
95
+ front, attrs, close, text = self._parse_line(line)
96
+ front_2, attrs_2, close_2, text_2 = self._parse_line(line_2)
97
+ if front != front_2:
98
+ return False
99
+ if self._attr_seq(attrs) != self._attr_seq(attrs_2):
100
+ return False
101
+ if close != close_2:
102
+ return False
103
+ if text != text_2:
104
+ return False
105
+ return True
106
+
107
+ def _parse_line(self, line: str):
108
+ """Return front, attrs, close, text 4-tuple result of parsing XML element string `line`."""
109
+ match = self._xml_elm_line_patt.match(line)
110
+ if match is None:
111
+ raise ValueError("`line` does not match pattern for an XML element")
112
+ front, attrs, close, text = [match.group(n) for n in range(1, 5)]
113
+ return front, attrs, close, text
114
+
115
+
116
+ class MetaOxmlElement(type):
117
+ """Metaclass for BaseOxmlElement."""
118
+
119
+ def __init__(cls, clsname: str, bases: tuple[type, ...], clsdict: dict[str, Any]):
120
+ dispatchable = (
121
+ OneAndOnlyOne,
122
+ OneOrMore,
123
+ OptionalAttribute,
124
+ RequiredAttribute,
125
+ ZeroOrMore,
126
+ ZeroOrOne,
127
+ ZeroOrOneChoice,
128
+ )
129
+ for key, value in clsdict.items():
130
+ if isinstance(value, dispatchable):
131
+ value.populate_class_members(cls, key)
132
+
133
+
134
+ class BaseAttribute:
135
+ """Base class for OptionalAttribute and RequiredAttribute, providing common methods."""
136
+
137
+ def __init__(self, attr_name: str, simple_type: type[AttributeType]):
138
+ self._attr_name = attr_name
139
+ self._simple_type = simple_type
140
+
141
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
142
+ """
143
+ Add the appropriate methods to *element_cls*.
144
+ """
145
+ self._element_cls = element_cls
146
+ self._prop_name = prop_name
147
+
148
+ self._add_attr_property()
149
+
150
+ def _add_attr_property(self):
151
+ """Add a read/write `{prop_name}` property to the element class.
152
+
153
+ The property returns the interpreted value of this attribute on access and changes the
154
+ attribute value to its ST_* counterpart on assignment.
155
+ """
156
+ property_ = property(self._getter, self._setter, None)
157
+ # assign unconditionally to overwrite element name definition
158
+ setattr(self._element_cls, self._prop_name, property_)
159
+
160
+ @property
161
+ def _clark_name(self):
162
+ if ":" in self._attr_name:
163
+ return qn(self._attr_name)
164
+ return self._attr_name
165
+
166
+ @property
167
+ def _getter(self) -> Callable[[BaseOxmlElement], Any]:
168
+ """Callable suitable for the "get" side of the attribute property descriptor."""
169
+ raise NotImplementedError("must be implemented by each subclass")
170
+
171
+ @property
172
+ def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
173
+ """Callable suitable for the "set" side of the attribute property descriptor."""
174
+ raise NotImplementedError("must be implemented by each subclass")
175
+
176
+
177
+ class OptionalAttribute(BaseAttribute):
178
+ """Defines an optional attribute on a custom element class.
179
+
180
+ An optional attribute returns a default value when not present for reading. When assigned
181
+ |None|, the attribute is removed.
182
+ """
183
+
184
+ def __init__(self, attr_name: str, simple_type: type[AttributeType], default: Any = None):
185
+ super(OptionalAttribute, self).__init__(attr_name, simple_type)
186
+ self._default = default
187
+
188
+ @property
189
+ def _docstring(self):
190
+ """
191
+ Return the string to use as the ``__doc__`` attribute of the property
192
+ for this attribute.
193
+ """
194
+ return (
195
+ "%s type-converted value of ``%s`` attribute, or |None| (or spec"
196
+ "ified default value) if not present. Assigning the default valu"
197
+ "e causes the attribute to be removed from the element."
198
+ % (self._simple_type.__name__, self._attr_name)
199
+ )
200
+
201
+ @property
202
+ def _getter(self) -> Callable[[BaseOxmlElement], Any]:
203
+ """Callable suitable for the "get" side of the attribute property descriptor."""
204
+
205
+ def get_attr_value(obj: BaseOxmlElement) -> Any:
206
+ attr_str_value = obj.get(self._clark_name)
207
+ if attr_str_value is None:
208
+ return self._default
209
+ return self._simple_type.from_xml(attr_str_value)
210
+
211
+ get_attr_value.__doc__ = self._docstring
212
+ return get_attr_value
213
+
214
+ @property
215
+ def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
216
+ """Callable suitable for the "set" side of the attribute property descriptor."""
217
+
218
+ def set_attr_value(obj: BaseOxmlElement, value: Any) -> None:
219
+ # -- when an XML attribute has a default value, setting it to that default removes the
220
+ # -- attribute from the element (when it is present)
221
+ if value == self._default:
222
+ if self._clark_name in obj.attrib:
223
+ del obj.attrib[self._clark_name]
224
+ return
225
+ str_value = self._simple_type.to_xml(value)
226
+ obj.set(self._clark_name, str_value)
227
+
228
+ return set_attr_value
229
+
230
+
231
+ class RequiredAttribute(BaseAttribute):
232
+ """Defines a required attribute on a custom element class.
233
+
234
+ A required attribute is assumed to be present for reading, so does not have a default value;
235
+ its actual value is always used. If missing on read, an |InvalidXmlError| is raised. It also
236
+ does not remove the attribute if |None| is assigned. Assigning |None| raises |TypeError| or
237
+ |ValueError|, depending on the simple type of the attribute.
238
+ """
239
+
240
+ @property
241
+ def _getter(self) -> Callable[[BaseOxmlElement], Any]:
242
+ """Callable suitable for the "get" side of the attribute property descriptor."""
243
+
244
+ def get_attr_value(obj: BaseOxmlElement) -> Any:
245
+ attr_str_value = obj.get(self._clark_name)
246
+ if attr_str_value is None:
247
+ raise InvalidXmlError(
248
+ "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag)
249
+ )
250
+ return self._simple_type.from_xml(attr_str_value)
251
+
252
+ get_attr_value.__doc__ = self._docstring
253
+ return get_attr_value
254
+
255
+ @property
256
+ def _docstring(self):
257
+ """
258
+ Return the string to use as the ``__doc__`` attribute of the property
259
+ for this attribute.
260
+ """
261
+ return "%s type-converted value of ``%s`` attribute." % (
262
+ self._simple_type.__name__,
263
+ self._attr_name,
264
+ )
265
+
266
+ @property
267
+ def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
268
+ """Callable suitable for the "set" side of the attribute property descriptor."""
269
+
270
+ def set_attr_value(obj: BaseOxmlElement, value: Any) -> None:
271
+ str_value = self._simple_type.to_xml(value)
272
+ obj.set(self._clark_name, str_value)
273
+
274
+ return set_attr_value
275
+
276
+
277
+ class _BaseChildElement:
278
+ """Base class for the child element classes corresponding to varying cardinalities.
279
+
280
+ Subclasses include ZeroOrOne and ZeroOrMore.
281
+ """
282
+
283
+ def __init__(self, nsptagname: str, successors: Sequence[str] = ()):
284
+ super(_BaseChildElement, self).__init__()
285
+ self._nsptagname = nsptagname
286
+ self._successors = successors
287
+
288
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
289
+ """Baseline behavior for adding the appropriate methods to `element_cls`."""
290
+ self._element_cls = element_cls
291
+ self._prop_name = prop_name
292
+
293
+ def _add_adder(self):
294
+ """Add an ``_add_x()`` method to the element class for this child element."""
295
+
296
+ def _add_child(obj: BaseOxmlElement, **attrs: Any):
297
+ new_method = getattr(obj, self._new_method_name)
298
+ child = new_method()
299
+ for key, value in attrs.items():
300
+ setattr(child, key, value)
301
+ insert_method = getattr(obj, self._insert_method_name)
302
+ insert_method(child)
303
+ return child
304
+
305
+ _add_child.__doc__ = (
306
+ "Add a new ``<%s>`` child element unconditionally, inserted in t"
307
+ "he correct sequence." % self._nsptagname
308
+ )
309
+ self._add_to_class(self._add_method_name, _add_child)
310
+
311
+ def _add_creator(self):
312
+ """Add a `_new_{prop_name}()` method to the element class.
313
+
314
+ This method creates a new, empty element of the correct type, having no attributes.
315
+ """
316
+ creator = self._creator
317
+ creator.__doc__ = (
318
+ 'Return a "loose", newly created ``<%s>`` element having no attri'
319
+ "butes, text, or children." % self._nsptagname
320
+ )
321
+ self._add_to_class(self._new_method_name, creator)
322
+
323
+ def _add_getter(self):
324
+ """Add a read-only `{prop_name}` property to the parent element class.
325
+
326
+ The property locates and returns this child element or `None` if not present.
327
+ """
328
+ property_ = property(self._getter, None, None)
329
+ # assign unconditionally to overwrite element name definition
330
+ setattr(self._element_cls, self._prop_name, property_)
331
+
332
+ def _add_inserter(self):
333
+ """Add an ``_insert_x()`` method to the element class for this child element."""
334
+
335
+ def _insert_child(obj: BaseOxmlElement, child: BaseOxmlElement):
336
+ obj.insert_element_before(child, *self._successors)
337
+ return child
338
+
339
+ _insert_child.__doc__ = (
340
+ "Return the passed ``<%s>`` element after inserting it as a chil"
341
+ "d in the correct sequence." % self._nsptagname
342
+ )
343
+ self._add_to_class(self._insert_method_name, _insert_child)
344
+
345
+ def _add_list_getter(self):
346
+ """
347
+ Add a read-only ``{prop_name}_lst`` property to the element class to
348
+ retrieve a list of child elements matching this type.
349
+ """
350
+ prop_name = f"{self._prop_name}_lst"
351
+ property_ = property(self._list_getter, None, None)
352
+ setattr(self._element_cls, prop_name, property_)
353
+
354
+ @lazyproperty
355
+ def _add_method_name(self):
356
+ return "_add_%s" % self._prop_name
357
+
358
+ def _add_to_class(self, name: str, method: Callable[..., Any]):
359
+ """Add `method` to the target class as `name`, unless `name` is already defined there."""
360
+ if hasattr(self._element_cls, name):
361
+ return
362
+ setattr(self._element_cls, name, method)
363
+
364
+ @property
365
+ def _creator(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]:
366
+ """Callable that creates a new, empty element of the child type, having no attributes."""
367
+
368
+ def new_child_element(obj: BaseOxmlElement):
369
+ return OxmlElement(self._nsptagname)
370
+
371
+ return new_child_element
372
+
373
+ @property
374
+ def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement | None]:
375
+ """Callable suitable for the "get" side of the property descriptor.
376
+
377
+ This default getter returns the child element with matching tag name or |None| if not
378
+ present.
379
+ """
380
+
381
+ def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement | None:
382
+ return obj.find(qn(self._nsptagname))
383
+
384
+ get_child_element.__doc__ = (
385
+ "``<%s>`` child element or |None| if not present." % self._nsptagname
386
+ )
387
+ return get_child_element
388
+
389
+ @lazyproperty
390
+ def _insert_method_name(self):
391
+ return "_insert_%s" % self._prop_name
392
+
393
+ @property
394
+ def _list_getter(self) -> Callable[[BaseOxmlElement], list[BaseOxmlElement]]:
395
+ """Callable suitable for the "get" side of a list property descriptor."""
396
+
397
+ def get_child_element_list(obj: BaseOxmlElement) -> list[BaseOxmlElement]:
398
+ return cast("list[BaseOxmlElement]", obj.findall(qn(self._nsptagname)))
399
+
400
+ get_child_element_list.__doc__ = (
401
+ "A list containing each of the ``<%s>`` child elements, in the o"
402
+ "rder they appear." % self._nsptagname
403
+ )
404
+ return get_child_element_list
405
+
406
+ @lazyproperty
407
+ def _remove_method_name(self):
408
+ return "_remove_%s" % self._prop_name
409
+
410
+ @lazyproperty
411
+ def _new_method_name(self):
412
+ return "_new_%s" % self._prop_name
413
+
414
+
415
+ class Choice(_BaseChildElement):
416
+ """Defines a child element belonging to a group, only one of which may appear as a child."""
417
+
418
+ @property
419
+ def nsptagname(self):
420
+ return self._nsptagname
421
+
422
+ def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride]
423
+ self, element_cls: Type[BaseOxmlElement], group_prop_name: str, successors: Sequence[str]
424
+ ):
425
+ """Add the appropriate methods to `element_cls`."""
426
+ self._element_cls = element_cls
427
+ self._group_prop_name = group_prop_name
428
+ self._successors = successors
429
+
430
+ self._add_getter()
431
+ self._add_creator()
432
+ self._add_inserter()
433
+ self._add_adder()
434
+ self._add_get_or_change_to_method()
435
+
436
+ def _add_get_or_change_to_method(self) -> None:
437
+ """Add a `get_or_change_to_x()` method to the element class for this child element."""
438
+
439
+ def get_or_change_to_child(obj: BaseOxmlElement):
440
+ child = getattr(obj, self._prop_name)
441
+ if child is not None:
442
+ return child
443
+ remove_group_method = getattr(obj, self._remove_group_method_name)
444
+ remove_group_method()
445
+ add_method = getattr(obj, self._add_method_name)
446
+ child = add_method()
447
+ return child
448
+
449
+ get_or_change_to_child.__doc__ = (
450
+ "Return the ``<%s>`` child, replacing any other group element if" " found."
451
+ ) % self._nsptagname
452
+ self._add_to_class(self._get_or_change_to_method_name, get_or_change_to_child)
453
+
454
+ @property
455
+ def _prop_name(self):
456
+ """
457
+ Calculate property name from tag name, e.g. a:schemeClr -> schemeClr.
458
+ """
459
+ if ":" in self._nsptagname:
460
+ start = self._nsptagname.index(":") + 1
461
+ else:
462
+ start = 0
463
+ return self._nsptagname[start:]
464
+
465
+ @lazyproperty
466
+ def _get_or_change_to_method_name(self):
467
+ return "get_or_change_to_%s" % self._prop_name
468
+
469
+ @lazyproperty
470
+ def _remove_group_method_name(self):
471
+ return "_remove_%s" % self._group_prop_name
472
+
473
+
474
+ class OneAndOnlyOne(_BaseChildElement):
475
+ """Defines a required child element for MetaOxmlElement."""
476
+
477
+ def __init__(self, nsptagname: str):
478
+ super(OneAndOnlyOne, self).__init__(nsptagname, ())
479
+
480
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
481
+ """
482
+ Add the appropriate methods to *element_cls*.
483
+ """
484
+ super(OneAndOnlyOne, self).populate_class_members(element_cls, prop_name)
485
+ self._add_getter()
486
+
487
+ @property
488
+ def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]:
489
+ """Callable suitable for the "get" side of the property descriptor."""
490
+
491
+ def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement:
492
+ child = obj.find(qn(self._nsptagname))
493
+ if child is None:
494
+ raise InvalidXmlError(
495
+ "required ``<%s>`` child element not present" % self._nsptagname
496
+ )
497
+ return child
498
+
499
+ get_child_element.__doc__ = "Required ``<%s>`` child element." % self._nsptagname
500
+ return get_child_element
501
+
502
+
503
+ class OneOrMore(_BaseChildElement):
504
+ """Defines a repeating child element for MetaOxmlElement that must appear at least once."""
505
+
506
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
507
+ """Add the appropriate methods to *element_cls*."""
508
+ super(OneOrMore, self).populate_class_members(element_cls, prop_name)
509
+ self._add_list_getter()
510
+ self._add_creator()
511
+ self._add_inserter()
512
+ self._add_adder()
513
+ self._add_public_adder()
514
+ delattr(element_cls, prop_name)
515
+
516
+ def _add_public_adder(self) -> None:
517
+ """Add a public `.add_x()` method to the parent element class."""
518
+
519
+ def add_child(obj: BaseOxmlElement) -> BaseOxmlElement:
520
+ private_add_method = getattr(obj, self._add_method_name)
521
+ child = private_add_method()
522
+ return child
523
+
524
+ add_child.__doc__ = (
525
+ "Add a new ``<%s>`` child element unconditionally, inserted in t"
526
+ "he correct sequence." % self._nsptagname
527
+ )
528
+ self._add_to_class(self._public_add_method_name, add_child)
529
+
530
+ @lazyproperty
531
+ def _public_add_method_name(self):
532
+ """
533
+ add_childElement() is public API for a repeating element, allowing
534
+ new elements to be added to the sequence. May be overridden to
535
+ provide a friendlier API to clients having domain appropriate
536
+ parameter names for required attributes.
537
+ """
538
+ return "add_%s" % self._prop_name
539
+
540
+
541
+ class ZeroOrMore(_BaseChildElement):
542
+ """
543
+ Defines an optional repeating child element for MetaOxmlElement.
544
+ """
545
+
546
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
547
+ """
548
+ Add the appropriate methods to *element_cls*.
549
+ """
550
+ super(ZeroOrMore, self).populate_class_members(element_cls, prop_name)
551
+ self._add_list_getter()
552
+ self._add_creator()
553
+ self._add_inserter()
554
+ self._add_adder()
555
+ delattr(element_cls, prop_name)
556
+
557
+
558
+ class ZeroOrOne(_BaseChildElement):
559
+ """Defines an optional child element for MetaOxmlElement."""
560
+
561
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
562
+ """Add the appropriate methods to `element_cls`."""
563
+ super(ZeroOrOne, self).populate_class_members(element_cls, prop_name)
564
+ self._add_getter()
565
+ self._add_creator()
566
+ self._add_inserter()
567
+ self._add_adder()
568
+ self._add_get_or_adder()
569
+ self._add_remover()
570
+
571
+ def _add_get_or_adder(self):
572
+ """Add a `.get_or_add_x()` method to the element class for this child element."""
573
+
574
+ def get_or_add_child(obj: BaseOxmlElement) -> BaseOxmlElement:
575
+ child = getattr(obj, self._prop_name)
576
+ if child is None:
577
+ add_method = getattr(obj, self._add_method_name)
578
+ child = add_method()
579
+ return child
580
+
581
+ get_or_add_child.__doc__ = (
582
+ "Return the ``<%s>`` child element, newly added if not present."
583
+ ) % self._nsptagname
584
+ self._add_to_class(self._get_or_add_method_name, get_or_add_child)
585
+
586
+ def _add_remover(self):
587
+ """Add a `._remove_x()` method to the element class for this child element."""
588
+
589
+ def _remove_child(obj: BaseOxmlElement) -> None:
590
+ obj.remove_all(self._nsptagname)
591
+
592
+ _remove_child.__doc__ = f"Remove all `{self._nsptagname}` child elements."
593
+ self._add_to_class(self._remove_method_name, _remove_child)
594
+
595
+ @lazyproperty
596
+ def _get_or_add_method_name(self):
597
+ return "get_or_add_%s" % self._prop_name
598
+
599
+
600
+ class ZeroOrOneChoice(_BaseChildElement):
601
+ """An `EG_*` element group where at most one of its members may appear as a child."""
602
+
603
+ def __init__(self, choices: Iterable[Choice], successors: Iterable[str] = ()):
604
+ self._choices = tuple(choices)
605
+ self._successors = tuple(successors)
606
+
607
+ def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
608
+ """Add the appropriate methods to `element_cls`."""
609
+ super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name)
610
+ self._add_choice_getter()
611
+ for choice in self._choices:
612
+ choice.populate_class_members(element_cls, self._prop_name, self._successors)
613
+ self._add_group_remover()
614
+
615
+ def _add_choice_getter(self):
616
+ """Add a read-only `.{prop_name}` property to the element class.
617
+
618
+ The property returns the present member of this group, or |None| if none are present.
619
+ """
620
+ property_ = property(self._choice_getter, None, None)
621
+ # assign unconditionally to overwrite element name definition
622
+ setattr(self._element_cls, self._prop_name, property_)
623
+
624
+ def _add_group_remover(self):
625
+ """Add a `._remove_eg_x()` method to the element class for this choice group."""
626
+
627
+ def _remove_choice_group(obj: BaseOxmlElement) -> None:
628
+ for tagname in self._member_nsptagnames:
629
+ obj.remove_all(tagname)
630
+
631
+ _remove_choice_group.__doc__ = "Remove the current choice group child element if present."
632
+ self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group)
633
+
634
+ @property
635
+ def _choice_getter(self):
636
+ """
637
+ Return a function object suitable for the "get" side of the property
638
+ descriptor.
639
+ """
640
+
641
+ def get_group_member_element(obj: BaseOxmlElement) -> BaseOxmlElement | None:
642
+ return cast(
643
+ "BaseOxmlElement | None", obj.first_child_found_in(*self._member_nsptagnames)
644
+ )
645
+
646
+ get_group_member_element.__doc__ = (
647
+ "Return the child element belonging to this element group, or "
648
+ "|None| if no member child is present."
649
+ )
650
+ return get_group_member_element
651
+
652
+ @lazyproperty
653
+ def _member_nsptagnames(self) -> list[str]:
654
+ """Sequence of namespace-prefixed tagnames, one for each member element of choice group."""
655
+ return [choice.nsptagname for choice in self._choices]
656
+
657
+ @lazyproperty
658
+ def _remove_choice_group_method_name(self):
659
+ """Function-name for choice remover."""
660
+ return f"_remove_{self._prop_name}"
661
+
662
+
663
+ # -- lxml typing isn't quite right here, just ignore this error on _Element --
664
+ class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement):
665
+ """Effective base class for all custom element classes.
666
+
667
+ Adds standardized behavior to all classes in one place.
668
+ """
669
+
670
+ def __repr__(self):
671
+ return "<%s '<%s>' at 0x%0x>" % (
672
+ self.__class__.__name__,
673
+ self._nsptag,
674
+ id(self),
675
+ )
676
+
677
+ def first_child_found_in(self, *tagnames: str) -> _Element | None:
678
+ """First child with tag in `tagnames`, or None if not found."""
679
+ for tagname in tagnames:
680
+ child = self.find(qn(tagname))
681
+ if child is not None:
682
+ return child
683
+ return None
684
+
685
+ def insert_element_before(self, elm: ElementBase, *tagnames: str):
686
+ successor = self.first_child_found_in(*tagnames)
687
+ if successor is not None:
688
+ successor.addprevious(elm)
689
+ else:
690
+ self.append(elm)
691
+ return elm
692
+
693
+ def remove_all(self, *tagnames: str) -> None:
694
+ """Remove child elements with tagname (e.g. "a:p") in `tagnames`."""
695
+ for tagname in tagnames:
696
+ matching = self.findall(qn(tagname))
697
+ for child in matching:
698
+ self.remove(child)
699
+
700
+ @property
701
+ def xml(self) -> str:
702
+ """XML string for this element, suitable for testing purposes.
703
+
704
+ Pretty printed for readability and without an XML declaration at the top.
705
+ """
706
+ return serialize_for_reading(self)
707
+
708
+ def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride]
709
+ """Override of `lxml` _Element.xpath() method.
710
+
711
+ Provides standard Open XML namespace mapping (`nsmap`) in centralized location.
712
+ """
713
+ return super().xpath(xpath_str, namespaces=_nsmap)
714
+
715
+ @property
716
+ def _nsptag(self) -> str:
717
+ return NamespacePrefixedTag.from_clark_name(self.tag)