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/table_column.py
ADDED
|
@@ -0,0 +1,1501 @@
|
|
|
1
|
+
"""Source-bound table column authoring and discovery for WordprocessingML documents.
|
|
2
|
+
|
|
3
|
+
Supports inserting and deleting columns in admitted unmerged tables and resizing
|
|
4
|
+
grid columns without changing merged regions. Body, reachable header/footer,
|
|
5
|
+
nested and text-box tables share source binding and publication checks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import zipfile
|
|
14
|
+
from collections.abc import Mapping, Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
from xml.etree import ElementTree as ET
|
|
19
|
+
|
|
20
|
+
from .authoring import (
|
|
21
|
+
_MAX_TEXT_CHARACTERS,
|
|
22
|
+
_PUBLISHED,
|
|
23
|
+
_REFUSED,
|
|
24
|
+
_XML_SPACE_ATTRIBUTE,
|
|
25
|
+
_cell_structure_fingerprint,
|
|
26
|
+
_require_sha256,
|
|
27
|
+
_sha256_file,
|
|
28
|
+
_simple_text_node,
|
|
29
|
+
_unsupported_context_by_element,
|
|
30
|
+
_word_namespace,
|
|
31
|
+
)
|
|
32
|
+
from .inspect import (
|
|
33
|
+
Q,
|
|
34
|
+
inspect_docx,
|
|
35
|
+
parse_xml_with_preserved_qnames,
|
|
36
|
+
serialize_xml_with_preserved_qnames,
|
|
37
|
+
)
|
|
38
|
+
from .package import PackageError, PackageGraph
|
|
39
|
+
from .review import _DOCUMENT, ReviewReport, _publish
|
|
40
|
+
from .table_properties import _check_reachable_part
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"TableColumnReport",
|
|
44
|
+
"TableColumnRequest",
|
|
45
|
+
"TableColumnTarget",
|
|
46
|
+
"author_table_column",
|
|
47
|
+
"discover_table_column_targets",
|
|
48
|
+
"load_table_column_request",
|
|
49
|
+
"parse_table_column_request",
|
|
50
|
+
"table_column_structure_fingerprint",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
_REQUIRED_REQUEST_FIELDS = frozenset(
|
|
54
|
+
{"source", "destination", "source_sha256", "target", "structure_fingerprint_sha256"}
|
|
55
|
+
)
|
|
56
|
+
_ALLOWED_REQUEST_FIELDS = frozenset(
|
|
57
|
+
{
|
|
58
|
+
"source",
|
|
59
|
+
"destination",
|
|
60
|
+
"source_sha256",
|
|
61
|
+
"target",
|
|
62
|
+
"structure_fingerprint_sha256",
|
|
63
|
+
"position",
|
|
64
|
+
"width",
|
|
65
|
+
"column_width",
|
|
66
|
+
"cell_texts",
|
|
67
|
+
"action",
|
|
68
|
+
}
|
|
69
|
+
)
|
|
70
|
+
_ALLOWED_DELETE_REQUEST_FIELDS = frozenset(
|
|
71
|
+
{
|
|
72
|
+
"source",
|
|
73
|
+
"destination",
|
|
74
|
+
"source_sha256",
|
|
75
|
+
"target",
|
|
76
|
+
"structure_fingerprint_sha256",
|
|
77
|
+
"action",
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
_REQUIRED_TARGET_FIELDS = frozenset({"table", "column"})
|
|
81
|
+
_ALLOWED_TARGET_FIELDS = frozenset({"table", "column", "col", "part"})
|
|
82
|
+
|
|
83
|
+
_ALLOWED_RESIZE_REQUEST_FIELDS = frozenset(
|
|
84
|
+
{
|
|
85
|
+
"source",
|
|
86
|
+
"destination",
|
|
87
|
+
"source_sha256",
|
|
88
|
+
"target",
|
|
89
|
+
"structure_fingerprint_sha256",
|
|
90
|
+
"width",
|
|
91
|
+
"column_width",
|
|
92
|
+
"action",
|
|
93
|
+
}
|
|
94
|
+
)
|
|
95
|
+
_ACTIONS = ("insert", "delete", "resize")
|
|
96
|
+
# Word's maximum page width (22 inches); no single grid column can exceed it.
|
|
97
|
+
_MAX_COLUMN_WIDTH_TWIPS = 31680
|
|
98
|
+
|
|
99
|
+
_FORBIDDEN_COLUMN_ELEMENTS = frozenset(
|
|
100
|
+
{
|
|
101
|
+
"bookmarkStart",
|
|
102
|
+
"bookmarkEnd",
|
|
103
|
+
"commentRangeStart",
|
|
104
|
+
"commentRangeEnd",
|
|
105
|
+
"commentReference",
|
|
106
|
+
"customXml",
|
|
107
|
+
"del",
|
|
108
|
+
"delText",
|
|
109
|
+
"drawing",
|
|
110
|
+
"endnoteReference",
|
|
111
|
+
"fldChar",
|
|
112
|
+
"fldSimple",
|
|
113
|
+
"footnoteReference",
|
|
114
|
+
"hyperlink",
|
|
115
|
+
"ins",
|
|
116
|
+
"instrText",
|
|
117
|
+
"moveFrom",
|
|
118
|
+
"moveFromRangeEnd",
|
|
119
|
+
"moveFromRangeStart",
|
|
120
|
+
"moveTo",
|
|
121
|
+
"moveToRangeEnd",
|
|
122
|
+
"moveToRangeStart",
|
|
123
|
+
"pict",
|
|
124
|
+
"sdt",
|
|
125
|
+
"smartTag",
|
|
126
|
+
"subDoc",
|
|
127
|
+
"wgp",
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
_TCPR_ORDER: tuple[str, ...] = (
|
|
132
|
+
"cnfStyle",
|
|
133
|
+
"tcW",
|
|
134
|
+
"gridSpan",
|
|
135
|
+
"hMerge",
|
|
136
|
+
"vMerge",
|
|
137
|
+
"tcBorders",
|
|
138
|
+
"shd",
|
|
139
|
+
"noWrap",
|
|
140
|
+
"tcMar",
|
|
141
|
+
"textDirection",
|
|
142
|
+
"tcFitText",
|
|
143
|
+
"vAlign",
|
|
144
|
+
"hideMark",
|
|
145
|
+
"headers",
|
|
146
|
+
"cellIns",
|
|
147
|
+
"cellDel",
|
|
148
|
+
"cellMerge",
|
|
149
|
+
"tcPrChange",
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _unrelated_parts_preserved(source: Path, candidate: Path, changed: frozenset[str]) -> bool:
|
|
154
|
+
"""True when every part the request did not change is byte-for-byte identical to source."""
|
|
155
|
+
with (
|
|
156
|
+
zipfile.ZipFile(source) as before,
|
|
157
|
+
zipfile.ZipFile(candidate) as after,
|
|
158
|
+
):
|
|
159
|
+
names = set(after.namelist())
|
|
160
|
+
return all(
|
|
161
|
+
info.filename in names and before.read(info.filename) == after.read(info.filename)
|
|
162
|
+
for info in before.infolist()
|
|
163
|
+
if info.filename not in changed
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _has_forbidden_descendant(element: ET.Element) -> bool:
|
|
168
|
+
"""True if element or any descendant has forbidden elements or IDs."""
|
|
169
|
+
for child in element.iter():
|
|
170
|
+
local = child.tag.rsplit("}", 1)[-1]
|
|
171
|
+
if local in _FORBIDDEN_COLUMN_ELEMENTS:
|
|
172
|
+
return True
|
|
173
|
+
for attr in child.attrib:
|
|
174
|
+
attr_local = attr.rsplit("}", 1)[-1]
|
|
175
|
+
if attr_local in ("id", "embed", "href"):
|
|
176
|
+
return True
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _has_illegal_xml_chars(text: str) -> bool:
|
|
181
|
+
"""True if text contains characters prohibited in XML 1.0."""
|
|
182
|
+
for ch in text:
|
|
183
|
+
cp = ord(ch)
|
|
184
|
+
if cp < 0x20:
|
|
185
|
+
if ch not in ("\t", "\n", "\r"):
|
|
186
|
+
return True
|
|
187
|
+
elif 0xD800 <= cp <= 0xDFFF or cp in (0xFFFE, 0xFFFF):
|
|
188
|
+
return True
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _is_approved_row(row: ET.Element, namespace: str, *, allow_merged: bool = False) -> bool:
|
|
193
|
+
"""True if row conforms to approved rectangular row conventions."""
|
|
194
|
+
def word(local):
|
|
195
|
+
return Q(namespace, local)
|
|
196
|
+
if any(child.tag not in {word("trPr"), word("tc")} for child in row):
|
|
197
|
+
return False
|
|
198
|
+
tr_pr = row.find(word("trPr"))
|
|
199
|
+
if tr_pr is not None and (
|
|
200
|
+
tr_pr.find(word("gridBefore")) is not None or tr_pr.find(word("gridAfter")) is not None
|
|
201
|
+
):
|
|
202
|
+
return False
|
|
203
|
+
cells = row.findall(word("tc"))
|
|
204
|
+
if not cells:
|
|
205
|
+
return False
|
|
206
|
+
for cell in cells:
|
|
207
|
+
if _has_forbidden_descendant(cell):
|
|
208
|
+
return False
|
|
209
|
+
properties = cell.find(word("tcPr"))
|
|
210
|
+
merged = properties is not None and any(
|
|
211
|
+
properties.find(word(name)) is not None for name in ("vMerge", "hMerge", "gridSpan")
|
|
212
|
+
)
|
|
213
|
+
if _simple_text_node(cell, namespace) is None and not (allow_merged and merged):
|
|
214
|
+
return False
|
|
215
|
+
if (
|
|
216
|
+
not allow_merged
|
|
217
|
+
and properties is not None
|
|
218
|
+
and any(
|
|
219
|
+
properties.find(word(name)) is not None for name in ("vMerge", "hMerge", "gridSpan")
|
|
220
|
+
)
|
|
221
|
+
):
|
|
222
|
+
return False
|
|
223
|
+
if cell.find(f".//{word('tbl')}") is not None:
|
|
224
|
+
return False
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _is_supported_table(table: ET.Element, namespace: str) -> bool:
|
|
229
|
+
"""True if table has supported body table structure."""
|
|
230
|
+
def word(local):
|
|
231
|
+
return Q(namespace, local)
|
|
232
|
+
if any(child.tag not in {word("tblPr"), word("tblGrid"), word("tr")} for child in table):
|
|
233
|
+
return False
|
|
234
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
235
|
+
if tbl_grid is None:
|
|
236
|
+
return False
|
|
237
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
238
|
+
if not grid_cols:
|
|
239
|
+
return False
|
|
240
|
+
rows = table.findall(word("tr"))
|
|
241
|
+
return bool(rows)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _grid_row_cells(row: ET.Element, namespace: str) -> list[tuple[ET.Element, int, int]]:
|
|
245
|
+
"""Physical cells and their inclusive, one-based grid intervals."""
|
|
246
|
+
def word(local):
|
|
247
|
+
return Q(namespace, local)
|
|
248
|
+
result = []
|
|
249
|
+
start = 1
|
|
250
|
+
for cell in row.findall(word("tc")):
|
|
251
|
+
span = cell.find(f"{word('tcPr')}/{word('gridSpan')}")
|
|
252
|
+
width = 1 if span is None else int(span.get(word("val"), "0"))
|
|
253
|
+
result.append((cell, start, start + width - 1))
|
|
254
|
+
start += width
|
|
255
|
+
return result
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _table_hazard_reason(
|
|
259
|
+
table: ET.Element, namespace: str, *, allow_merged: bool = False
|
|
260
|
+
) -> str | None:
|
|
261
|
+
"""Admit a complete rectangular grid, retaining merge markup during resize."""
|
|
262
|
+
def word(local):
|
|
263
|
+
return Q(namespace, local)
|
|
264
|
+
if any(child.tag not in {word("tblPr"), word("tblGrid"), word("tr")} for child in table):
|
|
265
|
+
return "table_column_table_unsupported"
|
|
266
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
267
|
+
if tbl_grid is None:
|
|
268
|
+
return "table_column_table_unsupported"
|
|
269
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
270
|
+
if not grid_cols:
|
|
271
|
+
return "table_column_table_unsupported"
|
|
272
|
+
rows = table.findall(word("tr"))
|
|
273
|
+
if not rows:
|
|
274
|
+
return "table_column_table_unsupported"
|
|
275
|
+
|
|
276
|
+
num_cols = len(grid_cols)
|
|
277
|
+
previous_vertical: set[tuple[int, int]] = set()
|
|
278
|
+
for row in rows:
|
|
279
|
+
tr_pr = row.find(word("trPr"))
|
|
280
|
+
if tr_pr is not None and (
|
|
281
|
+
tr_pr.find(word("gridBefore")) is not None or tr_pr.find(word("gridAfter")) is not None
|
|
282
|
+
):
|
|
283
|
+
return "table_column_grid_before_after_unsupported"
|
|
284
|
+
cells = row.findall(word("tc"))
|
|
285
|
+
if not allow_merged and len(cells) != num_cols:
|
|
286
|
+
return "table_column_grid_mismatch"
|
|
287
|
+
horizontal = False
|
|
288
|
+
vertical: set[tuple[int, int]] = set()
|
|
289
|
+
end = 0
|
|
290
|
+
for cell in cells:
|
|
291
|
+
if cell.find(f".//{word('tbl')}") is not None:
|
|
292
|
+
return "table_column_structure_unsupported"
|
|
293
|
+
if _has_forbidden_descendant(cell):
|
|
294
|
+
return "table_column_context_unsupported"
|
|
295
|
+
properties = cell.find(word("tcPr"))
|
|
296
|
+
span = 1
|
|
297
|
+
modes = {}
|
|
298
|
+
if properties is not None:
|
|
299
|
+
for name in ("gridSpan", "hMerge", "vMerge"):
|
|
300
|
+
nodes = properties.findall(word(name))
|
|
301
|
+
if nodes and not allow_merged:
|
|
302
|
+
return "table_column_merged_unsupported"
|
|
303
|
+
if len(nodes) > 1:
|
|
304
|
+
return "table_column_merge_markup_invalid"
|
|
305
|
+
if not nodes:
|
|
306
|
+
continue
|
|
307
|
+
value = nodes[0].get(word("val"))
|
|
308
|
+
if name == "gridSpan":
|
|
309
|
+
try:
|
|
310
|
+
span = int(value or "0")
|
|
311
|
+
except ValueError:
|
|
312
|
+
return "table_column_merge_markup_invalid"
|
|
313
|
+
if span < 1:
|
|
314
|
+
return "table_column_merge_markup_invalid"
|
|
315
|
+
else:
|
|
316
|
+
if value not in (None, "restart", "continue"):
|
|
317
|
+
return "table_column_merge_markup_invalid"
|
|
318
|
+
modes[name] = value or "continue"
|
|
319
|
+
interval = (end + 1, end + span)
|
|
320
|
+
end += span
|
|
321
|
+
h_mode = modes.get("hMerge")
|
|
322
|
+
if h_mode == "continue" and not horizontal:
|
|
323
|
+
return "table_column_merge_markup_invalid"
|
|
324
|
+
horizontal = h_mode is not None
|
|
325
|
+
v_mode = modes.get("vMerge")
|
|
326
|
+
if v_mode == "continue" and interval not in previous_vertical:
|
|
327
|
+
return "table_column_merge_markup_invalid"
|
|
328
|
+
if v_mode is not None:
|
|
329
|
+
vertical.add(interval)
|
|
330
|
+
if _simple_text_node(cell, namespace) is None and not (
|
|
331
|
+
allow_merged
|
|
332
|
+
and properties is not None
|
|
333
|
+
and any(
|
|
334
|
+
properties.find(word(name)) is not None
|
|
335
|
+
for name in ("gridSpan", "hMerge", "vMerge")
|
|
336
|
+
)
|
|
337
|
+
):
|
|
338
|
+
return "table_column_structure_unsupported"
|
|
339
|
+
if not cells or end != num_cols:
|
|
340
|
+
return "table_column_grid_mismatch"
|
|
341
|
+
previous_vertical = vertical
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _insert_tcpr_child_in_order(tc_pr: ET.Element, child: ET.Element, namespace: str) -> None:
|
|
346
|
+
"""Insert or replace a child element in tcPr while strictly maintaining schema order."""
|
|
347
|
+
child_name = child.tag.rsplit("}", 1)[-1]
|
|
348
|
+
if child_name not in _TCPR_ORDER:
|
|
349
|
+
tc_pr.append(child)
|
|
350
|
+
return
|
|
351
|
+
target_rank = _TCPR_ORDER.index(child_name)
|
|
352
|
+
existing = tc_pr.find(Q(namespace, child_name))
|
|
353
|
+
if existing is not None:
|
|
354
|
+
idx = list(tc_pr).index(existing)
|
|
355
|
+
tc_pr.remove(existing)
|
|
356
|
+
tc_pr.insert(idx, child)
|
|
357
|
+
return
|
|
358
|
+
insert_at = len(tc_pr)
|
|
359
|
+
for idx, c in enumerate(tc_pr):
|
|
360
|
+
c_name = c.tag.rsplit("}", 1)[-1]
|
|
361
|
+
c_rank = _TCPR_ORDER.index(c_name) if c_name in _TCPR_ORDER else 999
|
|
362
|
+
if c_rank > target_rank:
|
|
363
|
+
insert_at = idx
|
|
364
|
+
break
|
|
365
|
+
tc_pr.insert(insert_at, child)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _is_valid_column_width(width: object) -> bool:
|
|
369
|
+
"""True when width is a positive integer twips value no wider than a Word page."""
|
|
370
|
+
return (
|
|
371
|
+
isinstance(width, int)
|
|
372
|
+
and not isinstance(width, bool)
|
|
373
|
+
and 0 < width <= _MAX_COLUMN_WIDTH_TWIPS
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _cell_content_signature(
|
|
378
|
+
cell: ET.Element, namespace: str
|
|
379
|
+
) -> tuple[tuple[bytes, ...], tuple[bytes, ...]]:
|
|
380
|
+
"""Serialize a cell's content and its tcPr children except tcW, in document order."""
|
|
381
|
+
tc_pr_tag = Q(namespace, "tcPr")
|
|
382
|
+
tc_w_tag = Q(namespace, "tcW")
|
|
383
|
+
content = tuple(ET.tostring(child) for child in cell if child.tag != tc_pr_tag)
|
|
384
|
+
tc_pr = cell.find(tc_pr_tag)
|
|
385
|
+
properties = () if tc_pr is None else tuple(ET.tostring(c) for c in tc_pr if c.tag != tc_w_tag)
|
|
386
|
+
return content, properties
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _get_element_width(elem: ET.Element, namespace: str) -> int | None:
|
|
390
|
+
"""Read w:w integer attribute from gridCol, tcW, or tblW element."""
|
|
391
|
+
w_attr = elem.get(Q(namespace, "w")) or elem.get("w")
|
|
392
|
+
if w_attr is not None and w_attr.isdigit():
|
|
393
|
+
return int(w_attr)
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _column_structure_fingerprint(
|
|
398
|
+
table: ET.Element, column: int, namespace: str, *, part: str = _DOCUMENT
|
|
399
|
+
) -> str:
|
|
400
|
+
"""Hash the selected column's XML structure across tblGrid and every row, masking cell text."""
|
|
401
|
+
def word(local):
|
|
402
|
+
return Q(namespace, local)
|
|
403
|
+
col_idx = column - 1
|
|
404
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
405
|
+
assert tbl_grid is not None
|
|
406
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
407
|
+
grid_col = grid_cols[col_idx]
|
|
408
|
+
rows = table.findall(word("tr"))
|
|
409
|
+
wrapper = ET.Element(word("columnPrototype"))
|
|
410
|
+
if part != _DOCUMENT:
|
|
411
|
+
wrapper.set("part", part)
|
|
412
|
+
wrapper.append(copy.deepcopy(grid_col))
|
|
413
|
+
for row in rows:
|
|
414
|
+
for cell, start, end in _grid_row_cells(row, namespace):
|
|
415
|
+
if start <= column <= end:
|
|
416
|
+
wrapper.append(copy.deepcopy(cell))
|
|
417
|
+
break
|
|
418
|
+
return _cell_structure_fingerprint(wrapper)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def table_column_structure_fingerprint(
|
|
422
|
+
source: str | Path,
|
|
423
|
+
*,
|
|
424
|
+
table: int,
|
|
425
|
+
column: int,
|
|
426
|
+
part: str = _DOCUMENT,
|
|
427
|
+
) -> str | None:
|
|
428
|
+
"""Return the source-bound structural fingerprint for one target table column."""
|
|
429
|
+
# Reachability is checked against the package rather than the part's filename alone.
|
|
430
|
+
path = Path(source)
|
|
431
|
+
if not path.is_file():
|
|
432
|
+
return None
|
|
433
|
+
try:
|
|
434
|
+
graph = PackageGraph.from_file(path)
|
|
435
|
+
valid, _ = _check_reachable_part(graph, part, "table_column")
|
|
436
|
+
if not valid:
|
|
437
|
+
return None
|
|
438
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
439
|
+
ns = _word_namespace(root)
|
|
440
|
+
if ns is None:
|
|
441
|
+
return None
|
|
442
|
+
def word(local):
|
|
443
|
+
return Q(ns, local)
|
|
444
|
+
tables = list(root.iter(word("tbl")))
|
|
445
|
+
if table < 1 or table > len(tables):
|
|
446
|
+
return None
|
|
447
|
+
target_table = tables[table - 1]
|
|
448
|
+
if _table_hazard_reason(target_table, ns, allow_merged=True) is not None:
|
|
449
|
+
return None
|
|
450
|
+
tbl_grid = target_table.find(word("tblGrid"))
|
|
451
|
+
if tbl_grid is None:
|
|
452
|
+
return None
|
|
453
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
454
|
+
if column < 1 or column > len(grid_cols):
|
|
455
|
+
return None
|
|
456
|
+
return _column_structure_fingerprint(target_table, column, ns, part=part)
|
|
457
|
+
except (PackageError, OSError, ET.ParseError, KeyError, IndexError):
|
|
458
|
+
return None
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@dataclass(frozen=True)
|
|
462
|
+
class TableColumnTarget:
|
|
463
|
+
"""One discovered candidate table column that can serve as an authoring prototype or deletion target."""
|
|
464
|
+
|
|
465
|
+
table: int
|
|
466
|
+
column: int
|
|
467
|
+
rows_count: int
|
|
468
|
+
structure_fingerprint_sha256: str
|
|
469
|
+
cell_texts: tuple[str, ...]
|
|
470
|
+
width: int | None
|
|
471
|
+
part: str = _DOCUMENT
|
|
472
|
+
actions: tuple[str, ...] = ("insert", "delete")
|
|
473
|
+
|
|
474
|
+
@property
|
|
475
|
+
def target(self) -> dict[str, Any]:
|
|
476
|
+
return {
|
|
477
|
+
"part": self.part,
|
|
478
|
+
"table": self.table,
|
|
479
|
+
"column": self.column,
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
def to_dict(self) -> dict[str, Any]:
|
|
483
|
+
return {
|
|
484
|
+
"part": self.part,
|
|
485
|
+
"table": self.table,
|
|
486
|
+
"column": self.column,
|
|
487
|
+
"rows_count": self.rows_count,
|
|
488
|
+
"cell_texts": list(self.cell_texts),
|
|
489
|
+
"width": self.width,
|
|
490
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
491
|
+
"target": self.target,
|
|
492
|
+
"actions": list(self.actions),
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
@dataclass(frozen=True)
|
|
497
|
+
class TableColumnRequest:
|
|
498
|
+
"""One source-bound request to insert, delete, or resize a table column.
|
|
499
|
+
|
|
500
|
+
``width`` is in twips (dxa). For ``action="resize"`` it is the new width of
|
|
501
|
+
the target column; its range is checked by ``author_table_column``, which
|
|
502
|
+
returns a content-safe ``table_column_width_invalid`` refusal.
|
|
503
|
+
"""
|
|
504
|
+
|
|
505
|
+
source: Path
|
|
506
|
+
destination: Path
|
|
507
|
+
source_sha256: str
|
|
508
|
+
target: Mapping[str, Any]
|
|
509
|
+
structure_fingerprint_sha256: str
|
|
510
|
+
position: str | None = None
|
|
511
|
+
width: int | None = None
|
|
512
|
+
cell_texts: tuple[str, ...] | None = None
|
|
513
|
+
action: str = "insert"
|
|
514
|
+
|
|
515
|
+
def __post_init__(self) -> None:
|
|
516
|
+
if not isinstance(self.action, str) or self.action not in _ACTIONS:
|
|
517
|
+
raise ValueError("table_column_action_invalid")
|
|
518
|
+
if self.action == "resize":
|
|
519
|
+
if self.position is not None or self.cell_texts is not None:
|
|
520
|
+
raise ValueError("table_column_request_fields_invalid")
|
|
521
|
+
if self.width is None:
|
|
522
|
+
raise ValueError("table_column_request_fields_invalid")
|
|
523
|
+
elif self.action == "delete":
|
|
524
|
+
if self.position is not None:
|
|
525
|
+
raise ValueError("table_column_request_fields_invalid")
|
|
526
|
+
if self.cell_texts is not None:
|
|
527
|
+
raise ValueError("table_column_request_fields_invalid")
|
|
528
|
+
if self.width is not None:
|
|
529
|
+
raise ValueError("table_column_request_fields_invalid")
|
|
530
|
+
else:
|
|
531
|
+
if self.position is None:
|
|
532
|
+
object.__setattr__(self, "position", "after")
|
|
533
|
+
elif not isinstance(self.position, str) or self.position not in (
|
|
534
|
+
"before",
|
|
535
|
+
"after",
|
|
536
|
+
):
|
|
537
|
+
raise ValueError("table_column_position_invalid")
|
|
538
|
+
if self.width is not None and (
|
|
539
|
+
not isinstance(self.width, int) or isinstance(self.width, bool) or self.width <= 0
|
|
540
|
+
):
|
|
541
|
+
raise ValueError("table_column_width_invalid")
|
|
542
|
+
if self.cell_texts is not None:
|
|
543
|
+
if not isinstance(self.cell_texts, tuple):
|
|
544
|
+
try:
|
|
545
|
+
object.__setattr__(self, "cell_texts", tuple(self.cell_texts))
|
|
546
|
+
except TypeError:
|
|
547
|
+
raise TypeError("table_column_cell_texts_invalid")
|
|
548
|
+
for text in self.cell_texts:
|
|
549
|
+
if not isinstance(text, str):
|
|
550
|
+
raise TypeError("table_column_cell_text_invalid")
|
|
551
|
+
if len(text) > _MAX_TEXT_CHARACTERS:
|
|
552
|
+
raise ValueError("table_column_cell_text_limit_exceeded")
|
|
553
|
+
if _has_illegal_xml_chars(text):
|
|
554
|
+
raise ValueError("table_column_cell_text_invalid")
|
|
555
|
+
|
|
556
|
+
@property
|
|
557
|
+
def table(self) -> int:
|
|
558
|
+
return self.target["table"]
|
|
559
|
+
|
|
560
|
+
@property
|
|
561
|
+
def column(self) -> int:
|
|
562
|
+
val = self.target.get("column")
|
|
563
|
+
if val is None:
|
|
564
|
+
val = self.target.get("col")
|
|
565
|
+
return val
|
|
566
|
+
|
|
567
|
+
@property
|
|
568
|
+
def col(self) -> int:
|
|
569
|
+
return self.column
|
|
570
|
+
|
|
571
|
+
@property
|
|
572
|
+
def part(self) -> str:
|
|
573
|
+
return self.target.get("part", _DOCUMENT)
|
|
574
|
+
|
|
575
|
+
def target_dict(self) -> dict[str, Any]:
|
|
576
|
+
data: dict[str, Any] = {
|
|
577
|
+
"part": self.part,
|
|
578
|
+
"table": self.table,
|
|
579
|
+
"column": self.column,
|
|
580
|
+
}
|
|
581
|
+
if self.action == "insert" and self.position is not None:
|
|
582
|
+
data["position"] = self.position
|
|
583
|
+
return data
|
|
584
|
+
|
|
585
|
+
def to_dict(self) -> dict[str, Any]:
|
|
586
|
+
data: dict[str, Any] = {
|
|
587
|
+
"source": str(self.source),
|
|
588
|
+
"destination": str(self.destination),
|
|
589
|
+
"source_sha256": self.source_sha256,
|
|
590
|
+
"target": {
|
|
591
|
+
"part": self.part,
|
|
592
|
+
"table": self.table,
|
|
593
|
+
"column": self.column,
|
|
594
|
+
},
|
|
595
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
596
|
+
}
|
|
597
|
+
if self.action == "delete":
|
|
598
|
+
data["action"] = "delete"
|
|
599
|
+
return data
|
|
600
|
+
if self.action == "resize":
|
|
601
|
+
data["action"] = "resize"
|
|
602
|
+
data["width"] = self.width
|
|
603
|
+
return data
|
|
604
|
+
data["position"] = self.position
|
|
605
|
+
if self.width is not None:
|
|
606
|
+
data["width"] = self.width
|
|
607
|
+
if self.cell_texts is not None:
|
|
608
|
+
data["cell_texts"] = list(self.cell_texts)
|
|
609
|
+
return data
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
@dataclass(frozen=True)
|
|
613
|
+
class TableColumnReport:
|
|
614
|
+
"""Content-safe public result for a table column authoring request."""
|
|
615
|
+
|
|
616
|
+
status: str
|
|
617
|
+
code: str | None
|
|
618
|
+
source_sha256: str
|
|
619
|
+
destination_sha256: str | None = None
|
|
620
|
+
target: dict[str, Any] | None = None
|
|
621
|
+
target_change_report: dict[str, Any] | None = None
|
|
622
|
+
non_target_parts_preserved: bool | None = None
|
|
623
|
+
|
|
624
|
+
@property
|
|
625
|
+
def passed(self) -> bool:
|
|
626
|
+
return self.status == _PUBLISHED
|
|
627
|
+
|
|
628
|
+
def to_dict(self) -> dict[str, Any]:
|
|
629
|
+
return {
|
|
630
|
+
"schema_version": 1,
|
|
631
|
+
"operation": "table-column",
|
|
632
|
+
"passed": self.passed,
|
|
633
|
+
"status": self.status,
|
|
634
|
+
"code": self.code,
|
|
635
|
+
"source_sha256": self.source_sha256,
|
|
636
|
+
"destination_sha256": self.destination_sha256,
|
|
637
|
+
"target": self.target,
|
|
638
|
+
"target_change_report": self.target_change_report,
|
|
639
|
+
"non_target_parts_preserved": self.non_target_parts_preserved,
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _table_column_refusal(
|
|
644
|
+
request: TableColumnRequest,
|
|
645
|
+
code: str,
|
|
646
|
+
target: dict[str, Any] | None = None,
|
|
647
|
+
) -> TableColumnReport:
|
|
648
|
+
return TableColumnReport(
|
|
649
|
+
status=_REFUSED,
|
|
650
|
+
code=code,
|
|
651
|
+
source_sha256=request.source_sha256,
|
|
652
|
+
destination_sha256=None,
|
|
653
|
+
target=target if target is not None else request.target_dict(),
|
|
654
|
+
target_change_report=None,
|
|
655
|
+
non_target_parts_preserved=None,
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def parse_table_column_request(value: Any) -> TableColumnRequest:
|
|
660
|
+
"""Parse and strictly validate a table column authoring request."""
|
|
661
|
+
if not isinstance(value, Mapping):
|
|
662
|
+
raise TypeError("table_column_request_invalid")
|
|
663
|
+
keys = set(value.keys())
|
|
664
|
+
action = value.get("action", "insert")
|
|
665
|
+
if not isinstance(action, str) or action not in _ACTIONS:
|
|
666
|
+
raise ValueError("table_column_action_invalid")
|
|
667
|
+
|
|
668
|
+
if action == "delete":
|
|
669
|
+
if not _REQUIRED_REQUEST_FIELDS.issubset(keys):
|
|
670
|
+
raise ValueError("table_column_request_missing_fields")
|
|
671
|
+
if not keys.issubset(_ALLOWED_DELETE_REQUEST_FIELDS):
|
|
672
|
+
raise ValueError("table_column_request_extra_fields")
|
|
673
|
+
elif action == "resize":
|
|
674
|
+
if not _REQUIRED_REQUEST_FIELDS.issubset(keys) or not keys & {"width", "column_width"}:
|
|
675
|
+
raise ValueError("table_column_request_missing_fields")
|
|
676
|
+
if not keys.issubset(_ALLOWED_RESIZE_REQUEST_FIELDS):
|
|
677
|
+
raise ValueError("table_column_request_extra_fields")
|
|
678
|
+
else:
|
|
679
|
+
if not _REQUIRED_REQUEST_FIELDS.issubset(keys):
|
|
680
|
+
raise ValueError("table_column_request_missing_fields")
|
|
681
|
+
if not keys.issubset(_ALLOWED_REQUEST_FIELDS):
|
|
682
|
+
raise ValueError("table_column_request_extra_fields")
|
|
683
|
+
|
|
684
|
+
source = Path(value["source"])
|
|
685
|
+
destination = Path(value["destination"])
|
|
686
|
+
source_sha256 = _require_sha256(value["source_sha256"], "table_column_source_sha256_invalid")
|
|
687
|
+
structure_fingerprint_sha256 = _require_sha256(
|
|
688
|
+
value["structure_fingerprint_sha256"],
|
|
689
|
+
"table_column_structure_fingerprint_invalid",
|
|
690
|
+
)
|
|
691
|
+
|
|
692
|
+
target_raw = value["target"]
|
|
693
|
+
if not isinstance(target_raw, Mapping):
|
|
694
|
+
raise TypeError("table_column_target_invalid")
|
|
695
|
+
t_keys = set(target_raw.keys())
|
|
696
|
+
has_col = "column" in t_keys or "col" in t_keys
|
|
697
|
+
if "table" not in t_keys or not has_col:
|
|
698
|
+
raise ValueError("table_column_target_missing_fields")
|
|
699
|
+
if not t_keys.issubset(_ALLOWED_TARGET_FIELDS):
|
|
700
|
+
raise ValueError("table_column_target_extra_fields")
|
|
701
|
+
|
|
702
|
+
table_idx = target_raw["table"]
|
|
703
|
+
if not isinstance(table_idx, int) or isinstance(table_idx, bool) or table_idx < 1:
|
|
704
|
+
raise ValueError("table_column_target_invalid")
|
|
705
|
+
col_idx = target_raw.get("column", target_raw.get("col"))
|
|
706
|
+
if not isinstance(col_idx, int) or isinstance(col_idx, bool) or col_idx < 1:
|
|
707
|
+
raise ValueError("table_column_target_invalid")
|
|
708
|
+
part = target_raw.get("part", _DOCUMENT)
|
|
709
|
+
if not isinstance(part, str):
|
|
710
|
+
raise TypeError("table_column_part_invalid")
|
|
711
|
+
|
|
712
|
+
target = {"table": table_idx, "column": col_idx, "part": part}
|
|
713
|
+
|
|
714
|
+
position = value.get("position")
|
|
715
|
+
width = value.get("width", value.get("column_width"))
|
|
716
|
+
cell_texts_raw = value.get("cell_texts")
|
|
717
|
+
|
|
718
|
+
cell_texts: tuple[str, ...] | None = None
|
|
719
|
+
if cell_texts_raw is not None:
|
|
720
|
+
if not isinstance(cell_texts_raw, (list, tuple)):
|
|
721
|
+
raise TypeError("table_column_cell_texts_invalid")
|
|
722
|
+
texts_list = []
|
|
723
|
+
for item in cell_texts_raw:
|
|
724
|
+
if not isinstance(item, str):
|
|
725
|
+
raise TypeError("table_column_cell_text_invalid")
|
|
726
|
+
if len(item) > _MAX_TEXT_CHARACTERS:
|
|
727
|
+
raise ValueError("table_column_cell_text_limit_exceeded")
|
|
728
|
+
if _has_illegal_xml_chars(item):
|
|
729
|
+
raise ValueError("table_column_cell_text_invalid")
|
|
730
|
+
texts_list.append(item)
|
|
731
|
+
cell_texts = tuple(texts_list)
|
|
732
|
+
|
|
733
|
+
return TableColumnRequest(
|
|
734
|
+
source=source,
|
|
735
|
+
destination=destination,
|
|
736
|
+
source_sha256=source_sha256,
|
|
737
|
+
target=target,
|
|
738
|
+
structure_fingerprint_sha256=structure_fingerprint_sha256,
|
|
739
|
+
position=position,
|
|
740
|
+
width=width,
|
|
741
|
+
cell_texts=cell_texts,
|
|
742
|
+
action=action,
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def load_table_column_request(path: str | Path) -> TableColumnRequest:
|
|
747
|
+
"""Load and strictly validate one JSON table-column request from disk."""
|
|
748
|
+
with Path(path).open("r", encoding="utf-8") as stream:
|
|
749
|
+
return parse_table_column_request(json.load(stream))
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def discover_table_column_targets(
|
|
753
|
+
source: str | Path,
|
|
754
|
+
*,
|
|
755
|
+
part: str = _DOCUMENT,
|
|
756
|
+
) -> dict[str, Any]:
|
|
757
|
+
"""Inventory source-bound candidate table column targets for authoring."""
|
|
758
|
+
path = Path(source)
|
|
759
|
+
if not path.is_file():
|
|
760
|
+
return {
|
|
761
|
+
"schema_version": 1,
|
|
762
|
+
"operation": "table-column-targets",
|
|
763
|
+
"passed": False,
|
|
764
|
+
"status": _REFUSED,
|
|
765
|
+
"code": "table_column_source_missing",
|
|
766
|
+
"source_sha256": None,
|
|
767
|
+
"part": part,
|
|
768
|
+
"targets": [],
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
try:
|
|
772
|
+
source_sha256 = _sha256_file(path)
|
|
773
|
+
graph = PackageGraph.from_file(path)
|
|
774
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
775
|
+
return {
|
|
776
|
+
"schema_version": 1,
|
|
777
|
+
"operation": "table-column-targets",
|
|
778
|
+
"passed": False,
|
|
779
|
+
"status": _REFUSED,
|
|
780
|
+
"code": "table_column_package_invalid",
|
|
781
|
+
"source_sha256": None,
|
|
782
|
+
"part": part,
|
|
783
|
+
"targets": [],
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
valid_part, part_err = _check_reachable_part(graph, part, "table_column")
|
|
787
|
+
if not valid_part:
|
|
788
|
+
return {
|
|
789
|
+
"schema_version": 1,
|
|
790
|
+
"operation": "table-column-targets",
|
|
791
|
+
"passed": False,
|
|
792
|
+
"status": _REFUSED,
|
|
793
|
+
"code": part_err or "table_column_part_unsupported",
|
|
794
|
+
"source_sha256": source_sha256,
|
|
795
|
+
"part": part,
|
|
796
|
+
"targets": [],
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
try:
|
|
800
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
801
|
+
except (ET.ParseError, KeyError):
|
|
802
|
+
return {
|
|
803
|
+
"schema_version": 1,
|
|
804
|
+
"operation": "table-column-targets",
|
|
805
|
+
"passed": False,
|
|
806
|
+
"status": _REFUSED,
|
|
807
|
+
"code": "table_column_package_invalid",
|
|
808
|
+
"source_sha256": source_sha256,
|
|
809
|
+
"part": part,
|
|
810
|
+
"targets": [],
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
namespace = _word_namespace(root)
|
|
814
|
+
if namespace is None:
|
|
815
|
+
return {
|
|
816
|
+
"schema_version": 1,
|
|
817
|
+
"operation": "table-column-targets",
|
|
818
|
+
"passed": False,
|
|
819
|
+
"status": _REFUSED,
|
|
820
|
+
"code": "table_column_namespace_unsupported",
|
|
821
|
+
"source_sha256": source_sha256,
|
|
822
|
+
"part": part,
|
|
823
|
+
"targets": [],
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
827
|
+
tables = list(root.iter(Q(namespace, "tbl")))
|
|
828
|
+
targets: list[dict[str, Any]] = []
|
|
829
|
+
|
|
830
|
+
for table_idx, table in enumerate(tables, start=1):
|
|
831
|
+
if unsupported_context.get(id(table), False):
|
|
832
|
+
continue
|
|
833
|
+
if not _is_supported_table(table, namespace):
|
|
834
|
+
continue
|
|
835
|
+
if _table_hazard_reason(table, namespace, allow_merged=True) is not None:
|
|
836
|
+
continue
|
|
837
|
+
|
|
838
|
+
tbl_grid = table.find(Q(namespace, "tblGrid"))
|
|
839
|
+
assert tbl_grid is not None
|
|
840
|
+
grid_cols = tbl_grid.findall(Q(namespace, "gridCol"))
|
|
841
|
+
rows = table.findall(Q(namespace, "tr"))
|
|
842
|
+
num_cols = len(grid_cols)
|
|
843
|
+
mapped_rows = [_grid_row_cells(row, namespace) for row in rows]
|
|
844
|
+
merged = any(
|
|
845
|
+
start != end
|
|
846
|
+
or cell.find(f"{Q(namespace, 'tcPr')}/{Q(namespace, 'hMerge')}") is not None
|
|
847
|
+
or cell.find(f"{Q(namespace, 'tcPr')}/{Q(namespace, 'vMerge')}") is not None
|
|
848
|
+
for mapping in mapped_rows
|
|
849
|
+
for cell, start, end in mapping
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
row_context_blocked = any(
|
|
853
|
+
unsupported_context.get(id(row), False)
|
|
854
|
+
or not _is_approved_row(row, namespace, allow_merged=True)
|
|
855
|
+
for row in rows
|
|
856
|
+
)
|
|
857
|
+
if row_context_blocked:
|
|
858
|
+
continue
|
|
859
|
+
|
|
860
|
+
for col_idx in range(1, num_cols + 1):
|
|
861
|
+
grid_col = grid_cols[col_idx - 1]
|
|
862
|
+
col_width = _get_element_width(grid_col, namespace)
|
|
863
|
+
if col_width is None and rows:
|
|
864
|
+
first_row_cell = next(
|
|
865
|
+
cell for cell, start, end in mapped_rows[0] if start <= col_idx <= end
|
|
866
|
+
)
|
|
867
|
+
tc_w = first_row_cell.find(f"{Q(namespace, 'tcPr')}/{Q(namespace, 'tcW')}")
|
|
868
|
+
if tc_w is not None:
|
|
869
|
+
col_width = _get_element_width(tc_w, namespace)
|
|
870
|
+
|
|
871
|
+
cell_texts: list[str] = []
|
|
872
|
+
for mapping in mapped_rows:
|
|
873
|
+
cell = next(cell for cell, start, end in mapping if start <= col_idx <= end)
|
|
874
|
+
cell_texts.append("".join(node.text or "" for node in cell.iter(Q(namespace, "t"))))
|
|
875
|
+
|
|
876
|
+
fp = _column_structure_fingerprint(table, col_idx, namespace, part=part)
|
|
877
|
+
can_delete = num_cols > 1
|
|
878
|
+
actions = (
|
|
879
|
+
("resize",) if merged else (("insert", "delete") if can_delete else ("insert",))
|
|
880
|
+
)
|
|
881
|
+
|
|
882
|
+
target = TableColumnTarget(
|
|
883
|
+
table=table_idx,
|
|
884
|
+
column=col_idx,
|
|
885
|
+
rows_count=len(rows),
|
|
886
|
+
structure_fingerprint_sha256=fp,
|
|
887
|
+
cell_texts=tuple(cell_texts),
|
|
888
|
+
width=col_width,
|
|
889
|
+
part=part,
|
|
890
|
+
actions=actions,
|
|
891
|
+
)
|
|
892
|
+
targets.append(target.to_dict())
|
|
893
|
+
|
|
894
|
+
return {
|
|
895
|
+
"schema_version": 1,
|
|
896
|
+
"operation": "table-column-targets",
|
|
897
|
+
"passed": True,
|
|
898
|
+
"status": "discovered",
|
|
899
|
+
"code": None,
|
|
900
|
+
"source_sha256": source_sha256,
|
|
901
|
+
"part": part,
|
|
902
|
+
"targets": targets,
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _resize_table_column(
|
|
907
|
+
request: TableColumnRequest,
|
|
908
|
+
*,
|
|
909
|
+
root: ET.Element,
|
|
910
|
+
table: ET.Element,
|
|
911
|
+
tables_count: int,
|
|
912
|
+
original_cell_xmls_by_row: list[list[bytes]],
|
|
913
|
+
namespace: str,
|
|
914
|
+
) -> TableColumnReport:
|
|
915
|
+
"""Set one admitted column's grid and cell widths while keeping every cell's content intact."""
|
|
916
|
+
def word(local):
|
|
917
|
+
return Q(namespace, local)
|
|
918
|
+
width = request.width
|
|
919
|
+
assert width is not None
|
|
920
|
+
col_idx = request.column - 1
|
|
921
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
922
|
+
assert tbl_grid is not None
|
|
923
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
924
|
+
rows = table.findall(word("tr"))
|
|
925
|
+
original_grid_xmls = [ET.tostring(grid_col) for grid_col in grid_cols]
|
|
926
|
+
mapped_rows = [_grid_row_cells(row, namespace) for row in rows]
|
|
927
|
+
affected = [
|
|
928
|
+
(r_idx, c_idx, cell, start, end)
|
|
929
|
+
for r_idx, mapping in enumerate(mapped_rows)
|
|
930
|
+
for c_idx, (cell, start, end) in enumerate(mapping)
|
|
931
|
+
if start <= request.column <= end
|
|
932
|
+
]
|
|
933
|
+
original_signatures = {
|
|
934
|
+
(r_idx, c_idx): _cell_content_signature(cell, namespace)
|
|
935
|
+
for r_idx, c_idx, cell, _, _ in affected
|
|
936
|
+
}
|
|
937
|
+
tc_w_path = f"{word('tcPr')}/{word('tcW')}"
|
|
938
|
+
|
|
939
|
+
target_grid_col = grid_cols[col_idx]
|
|
940
|
+
width_before = _get_element_width(target_grid_col, namespace)
|
|
941
|
+
grid_widths = [_get_element_width(col, namespace) for col in grid_cols]
|
|
942
|
+
if width_before is None:
|
|
943
|
+
if affected[0][3] != affected[0][4]:
|
|
944
|
+
return _table_column_refusal(
|
|
945
|
+
request,
|
|
946
|
+
"table_column_grid_mismatch",
|
|
947
|
+
{**request.target_dict(), "row": affected[0][0] + 1, "cell": affected[0][1] + 1},
|
|
948
|
+
)
|
|
949
|
+
first_tc_w = affected[0][2].find(tc_w_path)
|
|
950
|
+
if first_tc_w is not None and (first_tc_w.get(word("type")) or "dxa") == "dxa":
|
|
951
|
+
width_before = _get_element_width(first_tc_w, namespace)
|
|
952
|
+
grid_widths[col_idx] = width
|
|
953
|
+
|
|
954
|
+
# 1. Synchronize tblGrid
|
|
955
|
+
target_grid_col.attrib.pop("w", None)
|
|
956
|
+
target_grid_col.set(word("w"), str(width))
|
|
957
|
+
|
|
958
|
+
# 2. Synchronize the target cell of every row; tcPr is always the first tc child
|
|
959
|
+
cell_widths = {}
|
|
960
|
+
for r_idx, c_idx, target_cell, start, end in affected:
|
|
961
|
+
widths = grid_widths[start - 1 : end]
|
|
962
|
+
if any(value is None or value <= 0 for value in widths):
|
|
963
|
+
return _table_column_refusal(
|
|
964
|
+
request,
|
|
965
|
+
"table_column_grid_mismatch",
|
|
966
|
+
{**request.target_dict(), "row": r_idx + 1, "cell": c_idx + 1},
|
|
967
|
+
)
|
|
968
|
+
cell_width = sum(widths)
|
|
969
|
+
cell_widths[r_idx, c_idx] = cell_width
|
|
970
|
+
tc_pr = target_cell.find(word("tcPr"))
|
|
971
|
+
if tc_pr is None:
|
|
972
|
+
tc_pr = ET.Element(word("tcPr"))
|
|
973
|
+
target_cell.insert(0, tc_pr)
|
|
974
|
+
tc_w = tc_pr.find(word("tcW"))
|
|
975
|
+
if tc_w is None:
|
|
976
|
+
tc_w = ET.Element(word("tcW"))
|
|
977
|
+
_insert_tcpr_child_in_order(tc_pr, tc_w, namespace)
|
|
978
|
+
tc_w.attrib.pop("w", None)
|
|
979
|
+
tc_w.attrib.pop("type", None)
|
|
980
|
+
tc_w.set(word("w"), str(cell_width))
|
|
981
|
+
tc_w.set(word("type"), "dxa")
|
|
982
|
+
|
|
983
|
+
# 3. Synchronize table width by the column delta if explicit dxa
|
|
984
|
+
table_width_before: int | None = None
|
|
985
|
+
table_width_after: int | None = None
|
|
986
|
+
tbl_w = table.find(f"{word('tblPr')}/{word('tblW')}")
|
|
987
|
+
if tbl_w is not None and width_before is not None:
|
|
988
|
+
w_type = tbl_w.get(word("type")) or tbl_w.get("type")
|
|
989
|
+
w_val = tbl_w.get(word("w")) or tbl_w.get("w")
|
|
990
|
+
if (w_type is None or w_type == "dxa") and w_val and w_val.isdigit():
|
|
991
|
+
table_width_before = int(w_val)
|
|
992
|
+
table_width_after = max(0, table_width_before + width - width_before)
|
|
993
|
+
tbl_w.set(word("w"), str(table_width_after))
|
|
994
|
+
|
|
995
|
+
target_change_report = {
|
|
996
|
+
"action": "resize",
|
|
997
|
+
"table": request.table,
|
|
998
|
+
"column": request.column,
|
|
999
|
+
"columns_count": len(grid_cols),
|
|
1000
|
+
"rows_count": len(rows),
|
|
1001
|
+
"width_before": width_before,
|
|
1002
|
+
"width_after": width,
|
|
1003
|
+
"table_width_before": table_width_before,
|
|
1004
|
+
"table_width_after": table_width_after,
|
|
1005
|
+
}
|
|
1006
|
+
failed = "table_column_staged_verification_failed"
|
|
1007
|
+
|
|
1008
|
+
def verify_resize_publication(staged: Path) -> str | None:
|
|
1009
|
+
if not _unrelated_parts_preserved(request.source, staged, frozenset({request.part})):
|
|
1010
|
+
return failed
|
|
1011
|
+
if not inspect_docx(staged).valid:
|
|
1012
|
+
return failed
|
|
1013
|
+
try:
|
|
1014
|
+
s_root = ET.fromstring(PackageGraph.from_file(staged).read_part_bytes(request.part))
|
|
1015
|
+
s_tables = list(s_root.iter(word("tbl")))
|
|
1016
|
+
if len(s_tables) != tables_count:
|
|
1017
|
+
return failed
|
|
1018
|
+
s_table = s_tables[request.table - 1]
|
|
1019
|
+
s_grid = s_table.find(word("tblGrid"))
|
|
1020
|
+
s_cols = s_grid.findall(word("gridCol")) if s_grid is not None else []
|
|
1021
|
+
if len(s_cols) != len(original_grid_xmls):
|
|
1022
|
+
return failed
|
|
1023
|
+
for g_i, (orig_xml, s_col) in enumerate(zip(original_grid_xmls, s_cols, strict=True)):
|
|
1024
|
+
if g_i == col_idx:
|
|
1025
|
+
if _get_element_width(s_col, namespace) != width:
|
|
1026
|
+
return failed
|
|
1027
|
+
elif ET.tostring(s_col) != orig_xml:
|
|
1028
|
+
return failed
|
|
1029
|
+
s_rows = s_table.findall(word("tr"))
|
|
1030
|
+
if len(s_rows) != len(rows):
|
|
1031
|
+
return failed
|
|
1032
|
+
for r_i, s_r in enumerate(s_rows):
|
|
1033
|
+
s_cells = s_r.findall(word("tc"))
|
|
1034
|
+
orig_xmls = original_cell_xmls_by_row[r_i]
|
|
1035
|
+
if len(s_cells) != len(orig_xmls):
|
|
1036
|
+
return failed
|
|
1037
|
+
for c_i, (orig_xml, s_cell) in enumerate(zip(orig_xmls, s_cells, strict=True)):
|
|
1038
|
+
if (r_i, c_i) not in cell_widths:
|
|
1039
|
+
if ET.tostring(s_cell) != orig_xml:
|
|
1040
|
+
return failed
|
|
1041
|
+
continue
|
|
1042
|
+
if _cell_content_signature(s_cell, namespace) != original_signatures[r_i, c_i]:
|
|
1043
|
+
return failed
|
|
1044
|
+
s_tc_w = s_cell.find(tc_w_path)
|
|
1045
|
+
if (
|
|
1046
|
+
s_tc_w is None
|
|
1047
|
+
or _get_element_width(s_tc_w, namespace) != cell_widths[r_i, c_i]
|
|
1048
|
+
or s_tc_w.get(word("type")) != "dxa"
|
|
1049
|
+
):
|
|
1050
|
+
return failed
|
|
1051
|
+
if table_width_after is not None:
|
|
1052
|
+
s_tbl_w = s_table.find(f"{word('tblPr')}/{word('tblW')}")
|
|
1053
|
+
if s_tbl_w is None or _get_element_width(s_tbl_w, namespace) != table_width_after:
|
|
1054
|
+
return failed
|
|
1055
|
+
except (OSError, PackageError, ET.ParseError, KeyError, IndexError, ValueError):
|
|
1056
|
+
return failed
|
|
1057
|
+
return None
|
|
1058
|
+
|
|
1059
|
+
published: ReviewReport = _publish(
|
|
1060
|
+
source=request.source,
|
|
1061
|
+
output=request.destination,
|
|
1062
|
+
source_sha256=request.source_sha256,
|
|
1063
|
+
replacements={request.part: serialize_xml_with_preserved_qnames(root)},
|
|
1064
|
+
revisions=[],
|
|
1065
|
+
targets=[target_change_report],
|
|
1066
|
+
verify=verify_resize_publication,
|
|
1067
|
+
failure_code=failed,
|
|
1068
|
+
exists_code="table_column_destination_occupied",
|
|
1069
|
+
unavailable_code="table_column_publication_unavailable",
|
|
1070
|
+
)
|
|
1071
|
+
if not published.passed:
|
|
1072
|
+
return _table_column_refusal(request, published.code or failed)
|
|
1073
|
+
|
|
1074
|
+
return TableColumnReport(
|
|
1075
|
+
status=_PUBLISHED,
|
|
1076
|
+
code=None,
|
|
1077
|
+
source_sha256=request.source_sha256,
|
|
1078
|
+
destination_sha256=published.output_sha256,
|
|
1079
|
+
target=request.target_dict(),
|
|
1080
|
+
target_change_report=target_change_report,
|
|
1081
|
+
non_target_parts_preserved=True,
|
|
1082
|
+
)
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def author_table_column(request: TableColumnRequest) -> TableColumnReport:
|
|
1086
|
+
"""Insert, delete, or resize a source-bound table column atomically with full geometry synchronization."""
|
|
1087
|
+
source = request.source
|
|
1088
|
+
destination = request.destination
|
|
1089
|
+
|
|
1090
|
+
if request.action == "resize" and not _is_valid_column_width(request.width):
|
|
1091
|
+
return _table_column_refusal(request, "table_column_width_invalid")
|
|
1092
|
+
if not source.is_file():
|
|
1093
|
+
return _table_column_refusal(request, "table_column_source_missing")
|
|
1094
|
+
if source == destination:
|
|
1095
|
+
return _table_column_refusal(request, "table_column_destination_invalid")
|
|
1096
|
+
if not destination.parent.is_dir():
|
|
1097
|
+
return _table_column_refusal(request, "table_column_destination_invalid")
|
|
1098
|
+
if destination.exists() or destination.is_symlink():
|
|
1099
|
+
return _table_column_refusal(request, "table_column_destination_occupied")
|
|
1100
|
+
|
|
1101
|
+
try:
|
|
1102
|
+
actual_source_sha256 = _sha256_file(source)
|
|
1103
|
+
except OSError:
|
|
1104
|
+
return _table_column_refusal(request, "table_column_source_missing")
|
|
1105
|
+
|
|
1106
|
+
if actual_source_sha256 != request.source_sha256:
|
|
1107
|
+
return _table_column_refusal(request, "table_column_source_hash_mismatch")
|
|
1108
|
+
|
|
1109
|
+
try:
|
|
1110
|
+
graph = PackageGraph.from_file(source)
|
|
1111
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
1112
|
+
return _table_column_refusal(request, "table_column_package_invalid")
|
|
1113
|
+
|
|
1114
|
+
if _DOCUMENT not in graph.parts:
|
|
1115
|
+
return _table_column_refusal(request, "table_column_package_invalid")
|
|
1116
|
+
|
|
1117
|
+
valid_part, part_err = _check_reachable_part(graph, request.part, "table_column")
|
|
1118
|
+
if not valid_part:
|
|
1119
|
+
return _table_column_refusal(request, part_err or "table_column_part_unsupported")
|
|
1120
|
+
|
|
1121
|
+
try:
|
|
1122
|
+
doc_bytes = graph.read_part_bytes(request.part)
|
|
1123
|
+
root = parse_xml_with_preserved_qnames(doc_bytes)
|
|
1124
|
+
except (KeyError, ET.ParseError):
|
|
1125
|
+
return _table_column_refusal(request, "table_column_package_invalid")
|
|
1126
|
+
|
|
1127
|
+
namespace = _word_namespace(root)
|
|
1128
|
+
if namespace is None:
|
|
1129
|
+
return _table_column_refusal(request, "table_column_namespace_unsupported")
|
|
1130
|
+
|
|
1131
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
1132
|
+
def word(local):
|
|
1133
|
+
return Q(namespace, local)
|
|
1134
|
+
tables = list(root.iter(word("tbl")))
|
|
1135
|
+
|
|
1136
|
+
if request.table < 1 or request.table > len(tables):
|
|
1137
|
+
return _table_column_refusal(request, "table_column_target_missing")
|
|
1138
|
+
|
|
1139
|
+
table = tables[request.table - 1]
|
|
1140
|
+
if unsupported_context.get(id(table), False):
|
|
1141
|
+
return _table_column_refusal(request, "table_column_context_unsupported")
|
|
1142
|
+
|
|
1143
|
+
hazard = _table_hazard_reason(table, namespace, allow_merged=request.action == "resize")
|
|
1144
|
+
if hazard is not None:
|
|
1145
|
+
target = request.target_dict()
|
|
1146
|
+
for r_idx, row in enumerate(table.findall(word("tr")), start=1):
|
|
1147
|
+
for c_idx, cell in enumerate(row.findall(word("tc")), start=1):
|
|
1148
|
+
properties = cell.find(word("tcPr"))
|
|
1149
|
+
if properties is not None and any(
|
|
1150
|
+
properties.find(word(name)) is not None
|
|
1151
|
+
for name in ("gridSpan", "hMerge", "vMerge")
|
|
1152
|
+
):
|
|
1153
|
+
target.update(row=r_idx, cell=c_idx)
|
|
1154
|
+
return _table_column_refusal(request, hazard, target)
|
|
1155
|
+
return _table_column_refusal(request, hazard)
|
|
1156
|
+
|
|
1157
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
1158
|
+
assert tbl_grid is not None
|
|
1159
|
+
grid_cols = tbl_grid.findall(word("gridCol"))
|
|
1160
|
+
rows = table.findall(word("tr"))
|
|
1161
|
+
num_cols = len(grid_cols)
|
|
1162
|
+
original_cell_xmls_by_row: list[list[bytes]] = [
|
|
1163
|
+
[ET.tostring(c) for c in r.findall(word("tc"))] for r in rows
|
|
1164
|
+
]
|
|
1165
|
+
|
|
1166
|
+
if request.column < 1 or request.column > num_cols:
|
|
1167
|
+
return _table_column_refusal(request, "table_column_target_missing")
|
|
1168
|
+
|
|
1169
|
+
actual_fp = _column_structure_fingerprint(table, request.column, namespace, part=request.part)
|
|
1170
|
+
if actual_fp != request.structure_fingerprint_sha256:
|
|
1171
|
+
return _table_column_refusal(request, "table_column_structure_fingerprint_mismatch")
|
|
1172
|
+
|
|
1173
|
+
if request.action == "resize":
|
|
1174
|
+
return _resize_table_column(
|
|
1175
|
+
request,
|
|
1176
|
+
root=root,
|
|
1177
|
+
table=table,
|
|
1178
|
+
tables_count=len(tables),
|
|
1179
|
+
original_cell_xmls_by_row=original_cell_xmls_by_row,
|
|
1180
|
+
namespace=namespace,
|
|
1181
|
+
)
|
|
1182
|
+
|
|
1183
|
+
target_col_idx = request.column - 1
|
|
1184
|
+
target_grid_col = grid_cols[target_col_idx]
|
|
1185
|
+
|
|
1186
|
+
expected_surviving_cells_by_row: list[list[bytes]] = [
|
|
1187
|
+
[cell_xml for c_i, cell_xml in enumerate(row_xmls) if c_i != target_col_idx]
|
|
1188
|
+
for row_xmls in original_cell_xmls_by_row
|
|
1189
|
+
]
|
|
1190
|
+
if request.action == "delete":
|
|
1191
|
+
if num_cols <= 1:
|
|
1192
|
+
return _table_column_refusal(request, "table_column_final_column_unsupported")
|
|
1193
|
+
|
|
1194
|
+
deleted_width = _get_element_width(target_grid_col, namespace)
|
|
1195
|
+
if deleted_width is None:
|
|
1196
|
+
first_tc = rows[0].findall(word("tc"))[target_col_idx]
|
|
1197
|
+
tc_w = first_tc.find(f".//{word('tcW')}")
|
|
1198
|
+
deleted_width = _get_element_width(tc_w, namespace) if tc_w is not None else 0
|
|
1199
|
+
|
|
1200
|
+
# 1. Synchronize tblGrid
|
|
1201
|
+
tbl_grid.remove(target_grid_col)
|
|
1202
|
+
|
|
1203
|
+
# 2. Synchronize every row
|
|
1204
|
+
for r in rows:
|
|
1205
|
+
r_cells = r.findall(word("tc"))
|
|
1206
|
+
r.remove(r_cells[target_col_idx])
|
|
1207
|
+
|
|
1208
|
+
# 3. Synchronize table width if explicit dxa
|
|
1209
|
+
tbl_pr = table.find(word("tblPr"))
|
|
1210
|
+
if tbl_pr is not None:
|
|
1211
|
+
tbl_w = tbl_pr.find(word("tblW"))
|
|
1212
|
+
if tbl_w is not None and deleted_width:
|
|
1213
|
+
w_type = tbl_w.get(word("type")) or tbl_w.get("type")
|
|
1214
|
+
w_val = tbl_w.get(word("w")) or tbl_w.get("w")
|
|
1215
|
+
if (w_type is None or w_type == "dxa") and w_val and w_val.isdigit():
|
|
1216
|
+
new_tbl_w = max(0, int(w_val) - deleted_width)
|
|
1217
|
+
tbl_w.set(word("w"), str(new_tbl_w))
|
|
1218
|
+
|
|
1219
|
+
target_change_report = {
|
|
1220
|
+
"action": "delete",
|
|
1221
|
+
"table": request.table,
|
|
1222
|
+
"deleted_column": request.column,
|
|
1223
|
+
"columns_count_before": num_cols,
|
|
1224
|
+
"columns_count_after": num_cols - 1,
|
|
1225
|
+
"rows_count": len(rows),
|
|
1226
|
+
"width": deleted_width,
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
def verify_deletion_publication(staged: Path) -> str | None:
|
|
1230
|
+
if not _unrelated_parts_preserved(source, staged, frozenset({request.part})):
|
|
1231
|
+
return "table_column_staged_verification_failed"
|
|
1232
|
+
insp = inspect_docx(staged)
|
|
1233
|
+
if not insp.valid:
|
|
1234
|
+
return "table_column_staged_verification_failed"
|
|
1235
|
+
try:
|
|
1236
|
+
s_graph = PackageGraph.from_file(staged)
|
|
1237
|
+
s_root = ET.fromstring(s_graph.read_part_bytes(request.part))
|
|
1238
|
+
s_tables = list(s_root.iter(word("tbl")))
|
|
1239
|
+
if len(s_tables) != len(tables):
|
|
1240
|
+
return "table_column_staged_verification_failed"
|
|
1241
|
+
s_table = s_tables[request.table - 1]
|
|
1242
|
+
s_grid = s_table.find(word("tblGrid"))
|
|
1243
|
+
if s_grid is None:
|
|
1244
|
+
return "table_column_staged_verification_failed"
|
|
1245
|
+
s_cols = s_grid.findall(word("gridCol"))
|
|
1246
|
+
if len(s_cols) != num_cols - 1:
|
|
1247
|
+
return "table_column_staged_verification_failed"
|
|
1248
|
+
s_rows = s_table.findall(word("tr"))
|
|
1249
|
+
if len(s_rows) != len(rows):
|
|
1250
|
+
return "table_column_staged_verification_failed"
|
|
1251
|
+
for r_i, s_r in enumerate(s_rows):
|
|
1252
|
+
s_cells = s_r.findall(word("tc"))
|
|
1253
|
+
expected_survivors = expected_surviving_cells_by_row[r_i]
|
|
1254
|
+
if len(s_cells) != len(expected_survivors):
|
|
1255
|
+
return "table_column_staged_verification_failed"
|
|
1256
|
+
for orig_xml, staged_c in zip(expected_survivors, s_cells, strict=True):
|
|
1257
|
+
if ET.tostring(staged_c) != orig_xml:
|
|
1258
|
+
return "table_column_staged_verification_failed"
|
|
1259
|
+
except (
|
|
1260
|
+
OSError,
|
|
1261
|
+
PackageError,
|
|
1262
|
+
ET.ParseError,
|
|
1263
|
+
KeyError,
|
|
1264
|
+
IndexError,
|
|
1265
|
+
ValueError,
|
|
1266
|
+
):
|
|
1267
|
+
return "table_column_staged_verification_failed"
|
|
1268
|
+
return None
|
|
1269
|
+
|
|
1270
|
+
serialized = serialize_xml_with_preserved_qnames(root)
|
|
1271
|
+
replacements = {request.part: serialized}
|
|
1272
|
+
|
|
1273
|
+
published: ReviewReport = _publish(
|
|
1274
|
+
source=source,
|
|
1275
|
+
output=destination,
|
|
1276
|
+
source_sha256=request.source_sha256,
|
|
1277
|
+
replacements=replacements,
|
|
1278
|
+
revisions=[],
|
|
1279
|
+
targets=[target_change_report],
|
|
1280
|
+
verify=verify_deletion_publication,
|
|
1281
|
+
failure_code="table_column_staged_verification_failed",
|
|
1282
|
+
exists_code="table_column_destination_occupied",
|
|
1283
|
+
unavailable_code="table_column_publication_unavailable",
|
|
1284
|
+
)
|
|
1285
|
+
|
|
1286
|
+
if not published.passed:
|
|
1287
|
+
return _table_column_refusal(
|
|
1288
|
+
request, published.code or "table_column_staged_verification_failed"
|
|
1289
|
+
)
|
|
1290
|
+
|
|
1291
|
+
return TableColumnReport(
|
|
1292
|
+
status=_PUBLISHED,
|
|
1293
|
+
code=None,
|
|
1294
|
+
source_sha256=request.source_sha256,
|
|
1295
|
+
destination_sha256=published.output_sha256,
|
|
1296
|
+
target=request.target_dict(),
|
|
1297
|
+
target_change_report=target_change_report,
|
|
1298
|
+
non_target_parts_preserved=True,
|
|
1299
|
+
)
|
|
1300
|
+
|
|
1301
|
+
# Insertion path
|
|
1302
|
+
if request.cell_texts is not None and len(request.cell_texts) != len(rows):
|
|
1303
|
+
return _table_column_refusal(request, "table_column_cell_texts_mismatch")
|
|
1304
|
+
|
|
1305
|
+
if request.width is not None:
|
|
1306
|
+
inserted_width = request.width
|
|
1307
|
+
else:
|
|
1308
|
+
inferred_w = _get_element_width(target_grid_col, namespace)
|
|
1309
|
+
if inferred_w is None:
|
|
1310
|
+
first_tc = rows[0].findall(word("tc"))[target_col_idx]
|
|
1311
|
+
tc_w = first_tc.find(f".//{word('tcW')}")
|
|
1312
|
+
inferred_w = _get_element_width(tc_w, namespace) if tc_w is not None else None
|
|
1313
|
+
inserted_width = inferred_w if inferred_w is not None else 2500
|
|
1314
|
+
|
|
1315
|
+
insertion_texts: Sequence[str] = (
|
|
1316
|
+
request.cell_texts if request.cell_texts is not None else ("",) * len(rows)
|
|
1317
|
+
)
|
|
1318
|
+
|
|
1319
|
+
if request.position == "before":
|
|
1320
|
+
ins_grid_idx = target_col_idx
|
|
1321
|
+
inserted_col_num = request.column
|
|
1322
|
+
else:
|
|
1323
|
+
ins_grid_idx = target_col_idx + 1
|
|
1324
|
+
inserted_col_num = request.column + 1
|
|
1325
|
+
|
|
1326
|
+
# 1. Synchronize tblGrid
|
|
1327
|
+
new_grid_col = ET.Element(word("gridCol"))
|
|
1328
|
+
new_grid_col.set(word("w"), str(inserted_width))
|
|
1329
|
+
tbl_grid.insert(ins_grid_idx, new_grid_col)
|
|
1330
|
+
|
|
1331
|
+
# 2. Synchronize every row
|
|
1332
|
+
for r_idx, r in enumerate(rows):
|
|
1333
|
+
r_cells = r.findall(word("tc"))
|
|
1334
|
+
proto_cell = r_cells[target_col_idx]
|
|
1335
|
+
proto_tc_pr = proto_cell.find(word("tcPr"))
|
|
1336
|
+
|
|
1337
|
+
new_cell = ET.Element(word("tc"))
|
|
1338
|
+
if proto_tc_pr is not None:
|
|
1339
|
+
new_tc_pr = copy.deepcopy(proto_tc_pr)
|
|
1340
|
+
else:
|
|
1341
|
+
new_tc_pr = ET.Element(word("tcPr"))
|
|
1342
|
+
|
|
1343
|
+
# Set explicit tcW maintaining schema ordering in tcPr
|
|
1344
|
+
tc_w = new_tc_pr.find(word("tcW"))
|
|
1345
|
+
if tc_w is None:
|
|
1346
|
+
tc_w = ET.Element(word("tcW"))
|
|
1347
|
+
_insert_tcpr_child_in_order(new_tc_pr, tc_w, namespace)
|
|
1348
|
+
tc_w.set(word("w"), str(inserted_width))
|
|
1349
|
+
tc_w.set(word("type"), "dxa")
|
|
1350
|
+
|
|
1351
|
+
# Purge any merge elements
|
|
1352
|
+
for tag_name in ("vMerge", "hMerge", "gridSpan"):
|
|
1353
|
+
m_elem = new_tc_pr.find(word(tag_name))
|
|
1354
|
+
if m_elem is not None:
|
|
1355
|
+
new_tc_pr.remove(m_elem)
|
|
1356
|
+
|
|
1357
|
+
new_cell.append(new_tc_pr)
|
|
1358
|
+
|
|
1359
|
+
# Paragraph & Run with cloned formatting
|
|
1360
|
+
proto_p = proto_cell.find(word("p"))
|
|
1361
|
+
new_p = ET.Element(word("p"))
|
|
1362
|
+
if proto_p is not None:
|
|
1363
|
+
proto_p_pr = proto_p.find(word("pPr"))
|
|
1364
|
+
if proto_p_pr is not None:
|
|
1365
|
+
new_p.append(copy.deepcopy(proto_p_pr))
|
|
1366
|
+
|
|
1367
|
+
new_r = ET.Element(word("r"))
|
|
1368
|
+
if proto_p is not None:
|
|
1369
|
+
proto_r = proto_p.find(word("r"))
|
|
1370
|
+
if proto_r is not None:
|
|
1371
|
+
proto_r_pr = proto_r.find(word("rPr"))
|
|
1372
|
+
if proto_r_pr is not None:
|
|
1373
|
+
new_r.append(copy.deepcopy(proto_r_pr))
|
|
1374
|
+
|
|
1375
|
+
t_elem = ET.Element(word("t"))
|
|
1376
|
+
t_text = insertion_texts[r_idx]
|
|
1377
|
+
t_elem.text = t_text
|
|
1378
|
+
if t_text.startswith(" ") or t_text.endswith(" ") or " " in t_text:
|
|
1379
|
+
t_elem.set(_XML_SPACE_ATTRIBUTE, "preserve")
|
|
1380
|
+
|
|
1381
|
+
new_r.append(t_elem)
|
|
1382
|
+
new_p.append(new_r)
|
|
1383
|
+
new_cell.append(new_p)
|
|
1384
|
+
|
|
1385
|
+
# Insert at exact position relative to proto_cell child index
|
|
1386
|
+
r_children = list(r)
|
|
1387
|
+
proto_child_idx = r_children.index(proto_cell)
|
|
1388
|
+
if request.position == "before":
|
|
1389
|
+
r.insert(proto_child_idx, new_cell)
|
|
1390
|
+
else:
|
|
1391
|
+
r.insert(proto_child_idx + 1, new_cell)
|
|
1392
|
+
|
|
1393
|
+
# 3. Synchronize table width if explicit dxa
|
|
1394
|
+
tbl_pr = table.find(word("tblPr"))
|
|
1395
|
+
if tbl_pr is not None:
|
|
1396
|
+
tbl_w = tbl_pr.find(word("tblW"))
|
|
1397
|
+
if tbl_w is not None and inserted_width:
|
|
1398
|
+
w_type = tbl_w.get(word("type")) or tbl_w.get("type")
|
|
1399
|
+
w_val = tbl_w.get(word("w")) or tbl_w.get("w")
|
|
1400
|
+
if (w_type is None or w_type == "dxa") and w_val and w_val.isdigit():
|
|
1401
|
+
new_tbl_w = int(w_val) + inserted_width
|
|
1402
|
+
tbl_w.set(word("w"), str(new_tbl_w))
|
|
1403
|
+
|
|
1404
|
+
target_change_report = {
|
|
1405
|
+
"action": "insert",
|
|
1406
|
+
"table": request.table,
|
|
1407
|
+
"prototype_column": request.column,
|
|
1408
|
+
"position": request.position,
|
|
1409
|
+
"inserted_column": inserted_col_num,
|
|
1410
|
+
"columns_count_before": num_cols,
|
|
1411
|
+
"columns_count_after": num_cols + 1,
|
|
1412
|
+
"rows_count": len(rows),
|
|
1413
|
+
"width": inserted_width,
|
|
1414
|
+
"cell_text_lengths": [len(t) for t in insertion_texts],
|
|
1415
|
+
"cell_texts_sha256": hashlib.sha256("".join(insertion_texts).encode("utf-8")).hexdigest(),
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
def verify_insertion_publication(staged: Path) -> str | None:
|
|
1419
|
+
if not _unrelated_parts_preserved(source, staged, frozenset({request.part})):
|
|
1420
|
+
return "table_column_staged_verification_failed"
|
|
1421
|
+
insp = inspect_docx(staged)
|
|
1422
|
+
if not insp.valid:
|
|
1423
|
+
return "table_column_staged_verification_failed"
|
|
1424
|
+
try:
|
|
1425
|
+
s_graph = PackageGraph.from_file(staged)
|
|
1426
|
+
s_root = ET.fromstring(s_graph.read_part_bytes(request.part))
|
|
1427
|
+
s_tables = list(s_root.iter(word("tbl")))
|
|
1428
|
+
if len(s_tables) != len(tables):
|
|
1429
|
+
return "table_column_staged_verification_failed"
|
|
1430
|
+
s_table = s_tables[request.table - 1]
|
|
1431
|
+
s_grid = s_table.find(word("tblGrid"))
|
|
1432
|
+
if s_grid is None:
|
|
1433
|
+
return "table_column_staged_verification_failed"
|
|
1434
|
+
s_cols = s_grid.findall(word("gridCol"))
|
|
1435
|
+
if len(s_cols) != num_cols + 1:
|
|
1436
|
+
return "table_column_staged_verification_failed"
|
|
1437
|
+
ins_grid_col = s_cols[ins_grid_idx]
|
|
1438
|
+
if _get_element_width(ins_grid_col, namespace) != inserted_width:
|
|
1439
|
+
return "table_column_staged_verification_failed"
|
|
1440
|
+
s_rows = s_table.findall(word("tr"))
|
|
1441
|
+
if len(s_rows) != len(rows):
|
|
1442
|
+
return "table_column_staged_verification_failed"
|
|
1443
|
+
for r_i, (orig_r, s_r) in enumerate(zip(rows, s_rows)):
|
|
1444
|
+
s_cells = s_r.findall(word("tc"))
|
|
1445
|
+
if len(s_cells) != num_cols + 1:
|
|
1446
|
+
return "table_column_staged_verification_failed"
|
|
1447
|
+
inserted_cell = s_cells[ins_grid_idx]
|
|
1448
|
+
simple = _simple_text_node(inserted_cell, namespace)
|
|
1449
|
+
if simple is None or simple[1] != insertion_texts[r_i]:
|
|
1450
|
+
return "table_column_staged_verification_failed"
|
|
1451
|
+
tc_w_elem = inserted_cell.find(f".//{word('tcW')}")
|
|
1452
|
+
if tc_w_elem is None or _get_element_width(tc_w_elem, namespace) != inserted_width:
|
|
1453
|
+
return "table_column_staged_verification_failed"
|
|
1454
|
+
orig_xmls = original_cell_xmls_by_row[r_i]
|
|
1455
|
+
staged_non_target = [c for i, c in enumerate(s_cells) if i != ins_grid_idx]
|
|
1456
|
+
if len(staged_non_target) != len(orig_xmls):
|
|
1457
|
+
return "table_column_staged_verification_failed"
|
|
1458
|
+
for orig_xml, staged_c in zip(orig_xmls, staged_non_target, strict=True):
|
|
1459
|
+
if ET.tostring(staged_c) != orig_xml:
|
|
1460
|
+
return "table_column_staged_verification_failed"
|
|
1461
|
+
except (
|
|
1462
|
+
OSError,
|
|
1463
|
+
PackageError,
|
|
1464
|
+
ET.ParseError,
|
|
1465
|
+
KeyError,
|
|
1466
|
+
IndexError,
|
|
1467
|
+
ValueError,
|
|
1468
|
+
):
|
|
1469
|
+
return "table_column_staged_verification_failed"
|
|
1470
|
+
return None
|
|
1471
|
+
|
|
1472
|
+
serialized = serialize_xml_with_preserved_qnames(root)
|
|
1473
|
+
replacements = {request.part: serialized}
|
|
1474
|
+
|
|
1475
|
+
published: ReviewReport = _publish(
|
|
1476
|
+
source=source,
|
|
1477
|
+
output=destination,
|
|
1478
|
+
source_sha256=request.source_sha256,
|
|
1479
|
+
replacements=replacements,
|
|
1480
|
+
revisions=[],
|
|
1481
|
+
targets=[target_change_report],
|
|
1482
|
+
verify=verify_insertion_publication,
|
|
1483
|
+
failure_code="table_column_staged_verification_failed",
|
|
1484
|
+
exists_code="table_column_destination_occupied",
|
|
1485
|
+
unavailable_code="table_column_publication_unavailable",
|
|
1486
|
+
)
|
|
1487
|
+
|
|
1488
|
+
if not published.passed:
|
|
1489
|
+
return _table_column_refusal(
|
|
1490
|
+
request, published.code or "table_column_staged_verification_failed"
|
|
1491
|
+
)
|
|
1492
|
+
|
|
1493
|
+
return TableColumnReport(
|
|
1494
|
+
status=_PUBLISHED,
|
|
1495
|
+
code=None,
|
|
1496
|
+
source_sha256=request.source_sha256,
|
|
1497
|
+
destination_sha256=published.output_sha256,
|
|
1498
|
+
target=request.target_dict(),
|
|
1499
|
+
target_change_report=target_change_report,
|
|
1500
|
+
non_target_parts_preserved=True,
|
|
1501
|
+
)
|