dknowc-dsh 1.0.4 → 1.1.0

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 (158) hide show
  1. package/README.md +9 -4
  2. package/package.json +2 -2
  3. package/skills/dknowc-ppt-assistant/README.md +54 -0
  4. package/skills/dknowc-ppt-assistant/SKILL.md +151 -0
  5. package/skills/dknowc-ppt-assistant/THIRD_PARTY_NOTICES.md +36 -0
  6. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  7. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  8. package/skills/dknowc-ppt-assistant/projects/.gitkeep +0 -0
  9. package/skills/dknowc-ppt-assistant/references/content-pack.md +55 -0
  10. package/skills/dknowc-ppt-assistant/references/material_usage.md +51 -0
  11. package/skills/dknowc-ppt-assistant/references/sample_effect.html +89 -0
  12. package/skills/dknowc-ppt-assistant/references/sample_search_result.md +48 -0
  13. package/skills/dknowc-ppt-assistant/references/search_intro.md +79 -0
  14. package/skills/dknowc-ppt-assistant/references/style-presets.md +126 -0
  15. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +81 -0
  16. package/skills/dknowc-ppt-assistant/references/upstream-docs/svg-pipeline.md +842 -0
  17. package/skills/dknowc-ppt-assistant/references/upstream-example/01_cover.svg +28 -0
  18. package/skills/dknowc-ppt-assistant/references/upstream-example/02_quote.svg +38 -0
  19. package/skills/dknowc-ppt-assistant/references/upstream-example/03_origin.svg +96 -0
  20. package/skills/dknowc-ppt-assistant/references/upstream-example/README.md +15 -0
  21. package/skills/dknowc-ppt-assistant/references/upstream-example/design_spec.md +408 -0
  22. package/skills/dknowc-ppt-assistant/references/upstream-example/spec_lock.md +78 -0
  23. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +279 -0
  24. package/skills/dknowc-ppt-assistant/scripts/check_release.py +106 -0
  25. package/skills/dknowc-ppt-assistant/scripts/compact_svg_coordinates.py +345 -0
  26. package/skills/dknowc-ppt-assistant/scripts/config.py +707 -0
  27. package/skills/dknowc-ppt-assistant/scripts/console_encoding.py +33 -0
  28. package/skills/dknowc-ppt-assistant/scripts/error_helper.py +434 -0
  29. package/skills/dknowc-ppt-assistant/scripts/finalize_svg.py +507 -0
  30. package/skills/dknowc-ppt-assistant/scripts/hyperlink_contract.py +399 -0
  31. package/skills/dknowc-ppt-assistant/scripts/initialize.py +182 -0
  32. package/skills/dknowc-ppt-assistant/scripts/language_tags.py +283 -0
  33. package/skills/dknowc-ppt-assistant/scripts/mcp_direct.py +158 -0
  34. package/skills/dknowc-ppt-assistant/scripts/native_payloads.py +655 -0
  35. package/skills/dknowc-ppt-assistant/scripts/pptx_animation_presets.json +3440 -0
  36. package/skills/dknowc-ppt-assistant/scripts/pptx_animations.py +3965 -0
  37. package/skills/dknowc-ppt-assistant/scripts/pptx_effects.py +143 -0
  38. package/skills/dknowc-ppt-assistant/scripts/pptx_opc_validation.py +346 -0
  39. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/__init__.py +130 -0
  40. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-APACHE-2.0.txt +202 -0
  41. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-OPEN-XML-SDK-MIT.txt +23 -0
  42. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/NOTICE.md +54 -0
  43. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeDefinitions.xml +19898 -0
  44. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeSemantics.json +1217 -0
  45. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/shape_type_values.txt +187 -0
  46. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/errors.py +39 -0
  47. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/formula.py +336 -0
  48. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/loader.py +364 -0
  49. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/models.py +201 -0
  50. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/registry.py +270 -0
  51. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantic_hash.py +456 -0
  52. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantics.py +543 -0
  53. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/xml_safety.py +21 -0
  54. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/__init__.py +21 -0
  55. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/animation_import.py +287 -0
  56. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chart_to_svg.py +2377 -0
  57. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chartex_to_svg.py +422 -0
  58. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/color_resolver.py +894 -0
  59. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/converter.py +1143 -0
  60. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/custgeom_to_svg.py +165 -0
  61. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/effect_to_svg.py +410 -0
  62. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/emu_units.py +258 -0
  63. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/fill_to_svg.py +816 -0
  64. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/formula_import.py +611 -0
  65. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/hyperlinks.py +93 -0
  66. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/import_diagnostics.py +37 -0
  67. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ln_to_svg.py +362 -0
  68. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/normalized_chart_svg.py +1217 -0
  69. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ooxml_loader.py +506 -0
  70. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/pic_to_svg.py +653 -0
  71. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_authoring.py +894 -0
  72. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_registry_to_svg.py +216 -0
  73. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_svg_markup.py +198 -0
  74. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/prstgeom_to_svg.py +162 -0
  75. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/shape_walker.py +556 -0
  76. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/slide_to_svg.py +2002 -0
  77. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/tbl_to_svg.py +1841 -0
  78. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/transition_import.py +201 -0
  79. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/txbody_to_svg.py +1433 -0
  80. package/skills/dknowc-ppt-assistant/scripts/pptx_transitions.py +3153 -0
  81. package/skills/dknowc-ppt-assistant/scripts/preset_shape_svg.py +450 -0
  82. package/skills/dknowc-ppt-assistant/scripts/project_utils.py +645 -0
  83. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +183 -0
  84. package/skills/dknowc-ppt-assistant/scripts/register_template.py +1327 -0
  85. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1048 -0
  86. package/skills/dknowc-ppt-assistant/scripts/resource_paths.py +282 -0
  87. package/skills/dknowc-ppt-assistant/scripts/shape_boolean_svg.py +189 -0
  88. package/skills/dknowc-ppt-assistant/scripts/slide_roster.py +44 -0
  89. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/__init__.py +12 -0
  90. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/align_embed_images.py +672 -0
  91. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/crop_images.py +370 -0
  92. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_icons.py +564 -0
  93. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_images.py +288 -0
  94. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/fix_image_aspect.py +389 -0
  95. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/flatten_tspan.py +948 -0
  96. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/svg_rect_to_path.py +346 -0
  97. package/skills/dknowc-ppt-assistant/scripts/svg_quality/__init__.py +15 -0
  98. package/skills/dknowc-ppt-assistant/scripts/svg_quality/checker.py +7791 -0
  99. package/skills/dknowc-ppt-assistant/scripts/svg_quality/cli.py +193 -0
  100. package/skills/dknowc-ppt-assistant/scripts/svg_quality/svg_contracts.py +1121 -0
  101. package/skills/dknowc-ppt-assistant/scripts/svg_quality/xml_support.py +35 -0
  102. package/skills/dknowc-ppt-assistant/scripts/svg_quality_checker.py +59 -0
  103. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/__init__.py +37 -0
  104. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/animation_config.py +1622 -0
  105. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/canvas_contract.py +226 -0
  106. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/__init__.py +1 -0
  107. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/context.py +291 -0
  108. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/converter.py +1980 -0
  109. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/elements.py +5272 -0
  110. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/hyperlinks.py +162 -0
  111. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/paths.py +847 -0
  112. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/styles.py +752 -0
  113. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/text_properties.py +796 -0
  114. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_colors.py +283 -0
  115. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_fonts.py +330 -0
  116. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/utils.py +3555 -0
  117. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/geometry_properties.py +140 -0
  118. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/__init__.py +356 -0
  119. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_data.py +1449 -0
  120. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_style.py +886 -0
  121. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_xml.py +1495 -0
  122. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chartex.py +272 -0
  123. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/fallback_hash.py +161 -0
  124. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula.py +243 -0
  125. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_ast.py +592 -0
  126. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_compiler.py +96 -0
  127. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_omml.py +1049 -0
  128. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_parser.py +2181 -0
  129. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_profile.py +739 -0
  130. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_run_properties.py +234 -0
  131. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/inline_formula.py +311 -0
  132. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_attributes.py +182 -0
  133. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_common.py +806 -0
  134. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_status.py +190 -0
  135. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/table.py +1113 -0
  136. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/workbook.py +216 -0
  137. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/__init__.py +1 -0
  138. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/builder.py +6273 -0
  139. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/cli.py +2059 -0
  140. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/dimensions.py +189 -0
  141. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/discovery.py +120 -0
  142. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/media.py +160 -0
  143. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/narration.py +696 -0
  144. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/notes.py +336 -0
  145. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/slide_xml.py +138 -0
  146. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_structure.py +3457 -0
  147. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_validation.py +1536 -0
  148. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/semantic_markers.py +240 -0
  149. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/shape_boolean.py +1355 -0
  150. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/text_outline.py +1121 -0
  151. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/tspan_flattener.py +64 -0
  152. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/use_expander.py +577 -0
  153. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx.py +21 -0
  154. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +336 -0
  155. package/skills/dknowc-ppt-assistant/scripts/update_spec.py +404 -0
  156. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +142 -0
  157. package/skills/dknowc-ppt-assistant/workflows/routing.md +38 -0
  158. package/src/index.js +7 -2
@@ -0,0 +1,1841 @@
1
+ """Convert a DrawingML <a:tbl> into SVG.
2
+
3
+ Tables in PowerPoint are stored under <p:graphicFrame> with
4
+ graphicData uri="...drawingml/2006/table" wrapping a single <a:tbl>:
5
+
6
+ <p:graphicFrame>
7
+ <p:xfrm>...</p:xfrm>
8
+ <a:graphic><a:graphicData uri="...table">
9
+ <a:tbl>
10
+ <a:tblPr/>
11
+ <a:tblGrid>
12
+ <a:gridCol w="..."/>...
13
+ </a:tblGrid>
14
+ <a:tr h="...">
15
+ <a:tc [gridSpan=N] [rowSpan=N] [hMerge=1] [vMerge=1]>
16
+ <a:txBody>...</a:txBody>
17
+ <a:tcPr>
18
+ <a:lnL/><a:lnR/><a:lnT/><a:lnB/>
19
+ <a:solidFill/>... or <a:gradFill/> ...
20
+ </a:tcPr>
21
+ </a:tc>
22
+ </a:tr>
23
+ </a:tbl>
24
+ </a:graphicData></a:graphic>
25
+ </p:graphicFrame>
26
+
27
+ The graphicFrame's <p:xfrm> gives the table's slide-space position and total
28
+ size; <a:tblGrid> + <a:tr> heights distribute that size across columns/rows.
29
+
30
+ Cell painting order:
31
+ 1. background fill (rect at cell box)
32
+ 2. text body (re-uses convert_txbody)
33
+ 3. cell borders (lnT / lnR / lnB / lnL — stroked as separate <line>s so
34
+ neighbouring cells with different border styles render correctly)
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import copy
40
+ import math
41
+ from dataclasses import dataclass
42
+ from typing import Any
43
+ from xml.etree import ElementTree as ET
44
+
45
+ from pptx_effects import txbody_has_run_effects
46
+
47
+ from .color_resolver import ColorPalette, find_color_elem, resolve_color
48
+ from .emu_units import (
49
+ NS,
50
+ Xfrm,
51
+ emu_to_px,
52
+ fmt_num,
53
+ hundredths_pt_to_px,
54
+ ooxml_bool,
55
+ )
56
+ from .fill_to_svg import FillResult, resolve_fill
57
+ from .ln_to_svg import resolve_stroke
58
+ from .txbody_to_svg import _resolve_theme_typeface, convert_txbody
59
+ from .txbody_to_svg import HyperlinkResolver
60
+
61
+
62
+ BUILTIN_MEDIUM_STYLE_2_ACCENT_1 = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"
63
+ _POWERPOINT_COORD_MIN = -(2**31)
64
+ _POWERPOINT_COORD_MAX = 2**31 - 1
65
+
66
+ _BUILTIN_MEDIUM_STYLE_2_ACCENT_1_XML = ET.fromstring(
67
+ f'''<a:tblStyle xmlns:a="{NS["a"]}"
68
+ styleId="{BUILTIN_MEDIUM_STYLE_2_ACCENT_1}">
69
+ <a:wholeTbl>
70
+ <a:tcTxStyle>
71
+ <a:fontRef idx="minor"><a:prstClr val="black"/></a:fontRef>
72
+ <a:schemeClr val="dk1"/>
73
+ </a:tcTxStyle>
74
+ <a:tcStyle>
75
+ <a:tcBdr>
76
+ <a:left><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:left>
77
+ <a:right><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:right>
78
+ <a:top><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:top>
79
+ <a:bottom><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:bottom>
80
+ <a:insideH><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:insideH>
81
+ <a:insideV><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:insideV>
82
+ </a:tcBdr>
83
+ <a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="20000"/></a:schemeClr></a:solidFill></a:fill>
84
+ </a:tcStyle>
85
+ </a:wholeTbl>
86
+ <a:band1H>
87
+ <a:tcStyle><a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="40000"/></a:schemeClr></a:solidFill></a:fill></a:tcStyle>
88
+ </a:band1H>
89
+ <a:band2H><a:tcStyle/></a:band2H>
90
+ <a:firstRow>
91
+ <a:tcTxStyle b="on">
92
+ <a:fontRef idx="minor"><a:prstClr val="black"/></a:fontRef>
93
+ <a:schemeClr val="lt1"/>
94
+ </a:tcTxStyle>
95
+ <a:tcStyle>
96
+ <a:tcBdr><a:bottom><a:ln w="38100"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:bottom></a:tcBdr>
97
+ <a:fill><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:fill>
98
+ </a:tcStyle>
99
+ </a:firstRow>
100
+ </a:tblStyle>'''
101
+ )
102
+
103
+
104
+ @dataclass
105
+ class TableResult:
106
+ """Composite render output, replacement metadata, and effect diagnostics."""
107
+
108
+ svg: str = ""
109
+ defs: list[str] = None
110
+ native_payload: dict[str, Any] | None = None
111
+ native_status: str | None = None
112
+ effect_reason: str | None = None
113
+
114
+ def __post_init__(self) -> None:
115
+ if self.defs is None:
116
+ self.defs = []
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class _TableStyleContext:
121
+ """Small, best-effort view of the table style regions we render."""
122
+
123
+ style: ET.Element | None
124
+ table_properties: ET.Element | None
125
+
126
+ def regions_for_row(self, row_index: int) -> tuple[tuple[str, ET.Element], ...]:
127
+ if self.style is None:
128
+ return ()
129
+
130
+ names: list[str] = []
131
+ first_row = bool(
132
+ self.table_properties is not None
133
+ and ooxml_bool(self.table_properties.get("firstRow"))
134
+ )
135
+ if first_row and row_index == 0:
136
+ names.append("firstRow")
137
+ elif (
138
+ self.table_properties is not None
139
+ and ooxml_bool(self.table_properties.get("bandRow"))
140
+ ):
141
+ band_index = row_index - (1 if first_row else 0)
142
+ names.append("band1H" if band_index % 2 == 0 else "band2H")
143
+ names.append("wholeTbl")
144
+
145
+ regions: list[tuple[str, ET.Element]] = []
146
+ for name in names:
147
+ region = self.style.find(f"a:{name}", NS)
148
+ if region is not None:
149
+ regions.append((name, region))
150
+ return tuple(regions)
151
+
152
+
153
+ def _normalize_table_style_id(value: str | None) -> str:
154
+ return (value or "").strip().strip("{}").upper()
155
+
156
+
157
+ def _resolve_table_style(
158
+ tbl: ET.Element,
159
+ table_styles: ET.Element | None,
160
+ ) -> _TableStyleContext:
161
+ tbl_pr = tbl.find("a:tblPr", NS)
162
+ style_id = (
163
+ tbl_pr.findtext("a:tableStyleId", default="", namespaces=NS).strip()
164
+ if tbl_pr is not None else ""
165
+ )
166
+ if not style_id and table_styles is not None:
167
+ style_id = table_styles.get("def", "").strip()
168
+ normalized_id = _normalize_table_style_id(style_id)
169
+ supported_id = _normalize_table_style_id(BUILTIN_MEDIUM_STYLE_2_ACCENT_1)
170
+
171
+ # P1 deliberately supports one built-in family. Consuming an arbitrary
172
+ # custom definition here would be asymmetric: native reconstruction keeps
173
+ # only the style id and does not copy custom tableStyles.xml definitions.
174
+ if normalized_id != supported_id:
175
+ return _TableStyleContext(None, tbl_pr)
176
+
177
+ if table_styles is not None and normalized_id:
178
+ for candidate in table_styles.findall("a:tblStyle", NS):
179
+ if _normalize_table_style_id(candidate.get("styleId")) == normalized_id:
180
+ return _TableStyleContext(candidate, tbl_pr)
181
+
182
+ return _TableStyleContext(_BUILTIN_MEDIUM_STYLE_2_ACCENT_1_XML, tbl_pr)
183
+
184
+
185
+ def _effective_cell_fill(
186
+ tc_pr: ET.Element | None,
187
+ table_style: _TableStyleContext,
188
+ row_index: int,
189
+ palette: ColorPalette | None,
190
+ *,
191
+ id_prefix: str,
192
+ id_seq: list[int],
193
+ ) -> FillResult:
194
+ """Resolve direct cell fill before row-region and whole-table defaults."""
195
+ direct = resolve_fill(
196
+ tc_pr, palette, id_prefix=id_prefix, id_seq=id_seq,
197
+ )
198
+ if direct.attrs or direct.defs:
199
+ return direct
200
+
201
+ for _name, region in table_style.regions_for_row(row_index):
202
+ fill_parent = region.find("a:tcStyle/a:fill", NS)
203
+ if fill_parent is None:
204
+ continue
205
+ inherited = resolve_fill(
206
+ fill_parent, palette, id_prefix=id_prefix, id_seq=id_seq,
207
+ )
208
+ if inherited.attrs or inherited.defs:
209
+ return inherited
210
+ return direct
211
+
212
+
213
+ def _table_text_run_props(
214
+ table_style: _TableStyleContext,
215
+ row_index: int,
216
+ theme_fonts: dict[str, str],
217
+ ) -> tuple[ET.Element, ...]:
218
+ """Materialize table text-style regions as lowest-priority run defaults."""
219
+ props: list[ET.Element] = []
220
+ for _name, region in table_style.regions_for_row(row_index):
221
+ tx_style = region.find("a:tcTxStyle", NS)
222
+ if tx_style is None:
223
+ continue
224
+ run_props = _table_tx_style_run_props(tx_style, theme_fonts)
225
+ if run_props is not None:
226
+ props.append(run_props)
227
+ return tuple(props)
228
+
229
+
230
+ def _table_tx_style_run_props(
231
+ tx_style: ET.Element,
232
+ theme_fonts: dict[str, str],
233
+ ) -> ET.Element | None:
234
+ run_props = ET.Element(f"{{{NS['a']}}}rPr")
235
+ for attr in ("b", "i"):
236
+ value = tx_style.get(attr)
237
+ if value is not None:
238
+ run_props.set(attr, "1" if ooxml_bool(value) else "0")
239
+
240
+ font_ref = tx_style.find("a:fontRef", NS)
241
+ font_role = font_ref.get("idx") if font_ref is not None else None
242
+ if font_role in {"major", "minor"}:
243
+ prefix = "major" if font_role == "major" else "minor"
244
+ latin = theme_fonts.get(f"{prefix}Latin")
245
+ east_asia = theme_fonts.get(f"{prefix}EastAsia") or latin
246
+ complex_script = theme_fonts.get(f"{prefix}ComplexScript") or latin
247
+ for tag, typeface in (
248
+ ("latin", latin),
249
+ ("ea", east_asia),
250
+ ("cs", complex_script),
251
+ ):
252
+ if typeface:
253
+ ET.SubElement(
254
+ run_props, f"{{{NS['a']}}}{tag}",
255
+ {"typeface": typeface},
256
+ )
257
+
258
+ color = find_color_elem(tx_style)
259
+ if color is not None:
260
+ solid_fill = ET.SubElement(run_props, f"{{{NS['a']}}}solidFill")
261
+ solid_fill.append(copy.deepcopy(color))
262
+
263
+ if not run_props.attrib and not list(run_props):
264
+ return None
265
+ return run_props
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Public entry
270
+ # ---------------------------------------------------------------------------
271
+
272
+ def convert_tbl(
273
+ tbl: ET.Element,
274
+ xfrm: Xfrm,
275
+ palette: ColorPalette | None,
276
+ *,
277
+ table_styles: ET.Element | None = None,
278
+ theme_fonts: dict[str, str] | None = None,
279
+ slide_number: int | None = None,
280
+ id_prefix: str = "tbl",
281
+ grad_seq: list[int] | None = None,
282
+ marker_seq: list[int] | None = None,
283
+ hyperlink_resolver: HyperlinkResolver | None = None,
284
+ ) -> TableResult:
285
+ """Render an <a:tbl> at the given absolute xfrm into SVG markup."""
286
+ grad_seq = grad_seq if grad_seq is not None else [0]
287
+ marker_seq = marker_seq if marker_seq is not None else [0]
288
+
289
+ col_widths_px = _column_widths_px(tbl)
290
+ if not col_widths_px:
291
+ return TableResult()
292
+ rows = tbl.findall("a:tr", NS)
293
+ if not rows:
294
+ return TableResult()
295
+ table_style = _resolve_table_style(tbl, table_styles)
296
+ row_heights_px = [_row_height_px(r) for r in rows]
297
+ grid_topology_invalid = any(
298
+ len(row.findall("a:tc", NS)) != len(col_widths_px)
299
+ for row in rows
300
+ )
301
+ source_geometry_invalid = (
302
+ grid_topology_invalid
303
+ or any(width <= 0 for width in col_widths_px)
304
+ or any(height <= 0 for height in row_heights_px)
305
+ or sum(col_widths_px) <= 0
306
+ or sum(row_heights_px) <= 0
307
+ )
308
+
309
+ # PowerPoint's tblGrid widths and tr heights together describe the
310
+ # *intrinsic* table size. The graphicFrame xfrm width/height may differ;
311
+ # if it does, scale rows/columns proportionally so the table fills the
312
+ # frame the way PowerPoint renders it.
313
+ intrinsic_w = sum(col_widths_px) or xfrm.w
314
+ intrinsic_h = sum(row_heights_px) or xfrm.h
315
+ sx = (xfrm.w / intrinsic_w) if intrinsic_w else 1.0
316
+ sy = (xfrm.h / intrinsic_h) if intrinsic_h else 1.0
317
+ col_widths = [w * sx for w in col_widths_px]
318
+ row_heights = [h * sy for h in row_heights_px]
319
+
320
+ col_lefts = _cumulative_starts(xfrm.x, col_widths)
321
+ row_tops = _cumulative_starts(xfrm.y, row_heights)
322
+
323
+ # First pass: resolve merge state so spanned cells get the union geometry
324
+ # and dropped cells don't render anything. PowerPoint expresses merges via
325
+ # gridSpan/rowSpan on the anchor cell + hMerge/vMerge on the dropped cells.
326
+ cells = _build_cell_grid(rows, len(col_widths))
327
+ merge_status = _canonical_native_merge_status(rows, len(col_widths))
328
+ effect_reason = (
329
+ "unsupported-run-effect-route:table-cell-text"
330
+ if any(
331
+ txbody_has_run_effects(tc.find("a:txBody", NS))
332
+ for tc in tbl.findall(".//a:tc", NS)
333
+ )
334
+ else None
335
+ )
336
+ if xfrm.rot or xfrm.flip_h or xfrm.flip_v:
337
+ native_status = "unsupported-native-transform"
338
+ elif merge_status:
339
+ native_status = merge_status
340
+ elif len(rows) > 1000 or len(col_widths) > 1000:
341
+ native_status = "unsupported-table-size"
342
+ elif source_geometry_invalid or (
343
+ any(width <= 0 for width in col_widths)
344
+ or any(height <= 0 for height in row_heights)
345
+ or sum(col_widths) <= 0
346
+ or sum(row_heights) <= 0
347
+ ):
348
+ native_status = "unsupported-table-geometry"
349
+ elif _table_has_unsupported_style(tbl):
350
+ native_status = "unsupported-table-style"
351
+ elif (
352
+ effect_reason
353
+ or _table_has_unsupported_direct_formatting(tbl, palette)
354
+ ):
355
+ native_status = "unsupported-table-direct-formatting"
356
+ else:
357
+ native_status = None
358
+ native_payload = (
359
+ None if native_status else _native_table_payload(
360
+ tbl,
361
+ xfrm,
362
+ col_widths,
363
+ row_heights,
364
+ cells,
365
+ palette,
366
+ theme_fonts or {},
367
+ )
368
+ )
369
+
370
+ body_parts: list[str] = []
371
+ defs: list[str] = []
372
+
373
+ # Pass A: cell backgrounds.
374
+ for r, row_cells in enumerate(cells):
375
+ for c, cell in enumerate(row_cells):
376
+ if cell is None or cell.is_dropped:
377
+ continue
378
+ rect_x = col_lefts[c]
379
+ rect_y = row_tops[r]
380
+ rect_w = sum(col_widths[c:c + cell.col_span])
381
+ rect_h = sum(row_heights[r:r + cell.row_span])
382
+ tcPr = cell.element.find("a:tcPr", NS)
383
+ fill = _effective_cell_fill(
384
+ tcPr, table_style, r, palette,
385
+ id_prefix=f"{id_prefix}fill",
386
+ id_seq=grad_seq,
387
+ )
388
+ defs.extend(fill.defs)
389
+ attrs = fill.attrs or {"fill": "none"}
390
+ attr_str = "".join(f' {k}="{v}"' for k, v in attrs.items())
391
+ body_parts.append(
392
+ f'<rect x="{fmt_num(rect_x)}" y="{fmt_num(rect_y)}" '
393
+ f'width="{fmt_num(rect_w)}" height="{fmt_num(rect_h)}"'
394
+ f'{attr_str}/>'
395
+ )
396
+
397
+ # Pass B: cell text. Cell xfrm uses default tcPr insets if none specified.
398
+ for r, row_cells in enumerate(cells):
399
+ for c, cell in enumerate(row_cells):
400
+ if cell is None or cell.is_dropped:
401
+ continue
402
+ tx_body = cell.element.find("a:txBody", NS)
403
+ if tx_body is None:
404
+ continue
405
+ tcPr = cell.element.find("a:tcPr", NS)
406
+ cell_x = col_lefts[c]
407
+ cell_y = row_tops[r]
408
+ cell_w = sum(col_widths[c:c + cell.col_span])
409
+ cell_h = sum(row_heights[r:r + cell.row_span])
410
+ cell_xfrm = Xfrm(x=cell_x, y=cell_y, w=cell_w, h=cell_h)
411
+ text_result = _convert_cell_text(
412
+ tx_body, tcPr, cell_xfrm, palette, theme_fonts,
413
+ fallback_run_props=_table_text_run_props(
414
+ table_style, r, theme_fonts or {},
415
+ ),
416
+ slide_number=slide_number,
417
+ id_prefix=f"{id_prefix}txt",
418
+ id_seq=grad_seq,
419
+ hyperlink_resolver=hyperlink_resolver,
420
+ )
421
+ defs.extend(text_result.defs)
422
+ if text_result.svg:
423
+ body_parts.append(text_result.svg)
424
+
425
+ # Pass C: cell borders. Drawn last so they appear on top of fills/text.
426
+ for r, row_cells in enumerate(cells):
427
+ for c, cell in enumerate(row_cells):
428
+ if cell is None or cell.is_dropped:
429
+ continue
430
+ cell_x = col_lefts[c]
431
+ cell_y = row_tops[r]
432
+ cell_w = sum(col_widths[c:c + cell.col_span])
433
+ cell_h = sum(row_heights[r:r + cell.row_span])
434
+ tcPr = cell.element.find("a:tcPr", NS)
435
+ for tag, x1, y1, x2, y2 in (
436
+ ("a:lnT", cell_x, cell_y, cell_x + cell_w, cell_y),
437
+ ("a:lnR", cell_x + cell_w, cell_y, cell_x + cell_w, cell_y + cell_h),
438
+ ("a:lnB", cell_x, cell_y + cell_h, cell_x + cell_w, cell_y + cell_h),
439
+ ("a:lnL", cell_x, cell_y, cell_x, cell_y + cell_h),
440
+ ):
441
+ line_xml = _border_line(
442
+ tcPr, table_style, r, c, len(rows), len(col_widths), tag,
443
+ x1, y1, x2, y2, palette,
444
+ id_prefix=f"{id_prefix}stk", id_seq=marker_seq, defs=defs,
445
+ )
446
+ if line_xml:
447
+ body_parts.append(line_xml)
448
+
449
+ return TableResult(
450
+ svg="\n".join(body_parts),
451
+ defs=defs,
452
+ native_payload=native_payload,
453
+ native_status=native_status,
454
+ effect_reason=effect_reason,
455
+ )
456
+
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # Geometry helpers
460
+ # ---------------------------------------------------------------------------
461
+
462
+ def _column_widths_px(tbl: ET.Element) -> list[float]:
463
+ grid = tbl.find("a:tblGrid", NS)
464
+ if grid is None:
465
+ return []
466
+ widths: list[float] = []
467
+ for col in grid.findall("a:gridCol", NS):
468
+ w_emu = col.attrib.get("w")
469
+ if w_emu is None:
470
+ widths.append(0.0)
471
+ continue
472
+ value = _safe_emu_integer(w_emu)
473
+ widths.append(emu_to_px(value) if value is not None else 0.0)
474
+ return widths
475
+
476
+
477
+ def _row_height_px(row: ET.Element) -> float:
478
+ h_emu = row.attrib.get("h")
479
+ if h_emu is None:
480
+ return 0.0
481
+ value = _safe_emu_integer(h_emu)
482
+ return emu_to_px(value) if value is not None else 0.0
483
+
484
+
485
+ def _safe_emu_integer(raw_value: str) -> int | None:
486
+ """Return a bounded ASCII DrawingML coordinate without float overflow."""
487
+ token = raw_value.strip(" \t\r\n")
488
+ digits = token[1:] if token.startswith("-") else token
489
+ if (
490
+ not digits
491
+ or not digits.isascii()
492
+ or not digits.isdigit()
493
+ or len(digits) > 10
494
+ ):
495
+ return None
496
+ value = int(token)
497
+ if not _POWERPOINT_COORD_MIN <= value <= _POWERPOINT_COORD_MAX:
498
+ return None
499
+ return value
500
+
501
+
502
+ def _cumulative_starts(origin: float, sizes: list[float]) -> list[float]:
503
+ out = [origin]
504
+ acc = origin
505
+ for size in sizes[:-1]:
506
+ acc += size
507
+ out.append(acc)
508
+ return out
509
+
510
+
511
+ # ---------------------------------------------------------------------------
512
+ # Cell grid
513
+ # ---------------------------------------------------------------------------
514
+
515
+ @dataclass
516
+ class _CellSlot:
517
+ """Per-grid-position resolution of <a:tc> attributes."""
518
+
519
+ element: ET.Element
520
+ col_span: int = 1
521
+ row_span: int = 1
522
+ is_dropped: bool = False # True for h/vMerge slaves: don't paint anything
523
+
524
+
525
+ @dataclass(frozen=True)
526
+ class _CanonicalMergeRegion:
527
+ row: int
528
+ col: int
529
+ row_span: int
530
+ col_span: int
531
+
532
+
533
+ def _build_cell_grid(rows: list[ET.Element], col_count: int) -> list[list[_CellSlot | None]]:
534
+ """Map each (row, col) to the <a:tc> that owns it.
535
+
536
+ Anchor cells (the top-left of a merge) carry col_span/row_span; merged
537
+ slaves are marked is_dropped so the renderer skips them. Cells not part
538
+ of any merge get span 1×1.
539
+ """
540
+ grid: list[list[_CellSlot | None]] = [[None] * col_count for _ in rows]
541
+
542
+ for r, row in enumerate(rows):
543
+ row_cells = row.findall("a:tc", NS)
544
+ # PowerPoint writes one physical <a:tc> for every grid column, including
545
+ # explicit hMerge/vMerge continuation cells. In that canonical form the
546
+ # physical index is the grid column; advancing by gridSpan would consume
547
+ # the continuation cell twice and shift every following cell left.
548
+ explicit_grid = len(row_cells) >= col_count
549
+ c = 0
550
+ for physical_col, tc in enumerate(row_cells):
551
+ if explicit_grid:
552
+ c = physical_col
553
+ else:
554
+ # Retain best-effort support for compact/non-canonical rows that
555
+ # omit explicit merge continuation cells.
556
+ while c < col_count and grid[r][c] is not None:
557
+ c += 1
558
+ if c >= col_count:
559
+ break
560
+
561
+ grid_span = _safe_int(tc.attrib.get("gridSpan"), 1)
562
+ row_span = _safe_int(tc.attrib.get("rowSpan"), 1)
563
+ h_merge = ooxml_bool(tc.attrib.get("hMerge"))
564
+ v_merge = ooxml_bool(tc.attrib.get("vMerge"))
565
+
566
+ if h_merge or v_merge:
567
+ # Merge slaves are physical cells but have no independent paint.
568
+ grid[r][c] = _CellSlot(element=tc, is_dropped=True)
569
+ c += 1
570
+ continue
571
+
572
+ slot = _CellSlot(
573
+ element=tc,
574
+ col_span=max(grid_span, 1),
575
+ row_span=max(row_span, 1),
576
+ )
577
+ for dr in range(slot.row_span):
578
+ for dc in range(slot.col_span):
579
+ rr = r + dr
580
+ cc = c + dc
581
+ if rr >= len(rows) or cc >= col_count:
582
+ continue
583
+ if dr == 0 and dc == 0:
584
+ grid[rr][cc] = slot
585
+ else:
586
+ grid[rr][cc] = _CellSlot(
587
+ element=tc, is_dropped=True,
588
+ )
589
+ c += 1 if explicit_grid else slot.col_span
590
+
591
+ return grid
592
+
593
+
594
+ def _safe_int(value: str | None, default: int) -> int:
595
+ if value is None:
596
+ return default
597
+ try:
598
+ return int(value)
599
+ except ValueError:
600
+ return default
601
+
602
+
603
+ def _strict_merge_bool(value: str | None) -> bool:
604
+ if value is None:
605
+ return False
606
+ normalized = value.strip().lower()
607
+ if normalized in {"1", "on", "true"}:
608
+ return True
609
+ if normalized in {"0", "false", "off"}:
610
+ return False
611
+ raise ValueError("invalid OOXML boolean")
612
+
613
+
614
+ def _strict_merge_span(value: str | None) -> int:
615
+ if value is None:
616
+ return 1
617
+ normalized = value.strip()
618
+ if not normalized.isdigit():
619
+ raise ValueError("invalid OOXML span")
620
+ span = int(normalized)
621
+ if span <= 0:
622
+ raise ValueError("invalid OOXML span")
623
+ return span
624
+
625
+
626
+ def _canonical_merge_slave_is_empty(tc: ET.Element) -> bool:
627
+ tc_pr = tc.find("a:tcPr", NS)
628
+ if tc_pr is None or tc_pr.attrib or list(tc_pr):
629
+ return False
630
+ tx_body = tc.find("a:txBody", NS)
631
+ if tx_body is None:
632
+ return False
633
+ paragraph_count = 0
634
+ for child in tx_body:
635
+ name = child.tag.rsplit("}", 1)[-1]
636
+ if name in {"bodyPr", "lstStyle"}:
637
+ if child.attrib or list(child):
638
+ return False
639
+ continue
640
+ if name == "p" and not child.attrib and not list(child):
641
+ paragraph_count += 1
642
+ continue
643
+ return False
644
+ return paragraph_count > 0 and not (tx_body.text or "").strip()
645
+
646
+
647
+ def _canonical_native_merge_status(
648
+ rows: list[ET.Element],
649
+ col_count: int,
650
+ ) -> str | None:
651
+ """Accept only explicit rectangular merge topology safe for regeneration."""
652
+ physical_rows = [row.findall("a:tc", NS) for row in rows]
653
+ merge_attrs = {"gridSpan", "rowSpan", "hMerge", "vMerge"}
654
+ if not any(
655
+ any(name in tc.attrib for name in merge_attrs)
656
+ for row_cells in physical_rows
657
+ for tc in row_cells
658
+ ):
659
+ return None
660
+ if col_count <= 0 or any(
661
+ len(row_cells) != col_count for row_cells in physical_rows
662
+ ):
663
+ return "unsupported-merge-topology"
664
+
665
+ states: dict[tuple[int, int], tuple[ET.Element, int, int, bool, bool]] = {}
666
+ try:
667
+ for row_idx, row_cells in enumerate(physical_rows):
668
+ for col_idx, tc in enumerate(row_cells):
669
+ states[(row_idx, col_idx)] = (
670
+ tc,
671
+ _strict_merge_span(tc.get("rowSpan")),
672
+ _strict_merge_span(tc.get("gridSpan")),
673
+ _strict_merge_bool(tc.get("hMerge")),
674
+ _strict_merge_bool(tc.get("vMerge")),
675
+ )
676
+ except ValueError:
677
+ return "unsupported-merge-topology"
678
+
679
+ anchors: list[_CanonicalMergeRegion] = []
680
+ for (
681
+ (row_idx, col_idx),
682
+ (_tc, row_span, col_span, h_merge, v_merge),
683
+ ) in states.items():
684
+ if not h_merge and not v_merge and (row_span > 1 or col_span > 1):
685
+ anchors.append(
686
+ _CanonicalMergeRegion(row_idx, col_idx, row_span, col_span)
687
+ )
688
+
689
+ owners: dict[tuple[int, int], _CanonicalMergeRegion] = {}
690
+ for region in anchors:
691
+ if (
692
+ region.row + region.row_span > len(rows)
693
+ or region.col + region.col_span > col_count
694
+ ):
695
+ return "unsupported-merge-topology"
696
+ for covered_row in range(region.row, region.row + region.row_span):
697
+ for covered_col in range(region.col, region.col + region.col_span):
698
+ position = (covered_row, covered_col)
699
+ if position in owners:
700
+ return "unsupported-merge-topology"
701
+ owners[position] = region
702
+
703
+ for (
704
+ (row_idx, col_idx),
705
+ (tc, row_span, col_span, h_merge, v_merge),
706
+ ) in states.items():
707
+ region = owners.get((row_idx, col_idx))
708
+ if region is None:
709
+ if h_merge or v_merge or row_span != 1 or col_span != 1:
710
+ return "unsupported-merge-topology"
711
+ continue
712
+
713
+ is_anchor = row_idx == region.row and col_idx == region.col
714
+ expected_row_span = region.row_span if row_idx == region.row else 1
715
+ expected_col_span = region.col_span if col_idx == region.col else 1
716
+ if (
717
+ row_span != expected_row_span
718
+ or col_span != expected_col_span
719
+ or h_merge != (col_idx > region.col)
720
+ or v_merge != (row_idx > region.row)
721
+ ):
722
+ return "unsupported-merge-topology"
723
+ if not is_anchor and not _canonical_merge_slave_is_empty(tc):
724
+ return "unsupported-merge-topology"
725
+
726
+ return None
727
+
728
+
729
+ def _table_has_unsupported_style(tbl: ET.Element) -> bool:
730
+ tbl_pr = tbl.find("a:tblPr", NS)
731
+ if tbl_pr is None:
732
+ return False
733
+ allowed_attrs = {
734
+ "firstRow", "bandRow", "firstCol", "lastCol", "lastRow",
735
+ "bandCol", "rtl",
736
+ }
737
+ if any(name not in allowed_attrs for name in tbl_pr.attrib):
738
+ return True
739
+ if any(
740
+ ooxml_bool(tbl_pr.attrib.get(name))
741
+ for name in ("firstCol", "lastCol", "lastRow", "bandCol", "rtl")
742
+ ):
743
+ return True
744
+ return any(
745
+ child.tag.rsplit("}", 1)[-1] != "tableStyleId"
746
+ for child in tbl_pr
747
+ )
748
+
749
+
750
+ _DIRECT_BORDER_TAGS = {
751
+ "lnL": "left",
752
+ "lnR": "right",
753
+ "lnT": "top",
754
+ "lnB": "bottom",
755
+ }
756
+ _DIRECT_BORDER_WIDTH_MAX = 20116800
757
+ _OPAQUE_COLOR_MODIFIERS = {
758
+ "tint",
759
+ "shade",
760
+ "lumMod",
761
+ "lumOff",
762
+ "satMod",
763
+ "satOff",
764
+ }
765
+
766
+
767
+ def _validate_opaque_border_color(color_elem: ET.Element | None) -> None:
768
+ if color_elem is None:
769
+ raise ValueError("missing border color")
770
+ name = color_elem.tag.rsplit("}", 1)[-1]
771
+ if name not in {"srgbClr", "schemeClr"} or set(color_elem.attrib) != {"val"}:
772
+ raise ValueError("unsupported border color")
773
+ for modifier in color_elem:
774
+ modifier_name = modifier.tag.rsplit("}", 1)[-1]
775
+ if (
776
+ modifier_name not in _OPAQUE_COLOR_MODIFIERS
777
+ or set(modifier.attrib) != {"val"}
778
+ or list(modifier)
779
+ ):
780
+ raise ValueError("unsupported border color modifier")
781
+ value = modifier.get("val", "")
782
+ if not value.isdigit() or not 0 <= int(value) <= 100000:
783
+ raise ValueError("invalid border color modifier")
784
+
785
+
786
+ def _direct_border_payload(
787
+ ln: ET.Element,
788
+ palette: ColorPalette | None,
789
+ ) -> dict[str, Any]:
790
+ if set(ln.attrib) - {"w", "cap", "cmpd", "algn"}:
791
+ raise ValueError("unsupported border line attribute")
792
+ if ln.get("cap") not in {None, "flat"}:
793
+ raise ValueError("unsupported border cap")
794
+ if ln.get("cmpd") not in {None, "sng"}:
795
+ raise ValueError("unsupported border compound style")
796
+ if ln.get("algn") not in {None, "ctr"}:
797
+ raise ValueError("unsupported border alignment")
798
+ width_emu: int | None = None
799
+ if "w" in ln.attrib:
800
+ raw_width = ln.get("w", "")
801
+ if not raw_width.isdigit():
802
+ raise ValueError("invalid border width")
803
+ width_emu = int(raw_width)
804
+ if not 0 < width_emu <= _DIRECT_BORDER_WIDTH_MAX:
805
+ raise ValueError("invalid border width")
806
+
807
+ children = list(ln)
808
+ child_names = [child.tag.rsplit("}", 1)[-1] for child in children]
809
+ if child_names == ["noFill"]:
810
+ no_fill = children[0]
811
+ if no_fill.attrib or list(no_fill):
812
+ raise ValueError("invalid noFill border")
813
+ return {"style": "none"}
814
+
815
+ decoration_names = {"round", "headEnd", "tailEnd"}
816
+ if child_names.count("solidFill") != 1 or any(
817
+ name not in {"solidFill", "prstDash", *decoration_names}
818
+ for name in child_names
819
+ ):
820
+ raise ValueError("unsupported border paint")
821
+ if (
822
+ child_names.count("prstDash") > 1
823
+ or any(child_names.count(name) > 1 for name in decoration_names)
824
+ or width_emu is None
825
+ ):
826
+ raise ValueError("invalid solid border")
827
+ dash = next(
828
+ (child for child in children if child.tag.rsplit("}", 1)[-1] == "prstDash"),
829
+ None,
830
+ )
831
+ if dash is not None and (
832
+ dash.attrib != {"val": "solid"} or list(dash)
833
+ ):
834
+ raise ValueError("unsupported border dash")
835
+ line_join = next(
836
+ (child for child in children if child.tag.rsplit("}", 1)[-1] == "round"),
837
+ None,
838
+ )
839
+ if line_join is not None and (line_join.attrib or list(line_join)):
840
+ raise ValueError("unsupported border line join")
841
+ for endpoint_name in ("headEnd", "tailEnd"):
842
+ endpoint = next(
843
+ (
844
+ child for child in children
845
+ if child.tag.rsplit("}", 1)[-1] == endpoint_name
846
+ ),
847
+ None,
848
+ )
849
+ if endpoint is None:
850
+ continue
851
+ if (
852
+ set(endpoint.attrib) - {"type", "w", "len"}
853
+ or endpoint.get("type") not in {None, "none"}
854
+ or endpoint.get("w") not in {None, "med"}
855
+ or endpoint.get("len") not in {None, "med"}
856
+ or list(endpoint)
857
+ ):
858
+ raise ValueError("unsupported border endpoint")
859
+
860
+ solid_fill = next(
861
+ child for child in children
862
+ if child.tag.rsplit("}", 1)[-1] == "solidFill"
863
+ )
864
+ if solid_fill.attrib or len(list(solid_fill)) != 1:
865
+ raise ValueError("invalid solid border fill")
866
+ color_elem = find_color_elem(solid_fill)
867
+ _validate_opaque_border_color(color_elem)
868
+ try:
869
+ color, alpha = resolve_color(color_elem, palette)
870
+ except (TypeError, ValueError, OverflowError) as exc:
871
+ raise ValueError("invalid solid border color") from exc
872
+ if color is None or alpha != 1.0:
873
+ raise ValueError("border color must resolve to opaque RGB")
874
+
875
+ width = _round_payload_number(emu_to_px(str(width_emu)))
876
+ if width <= 0:
877
+ raise ValueError("border width is too small")
878
+ return {
879
+ "style": "solid",
880
+ "color": color,
881
+ "width": width,
882
+ }
883
+
884
+
885
+ def _table_has_unsupported_direct_formatting(
886
+ tbl: ET.Element,
887
+ palette: ColorPalette | None,
888
+ ) -> bool:
889
+ """Reject direct cell features the compact native schema cannot retain."""
890
+ for tc in tbl.findall(".//a:tc", NS):
891
+ if _table_cell_has_unsupported_topology(tc):
892
+ return True
893
+ tc_pr = tc.find("a:tcPr", NS)
894
+ if tc_pr is not None:
895
+ allowed_attrs = {"marL", "marR", "marT", "marB", "anchor"}
896
+ if any(name not in allowed_attrs for name in tc_pr.attrib):
897
+ return True
898
+ if tc_pr.get("anchor") not in {None, "t", "ctr", "b"}:
899
+ return True
900
+ if any(
901
+ child.tag.rsplit("}", 1)[-1]
902
+ not in {"solidFill", "noFill", *_DIRECT_BORDER_TAGS}
903
+ for child in tc_pr
904
+ ):
905
+ return True
906
+ fills = [
907
+ child for child in tc_pr
908
+ if child.tag.rsplit("}", 1)[-1] in {"solidFill", "noFill"}
909
+ ]
910
+ if len(fills) > 1:
911
+ return True
912
+ no_fill = tc_pr.find("a:noFill", NS)
913
+ if no_fill is not None and (no_fill.attrib or list(no_fill)):
914
+ return True
915
+ for border_tag in _DIRECT_BORDER_TAGS:
916
+ borders = tc_pr.findall(f"a:{border_tag}", NS)
917
+ if len(borders) > 1:
918
+ return True
919
+ if borders:
920
+ try:
921
+ _direct_border_payload(borders[0], palette)
922
+ except ValueError:
923
+ return True
924
+ solid_fill = tc_pr.find("a:solidFill", NS)
925
+ if solid_fill is not None:
926
+ if solid_fill.find(".//a:alpha", NS) is not None:
927
+ return True
928
+ if _cell_fill_hex(tc_pr, palette) is None:
929
+ return True
930
+ tx_body = tc.find("a:txBody", NS)
931
+ if _text_body_has_unsupported_formatting(tx_body):
932
+ return True
933
+ return False
934
+
935
+
936
+ def _table_cell_has_unsupported_topology(tc: ET.Element) -> bool:
937
+ """Accept only the closed optional txBody -> optional tcPr cell sequence."""
938
+ if any(
939
+ name not in {"gridSpan", "rowSpan", "hMerge", "vMerge"}
940
+ for name in tc.attrib
941
+ ):
942
+ return True
943
+ tx_body_tag = f"{{{NS['a']}}}txBody"
944
+ tc_pr_tag = f"{{{NS['a']}}}tcPr"
945
+ child_tags = [child.tag for child in tc]
946
+ child_index = 0
947
+ if child_tags[:1] == [tx_body_tag]:
948
+ child_index += 1
949
+ if child_tags[child_index:child_index + 1] == [tc_pr_tag]:
950
+ child_index += 1
951
+ return child_index != len(child_tags)
952
+
953
+
954
+ def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
955
+ if tx_body is None:
956
+ return False
957
+ if tx_body.attrib:
958
+ return True
959
+
960
+ body_pr_tag = f"{{{NS['a']}}}bodyPr"
961
+ list_style_tag = f"{{{NS['a']}}}lstStyle"
962
+ paragraph_tag = f"{{{NS['a']}}}p"
963
+ body_tags = [child.tag for child in tx_body]
964
+ body_index = 0
965
+ if not body_tags or body_tags[0] != body_pr_tag:
966
+ return True
967
+ body_index += 1
968
+ if body_index < len(body_tags) and body_tags[body_index] == list_style_tag:
969
+ body_index += 1
970
+ if body_index == len(body_tags) or any(
971
+ tag != paragraph_tag for tag in body_tags[body_index:]
972
+ ):
973
+ return True
974
+
975
+ relationship_prefix = f"{{{NS['r']}}}"
976
+ forbidden_run_children = {
977
+ f"{{{NS['a']}}}extLst",
978
+ f"{{{NS['a']}}}hlinkClick",
979
+ f"{{{NS['a']}}}hlinkMouseOver",
980
+ }
981
+ if any(
982
+ node.tag in forbidden_run_children
983
+ or any(name.startswith(relationship_prefix) for name in node.attrib)
984
+ for node in tx_body.iter()
985
+ ):
986
+ return True
987
+
988
+ body_pr = tx_body.find("a:bodyPr", NS)
989
+ if body_pr is None or body_pr.attrib or list(body_pr):
990
+ return True
991
+ list_style = tx_body.find("a:lstStyle", NS)
992
+ if list_style is not None and (list_style.attrib or list(list_style)):
993
+ return True
994
+ for paragraph in tx_body.findall("a:p", NS):
995
+ if paragraph.attrib:
996
+ return True
997
+ p_pr_tag = f"{{{NS['a']}}}pPr"
998
+ run_tag = f"{{{NS['a']}}}r"
999
+ end_r_pr_tag = f"{{{NS['a']}}}endParaRPr"
1000
+ direct_tags = [child.tag for child in paragraph]
1001
+ paragraph_index = 0
1002
+ if direct_tags[:1] == [p_pr_tag]:
1003
+ paragraph_index += 1
1004
+ while (
1005
+ paragraph_index < len(direct_tags)
1006
+ and direct_tags[paragraph_index] == run_tag
1007
+ ):
1008
+ paragraph_index += 1
1009
+ if (
1010
+ paragraph_index < len(direct_tags)
1011
+ and direct_tags[paragraph_index] == end_r_pr_tag
1012
+ ):
1013
+ paragraph_index += 1
1014
+ if paragraph_index != len(direct_tags):
1015
+ return True
1016
+
1017
+ p_pr = paragraph.find("a:pPr", NS)
1018
+ if p_pr is not None:
1019
+ p_pr_tags = [child.tag.rsplit("}", 1)[-1] for child in p_pr]
1020
+ if p_pr_tags.count("defRPr") > 1 or p_pr_tags.count("buNone") > 1:
1021
+ return True
1022
+ if any(tag.startswith("bu") and tag != "buNone" for tag in p_pr_tags):
1023
+ return True
1024
+
1025
+ for run in paragraph.findall("a:r", NS):
1026
+ if run.attrib:
1027
+ return True
1028
+ r_pr_tag = f"{{{NS['a']}}}rPr"
1029
+ text_tag = f"{{{NS['a']}}}t"
1030
+ run_tags = [child.tag for child in run]
1031
+ if run_tags not in ([text_tag], [r_pr_tag, text_tag]):
1032
+ return True
1033
+ text_node = run.find("a:t", NS)
1034
+ if text_node is None or list(text_node):
1035
+ return True
1036
+ allowed_text_attrs = {"{http://www.w3.org/XML/1998/namespace}space"}
1037
+ if any(name not in allowed_text_attrs for name in text_node.attrib):
1038
+ return True
1039
+ return False
1040
+
1041
+
1042
+ def _legacy_text_body_has_unsupported_formatting(
1043
+ tx_body: ET.Element | None,
1044
+ ) -> bool:
1045
+ """Return the pre-P2-T4 gate so active plain payloads stay unchanged."""
1046
+ if tx_body is None:
1047
+ return False
1048
+ body_pr = tx_body.find("a:bodyPr", NS)
1049
+ if body_pr is not None and (body_pr.attrib or list(body_pr)):
1050
+ return True
1051
+ list_style = tx_body.find("a:lstStyle", NS)
1052
+ if list_style is not None and (list_style.attrib or list(list_style)):
1053
+ return True
1054
+ if (
1055
+ tx_body.find(".//a:br", NS) is not None
1056
+ or tx_body.find(".//a:fld", NS) is not None
1057
+ or tx_body.find(".//a:tab", NS) is not None
1058
+ ):
1059
+ return True
1060
+
1061
+ run_signatures: set[tuple[str | None, str | None, bytes | None]] = set()
1062
+ for paragraph in tx_body.findall("a:p", NS):
1063
+ p_pr = paragraph.find("a:pPr", NS)
1064
+ alignment = p_pr.get("algn") if p_pr is not None else None
1065
+ if alignment not in {None, "l", "ctr", "r"}:
1066
+ return True
1067
+ if p_pr is not None:
1068
+ if any(name != "algn" for name in p_pr.attrib):
1069
+ return True
1070
+ if any(
1071
+ child.tag.rsplit("}", 1)[-1] not in {"defRPr", "buNone"}
1072
+ for child in p_pr
1073
+ ):
1074
+ return True
1075
+
1076
+ default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
1077
+ if _legacy_run_props_have_unsupported_formatting(default_r_pr):
1078
+ return True
1079
+ for run in paragraph.findall("a:r", NS):
1080
+ r_pr = run.find("a:rPr", NS)
1081
+ if _legacy_run_props_have_unsupported_formatting(r_pr):
1082
+ return True
1083
+ run_signatures.add(
1084
+ _legacy_effective_run_signature(r_pr, default_r_pr)
1085
+ )
1086
+ end_r_pr = paragraph.find("a:endParaRPr", NS)
1087
+ if _legacy_run_props_have_unsupported_formatting(end_r_pr):
1088
+ return True
1089
+ if not paragraph.findall("a:r", NS) and end_r_pr is not None:
1090
+ run_signatures.add(
1091
+ _legacy_effective_run_signature(end_r_pr, default_r_pr)
1092
+ )
1093
+
1094
+ return len(run_signatures) > 1
1095
+
1096
+
1097
+ def _legacy_run_props_have_unsupported_formatting(
1098
+ r_pr: ET.Element | None,
1099
+ ) -> bool:
1100
+ if r_pr is None:
1101
+ return False
1102
+ if ooxml_bool(r_pr.get("i")):
1103
+ return True
1104
+ if r_pr.get("u") not in {None, "none"}:
1105
+ return True
1106
+ if r_pr.get("strike") not in {None, "noStrike"}:
1107
+ return True
1108
+ if r_pr.get("baseline") not in {None, "0"}:
1109
+ return True
1110
+ if r_pr.get("cap") not in {None, "none"}:
1111
+ return True
1112
+ if r_pr.get("spc") not in {None, "0"}:
1113
+ return True
1114
+ allowed_attrs = {
1115
+ "lang", "altLang", "sz", "b", "i", "u", "strike", "dirty",
1116
+ "baseline", "cap", "spc",
1117
+ }
1118
+ if any(name not in allowed_attrs for name in r_pr.attrib):
1119
+ return True
1120
+ solid_fill = r_pr.find("a:solidFill", NS)
1121
+ if solid_fill is not None and solid_fill.find(".//a:alpha", NS) is not None:
1122
+ return True
1123
+ return any(
1124
+ child.tag.rsplit("}", 1)[-1] != "solidFill"
1125
+ for child in r_pr
1126
+ )
1127
+
1128
+
1129
+ def _legacy_effective_run_signature(
1130
+ r_pr: ET.Element | None,
1131
+ default_r_pr: ET.Element | None,
1132
+ ) -> tuple[str | None, str | None, bytes | None]:
1133
+ def attr(name: str) -> str | None:
1134
+ if r_pr is not None and r_pr.get(name) is not None:
1135
+ return r_pr.get(name)
1136
+ return default_r_pr.get(name) if default_r_pr is not None else None
1137
+
1138
+ solid_fill = r_pr.find("a:solidFill", NS) if r_pr is not None else None
1139
+ if solid_fill is None and default_r_pr is not None:
1140
+ solid_fill = default_r_pr.find("a:solidFill", NS)
1141
+ fill_xml = (
1142
+ ET.tostring(solid_fill, encoding="utf-8")
1143
+ if solid_fill is not None else None
1144
+ )
1145
+ return attr("b"), attr("sz"), fill_xml
1146
+
1147
+
1148
+ def _round_payload_number(value: float) -> int | float:
1149
+ rounded = round(float(value), 3)
1150
+ return int(rounded) if rounded.is_integer() else rounded
1151
+
1152
+
1153
+ def _native_table_payload(
1154
+ tbl: ET.Element,
1155
+ xfrm: Xfrm,
1156
+ column_widths: list[float],
1157
+ row_heights: list[float],
1158
+ cells: list[list[_CellSlot | None]],
1159
+ palette: ColorPalette | None,
1160
+ theme_fonts: dict[str, str],
1161
+ ) -> dict[str, Any]:
1162
+ """Build the SVG native Table replacement payload for an unmerged table."""
1163
+ tbl_pr = tbl.find("a:tblPr", NS)
1164
+ payload: dict[str, Any] = {
1165
+ "x": _round_payload_number(xfrm.x),
1166
+ "y": _round_payload_number(xfrm.y),
1167
+ "width": _round_payload_number(xfrm.w),
1168
+ "height": _round_payload_number(xfrm.h),
1169
+ "strict_grid": True,
1170
+ "header_rows": (
1171
+ 1 if tbl_pr is not None and ooxml_bool(tbl_pr.get("firstRow")) else 0
1172
+ ),
1173
+ "column_widths": [_round_payload_number(width) for width in column_widths],
1174
+ "row_heights": [_round_payload_number(height) for height in row_heights],
1175
+ "rows": [],
1176
+ }
1177
+ style: dict[str, Any] = {
1178
+ "band_row": bool(tbl_pr is not None and ooxml_bool(tbl_pr.get("bandRow"))),
1179
+ }
1180
+ if tbl_pr is not None:
1181
+ table_style_id = tbl_pr.findtext("a:tableStyleId", default="", namespaces=NS).strip()
1182
+ if table_style_id:
1183
+ style["table_style_id"] = table_style_id
1184
+ payload["style"] = style
1185
+
1186
+ rows_payload: list[list[Any]] = []
1187
+ for row_cells in cells:
1188
+ row_payload: list[Any] = []
1189
+ for slot in row_cells:
1190
+ if slot is None or slot.is_dropped:
1191
+ row_payload.append("")
1192
+ continue
1193
+ cell_payload = _native_cell_payload(
1194
+ slot.element,
1195
+ palette,
1196
+ theme_fonts,
1197
+ )
1198
+ if slot.row_span > 1:
1199
+ cell_payload["row_span"] = slot.row_span
1200
+ if slot.col_span > 1:
1201
+ cell_payload["col_span"] = slot.col_span
1202
+ row_payload.append(cell_payload)
1203
+ rows_payload.append(row_payload)
1204
+ payload["rows"] = rows_payload
1205
+ return payload
1206
+
1207
+
1208
+ def _native_cell_payload(
1209
+ tc: ET.Element,
1210
+ palette: ColorPalette | None,
1211
+ theme_fonts: dict[str, str],
1212
+ ) -> dict[str, Any]:
1213
+ tx_body = tc.find("a:txBody", NS)
1214
+ tc_pr = tc.find("a:tcPr", NS)
1215
+ paragraph_payloads = _cell_paragraph_payloads(tx_body)
1216
+ rich_paragraphs = _cell_rich_paragraph_payloads(
1217
+ tx_body,
1218
+ palette,
1219
+ theme_fonts,
1220
+ )
1221
+ if rich_paragraphs is not None:
1222
+ cell: dict[str, Any] = {"paragraphs": rich_paragraphs}
1223
+ elif len(paragraph_payloads) > 1:
1224
+ cell: dict[str, Any] = {"paragraphs": paragraph_payloads}
1225
+ else:
1226
+ cell = {"text": _cell_plain_text(tx_body)}
1227
+
1228
+ fill = _cell_fill_hex(tc_pr, palette)
1229
+ if fill:
1230
+ cell["fill"] = fill
1231
+ if rich_paragraphs is None:
1232
+ color = _cell_text_color(tx_body, palette)
1233
+ if color:
1234
+ cell["color"] = color
1235
+ font_size = _cell_font_size_px(tx_body)
1236
+ if font_size:
1237
+ cell["font_size"] = font_size
1238
+ if len(paragraph_payloads) <= 1:
1239
+ align = _cell_align(tx_body)
1240
+ if align:
1241
+ cell["align"] = align
1242
+ valign = _cell_valign(tc_pr)
1243
+ if valign:
1244
+ cell["valign"] = valign
1245
+ if rich_paragraphs is None:
1246
+ bold = _cell_bold(tx_body)
1247
+ if bold is not None:
1248
+ cell["bold"] = bold
1249
+ borders = _cell_borders_payload(tc_pr, palette)
1250
+ if borders:
1251
+ cell["borders"] = borders
1252
+ _copy_cell_margins(tc_pr, cell)
1253
+ return cell
1254
+
1255
+
1256
+ def _cell_plain_text(tx_body: ET.Element | None) -> str:
1257
+ if tx_body is None:
1258
+ return ""
1259
+ paragraphs: list[str] = []
1260
+ for paragraph in tx_body.findall("a:p", NS):
1261
+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS))
1262
+ if text:
1263
+ paragraphs.append(text)
1264
+ return "\n".join(paragraphs)
1265
+
1266
+
1267
+ def _cell_paragraph_payloads(
1268
+ tx_body: ET.Element | None,
1269
+ ) -> list[str | dict[str, str]]:
1270
+ if tx_body is None:
1271
+ return []
1272
+ payloads: list[str | dict[str, str]] = []
1273
+ for paragraph in tx_body.findall("a:p", NS):
1274
+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS))
1275
+ p_pr = paragraph.find("a:pPr", NS)
1276
+ align = p_pr.get("algn") if p_pr is not None else None
1277
+ if align in {"l", "ctr", "r"}:
1278
+ payloads.append({"text": text, "align": align})
1279
+ else:
1280
+ payloads.append(text)
1281
+ return payloads
1282
+
1283
+
1284
+ def _effective_run_attr(
1285
+ r_pr: ET.Element | None,
1286
+ default_r_pr: ET.Element | None,
1287
+ name: str,
1288
+ ) -> str | None:
1289
+ if r_pr is not None and r_pr.get(name) is not None:
1290
+ return r_pr.get(name)
1291
+ return default_r_pr.get(name) if default_r_pr is not None else None
1292
+
1293
+
1294
+ def _effective_run_child(
1295
+ r_pr: ET.Element | None,
1296
+ default_r_pr: ET.Element | None,
1297
+ name: str,
1298
+ ) -> ET.Element | None:
1299
+ child = r_pr.find(f"a:{name}", NS) if r_pr is not None else None
1300
+ if child is not None:
1301
+ return child
1302
+ return default_r_pr.find(f"a:{name}", NS) if default_r_pr is not None else None
1303
+
1304
+
1305
+ def _native_run_font_family(
1306
+ r_pr: ET.Element | None,
1307
+ default_r_pr: ET.Element | None,
1308
+ theme_fonts: dict[str, str],
1309
+ ) -> str | None:
1310
+ faces: list[str] = []
1311
+ for tag in ("latin", "ea"):
1312
+ node = _effective_run_child(r_pr, default_r_pr, tag)
1313
+ raw_face = node.get("typeface") if node is not None else None
1314
+ face = _resolve_theme_typeface(raw_face, theme_fonts)
1315
+ if face and face not in faces:
1316
+ faces.append(face)
1317
+ if len(faces) != 1:
1318
+ return None
1319
+ face = faces[0].strip()
1320
+ return face if face and "," not in face else None
1321
+
1322
+
1323
+ def _native_run_payload(
1324
+ run: ET.Element,
1325
+ default_r_pr: ET.Element | None,
1326
+ palette: ColorPalette | None,
1327
+ theme_fonts: dict[str, str],
1328
+ ) -> dict[str, Any]:
1329
+ r_pr = run.find("a:rPr", NS)
1330
+ text = run.findtext("a:t", default="", namespaces=NS)
1331
+ payload: dict[str, Any] = {"text": text}
1332
+
1333
+ for source, target in (("b", "bold"), ("i", "italic")):
1334
+ raw = _effective_run_attr(r_pr, default_r_pr, source)
1335
+ if raw is not None:
1336
+ payload[target] = ooxml_bool(raw)
1337
+
1338
+ underline = _effective_run_attr(r_pr, default_r_pr, "u")
1339
+ if underline is not None:
1340
+ payload["underline"] = underline != "none"
1341
+ strike = _effective_run_attr(r_pr, default_r_pr, "strike")
1342
+ if strike is not None:
1343
+ payload["strike"] = strike != "noStrike"
1344
+
1345
+ font_size = _canonical_source_font_size_px(
1346
+ _effective_run_attr(r_pr, default_r_pr, "sz")
1347
+ )
1348
+ if font_size is not None:
1349
+ payload["font_size"] = font_size
1350
+
1351
+ solid_fill = _effective_run_child(r_pr, default_r_pr, "solidFill")
1352
+ if solid_fill is not None and not _solid_fill_is_unsafe(solid_fill, palette):
1353
+ try:
1354
+ color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
1355
+ except (AttributeError, OverflowError, TypeError, ValueError):
1356
+ color = None
1357
+ if color:
1358
+ payload["color"] = color
1359
+
1360
+ font_family = _native_run_font_family(
1361
+ r_pr,
1362
+ default_r_pr,
1363
+ theme_fonts,
1364
+ )
1365
+ if font_family:
1366
+ payload["font_family"] = font_family
1367
+
1368
+ for source, target in (("lang", "lang"), ("altLang", "alt_lang")):
1369
+ language = _effective_run_attr(r_pr, default_r_pr, source)
1370
+ if language and language.strip():
1371
+ payload[target] = language.strip()
1372
+ return payload
1373
+
1374
+
1375
+ def _cell_rich_paragraph_payloads(
1376
+ tx_body: ET.Element | None,
1377
+ palette: ColorPalette | None,
1378
+ theme_fonts: dict[str, str],
1379
+ ) -> list[dict[str, Any]] | None:
1380
+ """Materialize runs only when the legacy plain contract was insufficient."""
1381
+ if tx_body is None or not _legacy_text_body_has_unsupported_formatting(tx_body):
1382
+ return None
1383
+
1384
+ paragraphs: list[tuple[str | None, list[dict[str, Any]]]] = []
1385
+ style_signatures: set[tuple[tuple[str, Any], ...]] = set()
1386
+ needs_runs = False
1387
+ run_only_fields = {
1388
+ "italic", "underline", "strike", "font_family", "lang", "alt_lang",
1389
+ }
1390
+ for paragraph in tx_body.findall("a:p", NS):
1391
+ p_pr = paragraph.find("a:pPr", NS)
1392
+ align = p_pr.get("algn") if p_pr is not None else None
1393
+ if align not in {"l", "ctr", "r"}:
1394
+ align = None
1395
+ default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
1396
+ runs = [
1397
+ _native_run_payload(run, default_r_pr, palette, theme_fonts)
1398
+ for run in paragraph.findall("a:r", NS)
1399
+ ]
1400
+ paragraphs.append((align, runs))
1401
+ for run in runs:
1402
+ style = tuple(sorted((key, value) for key, value in run.items() if key != "text"))
1403
+ style_signatures.add(style)
1404
+ if run_only_fields.intersection(run):
1405
+ needs_runs = True
1406
+
1407
+ if len(style_signatures) > 1:
1408
+ needs_runs = True
1409
+ if not needs_runs:
1410
+ return None
1411
+
1412
+ payloads: list[dict[str, Any]] = []
1413
+ for align, runs in paragraphs:
1414
+ paragraph_payload: dict[str, Any]
1415
+ if runs:
1416
+ paragraph_payload = {"runs": runs}
1417
+ else:
1418
+ paragraph_payload = {"text": ""}
1419
+ if align is not None:
1420
+ paragraph_payload["align"] = align
1421
+ payloads.append(paragraph_payload)
1422
+ return payloads
1423
+
1424
+
1425
+ def _cell_fill_hex(tc_pr: ET.Element | None, palette: ColorPalette | None) -> str | None:
1426
+ fill = resolve_fill(tc_pr, palette)
1427
+ color = fill.attrs.get("fill") if fill.attrs else None
1428
+ if color and color.startswith("#"):
1429
+ return color
1430
+ return None
1431
+
1432
+
1433
+ def _cell_text_color(tx_body: ET.Element | None, palette: ColorPalette | None) -> str | None:
1434
+ for r_pr in _text_run_props_in_priority(tx_body):
1435
+ solid_fill = r_pr.find("a:solidFill", NS)
1436
+ if solid_fill is not None and not _solid_fill_is_unsafe(solid_fill, palette):
1437
+ try:
1438
+ color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
1439
+ except (AttributeError, OverflowError, TypeError, ValueError):
1440
+ continue
1441
+ if color:
1442
+ return color
1443
+ return None
1444
+
1445
+
1446
+ def _cell_font_size_px(tx_body: ET.Element | None) -> int | float | None:
1447
+ for r_pr in _text_run_props_in_priority(tx_body):
1448
+ size = _canonical_source_font_size_px(r_pr.get("sz"))
1449
+ if size is not None:
1450
+ return size
1451
+ return None
1452
+
1453
+
1454
+ def _canonical_source_font_size_px(raw_size: str | None) -> int | float | None:
1455
+ """Return a writer-stable font size for one bounded DrawingML token."""
1456
+ if (
1457
+ raw_size is None
1458
+ or not raw_size.isascii()
1459
+ or not raw_size.isdigit()
1460
+ or len(raw_size) > 6
1461
+ ):
1462
+ return None
1463
+ size_hpt = int(raw_size)
1464
+ if not 100 <= size_hpt <= 400000:
1465
+ return None
1466
+ # The writer emits sizes at 0.1pt precision; canonicalize on first import
1467
+ # so source and native reimport payloads stay stable.
1468
+ canonical_hpt = round(size_hpt / 10) * 10
1469
+ return _round_payload_number(hundredths_pt_to_px(canonical_hpt))
1470
+
1471
+
1472
+ def _cell_align(tx_body: ET.Element | None) -> str | None:
1473
+ if tx_body is None:
1474
+ return None
1475
+ p_pr = tx_body.find("a:p/a:pPr", NS)
1476
+ align = p_pr.get("algn") if p_pr is not None else None
1477
+ if align in {"l", "ctr", "r"}:
1478
+ return align
1479
+ return None
1480
+
1481
+
1482
+ def _cell_valign(tc_pr: ET.Element | None) -> str | None:
1483
+ anchor = tc_pr.get("anchor") if tc_pr is not None else None
1484
+ return {
1485
+ "t": "top",
1486
+ "ctr": "middle",
1487
+ "b": "bottom",
1488
+ }.get(anchor)
1489
+
1490
+
1491
+ def _cell_bold(tx_body: ET.Element | None) -> bool | None:
1492
+ for r_pr in _text_run_props_in_priority(tx_body):
1493
+ if r_pr.get("b") is not None:
1494
+ return ooxml_bool(r_pr.get("b"))
1495
+ return None
1496
+
1497
+
1498
+ def _cell_borders_payload(
1499
+ tc_pr: ET.Element | None,
1500
+ palette: ColorPalette | None,
1501
+ ) -> dict[str, dict[str, Any]]:
1502
+ if tc_pr is None:
1503
+ return {}
1504
+ borders: dict[str, dict[str, Any]] = {}
1505
+ for border_tag, side in _DIRECT_BORDER_TAGS.items():
1506
+ ln = tc_pr.find(f"a:{border_tag}", NS)
1507
+ if ln is not None:
1508
+ borders[side] = _direct_border_payload(ln, palette)
1509
+ return borders
1510
+
1511
+
1512
+ def _text_run_props_in_priority(tx_body: ET.Element | None) -> list[ET.Element]:
1513
+ if tx_body is None:
1514
+ return []
1515
+ props: list[ET.Element] = []
1516
+ for path in (".//a:r/a:rPr", ".//a:pPr/a:defRPr", ".//a:endParaRPr"):
1517
+ r_pr = tx_body.find(path, NS)
1518
+ if r_pr is not None:
1519
+ props.append(r_pr)
1520
+ return props
1521
+
1522
+
1523
+ def _copy_cell_margins(tc_pr: ET.Element | None, cell: dict[str, Any]) -> None:
1524
+ if tc_pr is None:
1525
+ return
1526
+ for source, target in (
1527
+ ("marL", "padding_left"),
1528
+ ("marR", "padding_right"),
1529
+ ("marT", "padding_top"),
1530
+ ("marB", "padding_bottom"),
1531
+ ):
1532
+ if source not in tc_pr.attrib:
1533
+ continue
1534
+ value = _safe_emu_integer(tc_pr.attrib[source])
1535
+ if value is None or value < 0:
1536
+ continue
1537
+ cell[target] = _round_payload_number(emu_to_px(value))
1538
+
1539
+
1540
+ # ---------------------------------------------------------------------------
1541
+ # Cell text & borders
1542
+ # ---------------------------------------------------------------------------
1543
+
1544
+ def _convert_cell_text(
1545
+ tx_body: ET.Element,
1546
+ tcPr: ET.Element | None,
1547
+ cell_xfrm: Xfrm,
1548
+ palette: ColorPalette | None,
1549
+ theme_fonts: dict[str, str] | None,
1550
+ *,
1551
+ fallback_run_props: tuple[ET.Element, ...],
1552
+ slide_number: int | None,
1553
+ id_prefix: str,
1554
+ id_seq: list[int] | None,
1555
+ hyperlink_resolver: HyperlinkResolver | None,
1556
+ ):
1557
+ """Render cell text. PowerPoint's <a:tcPr> can override txBody insets via
1558
+ its own marL/marR/marT/marB attrs; convert_txbody reads from <a:bodyPr>,
1559
+ so we materialise a synthetic bodyPr when tcPr has its own insets. Invalid
1560
+ malformed source font-size and run-color values are removed from a private
1561
+ render copy; they have already been omitted from the native payload and
1562
+ must not crash fallback SVG generation."""
1563
+ render_tx_body = tx_body
1564
+ run_props = [
1565
+ node
1566
+ for node in tx_body.iter()
1567
+ if node.tag in {
1568
+ f"{{{NS['a']}}}defRPr",
1569
+ f"{{{NS['a']}}}endParaRPr",
1570
+ f"{{{NS['a']}}}rPr",
1571
+ }
1572
+ ]
1573
+ if any(
1574
+ _run_props_need_render_normalization(node, palette)
1575
+ for node in run_props
1576
+ ):
1577
+ render_tx_body = copy.deepcopy(tx_body)
1578
+ for node in render_tx_body.iter():
1579
+ if node.tag not in {
1580
+ f"{{{NS['a']}}}defRPr",
1581
+ f"{{{NS['a']}}}endParaRPr",
1582
+ f"{{{NS['a']}}}rPr",
1583
+ }:
1584
+ continue
1585
+ if (
1586
+ node.get("sz") is not None
1587
+ and _canonical_source_font_size_px(node.get("sz")) is None
1588
+ ):
1589
+ node.attrib.pop("sz", None)
1590
+ solid_fill = node.find("a:solidFill", NS)
1591
+ if solid_fill is not None and _solid_fill_is_unsafe(solid_fill, palette):
1592
+ node.remove(solid_fill)
1593
+
1594
+ body_pr = render_tx_body.find("a:bodyPr", NS)
1595
+ overrides = _tcPr_inset_overrides(tcPr)
1596
+ saved: dict[str, str | None] = {}
1597
+ if overrides and body_pr is not None:
1598
+ for key, val in overrides.items():
1599
+ saved[key] = body_pr.attrib.get(key)
1600
+ body_pr.set(key, val)
1601
+ try:
1602
+ try:
1603
+ return convert_txbody(
1604
+ render_tx_body, cell_xfrm, palette, theme_fonts=theme_fonts,
1605
+ fallback_run_props=fallback_run_props,
1606
+ slide_number=slide_number,
1607
+ id_prefix=id_prefix,
1608
+ id_seq=id_seq,
1609
+ hyperlink_resolver=hyperlink_resolver,
1610
+ )
1611
+ except (AttributeError, OverflowError, TypeError, ValueError):
1612
+ plain_tx_body = _plain_table_text_body(render_tx_body, overrides)
1613
+ return convert_txbody(
1614
+ plain_tx_body, cell_xfrm, palette, theme_fonts=theme_fonts,
1615
+ fallback_run_props=(),
1616
+ slide_number=slide_number,
1617
+ id_prefix=id_prefix,
1618
+ id_seq=id_seq,
1619
+ hyperlink_resolver=hyperlink_resolver,
1620
+ )
1621
+ finally:
1622
+ if overrides and body_pr is not None:
1623
+ for key, prior in saved.items():
1624
+ if prior is None:
1625
+ body_pr.attrib.pop(key, None)
1626
+ else:
1627
+ body_pr.set(key, prior)
1628
+
1629
+
1630
+ def _run_props_need_render_normalization(
1631
+ run_props: ET.Element,
1632
+ palette: ColorPalette | None,
1633
+ ) -> bool:
1634
+ size = run_props.get("sz")
1635
+ if size is not None and _canonical_source_font_size_px(size) is None:
1636
+ return True
1637
+ solid_fill = run_props.find("a:solidFill", NS)
1638
+ return solid_fill is not None and _solid_fill_is_unsafe(solid_fill, palette)
1639
+
1640
+
1641
+ def _solid_fill_is_unsafe(
1642
+ solid_fill: ET.Element,
1643
+ palette: ColorPalette | None,
1644
+ ) -> bool:
1645
+ color = find_color_elem(solid_fill)
1646
+ if color is not None and not _color_numeric_tokens_are_finite(color):
1647
+ return True
1648
+ try:
1649
+ resolve_color(color, palette)
1650
+ except (AttributeError, OverflowError, TypeError, ValueError):
1651
+ return True
1652
+ return False
1653
+
1654
+
1655
+ def _color_numeric_tokens_are_finite(color: ET.Element) -> bool:
1656
+ """Reject non-finite numeric tokens before the resolver can clamp them."""
1657
+ base_numeric_attrs = {
1658
+ "hslClr": ("hue", "sat", "lum"),
1659
+ "scrgbClr": ("r", "g", "b"),
1660
+ }
1661
+ modifier_tags = {
1662
+ "alpha", "alphaMod", "alphaOff", "hueMod", "hueOff",
1663
+ "lumMod", "lumOff", "satMod", "satOff", "shade", "tint",
1664
+ }
1665
+ for node in color.iter():
1666
+ name = node.tag.rsplit("}", 1)[-1]
1667
+ attrs = base_numeric_attrs.get(name, ())
1668
+ if name in modifier_tags:
1669
+ attrs = ("val",)
1670
+ for attr in attrs:
1671
+ raw = node.get(attr)
1672
+ if raw is None:
1673
+ return False
1674
+ try:
1675
+ value = float(raw)
1676
+ except (OverflowError, TypeError, ValueError):
1677
+ return False
1678
+ if not math.isfinite(value):
1679
+ return False
1680
+ return True
1681
+
1682
+
1683
+ def _plain_table_text_body(
1684
+ tx_body: ET.Element,
1685
+ overrides: dict[str, str],
1686
+ ) -> ET.Element:
1687
+ """Return a text-preserving style-free fallback after malformed styling."""
1688
+ plain = copy.deepcopy(tx_body)
1689
+ body_pr = plain.find("a:bodyPr", NS)
1690
+ if body_pr is None:
1691
+ body_pr = ET.Element(f"{{{NS['a']}}}bodyPr")
1692
+ plain.insert(0, body_pr)
1693
+ body_pr.clear()
1694
+ for key, value in overrides.items():
1695
+ body_pr.set(key, value)
1696
+ list_style = plain.find("a:lstStyle", NS)
1697
+ if list_style is not None:
1698
+ list_style.clear()
1699
+ for paragraph in plain.findall("a:p", NS):
1700
+ p_pr = paragraph.find("a:pPr", NS)
1701
+ if p_pr is not None:
1702
+ align = p_pr.get("algn")
1703
+ p_pr.clear()
1704
+ if align in {"l", "ctr", "r"}:
1705
+ p_pr.set("algn", align)
1706
+ for path in (".//a:rPr", ".//a:defRPr", ".//a:endParaRPr"):
1707
+ for run_props in plain.findall(path, NS):
1708
+ run_props.clear()
1709
+ return plain
1710
+
1711
+
1712
+ def _tcPr_inset_overrides(tcPr: ET.Element | None) -> dict[str, str]:
1713
+ if tcPr is None:
1714
+ return {}
1715
+ out: dict[str, str] = {}
1716
+ for src, dst in (("marL", "lIns"), ("marR", "rIns"),
1717
+ ("marT", "tIns"), ("marB", "bIns")):
1718
+ if src not in tcPr.attrib:
1719
+ continue
1720
+ value = _safe_emu_integer(tcPr.attrib[src])
1721
+ if value is not None and value >= 0:
1722
+ out[dst] = str(value)
1723
+ return out
1724
+
1725
+
1726
+ def _border_line(
1727
+ tcPr: ET.Element | None,
1728
+ table_style: _TableStyleContext,
1729
+ row_index: int,
1730
+ col_index: int,
1731
+ row_count: int,
1732
+ col_count: int,
1733
+ tag: str,
1734
+ x1: float, y1: float, x2: float, y2: float,
1735
+ palette: ColorPalette | None,
1736
+ *,
1737
+ id_prefix: str,
1738
+ id_seq: list[int],
1739
+ defs: list[str],
1740
+ ) -> str:
1741
+ """Emit a single border <line> for a given cell side, or empty string when
1742
+ that side is explicitly noFill / not specified."""
1743
+ ln = tcPr.find(tag, NS) if tcPr is not None else None
1744
+ if ln is not None:
1745
+ return _line_element_to_svg(
1746
+ ln, x1, y1, x2, y2, palette,
1747
+ id_prefix=id_prefix, id_seq=id_seq, defs=defs,
1748
+ )
1749
+
1750
+ # Draw inherited shared edges once, from the upper/left cell. This keeps
1751
+ # a specific firstRow bottom border from being painted over by the next
1752
+ # row's whole-table top border. A direct border above still wins because
1753
+ # it is handled before this de-duplication gate.
1754
+ if (tag == "a:lnT" and row_index > 0) or (
1755
+ tag == "a:lnL" and col_index > 0
1756
+ ):
1757
+ return ""
1758
+
1759
+ for region_name, region in table_style.regions_for_row(row_index):
1760
+ for border_name in _table_style_border_names(
1761
+ region_name, row_index, col_index, row_count, col_count, tag,
1762
+ ):
1763
+ ln = region.find(
1764
+ f"a:tcStyle/a:tcBdr/a:{border_name}/a:ln", NS,
1765
+ )
1766
+ if ln is not None:
1767
+ return _line_element_to_svg(
1768
+ ln, x1, y1, x2, y2, palette,
1769
+ id_prefix=id_prefix, id_seq=id_seq, defs=defs,
1770
+ )
1771
+ return ""
1772
+
1773
+
1774
+ def _table_style_border_names(
1775
+ region_name: str,
1776
+ row_index: int,
1777
+ col_index: int,
1778
+ row_count: int,
1779
+ col_count: int,
1780
+ tag: str,
1781
+ ) -> tuple[str, ...]:
1782
+ side_names = {
1783
+ "a:lnT": ("top", "insideH", row_index > 0),
1784
+ "a:lnR": ("right", "insideV", col_index < col_count - 1),
1785
+ "a:lnB": ("bottom", "insideH", row_index < row_count - 1),
1786
+ "a:lnL": ("left", "insideV", col_index > 0),
1787
+ }
1788
+ side, inside, is_internal = side_names[tag]
1789
+ if region_name == "wholeTbl" and is_internal:
1790
+ return inside, side
1791
+ return side, inside
1792
+
1793
+
1794
+ def _line_element_to_svg(
1795
+ ln: ET.Element,
1796
+ x1: float,
1797
+ y1: float,
1798
+ x2: float,
1799
+ y2: float,
1800
+ palette: ColorPalette | None,
1801
+ *,
1802
+ id_prefix: str,
1803
+ id_seq: list[int],
1804
+ defs: list[str],
1805
+ ) -> str:
1806
+ # Skip explicit no-line.
1807
+ if ln.find("a:noFill", NS) is not None:
1808
+ return ""
1809
+
1810
+ stroke = resolve_stroke(
1811
+ # resolve_stroke expects a parent that contains <a:ln>; wrap so it
1812
+ # finds our tag's own children as the line spec.
1813
+ _make_ln_wrapper(ln),
1814
+ palette,
1815
+ id_prefix=id_prefix,
1816
+ id_seq=id_seq,
1817
+ )
1818
+ defs.extend(stroke.defs)
1819
+ attrs = stroke.attrs
1820
+ if not attrs.get("stroke"):
1821
+ return ""
1822
+ attr_str = "".join(f' {k}="{v}"' for k, v in attrs.items())
1823
+ return (
1824
+ f'<line x1="{fmt_num(x1)}" y1="{fmt_num(y1)}" '
1825
+ f'x2="{fmt_num(x2)}" y2="{fmt_num(y2)}"{attr_str}/>'
1826
+ )
1827
+
1828
+
1829
+ def _make_ln_wrapper(ln: ET.Element) -> ET.Element:
1830
+ """resolve_stroke walks for ``parent.find('a:ln')``; tcPr borders ARE the
1831
+ <a:ln> already, so wrap them in a synthetic parent that points back at
1832
+ the original element under the expected tag.
1833
+ """
1834
+ wrapper = ET.Element(f"{{{NS['a']}}}wrapper")
1835
+ proxy = ET.SubElement(wrapper, f"{{{NS['a']}}}ln")
1836
+ # Carry attributes (e.g. w="...") and children (solidFill, prstDash, ...).
1837
+ for k, v in ln.attrib.items():
1838
+ proxy.set(k, v)
1839
+ for child in list(ln):
1840
+ proxy.append(child)
1841
+ return wrapper