wolfdocx 0.1.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.
- wolfdocx/__init__.py +25 -0
- wolfdocx/_cache_root.py +24 -0
- wolfdocx/_comment_threads.py +278 -0
- wolfdocx/_inspection_cache.py +374 -0
- wolfdocx/_version.py +3 -0
- wolfdocx/admission.py +163 -0
- wolfdocx/assembly.py +463 -0
- wolfdocx/authoring.py +2773 -0
- wolfdocx/canonical.py +267 -0
- wolfdocx/content.py +963 -0
- wolfdocx/document.py +215 -0
- wolfdocx/errors.py +169 -0
- wolfdocx/find_replace.py +1210 -0
- wolfdocx/formatting.py +3160 -0
- wolfdocx/inspect.py +3999 -0
- wolfdocx/model.py +1038 -0
- wolfdocx/numbering_authoring.py +1422 -0
- wolfdocx/output.py +13 -0
- wolfdocx/package.py +2313 -0
- wolfdocx/package_profile.py +128 -0
- wolfdocx/page_setup.py +2483 -0
- wolfdocx/paragraph_authoring.py +1842 -0
- wolfdocx/properties.py +2728 -0
- wolfdocx/protection.py +1909 -0
- wolfdocx/regions.py +1993 -0
- wolfdocx/render_warnings.py +106 -0
- wolfdocx/reporting.py +943 -0
- wolfdocx/review.py +2862 -0
- wolfdocx/run_text.py +117 -0
- wolfdocx/section_break.py +1810 -0
- wolfdocx/session_ops/__init__.py +45 -0
- wolfdocx/session_ops/_bridge.py +151 -0
- wolfdocx/session_ops/lists.py +104 -0
- wolfdocx/session_ops/paragraphs.py +39 -0
- wolfdocx/session_ops/rich_objects.py +2598 -0
- wolfdocx/session_ops/run_edits.py +70 -0
- wolfdocx/session_ops/runs.py +313 -0
- wolfdocx/session_ops/sections.py +109 -0
- wolfdocx/session_ops/styling.py +99 -0
- wolfdocx/session_ops/tables.py +247 -0
- wolfdocx/styles_authoring.py +2822 -0
- wolfdocx/table_cell_properties.py +1458 -0
- wolfdocx/table_column.py +1501 -0
- wolfdocx/table_delete.py +942 -0
- wolfdocx/table_insert.py +1114 -0
- wolfdocx/table_merge.py +1863 -0
- wolfdocx/table_properties.py +2429 -0
- wolfdocx/table_row_properties.py +1095 -0
- wolfdocx/table_structure.py +1044 -0
- wolfdocx/text_effects.py +1438 -0
- wolfdocx-0.1.0.dist-info/METADATA +127 -0
- wolfdocx-0.1.0.dist-info/RECORD +54 -0
- wolfdocx-0.1.0.dist-info/WHEEL +4 -0
- wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
wolfdocx/assembly.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
"""Package editing helpers shared by authoring and session edits.
|
|
2
|
+
|
|
3
|
+
Relationship naming and allocation, content-type overrides and main-document
|
|
4
|
+
relationships keep package edits consistent with the Open Packaging Conventions.
|
|
5
|
+
Identity remapping keeps bookmarks, content controls, paragraph IDs, drawing
|
|
6
|
+
nonvisual IDs, VML shape names and Word anchor IDs unique within a destination
|
|
7
|
+
part when content moves between parts or packages.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import posixpath
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from xml.etree import ElementTree as ET
|
|
16
|
+
|
|
17
|
+
from ._comment_threads import generate_collision_safe_para_id
|
|
18
|
+
from .inspect import (
|
|
19
|
+
SUPPORTED_WORD_NAMESPACES,
|
|
20
|
+
Q,
|
|
21
|
+
parse_xml_with_preserved_qnames,
|
|
22
|
+
serialize_xml_with_preserved_qnames,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
26
|
+
_PR = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
27
|
+
_CT = "http://schemas.openxmlformats.org/package/2006/content-types"
|
|
28
|
+
_DOCUMENT = "word/document.xml"
|
|
29
|
+
_PARA_ID = "{http://schemas.microsoft.com/office/word/2010/wordml}paraId"
|
|
30
|
+
_W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
|
|
31
|
+
_VML = "urn:schemas-microsoft-com:vml"
|
|
32
|
+
_VML_OFFICE = "urn:schemas-microsoft-com:office:office"
|
|
33
|
+
_VML_SPID = f"{{{_VML_OFFICE}}}spid"
|
|
34
|
+
_WP14 = "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
|
|
35
|
+
# Word anchor identities per part: anchor ids are unique across VML (w14) and DrawingML
|
|
36
|
+
# (wp14) anchors; DrawingML edit ids form a second domain.
|
|
37
|
+
_ANCHOR_ID_DOMAINS = {
|
|
38
|
+
f"{{{_W14}}}anchorId": "anchorId",
|
|
39
|
+
f"{{{_WP14}}}anchorId": "anchorId",
|
|
40
|
+
f"{{{_WP14}}}editId": "editId",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
# Drawing IDs are unsigned integers, distinct from relationship IDs, paragraph
|
|
44
|
+
# IDs, SmartArt modelId values and VML shape names. The outer Word drawing and
|
|
45
|
+
# the inner DrawingML objects have separate nonvisual identity domains.
|
|
46
|
+
_DRAWING_ID_DOMAINS = {
|
|
47
|
+
**{
|
|
48
|
+
f"{{{namespace}}}docPr": "docPr"
|
|
49
|
+
for namespace in (
|
|
50
|
+
"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
|
|
51
|
+
"http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing",
|
|
52
|
+
)
|
|
53
|
+
},
|
|
54
|
+
**{
|
|
55
|
+
f"{{{namespace}}}cNvPr": "cNvPr"
|
|
56
|
+
for namespace in (
|
|
57
|
+
"http://schemas.openxmlformats.org/drawingml/2006/picture",
|
|
58
|
+
"http://purl.oclc.org/ooxml/drawingml/picture",
|
|
59
|
+
"http://schemas.openxmlformats.org/drawingml/2006/chartDrawing",
|
|
60
|
+
"http://purl.oclc.org/ooxml/drawingml/chartDrawing",
|
|
61
|
+
"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
|
|
62
|
+
"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",
|
|
63
|
+
"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",
|
|
64
|
+
"http://schemas.microsoft.com/office/drawing/2008/diagram",
|
|
65
|
+
)
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
_DRAWING_CONNECTIONS = {
|
|
69
|
+
f"{{{namespace}}}{name}"
|
|
70
|
+
for namespace in (
|
|
71
|
+
"http://schemas.openxmlformats.org/drawingml/2006/main",
|
|
72
|
+
"http://purl.oclc.org/ooxml/drawingml/main",
|
|
73
|
+
)
|
|
74
|
+
for name in ("stCxn", "endCxn")
|
|
75
|
+
}
|
|
76
|
+
_WORD_DRAWINGS = {
|
|
77
|
+
f"{{{namespace}}}drawing"
|
|
78
|
+
for namespace in (_W, "http://purl.oclc.org/ooxml/wordprocessingml/main")
|
|
79
|
+
}
|
|
80
|
+
_MAX_DRAWING_ID = 0xFFFFFFFF
|
|
81
|
+
_MAX_SDT_ID = 2_147_483_647
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _q(ns: str, name: str) -> str:
|
|
85
|
+
return f"{{{ns}}}{name}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _word_ns(root: ET.Element) -> str | None:
|
|
89
|
+
return (
|
|
90
|
+
root.tag[1:].split("}", 1)[0]
|
|
91
|
+
if root.tag.startswith("{") and root.tag[1:].split("}", 1)[0] in SUPPORTED_WORD_NAMESPACES
|
|
92
|
+
else None
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _rels_name(part: str) -> str:
|
|
97
|
+
parent, name = posixpath.split(part)
|
|
98
|
+
return posixpath.join(parent, "_rels", name + ".rels")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _resolve(part: str, target: str) -> str:
|
|
102
|
+
if target.startswith("/"):
|
|
103
|
+
return posixpath.normpath(target.lstrip("/"))
|
|
104
|
+
return posixpath.normpath(posixpath.join(posixpath.dirname(part), target))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _relative(part: str, target: str) -> str:
|
|
108
|
+
return posixpath.relpath(target, posixpath.dirname(part))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _read_rels(parts: Mapping[str, bytes], owner: str) -> ET.Element:
|
|
112
|
+
name = _rels_name(owner)
|
|
113
|
+
return (
|
|
114
|
+
parse_xml_with_preserved_qnames(parts[name])
|
|
115
|
+
if name in parts
|
|
116
|
+
else ET.Element(_q(_PR, "Relationships"))
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _ids(root: ET.Element) -> set[str]:
|
|
121
|
+
return {node.get("Id") for node in root.findall(_q(_PR, "Relationship")) if node.get("Id")}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _new_rel_id(root: ET.Element) -> str:
|
|
125
|
+
used = _ids(root)
|
|
126
|
+
serial = 1
|
|
127
|
+
while f"rId{serial}" in used:
|
|
128
|
+
serial += 1
|
|
129
|
+
return f"rId{serial}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _ensure_override(destination: dict[str, bytes], part: str, content_type: str) -> None:
|
|
133
|
+
types = parse_xml_with_preserved_qnames(destination["[Content_Types].xml"])
|
|
134
|
+
if not any(
|
|
135
|
+
node.get("PartName") == "/" + part and node.get("ContentType") == content_type
|
|
136
|
+
for node in types.findall(_q(_CT, "Override"))
|
|
137
|
+
):
|
|
138
|
+
types.append(
|
|
139
|
+
ET.Element(
|
|
140
|
+
_q(_CT, "Override"),
|
|
141
|
+
{"PartName": "/" + part, "ContentType": content_type},
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
destination["[Content_Types].xml"] = serialize_xml_with_preserved_qnames(types)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _add_document_relationship(
|
|
148
|
+
destination: dict[str, bytes], relationship_type: str, target: str
|
|
149
|
+
) -> None:
|
|
150
|
+
rels_name = _rels_name(_DOCUMENT)
|
|
151
|
+
rels = _read_rels(destination, _DOCUMENT)
|
|
152
|
+
rels.append(
|
|
153
|
+
ET.Element(
|
|
154
|
+
_q(_PR, "Relationship"),
|
|
155
|
+
{
|
|
156
|
+
"Id": _new_rel_id(rels),
|
|
157
|
+
"Type": relationship_type,
|
|
158
|
+
"Target": _relative(_DOCUMENT, target),
|
|
159
|
+
},
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
destination[rels_name] = serialize_xml_with_preserved_qnames(rels)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _remap_bookmarks(
|
|
166
|
+
destination: Mapping[str, bytes], roots: list[ET.Element], ns: str
|
|
167
|
+
) -> dict[str, str]:
|
|
168
|
+
destination_roots: list[ET.Element] = []
|
|
169
|
+
for part, data in destination.items():
|
|
170
|
+
if not part.startswith("word/") or not part.endswith(".xml"):
|
|
171
|
+
continue
|
|
172
|
+
try:
|
|
173
|
+
root = ET.fromstring(data)
|
|
174
|
+
except ET.ParseError:
|
|
175
|
+
continue
|
|
176
|
+
if _word_ns(root) == ns:
|
|
177
|
+
destination_roots.append(root)
|
|
178
|
+
used_ids = {
|
|
179
|
+
int(node.get(Q(ns, "id")))
|
|
180
|
+
for root in destination_roots
|
|
181
|
+
for node in root.iter(Q(ns, "bookmarkStart"))
|
|
182
|
+
if (node.get(Q(ns, "id")) or "").isdigit()
|
|
183
|
+
}
|
|
184
|
+
used_names = {
|
|
185
|
+
node.get(Q(ns, "name"))
|
|
186
|
+
for root in destination_roots
|
|
187
|
+
for node in root.iter(Q(ns, "bookmarkStart"))
|
|
188
|
+
if node.get(Q(ns, "name"))
|
|
189
|
+
}
|
|
190
|
+
next_id = max(used_ids, default=0) + 1
|
|
191
|
+
names: dict[str, str] = {}
|
|
192
|
+
ids: dict[str, str] = {}
|
|
193
|
+
for root in roots:
|
|
194
|
+
for node in root.iter(Q(ns, "bookmarkStart")):
|
|
195
|
+
old_id, old_name = node.get(Q(ns, "id")), node.get(Q(ns, "name"))
|
|
196
|
+
if old_id is None or old_name is None or old_id in ids or old_name in names:
|
|
197
|
+
raise ValueError("assembly_bookmark_invalid")
|
|
198
|
+
new_id = str(next_id)
|
|
199
|
+
next_id += 1
|
|
200
|
+
base = old_name[:32] or "Bookmark"
|
|
201
|
+
new_name = base
|
|
202
|
+
serial = 2
|
|
203
|
+
while new_name in used_names:
|
|
204
|
+
new_name = f"{base}_{serial}"
|
|
205
|
+
serial += 1
|
|
206
|
+
used_names.add(new_name)
|
|
207
|
+
ids[old_id] = new_id
|
|
208
|
+
names[old_name] = new_name
|
|
209
|
+
node.set(Q(ns, "id"), new_id)
|
|
210
|
+
node.set(Q(ns, "name"), new_name)
|
|
211
|
+
for root in roots:
|
|
212
|
+
for node in root.iter(Q(ns, "bookmarkEnd")):
|
|
213
|
+
old = node.get(Q(ns, "id"))
|
|
214
|
+
if old not in ids:
|
|
215
|
+
raise ValueError("assembly_bookmark_end_invalid")
|
|
216
|
+
node.set(Q(ns, "id"), ids[old])
|
|
217
|
+
for node in root.iter(Q(ns, "hyperlink")):
|
|
218
|
+
anchor = node.get(Q(ns, "anchor"))
|
|
219
|
+
if anchor in names:
|
|
220
|
+
node.set(Q(ns, "anchor"), names[anchor])
|
|
221
|
+
return names
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _allocate_sdt_id(used_ids: set[int]) -> int | None:
|
|
225
|
+
"""Deterministically allocate the lowest unused positive integer SDT ID."""
|
|
226
|
+
candidate = 1
|
|
227
|
+
while candidate in used_ids:
|
|
228
|
+
candidate += 1
|
|
229
|
+
return candidate if candidate <= _MAX_SDT_ID else None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _remap_sdt_ids(roots: list[ET.Element], ns: str, occupied: set[int]) -> None:
|
|
233
|
+
for root in roots:
|
|
234
|
+
for control in root.iter(Q(ns, "sdt")):
|
|
235
|
+
identifiers = control.findall(f"{Q(ns, 'sdtPr')}/{Q(ns, 'id')}")
|
|
236
|
+
if len(identifiers) != 1:
|
|
237
|
+
raise ValueError("assembly_sdt_identity_unsupported")
|
|
238
|
+
node = identifiers[0]
|
|
239
|
+
value = node.get(Q(ns, "val"), "")
|
|
240
|
+
if not value.isdigit() or int(value) > _MAX_SDT_ID:
|
|
241
|
+
raise ValueError("assembly_sdt_identity_unsupported")
|
|
242
|
+
identifier = int(value)
|
|
243
|
+
if identifier in occupied:
|
|
244
|
+
identifier = _allocate_sdt_id(occupied)
|
|
245
|
+
if identifier is None:
|
|
246
|
+
raise ValueError("assembly_sdt_identity_exhausted")
|
|
247
|
+
node.set(Q(ns, "val"), str(identifier))
|
|
248
|
+
occupied.add(identifier)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _remap_paragraph_ids(roots: list[ET.Element], ns: str, occupied: set[str]) -> None:
|
|
252
|
+
"""Reserve identities within one destination part, changing only collisions."""
|
|
253
|
+
for root in roots:
|
|
254
|
+
for paragraph in root.iter(Q(ns, "p")):
|
|
255
|
+
identifier = paragraph.get(_PARA_ID)
|
|
256
|
+
if identifier is None:
|
|
257
|
+
continue
|
|
258
|
+
if identifier.upper() in occupied:
|
|
259
|
+
paragraph.set(_PARA_ID, generate_collision_safe_para_id(occupied, identifier))
|
|
260
|
+
else:
|
|
261
|
+
occupied.add(identifier.upper())
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _drawing_identifier(node: ET.Element) -> int | None:
|
|
265
|
+
value = node.get("id")
|
|
266
|
+
if value is None:
|
|
267
|
+
return None
|
|
268
|
+
if not re.fullmatch(r"\+?[0-9]+", value.strip()):
|
|
269
|
+
raise ValueError("assembly_drawing_identity_invalid")
|
|
270
|
+
identifier = int(value)
|
|
271
|
+
if identifier > _MAX_DRAWING_ID:
|
|
272
|
+
raise ValueError("assembly_drawing_identity_invalid")
|
|
273
|
+
return identifier
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _drawing_ids(root: ET.Element) -> dict[str, set[int]]:
|
|
277
|
+
occupied: dict[str, set[int]] = {"docPr": set(), "cNvPr": set()}
|
|
278
|
+
for node in root.iter():
|
|
279
|
+
domain = _DRAWING_ID_DOMAINS.get(node.tag)
|
|
280
|
+
if domain is not None and (identifier := _drawing_identifier(node)) is not None:
|
|
281
|
+
occupied[domain].add(identifier)
|
|
282
|
+
return occupied
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _remap_drawing_ids(roots: list[ET.Element], occupied: dict[str, set[int]]) -> None:
|
|
286
|
+
"""Allocate only imported collisions within one destination package part.
|
|
287
|
+
|
|
288
|
+
Reserve all incoming values before allocation so a collision cannot steal a
|
|
289
|
+
later noncolliding identity. Resolve connector endpoints in their original
|
|
290
|
+
drawing graph before changing anything; repeated imported canvases may have
|
|
291
|
+
identical source IDs without sharing their endpoint bindings.
|
|
292
|
+
|
|
293
|
+
Related parts copied alongside imported content retain their own identity
|
|
294
|
+
scope and bytes. Only content merged into existing parts needs rebasing.
|
|
295
|
+
"""
|
|
296
|
+
definitions: list[tuple[ET.Element, ET.Element, str, int]] = []
|
|
297
|
+
connections: list[tuple[ET.Element, ET.Element, int]] = []
|
|
298
|
+
local: dict[tuple[ET.Element, str, int], list[ET.Element]] = {}
|
|
299
|
+
imported: dict[tuple[str, int], list[ET.Element]] = {}
|
|
300
|
+
reserved = {domain: set(values) for domain, values in occupied.items()}
|
|
301
|
+
for root in roots:
|
|
302
|
+
pending = [(root, root)]
|
|
303
|
+
while pending:
|
|
304
|
+
node, scope = pending.pop()
|
|
305
|
+
if node.tag in _WORD_DRAWINGS:
|
|
306
|
+
scope = node
|
|
307
|
+
domain = _DRAWING_ID_DOMAINS.get(node.tag)
|
|
308
|
+
if domain is not None:
|
|
309
|
+
identifier = _drawing_identifier(node)
|
|
310
|
+
if identifier is not None:
|
|
311
|
+
definitions.append((node, scope, domain, identifier))
|
|
312
|
+
local.setdefault((scope, domain, identifier), []).append(node)
|
|
313
|
+
imported.setdefault((domain, identifier), []).append(node)
|
|
314
|
+
reserved[domain].add(identifier)
|
|
315
|
+
elif node.tag in _DRAWING_CONNECTIONS:
|
|
316
|
+
identifier = _drawing_identifier(node)
|
|
317
|
+
if identifier is not None:
|
|
318
|
+
connections.append((node, scope, identifier))
|
|
319
|
+
pending.extend((child, scope) for child in reversed(node))
|
|
320
|
+
|
|
321
|
+
bindings: list[tuple[ET.Element, ET.Element, int]] = []
|
|
322
|
+
for connection, scope, identifier in connections:
|
|
323
|
+
# Inner canvas objects take precedence over their outer Word wrapper.
|
|
324
|
+
targets = (
|
|
325
|
+
local.get((scope, "cNvPr", identifier))
|
|
326
|
+
or local.get((scope, "docPr", identifier))
|
|
327
|
+
or imported.get(("cNvPr", identifier))
|
|
328
|
+
or imported.get(("docPr", identifier))
|
|
329
|
+
)
|
|
330
|
+
if not targets:
|
|
331
|
+
raise ValueError("assembly_drawing_reference_missing")
|
|
332
|
+
if len(targets) != 1:
|
|
333
|
+
raise ValueError("assembly_drawing_reference_ambiguous")
|
|
334
|
+
bindings.append((connection, targets[0], identifier))
|
|
335
|
+
|
|
336
|
+
next_ids = {domain: 1 for domain in occupied}
|
|
337
|
+
for node, _, domain, identifier in definitions:
|
|
338
|
+
if identifier in occupied[domain]:
|
|
339
|
+
candidate = next_ids[domain]
|
|
340
|
+
while candidate in reserved[domain]:
|
|
341
|
+
candidate += 1
|
|
342
|
+
if candidate > _MAX_DRAWING_ID:
|
|
343
|
+
raise ValueError("assembly_drawing_identity_exhausted")
|
|
344
|
+
node.set("id", str(candidate))
|
|
345
|
+
reserved[domain].add(candidate)
|
|
346
|
+
next_ids[domain] = candidate + 1
|
|
347
|
+
occupied[domain].add(candidate)
|
|
348
|
+
else:
|
|
349
|
+
occupied[domain].add(identifier)
|
|
350
|
+
for connection, target, identifier in bindings:
|
|
351
|
+
if int(target.attrib["id"]) != identifier:
|
|
352
|
+
connection.set("id", target.attrib["id"])
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _vml_identity_attributes(node: ET.Element) -> tuple[str, ...]:
|
|
356
|
+
if not node.tag.startswith(f"{{{_VML}}}"):
|
|
357
|
+
return ()
|
|
358
|
+
return tuple(name for name in ("id", _VML_SPID) if node.get(name))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _vml_ids(root: ET.Element) -> set[str]:
|
|
362
|
+
return {node.attrib[name] for node in root.iter() for name in _vml_identity_attributes(node)}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _fresh_vml_id(value: str, reserved: set[str]) -> str:
|
|
366
|
+
serial_id = re.fullmatch(r"(_x0000_[si])([0-9]+)", value)
|
|
367
|
+
if serial_id is not None:
|
|
368
|
+
# Word derives shape numbers from these spellings; keep them numeric.
|
|
369
|
+
prefix, serial = serial_id.group(1), int(serial_id.group(2))
|
|
370
|
+
while f"{prefix}{serial}" in reserved:
|
|
371
|
+
serial += 1
|
|
372
|
+
return f"{prefix}{serial}"
|
|
373
|
+
serial = 2
|
|
374
|
+
while f"{value}_{serial}" in reserved:
|
|
375
|
+
serial += 1
|
|
376
|
+
return f"{value}_{serial}"
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _remap_vml_ids(roots: list[ET.Element], ns: str, occupied: set[str]) -> None:
|
|
380
|
+
"""Rename imported VML shape identities that collide within one destination part.
|
|
381
|
+
|
|
382
|
+
VML ``id`` and ``o:spid`` values share one lexical domain. A renamed value
|
|
383
|
+
changes at every imported definition and reference, so an id equal to its spid,
|
|
384
|
+
shapetype uses, connector rules and OLE or ActiveX shape links stay bound.
|
|
385
|
+
"""
|
|
386
|
+
incoming = {
|
|
387
|
+
node.attrib[name]
|
|
388
|
+
for root in roots
|
|
389
|
+
for node in root.iter()
|
|
390
|
+
for name in _vml_identity_attributes(node)
|
|
391
|
+
}
|
|
392
|
+
reserved = occupied | incoming
|
|
393
|
+
renamed: dict[str, str] = {}
|
|
394
|
+
for root in roots:
|
|
395
|
+
for node in root.iter():
|
|
396
|
+
for name in _vml_identity_attributes(node):
|
|
397
|
+
value = node.attrib[name]
|
|
398
|
+
if value in occupied and value not in renamed:
|
|
399
|
+
renamed[value] = _fresh_vml_id(value, reserved)
|
|
400
|
+
reserved.add(renamed[value])
|
|
401
|
+
occupied.update(incoming - renamed.keys(), renamed.values())
|
|
402
|
+
if not renamed:
|
|
403
|
+
return
|
|
404
|
+
for root in roots:
|
|
405
|
+
for node in root.iter():
|
|
406
|
+
for name in _vml_identity_attributes(node):
|
|
407
|
+
node.set(name, renamed.get(node.attrib[name], node.attrib[name]))
|
|
408
|
+
if node.tag.startswith(f"{{{_VML}}}"):
|
|
409
|
+
references = ("type",)
|
|
410
|
+
elif node.tag == _q(_VML_OFFICE, "OLEObject"):
|
|
411
|
+
references = ("ShapeID",)
|
|
412
|
+
elif node.tag.startswith(f"{{{_VML_OFFICE}}}"):
|
|
413
|
+
references = ("idref",)
|
|
414
|
+
elif node.tag == Q(ns, "control"):
|
|
415
|
+
references = (Q(ns, "shapeid"),)
|
|
416
|
+
elif node.tag.endswith("}compatExt") and "spid" in node.attrib:
|
|
417
|
+
references = ("spid",)
|
|
418
|
+
else:
|
|
419
|
+
continue
|
|
420
|
+
for name in references:
|
|
421
|
+
value = node.get(name)
|
|
422
|
+
if value is None:
|
|
423
|
+
continue
|
|
424
|
+
fragment = value.startswith("#")
|
|
425
|
+
if fragment != (name in {"type", "idref"}):
|
|
426
|
+
continue
|
|
427
|
+
target = renamed.get(value.removeprefix("#"))
|
|
428
|
+
if target is not None:
|
|
429
|
+
node.set(name, f"#{target}" if fragment else target)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _anchor_ids(root: ET.Element) -> dict[str, set[str]]:
|
|
433
|
+
"""Every Word anchor identity in one part, by domain (anchorId, editId)."""
|
|
434
|
+
occupied: dict[str, set[str]] = {"anchorId": set(), "editId": set()}
|
|
435
|
+
for node in root.iter():
|
|
436
|
+
for name, value in node.attrib.items():
|
|
437
|
+
if (domain := _ANCHOR_ID_DOMAINS.get(name)) is not None:
|
|
438
|
+
occupied[domain].add(value.upper())
|
|
439
|
+
return occupied
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _remap_anchor_ids(roots: list[ET.Element], occupied: dict[str, set[str]]) -> None:
|
|
443
|
+
"""Give imported anchors whose w14/wp14 anchorId or wp14 editId collides a fresh id.
|
|
444
|
+
|
|
445
|
+
Word keeps these ids unique within a part (VML and DrawingML anchors share one
|
|
446
|
+
anchorId domain), and no other markup refers to them, so only the colliding
|
|
447
|
+
attribute changes. Reserve every incoming id first so a reallocation cannot take
|
|
448
|
+
a later imported value.
|
|
449
|
+
"""
|
|
450
|
+
reserved = {domain: set(values) for domain, values in occupied.items()}
|
|
451
|
+
for root in roots:
|
|
452
|
+
for domain, values in _anchor_ids(root).items():
|
|
453
|
+
reserved[domain] |= values
|
|
454
|
+
for root in roots:
|
|
455
|
+
for node in root.iter():
|
|
456
|
+
for name, domain in _ANCHOR_ID_DOMAINS.items():
|
|
457
|
+
if (value := node.get(name)) is None:
|
|
458
|
+
continue
|
|
459
|
+
value = value.upper()
|
|
460
|
+
if value in occupied[domain]:
|
|
461
|
+
value = generate_collision_safe_para_id(reserved[domain], value)
|
|
462
|
+
node.set(name, value)
|
|
463
|
+
occupied[domain].add(value)
|