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_merge.py
ADDED
|
@@ -0,0 +1,1863 @@
|
|
|
1
|
+
"""Source-bound table cell merge and split authoring and discovery for WordprocessingML documents.
|
|
2
|
+
|
|
3
|
+
Supports horizontal gridSpan merges, vertical vMerge restarts and continuations,
|
|
4
|
+
and combined rectangular merges on explicit grid rectangles in supported tables of
|
|
5
|
+
the main document body or of a genuinely referenced header or footer part.
|
|
6
|
+
Guarantees zero data loss by refusing merges over non-empty non-origin cells
|
|
7
|
+
(including whitespace, tabs, breaks, and control symbols), preserves tblGrid unchanged,
|
|
8
|
+
derives split cell widths from explicit positive grid widths, and strictly preserves
|
|
9
|
+
OOXML schema element ordering in tcPr.
|
|
10
|
+
|
|
11
|
+
Legacy ``w:hMerge`` regions are discoverable as split targets but are never mutated:
|
|
12
|
+
any request against a table that carries ``w:hMerge`` is refused with
|
|
13
|
+
``table_merge_structure_unsupported`` and the refusal's ``target_change_report`` names
|
|
14
|
+
the exact one-based ``row`` and ``cell`` of the offending cell. Existing gridSpan and
|
|
15
|
+
vMerge regions a request would cross are likewise refused with row and cell details
|
|
16
|
+
and are never canonicalized or deleted.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import copy
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import zipfile
|
|
25
|
+
from collections.abc import Mapping
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
from xml.etree import ElementTree as ET
|
|
30
|
+
|
|
31
|
+
from .authoring import (
|
|
32
|
+
_PUBLISHED,
|
|
33
|
+
_REFUSED,
|
|
34
|
+
_require_sha256,
|
|
35
|
+
_sha256_file,
|
|
36
|
+
_unsupported_context_by_element,
|
|
37
|
+
_word_namespace,
|
|
38
|
+
)
|
|
39
|
+
from .inspect import (
|
|
40
|
+
Q,
|
|
41
|
+
inspect_docx,
|
|
42
|
+
parse_xml_with_preserved_qnames,
|
|
43
|
+
serialize_xml_with_preserved_qnames,
|
|
44
|
+
)
|
|
45
|
+
from .package import PackageError, PackageGraph
|
|
46
|
+
from .review import _DOCUMENT, ReviewReport, _publish
|
|
47
|
+
from .table_properties import _check_reachable_part
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"TableMergeReport",
|
|
51
|
+
"TableMergeRequest",
|
|
52
|
+
"TableMergeTarget",
|
|
53
|
+
"author_table_merge",
|
|
54
|
+
"discover_table_merge_targets",
|
|
55
|
+
"load_table_merge_request",
|
|
56
|
+
"parse_table_merge_request",
|
|
57
|
+
"table_merge_structure_fingerprint",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
_REQUIRED_REQUEST_FIELDS = frozenset(
|
|
61
|
+
{"source", "destination", "source_sha256", "target", "structure_fingerprint_sha256"}
|
|
62
|
+
)
|
|
63
|
+
_ALLOWED_REQUEST_FIELDS = frozenset(
|
|
64
|
+
{
|
|
65
|
+
"source",
|
|
66
|
+
"destination",
|
|
67
|
+
"source_sha256",
|
|
68
|
+
"target",
|
|
69
|
+
"structure_fingerprint_sha256",
|
|
70
|
+
"action",
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
_REQUIRED_TARGET_FIELDS = frozenset({"table", "start_row", "end_row", "start_col", "end_col"})
|
|
74
|
+
_ALLOWED_TARGET_FIELDS = frozenset(
|
|
75
|
+
{"table", "start_row", "end_row", "start_col", "end_col", "part"}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
_TCPR_ORDER: tuple[str, ...] = (
|
|
79
|
+
"cnfStyle",
|
|
80
|
+
"tcW",
|
|
81
|
+
"gridSpan",
|
|
82
|
+
"hMerge",
|
|
83
|
+
"vMerge",
|
|
84
|
+
"tcBorders",
|
|
85
|
+
"shd",
|
|
86
|
+
"noWrap",
|
|
87
|
+
"tcMar",
|
|
88
|
+
"textDirection",
|
|
89
|
+
"tcFitText",
|
|
90
|
+
"vAlign",
|
|
91
|
+
"hideMark",
|
|
92
|
+
"headers",
|
|
93
|
+
"cellIns",
|
|
94
|
+
"cellDel",
|
|
95
|
+
"cellMerge",
|
|
96
|
+
"tcPrChange",
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
_FORBIDDEN_CELL_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
|
+
"ins",
|
|
115
|
+
"instrText",
|
|
116
|
+
"moveFrom",
|
|
117
|
+
"moveFromRangeEnd",
|
|
118
|
+
"moveFromRangeStart",
|
|
119
|
+
"moveTo",
|
|
120
|
+
"moveToRangeEnd",
|
|
121
|
+
"moveToRangeStart",
|
|
122
|
+
"pict",
|
|
123
|
+
"sdt",
|
|
124
|
+
"smartTag",
|
|
125
|
+
"subDoc",
|
|
126
|
+
"wgp",
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
_USER_CONTENT_LOCAL_TAGS = frozenset(
|
|
131
|
+
{
|
|
132
|
+
"tab",
|
|
133
|
+
"br",
|
|
134
|
+
"cr",
|
|
135
|
+
"sym",
|
|
136
|
+
"noBreakHyphen",
|
|
137
|
+
"softHyphen",
|
|
138
|
+
"drawing",
|
|
139
|
+
"pict",
|
|
140
|
+
"tbl",
|
|
141
|
+
"hyperlink",
|
|
142
|
+
"fldSimple",
|
|
143
|
+
"fldChar",
|
|
144
|
+
"instrText",
|
|
145
|
+
"footnoteReference",
|
|
146
|
+
"endnoteReference",
|
|
147
|
+
"commentReference",
|
|
148
|
+
"subDoc",
|
|
149
|
+
"ptab",
|
|
150
|
+
"dayShort",
|
|
151
|
+
"monthShort",
|
|
152
|
+
"yearShort",
|
|
153
|
+
"dayLong",
|
|
154
|
+
"monthLong",
|
|
155
|
+
"yearLong",
|
|
156
|
+
"annotationRef",
|
|
157
|
+
"footnoteRef",
|
|
158
|
+
"endnoteRef",
|
|
159
|
+
"separator",
|
|
160
|
+
"continuationSeparator",
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _unrelated_parts_preserved(source: Path, candidate: Path, changed: frozenset[str]) -> bool:
|
|
166
|
+
"""True when every part the request did not change is the source part byte for byte."""
|
|
167
|
+
with (
|
|
168
|
+
zipfile.ZipFile(source) as before,
|
|
169
|
+
zipfile.ZipFile(candidate) as after,
|
|
170
|
+
):
|
|
171
|
+
names = set(after.namelist())
|
|
172
|
+
return all(
|
|
173
|
+
info.filename in names and before.read(info.filename) == after.read(info.filename)
|
|
174
|
+
for info in before.infolist()
|
|
175
|
+
if info.filename not in changed
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _has_forbidden_cell_descendant(element: ET.Element) -> bool:
|
|
180
|
+
"""True if element or any descendant has forbidden elements or IDs."""
|
|
181
|
+
for child in element.iter():
|
|
182
|
+
local = child.tag.rsplit("}", 1)[-1]
|
|
183
|
+
if local in _FORBIDDEN_CELL_ELEMENTS:
|
|
184
|
+
return True
|
|
185
|
+
for attr in child.attrib:
|
|
186
|
+
attr_local = attr.rsplit("}", 1)[-1]
|
|
187
|
+
if attr_local == "id":
|
|
188
|
+
return True
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _cell_has_user_content(cell: ET.Element, namespace: str) -> bool:
|
|
193
|
+
"""Return True if the cell contains user text, whitespace, control characters, or non-text payload."""
|
|
194
|
+
def word(local):
|
|
195
|
+
return Q(namespace, local)
|
|
196
|
+
for t_node in cell.iter(word("t")):
|
|
197
|
+
if t_node.text is not None and len(t_node.text) > 0:
|
|
198
|
+
return True
|
|
199
|
+
for child in cell.iter():
|
|
200
|
+
local = child.tag.rsplit("}", 1)[-1]
|
|
201
|
+
if local in _USER_CONTENT_LOCAL_TAGS:
|
|
202
|
+
return True
|
|
203
|
+
return len(cell.findall(word("p"))) > 1
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _get_cell_text(cell: ET.Element, namespace: str) -> str:
|
|
207
|
+
"""Extract plain text from all w:t descendants in the cell."""
|
|
208
|
+
def word(local):
|
|
209
|
+
return Q(namespace, local)
|
|
210
|
+
texts: list[str] = []
|
|
211
|
+
for t_node in cell.iter(word("t")):
|
|
212
|
+
if t_node.text:
|
|
213
|
+
texts.append(t_node.text)
|
|
214
|
+
return "".join(texts)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _cell_structure_projection(element: ET.Element) -> list[Any]:
|
|
218
|
+
"""Mask text inside w:t while preserving element hierarchy, attributes, and non-text values."""
|
|
219
|
+
return [
|
|
220
|
+
element.tag,
|
|
221
|
+
sorted(element.attrib.items()),
|
|
222
|
+
None if element.tag.rsplit("}", 1)[-1] == "t" else element.text,
|
|
223
|
+
element.tail,
|
|
224
|
+
[_cell_structure_projection(child) for child in element],
|
|
225
|
+
]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _is_supported_table(table: ET.Element, namespace: str) -> bool:
|
|
229
|
+
"""True if table has supported body table structure with explicit grid columns."""
|
|
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 _cell_hmerge_mode(cell: ET.Element, namespace: str) -> str | None:
|
|
245
|
+
"""Return the legacy hMerge mode ('restart', 'continue') or None when absent.
|
|
246
|
+
|
|
247
|
+
Raises ValueError on duplicate or invalid hMerge markup.
|
|
248
|
+
"""
|
|
249
|
+
def word(local):
|
|
250
|
+
return Q(namespace, local)
|
|
251
|
+
tc_pr = cell.find(word("tcPr"))
|
|
252
|
+
if tc_pr is None:
|
|
253
|
+
return None
|
|
254
|
+
h_merges = tc_pr.findall(word("hMerge"))
|
|
255
|
+
if not h_merges:
|
|
256
|
+
return None
|
|
257
|
+
if len(h_merges) > 1:
|
|
258
|
+
raise ValueError("duplicate_hMerge")
|
|
259
|
+
val = h_merges[0].get(word("val"))
|
|
260
|
+
if val is None or val == "continue":
|
|
261
|
+
return "continue"
|
|
262
|
+
if val == "restart":
|
|
263
|
+
return "restart"
|
|
264
|
+
raise ValueError("invalid_hMerge_val")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _cell_malformed_reason(
|
|
268
|
+
cell: ET.Element, namespace: str, *, legacy_hmerge: bool = False
|
|
269
|
+
) -> str | None:
|
|
270
|
+
"""Name the first malformed or unsupported merge marker of a cell, else None.
|
|
271
|
+
|
|
272
|
+
A legacy hMerge is reported as ``hMerge_unsupported`` unless ``legacy_hmerge`` admits it,
|
|
273
|
+
in which case it must be a well-formed, single-column marker.
|
|
274
|
+
"""
|
|
275
|
+
def word(local):
|
|
276
|
+
return Q(namespace, local)
|
|
277
|
+
tc_pr = cell.find(word("tcPr"))
|
|
278
|
+
if tc_pr is None:
|
|
279
|
+
return None
|
|
280
|
+
try:
|
|
281
|
+
span, _ = _cell_merge_state(cell, namespace, legacy_hmerge=legacy_hmerge)
|
|
282
|
+
if legacy_hmerge and tc_pr.find(word("hMerge")) is not None:
|
|
283
|
+
_cell_hmerge_mode(cell, namespace)
|
|
284
|
+
if span != 1:
|
|
285
|
+
return "hMerge_gridSpan_unsupported"
|
|
286
|
+
except ValueError as error:
|
|
287
|
+
return str(error)
|
|
288
|
+
return None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _row_legacy_hmerge_runs(row: ET.Element, namespace: str) -> list[tuple[int, int]] | None:
|
|
292
|
+
"""Return zero-based inclusive (first, last) cell indexes of every legacy hMerge run.
|
|
293
|
+
|
|
294
|
+
A run is a restart cell followed by one or more continue cells. Returns None when the
|
|
295
|
+
row's hMerge markup is malformed or a continue cell has no restart before it.
|
|
296
|
+
"""
|
|
297
|
+
runs: list[tuple[int, int]] = []
|
|
298
|
+
start: int | None = None
|
|
299
|
+
last = 0
|
|
300
|
+
for index, cell in enumerate(row.findall(Q(namespace, "tc"))):
|
|
301
|
+
try:
|
|
302
|
+
mode = _cell_hmerge_mode(cell, namespace)
|
|
303
|
+
except ValueError:
|
|
304
|
+
return None
|
|
305
|
+
if mode == "continue":
|
|
306
|
+
if start is None:
|
|
307
|
+
return None
|
|
308
|
+
last = index
|
|
309
|
+
continue
|
|
310
|
+
if start is not None and last > start:
|
|
311
|
+
runs.append((start, last))
|
|
312
|
+
start = index if mode == "restart" else None
|
|
313
|
+
last = index
|
|
314
|
+
if start is not None and last > start:
|
|
315
|
+
runs.append((start, last))
|
|
316
|
+
return runs
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _row_has_malformed_merge_markup(
|
|
320
|
+
row: ET.Element, namespace: str, *, legacy_hmerge: bool = False
|
|
321
|
+
) -> bool:
|
|
322
|
+
"""True if any cell in row has duplicate or invalid gridSpan/vMerge or unadmitted hMerge."""
|
|
323
|
+
for cell in row.findall(Q(namespace, "tc")):
|
|
324
|
+
if _cell_malformed_reason(cell, namespace, legacy_hmerge=legacy_hmerge) is not None:
|
|
325
|
+
return True
|
|
326
|
+
return legacy_hmerge and _row_legacy_hmerge_runs(row, namespace) is None
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _row_grid_mapping(
|
|
330
|
+
row: ET.Element,
|
|
331
|
+
num_grid_cols: int,
|
|
332
|
+
namespace: str,
|
|
333
|
+
*,
|
|
334
|
+
legacy_hmerge: bool = False,
|
|
335
|
+
) -> list[tuple[ET.Element, int, int]] | None:
|
|
336
|
+
"""Map each cell in row to (cell, col_start, col_end) (1-based, inclusive).
|
|
337
|
+
|
|
338
|
+
Returns None if the row's cells do not cleanly partition the grid columns.
|
|
339
|
+
"""
|
|
340
|
+
def word(local):
|
|
341
|
+
return Q(namespace, local)
|
|
342
|
+
cells = row.findall(word("tc"))
|
|
343
|
+
if not cells:
|
|
344
|
+
return None
|
|
345
|
+
mapping: list[tuple[ET.Element, int, int]] = []
|
|
346
|
+
current_col = 1
|
|
347
|
+
for cell in cells:
|
|
348
|
+
tc_pr = cell.find(word("tcPr"))
|
|
349
|
+
span = 1
|
|
350
|
+
if tc_pr is not None:
|
|
351
|
+
if tc_pr.find(word("hMerge")) is not None and not legacy_hmerge:
|
|
352
|
+
return None
|
|
353
|
+
grid_spans = tc_pr.findall(word("gridSpan"))
|
|
354
|
+
if len(grid_spans) > 1:
|
|
355
|
+
return None
|
|
356
|
+
if grid_spans:
|
|
357
|
+
val_str = grid_spans[0].get(word("val"))
|
|
358
|
+
if val_str is None:
|
|
359
|
+
return None
|
|
360
|
+
try:
|
|
361
|
+
span = int(val_str)
|
|
362
|
+
except (ValueError, TypeError):
|
|
363
|
+
return None
|
|
364
|
+
if span < 1:
|
|
365
|
+
return None
|
|
366
|
+
col_start = current_col
|
|
367
|
+
col_end = current_col + span - 1
|
|
368
|
+
if col_end > num_grid_cols:
|
|
369
|
+
return None
|
|
370
|
+
mapping.append((cell, col_start, col_end))
|
|
371
|
+
current_col += span
|
|
372
|
+
if current_col - 1 != num_grid_cols:
|
|
373
|
+
return None
|
|
374
|
+
return mapping
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _cell_merge_state(
|
|
378
|
+
cell: ET.Element, namespace: str, *, legacy_hmerge: bool = False
|
|
379
|
+
) -> tuple[int, str | None]:
|
|
380
|
+
"""Return (grid_span, v_merge_mode).
|
|
381
|
+
|
|
382
|
+
v_merge_mode is 'restart', 'continue', or None.
|
|
383
|
+
Raises ValueError on malformed or duplicate merge markup.
|
|
384
|
+
"""
|
|
385
|
+
def word(local):
|
|
386
|
+
return Q(namespace, local)
|
|
387
|
+
tc_pr = cell.find(word("tcPr"))
|
|
388
|
+
if tc_pr is None:
|
|
389
|
+
return 1, None
|
|
390
|
+
|
|
391
|
+
if tc_pr.find(word("hMerge")) is not None and not legacy_hmerge:
|
|
392
|
+
raise ValueError("hMerge_unsupported")
|
|
393
|
+
|
|
394
|
+
grid_spans = tc_pr.findall(word("gridSpan"))
|
|
395
|
+
if len(grid_spans) > 1:
|
|
396
|
+
raise ValueError("duplicate_gridSpan")
|
|
397
|
+
span = 1
|
|
398
|
+
if grid_spans:
|
|
399
|
+
val_str = grid_spans[0].get(word("val"))
|
|
400
|
+
if val_str is None:
|
|
401
|
+
raise ValueError("missing_gridSpan_val")
|
|
402
|
+
try:
|
|
403
|
+
span = int(val_str)
|
|
404
|
+
except (ValueError, TypeError):
|
|
405
|
+
raise ValueError("invalid_gridSpan_val") from None
|
|
406
|
+
if span < 1:
|
|
407
|
+
raise ValueError("invalid_gridSpan_val")
|
|
408
|
+
|
|
409
|
+
v_merges = tc_pr.findall(word("vMerge"))
|
|
410
|
+
if len(v_merges) > 1:
|
|
411
|
+
raise ValueError("duplicate_vMerge")
|
|
412
|
+
v_merge = None
|
|
413
|
+
if v_merges:
|
|
414
|
+
val = v_merges[0].get(word("val"))
|
|
415
|
+
if val is None or val == "continue":
|
|
416
|
+
v_merge = "continue"
|
|
417
|
+
elif val == "restart":
|
|
418
|
+
v_merge = "restart"
|
|
419
|
+
else:
|
|
420
|
+
raise ValueError("invalid_vMerge_val")
|
|
421
|
+
|
|
422
|
+
return span, v_merge
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _insert_or_replace_tcpr_child(tc_pr: ET.Element, new_child: ET.Element, namespace: str) -> None:
|
|
426
|
+
"""Insert or replace a child element in tcPr while maintaining schema order."""
|
|
427
|
+
local_name = new_child.tag.rsplit("}", 1)[-1]
|
|
428
|
+
def word(local):
|
|
429
|
+
return Q(namespace, local)
|
|
430
|
+
for existing in list(tc_pr.findall(word(local_name))):
|
|
431
|
+
tc_pr.remove(existing)
|
|
432
|
+
try:
|
|
433
|
+
new_order = _TCPR_ORDER.index(local_name)
|
|
434
|
+
except ValueError:
|
|
435
|
+
new_order = 999
|
|
436
|
+
insert_idx = len(tc_pr)
|
|
437
|
+
for idx, child in enumerate(tc_pr):
|
|
438
|
+
child_local = child.tag.rsplit("}", 1)[-1]
|
|
439
|
+
try:
|
|
440
|
+
child_order = _TCPR_ORDER.index(child_local)
|
|
441
|
+
except ValueError:
|
|
442
|
+
child_order = 999
|
|
443
|
+
if child_order > new_order:
|
|
444
|
+
insert_idx = idx
|
|
445
|
+
break
|
|
446
|
+
tc_pr.insert(insert_idx, new_child)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _remove_tcpr_child(tc_pr: ET.Element, local_name: str, namespace: str) -> None:
|
|
450
|
+
"""Remove any child matching local_name from tcPr."""
|
|
451
|
+
def word(local):
|
|
452
|
+
return Q(namespace, local)
|
|
453
|
+
for child in list(tc_pr.findall(word(local_name))):
|
|
454
|
+
tc_pr.remove(child)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _set_tc_width(tc_pr: ET.Element, width_val: int | str, namespace: str) -> None:
|
|
458
|
+
def word(local):
|
|
459
|
+
return Q(namespace, local)
|
|
460
|
+
tc_w = ET.Element(word("tcW"))
|
|
461
|
+
tc_w.set(word("w"), str(width_val))
|
|
462
|
+
tc_w.set(word("type"), "dxa")
|
|
463
|
+
_insert_or_replace_tcpr_child(tc_pr, tc_w, namespace)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _set_grid_span(tc_pr: ET.Element, span: int, namespace: str) -> None:
|
|
467
|
+
def word(local):
|
|
468
|
+
return Q(namespace, local)
|
|
469
|
+
gs = ET.Element(word("gridSpan"))
|
|
470
|
+
gs.set(word("val"), str(span))
|
|
471
|
+
_insert_or_replace_tcpr_child(tc_pr, gs, namespace)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _set_v_merge(tc_pr: ET.Element, mode: str, namespace: str) -> None:
|
|
475
|
+
def word(local):
|
|
476
|
+
return Q(namespace, local)
|
|
477
|
+
vm = ET.Element(word("vMerge"))
|
|
478
|
+
if mode == "restart":
|
|
479
|
+
vm.set(word("val"), "restart")
|
|
480
|
+
_insert_or_replace_tcpr_child(tc_pr, vm, namespace)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _create_split_cell(
|
|
484
|
+
prototype_tc_pr: ET.Element | None,
|
|
485
|
+
width_val: str | None,
|
|
486
|
+
namespace: str,
|
|
487
|
+
) -> ET.Element:
|
|
488
|
+
"""Create a new per-grid cell inheriting applicable properties without merge attributes."""
|
|
489
|
+
def word(local):
|
|
490
|
+
return Q(namespace, local)
|
|
491
|
+
new_tc = ET.Element(word("tc"))
|
|
492
|
+
new_tc_pr = ET.SubElement(new_tc, word("tcPr"))
|
|
493
|
+
if width_val is not None:
|
|
494
|
+
_set_tc_width(new_tc_pr, width_val, namespace)
|
|
495
|
+
if prototype_tc_pr is not None:
|
|
496
|
+
applicable_tags = ("tcBorders", "shd", "tcMar", "vAlign", "noWrap")
|
|
497
|
+
for tag in applicable_tags:
|
|
498
|
+
child = prototype_tc_pr.find(word(tag))
|
|
499
|
+
if child is not None:
|
|
500
|
+
new_child = copy.deepcopy(child)
|
|
501
|
+
_insert_or_replace_tcpr_child(new_tc_pr, new_child, namespace)
|
|
502
|
+
ET.SubElement(new_tc, word("p"))
|
|
503
|
+
return new_tc
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _validate_table_merge_target_dict(target: Mapping[str, Any]) -> dict[str, Any]:
|
|
507
|
+
"""Strictly validate and return an immutable copy of target coordinates."""
|
|
508
|
+
if not isinstance(target, Mapping):
|
|
509
|
+
raise TypeError("table_merge_target_invalid")
|
|
510
|
+
target_keys = set(target)
|
|
511
|
+
if not target_keys.issubset(_ALLOWED_TARGET_FIELDS) or not _REQUIRED_TARGET_FIELDS.issubset(
|
|
512
|
+
target_keys
|
|
513
|
+
):
|
|
514
|
+
raise ValueError("table_merge_target_fields_invalid")
|
|
515
|
+
|
|
516
|
+
table = target["table"]
|
|
517
|
+
if isinstance(table, bool) or not isinstance(table, int) or table < 1:
|
|
518
|
+
raise ValueError("table_merge_table_invalid")
|
|
519
|
+
|
|
520
|
+
start_row = target["start_row"]
|
|
521
|
+
if isinstance(start_row, bool) or not isinstance(start_row, int) or start_row < 1:
|
|
522
|
+
raise ValueError("table_merge_start_row_invalid")
|
|
523
|
+
|
|
524
|
+
end_row = target["end_row"]
|
|
525
|
+
if isinstance(end_row, bool) or not isinstance(end_row, int) or end_row < 1:
|
|
526
|
+
raise ValueError("table_merge_end_row_invalid")
|
|
527
|
+
|
|
528
|
+
start_col = target["start_col"]
|
|
529
|
+
if isinstance(start_col, bool) or not isinstance(start_col, int) or start_col < 1:
|
|
530
|
+
raise ValueError("table_merge_start_col_invalid")
|
|
531
|
+
|
|
532
|
+
end_col = target["end_col"]
|
|
533
|
+
if isinstance(end_col, bool) or not isinstance(end_col, int) or end_col < 1:
|
|
534
|
+
raise ValueError("table_merge_end_col_invalid")
|
|
535
|
+
|
|
536
|
+
if start_row > end_row or start_col > end_col:
|
|
537
|
+
raise ValueError("table_merge_coordinates_invalid")
|
|
538
|
+
|
|
539
|
+
part = target.get("part", _DOCUMENT)
|
|
540
|
+
if not isinstance(part, str) or not part:
|
|
541
|
+
raise ValueError("table_merge_part_invalid")
|
|
542
|
+
|
|
543
|
+
return {
|
|
544
|
+
"table": table,
|
|
545
|
+
"start_row": start_row,
|
|
546
|
+
"end_row": end_row,
|
|
547
|
+
"start_col": start_col,
|
|
548
|
+
"end_col": end_col,
|
|
549
|
+
"part": part,
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def table_merge_structure_fingerprint(
|
|
554
|
+
source: str | Path,
|
|
555
|
+
*,
|
|
556
|
+
table: int,
|
|
557
|
+
start_row: int,
|
|
558
|
+
end_row: int,
|
|
559
|
+
start_col: int,
|
|
560
|
+
end_col: int,
|
|
561
|
+
part: str = _DOCUMENT,
|
|
562
|
+
) -> str | None:
|
|
563
|
+
"""Return the source-bound structural fingerprint for a target table rectangle."""
|
|
564
|
+
path = Path(source)
|
|
565
|
+
if not path.is_file():
|
|
566
|
+
return None
|
|
567
|
+
try:
|
|
568
|
+
graph = PackageGraph.from_file(path)
|
|
569
|
+
valid_part, _ = _check_reachable_part(graph, part, "table_merge")
|
|
570
|
+
if not valid_part:
|
|
571
|
+
return None
|
|
572
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
573
|
+
ns = _word_namespace(root)
|
|
574
|
+
if ns is None:
|
|
575
|
+
return None
|
|
576
|
+
tables = list(root.iter(Q(ns, "tbl")))
|
|
577
|
+
if table < 1 or table > len(tables):
|
|
578
|
+
return None
|
|
579
|
+
target_table = tables[table - 1]
|
|
580
|
+
if not _is_supported_table(target_table, ns):
|
|
581
|
+
return None
|
|
582
|
+
tbl_grid = target_table.find(Q(ns, "tblGrid"))
|
|
583
|
+
if tbl_grid is None:
|
|
584
|
+
return None
|
|
585
|
+
grid_cols = tbl_grid.findall(Q(ns, "gridCol"))
|
|
586
|
+
if not grid_cols:
|
|
587
|
+
return None
|
|
588
|
+
rows = target_table.findall(Q(ns, "tr"))
|
|
589
|
+
if start_row < 1 or end_row > len(rows) or start_row > end_row:
|
|
590
|
+
return None
|
|
591
|
+
if start_col < 1 or end_col > len(grid_cols) or start_col > end_col:
|
|
592
|
+
return None
|
|
593
|
+
|
|
594
|
+
binding: dict[str, Any] = {
|
|
595
|
+
"table": table,
|
|
596
|
+
"start_row": start_row,
|
|
597
|
+
"end_row": end_row,
|
|
598
|
+
"start_col": start_col,
|
|
599
|
+
"end_col": end_col,
|
|
600
|
+
}
|
|
601
|
+
if part != _DOCUMENT:
|
|
602
|
+
binding["part"] = part
|
|
603
|
+
projections: list[Any] = [_cell_structure_projection(tbl_grid), binding]
|
|
604
|
+
for r_idx in range(start_row, end_row + 1):
|
|
605
|
+
row = rows[r_idx - 1]
|
|
606
|
+
if _row_has_malformed_merge_markup(row, ns, legacy_hmerge=True):
|
|
607
|
+
return None
|
|
608
|
+
mapping = _row_grid_mapping(row, len(grid_cols), ns, legacy_hmerge=True)
|
|
609
|
+
if mapping is None:
|
|
610
|
+
return None
|
|
611
|
+
for cell, c_start, c_end in mapping:
|
|
612
|
+
if not (c_end < start_col or c_start > end_col):
|
|
613
|
+
projections.append([r_idx, c_start, c_end, _cell_structure_projection(cell)])
|
|
614
|
+
|
|
615
|
+
canonical = json.dumps(projections, ensure_ascii=False, separators=(",", ":"))
|
|
616
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
617
|
+
except (PackageError, OSError, zipfile.BadZipFile, ET.ParseError, KeyError, ValueError):
|
|
618
|
+
return None
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
@dataclass(frozen=True)
|
|
622
|
+
class TableMergeTarget:
|
|
623
|
+
"""One discovered candidate table rectangle for merge or split authoring."""
|
|
624
|
+
|
|
625
|
+
table: int
|
|
626
|
+
start_row: int
|
|
627
|
+
end_row: int
|
|
628
|
+
start_col: int
|
|
629
|
+
end_col: int
|
|
630
|
+
structure_fingerprint_sha256: str
|
|
631
|
+
action: str
|
|
632
|
+
part: str = _DOCUMENT
|
|
633
|
+
origin_text: str = ""
|
|
634
|
+
is_merged: bool = False
|
|
635
|
+
|
|
636
|
+
@property
|
|
637
|
+
def target(self) -> dict[str, Any]:
|
|
638
|
+
return {
|
|
639
|
+
"part": self.part,
|
|
640
|
+
"table": self.table,
|
|
641
|
+
"start_row": self.start_row,
|
|
642
|
+
"end_row": self.end_row,
|
|
643
|
+
"start_col": self.start_col,
|
|
644
|
+
"end_col": self.end_col,
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
def to_dict(self) -> dict[str, Any]:
|
|
648
|
+
return {
|
|
649
|
+
"part": self.part,
|
|
650
|
+
"table": self.table,
|
|
651
|
+
"start_row": self.start_row,
|
|
652
|
+
"end_row": self.end_row,
|
|
653
|
+
"start_col": self.start_col,
|
|
654
|
+
"end_col": self.end_col,
|
|
655
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
656
|
+
"action": self.action,
|
|
657
|
+
"is_merged": self.is_merged,
|
|
658
|
+
"origin_text": self.origin_text,
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
@dataclass(frozen=True)
|
|
663
|
+
class TableMergeRequest:
|
|
664
|
+
"""One source-bound request to merge or split an explicit bounded table grid rectangle."""
|
|
665
|
+
|
|
666
|
+
source: Path
|
|
667
|
+
destination: Path
|
|
668
|
+
source_sha256: str
|
|
669
|
+
target: Mapping[str, Any]
|
|
670
|
+
structure_fingerprint_sha256: str
|
|
671
|
+
action: str = "merge"
|
|
672
|
+
|
|
673
|
+
def __post_init__(self) -> None:
|
|
674
|
+
if isinstance(self.source, str):
|
|
675
|
+
object.__setattr__(self, "source", Path(self.source))
|
|
676
|
+
elif not isinstance(self.source, Path):
|
|
677
|
+
raise TypeError("table_merge_source_invalid")
|
|
678
|
+
if not str(self.source):
|
|
679
|
+
raise ValueError("table_merge_source_invalid")
|
|
680
|
+
|
|
681
|
+
if isinstance(self.destination, str):
|
|
682
|
+
object.__setattr__(self, "destination", Path(self.destination))
|
|
683
|
+
elif not isinstance(self.destination, Path):
|
|
684
|
+
raise TypeError("table_merge_destination_invalid")
|
|
685
|
+
if not str(self.destination):
|
|
686
|
+
raise ValueError("table_merge_destination_invalid")
|
|
687
|
+
|
|
688
|
+
_require_sha256(self.source_sha256, "table_merge_source_sha256")
|
|
689
|
+
_require_sha256(
|
|
690
|
+
self.structure_fingerprint_sha256,
|
|
691
|
+
"table_merge_structure_fingerprint_sha256",
|
|
692
|
+
)
|
|
693
|
+
if not isinstance(self.action, str) or self.action not in ("merge", "split"):
|
|
694
|
+
raise ValueError("table_merge_action_invalid")
|
|
695
|
+
|
|
696
|
+
validated_target = _validate_table_merge_target_dict(self.target)
|
|
697
|
+
object.__setattr__(self, "target", validated_target)
|
|
698
|
+
|
|
699
|
+
@property
|
|
700
|
+
def table(self) -> int:
|
|
701
|
+
return self.target["table"]
|
|
702
|
+
|
|
703
|
+
@property
|
|
704
|
+
def start_row(self) -> int:
|
|
705
|
+
return self.target["start_row"]
|
|
706
|
+
|
|
707
|
+
@property
|
|
708
|
+
def end_row(self) -> int:
|
|
709
|
+
return self.target["end_row"]
|
|
710
|
+
|
|
711
|
+
@property
|
|
712
|
+
def start_col(self) -> int:
|
|
713
|
+
return self.target["start_col"]
|
|
714
|
+
|
|
715
|
+
@property
|
|
716
|
+
def end_col(self) -> int:
|
|
717
|
+
return self.target["end_col"]
|
|
718
|
+
|
|
719
|
+
@property
|
|
720
|
+
def part(self) -> str:
|
|
721
|
+
return self.target.get("part", _DOCUMENT)
|
|
722
|
+
|
|
723
|
+
def target_dict(self) -> dict[str, Any]:
|
|
724
|
+
return {
|
|
725
|
+
"part": self.part,
|
|
726
|
+
"table": self.table,
|
|
727
|
+
"start_row": self.start_row,
|
|
728
|
+
"end_row": self.end_row,
|
|
729
|
+
"start_col": self.start_col,
|
|
730
|
+
"end_col": self.end_col,
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
def to_dict(self) -> dict[str, Any]:
|
|
734
|
+
return {
|
|
735
|
+
"source": str(self.source),
|
|
736
|
+
"destination": str(self.destination),
|
|
737
|
+
"source_sha256": self.source_sha256,
|
|
738
|
+
"target": self.target_dict(),
|
|
739
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
740
|
+
"action": self.action,
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
@dataclass(frozen=True)
|
|
745
|
+
class TableMergeReport:
|
|
746
|
+
"""Content-safe public result for a table merge or split authoring request."""
|
|
747
|
+
|
|
748
|
+
status: str
|
|
749
|
+
code: str | None
|
|
750
|
+
source_sha256: str
|
|
751
|
+
destination_sha256: str | None = None
|
|
752
|
+
target: dict[str, Any] | None = None
|
|
753
|
+
target_change_report: dict[str, Any] | None = None
|
|
754
|
+
non_target_parts_preserved: bool | None = None
|
|
755
|
+
|
|
756
|
+
@property
|
|
757
|
+
def passed(self) -> bool:
|
|
758
|
+
return self.status == _PUBLISHED
|
|
759
|
+
|
|
760
|
+
def to_dict(self) -> dict[str, Any]:
|
|
761
|
+
return {
|
|
762
|
+
"schema_version": 1,
|
|
763
|
+
"operation": "table-merge",
|
|
764
|
+
"passed": self.passed,
|
|
765
|
+
"status": self.status,
|
|
766
|
+
"code": self.code,
|
|
767
|
+
"source_sha256": self.source_sha256,
|
|
768
|
+
"destination_sha256": self.destination_sha256,
|
|
769
|
+
"target": self.target,
|
|
770
|
+
"target_change_report": self.target_change_report,
|
|
771
|
+
"non_target_parts_preserved": self.non_target_parts_preserved,
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _table_merge_refusal(
|
|
776
|
+
request: TableMergeRequest,
|
|
777
|
+
code: str,
|
|
778
|
+
target: dict[str, Any] | None = None,
|
|
779
|
+
change_report: dict[str, Any] | None = None,
|
|
780
|
+
) -> TableMergeReport:
|
|
781
|
+
return TableMergeReport(
|
|
782
|
+
status=_REFUSED,
|
|
783
|
+
code=code,
|
|
784
|
+
source_sha256=request.source_sha256,
|
|
785
|
+
destination_sha256=None,
|
|
786
|
+
target=target if target is not None else request.target_dict(),
|
|
787
|
+
target_change_report=change_report,
|
|
788
|
+
non_target_parts_preserved=None,
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def parse_table_merge_request(value: Any) -> TableMergeRequest:
|
|
793
|
+
"""Parse and strictly validate a table cell merge or split authoring request."""
|
|
794
|
+
if not isinstance(value, Mapping):
|
|
795
|
+
raise TypeError("table_merge_request_invalid")
|
|
796
|
+
|
|
797
|
+
keys = set(value)
|
|
798
|
+
if not keys.issubset(_ALLOWED_REQUEST_FIELDS) or not _REQUIRED_REQUEST_FIELDS.issubset(keys):
|
|
799
|
+
raise ValueError("table_merge_request_fields_invalid")
|
|
800
|
+
|
|
801
|
+
source = value["source"]
|
|
802
|
+
if not isinstance(source, str) or not source:
|
|
803
|
+
raise ValueError("table_merge_source_invalid")
|
|
804
|
+
|
|
805
|
+
destination = value["destination"]
|
|
806
|
+
if not isinstance(destination, str) or not destination:
|
|
807
|
+
raise ValueError("table_merge_destination_invalid")
|
|
808
|
+
|
|
809
|
+
action = value.get("action", "merge")
|
|
810
|
+
if not isinstance(action, str) or action not in ("merge", "split"):
|
|
811
|
+
raise ValueError("table_merge_action_invalid")
|
|
812
|
+
|
|
813
|
+
return TableMergeRequest(
|
|
814
|
+
source=Path(source),
|
|
815
|
+
destination=Path(destination),
|
|
816
|
+
source_sha256=value["source_sha256"],
|
|
817
|
+
target=value["target"],
|
|
818
|
+
structure_fingerprint_sha256=value["structure_fingerprint_sha256"],
|
|
819
|
+
action=action,
|
|
820
|
+
)
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def load_table_merge_request(path: str | Path) -> TableMergeRequest:
|
|
824
|
+
"""Load and strictly validate one JSON table-merge request from disk."""
|
|
825
|
+
with Path(path).open("r", encoding="utf-8") as stream:
|
|
826
|
+
return parse_table_merge_request(json.load(stream))
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def discover_table_merge_targets(
|
|
830
|
+
source: str | Path,
|
|
831
|
+
*,
|
|
832
|
+
part: str = _DOCUMENT,
|
|
833
|
+
) -> dict[str, Any]:
|
|
834
|
+
"""Inventory source-bound candidate table cell merge and split targets for authoring."""
|
|
835
|
+
path = Path(source)
|
|
836
|
+
if not path.is_file():
|
|
837
|
+
return {
|
|
838
|
+
"schema_version": 1,
|
|
839
|
+
"operation": "table-merge-targets",
|
|
840
|
+
"passed": False,
|
|
841
|
+
"status": _REFUSED,
|
|
842
|
+
"code": "table_merge_source_missing",
|
|
843
|
+
"source_sha256": None,
|
|
844
|
+
"part": part,
|
|
845
|
+
"targets": [],
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
try:
|
|
849
|
+
source_sha256 = _sha256_file(path)
|
|
850
|
+
graph = PackageGraph.from_file(path)
|
|
851
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
852
|
+
return {
|
|
853
|
+
"schema_version": 1,
|
|
854
|
+
"operation": "table-merge-targets",
|
|
855
|
+
"passed": False,
|
|
856
|
+
"status": _REFUSED,
|
|
857
|
+
"code": "table_merge_package_invalid",
|
|
858
|
+
"source_sha256": None,
|
|
859
|
+
"part": part,
|
|
860
|
+
"targets": [],
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
valid_part, part_err = _check_reachable_part(graph, part, "table_merge")
|
|
864
|
+
if not valid_part:
|
|
865
|
+
return {
|
|
866
|
+
"schema_version": 1,
|
|
867
|
+
"operation": "table-merge-targets",
|
|
868
|
+
"passed": False,
|
|
869
|
+
"status": _REFUSED,
|
|
870
|
+
"code": part_err or "table_merge_part_unsupported",
|
|
871
|
+
"source_sha256": source_sha256,
|
|
872
|
+
"part": part,
|
|
873
|
+
"targets": [],
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
try:
|
|
877
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
878
|
+
except (ET.ParseError, KeyError):
|
|
879
|
+
return {
|
|
880
|
+
"schema_version": 1,
|
|
881
|
+
"operation": "table-merge-targets",
|
|
882
|
+
"passed": False,
|
|
883
|
+
"status": _REFUSED,
|
|
884
|
+
"code": "table_merge_package_invalid",
|
|
885
|
+
"source_sha256": source_sha256,
|
|
886
|
+
"part": part,
|
|
887
|
+
"targets": [],
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
namespace = _word_namespace(root)
|
|
891
|
+
if namespace is None:
|
|
892
|
+
return {
|
|
893
|
+
"schema_version": 1,
|
|
894
|
+
"operation": "table-merge-targets",
|
|
895
|
+
"passed": False,
|
|
896
|
+
"status": _REFUSED,
|
|
897
|
+
"code": "table_merge_namespace_unsupported",
|
|
898
|
+
"source_sha256": source_sha256,
|
|
899
|
+
"part": part,
|
|
900
|
+
"targets": [],
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
904
|
+
tables = list(root.iter(Q(namespace, "tbl")))
|
|
905
|
+
targets: list[dict[str, Any]] = []
|
|
906
|
+
|
|
907
|
+
for table_idx, table in enumerate(tables, start=1):
|
|
908
|
+
if unsupported_context.get(id(table), False):
|
|
909
|
+
continue
|
|
910
|
+
if not _is_supported_table(table, namespace):
|
|
911
|
+
continue
|
|
912
|
+
tbl_grid = table.find(Q(namespace, "tblGrid"))
|
|
913
|
+
grid_cols = tbl_grid.findall(Q(namespace, "gridCol")) if tbl_grid is not None else []
|
|
914
|
+
num_grid_cols = len(grid_cols)
|
|
915
|
+
if num_grid_cols == 0:
|
|
916
|
+
continue
|
|
917
|
+
rows = table.findall(Q(namespace, "tr"))
|
|
918
|
+
if not rows:
|
|
919
|
+
continue
|
|
920
|
+
|
|
921
|
+
row_mappings: list[list[tuple[ET.Element, int, int]]] = []
|
|
922
|
+
table_grid_valid = True
|
|
923
|
+
for row in rows:
|
|
924
|
+
if unsupported_context.get(id(row), False):
|
|
925
|
+
table_grid_valid = False
|
|
926
|
+
break
|
|
927
|
+
if _row_has_malformed_merge_markup(row, namespace, legacy_hmerge=True):
|
|
928
|
+
table_grid_valid = False
|
|
929
|
+
break
|
|
930
|
+
mapping = _row_grid_mapping(row, num_grid_cols, namespace, legacy_hmerge=True)
|
|
931
|
+
if mapping is None:
|
|
932
|
+
table_grid_valid = False
|
|
933
|
+
break
|
|
934
|
+
row_mappings.append(mapping)
|
|
935
|
+
if not table_grid_valid:
|
|
936
|
+
continue
|
|
937
|
+
|
|
938
|
+
# 0. Legacy hMerge tables: mutation is refused table-wide, so only the split regions
|
|
939
|
+
# themselves are inventoried; each names the restart cell and its continue cells.
|
|
940
|
+
if any(
|
|
941
|
+
_cell_hmerge_mode(cell, namespace) is not None
|
|
942
|
+
for mapping in row_mappings
|
|
943
|
+
for cell, _, _ in mapping
|
|
944
|
+
):
|
|
945
|
+
for r_idx, row in enumerate(rows, start=1):
|
|
946
|
+
mapping = row_mappings[r_idx - 1]
|
|
947
|
+
for first, last in _row_legacy_hmerge_runs(row, namespace) or []:
|
|
948
|
+
run_cells = mapping[first : last + 1]
|
|
949
|
+
if any(
|
|
950
|
+
_cell_merge_state(run_cell, namespace, legacy_hmerge=True)[1] is not None
|
|
951
|
+
for run_cell, _, _ in run_cells
|
|
952
|
+
):
|
|
953
|
+
continue
|
|
954
|
+
run_start, run_end = mapping[first][1], mapping[last][2]
|
|
955
|
+
fp = table_merge_structure_fingerprint(
|
|
956
|
+
source,
|
|
957
|
+
table=table_idx,
|
|
958
|
+
start_row=r_idx,
|
|
959
|
+
end_row=r_idx,
|
|
960
|
+
start_col=run_start,
|
|
961
|
+
end_col=run_end,
|
|
962
|
+
part=part,
|
|
963
|
+
)
|
|
964
|
+
if fp is not None:
|
|
965
|
+
target = TableMergeTarget(
|
|
966
|
+
table=table_idx,
|
|
967
|
+
start_row=r_idx,
|
|
968
|
+
end_row=r_idx,
|
|
969
|
+
start_col=run_start,
|
|
970
|
+
end_col=run_end,
|
|
971
|
+
structure_fingerprint_sha256=fp,
|
|
972
|
+
action="split",
|
|
973
|
+
part=part,
|
|
974
|
+
origin_text=_get_cell_text(mapping[first][0], namespace),
|
|
975
|
+
is_merged=True,
|
|
976
|
+
)
|
|
977
|
+
targets.append(target.to_dict())
|
|
978
|
+
continue
|
|
979
|
+
|
|
980
|
+
# 1. Discover existing merges (splittable targets)
|
|
981
|
+
visited_vertical: set[tuple[int, int]] = set()
|
|
982
|
+
for r_idx, row in enumerate(rows, start=1):
|
|
983
|
+
mapping = row_mappings[r_idx - 1]
|
|
984
|
+
for cell, c_start, c_end in mapping:
|
|
985
|
+
if (r_idx, c_start) in visited_vertical:
|
|
986
|
+
continue
|
|
987
|
+
try:
|
|
988
|
+
span, v_merge = _cell_merge_state(cell, namespace)
|
|
989
|
+
except ValueError:
|
|
990
|
+
continue
|
|
991
|
+
if v_merge == "restart":
|
|
992
|
+
end_r = r_idx
|
|
993
|
+
while end_r + 1 <= len(rows):
|
|
994
|
+
next_mapping = row_mappings[end_r]
|
|
995
|
+
next_cell = None
|
|
996
|
+
for c_elem, n_cs, n_ce in next_mapping:
|
|
997
|
+
if n_cs == c_start and n_ce == c_end:
|
|
998
|
+
next_cell = c_elem
|
|
999
|
+
break
|
|
1000
|
+
if next_cell is None:
|
|
1001
|
+
break
|
|
1002
|
+
try:
|
|
1003
|
+
n_span, n_vmerge = _cell_merge_state(next_cell, namespace)
|
|
1004
|
+
except ValueError:
|
|
1005
|
+
break
|
|
1006
|
+
if n_vmerge != "continue" or n_span != span:
|
|
1007
|
+
break
|
|
1008
|
+
visited_vertical.add((end_r + 1, c_start))
|
|
1009
|
+
end_r += 1
|
|
1010
|
+
if end_r > r_idx:
|
|
1011
|
+
fp = table_merge_structure_fingerprint(
|
|
1012
|
+
source,
|
|
1013
|
+
table=table_idx,
|
|
1014
|
+
start_row=r_idx,
|
|
1015
|
+
end_row=end_r,
|
|
1016
|
+
start_col=c_start,
|
|
1017
|
+
end_col=c_end,
|
|
1018
|
+
part=part,
|
|
1019
|
+
)
|
|
1020
|
+
if fp is not None:
|
|
1021
|
+
target = TableMergeTarget(
|
|
1022
|
+
table=table_idx,
|
|
1023
|
+
start_row=r_idx,
|
|
1024
|
+
end_row=end_r,
|
|
1025
|
+
start_col=c_start,
|
|
1026
|
+
end_col=c_end,
|
|
1027
|
+
structure_fingerprint_sha256=fp,
|
|
1028
|
+
action="split",
|
|
1029
|
+
part=part,
|
|
1030
|
+
origin_text=_get_cell_text(cell, namespace),
|
|
1031
|
+
is_merged=True,
|
|
1032
|
+
)
|
|
1033
|
+
targets.append(target.to_dict())
|
|
1034
|
+
continue
|
|
1035
|
+
|
|
1036
|
+
if c_end > c_start and v_merge is None:
|
|
1037
|
+
fp = table_merge_structure_fingerprint(
|
|
1038
|
+
source,
|
|
1039
|
+
table=table_idx,
|
|
1040
|
+
start_row=r_idx,
|
|
1041
|
+
end_row=r_idx,
|
|
1042
|
+
start_col=c_start,
|
|
1043
|
+
end_col=c_end,
|
|
1044
|
+
part=part,
|
|
1045
|
+
)
|
|
1046
|
+
if fp is not None:
|
|
1047
|
+
target = TableMergeTarget(
|
|
1048
|
+
table=table_idx,
|
|
1049
|
+
start_row=r_idx,
|
|
1050
|
+
end_row=r_idx,
|
|
1051
|
+
start_col=c_start,
|
|
1052
|
+
end_col=c_end,
|
|
1053
|
+
structure_fingerprint_sha256=fp,
|
|
1054
|
+
action="split",
|
|
1055
|
+
part=part,
|
|
1056
|
+
origin_text=_get_cell_text(cell, namespace),
|
|
1057
|
+
is_merged=True,
|
|
1058
|
+
)
|
|
1059
|
+
targets.append(target.to_dict())
|
|
1060
|
+
|
|
1061
|
+
# 2. Discover unmerged merge candidates (adjacent cells without content loss)
|
|
1062
|
+
for r_idx, row in enumerate(rows, start=1):
|
|
1063
|
+
mapping = row_mappings[r_idx - 1]
|
|
1064
|
+
for idx in range(len(mapping) - 1):
|
|
1065
|
+
c1, c1_s, _c1_e = mapping[idx]
|
|
1066
|
+
c2, _c2_s, c2_e = mapping[idx + 1]
|
|
1067
|
+
try:
|
|
1068
|
+
s1, vm1 = _cell_merge_state(c1, namespace)
|
|
1069
|
+
s2, vm2 = _cell_merge_state(c2, namespace)
|
|
1070
|
+
except ValueError:
|
|
1071
|
+
continue
|
|
1072
|
+
if (
|
|
1073
|
+
s1 == 1
|
|
1074
|
+
and s2 == 1
|
|
1075
|
+
and vm1 is None
|
|
1076
|
+
and vm2 is None
|
|
1077
|
+
and not _cell_has_user_content(c2, namespace)
|
|
1078
|
+
):
|
|
1079
|
+
fp = table_merge_structure_fingerprint(
|
|
1080
|
+
source,
|
|
1081
|
+
table=table_idx,
|
|
1082
|
+
start_row=r_idx,
|
|
1083
|
+
end_row=r_idx,
|
|
1084
|
+
start_col=c1_s,
|
|
1085
|
+
end_col=c2_e,
|
|
1086
|
+
part=part,
|
|
1087
|
+
)
|
|
1088
|
+
if fp is not None:
|
|
1089
|
+
target = TableMergeTarget(
|
|
1090
|
+
table=table_idx,
|
|
1091
|
+
start_row=r_idx,
|
|
1092
|
+
end_row=r_idx,
|
|
1093
|
+
start_col=c1_s,
|
|
1094
|
+
end_col=c2_e,
|
|
1095
|
+
structure_fingerprint_sha256=fp,
|
|
1096
|
+
action="merge",
|
|
1097
|
+
part=part,
|
|
1098
|
+
origin_text=_get_cell_text(c1, namespace),
|
|
1099
|
+
is_merged=False,
|
|
1100
|
+
)
|
|
1101
|
+
targets.append(target.to_dict())
|
|
1102
|
+
|
|
1103
|
+
return {
|
|
1104
|
+
"schema_version": 1,
|
|
1105
|
+
"operation": "table-merge-targets",
|
|
1106
|
+
"passed": True,
|
|
1107
|
+
"status": "discovered",
|
|
1108
|
+
"code": None,
|
|
1109
|
+
"source_sha256": source_sha256,
|
|
1110
|
+
"part": part,
|
|
1111
|
+
"targets": targets,
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
_MERGE_OWNED_TCPR = frozenset({"tcW", "gridSpan", "vMerge"})
|
|
1116
|
+
_FAILED_VERIFICATION = "table_merge_staged_verification_failed"
|
|
1117
|
+
|
|
1118
|
+
|
|
1119
|
+
def _conflict_report(
|
|
1120
|
+
request: TableMergeRequest,
|
|
1121
|
+
reason: str,
|
|
1122
|
+
row: int,
|
|
1123
|
+
cell: int | None,
|
|
1124
|
+
**details: Any,
|
|
1125
|
+
) -> dict[str, Any]:
|
|
1126
|
+
"""Content-safe refusal report naming the exact one-based row and cell in conflict."""
|
|
1127
|
+
return {
|
|
1128
|
+
"table": request.table,
|
|
1129
|
+
"action": request.action,
|
|
1130
|
+
"part": request.part,
|
|
1131
|
+
"start_row": request.start_row,
|
|
1132
|
+
"end_row": request.end_row,
|
|
1133
|
+
"start_col": request.start_col,
|
|
1134
|
+
"end_col": request.end_col,
|
|
1135
|
+
"reason": reason,
|
|
1136
|
+
"row": row,
|
|
1137
|
+
"cell": cell,
|
|
1138
|
+
**details,
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
def _first_unsupported_merge_cell(
|
|
1143
|
+
request: TableMergeRequest, rows: list[ET.Element], namespace: str
|
|
1144
|
+
) -> dict[str, Any] | None:
|
|
1145
|
+
"""Locate the first cell with malformed or legacy hMerge markup, requested rows first."""
|
|
1146
|
+
requested = list(range(request.start_row, request.end_row + 1))
|
|
1147
|
+
others = [index for index in range(1, len(rows) + 1) if index not in requested]
|
|
1148
|
+
for r_idx in (*requested, *others):
|
|
1149
|
+
for ordinal, cell in enumerate(rows[r_idx - 1].findall(Q(namespace, "tc")), start=1):
|
|
1150
|
+
reason = _cell_malformed_reason(cell, namespace)
|
|
1151
|
+
if reason is None:
|
|
1152
|
+
continue
|
|
1153
|
+
details: dict[str, Any] = {}
|
|
1154
|
+
if reason == "hMerge_unsupported":
|
|
1155
|
+
try:
|
|
1156
|
+
details["h_merge"] = _cell_hmerge_mode(cell, namespace)
|
|
1157
|
+
except ValueError:
|
|
1158
|
+
details["h_merge"] = None
|
|
1159
|
+
return _conflict_report(request, reason, r_idx, ordinal, **details)
|
|
1160
|
+
return None
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def _entry_at(
|
|
1164
|
+
entries: list[tuple[int, ET.Element, int, int]], column: int
|
|
1165
|
+
) -> tuple[int, ET.Element, int, int] | None:
|
|
1166
|
+
"""The (ordinal, cell, col_start, col_end) entry whose columns cover ``column``."""
|
|
1167
|
+
for entry in entries:
|
|
1168
|
+
if entry[2] <= column <= entry[3]:
|
|
1169
|
+
return entry
|
|
1170
|
+
return None
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
def _signature_outside_table(root: ET.Element, table: ET.Element) -> bytes | None:
|
|
1174
|
+
"""Serialize the whole part with ``table`` masked out; the tree is restored afterwards."""
|
|
1175
|
+
for parent in root.iter():
|
|
1176
|
+
for index, child in enumerate(parent):
|
|
1177
|
+
if child is table:
|
|
1178
|
+
marker = ET.Element("table-merge-target")
|
|
1179
|
+
marker.tail = table.tail
|
|
1180
|
+
parent[index] = marker
|
|
1181
|
+
try:
|
|
1182
|
+
return ET.tostring(root)
|
|
1183
|
+
finally:
|
|
1184
|
+
parent[index] = table
|
|
1185
|
+
return None
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
def _cell_preserved_projection(
|
|
1189
|
+
cell: ET.Element, namespace: str, owned: frozenset[str]
|
|
1190
|
+
) -> tuple[list[bytes], list[bytes]]:
|
|
1191
|
+
"""(tcPr children not in ``owned``, non-tcPr children) of a cell, serialized in order."""
|
|
1192
|
+
tc_pr = cell.find(Q(namespace, "tcPr"))
|
|
1193
|
+
props = (
|
|
1194
|
+
[]
|
|
1195
|
+
if tc_pr is None
|
|
1196
|
+
else [ET.tostring(child) for child in tc_pr if child.tag.rsplit("}", 1)[-1] not in owned]
|
|
1197
|
+
)
|
|
1198
|
+
return props, [ET.tostring(child) for child in cell if child is not tc_pr]
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def author_table_merge(request: TableMergeRequest) -> TableMergeReport:
|
|
1202
|
+
"""Execute a source-bound table cell merge or split authoring request atomically."""
|
|
1203
|
+
if not isinstance(request, TableMergeRequest):
|
|
1204
|
+
raise TypeError("table_merge_request_invalid")
|
|
1205
|
+
|
|
1206
|
+
if request.action not in ("merge", "split"):
|
|
1207
|
+
return _table_merge_refusal(request, "table_merge_action_invalid")
|
|
1208
|
+
|
|
1209
|
+
if request.start_row > request.end_row or request.start_col > request.end_col:
|
|
1210
|
+
return _table_merge_refusal(request, "table_merge_coordinates_invalid")
|
|
1211
|
+
|
|
1212
|
+
source = request.source
|
|
1213
|
+
destination = request.destination
|
|
1214
|
+
|
|
1215
|
+
if not source.is_file():
|
|
1216
|
+
return _table_merge_refusal(request, "table_merge_source_missing")
|
|
1217
|
+
if source == destination:
|
|
1218
|
+
return _table_merge_refusal(request, "table_merge_destination_invalid")
|
|
1219
|
+
if not destination.parent.is_dir():
|
|
1220
|
+
return _table_merge_refusal(request, "table_merge_destination_invalid")
|
|
1221
|
+
if destination.exists() or destination.is_symlink():
|
|
1222
|
+
return _table_merge_refusal(request, "table_merge_destination_occupied")
|
|
1223
|
+
|
|
1224
|
+
try:
|
|
1225
|
+
actual_source_sha256 = _sha256_file(source)
|
|
1226
|
+
except OSError:
|
|
1227
|
+
return _table_merge_refusal(request, "table_merge_source_missing")
|
|
1228
|
+
|
|
1229
|
+
if actual_source_sha256 != request.source_sha256:
|
|
1230
|
+
return _table_merge_refusal(request, "table_merge_source_hash_mismatch")
|
|
1231
|
+
|
|
1232
|
+
try:
|
|
1233
|
+
graph = PackageGraph.from_file(source)
|
|
1234
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
1235
|
+
return _table_merge_refusal(request, "table_merge_package_invalid")
|
|
1236
|
+
|
|
1237
|
+
if request.part == _DOCUMENT and _DOCUMENT not in graph.parts:
|
|
1238
|
+
return _table_merge_refusal(request, "table_merge_package_invalid")
|
|
1239
|
+
|
|
1240
|
+
valid_part, part_err = _check_reachable_part(graph, request.part, "table_merge")
|
|
1241
|
+
if not valid_part:
|
|
1242
|
+
return _table_merge_refusal(request, part_err or "table_merge_part_unsupported")
|
|
1243
|
+
|
|
1244
|
+
try:
|
|
1245
|
+
part_bytes = graph.read_part_bytes(request.part)
|
|
1246
|
+
root = parse_xml_with_preserved_qnames(part_bytes)
|
|
1247
|
+
except (KeyError, ET.ParseError):
|
|
1248
|
+
return _table_merge_refusal(request, "table_merge_package_invalid")
|
|
1249
|
+
|
|
1250
|
+
namespace = _word_namespace(root)
|
|
1251
|
+
if namespace is None:
|
|
1252
|
+
return _table_merge_refusal(request, "table_merge_namespace_unsupported")
|
|
1253
|
+
|
|
1254
|
+
def word(local):
|
|
1255
|
+
return Q(namespace, local)
|
|
1256
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
1257
|
+
tables = list(root.iter(word("tbl")))
|
|
1258
|
+
if request.table < 1 or request.table > len(tables):
|
|
1259
|
+
return _table_merge_refusal(request, "table_merge_target_missing")
|
|
1260
|
+
|
|
1261
|
+
table = tables[request.table - 1]
|
|
1262
|
+
if unsupported_context.get(id(table), False):
|
|
1263
|
+
return _table_merge_refusal(request, "table_merge_context_unsupported")
|
|
1264
|
+
|
|
1265
|
+
if not _is_supported_table(table, namespace):
|
|
1266
|
+
return _table_merge_refusal(request, "table_merge_table_unsupported")
|
|
1267
|
+
|
|
1268
|
+
tbl_grid = table.find(word("tblGrid"))
|
|
1269
|
+
grid_cols = tbl_grid.findall(word("gridCol")) if tbl_grid is not None else []
|
|
1270
|
+
num_grid_cols = len(grid_cols)
|
|
1271
|
+
if num_grid_cols == 0:
|
|
1272
|
+
return _table_merge_refusal(request, "table_merge_grid_mismatch")
|
|
1273
|
+
|
|
1274
|
+
rows = table.findall(word("tr"))
|
|
1275
|
+
if not rows:
|
|
1276
|
+
return _table_merge_refusal(request, "table_merge_table_unsupported")
|
|
1277
|
+
|
|
1278
|
+
if (
|
|
1279
|
+
request.start_row < 1
|
|
1280
|
+
or request.end_row > len(rows)
|
|
1281
|
+
or request.start_col < 1
|
|
1282
|
+
or request.end_col > num_grid_cols
|
|
1283
|
+
):
|
|
1284
|
+
return _table_merge_refusal(request, "table_merge_target_missing")
|
|
1285
|
+
|
|
1286
|
+
# Any malformed markup or legacy hMerge anywhere in the table refuses the whole table,
|
|
1287
|
+
# naming the exact row and cell so nothing is silently canonicalized or dropped.
|
|
1288
|
+
unsupported_markup = _first_unsupported_merge_cell(request, rows, namespace)
|
|
1289
|
+
if unsupported_markup is not None:
|
|
1290
|
+
return _table_merge_refusal(
|
|
1291
|
+
request, "table_merge_structure_unsupported", change_report=unsupported_markup
|
|
1292
|
+
)
|
|
1293
|
+
|
|
1294
|
+
for r_idx in range(request.start_row, request.end_row + 1):
|
|
1295
|
+
row = rows[r_idx - 1]
|
|
1296
|
+
if unsupported_context.get(id(row), False):
|
|
1297
|
+
return _table_merge_refusal(request, "table_merge_context_unsupported")
|
|
1298
|
+
|
|
1299
|
+
row_mappings: list[list[tuple[ET.Element, int, int]]] = []
|
|
1300
|
+
for row in rows:
|
|
1301
|
+
mapping = _row_grid_mapping(row, num_grid_cols, namespace)
|
|
1302
|
+
if mapping is None:
|
|
1303
|
+
return _table_merge_refusal(request, "table_merge_grid_mismatch")
|
|
1304
|
+
row_mappings.append(mapping)
|
|
1305
|
+
entries = [
|
|
1306
|
+
[(ordinal, cell, c_start, c_end) for ordinal, (cell, c_start, c_end) in enumerate(m, 1)]
|
|
1307
|
+
for m in row_mappings
|
|
1308
|
+
]
|
|
1309
|
+
|
|
1310
|
+
def cell_refusal(
|
|
1311
|
+
code: str, reason: str, r_idx: int, entry: tuple[int, ET.Element, int, int]
|
|
1312
|
+
) -> TableMergeReport:
|
|
1313
|
+
ordinal, conflict_cell, c_start, c_end = entry
|
|
1314
|
+
try:
|
|
1315
|
+
c_span, c_vmerge = _cell_merge_state(conflict_cell, namespace)
|
|
1316
|
+
except ValueError:
|
|
1317
|
+
c_span, c_vmerge = None, None
|
|
1318
|
+
return _table_merge_refusal(
|
|
1319
|
+
request,
|
|
1320
|
+
code,
|
|
1321
|
+
change_report=_conflict_report(
|
|
1322
|
+
request,
|
|
1323
|
+
reason,
|
|
1324
|
+
r_idx,
|
|
1325
|
+
ordinal,
|
|
1326
|
+
cell_start_col=c_start,
|
|
1327
|
+
cell_end_col=c_end,
|
|
1328
|
+
cell_grid_span=c_span,
|
|
1329
|
+
cell_v_merge=c_vmerge,
|
|
1330
|
+
),
|
|
1331
|
+
)
|
|
1332
|
+
|
|
1333
|
+
# Require valid positive explicit affected grid widths (no silent skipped sizing)
|
|
1334
|
+
col_widths: list[int] = []
|
|
1335
|
+
for c in range(request.start_col, request.end_col + 1):
|
|
1336
|
+
w_attr = grid_cols[c - 1].get(word("w"))
|
|
1337
|
+
if w_attr is None:
|
|
1338
|
+
return _table_merge_refusal(request, "table_merge_grid_mismatch")
|
|
1339
|
+
try:
|
|
1340
|
+
col_w = int(w_attr)
|
|
1341
|
+
if col_w <= 0:
|
|
1342
|
+
return _table_merge_refusal(request, "table_merge_grid_mismatch")
|
|
1343
|
+
except (ValueError, TypeError):
|
|
1344
|
+
return _table_merge_refusal(request, "table_merge_grid_mismatch")
|
|
1345
|
+
col_widths.append(col_w)
|
|
1346
|
+
total_width = sum(col_widths)
|
|
1347
|
+
|
|
1348
|
+
actual_fp = table_merge_structure_fingerprint(
|
|
1349
|
+
source,
|
|
1350
|
+
table=request.table,
|
|
1351
|
+
start_row=request.start_row,
|
|
1352
|
+
end_row=request.end_row,
|
|
1353
|
+
start_col=request.start_col,
|
|
1354
|
+
end_col=request.end_col,
|
|
1355
|
+
part=request.part,
|
|
1356
|
+
)
|
|
1357
|
+
if actual_fp != request.structure_fingerprint_sha256:
|
|
1358
|
+
return _table_merge_refusal(request, "table_merge_structure_fingerprint_mismatch")
|
|
1359
|
+
|
|
1360
|
+
col_span = request.end_col - request.start_col + 1
|
|
1361
|
+
row_span = request.end_row - request.start_row + 1
|
|
1362
|
+
|
|
1363
|
+
if col_span == 1 and row_span == 1:
|
|
1364
|
+
return _table_merge_refusal(request, "table_merge_geometry_unsupported")
|
|
1365
|
+
|
|
1366
|
+
# Pristine references for staged verification; the live tree is mutated below.
|
|
1367
|
+
pristine_table = copy.deepcopy(table)
|
|
1368
|
+
outside_before = _signature_outside_table(root, table)
|
|
1369
|
+
if outside_before is None:
|
|
1370
|
+
return _table_merge_refusal(request, "table_merge_table_unsupported")
|
|
1371
|
+
|
|
1372
|
+
origin_cell: ET.Element | None = None
|
|
1373
|
+
origin_text = ""
|
|
1374
|
+
continuation_texts: dict[int, str] = {}
|
|
1375
|
+
|
|
1376
|
+
if request.action == "merge":
|
|
1377
|
+
# MERGE VALIDATION
|
|
1378
|
+
for r_idx in range(request.start_row, request.end_row + 1):
|
|
1379
|
+
for entry in entries[r_idx - 1]:
|
|
1380
|
+
_, cell, c_start, c_end = entry
|
|
1381
|
+
if c_end < request.start_col or c_start > request.end_col:
|
|
1382
|
+
continue
|
|
1383
|
+
if c_start < request.start_col or c_end > request.end_col:
|
|
1384
|
+
return cell_refusal(
|
|
1385
|
+
"table_merge_geometry_unsupported",
|
|
1386
|
+
"cell_crosses_target_boundary",
|
|
1387
|
+
r_idx,
|
|
1388
|
+
entry,
|
|
1389
|
+
)
|
|
1390
|
+
if cell.find(f".//{word('tbl')}") is not None:
|
|
1391
|
+
return cell_refusal(
|
|
1392
|
+
"table_merge_geometry_unsupported",
|
|
1393
|
+
"cell_contains_nested_table",
|
|
1394
|
+
r_idx,
|
|
1395
|
+
entry,
|
|
1396
|
+
)
|
|
1397
|
+
if _has_forbidden_cell_descendant(cell):
|
|
1398
|
+
return cell_refusal(
|
|
1399
|
+
"table_merge_geometry_unsupported",
|
|
1400
|
+
"cell_contains_unsupported_content",
|
|
1401
|
+
r_idx,
|
|
1402
|
+
entry,
|
|
1403
|
+
)
|
|
1404
|
+
try:
|
|
1405
|
+
span, v_merge = _cell_merge_state(cell, namespace)
|
|
1406
|
+
except ValueError:
|
|
1407
|
+
return cell_refusal(
|
|
1408
|
+
"table_merge_structure_unsupported",
|
|
1409
|
+
"malformed_merge_markup",
|
|
1410
|
+
r_idx,
|
|
1411
|
+
entry,
|
|
1412
|
+
)
|
|
1413
|
+
if span > 1 or v_merge is not None:
|
|
1414
|
+
return cell_refusal(
|
|
1415
|
+
"table_merge_geometry_unsupported", "cell_already_merged", r_idx, entry
|
|
1416
|
+
)
|
|
1417
|
+
if r_idx == request.start_row and c_start == request.start_col:
|
|
1418
|
+
origin_cell = cell
|
|
1419
|
+
origin_text = _get_cell_text(cell, namespace)
|
|
1420
|
+
elif _cell_has_user_content(cell, namespace):
|
|
1421
|
+
return cell_refusal(
|
|
1422
|
+
"table_merge_content_loss_unsupported", "cell_has_content", r_idx, entry
|
|
1423
|
+
)
|
|
1424
|
+
|
|
1425
|
+
if origin_cell is None:
|
|
1426
|
+
return _table_merge_refusal(request, "table_merge_geometry_unsupported")
|
|
1427
|
+
|
|
1428
|
+
# A continue cell directly below would silently join the new vertical merge.
|
|
1429
|
+
if row_span > 1 and request.end_row < len(rows):
|
|
1430
|
+
below = _entry_at(entries[request.end_row], request.start_col)
|
|
1431
|
+
if below is not None and below[2] == request.start_col:
|
|
1432
|
+
try:
|
|
1433
|
+
_, below_vmerge = _cell_merge_state(below[1], namespace)
|
|
1434
|
+
except ValueError:
|
|
1435
|
+
below_vmerge = None
|
|
1436
|
+
if below_vmerge == "continue":
|
|
1437
|
+
return cell_refusal(
|
|
1438
|
+
"table_merge_geometry_unsupported",
|
|
1439
|
+
"vmerge_continues_below_target",
|
|
1440
|
+
request.end_row + 1,
|
|
1441
|
+
below,
|
|
1442
|
+
)
|
|
1443
|
+
|
|
1444
|
+
# EXECUTE MERGE
|
|
1445
|
+
origin_tc_pr = origin_cell.find(word("tcPr"))
|
|
1446
|
+
if origin_tc_pr is None:
|
|
1447
|
+
origin_tc_pr = ET.Element(word("tcPr"))
|
|
1448
|
+
origin_cell.insert(0, origin_tc_pr)
|
|
1449
|
+
|
|
1450
|
+
_set_tc_width(origin_tc_pr, total_width, namespace)
|
|
1451
|
+
if col_span > 1:
|
|
1452
|
+
_set_grid_span(origin_tc_pr, col_span, namespace)
|
|
1453
|
+
if row_span > 1:
|
|
1454
|
+
_set_v_merge(origin_tc_pr, "restart", namespace)
|
|
1455
|
+
|
|
1456
|
+
origin_row = rows[request.start_row - 1]
|
|
1457
|
+
origin_row_mapping = row_mappings[request.start_row - 1]
|
|
1458
|
+
for cell, c_start, c_end in origin_row_mapping:
|
|
1459
|
+
if c_start > request.start_col and c_end <= request.end_col:
|
|
1460
|
+
origin_row.remove(cell)
|
|
1461
|
+
|
|
1462
|
+
for r_idx in range(request.start_row + 1, request.end_row + 1):
|
|
1463
|
+
row = rows[r_idx - 1]
|
|
1464
|
+
mapping = row_mappings[r_idx - 1]
|
|
1465
|
+
cont_cell: ET.Element | None = None
|
|
1466
|
+
for cell, c_start, c_end in mapping:
|
|
1467
|
+
if c_start == request.start_col:
|
|
1468
|
+
cont_cell = cell
|
|
1469
|
+
elif c_start > request.start_col and c_end <= request.end_col:
|
|
1470
|
+
row.remove(cell)
|
|
1471
|
+
|
|
1472
|
+
if cont_cell is None:
|
|
1473
|
+
return _table_merge_refusal(request, "table_merge_geometry_unsupported")
|
|
1474
|
+
|
|
1475
|
+
cont_tc_pr = cont_cell.find(word("tcPr"))
|
|
1476
|
+
if cont_tc_pr is None:
|
|
1477
|
+
cont_tc_pr = ET.Element(word("tcPr"))
|
|
1478
|
+
cont_cell.insert(0, cont_tc_pr)
|
|
1479
|
+
|
|
1480
|
+
_set_tc_width(cont_tc_pr, total_width, namespace)
|
|
1481
|
+
if col_span > 1:
|
|
1482
|
+
_set_grid_span(cont_tc_pr, col_span, namespace)
|
|
1483
|
+
_set_v_merge(cont_tc_pr, "continue", namespace)
|
|
1484
|
+
|
|
1485
|
+
for p in cont_cell.findall(word("p")):
|
|
1486
|
+
for r in p.findall(word("r")):
|
|
1487
|
+
p.remove(r)
|
|
1488
|
+
if not cont_cell.findall(word("p")):
|
|
1489
|
+
ET.SubElement(cont_cell, word("p"))
|
|
1490
|
+
|
|
1491
|
+
elif request.action == "split":
|
|
1492
|
+
# SPLIT VALIDATION
|
|
1493
|
+
origin_entry = _entry_at(entries[request.start_row - 1], request.start_col)
|
|
1494
|
+
if origin_entry is None:
|
|
1495
|
+
return _table_merge_refusal(request, "table_merge_geometry_unsupported")
|
|
1496
|
+
if origin_entry[2] != request.start_col or origin_entry[3] != request.end_col:
|
|
1497
|
+
return cell_refusal(
|
|
1498
|
+
"table_merge_geometry_unsupported",
|
|
1499
|
+
"cell_extent_mismatch",
|
|
1500
|
+
request.start_row,
|
|
1501
|
+
origin_entry,
|
|
1502
|
+
)
|
|
1503
|
+
origin_cell = origin_entry[1]
|
|
1504
|
+
|
|
1505
|
+
origin_text = _get_cell_text(origin_cell, namespace)
|
|
1506
|
+
try:
|
|
1507
|
+
span, v_merge = _cell_merge_state(origin_cell, namespace)
|
|
1508
|
+
except ValueError:
|
|
1509
|
+
return cell_refusal(
|
|
1510
|
+
"table_merge_structure_unsupported",
|
|
1511
|
+
"malformed_merge_markup",
|
|
1512
|
+
request.start_row,
|
|
1513
|
+
origin_entry,
|
|
1514
|
+
)
|
|
1515
|
+
|
|
1516
|
+
if span != col_span:
|
|
1517
|
+
return cell_refusal(
|
|
1518
|
+
"table_merge_geometry_unsupported",
|
|
1519
|
+
"grid_span_mismatch",
|
|
1520
|
+
request.start_row,
|
|
1521
|
+
origin_entry,
|
|
1522
|
+
)
|
|
1523
|
+
|
|
1524
|
+
if row_span > 1:
|
|
1525
|
+
if v_merge != "restart":
|
|
1526
|
+
return cell_refusal(
|
|
1527
|
+
"table_merge_geometry_unsupported",
|
|
1528
|
+
"vmerge_restart_missing",
|
|
1529
|
+
request.start_row,
|
|
1530
|
+
origin_entry,
|
|
1531
|
+
)
|
|
1532
|
+
if request.start_row > 1:
|
|
1533
|
+
prev_entry = _entry_at(entries[request.start_row - 2], request.start_col)
|
|
1534
|
+
if prev_entry is not None and prev_entry[2] == request.start_col:
|
|
1535
|
+
try:
|
|
1536
|
+
_, prev_vm = _cell_merge_state(prev_entry[1], namespace)
|
|
1537
|
+
except ValueError:
|
|
1538
|
+
return cell_refusal(
|
|
1539
|
+
"table_merge_structure_unsupported",
|
|
1540
|
+
"malformed_merge_markup",
|
|
1541
|
+
request.start_row - 1,
|
|
1542
|
+
prev_entry,
|
|
1543
|
+
)
|
|
1544
|
+
if prev_vm == "continue":
|
|
1545
|
+
return cell_refusal(
|
|
1546
|
+
"table_merge_geometry_unsupported",
|
|
1547
|
+
"vmerge_continues_above_target",
|
|
1548
|
+
request.start_row - 1,
|
|
1549
|
+
prev_entry,
|
|
1550
|
+
)
|
|
1551
|
+
elif v_merge is not None:
|
|
1552
|
+
return cell_refusal(
|
|
1553
|
+
"table_merge_geometry_unsupported",
|
|
1554
|
+
"vmerge_present",
|
|
1555
|
+
request.start_row,
|
|
1556
|
+
origin_entry,
|
|
1557
|
+
)
|
|
1558
|
+
|
|
1559
|
+
# Validate every affected cell across all covered rows
|
|
1560
|
+
for r_idx in range(request.start_row, request.end_row + 1):
|
|
1561
|
+
affected = _entry_at(entries[r_idx - 1], request.start_col)
|
|
1562
|
+
if affected is None:
|
|
1563
|
+
return _table_merge_refusal(request, "table_merge_geometry_unsupported")
|
|
1564
|
+
if affected[2] != request.start_col or affected[3] != request.end_col:
|
|
1565
|
+
return cell_refusal(
|
|
1566
|
+
"table_merge_geometry_unsupported", "cell_extent_mismatch", r_idx, affected
|
|
1567
|
+
)
|
|
1568
|
+
affected_cell = affected[1]
|
|
1569
|
+
|
|
1570
|
+
if unsupported_context.get(id(affected_cell), False):
|
|
1571
|
+
return cell_refusal(
|
|
1572
|
+
"table_merge_context_unsupported",
|
|
1573
|
+
"cell_in_unsupported_context",
|
|
1574
|
+
r_idx,
|
|
1575
|
+
affected,
|
|
1576
|
+
)
|
|
1577
|
+
if affected_cell.find(f".//{word('tbl')}") is not None:
|
|
1578
|
+
return cell_refusal(
|
|
1579
|
+
"table_merge_geometry_unsupported",
|
|
1580
|
+
"cell_contains_nested_table",
|
|
1581
|
+
r_idx,
|
|
1582
|
+
affected,
|
|
1583
|
+
)
|
|
1584
|
+
if _has_forbidden_cell_descendant(affected_cell):
|
|
1585
|
+
return cell_refusal(
|
|
1586
|
+
"table_merge_geometry_unsupported",
|
|
1587
|
+
"cell_contains_unsupported_content",
|
|
1588
|
+
r_idx,
|
|
1589
|
+
affected,
|
|
1590
|
+
)
|
|
1591
|
+
|
|
1592
|
+
if r_idx > request.start_row:
|
|
1593
|
+
try:
|
|
1594
|
+
c_span, c_vmerge = _cell_merge_state(affected_cell, namespace)
|
|
1595
|
+
except ValueError:
|
|
1596
|
+
return cell_refusal(
|
|
1597
|
+
"table_merge_structure_unsupported",
|
|
1598
|
+
"malformed_merge_markup",
|
|
1599
|
+
r_idx,
|
|
1600
|
+
affected,
|
|
1601
|
+
)
|
|
1602
|
+
if c_vmerge != "continue" or c_span != span:
|
|
1603
|
+
return cell_refusal(
|
|
1604
|
+
"table_merge_geometry_unsupported",
|
|
1605
|
+
"vmerge_continuation_missing",
|
|
1606
|
+
r_idx,
|
|
1607
|
+
affected,
|
|
1608
|
+
)
|
|
1609
|
+
continuation_texts[r_idx] = _get_cell_text(affected_cell, namespace)
|
|
1610
|
+
|
|
1611
|
+
# Check vertical merge does not continue past end_row
|
|
1612
|
+
if row_span > 1 and request.end_row < len(rows):
|
|
1613
|
+
below = _entry_at(entries[request.end_row], request.start_col)
|
|
1614
|
+
if below is not None and below[2] == request.start_col:
|
|
1615
|
+
try:
|
|
1616
|
+
_, after_vmerge = _cell_merge_state(below[1], namespace)
|
|
1617
|
+
except ValueError:
|
|
1618
|
+
return cell_refusal(
|
|
1619
|
+
"table_merge_structure_unsupported",
|
|
1620
|
+
"malformed_merge_markup",
|
|
1621
|
+
request.end_row + 1,
|
|
1622
|
+
below,
|
|
1623
|
+
)
|
|
1624
|
+
if after_vmerge == "continue":
|
|
1625
|
+
return cell_refusal(
|
|
1626
|
+
"table_merge_geometry_unsupported",
|
|
1627
|
+
"vmerge_continues_below_target",
|
|
1628
|
+
request.end_row + 1,
|
|
1629
|
+
below,
|
|
1630
|
+
)
|
|
1631
|
+
|
|
1632
|
+
# EXECUTE SPLIT
|
|
1633
|
+
for r_idx in range(request.start_row, request.end_row + 1):
|
|
1634
|
+
row = rows[r_idx - 1]
|
|
1635
|
+
mapping = row_mappings[r_idx - 1]
|
|
1636
|
+
cell_to_split = None
|
|
1637
|
+
for cell, c_start, _ in mapping:
|
|
1638
|
+
if c_start == request.start_col:
|
|
1639
|
+
cell_to_split = cell
|
|
1640
|
+
break
|
|
1641
|
+
assert cell_to_split is not None
|
|
1642
|
+
|
|
1643
|
+
tc_pr = cell_to_split.find(word("tcPr"))
|
|
1644
|
+
if tc_pr is not None:
|
|
1645
|
+
_remove_tcpr_child(tc_pr, "gridSpan", namespace)
|
|
1646
|
+
_remove_tcpr_child(tc_pr, "vMerge", namespace)
|
|
1647
|
+
col_w0 = grid_cols[request.start_col - 1].get(word("w"))
|
|
1648
|
+
_set_tc_width(tc_pr, col_w0, namespace)
|
|
1649
|
+
|
|
1650
|
+
if not cell_to_split.findall(word("p")):
|
|
1651
|
+
ET.SubElement(cell_to_split, word("p"))
|
|
1652
|
+
|
|
1653
|
+
if col_span > 1:
|
|
1654
|
+
current_anchor = cell_to_split
|
|
1655
|
+
for col in range(request.start_col + 1, request.end_col + 1):
|
|
1656
|
+
col_w = grid_cols[col - 1].get(word("w"))
|
|
1657
|
+
new_cell = _create_split_cell(tc_pr, col_w, namespace)
|
|
1658
|
+
anchor_idx = list(row).index(current_anchor)
|
|
1659
|
+
row.insert(anchor_idx + 1, new_cell)
|
|
1660
|
+
current_anchor = new_cell
|
|
1661
|
+
else:
|
|
1662
|
+
return _table_merge_refusal(request, "table_merge_action_invalid")
|
|
1663
|
+
|
|
1664
|
+
target_change_report = {
|
|
1665
|
+
"table": request.table,
|
|
1666
|
+
"part": request.part,
|
|
1667
|
+
"action": request.action,
|
|
1668
|
+
"start_row": request.start_row,
|
|
1669
|
+
"end_row": request.end_row,
|
|
1670
|
+
"start_col": request.start_col,
|
|
1671
|
+
"end_col": request.end_col,
|
|
1672
|
+
"rows_count": len(rows),
|
|
1673
|
+
"cols_count": num_grid_cols,
|
|
1674
|
+
"origin_text": origin_text,
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
def verify_publication(staged: Path) -> str | None:
|
|
1678
|
+
if not _unrelated_parts_preserved(source, staged, frozenset({request.part})):
|
|
1679
|
+
return _FAILED_VERIFICATION
|
|
1680
|
+
insp = inspect_docx(staged)
|
|
1681
|
+
if not insp.valid:
|
|
1682
|
+
return _FAILED_VERIFICATION
|
|
1683
|
+
try:
|
|
1684
|
+
s_graph = PackageGraph.from_file(staged)
|
|
1685
|
+
staged_part_valid, _ = _check_reachable_part(s_graph, request.part, "table_merge")
|
|
1686
|
+
if not staged_part_valid:
|
|
1687
|
+
return _FAILED_VERIFICATION
|
|
1688
|
+
s_root = ET.fromstring(s_graph.read_part_bytes(request.part))
|
|
1689
|
+
if _word_namespace(s_root) != namespace:
|
|
1690
|
+
return _FAILED_VERIFICATION
|
|
1691
|
+
|
|
1692
|
+
s_tables = list(s_root.iter(word("tbl")))
|
|
1693
|
+
if len(s_tables) != len(tables):
|
|
1694
|
+
return _FAILED_VERIFICATION
|
|
1695
|
+
s_table = s_tables[request.table - 1]
|
|
1696
|
+
|
|
1697
|
+
# Everything in the selected part outside the target table is unchanged
|
|
1698
|
+
outside_after = _signature_outside_table(s_root, s_table)
|
|
1699
|
+
if outside_after is None or outside_after != outside_before:
|
|
1700
|
+
return _FAILED_VERIFICATION
|
|
1701
|
+
|
|
1702
|
+
# Verify tblGrid is byte-identical
|
|
1703
|
+
orig_grid = pristine_table.find(word("tblGrid"))
|
|
1704
|
+
staged_grid = s_table.find(word("tblGrid"))
|
|
1705
|
+
if (orig_grid is None) != (staged_grid is None):
|
|
1706
|
+
return _FAILED_VERIFICATION
|
|
1707
|
+
if (
|
|
1708
|
+
orig_grid is not None
|
|
1709
|
+
and staged_grid is not None
|
|
1710
|
+
and ET.tostring(orig_grid) != ET.tostring(staged_grid)
|
|
1711
|
+
):
|
|
1712
|
+
return _FAILED_VERIFICATION
|
|
1713
|
+
|
|
1714
|
+
orig_rows = pristine_table.findall(word("tr"))
|
|
1715
|
+
s_rows = s_table.findall(word("tr"))
|
|
1716
|
+
if len(s_rows) != len(orig_rows):
|
|
1717
|
+
return _FAILED_VERIFICATION
|
|
1718
|
+
|
|
1719
|
+
# Verify preservation of unselected rows
|
|
1720
|
+
for r_idx in range(1, len(orig_rows) + 1):
|
|
1721
|
+
if (r_idx < request.start_row or r_idx > request.end_row) and ET.tostring(
|
|
1722
|
+
s_rows[r_idx - 1]
|
|
1723
|
+
) != ET.tostring(orig_rows[r_idx - 1]):
|
|
1724
|
+
return _FAILED_VERIFICATION
|
|
1725
|
+
|
|
1726
|
+
# Verify every row in [start_row, end_row]
|
|
1727
|
+
for r_idx in range(request.start_row, request.end_row + 1):
|
|
1728
|
+
s_mapping = _row_grid_mapping(s_rows[r_idx - 1], num_grid_cols, namespace)
|
|
1729
|
+
orig_mapping = _row_grid_mapping(orig_rows[r_idx - 1], num_grid_cols, namespace)
|
|
1730
|
+
if s_mapping is None or orig_mapping is None:
|
|
1731
|
+
return _FAILED_VERIFICATION
|
|
1732
|
+
|
|
1733
|
+
# Verify unselected cells in affected row
|
|
1734
|
+
for s_cell, sc_s, sc_e in s_mapping:
|
|
1735
|
+
if sc_e < request.start_col or sc_s > request.end_col:
|
|
1736
|
+
matched = False
|
|
1737
|
+
for o_cell, oc_s, oc_e in orig_mapping:
|
|
1738
|
+
if oc_s == sc_s and oc_e == sc_e:
|
|
1739
|
+
if ET.tostring(s_cell) == ET.tostring(o_cell):
|
|
1740
|
+
matched = True
|
|
1741
|
+
break
|
|
1742
|
+
if not matched:
|
|
1743
|
+
return _FAILED_VERIFICATION
|
|
1744
|
+
|
|
1745
|
+
orig_at_start = next(
|
|
1746
|
+
(o_cell for o_cell, oc_s, _ in orig_mapping if oc_s == request.start_col),
|
|
1747
|
+
None,
|
|
1748
|
+
)
|
|
1749
|
+
if orig_at_start is None:
|
|
1750
|
+
return _FAILED_VERIFICATION
|
|
1751
|
+
orig_props, orig_content = _cell_preserved_projection(
|
|
1752
|
+
orig_at_start, namespace, _MERGE_OWNED_TCPR
|
|
1753
|
+
)
|
|
1754
|
+
|
|
1755
|
+
# Verify affected cells in affected row
|
|
1756
|
+
if request.action == "merge":
|
|
1757
|
+
covered = [
|
|
1758
|
+
(c, cs, ce)
|
|
1759
|
+
for c, cs, ce in s_mapping
|
|
1760
|
+
if not (ce < request.start_col or cs > request.end_col)
|
|
1761
|
+
]
|
|
1762
|
+
if len(covered) != 1:
|
|
1763
|
+
return _FAILED_VERIFICATION
|
|
1764
|
+
m_cell, mc_s, mc_e = covered[0]
|
|
1765
|
+
if mc_s != request.start_col or mc_e != request.end_col:
|
|
1766
|
+
return _FAILED_VERIFICATION
|
|
1767
|
+
span, vm = _cell_merge_state(m_cell, namespace)
|
|
1768
|
+
if col_span > 1 and span != col_span:
|
|
1769
|
+
return _FAILED_VERIFICATION
|
|
1770
|
+
if col_span == 1 and span != 1:
|
|
1771
|
+
return _FAILED_VERIFICATION
|
|
1772
|
+
m_props, m_content = _cell_preserved_projection(
|
|
1773
|
+
m_cell, namespace, _MERGE_OWNED_TCPR
|
|
1774
|
+
)
|
|
1775
|
+
if m_props != orig_props:
|
|
1776
|
+
return _FAILED_VERIFICATION
|
|
1777
|
+
if r_idx == request.start_row:
|
|
1778
|
+
if row_span > 1 and vm != "restart":
|
|
1779
|
+
return _FAILED_VERIFICATION
|
|
1780
|
+
if row_span == 1 and vm is not None:
|
|
1781
|
+
return _FAILED_VERIFICATION
|
|
1782
|
+
if _get_cell_text(m_cell, namespace) != origin_text:
|
|
1783
|
+
return _FAILED_VERIFICATION
|
|
1784
|
+
if m_content != orig_content:
|
|
1785
|
+
return _FAILED_VERIFICATION
|
|
1786
|
+
else:
|
|
1787
|
+
if vm != "continue":
|
|
1788
|
+
return _FAILED_VERIFICATION
|
|
1789
|
+
if _get_cell_text(m_cell, namespace) != "":
|
|
1790
|
+
return _FAILED_VERIFICATION
|
|
1791
|
+
else:
|
|
1792
|
+
# Split action
|
|
1793
|
+
split_cells = [
|
|
1794
|
+
(c, cs, ce)
|
|
1795
|
+
for c, cs, ce in s_mapping
|
|
1796
|
+
if cs >= request.start_col and ce <= request.end_col
|
|
1797
|
+
]
|
|
1798
|
+
if len(split_cells) != col_span:
|
|
1799
|
+
return _FAILED_VERIFICATION
|
|
1800
|
+
for idx, (s_c, sc_s, sc_e) in enumerate(split_cells):
|
|
1801
|
+
exp_col = request.start_col + idx
|
|
1802
|
+
if sc_s != exp_col or sc_e != exp_col:
|
|
1803
|
+
return _FAILED_VERIFICATION
|
|
1804
|
+
span, vm = _cell_merge_state(s_c, namespace)
|
|
1805
|
+
if span != 1 or vm is not None:
|
|
1806
|
+
return _FAILED_VERIFICATION
|
|
1807
|
+
s_tc_pr = s_c.find(word("tcPr"))
|
|
1808
|
+
if s_tc_pr is None:
|
|
1809
|
+
return _FAILED_VERIFICATION
|
|
1810
|
+
w_elem = s_tc_pr.find(word("tcW"))
|
|
1811
|
+
if w_elem is None or w_elem.get(word("w")) != grid_cols[exp_col - 1].get(
|
|
1812
|
+
word("w")
|
|
1813
|
+
):
|
|
1814
|
+
return _FAILED_VERIFICATION
|
|
1815
|
+
if exp_col > request.start_col:
|
|
1816
|
+
if _get_cell_text(s_c, namespace) != "":
|
|
1817
|
+
return _FAILED_VERIFICATION
|
|
1818
|
+
continue
|
|
1819
|
+
s_props, s_content = _cell_preserved_projection(
|
|
1820
|
+
s_c, namespace, _MERGE_OWNED_TCPR
|
|
1821
|
+
)
|
|
1822
|
+
if s_props != orig_props:
|
|
1823
|
+
return _FAILED_VERIFICATION
|
|
1824
|
+
if orig_at_start.findall(word("p")) and s_content != orig_content:
|
|
1825
|
+
return _FAILED_VERIFICATION
|
|
1826
|
+
if r_idx == request.start_row:
|
|
1827
|
+
if _get_cell_text(s_c, namespace) != origin_text:
|
|
1828
|
+
return _FAILED_VERIFICATION
|
|
1829
|
+
elif _get_cell_text(s_c, namespace) != continuation_texts.get(r_idx, ""):
|
|
1830
|
+
return _FAILED_VERIFICATION
|
|
1831
|
+
|
|
1832
|
+
except (OSError, PackageError, ET.ParseError, KeyError, IndexError, ValueError):
|
|
1833
|
+
return _FAILED_VERIFICATION
|
|
1834
|
+
return None
|
|
1835
|
+
|
|
1836
|
+
serialized = serialize_xml_with_preserved_qnames(root)
|
|
1837
|
+
replacements = {request.part: serialized}
|
|
1838
|
+
|
|
1839
|
+
published: ReviewReport = _publish(
|
|
1840
|
+
source=source,
|
|
1841
|
+
output=destination,
|
|
1842
|
+
source_sha256=request.source_sha256,
|
|
1843
|
+
replacements=replacements,
|
|
1844
|
+
revisions=[],
|
|
1845
|
+
targets=[target_change_report],
|
|
1846
|
+
verify=verify_publication,
|
|
1847
|
+
failure_code=_FAILED_VERIFICATION,
|
|
1848
|
+
exists_code="table_merge_destination_occupied",
|
|
1849
|
+
unavailable_code="table_merge_publication_unavailable",
|
|
1850
|
+
)
|
|
1851
|
+
|
|
1852
|
+
if not published.passed:
|
|
1853
|
+
return _table_merge_refusal(request, published.code or _FAILED_VERIFICATION)
|
|
1854
|
+
|
|
1855
|
+
return TableMergeReport(
|
|
1856
|
+
status=_PUBLISHED,
|
|
1857
|
+
code=None,
|
|
1858
|
+
source_sha256=request.source_sha256,
|
|
1859
|
+
destination_sha256=published.output_sha256,
|
|
1860
|
+
target=request.target_dict(),
|
|
1861
|
+
target_change_report=target_change_report,
|
|
1862
|
+
non_target_parts_preserved=True,
|
|
1863
|
+
)
|