@hfyjq/crannia 1.0.0 → 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 (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -1,781 +1,781 @@
1
- """Core SVG -> DrawingML dispatcher, group handling, and main entry point."""
2
-
3
- from __future__ import annotations
4
-
5
- import math
6
- import re
7
- from pathlib import Path
8
- from typing import Any
9
- from xml.etree import ElementTree as ET
10
-
11
- from ...resource_paths import icon_search_dirs_for_svg
12
-
13
- from .context import ConvertContext, ShapeResult
14
- from .utils import (
15
- SVG_NS, EMU_PER_PX,
16
- _extract_inheritable_styles, _f, _get_attr, parse_transform_matrix, resolve_url_id,
17
- parse_svg_length,
18
- )
19
- from .styles import (
20
- build_effect_xml, build_fill_xml, get_fill_opacity, get_stroke_opacity,
21
- )
22
- from .elements import (
23
- convert_rect, convert_circle, convert_ellipse,
24
- convert_line, convert_path,
25
- convert_polygon, convert_polyline,
26
- convert_text, convert_image, convert_nested_svg,
27
- )
28
- try:
29
- from ..native_objects import convert_native_object
30
- except ImportError:
31
- convert_native_object = None
32
-
33
-
34
- class SvgNativeConversionError(RuntimeError):
35
- """Raised when an SVG cannot be faithfully converted to native DrawingML."""
36
-
37
-
38
- # ---------------------------------------------------------------------------
39
- # Animation anchor selection
40
- # ---------------------------------------------------------------------------
41
-
42
- # Tokens that mark a top-level <g id="..."> as page chrome rather than animated
43
- # content. When any token (after splitting id on '-' and '_') matches, the group
44
- # is excluded from the per-element entrance animation cascade so background,
45
- # header/footer, decorations etc. appear together with the slide instead of
46
- # requiring presenter clicks.
47
- _CHROME_ID_TOKENS = frozenset({
48
- 'background', 'bg',
49
- 'decoration', 'decorations', 'decor',
50
- 'header', 'footer',
51
- 'chrome', 'watermark',
52
- 'pagenumber', 'pagenum',
53
- 'nav', 'logo', 'rule',
54
- })
55
-
56
-
57
- def _is_chrome_id(elem_id: str | None) -> bool:
58
- if not elem_id:
59
- return False
60
- lower = elem_id.lower()
61
- if lower.replace('-', '').replace('_', '') in _CHROME_ID_TOKENS:
62
- return True
63
- tokens = re.split(r'[-_]', lower)
64
- return any(t in _CHROME_ID_TOKENS for t in tokens if t)
65
-
66
-
67
- # ---------------------------------------------------------------------------
68
- # Transform & layout helpers
69
- # ---------------------------------------------------------------------------
70
-
71
- def parse_transform(transform_str: str) -> tuple[float, float, float, float, float]:
72
- """Parse an SVG transform list into (dx, dy, sx, sy, angle_deg).
73
-
74
- Composes every translate/scale/rotate/matrix operation rather than picking
75
- the first occurrence — needed for idioms like
76
- translate(cx cy) scale(-1 -1) translate(-cx -cy) which encode a flip
77
- around a non-origin pivot.
78
-
79
- When the composed matrix has no shear and no rotation, the decomposition is
80
- exact (sx/sy may be negative to represent flips). When rotation is present
81
- without shear, sx/sy default to the column magnitudes and angle_deg is the
82
- rotation. Shear is not representable in this 5-tuple and silently
83
- collapses; callers that need exact fidelity should consume the full matrix
84
- via `parse_transform_matrix`.
85
- """
86
- if not transform_str:
87
- return 0.0, 0.0, 1.0, 1.0, 0.0
88
-
89
- a, b, c, d, e, f = parse_transform_matrix(transform_str)
90
-
91
- # No shear / rotation: direct decomposition preserves the original signs of
92
- # sx / sy. ctx_x / ctx_y use the simple val * sx + tx formula, so this
93
- # is the only form that survives flip-around-pivot composites without
94
- # collapsing them into a rotation that the consumer can't honour.
95
- if abs(b) < 1e-9 and abs(c) < 1e-9:
96
- sx = a if a != 0 else 1.0
97
- sy = d if d != 0 else 1.0
98
- return e, f, sx, sy, 0.0
99
-
100
- sx = math.hypot(a, b)
101
- sy = math.hypot(c, d)
102
- if sx == 0:
103
- sx = 1.0
104
- if sy == 0:
105
- sy = 1.0
106
-
107
- angle_deg = math.degrees(math.atan2(b, a))
108
- return e, f, sx, sy, angle_deg
109
-
110
-
111
- # `rotate(angle)` defaults to pivot (0,0); rotate(angle, cx, cy) rotates
112
- # around (cx, cy). DrawingML grpSp `rot` always rotates around the group's
113
- # own bounding-box centre — we need the SVG pivot so `convert_g` can
114
- # compensate for the offset between those two centres.
115
- _ROTATE_RE = re.compile(
116
- r'rotate\(\s*([-\d.eE+]+)(?:[\s,]+([-\d.eE+]+)[\s,]+([-\d.eE+]+))?\s*\)'
117
- )
118
-
119
-
120
- def _root_viewport_size(root: ET.Element) -> tuple[float, float]:
121
- """Return the SVG root viewport size in user units."""
122
- view_box = root.get('viewBox')
123
- if view_box:
124
- raw_parts = re.split(r'[\s,]+', view_box.strip())
125
- if len(raw_parts) == 4:
126
- try:
127
- parts = [float(n) for n in raw_parts]
128
- except ValueError:
129
- parts = []
130
- if parts and parts[2] > 0 and parts[3] > 0:
131
- return parts[2], parts[3]
132
-
133
- width = parse_svg_length(root.get('width'), 1280.0)
134
- height = parse_svg_length(root.get('height'), 720.0)
135
- return max(width, 1.0), max(height, 1.0)
136
-
137
-
138
- def _extract_rotate_pivot(transform_str: str) -> tuple[float, float] | None:
139
- """Return the (cx, cy) pivot of a sole `rotate(...)` in *transform_str*.
140
-
141
- Returns `None` when the transform list contains anything other than one
142
- rotate (other ops compose with rotate in a way the pivot-compensation
143
- fallback can't express). A bare `rotate(angle)` returns (0, 0).
144
- """
145
- if not transform_str:
146
- return None
147
- ops = [op for op in re.findall(r'(\w+)\s*\(', transform_str) if op]
148
- if ops != ['rotate']:
149
- return None
150
- match = _ROTATE_RE.search(transform_str)
151
- if not match:
152
- return None
153
- cx = float(match.group(2)) if match.group(2) is not None else 0.0
154
- cy = float(match.group(3)) if match.group(3) is not None else 0.0
155
- return cx, cy
156
-
157
-
158
- # ---------------------------------------------------------------------------
159
- # Group handling
160
- # ---------------------------------------------------------------------------
161
-
162
- def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
163
- """Convert SVG <g> to DrawingML group shape <p:grpSp>.
164
-
165
- Preserves group structure so elements can be selected and moved together
166
- in PowerPoint. Single-child groups are flattened to avoid unnecessary nesting.
167
-
168
- Uses identity coordinate mapping (chOff/chExt == off/ext) so child shapes
169
- keep their absolute slide coordinates unchanged.
170
- """
171
- transform = elem.get('transform', '')
172
- dx, dy, sx, sy, angle_deg = parse_transform(transform)
173
-
174
- filter_id = resolve_url_id(elem.get('filter', ''))
175
- style_overrides = _extract_inheritable_styles(elem)
176
-
177
- elem_id = elem.get('id')
178
- should_animate_group = ctx.depth == 0 and elem_id and not _is_chrome_id(elem_id)
179
- visual_children = [
180
- child for child in elem
181
- if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
182
- ]
183
- matrix_supported = bool(transform) and visual_children and all(
184
- _supports_matrix_transform(child) for child in visual_children
185
- )
186
- # A pure rotate(angle [cx cy]) falls through to the fallback path
187
- # below (children are rect/text/path/etc. that don't consume a full
188
- # matrix). Decomposing the matrix produces translation components
189
- # (e, f) that encode the pivot — handing those to children would
190
- # *double-translate* them because grpSp's own `rot` already
191
- # rotates around the group's bounding-box centre. Skip the child
192
- # translation here and apply pivot-centre compensation to `a:off`
193
- # below instead.
194
- rotate_pivot = _extract_rotate_pivot(transform) if not matrix_supported else None
195
- if matrix_supported:
196
- child_ctx = ctx.child(
197
- 0, 0, 1.0, 1.0,
198
- transform_matrix=parse_transform_matrix(transform),
199
- filter_id=filter_id,
200
- style_overrides=style_overrides,
201
- )
202
- elif rotate_pivot is not None:
203
- child_ctx = ctx.child(
204
- 0, 0, 1.0, 1.0,
205
- filter_id=filter_id,
206
- style_overrides=style_overrides,
207
- )
208
- else:
209
- child_ctx = ctx.child(dx, dy, sx, sy, filter_id=filter_id, style_overrides=style_overrides)
210
-
211
- if child_ctx.native_objects_enabled and convert_native_object:
212
- native_result = convert_native_object(elem, child_ctx)
213
- if native_result:
214
- ctx.sync_from_child(child_ctx)
215
- if should_animate_group:
216
- shape_match = re.search(r'<p:cNvPr id="(\d+)"', native_result.xml)
217
- if shape_match:
218
- ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
219
- return native_result
220
-
221
- child_results: list[ShapeResult] = []
222
- for child in elem:
223
- result = convert_element(child, child_ctx)
224
- if result:
225
- child_results.append(result)
226
-
227
- ctx.sync_from_child(child_ctx)
228
-
229
- if not child_results:
230
- return None
231
-
232
- # Single-child non-semantic groups are flattened to reduce nesting. Top-level
233
- # semantic groups are preserved so animations target the group, not its
234
- # individual child shapes.
235
- if len(child_results) == 1 and not should_animate_group:
236
- return child_results[0]
237
-
238
- # Multiple children, or a top-level semantic one-child group: wrap in
239
- # <p:grpSp> so PowerPoint can animate the group as one unit.
240
- min_x = min_y = float('inf')
241
- max_x = max_y = float('-inf')
242
-
243
- for child_result in child_results:
244
- bounds = child_result.bounds_emu
245
- if bounds is None:
246
- continue
247
- min_x = min(min_x, bounds[0])
248
- min_y = min(min_y, bounds[1])
249
- max_x = max(max_x, bounds[2])
250
- max_y = max(max_y, bounds[3])
251
-
252
- if min_x == float('inf'):
253
- return ShapeResult(xml='\n'.join(result.xml for result in child_results))
254
-
255
- group_x = int(min_x)
256
- group_y = int(min_y)
257
- group_w = max(int(max_x - min_x), 1)
258
- group_h = max(int(max_y - min_y), 1)
259
-
260
- # rotate(angle, cx, cy) rotates around the SVG pivot, but DrawingML
261
- # grpSp `rot` always rotates around the group's own bbox centre. When
262
- # those centres differ, the visual position drifts by exactly the
263
- # translation a rotate-around-pivot equals. Compensate by offsetting the
264
- # outer <a:off> only; <a:chOff> stays on the unshifted bbox so children
265
- # (still at their original SVG positions because rotate_pivot suppressed
266
- # the dx/dy translation above) remain aligned inside the group.
267
- off_x = group_x
268
- off_y = group_y
269
- if rotate_pivot is not None and angle_deg:
270
- cx_svg, cy_svg = rotate_pivot
271
- pivot_ex = (cx_svg + ctx.translate_x) * EMU_PER_PX
272
- pivot_ey = (cy_svg + ctx.translate_y) * EMU_PER_PX
273
- bbox_cx = group_x + group_w / 2
274
- bbox_cy = group_y + group_h / 2
275
- theta = math.radians(angle_deg)
276
- cos_t = math.cos(theta)
277
- sin_t = math.sin(theta)
278
- # Where the bbox centre lands after rotating around the pivot, minus
279
- # where DrawingML's grpSp rot would leave it (i.e. unchanged).
280
- delta_x = (bbox_cx - pivot_ex) * cos_t - (bbox_cy - pivot_ey) * sin_t + pivot_ex - bbox_cx
281
- delta_y = (bbox_cx - pivot_ex) * sin_t + (bbox_cy - pivot_ey) * cos_t + pivot_ey - bbox_cy
282
- off_x = int(round(group_x + delta_x))
283
- off_y = int(round(group_y + delta_y))
284
-
285
- shapes_xml = '\n'.join(result.xml for result in child_results)
286
- group_id = ctx.next_id()
287
-
288
- # Record top-level semantic groups (e.g. <g id="p02-title">) so the
289
- # PPTX builder can emit per-element entrance timing. Only the outermost
290
- # multi-child wrapper qualifies — flattened single-child groups have no
291
- # <p:grpSp> to anchor a timing target on, and nested groups are
292
- # ignored to keep the animation budget at ~per-section granularity.
293
- if should_animate_group:
294
- ctx.anim_targets.append((group_id, elem_id))
295
-
296
- group_effect = ''
297
- if filter_id and filter_id in ctx.defs:
298
- group_effect = build_effect_xml(ctx.defs[filter_id])
299
-
300
- rot_emu = 0 if matrix_supported else int(angle_deg * 60000)
301
- rot_attr = f' rot="{rot_emu}"' if rot_emu else ''
302
-
303
- return ShapeResult(xml=f'''<p:grpSp>
304
- <p:nvGrpSpPr>
305
- <p:cNvPr id="{group_id}" name="Group {group_id}"/>
306
- <p:cNvGrpSpPr/>
307
- <p:nvPr/>
308
- </p:nvGrpSpPr>
309
- <p:grpSpPr>
310
- <a:xfrm{rot_attr}>
311
- <a:off x="{off_x}" y="{off_y}"/>
312
- <a:ext cx="{group_w}" cy="{group_h}"/>
313
- <a:chOff x="{group_x}" y="{group_y}"/>
314
- <a:chExt cx="{group_w}" cy="{group_h}"/>
315
- </a:xfrm>
316
- {group_effect}
317
- </p:grpSpPr>
318
- {shapes_xml}
319
- </p:grpSp>''', bounds_emu=(group_x, group_y, group_x + group_w, group_y + group_h))
320
-
321
-
322
- # ---------------------------------------------------------------------------
323
- # Defs collection & element dispatch
324
- # ---------------------------------------------------------------------------
325
-
326
- _NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))
327
-
328
-
329
- def _supports_matrix_transform(elem: ET.Element) -> bool:
330
- """Return whether this subtree can consume a full affine matrix directly."""
331
- tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
332
- if tag in {'rect', 'circle', 'ellipse', 'line', 'path', 'polygon', 'polyline', 'image'}:
333
- return True
334
- if tag == 'svg':
335
- visual_children = [
336
- child for child in elem
337
- if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
338
- ]
339
- return len(visual_children) == 1 and (
340
- visual_children[0].tag.replace(f'{{{SVG_NS}}}', '') == 'image'
341
- )
342
- if tag == 'g':
343
- visual_children = [
344
- child for child in elem
345
- if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
346
- ]
347
- return bool(visual_children) and all(
348
- _supports_matrix_transform(child) for child in visual_children
349
- )
350
- return False
351
-
352
- _CONVERTERS = {
353
- 'rect': convert_rect,
354
- 'circle': convert_circle,
355
- 'ellipse': convert_ellipse,
356
- 'line': convert_line,
357
- 'path': convert_path,
358
- 'polygon': convert_polygon,
359
- 'polyline': convert_polyline,
360
- 'text': convert_text,
361
- 'image': convert_image,
362
- 'g': convert_g,
363
- 'svg': convert_nested_svg,
364
- }
365
-
366
- _SUPPORTED_VISUAL_CHILD_TAGS = frozenset(('tspan',))
367
-
368
-
369
- def _parse_svg_canvas(root: ET.Element) -> tuple[float, float, float, float]:
370
- """Return the SVG canvas as (x, y, width, height) in SVG units."""
371
- view_box = root.get('viewBox', '')
372
- parts = re.split(r'[\s,]+', view_box.strip()) if view_box else []
373
- if len(parts) == 4:
374
- try:
375
- x, y, w, h = (float(part) for part in parts)
376
- if w > 0 and h > 0:
377
- return x, y, w, h
378
- except ValueError:
379
- pass
380
- return 0.0, 0.0, _f(root.get('width')), _f(root.get('height'))
381
-
382
-
383
- def _is_full_canvas_rect(
384
- elem: ET.Element,
385
- ctx: ConvertContext,
386
- canvas: tuple[float, float, float, float],
387
- ) -> bool:
388
- """Return whether a rect is a safe candidate for native slide background."""
389
- if elem.get('transform') or elem.get('filter') or elem.get('clip-path'):
390
- return False
391
- if _f(elem.get('rx')) > 0 or _f(elem.get('ry')) > 0:
392
- return False
393
-
394
- canvas_x, canvas_y, canvas_w, canvas_h = canvas
395
- if canvas_w <= 0 or canvas_h <= 0:
396
- return False
397
-
398
- tolerance = 0.5
399
- if abs(_f(elem.get('x')) - canvas_x) > tolerance:
400
- return False
401
- if abs(_f(elem.get('y')) - canvas_y) > tolerance:
402
- return False
403
- if abs(_f(elem.get('width')) - canvas_w) > tolerance:
404
- return False
405
- if abs(_f(elem.get('height')) - canvas_h) > tolerance:
406
- return False
407
-
408
- fill = _get_attr(elem, 'fill', ctx)
409
- if fill == 'none':
410
- return False
411
-
412
- stroke = _get_attr(elem, 'stroke', ctx)
413
- stroke_width = _f(_get_attr(elem, 'stroke-width', ctx), 1.0)
414
- stroke_opacity = get_stroke_opacity(elem, ctx)
415
- if stroke and stroke != 'none' and stroke_width > 0 and stroke_opacity != 0:
416
- return False
417
-
418
- return True
419
-
420
-
421
- def _background_xml_from_rect(
422
- elem: ET.Element,
423
- ctx: ConvertContext,
424
- ) -> str:
425
- """Build native `p:bg` XML from a full-slide SVG background rect."""
426
- fill_xml = build_fill_xml(elem, ctx, get_fill_opacity(elem, ctx))
427
- if not fill_xml or '<a:noFill' in fill_xml:
428
- return ''
429
- return f'<p:bg><p:bgPr>{fill_xml}<a:effectLst/></p:bgPr></p:bg>'
430
-
431
-
432
- def _extract_background_candidate(
433
- root: ET.Element,
434
- ctx: ConvertContext,
435
- ) -> tuple[str, int | None]:
436
- """Promote a first-layer SVG background rect to native PowerPoint bgPr.
437
-
438
- PowerPoint stores page background fills under `p:cSld/p:bg/p:bgPr`.
439
- Keeping the full-canvas SVG rect in `p:spTree` makes it an ordinary
440
- selectable shape, so users hit it during bulk element selection. Only the
441
- first visual layer is considered, matching pptx_to_svg's round-trip output
442
- and avoiding accidental promotion of content panels.
443
- """
444
- canvas = _parse_svg_canvas(root)
445
- for child in root:
446
- tag = child.tag.replace(f'{{{SVG_NS}}}', '')
447
- if tag in _NON_VISUAL_TAGS:
448
- continue
449
-
450
- if tag == 'rect' and _is_full_canvas_rect(child, ctx, canvas):
451
- bg_xml = _background_xml_from_rect(child, ctx)
452
- if bg_xml:
453
- return bg_xml, id(child)
454
- return '', None
455
-
456
- if tag != 'g':
457
- return '', None
458
- if child.get('transform') or child.get('filter') or child.get('clip-path'):
459
- return '', None
460
- style_overrides = _extract_inheritable_styles(child)
461
- child_ctx = ctx.child(style_overrides=style_overrides)
462
- visual_children = [
463
- grandchild for grandchild in child
464
- if grandchild.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
465
- ]
466
- if len(visual_children) != 1:
467
- return '', None
468
- only_child = visual_children[0]
469
- only_tag = only_child.tag.replace(f'{{{SVG_NS}}}', '')
470
- if only_tag == 'rect' and _is_full_canvas_rect(only_child, child_ctx, canvas):
471
- bg_xml = _background_xml_from_rect(only_child, child_ctx)
472
- if bg_xml:
473
- ctx.sync_from_child(child_ctx)
474
- return bg_xml, id(child)
475
- return '', None
476
- return '', None
477
-
478
- return '', None
479
-
480
-
481
- def collect_defs(root: ET.Element) -> dict[str, ET.Element]:
482
- """Collect all <defs> children into an {id: element} dictionary."""
483
- defs: dict[str, ET.Element] = {}
484
- for defs_elem in root.iter(f'{{{SVG_NS}}}defs'):
485
- for child in defs_elem:
486
- elem_id = child.get('id')
487
- if elem_id:
488
- defs[elem_id] = child
489
- # Also check for defs without namespace
490
- for defs_elem in root.iter('defs'):
491
- for child in defs_elem:
492
- elem_id = child.get('id')
493
- if elem_id:
494
- defs[elem_id] = child
495
- return defs
496
-
497
-
498
- def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
499
- """Dispatch an SVG element to the appropriate converter."""
500
- tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
501
- elem_id = elem.get('id')
502
-
503
- def trace(decision: str, **metadata: Any) -> None:
504
- if ctx.trace_events is None:
505
- return
506
- event: dict[str, Any] = {
507
- 'tag': tag,
508
- 'decision': decision,
509
- }
510
- if elem_id:
511
- event['id'] = elem_id
512
- event.update(metadata)
513
- ctx.trace_events.append(event)
514
-
515
- converter = _CONVERTERS.get(tag)
516
- if converter:
517
- try:
518
- result = converter(elem, ctx)
519
- except Exception as e:
520
- trace('error', error=str(e))
521
- raise SvgNativeConversionError(f'Failed to convert <{tag}>: {e}') from e
522
- if result:
523
- shape_match = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
524
- metadata: dict[str, Any] = {}
525
- if shape_match:
526
- metadata['shape_id'] = int(shape_match.group(1))
527
- if result.bounds_emu is not None:
528
- metadata['bounds_emu'] = list(result.bounds_emu)
529
- trace('native', **metadata)
530
- else:
531
- trace('skip', reason='empty-or-non-rendering')
532
- return result
533
-
534
- if tag in _NON_VISUAL_TAGS:
535
- trace('skip', reason='non-visual')
536
- return None
537
-
538
- trace('unsupported')
539
- raise SvgNativeConversionError(f'Unsupported visual SVG element <{tag}>')
540
-
541
-
542
- def _local_tag(elem: ET.Element) -> str:
543
- return elem.tag.split('}', 1)[-1] if isinstance(elem.tag, str) and '}' in elem.tag else str(elem.tag)
544
-
545
-
546
- def _collect_unsupported_visuals(root: ET.Element) -> list[str]:
547
- issues: list[str] = []
548
-
549
- def walk(elem: ET.Element, path: str, in_defs: bool = False) -> None:
550
- tag = _local_tag(elem)
551
- current = f'{path}/{tag}'
552
- if in_defs:
553
- return
554
- if tag in _NON_VISUAL_TAGS:
555
- return
556
- if (tag not in _CONVERTERS
557
- and tag not in _NON_VISUAL_TAGS
558
- and tag not in _SUPPORTED_VISUAL_CHILD_TAGS):
559
- issues.append(current)
560
- for idx, child in enumerate(list(elem), start=1):
561
- walk(child, f'{current}[{idx}]', in_defs=(tag == 'defs'))
562
-
563
- for idx, child in enumerate(list(root), start=1):
564
- walk(child, f'/svg[{idx}]')
565
- return issues
566
-
567
-
568
- def convert_svg_to_slide_shapes(
569
- svg_path: Path,
570
- slide_num: int = 1,
571
- verbose: bool = False,
572
- merge_paragraphs: bool = True,
573
- image_optimize: bool = True,
574
- image_max_dimension: int | None = 2560,
575
- image_sizing: str = 'cap',
576
- image_scale: float = 2.0,
577
- image_quality: int = 85,
578
- native_objects: bool = False,
579
- trace_out: list[dict[str, Any]] | None = None,
580
- ) -> tuple[
581
- str,
582
- dict[str, bytes],
583
- list[dict[str, str]],
584
- list,
585
- dict[str, bytes],
586
- dict[str, str],
587
- ]:
588
- """Convert an SVG file to a complete DrawingML slide XML.
589
-
590
- Args:
591
- svg_path: Path to the SVG file.
592
- slide_num: Slide number (for naming).
593
- verbose: Print progress info.
594
- merge_paragraphs: When True, mergeable paragraph blocks (same x,
595
- dy clustered around one base line-height) become a single
596
- editable text frame with multiple <a:p>. Disable it to preserve
597
- the SVG's exact line layout (one textbox per line).
598
- image_optimize: Downsample oversized raster images for PPTX export.
599
- image_max_dimension: Maximum optimized image dimension in pixels.
600
- image_sizing: `cap` to only cap source dimensions, `display` to
601
- size from rendered SVG boxes.
602
- image_scale: Target image pixels per SVG display pixel.
603
- image_quality: JPEG quality used for opaque optimized rasters.
604
- native_objects: Convert explicit `data-pptx-native` table/chart
605
- markers to native PowerPoint objects. Default off.
606
- trace_out: Optional list populated with one per-slide trace dictionary.
607
-
608
- Returns:
609
- (slide_xml, media_files, rel_entries, anim_targets,
610
- package_files, content_type_overrides) where:
611
- - slide_xml: Complete slide XML string.
612
- - media_files: Dict of {filename: bytes} for media to write.
613
- - rel_entries: List of relationship entries to add.
614
- - anim_targets: List of (shape_id, svg_id) tuples for top-level
615
- semantic groups, in z-order; consumed by the builder's optional
616
- per-element entrance timing emitter.
617
- - package_files: Dict of {pptx internal path: bytes} for non-media
618
- OOXML parts such as native chart XML and embedded workbooks.
619
- - content_type_overrides: Dict of {pptx internal path: content type}
620
- for package_files that require [Content_Types].xml overrides.
621
- """
622
- tree = ET.parse(str(svg_path))
623
- root = tree.getroot()
624
- viewport_width, viewport_height = _root_viewport_size(root)
625
- trace_events: list[dict[str, Any]] | None = [] if trace_out is not None else None
626
- trace_steps: list[dict[str, Any]] = []
627
-
628
- # Expand <use data-icon="..."/> placeholders in-memory so this dispatcher
629
- # can consume svg_output/ directly. Standard renderers and this converter
630
- # both ignore data-icon, so without expansion icons would silently drop.
631
- # The on-disk finalize_svg pipeline does the same expansion for svg_final/;
632
- # running this here makes the two pipelines behaviourally aligned.
633
- icons_dir, icons_fallback_dir = icon_search_dirs_for_svg(svg_path)
634
- if icons_dir.exists():
635
- from ..use_expander import expand_use_data_icons
636
- expanded = expand_use_data_icons(root, icons_dir, icons_fallback_dir)
637
- if expanded:
638
- trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})
639
- if verbose and expanded:
640
- print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')
641
-
642
- # Flatten positional <tspan> (those with x/y/non-zero dy) into independent
643
- # <text> elements. DrawingML runs cannot reposition mid-paragraph, so a
644
- # dy-stacked block of tspans would otherwise collapse onto one baseline,
645
- # and an x-anchored tspan would render in the wrong column. finalize_svg
646
- # does the same flattening on disk; doing it here keeps native pptx output
647
- # correct when reading raw svg_output/.
648
- # merge_paragraphs additionally folds mergeable paragraph blocks into a
649
- # single annotated <text> for downstream multi-<a:p> conversion.
650
- from ..tspan_flattener import flatten_positional_tspans
651
- flattened = flatten_positional_tspans(tree, merge_paragraphs=merge_paragraphs)
652
- if flattened:
653
- trace_steps.append({
654
- 'action': 'flatten-positional-tspans',
655
- 'merge_paragraphs': merge_paragraphs,
656
- })
657
- if verbose:
658
- print(' Flattened positional <tspan> into independent <text>')
659
-
660
- unsupported = _collect_unsupported_visuals(root)
661
- if unsupported:
662
- preview = '; '.join(unsupported[:8])
663
- suffix = '' if len(unsupported) <= 8 else f'; +{len(unsupported) - 8} more'
664
- raise SvgNativeConversionError(
665
- f'{svg_path.name}: unsupported visual SVG element(s): {preview}{suffix}'
666
- )
667
-
668
- defs = collect_defs(root)
669
- ctx = ConvertContext(
670
- defs=defs,
671
- slide_num=slide_num,
672
- viewport_width=viewport_width,
673
- viewport_height=viewport_height,
674
- svg_dir=Path(svg_path).parent,
675
- merge_paragraphs=merge_paragraphs,
676
- image_optimize=image_optimize,
677
- image_max_dimension=image_max_dimension,
678
- image_sizing=image_sizing,
679
- image_scale=image_scale,
680
- image_quality=image_quality,
681
- native_objects_enabled=native_objects,
682
- trace_events=trace_events,
683
- )
684
-
685
- shapes: list[str] = []
686
- converted = 0
687
- skipped = 0
688
- background_xml, background_skip_id = _extract_background_candidate(root, ctx)
689
- promoted_backgrounds = 1 if background_xml else 0
690
- if background_xml and trace_events is not None:
691
- trace_events.append({
692
- 'tag': 'rect',
693
- 'decision': 'native-background',
694
- 'reason': 'promoted-full-canvas-rect-to-bgPr',
695
- })
696
- # Per-element shape ids of every top-level child, used as an animation
697
- # fallback when no <g id="..."> groups are present at the root.
698
- fallback_targets: list = []
699
-
700
- for child in root:
701
- tag = child.tag.replace(f'{{{SVG_NS}}}', '')
702
- if tag == 'defs':
703
- continue
704
- if id(child) == background_skip_id:
705
- continue
706
- result = convert_element(child, ctx)
707
- if result:
708
- shapes.append(result.xml)
709
- converted += 1
710
- m = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
711
- if m:
712
- fallback_targets.append((int(m.group(1)), tag))
713
- else:
714
- if tag not in _NON_VISUAL_TAGS:
715
- skipped += 1
716
-
717
- # Animation target fallback. Semantic <g id="..."> groups are the
718
- # preferred anchors (set inside convert_g). When the SVG has none
719
- # at the root we fall back to top-level primitives, but only when
720
- # the count is reasonable. Presenter-click animation should reveal
721
- # semantic blocks, not atomized drawing primitives, so fallback is
722
- # intentionally capped at a low count.
723
- _ANIM_FALLBACK_CAP = 8
724
- if not ctx.anim_targets and 0 < len(fallback_targets) <= _ANIM_FALLBACK_CAP:
725
- ctx.anim_targets = fallback_targets
726
-
727
- if verbose:
728
- promoted = (
729
- f', promoted {promoted_backgrounds} background'
730
- if promoted_backgrounds else ''
731
- )
732
- print(f' Converted {converted} elements, skipped {skipped}{promoted}')
733
-
734
- if trace_out is not None:
735
- trace_out.append({
736
- 'slide_num': slide_num,
737
- 'svg': str(svg_path),
738
- 'summary': {
739
- 'converted': converted,
740
- 'skipped': skipped,
741
- 'promoted_backgrounds': promoted_backgrounds,
742
- 'media_files': len(ctx.media_files),
743
- 'package_files': len(ctx.package_files),
744
- 'relationships': len(ctx.rel_entries),
745
- 'animation_targets': len(ctx.anim_targets),
746
- },
747
- 'preprocess': trace_steps,
748
- 'events': trace_events or [],
749
- })
750
-
751
- shapes_xml = '\n'.join(shapes)
752
-
753
- slide_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
754
- <p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
755
- xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
756
- xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
757
- <p:cSld>
758
- {background_xml}
759
- <p:spTree>
760
- <p:nvGrpSpPr>
761
- <p:cNvPr id="1" name=""/>
762
- <p:cNvGrpSpPr/><p:nvPr/>
763
- </p:nvGrpSpPr>
764
- <p:grpSpPr>
765
- <a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>
766
- <a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm>
767
- </p:grpSpPr>
768
- {shapes_xml}
769
- </p:spTree>
770
- </p:cSld>
771
- <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>
772
- </p:sld>'''
773
-
774
- return (
775
- slide_xml,
776
- ctx.media_files,
777
- ctx.rel_entries,
778
- ctx.anim_targets,
779
- ctx.package_files,
780
- ctx.content_type_overrides,
781
- )
1
+ """Core SVG -> DrawingML dispatcher, group handling, and main entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+ from xml.etree import ElementTree as ET
10
+
11
+ from ...resource_paths import icon_search_dirs_for_svg
12
+
13
+ from .context import ConvertContext, ShapeResult
14
+ from .utils import (
15
+ SVG_NS, EMU_PER_PX,
16
+ _extract_inheritable_styles, _f, _get_attr, parse_transform_matrix, resolve_url_id,
17
+ parse_svg_length,
18
+ )
19
+ from .styles import (
20
+ build_effect_xml, build_fill_xml, get_fill_opacity, get_stroke_opacity,
21
+ )
22
+ from .elements import (
23
+ convert_rect, convert_circle, convert_ellipse,
24
+ convert_line, convert_path,
25
+ convert_polygon, convert_polyline,
26
+ convert_text, convert_image, convert_nested_svg,
27
+ )
28
+ try:
29
+ from ..native_objects import convert_native_object
30
+ except ImportError:
31
+ convert_native_object = None
32
+
33
+
34
+ class SvgNativeConversionError(RuntimeError):
35
+ """Raised when an SVG cannot be faithfully converted to native DrawingML."""
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Animation anchor selection
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # Tokens that mark a top-level <g id="..."> as page chrome rather than animated
43
+ # content. When any token (after splitting id on '-' and '_') matches, the group
44
+ # is excluded from the per-element entrance animation cascade so background,
45
+ # header/footer, decorations etc. appear together with the slide instead of
46
+ # requiring presenter clicks.
47
+ _CHROME_ID_TOKENS = frozenset({
48
+ 'background', 'bg',
49
+ 'decoration', 'decorations', 'decor',
50
+ 'header', 'footer',
51
+ 'chrome', 'watermark',
52
+ 'pagenumber', 'pagenum',
53
+ 'nav', 'logo', 'rule',
54
+ })
55
+
56
+
57
+ def _is_chrome_id(elem_id: str | None) -> bool:
58
+ if not elem_id:
59
+ return False
60
+ lower = elem_id.lower()
61
+ if lower.replace('-', '').replace('_', '') in _CHROME_ID_TOKENS:
62
+ return True
63
+ tokens = re.split(r'[-_]', lower)
64
+ return any(t in _CHROME_ID_TOKENS for t in tokens if t)
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Transform & layout helpers
69
+ # ---------------------------------------------------------------------------
70
+
71
+ def parse_transform(transform_str: str) -> tuple[float, float, float, float, float]:
72
+ """Parse an SVG transform list into (dx, dy, sx, sy, angle_deg).
73
+
74
+ Composes every translate/scale/rotate/matrix operation rather than picking
75
+ the first occurrence — needed for idioms like
76
+ translate(cx cy) scale(-1 -1) translate(-cx -cy) which encode a flip
77
+ around a non-origin pivot.
78
+
79
+ When the composed matrix has no shear and no rotation, the decomposition is
80
+ exact (sx/sy may be negative to represent flips). When rotation is present
81
+ without shear, sx/sy default to the column magnitudes and angle_deg is the
82
+ rotation. Shear is not representable in this 5-tuple and silently
83
+ collapses; callers that need exact fidelity should consume the full matrix
84
+ via `parse_transform_matrix`.
85
+ """
86
+ if not transform_str:
87
+ return 0.0, 0.0, 1.0, 1.0, 0.0
88
+
89
+ a, b, c, d, e, f = parse_transform_matrix(transform_str)
90
+
91
+ # No shear / rotation: direct decomposition preserves the original signs of
92
+ # sx / sy. ctx_x / ctx_y use the simple val * sx + tx formula, so this
93
+ # is the only form that survives flip-around-pivot composites without
94
+ # collapsing them into a rotation that the consumer can't honour.
95
+ if abs(b) < 1e-9 and abs(c) < 1e-9:
96
+ sx = a if a != 0 else 1.0
97
+ sy = d if d != 0 else 1.0
98
+ return e, f, sx, sy, 0.0
99
+
100
+ sx = math.hypot(a, b)
101
+ sy = math.hypot(c, d)
102
+ if sx == 0:
103
+ sx = 1.0
104
+ if sy == 0:
105
+ sy = 1.0
106
+
107
+ angle_deg = math.degrees(math.atan2(b, a))
108
+ return e, f, sx, sy, angle_deg
109
+
110
+
111
+ # `rotate(angle)` defaults to pivot (0,0); rotate(angle, cx, cy) rotates
112
+ # around (cx, cy). DrawingML grpSp `rot` always rotates around the group's
113
+ # own bounding-box centre — we need the SVG pivot so `convert_g` can
114
+ # compensate for the offset between those two centres.
115
+ _ROTATE_RE = re.compile(
116
+ r'rotate\(\s*([-\d.eE+]+)(?:[\s,]+([-\d.eE+]+)[\s,]+([-\d.eE+]+))?\s*\)'
117
+ )
118
+
119
+
120
+ def _root_viewport_size(root: ET.Element) -> tuple[float, float]:
121
+ """Return the SVG root viewport size in user units."""
122
+ view_box = root.get('viewBox')
123
+ if view_box:
124
+ raw_parts = re.split(r'[\s,]+', view_box.strip())
125
+ if len(raw_parts) == 4:
126
+ try:
127
+ parts = [float(n) for n in raw_parts]
128
+ except ValueError:
129
+ parts = []
130
+ if parts and parts[2] > 0 and parts[3] > 0:
131
+ return parts[2], parts[3]
132
+
133
+ width = parse_svg_length(root.get('width'), 1280.0)
134
+ height = parse_svg_length(root.get('height'), 720.0)
135
+ return max(width, 1.0), max(height, 1.0)
136
+
137
+
138
+ def _extract_rotate_pivot(transform_str: str) -> tuple[float, float] | None:
139
+ """Return the (cx, cy) pivot of a sole `rotate(...)` in *transform_str*.
140
+
141
+ Returns `None` when the transform list contains anything other than one
142
+ rotate (other ops compose with rotate in a way the pivot-compensation
143
+ fallback can't express). A bare `rotate(angle)` returns (0, 0).
144
+ """
145
+ if not transform_str:
146
+ return None
147
+ ops = [op for op in re.findall(r'(\w+)\s*\(', transform_str) if op]
148
+ if ops != ['rotate']:
149
+ return None
150
+ match = _ROTATE_RE.search(transform_str)
151
+ if not match:
152
+ return None
153
+ cx = float(match.group(2)) if match.group(2) is not None else 0.0
154
+ cy = float(match.group(3)) if match.group(3) is not None else 0.0
155
+ return cx, cy
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Group handling
160
+ # ---------------------------------------------------------------------------
161
+
162
+ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
163
+ """Convert SVG <g> to DrawingML group shape <p:grpSp>.
164
+
165
+ Preserves group structure so elements can be selected and moved together
166
+ in PowerPoint. Single-child groups are flattened to avoid unnecessary nesting.
167
+
168
+ Uses identity coordinate mapping (chOff/chExt == off/ext) so child shapes
169
+ keep their absolute slide coordinates unchanged.
170
+ """
171
+ transform = elem.get('transform', '')
172
+ dx, dy, sx, sy, angle_deg = parse_transform(transform)
173
+
174
+ filter_id = resolve_url_id(elem.get('filter', ''))
175
+ style_overrides = _extract_inheritable_styles(elem)
176
+
177
+ elem_id = elem.get('id')
178
+ should_animate_group = ctx.depth == 0 and elem_id and not _is_chrome_id(elem_id)
179
+ visual_children = [
180
+ child for child in elem
181
+ if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
182
+ ]
183
+ matrix_supported = bool(transform) and visual_children and all(
184
+ _supports_matrix_transform(child) for child in visual_children
185
+ )
186
+ # A pure rotate(angle [cx cy]) falls through to the fallback path
187
+ # below (children are rect/text/path/etc. that don't consume a full
188
+ # matrix). Decomposing the matrix produces translation components
189
+ # (e, f) that encode the pivot — handing those to children would
190
+ # *double-translate* them because grpSp's own `rot` already
191
+ # rotates around the group's bounding-box centre. Skip the child
192
+ # translation here and apply pivot-centre compensation to `a:off`
193
+ # below instead.
194
+ rotate_pivot = _extract_rotate_pivot(transform) if not matrix_supported else None
195
+ if matrix_supported:
196
+ child_ctx = ctx.child(
197
+ 0, 0, 1.0, 1.0,
198
+ transform_matrix=parse_transform_matrix(transform),
199
+ filter_id=filter_id,
200
+ style_overrides=style_overrides,
201
+ )
202
+ elif rotate_pivot is not None:
203
+ child_ctx = ctx.child(
204
+ 0, 0, 1.0, 1.0,
205
+ filter_id=filter_id,
206
+ style_overrides=style_overrides,
207
+ )
208
+ else:
209
+ child_ctx = ctx.child(dx, dy, sx, sy, filter_id=filter_id, style_overrides=style_overrides)
210
+
211
+ if child_ctx.native_objects_enabled and convert_native_object:
212
+ native_result = convert_native_object(elem, child_ctx)
213
+ if native_result:
214
+ ctx.sync_from_child(child_ctx)
215
+ if should_animate_group:
216
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', native_result.xml)
217
+ if shape_match:
218
+ ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
219
+ return native_result
220
+
221
+ child_results: list[ShapeResult] = []
222
+ for child in elem:
223
+ result = convert_element(child, child_ctx)
224
+ if result:
225
+ child_results.append(result)
226
+
227
+ ctx.sync_from_child(child_ctx)
228
+
229
+ if not child_results:
230
+ return None
231
+
232
+ # Single-child non-semantic groups are flattened to reduce nesting. Top-level
233
+ # semantic groups are preserved so animations target the group, not its
234
+ # individual child shapes.
235
+ if len(child_results) == 1 and not should_animate_group:
236
+ return child_results[0]
237
+
238
+ # Multiple children, or a top-level semantic one-child group: wrap in
239
+ # <p:grpSp> so PowerPoint can animate the group as one unit.
240
+ min_x = min_y = float('inf')
241
+ max_x = max_y = float('-inf')
242
+
243
+ for child_result in child_results:
244
+ bounds = child_result.bounds_emu
245
+ if bounds is None:
246
+ continue
247
+ min_x = min(min_x, bounds[0])
248
+ min_y = min(min_y, bounds[1])
249
+ max_x = max(max_x, bounds[2])
250
+ max_y = max(max_y, bounds[3])
251
+
252
+ if min_x == float('inf'):
253
+ return ShapeResult(xml='\n'.join(result.xml for result in child_results))
254
+
255
+ group_x = int(min_x)
256
+ group_y = int(min_y)
257
+ group_w = max(int(max_x - min_x), 1)
258
+ group_h = max(int(max_y - min_y), 1)
259
+
260
+ # rotate(angle, cx, cy) rotates around the SVG pivot, but DrawingML
261
+ # grpSp `rot` always rotates around the group's own bbox centre. When
262
+ # those centres differ, the visual position drifts by exactly the
263
+ # translation a rotate-around-pivot equals. Compensate by offsetting the
264
+ # outer <a:off> only; <a:chOff> stays on the unshifted bbox so children
265
+ # (still at their original SVG positions because rotate_pivot suppressed
266
+ # the dx/dy translation above) remain aligned inside the group.
267
+ off_x = group_x
268
+ off_y = group_y
269
+ if rotate_pivot is not None and angle_deg:
270
+ cx_svg, cy_svg = rotate_pivot
271
+ pivot_ex = (cx_svg + ctx.translate_x) * EMU_PER_PX
272
+ pivot_ey = (cy_svg + ctx.translate_y) * EMU_PER_PX
273
+ bbox_cx = group_x + group_w / 2
274
+ bbox_cy = group_y + group_h / 2
275
+ theta = math.radians(angle_deg)
276
+ cos_t = math.cos(theta)
277
+ sin_t = math.sin(theta)
278
+ # Where the bbox centre lands after rotating around the pivot, minus
279
+ # where DrawingML's grpSp rot would leave it (i.e. unchanged).
280
+ delta_x = (bbox_cx - pivot_ex) * cos_t - (bbox_cy - pivot_ey) * sin_t + pivot_ex - bbox_cx
281
+ delta_y = (bbox_cx - pivot_ex) * sin_t + (bbox_cy - pivot_ey) * cos_t + pivot_ey - bbox_cy
282
+ off_x = int(round(group_x + delta_x))
283
+ off_y = int(round(group_y + delta_y))
284
+
285
+ shapes_xml = '\n'.join(result.xml for result in child_results)
286
+ group_id = ctx.next_id()
287
+
288
+ # Record top-level semantic groups (e.g. <g id="p02-title">) so the
289
+ # PPTX builder can emit per-element entrance timing. Only the outermost
290
+ # multi-child wrapper qualifies — flattened single-child groups have no
291
+ # <p:grpSp> to anchor a timing target on, and nested groups are
292
+ # ignored to keep the animation budget at ~per-section granularity.
293
+ if should_animate_group:
294
+ ctx.anim_targets.append((group_id, elem_id))
295
+
296
+ group_effect = ''
297
+ if filter_id and filter_id in ctx.defs:
298
+ group_effect = build_effect_xml(ctx.defs[filter_id])
299
+
300
+ rot_emu = 0 if matrix_supported else int(angle_deg * 60000)
301
+ rot_attr = f' rot="{rot_emu}"' if rot_emu else ''
302
+
303
+ return ShapeResult(xml=f'''<p:grpSp>
304
+ <p:nvGrpSpPr>
305
+ <p:cNvPr id="{group_id}" name="Group {group_id}"/>
306
+ <p:cNvGrpSpPr/>
307
+ <p:nvPr/>
308
+ </p:nvGrpSpPr>
309
+ <p:grpSpPr>
310
+ <a:xfrm{rot_attr}>
311
+ <a:off x="{off_x}" y="{off_y}"/>
312
+ <a:ext cx="{group_w}" cy="{group_h}"/>
313
+ <a:chOff x="{group_x}" y="{group_y}"/>
314
+ <a:chExt cx="{group_w}" cy="{group_h}"/>
315
+ </a:xfrm>
316
+ {group_effect}
317
+ </p:grpSpPr>
318
+ {shapes_xml}
319
+ </p:grpSp>''', bounds_emu=(group_x, group_y, group_x + group_w, group_y + group_h))
320
+
321
+
322
+ # ---------------------------------------------------------------------------
323
+ # Defs collection & element dispatch
324
+ # ---------------------------------------------------------------------------
325
+
326
+ _NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))
327
+
328
+
329
+ def _supports_matrix_transform(elem: ET.Element) -> bool:
330
+ """Return whether this subtree can consume a full affine matrix directly."""
331
+ tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
332
+ if tag in {'rect', 'circle', 'ellipse', 'line', 'path', 'polygon', 'polyline', 'image'}:
333
+ return True
334
+ if tag == 'svg':
335
+ visual_children = [
336
+ child for child in elem
337
+ if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
338
+ ]
339
+ return len(visual_children) == 1 and (
340
+ visual_children[0].tag.replace(f'{{{SVG_NS}}}', '') == 'image'
341
+ )
342
+ if tag == 'g':
343
+ visual_children = [
344
+ child for child in elem
345
+ if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
346
+ ]
347
+ return bool(visual_children) and all(
348
+ _supports_matrix_transform(child) for child in visual_children
349
+ )
350
+ return False
351
+
352
+ _CONVERTERS = {
353
+ 'rect': convert_rect,
354
+ 'circle': convert_circle,
355
+ 'ellipse': convert_ellipse,
356
+ 'line': convert_line,
357
+ 'path': convert_path,
358
+ 'polygon': convert_polygon,
359
+ 'polyline': convert_polyline,
360
+ 'text': convert_text,
361
+ 'image': convert_image,
362
+ 'g': convert_g,
363
+ 'svg': convert_nested_svg,
364
+ }
365
+
366
+ _SUPPORTED_VISUAL_CHILD_TAGS = frozenset(('tspan',))
367
+
368
+
369
+ def _parse_svg_canvas(root: ET.Element) -> tuple[float, float, float, float]:
370
+ """Return the SVG canvas as (x, y, width, height) in SVG units."""
371
+ view_box = root.get('viewBox', '')
372
+ parts = re.split(r'[\s,]+', view_box.strip()) if view_box else []
373
+ if len(parts) == 4:
374
+ try:
375
+ x, y, w, h = (float(part) for part in parts)
376
+ if w > 0 and h > 0:
377
+ return x, y, w, h
378
+ except ValueError:
379
+ pass
380
+ return 0.0, 0.0, _f(root.get('width')), _f(root.get('height'))
381
+
382
+
383
+ def _is_full_canvas_rect(
384
+ elem: ET.Element,
385
+ ctx: ConvertContext,
386
+ canvas: tuple[float, float, float, float],
387
+ ) -> bool:
388
+ """Return whether a rect is a safe candidate for native slide background."""
389
+ if elem.get('transform') or elem.get('filter') or elem.get('clip-path'):
390
+ return False
391
+ if _f(elem.get('rx')) > 0 or _f(elem.get('ry')) > 0:
392
+ return False
393
+
394
+ canvas_x, canvas_y, canvas_w, canvas_h = canvas
395
+ if canvas_w <= 0 or canvas_h <= 0:
396
+ return False
397
+
398
+ tolerance = 0.5
399
+ if abs(_f(elem.get('x')) - canvas_x) > tolerance:
400
+ return False
401
+ if abs(_f(elem.get('y')) - canvas_y) > tolerance:
402
+ return False
403
+ if abs(_f(elem.get('width')) - canvas_w) > tolerance:
404
+ return False
405
+ if abs(_f(elem.get('height')) - canvas_h) > tolerance:
406
+ return False
407
+
408
+ fill = _get_attr(elem, 'fill', ctx)
409
+ if fill == 'none':
410
+ return False
411
+
412
+ stroke = _get_attr(elem, 'stroke', ctx)
413
+ stroke_width = _f(_get_attr(elem, 'stroke-width', ctx), 1.0)
414
+ stroke_opacity = get_stroke_opacity(elem, ctx)
415
+ if stroke and stroke != 'none' and stroke_width > 0 and stroke_opacity != 0:
416
+ return False
417
+
418
+ return True
419
+
420
+
421
+ def _background_xml_from_rect(
422
+ elem: ET.Element,
423
+ ctx: ConvertContext,
424
+ ) -> str:
425
+ """Build native `p:bg` XML from a full-slide SVG background rect."""
426
+ fill_xml = build_fill_xml(elem, ctx, get_fill_opacity(elem, ctx))
427
+ if not fill_xml or '<a:noFill' in fill_xml:
428
+ return ''
429
+ return f'<p:bg><p:bgPr>{fill_xml}<a:effectLst/></p:bgPr></p:bg>'
430
+
431
+
432
+ def _extract_background_candidate(
433
+ root: ET.Element,
434
+ ctx: ConvertContext,
435
+ ) -> tuple[str, int | None]:
436
+ """Promote a first-layer SVG background rect to native PowerPoint bgPr.
437
+
438
+ PowerPoint stores page background fills under `p:cSld/p:bg/p:bgPr`.
439
+ Keeping the full-canvas SVG rect in `p:spTree` makes it an ordinary
440
+ selectable shape, so users hit it during bulk element selection. Only the
441
+ first visual layer is considered, matching pptx_to_svg's round-trip output
442
+ and avoiding accidental promotion of content panels.
443
+ """
444
+ canvas = _parse_svg_canvas(root)
445
+ for child in root:
446
+ tag = child.tag.replace(f'{{{SVG_NS}}}', '')
447
+ if tag in _NON_VISUAL_TAGS:
448
+ continue
449
+
450
+ if tag == 'rect' and _is_full_canvas_rect(child, ctx, canvas):
451
+ bg_xml = _background_xml_from_rect(child, ctx)
452
+ if bg_xml:
453
+ return bg_xml, id(child)
454
+ return '', None
455
+
456
+ if tag != 'g':
457
+ return '', None
458
+ if child.get('transform') or child.get('filter') or child.get('clip-path'):
459
+ return '', None
460
+ style_overrides = _extract_inheritable_styles(child)
461
+ child_ctx = ctx.child(style_overrides=style_overrides)
462
+ visual_children = [
463
+ grandchild for grandchild in child
464
+ if grandchild.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
465
+ ]
466
+ if len(visual_children) != 1:
467
+ return '', None
468
+ only_child = visual_children[0]
469
+ only_tag = only_child.tag.replace(f'{{{SVG_NS}}}', '')
470
+ if only_tag == 'rect' and _is_full_canvas_rect(only_child, child_ctx, canvas):
471
+ bg_xml = _background_xml_from_rect(only_child, child_ctx)
472
+ if bg_xml:
473
+ ctx.sync_from_child(child_ctx)
474
+ return bg_xml, id(child)
475
+ return '', None
476
+ return '', None
477
+
478
+ return '', None
479
+
480
+
481
+ def collect_defs(root: ET.Element) -> dict[str, ET.Element]:
482
+ """Collect all <defs> children into an {id: element} dictionary."""
483
+ defs: dict[str, ET.Element] = {}
484
+ for defs_elem in root.iter(f'{{{SVG_NS}}}defs'):
485
+ for child in defs_elem:
486
+ elem_id = child.get('id')
487
+ if elem_id:
488
+ defs[elem_id] = child
489
+ # Also check for defs without namespace
490
+ for defs_elem in root.iter('defs'):
491
+ for child in defs_elem:
492
+ elem_id = child.get('id')
493
+ if elem_id:
494
+ defs[elem_id] = child
495
+ return defs
496
+
497
+
498
+ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
499
+ """Dispatch an SVG element to the appropriate converter."""
500
+ tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
501
+ elem_id = elem.get('id')
502
+
503
+ def trace(decision: str, **metadata: Any) -> None:
504
+ if ctx.trace_events is None:
505
+ return
506
+ event: dict[str, Any] = {
507
+ 'tag': tag,
508
+ 'decision': decision,
509
+ }
510
+ if elem_id:
511
+ event['id'] = elem_id
512
+ event.update(metadata)
513
+ ctx.trace_events.append(event)
514
+
515
+ converter = _CONVERTERS.get(tag)
516
+ if converter:
517
+ try:
518
+ result = converter(elem, ctx)
519
+ except Exception as e:
520
+ trace('error', error=str(e))
521
+ raise SvgNativeConversionError(f'Failed to convert <{tag}>: {e}') from e
522
+ if result:
523
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
524
+ metadata: dict[str, Any] = {}
525
+ if shape_match:
526
+ metadata['shape_id'] = int(shape_match.group(1))
527
+ if result.bounds_emu is not None:
528
+ metadata['bounds_emu'] = list(result.bounds_emu)
529
+ trace('native', **metadata)
530
+ else:
531
+ trace('skip', reason='empty-or-non-rendering')
532
+ return result
533
+
534
+ if tag in _NON_VISUAL_TAGS:
535
+ trace('skip', reason='non-visual')
536
+ return None
537
+
538
+ trace('unsupported')
539
+ raise SvgNativeConversionError(f'Unsupported visual SVG element <{tag}>')
540
+
541
+
542
+ def _local_tag(elem: ET.Element) -> str:
543
+ return elem.tag.split('}', 1)[-1] if isinstance(elem.tag, str) and '}' in elem.tag else str(elem.tag)
544
+
545
+
546
+ def _collect_unsupported_visuals(root: ET.Element) -> list[str]:
547
+ issues: list[str] = []
548
+
549
+ def walk(elem: ET.Element, path: str, in_defs: bool = False) -> None:
550
+ tag = _local_tag(elem)
551
+ current = f'{path}/{tag}'
552
+ if in_defs:
553
+ return
554
+ if tag in _NON_VISUAL_TAGS:
555
+ return
556
+ if (tag not in _CONVERTERS
557
+ and tag not in _NON_VISUAL_TAGS
558
+ and tag not in _SUPPORTED_VISUAL_CHILD_TAGS):
559
+ issues.append(current)
560
+ for idx, child in enumerate(list(elem), start=1):
561
+ walk(child, f'{current}[{idx}]', in_defs=(tag == 'defs'))
562
+
563
+ for idx, child in enumerate(list(root), start=1):
564
+ walk(child, f'/svg[{idx}]')
565
+ return issues
566
+
567
+
568
+ def convert_svg_to_slide_shapes(
569
+ svg_path: Path,
570
+ slide_num: int = 1,
571
+ verbose: bool = False,
572
+ merge_paragraphs: bool = True,
573
+ image_optimize: bool = True,
574
+ image_max_dimension: int | None = 2560,
575
+ image_sizing: str = 'cap',
576
+ image_scale: float = 2.0,
577
+ image_quality: int = 85,
578
+ native_objects: bool = False,
579
+ trace_out: list[dict[str, Any]] | None = None,
580
+ ) -> tuple[
581
+ str,
582
+ dict[str, bytes],
583
+ list[dict[str, str]],
584
+ list,
585
+ dict[str, bytes],
586
+ dict[str, str],
587
+ ]:
588
+ """Convert an SVG file to a complete DrawingML slide XML.
589
+
590
+ Args:
591
+ svg_path: Path to the SVG file.
592
+ slide_num: Slide number (for naming).
593
+ verbose: Print progress info.
594
+ merge_paragraphs: When True, mergeable paragraph blocks (same x,
595
+ dy clustered around one base line-height) become a single
596
+ editable text frame with multiple <a:p>. Disable it to preserve
597
+ the SVG's exact line layout (one textbox per line).
598
+ image_optimize: Downsample oversized raster images for PPTX export.
599
+ image_max_dimension: Maximum optimized image dimension in pixels.
600
+ image_sizing: `cap` to only cap source dimensions, `display` to
601
+ size from rendered SVG boxes.
602
+ image_scale: Target image pixels per SVG display pixel.
603
+ image_quality: JPEG quality used for opaque optimized rasters.
604
+ native_objects: Convert explicit `data-pptx-native` table/chart
605
+ markers to native PowerPoint objects. Default off.
606
+ trace_out: Optional list populated with one per-slide trace dictionary.
607
+
608
+ Returns:
609
+ (slide_xml, media_files, rel_entries, anim_targets,
610
+ package_files, content_type_overrides) where:
611
+ - slide_xml: Complete slide XML string.
612
+ - media_files: Dict of {filename: bytes} for media to write.
613
+ - rel_entries: List of relationship entries to add.
614
+ - anim_targets: List of (shape_id, svg_id) tuples for top-level
615
+ semantic groups, in z-order; consumed by the builder's optional
616
+ per-element entrance timing emitter.
617
+ - package_files: Dict of {pptx internal path: bytes} for non-media
618
+ OOXML parts such as native chart XML and embedded workbooks.
619
+ - content_type_overrides: Dict of {pptx internal path: content type}
620
+ for package_files that require [Content_Types].xml overrides.
621
+ """
622
+ tree = ET.parse(str(svg_path))
623
+ root = tree.getroot()
624
+ viewport_width, viewport_height = _root_viewport_size(root)
625
+ trace_events: list[dict[str, Any]] | None = [] if trace_out is not None else None
626
+ trace_steps: list[dict[str, Any]] = []
627
+
628
+ # Expand <use data-icon="..."/> placeholders in-memory so this dispatcher
629
+ # can consume svg_output/ directly. Standard renderers and this converter
630
+ # both ignore data-icon, so without expansion icons would silently drop.
631
+ # The on-disk finalize_svg pipeline does the same expansion for svg_final/;
632
+ # running this here makes the two pipelines behaviourally aligned.
633
+ icons_dir, icons_fallback_dir = icon_search_dirs_for_svg(svg_path)
634
+ if icons_dir.exists():
635
+ from ..use_expander import expand_use_data_icons
636
+ expanded = expand_use_data_icons(root, icons_dir, icons_fallback_dir)
637
+ if expanded:
638
+ trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})
639
+ if verbose and expanded:
640
+ print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')
641
+
642
+ # Flatten positional <tspan> (those with x/y/non-zero dy) into independent
643
+ # <text> elements. DrawingML runs cannot reposition mid-paragraph, so a
644
+ # dy-stacked block of tspans would otherwise collapse onto one baseline,
645
+ # and an x-anchored tspan would render in the wrong column. finalize_svg
646
+ # does the same flattening on disk; doing it here keeps native pptx output
647
+ # correct when reading raw svg_output/.
648
+ # merge_paragraphs additionally folds mergeable paragraph blocks into a
649
+ # single annotated <text> for downstream multi-<a:p> conversion.
650
+ from ..tspan_flattener import flatten_positional_tspans
651
+ flattened = flatten_positional_tspans(tree, merge_paragraphs=merge_paragraphs)
652
+ if flattened:
653
+ trace_steps.append({
654
+ 'action': 'flatten-positional-tspans',
655
+ 'merge_paragraphs': merge_paragraphs,
656
+ })
657
+ if verbose:
658
+ print(' Flattened positional <tspan> into independent <text>')
659
+
660
+ unsupported = _collect_unsupported_visuals(root)
661
+ if unsupported:
662
+ preview = '; '.join(unsupported[:8])
663
+ suffix = '' if len(unsupported) <= 8 else f'; +{len(unsupported) - 8} more'
664
+ raise SvgNativeConversionError(
665
+ f'{svg_path.name}: unsupported visual SVG element(s): {preview}{suffix}'
666
+ )
667
+
668
+ defs = collect_defs(root)
669
+ ctx = ConvertContext(
670
+ defs=defs,
671
+ slide_num=slide_num,
672
+ viewport_width=viewport_width,
673
+ viewport_height=viewport_height,
674
+ svg_dir=Path(svg_path).parent,
675
+ merge_paragraphs=merge_paragraphs,
676
+ image_optimize=image_optimize,
677
+ image_max_dimension=image_max_dimension,
678
+ image_sizing=image_sizing,
679
+ image_scale=image_scale,
680
+ image_quality=image_quality,
681
+ native_objects_enabled=native_objects,
682
+ trace_events=trace_events,
683
+ )
684
+
685
+ shapes: list[str] = []
686
+ converted = 0
687
+ skipped = 0
688
+ background_xml, background_skip_id = _extract_background_candidate(root, ctx)
689
+ promoted_backgrounds = 1 if background_xml else 0
690
+ if background_xml and trace_events is not None:
691
+ trace_events.append({
692
+ 'tag': 'rect',
693
+ 'decision': 'native-background',
694
+ 'reason': 'promoted-full-canvas-rect-to-bgPr',
695
+ })
696
+ # Per-element shape ids of every top-level child, used as an animation
697
+ # fallback when no <g id="..."> groups are present at the root.
698
+ fallback_targets: list = []
699
+
700
+ for child in root:
701
+ tag = child.tag.replace(f'{{{SVG_NS}}}', '')
702
+ if tag == 'defs':
703
+ continue
704
+ if id(child) == background_skip_id:
705
+ continue
706
+ result = convert_element(child, ctx)
707
+ if result:
708
+ shapes.append(result.xml)
709
+ converted += 1
710
+ m = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
711
+ if m:
712
+ fallback_targets.append((int(m.group(1)), tag))
713
+ else:
714
+ if tag not in _NON_VISUAL_TAGS:
715
+ skipped += 1
716
+
717
+ # Animation target fallback. Semantic <g id="..."> groups are the
718
+ # preferred anchors (set inside convert_g). When the SVG has none
719
+ # at the root we fall back to top-level primitives, but only when
720
+ # the count is reasonable. Presenter-click animation should reveal
721
+ # semantic blocks, not atomized drawing primitives, so fallback is
722
+ # intentionally capped at a low count.
723
+ _ANIM_FALLBACK_CAP = 8
724
+ if not ctx.anim_targets and 0 < len(fallback_targets) <= _ANIM_FALLBACK_CAP:
725
+ ctx.anim_targets = fallback_targets
726
+
727
+ if verbose:
728
+ promoted = (
729
+ f', promoted {promoted_backgrounds} background'
730
+ if promoted_backgrounds else ''
731
+ )
732
+ print(f' Converted {converted} elements, skipped {skipped}{promoted}')
733
+
734
+ if trace_out is not None:
735
+ trace_out.append({
736
+ 'slide_num': slide_num,
737
+ 'svg': str(svg_path),
738
+ 'summary': {
739
+ 'converted': converted,
740
+ 'skipped': skipped,
741
+ 'promoted_backgrounds': promoted_backgrounds,
742
+ 'media_files': len(ctx.media_files),
743
+ 'package_files': len(ctx.package_files),
744
+ 'relationships': len(ctx.rel_entries),
745
+ 'animation_targets': len(ctx.anim_targets),
746
+ },
747
+ 'preprocess': trace_steps,
748
+ 'events': trace_events or [],
749
+ })
750
+
751
+ shapes_xml = '\n'.join(shapes)
752
+
753
+ slide_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
754
+ <p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
755
+ xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
756
+ xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
757
+ <p:cSld>
758
+ {background_xml}
759
+ <p:spTree>
760
+ <p:nvGrpSpPr>
761
+ <p:cNvPr id="1" name=""/>
762
+ <p:cNvGrpSpPr/><p:nvPr/>
763
+ </p:nvGrpSpPr>
764
+ <p:grpSpPr>
765
+ <a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>
766
+ <a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm>
767
+ </p:grpSpPr>
768
+ {shapes_xml}
769
+ </p:spTree>
770
+ </p:cSld>
771
+ <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>
772
+ </p:sld>'''
773
+
774
+ return (
775
+ slide_xml,
776
+ ctx.media_files,
777
+ ctx.rel_entries,
778
+ ctx.anim_targets,
779
+ ctx.package_files,
780
+ ctx.content_type_overrides,
781
+ )