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.
Files changed (54) hide show
  1. wolfdocx/__init__.py +25 -0
  2. wolfdocx/_cache_root.py +24 -0
  3. wolfdocx/_comment_threads.py +278 -0
  4. wolfdocx/_inspection_cache.py +374 -0
  5. wolfdocx/_version.py +3 -0
  6. wolfdocx/admission.py +163 -0
  7. wolfdocx/assembly.py +463 -0
  8. wolfdocx/authoring.py +2773 -0
  9. wolfdocx/canonical.py +267 -0
  10. wolfdocx/content.py +963 -0
  11. wolfdocx/document.py +215 -0
  12. wolfdocx/errors.py +169 -0
  13. wolfdocx/find_replace.py +1210 -0
  14. wolfdocx/formatting.py +3160 -0
  15. wolfdocx/inspect.py +3999 -0
  16. wolfdocx/model.py +1038 -0
  17. wolfdocx/numbering_authoring.py +1422 -0
  18. wolfdocx/output.py +13 -0
  19. wolfdocx/package.py +2313 -0
  20. wolfdocx/package_profile.py +128 -0
  21. wolfdocx/page_setup.py +2483 -0
  22. wolfdocx/paragraph_authoring.py +1842 -0
  23. wolfdocx/properties.py +2728 -0
  24. wolfdocx/protection.py +1909 -0
  25. wolfdocx/regions.py +1993 -0
  26. wolfdocx/render_warnings.py +106 -0
  27. wolfdocx/reporting.py +943 -0
  28. wolfdocx/review.py +2862 -0
  29. wolfdocx/run_text.py +117 -0
  30. wolfdocx/section_break.py +1810 -0
  31. wolfdocx/session_ops/__init__.py +45 -0
  32. wolfdocx/session_ops/_bridge.py +151 -0
  33. wolfdocx/session_ops/lists.py +104 -0
  34. wolfdocx/session_ops/paragraphs.py +39 -0
  35. wolfdocx/session_ops/rich_objects.py +2598 -0
  36. wolfdocx/session_ops/run_edits.py +70 -0
  37. wolfdocx/session_ops/runs.py +313 -0
  38. wolfdocx/session_ops/sections.py +109 -0
  39. wolfdocx/session_ops/styling.py +99 -0
  40. wolfdocx/session_ops/tables.py +247 -0
  41. wolfdocx/styles_authoring.py +2822 -0
  42. wolfdocx/table_cell_properties.py +1458 -0
  43. wolfdocx/table_column.py +1501 -0
  44. wolfdocx/table_delete.py +942 -0
  45. wolfdocx/table_insert.py +1114 -0
  46. wolfdocx/table_merge.py +1863 -0
  47. wolfdocx/table_properties.py +2429 -0
  48. wolfdocx/table_row_properties.py +1095 -0
  49. wolfdocx/table_structure.py +1044 -0
  50. wolfdocx/text_effects.py +1438 -0
  51. wolfdocx-0.1.0.dist-info/METADATA +127 -0
  52. wolfdocx-0.1.0.dist-info/RECORD +54 -0
  53. wolfdocx-0.1.0.dist-info/WHEEL +4 -0
  54. wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1438 @@
1
+ """Source-bound Word 2010 (w14) run text effects: authoring and inspection.
2
+
3
+ Five effects are authored as Word writes them, as ``w14`` children of ``w:rPr``:
4
+
5
+ - ``glow``: ``w14:glow`` (radius and color).
6
+ - ``shadow``: ``w14:shadow``, an outer shadow (blur, distance, direction, scale, skew).
7
+ - ``reflection``: ``w14:reflection`` (blur, distance, opacity ramp, size).
8
+ - ``outline``: ``w14:textOutline`` (width, color, dash, join).
9
+ - ``fill``: ``w14:textFill`` as a linear or path gradient, a solid color, or no fill.
10
+
11
+ Lengths are points (stored as EMU, 12700 per point), angles are degrees (stored in
12
+ 60000ths), and percentages are stored in thousandths. Values are quantized to those
13
+ units when a request is parsed, so what :func:`inspect_text_effects` reports for a run is
14
+ exactly what was authored, and every inspected effect is itself a valid authoring spec.
15
+
16
+ In ``w14`` color transforms ``w14:alpha`` is a transparency, reported as
17
+ ``transparency``. Reflection ``stA``/``endA`` are opacities, reported as
18
+ ``start_opacity``/``end_opacity``.
19
+
20
+ Edits target a bounded text range in one paragraph exactly as :mod:`wolfdocx.formatting`
21
+ run edits do (paragraph index, offsets, expected text, structure fingerprint from
22
+ :func:`wolfdocx.formatting.discover_format_targets`). Runs are split at the range
23
+ boundaries. Per effect, a spec sets it, ``False`` removes it, and an absent key leaves it.
24
+ Anything that cannot be applied exactly is refused with a ``text_effect_*`` code; the
25
+ document root gains the ``w14`` namespace and an ``mc:Ignorable`` entry when it lacks them.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import itertools
31
+ import json
32
+ import math
33
+ import zipfile
34
+ from collections.abc import Mapping, Sequence
35
+ from dataclasses import dataclass, field
36
+ from pathlib import Path
37
+ from typing import Any, Literal
38
+ from xml.etree import ElementTree as ET
39
+
40
+ from .formatting import (
41
+ _HEX_COLOR_PATTERN,
42
+ _detect_context_unsupported,
43
+ _is_inside_sdt_or_unsupported,
44
+ _local_name,
45
+ _unrelated_parts_preserved,
46
+ )
47
+ from .inspect import (
48
+ SUPPORTED_WORD_NAMESPACES,
49
+ Q,
50
+ _QNameElement,
51
+ parse_xml_with_preserved_qnames,
52
+ serialize_xml_with_preserved_qnames,
53
+ )
54
+ from .package import PackageError, PackageGraph
55
+ from .review import (
56
+ _DOCUMENT,
57
+ ReviewReport,
58
+ _clone_run,
59
+ _mask_text,
60
+ _paragraph_map,
61
+ _publish,
62
+ _review_parts,
63
+ _ReviewContextError,
64
+ _sha,
65
+ _sha256,
66
+ _word_namespace,
67
+ )
68
+
69
+ W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
70
+ MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"
71
+
72
+ _STYLES = "word/styles.xml"
73
+ _REFUSED = "refused"
74
+ _PUBLISHED = "published"
75
+
76
+ EMU_PER_POINT = 12700
77
+ _ANGLE_UNIT = 60000
78
+ _PERCENT_UNIT = 1000
79
+
80
+ EFFECT_KEYS: tuple[str, ...] = ("glow", "shadow", "reflection", "outline", "fill")
81
+
82
+ # Order of the w14 run property elements Word writes after the w: elements of CT_RPr.
83
+ _W14_RPR_ORDER: tuple[str, ...] = (
84
+ "glow",
85
+ "shadow",
86
+ "reflection",
87
+ "textOutline",
88
+ "textFill",
89
+ "scene3d",
90
+ "props3d",
91
+ "ligatures",
92
+ "numForm",
93
+ "numSpacing",
94
+ "stylisticSets",
95
+ "cntxtAlts",
96
+ )
97
+ _W14_RANK = {local: index for index, local in enumerate(_W14_RPR_ORDER)}
98
+ _ELEMENT_FOR_KEY = {
99
+ "glow": "glow",
100
+ "shadow": "shadow",
101
+ "reflection": "reflection",
102
+ "outline": "textOutline",
103
+ "fill": "textFill",
104
+ }
105
+ _KEY_FOR_ELEMENT = {element: key for key, element in _ELEMENT_FOR_KEY.items()}
106
+
107
+ # w14 ST_SchemeColorVal.
108
+ SCHEME_COLORS = frozenset(
109
+ {
110
+ "bg1",
111
+ "tx1",
112
+ "bg2",
113
+ "tx2",
114
+ "accent1",
115
+ "accent2",
116
+ "accent3",
117
+ "accent4",
118
+ "accent5",
119
+ "accent6",
120
+ "hlink",
121
+ "folHlink",
122
+ "dk1",
123
+ "lt1",
124
+ "dk2",
125
+ "lt2",
126
+ "phClr",
127
+ }
128
+ )
129
+ # EG_ColorTransform sequence order; alpha is carried as ``transparency``.
130
+ _COLOR_TRANSFORM_ORDER: tuple[str, ...] = (
131
+ "tint",
132
+ "shade",
133
+ "alpha",
134
+ "hueMod",
135
+ "sat",
136
+ "satOff",
137
+ "satMod",
138
+ "lum",
139
+ "lumOff",
140
+ "lumMod",
141
+ )
142
+ _COLOR_MODIFIERS = frozenset(_COLOR_TRANSFORM_ORDER) - {"alpha"}
143
+ _DASHES = frozenset(
144
+ {
145
+ "solid",
146
+ "dot",
147
+ "sysDash",
148
+ "sysDot",
149
+ "dash",
150
+ "dashDot",
151
+ "lgDash",
152
+ "lgDashDot",
153
+ "lgDashDotDot",
154
+ "sysDashDot",
155
+ "sysDashDotDot",
156
+ }
157
+ )
158
+ _JOINS = frozenset({"round", "bevel", "miter"})
159
+ _CAPS = frozenset({"rnd", "sq", "flat"})
160
+ _COMPOUNDS = frozenset({"sng", "dbl", "thickThin", "thinThick", "tri"})
161
+ _ALIGNMENTS = frozenset({"tl", "t", "tr", "l", "ctr", "r", "bl", "b", "br"})
162
+ _PEN_ALIGNMENTS = frozenset({"ctr", "in"})
163
+ _PATH_SHADES = frozenset({"circle", "rect", "shape"})
164
+
165
+ _MAX_RADIUS_PT = 150.0
166
+ _MAX_BLUR_PT = 100.0
167
+ _MAX_DISTANCE_PT = 200.0
168
+ _MAX_OUTLINE_PT = 100.0
169
+ _MAX_GRADIENT_STOPS = 10
170
+
171
+
172
+ class TextEffectError(ValueError):
173
+ """A malformed effect spec; ``str(error)`` is the ``text_effect_*`` code."""
174
+
175
+
176
+ def _fail(code: str) -> TextEffectError:
177
+ return TextEffectError(f"text_effect_{code}")
178
+
179
+
180
+ def _number(value: Any, code: str) -> float:
181
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
182
+ raise _fail(code)
183
+ return float(value)
184
+
185
+
186
+ def _points(value: Any, code: str, maximum: float) -> int:
187
+ number = _number(value, code)
188
+ if number < 0 or number > maximum:
189
+ raise _fail(code)
190
+ return round(number * EMU_PER_POINT)
191
+
192
+
193
+ def _percent(value: Any, code: str, low: float = 0.0, high: float = 100.0) -> int:
194
+ number = _number(value, code)
195
+ if number < low or number > high:
196
+ raise _fail(code)
197
+ return round(number * _PERCENT_UNIT)
198
+
199
+
200
+ def _angle(value: Any, code: str) -> int:
201
+ number = _number(value, code)
202
+ if number < 0 or number >= 360:
203
+ raise _fail(code)
204
+ return round(number * _ANGLE_UNIT) % (360 * _ANGLE_UNIT)
205
+
206
+
207
+ def _skew(value: Any, code: str) -> int:
208
+ number = _number(value, code)
209
+ if number <= -90 or number >= 90:
210
+ raise _fail(code)
211
+ return round(number * _ANGLE_UNIT)
212
+
213
+
214
+ def _choice(value: Any, allowed: frozenset[str], code: str) -> str:
215
+ """``value`` when it is one of ``allowed``; ``code`` is the full refusal code."""
216
+ if not isinstance(value, str) or value not in allowed:
217
+ raise TextEffectError(code)
218
+ return value
219
+
220
+
221
+ def _keys(value: Any, allowed: set[str], required: set[str], code: str) -> Mapping[str, Any]:
222
+ if not isinstance(value, Mapping):
223
+ raise _fail(f"{code}_invalid")
224
+ unknown = set(value) - allowed
225
+ if unknown:
226
+ raise _fail(f"{code}_unknown_keys")
227
+ if required - set(value):
228
+ raise _fail(f"{code}_missing_keys")
229
+ return value
230
+
231
+
232
+ def _points_out(emu: int) -> float:
233
+ return round(emu / EMU_PER_POINT, 6)
234
+
235
+
236
+ def _units_out(value: int, unit: int) -> float:
237
+ return round(value / unit, 6)
238
+
239
+
240
+ @dataclass(frozen=True)
241
+ class EffectColor:
242
+ """An ``srgbClr`` (``RRGGBB``) or ``schemeClr`` color with its transforms."""
243
+
244
+ value: str
245
+ transparency: int = 0
246
+ modifiers: tuple[tuple[str, int], ...] = ()
247
+
248
+ @property
249
+ def is_scheme(self) -> bool:
250
+ return self.value in SCHEME_COLORS
251
+
252
+ def to_dict(self) -> dict[str, Any]:
253
+ result: dict[str, Any] = {
254
+ "color": self.value,
255
+ "transparency": _units_out(self.transparency, _PERCENT_UNIT),
256
+ }
257
+ if self.modifiers:
258
+ result["color_modifiers"] = dict(self.modifiers)
259
+ return result
260
+
261
+
262
+ def _color_from(spec: Mapping[str, Any], code: str) -> EffectColor:
263
+ raw = spec.get("color")
264
+ if not isinstance(raw, str):
265
+ raise _fail(f"{code}_color_invalid")
266
+ if raw in SCHEME_COLORS:
267
+ value = raw
268
+ elif _HEX_COLOR_PATTERN.match(raw):
269
+ value = raw.upper()
270
+ else:
271
+ raise _fail(f"{code}_color_invalid")
272
+ transparency = _percent(spec.get("transparency", 0), f"{code}_transparency_invalid")
273
+ raw_modifiers = spec.get("color_modifiers", {})
274
+ if not isinstance(raw_modifiers, Mapping):
275
+ raise _fail(f"{code}_color_modifiers_invalid")
276
+ modifiers: list[tuple[str, int]] = []
277
+ for name in _COLOR_TRANSFORM_ORDER:
278
+ if name not in raw_modifiers:
279
+ continue
280
+ amount = raw_modifiers[name]
281
+ if isinstance(amount, bool) or not isinstance(amount, int) or abs(amount) > 10_000_000:
282
+ raise _fail(f"{code}_color_modifiers_invalid")
283
+ modifiers.append((name, amount))
284
+ if set(raw_modifiers) - _COLOR_MODIFIERS:
285
+ raise _fail(f"{code}_color_modifiers_invalid")
286
+ return EffectColor(value, transparency, tuple(modifiers))
287
+
288
+
289
+ _COLOR_KEYS = {"color", "transparency", "color_modifiers"}
290
+
291
+
292
+ @dataclass(frozen=True)
293
+ class Glow:
294
+ radius: int
295
+ color: EffectColor
296
+
297
+ @classmethod
298
+ def from_dict(cls, value: Any) -> Glow:
299
+ spec = _keys(value, {"radius"} | _COLOR_KEYS, {"radius", "color"}, "glow")
300
+ return cls(
301
+ radius=_points(spec["radius"], "glow_radius_invalid", _MAX_RADIUS_PT),
302
+ color=_color_from(spec, "glow"),
303
+ )
304
+
305
+ def to_dict(self) -> dict[str, Any]:
306
+ return {"radius": _points_out(self.radius), **self.color.to_dict()}
307
+
308
+
309
+ @dataclass(frozen=True)
310
+ class OuterShadow:
311
+ color: EffectColor
312
+ blur: int = round(4 * EMU_PER_POINT)
313
+ distance: int = round(3 * EMU_PER_POINT)
314
+ direction: int = 45 * _ANGLE_UNIT
315
+ scale_x: int = 100 * _PERCENT_UNIT
316
+ scale_y: int = 100 * _PERCENT_UNIT
317
+ skew_x: int = 0
318
+ skew_y: int = 0
319
+ alignment: str = "tl"
320
+
321
+ @classmethod
322
+ def from_dict(cls, value: Any) -> OuterShadow:
323
+ allowed = {
324
+ "blur",
325
+ "distance",
326
+ "direction",
327
+ "scale_x",
328
+ "scale_y",
329
+ "skew_x",
330
+ "skew_y",
331
+ "alignment",
332
+ } | _COLOR_KEYS
333
+ spec = _keys(value, allowed, {"color"}, "shadow")
334
+ defaults = cls(color=EffectColor("000000"))
335
+ return cls(
336
+ color=_color_from(spec, "shadow"),
337
+ blur=_points(spec["blur"], "shadow_blur_invalid", _MAX_BLUR_PT)
338
+ if "blur" in spec
339
+ else defaults.blur,
340
+ distance=_points(spec["distance"], "shadow_distance_invalid", _MAX_DISTANCE_PT)
341
+ if "distance" in spec
342
+ else defaults.distance,
343
+ direction=_angle(spec["direction"], "shadow_direction_invalid")
344
+ if "direction" in spec
345
+ else defaults.direction,
346
+ scale_x=_percent(spec["scale_x"], "shadow_scale_invalid", -200, 200)
347
+ if "scale_x" in spec
348
+ else defaults.scale_x,
349
+ scale_y=_percent(spec["scale_y"], "shadow_scale_invalid", -200, 200)
350
+ if "scale_y" in spec
351
+ else defaults.scale_y,
352
+ skew_x=_skew(spec["skew_x"], "shadow_skew_invalid")
353
+ if "skew_x" in spec
354
+ else defaults.skew_x,
355
+ skew_y=_skew(spec["skew_y"], "shadow_skew_invalid")
356
+ if "skew_y" in spec
357
+ else defaults.skew_y,
358
+ alignment=_choice(
359
+ spec["alignment"], _ALIGNMENTS, "text_effect_shadow_alignment_invalid"
360
+ )
361
+ if "alignment" in spec
362
+ else defaults.alignment,
363
+ )
364
+
365
+ def to_dict(self) -> dict[str, Any]:
366
+ return {
367
+ "blur": _points_out(self.blur),
368
+ "distance": _points_out(self.distance),
369
+ "direction": _units_out(self.direction, _ANGLE_UNIT),
370
+ "scale_x": _units_out(self.scale_x, _PERCENT_UNIT),
371
+ "scale_y": _units_out(self.scale_y, _PERCENT_UNIT),
372
+ "skew_x": _units_out(self.skew_x, _ANGLE_UNIT),
373
+ "skew_y": _units_out(self.skew_y, _ANGLE_UNIT),
374
+ "alignment": self.alignment,
375
+ **self.color.to_dict(),
376
+ }
377
+
378
+
379
+ @dataclass(frozen=True)
380
+ class Reflection:
381
+ blur: int = round(0.5 * EMU_PER_POINT)
382
+ distance: int = 0
383
+ start_opacity: int = 50 * _PERCENT_UNIT
384
+ start_position: int = 0
385
+ end_opacity: int = 300
386
+ end_position: int = 55 * _PERCENT_UNIT
387
+ direction: int = 90 * _ANGLE_UNIT
388
+ fade_direction: int = 90 * _ANGLE_UNIT
389
+ scale_x: int = 100 * _PERCENT_UNIT
390
+ scale_y: int = -100 * _PERCENT_UNIT
391
+ skew_x: int = 0
392
+ skew_y: int = 0
393
+ alignment: str = "bl"
394
+
395
+ @classmethod
396
+ def from_dict(cls, value: Any) -> Reflection:
397
+ allowed = {
398
+ "blur",
399
+ "distance",
400
+ "start_opacity",
401
+ "start_position",
402
+ "end_opacity",
403
+ "size",
404
+ "direction",
405
+ "fade_direction",
406
+ "scale_x",
407
+ "scale_y",
408
+ "skew_x",
409
+ "skew_y",
410
+ "alignment",
411
+ }
412
+ spec = _keys(value, allowed, set(), "reflection")
413
+ base = cls()
414
+
415
+ def pick(key: str, convert: Any, default: int) -> int:
416
+ return convert(spec[key]) if key in spec else default
417
+
418
+ result = cls(
419
+ blur=pick(
420
+ "blur",
421
+ lambda v: _points(v, "reflection_blur_invalid", _MAX_BLUR_PT),
422
+ base.blur,
423
+ ),
424
+ distance=pick(
425
+ "distance",
426
+ lambda v: _points(v, "reflection_distance_invalid", _MAX_DISTANCE_PT),
427
+ base.distance,
428
+ ),
429
+ start_opacity=pick(
430
+ "start_opacity",
431
+ lambda v: _percent(v, "reflection_opacity_invalid"),
432
+ base.start_opacity,
433
+ ),
434
+ start_position=pick(
435
+ "start_position",
436
+ lambda v: _percent(v, "reflection_position_invalid"),
437
+ base.start_position,
438
+ ),
439
+ end_opacity=pick(
440
+ "end_opacity",
441
+ lambda v: _percent(v, "reflection_opacity_invalid"),
442
+ base.end_opacity,
443
+ ),
444
+ end_position=pick(
445
+ "size",
446
+ lambda v: _percent(v, "reflection_position_invalid"),
447
+ base.end_position,
448
+ ),
449
+ direction=pick(
450
+ "direction",
451
+ lambda v: _angle(v, "reflection_direction_invalid"),
452
+ base.direction,
453
+ ),
454
+ fade_direction=pick(
455
+ "fade_direction",
456
+ lambda v: _angle(v, "reflection_direction_invalid"),
457
+ base.fade_direction,
458
+ ),
459
+ scale_x=pick(
460
+ "scale_x",
461
+ lambda v: _percent(v, "reflection_scale_invalid", -200, 200),
462
+ base.scale_x,
463
+ ),
464
+ scale_y=pick(
465
+ "scale_y",
466
+ lambda v: _percent(v, "reflection_scale_invalid", -200, 200),
467
+ base.scale_y,
468
+ ),
469
+ skew_x=pick("skew_x", lambda v: _skew(v, "reflection_skew_invalid"), base.skew_x),
470
+ skew_y=pick("skew_y", lambda v: _skew(v, "reflection_skew_invalid"), base.skew_y),
471
+ alignment=_choice(
472
+ spec["alignment"],
473
+ _ALIGNMENTS,
474
+ "text_effect_reflection_alignment_invalid",
475
+ )
476
+ if "alignment" in spec
477
+ else base.alignment,
478
+ )
479
+ if result.end_position < result.start_position:
480
+ raise _fail("reflection_position_invalid")
481
+ return result
482
+
483
+ def to_dict(self) -> dict[str, Any]:
484
+ return {
485
+ "blur": _points_out(self.blur),
486
+ "distance": _points_out(self.distance),
487
+ "start_opacity": _units_out(self.start_opacity, _PERCENT_UNIT),
488
+ "start_position": _units_out(self.start_position, _PERCENT_UNIT),
489
+ "end_opacity": _units_out(self.end_opacity, _PERCENT_UNIT),
490
+ "size": _units_out(self.end_position, _PERCENT_UNIT),
491
+ "direction": _units_out(self.direction, _ANGLE_UNIT),
492
+ "fade_direction": _units_out(self.fade_direction, _ANGLE_UNIT),
493
+ "scale_x": _units_out(self.scale_x, _PERCENT_UNIT),
494
+ "scale_y": _units_out(self.scale_y, _PERCENT_UNIT),
495
+ "skew_x": _units_out(self.skew_x, _ANGLE_UNIT),
496
+ "skew_y": _units_out(self.skew_y, _ANGLE_UNIT),
497
+ "alignment": self.alignment,
498
+ }
499
+
500
+
501
+ @dataclass(frozen=True)
502
+ class GradientStop:
503
+ position: int
504
+ color: EffectColor
505
+
506
+ def to_dict(self) -> dict[str, Any]:
507
+ return {
508
+ "position": _units_out(self.position, _PERCENT_UNIT),
509
+ **self.color.to_dict(),
510
+ }
511
+
512
+
513
+ @dataclass(frozen=True)
514
+ class Fill:
515
+ """``w14:textFill`` (or the fill of ``w14:textOutline``).
516
+
517
+ ``kind`` is ``gradient``, ``solid``, or ``none``. A gradient has ``stops`` and either
518
+ a linear ``angle`` or a ``path`` shade (``circle``, ``rect``, ``shape``).
519
+ """
520
+
521
+ kind: Literal["gradient", "solid", "none"]
522
+ color: EffectColor | None = None
523
+ stops: tuple[GradientStop, ...] = ()
524
+ angle: int | None = None
525
+ scaled: bool = False
526
+ path: str | None = None
527
+
528
+ @classmethod
529
+ def from_dict(cls, value: Any, code: str = "fill") -> Fill:
530
+ if not isinstance(value, Mapping):
531
+ raise _fail(f"{code}_invalid")
532
+ kind = value.get("type")
533
+ if kind == "none":
534
+ _keys(value, {"type"}, {"type"}, code)
535
+ return cls("none")
536
+ if kind == "solid":
537
+ spec = _keys(value, {"type"} | _COLOR_KEYS, {"type", "color"}, code)
538
+ return cls("solid", color=_color_from(spec, code))
539
+ if kind != "gradient":
540
+ raise _fail(f"{code}_type_invalid")
541
+ spec = _keys(value, {"type", "stops", "angle", "scaled", "path"}, {"type", "stops"}, code)
542
+ raw_stops = spec["stops"]
543
+ if (
544
+ not isinstance(raw_stops, Sequence)
545
+ or isinstance(raw_stops, (str, bytes))
546
+ or not 2 <= len(raw_stops) <= _MAX_GRADIENT_STOPS
547
+ ):
548
+ raise _fail(f"{code}_stops_invalid")
549
+ stops: list[GradientStop] = []
550
+ for raw in raw_stops:
551
+ stop = _keys(raw, {"position"} | _COLOR_KEYS, {"position", "color"}, f"{code}_stop")
552
+ stops.append(
553
+ GradientStop(
554
+ position=_percent(stop["position"], f"{code}_stop_position_invalid"),
555
+ color=_color_from(stop, f"{code}_stop"),
556
+ )
557
+ )
558
+ if any(a.position > b.position for a, b in itertools.pairwise(stops)):
559
+ raise _fail(f"{code}_stops_unordered")
560
+ if "path" in spec and "angle" in spec:
561
+ raise _fail(f"{code}_shade_conflict")
562
+ path = (
563
+ _choice(spec["path"], _PATH_SHADES, f"text_effect_{code}_path_invalid")
564
+ if "path" in spec
565
+ else None
566
+ )
567
+ scaled = spec.get("scaled", False)
568
+ if not isinstance(scaled, bool):
569
+ raise _fail(f"{code}_scaled_invalid")
570
+ angle = None if path else _angle(spec.get("angle", 0), f"{code}_angle_invalid")
571
+ return cls("gradient", stops=tuple(stops), angle=angle, scaled=scaled, path=path)
572
+
573
+ def to_dict(self) -> dict[str, Any]:
574
+ if self.kind == "none":
575
+ return {"type": "none"}
576
+ if self.kind == "solid":
577
+ assert self.color is not None
578
+ return {"type": "solid", **self.color.to_dict()}
579
+ result: dict[str, Any] = {
580
+ "type": "gradient",
581
+ "stops": [stop.to_dict() for stop in self.stops],
582
+ }
583
+ if self.path is not None:
584
+ result["path"] = self.path
585
+ else:
586
+ assert self.angle is not None
587
+ result["angle"] = _units_out(self.angle, _ANGLE_UNIT)
588
+ result["scaled"] = self.scaled
589
+ return result
590
+
591
+
592
+ @dataclass(frozen=True)
593
+ class Outline:
594
+ width: int
595
+ fill: Fill
596
+ dash: str = "solid"
597
+ join: str = "round"
598
+ cap: str = "flat"
599
+ compound: str = "sng"
600
+ alignment: str = "ctr"
601
+
602
+ @classmethod
603
+ def from_dict(cls, value: Any) -> Outline:
604
+ allowed = {
605
+ "width",
606
+ "fill",
607
+ "dash",
608
+ "join",
609
+ "cap",
610
+ "compound",
611
+ "alignment",
612
+ } | _COLOR_KEYS
613
+ spec = _keys(value, allowed, {"width"}, "outline")
614
+ if ("fill" in spec) == ("color" in spec):
615
+ raise _fail("outline_fill_invalid")
616
+ if "fill" in spec:
617
+ if set(spec) & {"transparency", "color_modifiers"}:
618
+ raise _fail("outline_fill_invalid")
619
+ fill = Fill.from_dict(spec["fill"], "outline_fill")
620
+ else:
621
+ fill = Fill("solid", color=_color_from(spec, "outline"))
622
+ return cls(
623
+ width=_points(spec["width"], "outline_width_invalid", _MAX_OUTLINE_PT),
624
+ fill=fill,
625
+ dash=_choice(spec.get("dash", "solid"), _DASHES, "text_effect_outline_dash_invalid"),
626
+ join=_choice(spec.get("join", "round"), _JOINS, "text_effect_outline_join_invalid"),
627
+ cap=_choice(spec.get("cap", "flat"), _CAPS, "text_effect_outline_cap_invalid"),
628
+ compound=_choice(
629
+ spec.get("compound", "sng"),
630
+ _COMPOUNDS,
631
+ "text_effect_outline_compound_invalid",
632
+ ),
633
+ alignment=_choice(
634
+ spec.get("alignment", "ctr"),
635
+ _PEN_ALIGNMENTS,
636
+ "text_effect_outline_alignment_invalid",
637
+ ),
638
+ )
639
+
640
+ def to_dict(self) -> dict[str, Any]:
641
+ result: dict[str, Any] = {
642
+ "width": _points_out(self.width),
643
+ "dash": self.dash,
644
+ "join": self.join,
645
+ "cap": self.cap,
646
+ "compound": self.compound,
647
+ "alignment": self.alignment,
648
+ }
649
+ if self.fill.kind == "solid":
650
+ assert self.fill.color is not None
651
+ result.update(self.fill.color.to_dict())
652
+ else:
653
+ result["fill"] = self.fill.to_dict()
654
+ return result
655
+
656
+
657
+ _EFFECT_PARSERS: dict[str, Any] = {
658
+ "glow": Glow.from_dict,
659
+ "shadow": OuterShadow.from_dict,
660
+ "reflection": Reflection.from_dict,
661
+ "outline": Outline.from_dict,
662
+ "fill": Fill.from_dict,
663
+ }
664
+
665
+ Effect = Glow | OuterShadow | Reflection | Outline | Fill
666
+
667
+
668
+ @dataclass(frozen=True)
669
+ class TextEffects:
670
+ """Per effect: a spec sets it, ``False`` removes it, ``None`` leaves it unchanged."""
671
+
672
+ glow: Glow | Literal[False] | None = None
673
+ shadow: OuterShadow | Literal[False] | None = None
674
+ reflection: Reflection | Literal[False] | None = None
675
+ outline: Outline | Literal[False] | None = None
676
+ fill: Fill | Literal[False] | None = None
677
+
678
+ @classmethod
679
+ def from_dict(cls, value: Any) -> TextEffects:
680
+ spec = _keys(value, set(EFFECT_KEYS), set(), "effects")
681
+ parsed: dict[str, Any] = {}
682
+ for key, raw in spec.items():
683
+ if raw is False:
684
+ parsed[key] = False
685
+ elif raw is None:
686
+ continue
687
+ else:
688
+ parsed[key] = _EFFECT_PARSERS[key](raw)
689
+ result = cls(**parsed)
690
+ if result.is_empty():
691
+ raise _fail("effects_missing")
692
+ return result
693
+
694
+ def items(self) -> list[tuple[str, Effect | Literal[False]]]:
695
+ return [(key, getattr(self, key)) for key in EFFECT_KEYS if getattr(self, key) is not None]
696
+
697
+ def is_empty(self) -> bool:
698
+ return not self.items()
699
+
700
+ def to_dict(self) -> dict[str, Any]:
701
+ return {key: (False if value is False else value.to_dict()) for key, value in self.items()}
702
+
703
+
704
+ @dataclass(frozen=True)
705
+ class TextEffectEdit:
706
+ """Text effects applied to ``expected_old_text`` at ``start:end`` of one paragraph."""
707
+
708
+ paragraph: int
709
+ start: int
710
+ end: int
711
+ expected_old_text: str
712
+ structure_fingerprint_sha256: str
713
+ effects: TextEffects
714
+ part: str = _DOCUMENT
715
+
716
+ def to_dict(self) -> dict[str, Any]:
717
+ return {
718
+ "part": self.part,
719
+ "paragraph": self.paragraph,
720
+ "start": self.start,
721
+ "end": self.end,
722
+ "expected_old_text": self.expected_old_text,
723
+ "structure_fingerprint_sha256": self.structure_fingerprint_sha256,
724
+ "effects": self.effects.to_dict(),
725
+ }
726
+
727
+
728
+ @dataclass(frozen=True)
729
+ class TextEffectRequest:
730
+ source: Path
731
+ source_sha256: str
732
+ destination: Path
733
+ edits: tuple[TextEffectEdit, ...] = ()
734
+
735
+
736
+ @dataclass(frozen=True)
737
+ class TextEffectReport:
738
+ """Content-safe receipt for one atomic text-effect authoring request."""
739
+
740
+ status: str
741
+ code: str | None
742
+ source_sha256: str
743
+ destination_sha256: str | None
744
+ edits: list[dict[str, Any]] = field(default_factory=list)
745
+
746
+ @property
747
+ def passed(self) -> bool:
748
+ return self.status == _PUBLISHED
749
+
750
+ def to_dict(self) -> dict[str, Any]:
751
+ return {
752
+ "schema_version": 1,
753
+ "passed": self.passed,
754
+ "status": self.status,
755
+ "code": self.code,
756
+ "source_sha256": self.source_sha256,
757
+ "destination_sha256": self.destination_sha256,
758
+ "edits": self.edits,
759
+ }
760
+
761
+
762
+ def _parse_edit(value: Any) -> TextEffectEdit:
763
+ spec = _keys(
764
+ value,
765
+ {
766
+ "part",
767
+ "paragraph",
768
+ "start",
769
+ "end",
770
+ "expected_old_text",
771
+ "structure_fingerprint_sha256",
772
+ "effects",
773
+ },
774
+ {
775
+ "paragraph",
776
+ "start",
777
+ "end",
778
+ "expected_old_text",
779
+ "structure_fingerprint_sha256",
780
+ "effects",
781
+ },
782
+ "edit",
783
+ )
784
+ paragraph = spec["paragraph"]
785
+ if isinstance(paragraph, bool) or not isinstance(paragraph, int) or paragraph < 1:
786
+ raise _fail("paragraph_invalid")
787
+ start, end = spec["start"], spec["end"]
788
+ if (
789
+ isinstance(start, bool)
790
+ or not isinstance(start, int)
791
+ or isinstance(end, bool)
792
+ or not isinstance(end, int)
793
+ or start < 0
794
+ or end <= start
795
+ ):
796
+ raise _fail("range_invalid")
797
+ expected = spec["expected_old_text"]
798
+ if not isinstance(expected, str) or len(expected) != end - start:
799
+ raise _fail("expected_text_invalid")
800
+ part = spec.get("part", _DOCUMENT)
801
+ if not isinstance(part, str) or not part:
802
+ raise _fail("part_invalid")
803
+ try:
804
+ fingerprint = _sha(
805
+ spec["structure_fingerprint_sha256"], "text_effect_structure_fingerprint"
806
+ )
807
+ except ValueError as error:
808
+ raise TextEffectError(str(error)) from None
809
+ return TextEffectEdit(
810
+ paragraph=paragraph,
811
+ start=start,
812
+ end=end,
813
+ expected_old_text=expected,
814
+ structure_fingerprint_sha256=fingerprint,
815
+ effects=TextEffects.from_dict(spec["effects"]),
816
+ part=part,
817
+ )
818
+
819
+
820
+ def parse_text_effect_request(value: Any) -> TextEffectRequest:
821
+ """Parse the strict JSON request; malformed input raises :class:`TextEffectError`."""
822
+ spec = _keys(
823
+ value,
824
+ {"source", "source_sha256", "destination", "edits"},
825
+ {"source", "source_sha256", "destination", "edits"},
826
+ "request",
827
+ )
828
+ source, destination = spec["source"], spec["destination"]
829
+ if not isinstance(source, str) or not source:
830
+ raise _fail("source_path_invalid")
831
+ if not isinstance(destination, str) or not destination:
832
+ raise _fail("destination_path_invalid")
833
+ try:
834
+ source_sha256 = _sha(spec["source_sha256"], "text_effect_source_sha256")
835
+ except ValueError as error:
836
+ raise TextEffectError(str(error)) from None
837
+ raw_edits = spec["edits"]
838
+ if not isinstance(raw_edits, Sequence) or isinstance(raw_edits, (str, bytes)) or not raw_edits:
839
+ raise _fail("edits_missing")
840
+ return TextEffectRequest(
841
+ source=Path(source),
842
+ source_sha256=source_sha256,
843
+ destination=Path(destination),
844
+ edits=tuple(_parse_edit(item) for item in raw_edits),
845
+ )
846
+
847
+
848
+ def load_text_effect_request(path: str | Path) -> TextEffectRequest:
849
+ with Path(path).open(encoding="utf-8") as stream:
850
+ return parse_text_effect_request(json.load(stream))
851
+
852
+
853
+ # --- XML writing ---------------------------------------------------------------------
854
+
855
+
856
+ def _w14(local: str) -> str:
857
+ return Q(W14, local)
858
+
859
+
860
+ def _color_element(color: EffectColor) -> ET.Element:
861
+ element = ET.Element(
862
+ _w14("schemeClr" if color.is_scheme else "srgbClr"), {_w14("val"): color.value}
863
+ )
864
+ transforms = dict(color.modifiers)
865
+ if color.transparency:
866
+ transforms["alpha"] = color.transparency
867
+ for name in _COLOR_TRANSFORM_ORDER:
868
+ if name in transforms:
869
+ ET.SubElement(element, _w14(name), {_w14("val"): str(transforms[name])})
870
+ return element
871
+
872
+
873
+ def _fill_children(fill: Fill) -> list[ET.Element]:
874
+ if fill.kind == "none":
875
+ return [ET.Element(_w14("noFill"))]
876
+ if fill.kind == "solid":
877
+ assert fill.color is not None
878
+ solid = ET.Element(_w14("solidFill"))
879
+ solid.append(_color_element(fill.color))
880
+ return [solid]
881
+ gradient = ET.Element(_w14("gradFill"))
882
+ stops = ET.SubElement(gradient, _w14("gsLst"))
883
+ for stop in fill.stops:
884
+ node = ET.SubElement(stops, _w14("gs"), {_w14("pos"): str(stop.position)})
885
+ node.append(_color_element(stop.color))
886
+ if fill.path is not None:
887
+ shade = ET.SubElement(gradient, _w14("path"), {_w14("path"): fill.path})
888
+ ET.SubElement(
889
+ shade,
890
+ _w14("fillToRect"),
891
+ {
892
+ _w14("l"): "50000",
893
+ _w14("t"): "50000",
894
+ _w14("r"): "50000",
895
+ _w14("b"): "50000",
896
+ },
897
+ )
898
+ else:
899
+ ET.SubElement(
900
+ gradient,
901
+ _w14("lin"),
902
+ {_w14("ang"): str(fill.angle), _w14("scaled"): "1" if fill.scaled else "0"},
903
+ )
904
+ return [gradient]
905
+
906
+
907
+ def _attrs(pairs: Sequence[tuple[str, Any]]) -> dict[str, str]:
908
+ return {_w14(name): str(value) for name, value in pairs}
909
+
910
+
911
+ def effect_element(key: str, effect: Effect) -> ET.Element:
912
+ """The ``w14`` element Word writes for one effect."""
913
+ if isinstance(effect, Glow):
914
+ element = ET.Element(_w14("glow"), _attrs([("rad", effect.radius)]))
915
+ element.append(_color_element(effect.color))
916
+ return element
917
+ if isinstance(effect, OuterShadow):
918
+ element = ET.Element(
919
+ _w14("shadow"),
920
+ _attrs(
921
+ [
922
+ ("blurRad", effect.blur),
923
+ ("dist", effect.distance),
924
+ ("dir", effect.direction),
925
+ ("sx", effect.scale_x),
926
+ ("sy", effect.scale_y),
927
+ ("kx", effect.skew_x),
928
+ ("ky", effect.skew_y),
929
+ ("algn", effect.alignment),
930
+ ]
931
+ ),
932
+ )
933
+ element.append(_color_element(effect.color))
934
+ return element
935
+ if isinstance(effect, Reflection):
936
+ return ET.Element(
937
+ _w14("reflection"),
938
+ _attrs(
939
+ [
940
+ ("blurRad", effect.blur),
941
+ ("stA", effect.start_opacity),
942
+ ("stPos", effect.start_position),
943
+ ("endA", effect.end_opacity),
944
+ ("endPos", effect.end_position),
945
+ ("dist", effect.distance),
946
+ ("dir", effect.direction),
947
+ ("fadeDir", effect.fade_direction),
948
+ ("sx", effect.scale_x),
949
+ ("sy", effect.scale_y),
950
+ ("kx", effect.skew_x),
951
+ ("ky", effect.skew_y),
952
+ ("algn", effect.alignment),
953
+ ]
954
+ ),
955
+ )
956
+ if isinstance(effect, Outline):
957
+ element = ET.Element(
958
+ _w14("textOutline"),
959
+ _attrs(
960
+ [
961
+ ("w", effect.width),
962
+ ("cap", effect.cap),
963
+ ("cmpd", effect.compound),
964
+ ("algn", effect.alignment),
965
+ ]
966
+ ),
967
+ )
968
+ element.extend(_fill_children(effect.fill))
969
+ ET.SubElement(element, _w14("prstDash"), {_w14("val"): effect.dash})
970
+ if effect.join == "miter":
971
+ ET.SubElement(element, _w14("miter"), {_w14("lim"): "800000"})
972
+ else:
973
+ ET.SubElement(element, _w14(effect.join))
974
+ return element
975
+ assert isinstance(effect, Fill) and key == "fill"
976
+ element = ET.Element(_w14("textFill"))
977
+ element.extend(_fill_children(effect))
978
+ return element
979
+
980
+
981
+ def _apply_effects(run: ET.Element, effects: TextEffects, namespace: str) -> None:
982
+ rpr = run.find(Q(namespace, "rPr"))
983
+ if rpr is None:
984
+ rpr = ET.Element(Q(namespace, "rPr"))
985
+ run.insert(0, rpr)
986
+ for key, value in effects.items():
987
+ for existing in rpr.findall(_w14(_ELEMENT_FOR_KEY[key])):
988
+ rpr.remove(existing)
989
+ if value is not False:
990
+ rpr.append(effect_element(key, value))
991
+ word = [child for child in rpr if not child.tag.startswith(f"{{{W14}}}")]
992
+ trailing = [child for child in word if _local_name(child.tag) == "rPrChange"]
993
+ leading = [child for child in word if _local_name(child.tag) != "rPrChange"]
994
+ w14 = sorted(
995
+ (child for child in rpr if child.tag.startswith(f"{{{W14}}}")),
996
+ key=lambda child: _W14_RANK.get(_local_name(child.tag), len(_W14_RANK)),
997
+ )
998
+ rpr[:] = leading + w14 + trailing
999
+ if not len(rpr):
1000
+ run.remove(rpr)
1001
+
1002
+
1003
+ def _declare_w14(root: ET.Element) -> None:
1004
+ """Bind ``w14`` on the root and list it in ``mc:Ignorable`` (Word 2007 readers)."""
1005
+ if not isinstance(root, _QNameElement):
1006
+ return
1007
+ scope = dict(root._namespace_scope)
1008
+ prefix = next((p for p, uri in scope.items() if p and uri == W14), None)
1009
+ if prefix is None:
1010
+ prefix = "w14"
1011
+ index = 0
1012
+ while prefix in scope:
1013
+ index += 1
1014
+ prefix = f"w14x{index}"
1015
+ scope[prefix] = W14
1016
+ if not any(p and uri == MC for p, uri in scope.items()):
1017
+ mc_prefix = "mc"
1018
+ index = 0
1019
+ while mc_prefix in scope:
1020
+ index += 1
1021
+ mc_prefix = f"mc{index}"
1022
+ scope[mc_prefix] = MC
1023
+ # The attribute's inferred type is its two-binding default; any binding tuple is valid.
1024
+ root._namespace_scope = tuple(scope.items()) # type: ignore[assignment]
1025
+ ignorable = (root.get(Q(MC, "Ignorable")) or "").split()
1026
+ if prefix not in ignorable:
1027
+ ignorable.append(prefix)
1028
+ root.set(Q(MC, "Ignorable"), " ".join(ignorable))
1029
+
1030
+
1031
+ # --- Reading -------------------------------------------------------------------------
1032
+
1033
+
1034
+ def _int_attr(element: ET.Element, local: str, default: int) -> int:
1035
+ raw = element.get(_w14(local))
1036
+ if raw is None:
1037
+ return default
1038
+ try:
1039
+ return int(raw)
1040
+ except ValueError:
1041
+ return default
1042
+
1043
+
1044
+ def _read_color(parent: ET.Element | None) -> EffectColor | None:
1045
+ if parent is None:
1046
+ return None
1047
+ for child in parent:
1048
+ local = _local_name(child.tag)
1049
+ if not child.tag.startswith(f"{{{W14}}}") or local not in {
1050
+ "srgbClr",
1051
+ "schemeClr",
1052
+ }:
1053
+ continue
1054
+ value = child.get(_w14("val")) or ""
1055
+ if local == "srgbClr":
1056
+ value = value.upper()
1057
+ transparency = 0
1058
+ modifiers: list[tuple[str, int]] = []
1059
+ for transform in child:
1060
+ name = _local_name(transform.tag)
1061
+ amount = _int_attr(transform, "val", 0)
1062
+ if name == "alpha":
1063
+ transparency = amount
1064
+ elif name in _COLOR_MODIFIERS:
1065
+ modifiers.append((name, amount))
1066
+ modifiers.sort(key=lambda item: _COLOR_TRANSFORM_ORDER.index(item[0]))
1067
+ return EffectColor(value, transparency, tuple(modifiers))
1068
+ return None
1069
+
1070
+
1071
+ def _read_fill(parent: ET.Element) -> Fill | None:
1072
+ for child in parent:
1073
+ local = _local_name(child.tag)
1074
+ if local == "noFill":
1075
+ return Fill("none")
1076
+ if local == "solidFill":
1077
+ color = _read_color(child)
1078
+ return Fill("solid", color=color) if color else None
1079
+ if local == "gradFill":
1080
+ stops: list[GradientStop] = []
1081
+ for stop in child.iter(_w14("gs")):
1082
+ color = _read_color(stop)
1083
+ if color is not None:
1084
+ stops.append(GradientStop(_int_attr(stop, "pos", 0), color))
1085
+ stops.sort(key=lambda stop: stop.position)
1086
+ linear = child.find(_w14("lin"))
1087
+ shade = child.find(_w14("path"))
1088
+ if shade is not None:
1089
+ return Fill(
1090
+ "gradient",
1091
+ stops=tuple(stops),
1092
+ path=shade.get(_w14("path"), "circle"),
1093
+ )
1094
+ angle = _int_attr(linear, "ang", 0) if linear is not None else 0
1095
+ scaled = linear is not None and linear.get(_w14("scaled")) in {
1096
+ "1",
1097
+ "true",
1098
+ "on",
1099
+ }
1100
+ return Fill("gradient", stops=tuple(stops), angle=angle, scaled=scaled)
1101
+ return None
1102
+
1103
+
1104
+ def read_effect(element: ET.Element) -> tuple[str, Effect] | None:
1105
+ """Parse one ``w14`` run property element, or ``None`` when it is not one of the five."""
1106
+ local = _local_name(element.tag)
1107
+ if not element.tag.startswith(f"{{{W14}}}") or local not in _KEY_FOR_ELEMENT:
1108
+ return None
1109
+ key = _KEY_FOR_ELEMENT[local]
1110
+ if local == "glow":
1111
+ color = _read_color(element)
1112
+ return (key, Glow(_int_attr(element, "rad", 0), color)) if color else None
1113
+ if local == "shadow":
1114
+ color = _read_color(element)
1115
+ if color is None:
1116
+ return None
1117
+ return key, OuterShadow(
1118
+ color=color,
1119
+ blur=_int_attr(element, "blurRad", 0),
1120
+ distance=_int_attr(element, "dist", 0),
1121
+ direction=_int_attr(element, "dir", 0),
1122
+ scale_x=_int_attr(element, "sx", 100_000),
1123
+ scale_y=_int_attr(element, "sy", 100_000),
1124
+ skew_x=_int_attr(element, "kx", 0),
1125
+ skew_y=_int_attr(element, "ky", 0),
1126
+ alignment=element.get(_w14("algn"), "b"),
1127
+ )
1128
+ if local == "reflection":
1129
+ return key, Reflection(
1130
+ blur=_int_attr(element, "blurRad", 0),
1131
+ distance=_int_attr(element, "dist", 0),
1132
+ start_opacity=_int_attr(element, "stA", 100_000),
1133
+ start_position=_int_attr(element, "stPos", 0),
1134
+ end_opacity=_int_attr(element, "endA", 0),
1135
+ end_position=_int_attr(element, "endPos", 100_000),
1136
+ direction=_int_attr(element, "dir", 0),
1137
+ fade_direction=_int_attr(element, "fadeDir", 5_400_000),
1138
+ scale_x=_int_attr(element, "sx", 100_000),
1139
+ scale_y=_int_attr(element, "sy", 100_000),
1140
+ skew_x=_int_attr(element, "kx", 0),
1141
+ skew_y=_int_attr(element, "ky", 0),
1142
+ alignment=element.get(_w14("algn"), "b"),
1143
+ )
1144
+ if local == "textOutline":
1145
+ fill = _read_fill(element) or Fill("none")
1146
+ dash = element.find(_w14("prstDash"))
1147
+ join = next(
1148
+ (_local_name(child.tag) for child in element if _local_name(child.tag) in _JOINS),
1149
+ "round",
1150
+ )
1151
+ return key, Outline(
1152
+ width=_int_attr(element, "w", 0),
1153
+ fill=fill,
1154
+ dash=dash.get(_w14("val"), "solid") if dash is not None else "solid",
1155
+ join=join,
1156
+ cap=element.get(_w14("cap"), "flat"),
1157
+ compound=element.get(_w14("cmpd"), "sng"),
1158
+ alignment=element.get(_w14("algn"), "ctr"),
1159
+ )
1160
+ text_fill = _read_fill(element)
1161
+ return (key, text_fill) if text_fill else None
1162
+
1163
+
1164
+ def _effects_of(rpr: ET.Element | None) -> dict[str, Effect]:
1165
+ effects: dict[str, Effect] = {}
1166
+ if rpr is None:
1167
+ return effects
1168
+ for child in rpr:
1169
+ parsed = read_effect(child)
1170
+ if parsed is not None:
1171
+ effects[parsed[0]] = parsed[1]
1172
+ return effects
1173
+
1174
+
1175
+ def _style_effects(
1176
+ styles_root: ET.Element | None, namespace: str
1177
+ ) -> tuple[dict[str, tuple[str | None, dict[str, Effect]]], dict[str, Effect]]:
1178
+ if styles_root is None:
1179
+ return {}, {}
1180
+
1181
+ def word(local: str) -> str:
1182
+ return Q(namespace, local)
1183
+
1184
+ defaults = _effects_of(
1185
+ styles_root.find(f"{word('docDefaults')}/{word('rPrDefault')}/{word('rPr')}")
1186
+ )
1187
+ styles: dict[str, tuple[str | None, dict[str, Effect]]] = {}
1188
+ for style in styles_root.findall(word("style")):
1189
+ style_id = style.get(word("styleId"))
1190
+ if not style_id:
1191
+ continue
1192
+ based_on = style.find(word("basedOn"))
1193
+ styles[style_id] = (
1194
+ based_on.get(word("val")) if based_on is not None else None,
1195
+ _effects_of(style.find(word("rPr"))),
1196
+ )
1197
+ return styles, defaults
1198
+
1199
+
1200
+ def _chain_effects(
1201
+ style_id: str | None, styles: Mapping[str, tuple[str | None, dict[str, Effect]]]
1202
+ ) -> dict[str, Effect]:
1203
+ chain: list[dict[str, Effect]] = []
1204
+ seen: set[str] = set()
1205
+ while style_id and style_id not in seen and style_id in styles:
1206
+ seen.add(style_id)
1207
+ based_on, effects = styles[style_id]
1208
+ chain.append(effects)
1209
+ style_id = based_on
1210
+ resolved: dict[str, Effect] = {}
1211
+ for effects in reversed(chain):
1212
+ resolved.update(effects)
1213
+ return resolved
1214
+
1215
+
1216
+ def _as_dict(effects: Mapping[str, Effect]) -> dict[str, Any]:
1217
+ return {key: effects[key].to_dict() for key in EFFECT_KEYS if key in effects}
1218
+
1219
+
1220
+ def inspect_text_effects(source: str | Path, *, part: str = _DOCUMENT) -> dict[str, Any]:
1221
+ """Report the five text effects of every run in ``part``.
1222
+
1223
+ ``runs`` lists every ``w:r`` with direct or inherited effects, in document order:
1224
+ 1-based ``paragraph`` (as in :func:`wolfdocx.formatting.discover_format_targets`),
1225
+ 0-based ``run`` within the paragraph, the run's ``start``/``end`` text offsets,
1226
+ ``effects`` (direct ``w:rPr``) and ``resolved_effects`` (document defaults, the
1227
+ paragraph style chain, the character style chain, then direct, each effect replacing
1228
+ the one before). Each effect dict is a valid authoring spec.
1229
+ """
1230
+ path = Path(source)
1231
+ failure = {"passed": False, "part": part, "runs": []}
1232
+ try:
1233
+ graph = PackageGraph.from_file(path)
1234
+ document_root = ET.fromstring(graph.read_part_bytes(_DOCUMENT))
1235
+ except (OSError, PackageError, zipfile.BadZipFile, ET.ParseError, KeyError):
1236
+ return {**failure, "code": "text_effect_package_invalid"}
1237
+ namespace = _word_namespace(document_root)
1238
+ if namespace is None:
1239
+ return {**failure, "code": "text_effect_namespace_unsupported"}
1240
+ if part not in _review_parts(graph, document_root, namespace):
1241
+ return {**failure, "code": "text_effect_part_unsupported"}
1242
+ try:
1243
+ root = ET.fromstring(graph.read_part_bytes(part))
1244
+ styles_root = (
1245
+ ET.fromstring(graph.read_part_bytes(_STYLES)) if _STYLES in graph.parts else None
1246
+ )
1247
+ except (OSError, PackageError, ET.ParseError, KeyError):
1248
+ return {**failure, "code": "text_effect_package_invalid"}
1249
+ styles, defaults = _style_effects(styles_root, namespace)
1250
+
1251
+ def word(local: str) -> str:
1252
+ return Q(namespace, local)
1253
+
1254
+ runs: list[dict[str, Any]] = []
1255
+ for paragraph_index, paragraph in enumerate(root.iter(word("p")), start=1):
1256
+ ppr = paragraph.find(word("pPr"))
1257
+ paragraph_style = ppr.find(word("pStyle")) if ppr is not None else None
1258
+ paragraph_effects = dict(defaults)
1259
+ paragraph_effects.update(
1260
+ _chain_effects(
1261
+ paragraph_style.get(word("val")) if paragraph_style is not None else None,
1262
+ styles,
1263
+ )
1264
+ )
1265
+ offset = 0
1266
+ for run_index, run in enumerate(paragraph.iter(word("r"))):
1267
+ text = "".join(node.text or "" for node in run.iter(word("t")))
1268
+ start, offset = offset, offset + len(text)
1269
+ rpr = run.find(word("rPr"))
1270
+ character_style = rpr.find(word("rStyle")) if rpr is not None else None
1271
+ style_id = character_style.get(word("val")) if character_style is not None else None
1272
+ direct = _effects_of(rpr)
1273
+ resolved = dict(paragraph_effects)
1274
+ resolved.update(_chain_effects(style_id, styles))
1275
+ resolved.update(direct)
1276
+ if not resolved:
1277
+ continue
1278
+ runs.append(
1279
+ {
1280
+ "paragraph": paragraph_index,
1281
+ "run": run_index,
1282
+ "start": start,
1283
+ "end": offset,
1284
+ "text": text,
1285
+ "character_style": style_id,
1286
+ "effects": _as_dict(direct),
1287
+ "resolved_effects": _as_dict(resolved),
1288
+ }
1289
+ )
1290
+ return {
1291
+ "passed": True,
1292
+ "code": None,
1293
+ "source_sha256": graph.file_sha256,
1294
+ "part": part,
1295
+ "runs": runs,
1296
+ }
1297
+
1298
+
1299
+ # --- Authoring -----------------------------------------------------------------------
1300
+
1301
+
1302
+ def _refusal(request: TextEffectRequest, code: str) -> TextEffectReport:
1303
+ return TextEffectReport(
1304
+ status=_REFUSED,
1305
+ code=code,
1306
+ source_sha256=request.source_sha256,
1307
+ destination_sha256=None,
1308
+ edits=[edit.to_dict() for edit in request.edits],
1309
+ )
1310
+
1311
+
1312
+ def _context_code(code: str) -> str:
1313
+ return "text_effect_" + code.removeprefix("format_")
1314
+
1315
+
1316
+ def author_text_effects(request: TextEffectRequest) -> TextEffectReport:
1317
+ """Apply every edit's text effects atomically, or refuse with one code."""
1318
+ source, destination = request.source, request.destination
1319
+ if not source.is_file():
1320
+ return _refusal(request, "text_effect_source_not_found")
1321
+ if _sha256(source) != request.source_sha256:
1322
+ return _refusal(request, "text_effect_source_sha256_mismatch")
1323
+ if destination.exists() or destination.is_symlink():
1324
+ return _refusal(request, "text_effect_destination_invalid")
1325
+ try:
1326
+ graph = PackageGraph.from_file(source)
1327
+ document_root = ET.fromstring(graph.read_part_bytes(_DOCUMENT))
1328
+ except (OSError, PackageError, zipfile.BadZipFile, ET.ParseError, KeyError):
1329
+ return _refusal(request, "text_effect_package_invalid")
1330
+ namespace = _word_namespace(document_root)
1331
+ if namespace is None or namespace not in SUPPORTED_WORD_NAMESPACES:
1332
+ return _refusal(request, "text_effect_namespace_unsupported")
1333
+ allowed_parts = _review_parts(graph, document_root, namespace)
1334
+
1335
+ by_paragraph: dict[tuple[str, int], list[TextEffectEdit]] = {}
1336
+ for edit in request.edits:
1337
+ if edit.part not in allowed_parts:
1338
+ return _refusal(request, "text_effect_part_unsupported")
1339
+ by_paragraph.setdefault((edit.part, edit.paragraph), []).append(edit)
1340
+ for edits in by_paragraph.values():
1341
+ ordered = sorted(edits, key=lambda edit: (edit.start, edit.end))
1342
+ if any(a.end > b.start for a, b in itertools.pairwise(ordered)):
1343
+ return _refusal(request, "text_effect_edits_overlap")
1344
+
1345
+ roots: dict[str, ET.Element] = {}
1346
+ for part_name in sorted({part for part, _ in by_paragraph}):
1347
+ try:
1348
+ root = parse_xml_with_preserved_qnames(graph.read_part_bytes(part_name))
1349
+ except (OSError, PackageError, ET.ParseError, KeyError):
1350
+ return _refusal(request, "text_effect_package_invalid")
1351
+ if _word_namespace(root) != namespace:
1352
+ return _refusal(request, "text_effect_namespace_unsupported")
1353
+ roots[part_name] = root
1354
+
1355
+ targets: dict[tuple[str, int], ET.Element] = {}
1356
+ for (part_name, index), edits in by_paragraph.items():
1357
+ root = roots[part_name]
1358
+ paragraphs = list(root.iter(Q(namespace, "p")))
1359
+ if index > len(paragraphs):
1360
+ return _refusal(request, "text_effect_paragraph_missing")
1361
+ paragraph = paragraphs[index - 1]
1362
+ fingerprint = _mask_text(paragraph, namespace)
1363
+ if any(edit.structure_fingerprint_sha256 != fingerprint for edit in edits):
1364
+ return _refusal(request, "text_effect_structure_fingerprint_mismatch")
1365
+ parents = {id(child): parent for parent in root.iter() for child in parent}
1366
+ context = _detect_context_unsupported(paragraph) or _is_inside_sdt_or_unsupported(
1367
+ paragraph, parents
1368
+ )
1369
+ if context:
1370
+ return _refusal(request, _context_code(context))
1371
+ try:
1372
+ text = _paragraph_map(paragraph, namespace).text
1373
+ except _ReviewContextError:
1374
+ return _refusal(request, "text_effect_context_unsupported")
1375
+ for edit in edits:
1376
+ if edit.end > len(text):
1377
+ return _refusal(request, "text_effect_range_invalid")
1378
+ if text[edit.start : edit.end] != edit.expected_old_text:
1379
+ return _refusal(request, "text_effect_expected_text_mismatch")
1380
+ targets[(part_name, index)] = paragraph
1381
+
1382
+ for key, paragraph in targets.items():
1383
+ edits = by_paragraph[key]
1384
+ mapping = _paragraph_map(paragraph, namespace)
1385
+ runs_by_id = {id(run.element): run for run in mapping.runs}
1386
+ boundaries = sorted({edit.start for edit in edits} | {edit.end for edit in edits})
1387
+ for child in list(paragraph):
1388
+ run = runs_by_id.get(id(child))
1389
+ if run is None or not run.text:
1390
+ continue
1391
+ cuts = [
1392
+ run.start,
1393
+ *(b for b in boundaries if run.start < b < run.end),
1394
+ run.end,
1395
+ ]
1396
+ pieces: list[ET.Element] = []
1397
+ for lower, upper in itertools.pairwise(cuts):
1398
+ piece = _clone_run(
1399
+ child, namespace, run.text[lower - run.start : upper - run.start]
1400
+ )
1401
+ covering = next((e for e in edits if e.start <= lower and upper <= e.end), None)
1402
+ if covering is not None:
1403
+ _apply_effects(piece, covering.effects, namespace)
1404
+ pieces.append(piece)
1405
+ position = list(paragraph).index(child)
1406
+ paragraph.remove(child)
1407
+ for offset, piece in enumerate(pieces):
1408
+ paragraph.insert(position + offset, piece)
1409
+
1410
+ for root in roots.values():
1411
+ _declare_w14(root)
1412
+ replacements = {name: serialize_xml_with_preserved_qnames(root) for name, root in roots.items()}
1413
+ changed = [edit.to_dict() for edit in request.edits]
1414
+
1415
+ def verifier(staged: Path) -> str | None:
1416
+ if not _unrelated_parts_preserved(source, staged, frozenset(replacements)):
1417
+ return "text_effect_staged_verification_failed"
1418
+ return None
1419
+
1420
+ published: ReviewReport = _publish(
1421
+ source=source,
1422
+ output=destination,
1423
+ source_sha256=request.source_sha256,
1424
+ replacements=replacements,
1425
+ revisions=[],
1426
+ targets=changed,
1427
+ verify=verifier,
1428
+ failure_code="text_effect_staged_verification_failed",
1429
+ exists_code="text_effect_destination_invalid",
1430
+ unavailable_code="text_effect_publication_unavailable",
1431
+ )
1432
+ return TextEffectReport(
1433
+ status=published.status,
1434
+ code=published.code,
1435
+ source_sha256=published.source_sha256,
1436
+ destination_sha256=published.output_sha256,
1437
+ edits=changed,
1438
+ )