@hfyjq/crannia 1.0.0 → 1.1.1

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 (222) 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/updater.py +229 -40
  68. package/core/version.py +2 -2
  69. package/core/web_cache.py +152 -0
  70. package/crannia_tray.py +278 -278
  71. package/creators/models.json +4 -4
  72. package/data/settings.example.json +67 -0
  73. package/licenses/GPL-3.0.txt +619 -619
  74. package/licenses/LGPL-2.1.txt +502 -502
  75. package/licenses/LGPL-3.0.txt +165 -165
  76. package/licenses/MIT-chat-on-wechat.txt +18 -18
  77. package/licenses/MIT-deepseek-harness.txt +21 -21
  78. package/licenses/Molio-LICENSE.txt +44 -44
  79. package/locales/en.json +9 -4
  80. package/main.py +154 -154
  81. package/mcpx/manager.py +522 -522
  82. package/mcpx/servers/__init__.py +22 -22
  83. package/mcpx/servers/web_search.py +321 -33
  84. package/package.json +24 -10
  85. package/providers/anthropic/client.py +772 -772
  86. package/providers/cost_table.json +3779 -3779
  87. package/providers/deepseek/client.py +20 -20
  88. package/providers/deepseek/manifest.yaml +2 -2
  89. package/providers/factory.py +136 -136
  90. package/providers/lmstudio/client.py +2 -2
  91. package/providers/metadata.py +80 -80
  92. package/providers/model_capabilities.json +6665 -6665
  93. package/providers/moonshot/client.py +12 -12
  94. package/providers/ollama/client.py +2 -2
  95. package/providers/openai/client.py +13 -13
  96. package/providers/openrouter/client.py +2 -2
  97. package/providers/qwen/__init__.py +1 -1
  98. package/providers/qwen/client.py +2 -2
  99. package/providers/qwen/manifest.yaml +16 -16
  100. package/providers/rate_limiter.py +144 -144
  101. package/providers/siliconflow/client.py +2 -2
  102. package/providers/validation.py +171 -171
  103. package/providers/window_table.json +8909 -8909
  104. package/sbom.json +4413 -4296
  105. package/skills/entertainment/SKILL.md +35 -35
  106. package/skills/entertainment/__init__.py +1 -1
  107. package/skills/entertainment/handler.py +91 -91
  108. package/skills/entertainment/manifest.yaml +26 -26
  109. package/skills/file_parser/GUIDANCE.md +10 -10
  110. package/skills/file_parser/handler.py +177 -4
  111. package/skills/file_parser/manifest.yaml +22 -1
  112. package/skills/github/SKILL.md +32 -32
  113. package/skills/github/__init__.py +1 -1
  114. package/skills/github/manifest.yaml +5 -0
  115. package/skills/mail_parser/SKILL.md +68 -68
  116. package/skills/mail_parser/__init__.py +1 -1
  117. package/skills/mail_parser/handler.py +806 -806
  118. package/skills/mail_parser/manifest.yaml +5 -0
  119. package/skills/media_gen/GUIDANCE.md +19 -19
  120. package/skills/media_gen/SKILL.md +43 -43
  121. package/skills/media_gen/__init__.py +1 -1
  122. package/skills/media_gen/handler.py +430 -430
  123. package/skills/media_gen/manifest.yaml +93 -88
  124. package/skills/office_parser/cell_validation.py +127 -127
  125. package/skills/office_parser/excel_transform.py +936 -936
  126. package/skills/office_parser/layout_spec.py +243 -243
  127. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  128. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  129. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  130. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  131. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  133. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  134. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  135. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  136. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  137. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  143. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  151. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  152. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  153. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  154. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  155. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  156. package/skills/office_parser/references/layout_library.md +816 -816
  157. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  158. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  159. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  160. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  161. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  162. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  181. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  182. package/skills/office_parser/references/spec_lock.md +235 -235
  183. package/skills/office_parser/soffice.py +68 -68
  184. package/skills/office_parser/word_tools.py +2909 -2909
  185. package/tui/crannia.cmd +134 -0
  186. package/tui/crannia_tui/__init__.py +1 -0
  187. package/tui/crannia_tui/__main__.py +223 -0
  188. package/tui/crannia_tui/app.py +1318 -0
  189. package/tui/crannia_tui/app.tcss +153 -0
  190. package/tui/crannia_tui/approval.py +85 -0
  191. package/tui/crannia_tui/backend.py +279 -0
  192. package/tui/crannia_tui/channel.py +472 -0
  193. package/tui/crannia_tui/client.py +125 -0
  194. package/tui/crannia_tui/clipboard.py +62 -0
  195. package/tui/crannia_tui/commands.py +65 -0
  196. package/tui/crannia_tui/doctor.py +304 -0
  197. package/tui/crannia_tui/events.py +84 -0
  198. package/tui/crannia_tui/headless.py +152 -0
  199. package/tui/crannia_tui/i18n.py +164 -0
  200. package/tui/crannia_tui/locales/en.json +263 -0
  201. package/tui/crannia_tui/outcome.py +62 -0
  202. package/tui/crannia_tui/paths.py +181 -0
  203. package/tui/crannia_tui/probe.py +53 -0
  204. package/tui/crannia_tui/profile.py +169 -0
  205. package/tui/crannia_tui/render.py +209 -0
  206. package/tui/crannia_tui/settings.py +134 -0
  207. package/tui/crannia_tui/setup.py +380 -0
  208. package/tui/crannia_tui/term.py +116 -0
  209. package/tui/crannia_tui/ui.py +1236 -0
  210. package/tui/crannia_tui/update.py +389 -0
  211. package/vendor/ripgrep/COPYING.txt +3 -3
  212. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  213. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  214. package/vendor/ripgrep/README.md +51 -51
  215. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  216. package/vendor/ripgrep/package-source.json +19 -19
  217. package/web/__main__.py +15 -0
  218. package/web/server.py +178 -20
  219. package/web/static/img/channel-telegram.svg +1 -1
  220. package/web/static/img/channel-wechat.svg +1 -1
  221. package/web/templates/logs.html +49 -49
  222. package/web/templates/models.html +46 -46
@@ -1,656 +1,656 @@
1
- """Fill, stroke, and shadow XML builders for DrawingML conversion."""
2
-
3
- from __future__ import annotations
4
-
5
- import math
6
- import re
7
- from xml.etree import ElementTree as ET
8
-
9
- from .context import ConvertContext
10
- from .utils import (
11
- SVG_NS, ANGLE_UNIT, DASH_PRESETS,
12
- px_to_emu, _f, _get_attr, parse_svg_length,
13
- parse_hex_color, parse_stop_style, resolve_url_id,
14
- )
15
-
16
-
17
- def build_solid_fill(color: str, opacity: float | None = None) -> str:
18
- """Build <a:solidFill> XML."""
19
- alpha = ''
20
- if opacity is not None and opacity < 1.0:
21
- alpha = f'<a:alpha val="{int(opacity * 100000)}"/>'
22
- return f'<a:solidFill><a:srgbClr val="{color}">{alpha}</a:srgbClr></a:solidFill>'
23
-
24
-
25
- def build_gradient_fill(
26
- grad_elem: ET.Element,
27
- opacity: float | None = None,
28
- ) -> str:
29
- """Build <a:gradFill> from SVG linearGradient or radialGradient element."""
30
- tag = grad_elem.tag.replace(f'{{{SVG_NS}}}', '')
31
-
32
- stops_xml = []
33
- for child in grad_elem:
34
- child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
35
- if child_tag != 'stop':
36
- continue
37
-
38
- offset_str = child.get('offset', '0').strip().rstrip('%')
39
- try:
40
- offset = float(offset_str)
41
- if offset > 1.0:
42
- offset = offset / 100.0
43
- except ValueError:
44
- offset = 0.0
45
- pos = int(offset * 100000)
46
-
47
- # Parse color from style attribute or direct attributes
48
- style = child.get('style', '')
49
- color, stop_opacity = parse_stop_style(style)
50
- if not color:
51
- color = parse_hex_color(child.get('stop-color', '#000000'))
52
- if color is None:
53
- color = '000000'
54
-
55
- direct_stop_op = child.get('stop-opacity')
56
- if direct_stop_op is not None:
57
- try:
58
- stop_opacity = float(direct_stop_op)
59
- except ValueError:
60
- pass
61
-
62
- alpha_xml = ''
63
- effective_opacity = stop_opacity
64
- if opacity is not None:
65
- effective_opacity *= opacity
66
- if effective_opacity < 1.0:
67
- alpha_xml = f'<a:alpha val="{int(effective_opacity * 100000)}"/>'
68
-
69
- stops_xml.append(
70
- f'<a:gs pos="{pos}"><a:srgbClr val="{color}">{alpha_xml}</a:srgbClr></a:gs>'
71
- )
72
-
73
- if not stops_xml:
74
- return ''
75
-
76
- gs_list = '\n'.join(stops_xml)
77
-
78
- if tag == 'linearGradient':
79
- def parse_grad_coord(val_str: str, default: float = 0.0) -> float:
80
- val_str = val_str.strip()
81
- if val_str.endswith('%'):
82
- return float(val_str.rstrip('%')) / 100.0
83
- v = float(val_str)
84
- return v / 100.0 if v > 1.0 else v
85
-
86
- x1 = parse_grad_coord(grad_elem.get('x1', '0'))
87
- y1 = parse_grad_coord(grad_elem.get('y1', '0'))
88
- x2 = parse_grad_coord(grad_elem.get('x2', '1'))
89
- y2 = parse_grad_coord(grad_elem.get('y2', '1'))
90
-
91
- angle_rad = math.atan2(y2 - y1, x2 - x1)
92
- angle_deg = math.degrees(angle_rad)
93
- dml_angle = int((angle_deg % 360) * ANGLE_UNIT)
94
-
95
- return f'''<a:gradFill>
96
- <a:gsLst>{gs_list}</a:gsLst>
97
- <a:lin ang="{dml_angle}" scaled="1"/>
98
- </a:gradFill>'''
99
-
100
- elif tag == 'radialGradient':
101
- return f'''<a:gradFill>
102
- <a:gsLst>{gs_list}</a:gsLst>
103
- <a:path path="circle">
104
- <a:fillToRect l="50000" t="50000" r="50000" b="50000"/>
105
- </a:path>
106
- </a:gradFill>'''
107
-
108
- return ''
109
-
110
-
111
- def build_fill_xml(
112
- elem: ET.Element,
113
- ctx: ConvertContext,
114
- opacity: float | None = None,
115
- ) -> str:
116
- """Build fill XML for a shape element, with inherited style support."""
117
- fill = _get_attr(elem, 'fill', ctx)
118
- if fill is None:
119
- fill = '#000000' # SVG default fill is black
120
-
121
- if fill.strip().lower() in ('none', 'transparent'):
122
- return '<a:noFill/>'
123
-
124
- ref_id = resolve_url_id(fill)
125
- if ref_id and ref_id in ctx.defs:
126
- ref_elem = ctx.defs[ref_id]
127
- ref_tag = ref_elem.tag.replace(f'{{{SVG_NS}}}', '')
128
- if ref_tag == 'pattern':
129
- patt_xml = build_pattern_fill(ref_elem, opacity)
130
- if patt_xml:
131
- return patt_xml
132
- return '<a:noFill/>'
133
- return build_gradient_fill(ref_elem, opacity)
134
-
135
- color = parse_hex_color(fill)
136
- if color:
137
- return build_solid_fill(color, opacity)
138
-
139
- return '<a:noFill/>'
140
-
141
-
142
- def build_pattern_fill(
143
- pattern_elem: ET.Element,
144
- opacity: float | None = None,
145
- ) -> str:
146
- """Build <a:pattFill> from an SVG <pattern> emitted by pptx_to_svg.
147
-
148
- Reads the round-trip annotations (data-pptx-pattern / data-pptx-fg /
149
- data-pptx-bg) when present. Falls back to inspecting the inner stroke /
150
- rect colors when annotations are absent (hand-authored SVG).
151
- """
152
- prst = pattern_elem.get('data-pptx-pattern') or 'ltUpDiag'
153
-
154
- fg_color = pattern_elem.get('data-pptx-fg')
155
- bg_color = pattern_elem.get('data-pptx-bg')
156
-
157
- if not fg_color or not bg_color:
158
- # Hand-authored fallback: derive from child elements.
159
- for child in pattern_elem:
160
- tag = child.tag.replace(f'{{{SVG_NS}}}', '')
161
- if tag == 'rect' and not bg_color:
162
- bg_color = child.get('fill')
163
- elif tag == 'path' and not fg_color:
164
- fg_color = child.get('stroke')
165
-
166
- fg_hex = parse_hex_color(fg_color) if fg_color else None
167
- bg_hex = parse_hex_color(bg_color) if bg_color else None
168
- if not fg_hex:
169
- return ''
170
-
171
- alpha_xml = ''
172
- if opacity is not None and opacity < 1.0:
173
- alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
174
-
175
- fg_xml = f'<a:srgbClr val="{fg_hex}">{alpha_xml}</a:srgbClr>'
176
- if bg_hex:
177
- bg_xml = f'<a:srgbClr val="{bg_hex}"/>'
178
- else:
179
- bg_xml = '<a:srgbClr val="FFFFFF"/>'
180
-
181
- return (
182
- f'<a:pattFill prst="{prst}">'
183
- f'<a:fgClr>{fg_xml}</a:fgClr>'
184
- f'<a:bgClr>{bg_xml}</a:bgClr>'
185
- f'</a:pattFill>'
186
- )
187
-
188
-
189
- # ---------------------------------------------------------------------------
190
- # Marker (arrow-head) support
191
- # ---------------------------------------------------------------------------
192
-
193
- # Matches an (x, y) pair in a path "d" attribute: "M 10, 20" / "L -5 7.5" / etc.
194
- _MARKER_POINT_RE = re.compile(
195
- r'[MLml]\s*(-?\d+(?:\.\d+)?)\s*[,\s]\s*(-?\d+(?:\.\d+)?)'
196
- )
197
- _MARKER_POLY_POINT_RE = re.compile(
198
- r'(-?\d+(?:\.\d+)?)\s*[,\s]\s*(-?\d+(?:\.\d+)?)'
199
- )
200
-
201
-
202
- def _marker_size_buckets(w_attr: float, h_attr: float) -> tuple[str, str]:
203
- """Map SVG markerWidth / markerHeight to DrawingML (w, len) buckets.
204
-
205
- DrawingML arrow-end sizing is categorical: sm / med / lg.
206
- Width (perpendicular to the line) maps from markerHeight;
207
- length (along the line) maps from markerWidth.
208
- """
209
-
210
- def bucket(v: float) -> str:
211
- if v < 6:
212
- return 'sm'
213
- if v > 12:
214
- return 'lg'
215
- return 'med'
216
-
217
- return bucket(h_attr), bucket(w_attr)
218
-
219
-
220
- def _classify_marker(marker_elem: ET.Element) -> tuple[str, str, str] | None:
221
- """Classify an SVG <marker> into a DrawingML line-end preset.
222
-
223
- Returns (type, w, len) where:
224
- type in {'triangle', 'stealth', 'diamond', 'oval', 'arrow'}
225
- w, len in {'sm', 'med', 'lg'}
226
- or None if the marker cannot be classified.
227
-
228
- Current coverage (80/20): triangles (3-vertex closed paths or polygons),
229
- diamonds (4-vertex symmetric), and circles / ellipses. Anything else
230
- returns None so the caller can warn and skip.
231
- """
232
- mw = _f(marker_elem.get('markerWidth'), 3.0)
233
- mh = _f(marker_elem.get('markerHeight'), 3.0)
234
- w_bucket, len_bucket = _marker_size_buckets(mw, mh)
235
-
236
- for child in marker_elem:
237
- tag = child.tag.replace(f'{{{SVG_NS}}}', '')
238
-
239
- if tag in ('circle', 'ellipse'):
240
- return ('oval', w_bucket, len_bucket)
241
-
242
- if tag == 'path':
243
- d = child.get('d', '')
244
- if not d:
245
- continue
246
- points = _MARKER_POINT_RE.findall(d)
247
- n = len(points)
248
- closed = bool(re.search(r'[Zz]\s*$', d.strip()))
249
- if n == 3 and closed:
250
- return ('triangle', w_bucket, len_bucket)
251
- if n == 4 and closed:
252
- return ('diamond', w_bucket, len_bucket)
253
- continue
254
-
255
- if tag in ('polygon', 'polyline'):
256
- pts_attr = child.get('points', '')
257
- pts = _MARKER_POLY_POINT_RE.findall(pts_attr)
258
- n = len(pts)
259
- if n == 3:
260
- return ('triangle', w_bucket, len_bucket)
261
- if n == 4:
262
- return ('diamond', w_bucket, len_bucket)
263
- continue
264
-
265
- return None
266
-
267
-
268
- def _emit_line_end(
269
- elem: ET.Element,
270
- ctx: ConvertContext,
271
- which: str,
272
- ) -> str:
273
- """Build <a:headEnd> or <a:tailEnd> XML for an element's marker reference.
274
-
275
- Args:
276
- which: 'head' (SVG marker-start) or 'tail' (SVG marker-end).
277
-
278
- Returns empty string if no marker, cannot resolve, or cannot classify.
279
- """
280
- attr = 'marker-start' if which == 'head' else 'marker-end'
281
- ref = _get_attr(elem, attr, ctx)
282
- if not ref or ref == 'none':
283
- return ''
284
-
285
- marker_id = resolve_url_id(ref)
286
- if not marker_id or marker_id not in ctx.defs:
287
- return ''
288
-
289
- marker_elem = ctx.defs[marker_id]
290
- tag = marker_elem.tag.replace(f'{{{SVG_NS}}}', '')
291
- if tag != 'marker':
292
- # ID collision with non-marker defs entry; ignore.
293
- return ''
294
-
295
- cls = _classify_marker(marker_elem)
296
- if cls is None:
297
- print(
298
- f' Warning: marker "{marker_id}" shape cannot be classified; '
299
- f'skipping (supported: triangle, diamond, oval)'
300
- )
301
- return ''
302
-
303
- typ, w_bucket, len_bucket = cls
304
-
305
- # Reclassify size buckets based on markerUnits semantics:
306
- #
307
- # markerUnits="strokeWidth" (SVG default):
308
- # markerWidth IS a ratio to stroke-width, and DrawingML headEnd/tailEnd
309
- # also scale proportionally with line width. We should compare the ratio
310
- # (markerWidth) directly against ratio-based thresholds — do NOT multiply
311
- # by stroke-width, because that double-counts the scaling.
312
- # Empirical DrawingML arrow ratios:
313
- # sm ≈ 1.5× stroke-width → markerWidth ≤ 2.0
314
- # med ≈ 2.5× stroke-width → markerWidth 2.0 – 3.5
315
- # lg ≈ 3.5× stroke-width → markerWidth ≥ 3.5
316
- #
317
- # markerUnits="userSpaceOnUse":
318
- # markerWidth/Height are absolute pixel values – keep the existing
319
- # absolute-pixel thresholds from _marker_size_buckets (6 / 12).
320
- marker_units = marker_elem.get('markerUnits', 'strokeWidth')
321
- if marker_units != 'userSpaceOnUse':
322
- mw = _f(marker_elem.get('markerWidth'), 3.0)
323
- mh = _f(marker_elem.get('markerHeight'), 3.0)
324
-
325
- def _ratio_bucket(v: float) -> str:
326
- if v <= 2.0:
327
- return 'sm'
328
- if v >= 3.5:
329
- return 'lg'
330
- return 'med'
331
-
332
- w_bucket = _ratio_bucket(mh) # h → perpendicular width
333
- len_bucket = _ratio_bucket(mw) # w → length along line
334
-
335
- dml_tag = 'headEnd' if which == 'head' else 'tailEnd'
336
- return f'<a:{dml_tag} type="{typ}" w="{w_bucket}" len="{len_bucket}"/>'
337
-
338
-
339
- def build_stroke_xml(
340
- elem: ET.Element,
341
- ctx: ConvertContext,
342
- opacity: float | None = None,
343
- ) -> str:
344
- """Build <a:ln> XML for stroke, with inherited style support."""
345
- stroke = _get_attr(elem, 'stroke', ctx)
346
- if not stroke or stroke.strip().lower() in ('none', 'transparent'):
347
- return '<a:ln><a:noFill/></a:ln>'
348
-
349
- width = parse_svg_length(_get_attr(elem, 'stroke-width', ctx), 1.0)
350
- width_emu = px_to_emu(width)
351
-
352
- # Dash pattern
353
- dash_xml = ''
354
- dasharray = _get_attr(elem, 'stroke-dasharray', ctx)
355
- if dasharray and dasharray != 'none':
356
- preset = DASH_PRESETS.get(dasharray.strip())
357
- if preset:
358
- dash_xml = f'<a:prstDash val="{preset}"/>'
359
- else:
360
- # Unknown pattern → build custDash proportional to stroke width
361
- try:
362
- parts = re.split(r'[\s,]+', dasharray.strip())
363
- d_raw = float(parts[0])
364
- sp_raw = float(parts[1]) if len(parts) > 1 else d_raw
365
- sw = max(width, 0.001)
366
- d_pct = int(d_raw / sw * 100000)
367
- sp_pct = int(sp_raw / sw * 100000)
368
- dash_xml = f'<a:custDash><a:ds d="{d_pct}" sp="{sp_pct}"/></a:custDash>'
369
- except (ValueError, IndexError):
370
- dash_xml = '<a:prstDash val="sysDash"/>'
371
-
372
- # Line cap
373
- cap_map = {'round': 'rnd', 'square': 'sq', 'butt': 'flat'}
374
- cap_attr = ''
375
- linecap = _get_attr(elem, 'stroke-linecap', ctx)
376
- if linecap and linecap in cap_map:
377
- cap_attr = f' cap="{cap_map[linecap]}"'
378
-
379
- # Line join
380
- join_xml = ''
381
- linejoin = _get_attr(elem, 'stroke-linejoin', ctx)
382
- if linejoin == 'round':
383
- join_xml = '<a:round/>'
384
- elif linejoin == 'bevel':
385
- join_xml = '<a:bevel/>'
386
- elif linejoin == 'miter':
387
- join_xml = '<a:miter lim="800000"/>'
388
-
389
- # Line-end markers (SVG marker-start / marker-end → <a:headEnd>/<a:tailEnd>)
390
- # DrawingML schema order is: fill → prstDash → join → headEnd → tailEnd,
391
- # so these must be appended after join_xml.
392
- head_end = _emit_line_end(elem, ctx, 'head')
393
- tail_end = _emit_line_end(elem, ctx, 'tail')
394
- line_ends = head_end + tail_end
395
-
396
- # Gradient stroke
397
- grad_id = resolve_url_id(stroke)
398
- if grad_id and grad_id in ctx.defs:
399
- grad_fill = build_gradient_fill(ctx.defs[grad_id], opacity)
400
- return f'<a:ln w="{width_emu}"{cap_attr}>{grad_fill}{dash_xml}{join_xml}{line_ends}</a:ln>'
401
-
402
- # Solid color stroke
403
- color = parse_hex_color(stroke)
404
- if not color:
405
- return '<a:ln><a:noFill/></a:ln>'
406
-
407
- alpha_xml = ''
408
- if opacity is not None and opacity < 1.0:
409
- alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
410
-
411
- return f'''<a:ln w="{width_emu}"{cap_attr}>
412
- <a:solidFill><a:srgbClr val="{color}">{alpha_xml}</a:srgbClr></a:solidFill>{dash_xml}{join_xml}{line_ends}
413
- </a:ln>'''
414
-
415
-
416
- def _parse_filter_params(
417
- filter_elem: ET.Element,
418
- ) -> dict[str, float | str]:
419
- """Extract common parameters from an SVG filter element.
420
-
421
- Returns:
422
- Dict with keys: std_dev, dx, dy, opacity, color, has_offset.
423
- """
424
- std_dev = 4.0
425
- dx = 0.0
426
- dy = 0.0
427
- opacity = 0.3
428
- color = '000000'
429
- has_offset = False
430
-
431
- for child in filter_elem.iter():
432
- tag = child.tag.replace(f'{{{SVG_NS}}}', '')
433
- if tag == 'feDropShadow':
434
- # Shorthand element: all params in one place
435
- std_dev = _f(child.get('stdDeviation'), 4.0)
436
- dx = _f(child.get('dx'), 0.0)
437
- dy = _f(child.get('dy'), 0.0)
438
- if abs(dx) > 0.01 or abs(dy) > 0.01:
439
- has_offset = True
440
- opacity = _f(child.get('flood-opacity'), 0.3)
441
- raw_color = child.get('flood-color', '').strip().lstrip('#')
442
- if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
443
- color = raw_color.upper()
444
- elif tag == 'feGaussianBlur':
445
- std_dev = _f(child.get('stdDeviation'), 4.0)
446
- elif tag == 'feOffset':
447
- dx = _f(child.get('dx'), 0.0)
448
- dy = _f(child.get('dy'), 0.0)
449
- if abs(dx) > 0.01 or abs(dy) > 0.01:
450
- has_offset = True
451
- elif tag == 'feFlood':
452
- opacity = _f(child.get('flood-opacity'), 0.3)
453
- raw_color = child.get('flood-color', '').strip().lstrip('#')
454
- if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
455
- color = raw_color.upper()
456
- elif tag == 'feFuncA':
457
- if child.get('type') == 'linear':
458
- opacity = _f(child.get('slope'), 0.3)
459
-
460
- return {
461
- 'std_dev': std_dev, 'dx': dx, 'dy': dy,
462
- 'opacity': opacity, 'color': color, 'has_offset': has_offset,
463
- }
464
-
465
-
466
- def _infer_shadow_alignment(dx: float, dy: float, threshold: float = 0.5) -> str:
467
- """Infer outer shadow alignment from the SVG offset vector.
468
-
469
- DrawingML applies alignment before blur/offset transforms, so we anchor the
470
- shadow opposite to the dominant offset direction:
471
- - diagonal offsets map to the opposite corner
472
- - pure vertical offsets stay centered, matching common PPT shadow presets
473
- - pure horizontal offsets anchor to the opposite side
474
- """
475
- if abs(dx) < threshold and abs(dy) < threshold:
476
- return 'ctr'
477
- if abs(dx) < threshold:
478
- return 'ctr'
479
- if abs(dy) < threshold:
480
- return 'l' if dx > 0 else 'r'
481
- if dx > 0 and dy > 0:
482
- return 'tl'
483
- if dx < 0 and dy > 0:
484
- return 'tr'
485
- if dx > 0 and dy < 0:
486
- return 'bl'
487
- return 'br'
488
-
489
-
490
- def _shadow_dir_angle(dx: float, dy: float) -> int:
491
- """Convert an SVG offset vector to DrawingML clockwise angle units.
492
-
493
- OOXML angles are expressed in 60,000ths of a degree, with positive angles
494
- rotating clockwise toward the positive Y axis. SVG uses the same screen
495
- coordinate orientation (positive Y points downward), so the raw screen-space
496
- vector angle can be mapped directly with atan2(dy, dx).
497
- """
498
- if abs(dx) < 0.001 and abs(dy) < 0.001:
499
- return 0
500
- angle_deg = math.degrees(math.atan2(dy, dx)) % 360
501
- return int(angle_deg * ANGLE_UNIT)
502
-
503
-
504
- def build_shadow_xml(filter_elem: ET.Element) -> str:
505
- """Build <a:effectLst> with <a:outerShdw> from SVG filter element.
506
-
507
- SVG-to-DrawingML shadow mapping notes:
508
- - SVG feGaussianBlur stdDeviation (σ) maps to DrawingML blurRad using a
509
- 2.0× scale. Rationale: σ is a standard deviation whose visual radius
510
- is ~3σ, while DrawingML blurRad is an outer-spread pixel distance.
511
- A 1.0× scale makes PowerPoint render sharp, concentrated shadows
512
- ("heavy" visual). 2.0× matches the CSS drop-shadow↔box-shadow
513
- convention and produces softer diffusion closer to the SVG preview.
514
- - The algn attribute is inferred from the offset direction so that
515
- the shadow aligns naturally with the shape edge.
516
- """
517
- if filter_elem is None:
518
- return ''
519
-
520
- p = _parse_filter_params(filter_elem)
521
- std_dev = p['std_dev']
522
- dx = p['dx']
523
- dy = p['dy']
524
- # For shadow, default dy to 4 if no offset was found
525
- if not p['has_offset']:
526
- dy = 4.0
527
-
528
- blur_rad = px_to_emu(std_dev * 2.0)
529
- dist = px_to_emu(math.sqrt(dx * dx + dy * dy))
530
- dir_angle = _shadow_dir_angle(dx, dy)
531
- # PowerPoint renders outerShdw alpha slightly heavier than SVG's filter
532
- # composite (different blending path). Scale by 0.75 to match the SVG
533
- # preview after blur has been corrected to 2.0× σ.
534
- alpha_val = int(p['opacity'] * 75000)
535
- algn = _infer_shadow_alignment(dx, dy)
536
-
537
- return f'''<a:effectLst>
538
- <a:outerShdw blurRad="{blur_rad}" dist="{dist}" dir="{dir_angle}" algn="{algn}" rotWithShape="0">
539
- <a:srgbClr val="{p['color']}"><a:alpha val="{alpha_val}"/></a:srgbClr>
540
- </a:outerShdw>
541
- </a:effectLst>'''
542
-
543
-
544
- def build_glow_xml(filter_elem: ET.Element) -> str:
545
- """Build <a:effectLst> with <a:glow> from SVG filter element.
546
-
547
- Used for filters that have feGaussianBlur without meaningful feOffset,
548
- typically title glow or highlight effects.
549
- """
550
- if filter_elem is None:
551
- return ''
552
-
553
- p = _parse_filter_params(filter_elem)
554
- rad = px_to_emu(p['std_dev'])
555
- alpha_val = int(p['opacity'] * 100000)
556
-
557
- return f'''<a:effectLst>
558
- <a:glow rad="{rad}">
559
- <a:srgbClr val="{p['color']}"><a:alpha val="{alpha_val}"/></a:srgbClr>
560
- </a:glow>
561
- </a:effectLst>'''
562
-
563
-
564
- def classify_filter_effect(filter_elem: ET.Element) -> str | None:
565
- """Classify an SVG filter into a supported DrawingML effect kind."""
566
- if filter_elem is None:
567
- return None
568
-
569
- p = _parse_filter_params(filter_elem)
570
- return 'shadow' if p['has_offset'] else 'glow'
571
-
572
-
573
- def build_effect_xml(filter_elem: ET.Element) -> str:
574
- """Build effect XML by classifying the SVG filter as shadow or glow.
575
-
576
- Classification rules:
577
- - feOffset with non-zero dx/dy → outer shadow
578
- - No feOffset or zero offset → glow effect
579
- """
580
- if filter_elem is None:
581
- return ''
582
-
583
- effect_kind = classify_filter_effect(filter_elem)
584
- if effect_kind == 'shadow':
585
- return build_shadow_xml(filter_elem)
586
- if effect_kind == 'glow':
587
- return build_glow_xml(filter_elem)
588
- return ''
589
-
590
-
591
- def get_element_opacity(elem: ET.Element) -> float | None:
592
- """Get opacity value from element. Returns None if 1.0 or not set."""
593
- op = elem.get('opacity')
594
- if op is None:
595
- return None
596
- try:
597
- val = float(op)
598
- return val if val < 1.0 else None
599
- except ValueError:
600
- return None
601
-
602
-
603
- def get_fill_opacity(
604
- elem: ET.Element,
605
- ctx: ConvertContext | None = None,
606
- ) -> float | None:
607
- """Get effective fill opacity combining 'opacity' and 'fill-opacity'.
608
-
609
- Returns:
610
- Combined opacity value, or None if fully opaque.
611
- """
612
- base = 1.0
613
-
614
- op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
615
- if op:
616
- try:
617
- base = float(op)
618
- except ValueError:
619
- pass
620
-
621
- fill_op = _get_attr(elem, 'fill-opacity', ctx) if ctx else elem.get('fill-opacity')
622
- if fill_op:
623
- try:
624
- base *= float(fill_op)
625
- except ValueError:
626
- pass
627
-
628
- return base if base < 1.0 else None
629
-
630
-
631
- def get_stroke_opacity(
632
- elem: ET.Element,
633
- ctx: ConvertContext | None = None,
634
- ) -> float | None:
635
- """Get effective stroke opacity combining 'opacity' and 'stroke-opacity'.
636
-
637
- Returns:
638
- Combined opacity value, or None if fully opaque.
639
- """
640
- base = 1.0
641
-
642
- op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
643
- if op:
644
- try:
645
- base = float(op)
646
- except ValueError:
647
- pass
648
-
649
- stroke_op = _get_attr(elem, 'stroke-opacity', ctx) if ctx else elem.get('stroke-opacity')
650
- if stroke_op:
651
- try:
652
- base *= float(stroke_op)
653
- except ValueError:
654
- pass
655
-
656
- return base if base < 1.0 else None
1
+ """Fill, stroke, and shadow XML builders for DrawingML conversion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from xml.etree import ElementTree as ET
8
+
9
+ from .context import ConvertContext
10
+ from .utils import (
11
+ SVG_NS, ANGLE_UNIT, DASH_PRESETS,
12
+ px_to_emu, _f, _get_attr, parse_svg_length,
13
+ parse_hex_color, parse_stop_style, resolve_url_id,
14
+ )
15
+
16
+
17
+ def build_solid_fill(color: str, opacity: float | None = None) -> str:
18
+ """Build <a:solidFill> XML."""
19
+ alpha = ''
20
+ if opacity is not None and opacity < 1.0:
21
+ alpha = f'<a:alpha val="{int(opacity * 100000)}"/>'
22
+ return f'<a:solidFill><a:srgbClr val="{color}">{alpha}</a:srgbClr></a:solidFill>'
23
+
24
+
25
+ def build_gradient_fill(
26
+ grad_elem: ET.Element,
27
+ opacity: float | None = None,
28
+ ) -> str:
29
+ """Build <a:gradFill> from SVG linearGradient or radialGradient element."""
30
+ tag = grad_elem.tag.replace(f'{{{SVG_NS}}}', '')
31
+
32
+ stops_xml = []
33
+ for child in grad_elem:
34
+ child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
35
+ if child_tag != 'stop':
36
+ continue
37
+
38
+ offset_str = child.get('offset', '0').strip().rstrip('%')
39
+ try:
40
+ offset = float(offset_str)
41
+ if offset > 1.0:
42
+ offset = offset / 100.0
43
+ except ValueError:
44
+ offset = 0.0
45
+ pos = int(offset * 100000)
46
+
47
+ # Parse color from style attribute or direct attributes
48
+ style = child.get('style', '')
49
+ color, stop_opacity = parse_stop_style(style)
50
+ if not color:
51
+ color = parse_hex_color(child.get('stop-color', '#000000'))
52
+ if color is None:
53
+ color = '000000'
54
+
55
+ direct_stop_op = child.get('stop-opacity')
56
+ if direct_stop_op is not None:
57
+ try:
58
+ stop_opacity = float(direct_stop_op)
59
+ except ValueError:
60
+ pass
61
+
62
+ alpha_xml = ''
63
+ effective_opacity = stop_opacity
64
+ if opacity is not None:
65
+ effective_opacity *= opacity
66
+ if effective_opacity < 1.0:
67
+ alpha_xml = f'<a:alpha val="{int(effective_opacity * 100000)}"/>'
68
+
69
+ stops_xml.append(
70
+ f'<a:gs pos="{pos}"><a:srgbClr val="{color}">{alpha_xml}</a:srgbClr></a:gs>'
71
+ )
72
+
73
+ if not stops_xml:
74
+ return ''
75
+
76
+ gs_list = '\n'.join(stops_xml)
77
+
78
+ if tag == 'linearGradient':
79
+ def parse_grad_coord(val_str: str, default: float = 0.0) -> float:
80
+ val_str = val_str.strip()
81
+ if val_str.endswith('%'):
82
+ return float(val_str.rstrip('%')) / 100.0
83
+ v = float(val_str)
84
+ return v / 100.0 if v > 1.0 else v
85
+
86
+ x1 = parse_grad_coord(grad_elem.get('x1', '0'))
87
+ y1 = parse_grad_coord(grad_elem.get('y1', '0'))
88
+ x2 = parse_grad_coord(grad_elem.get('x2', '1'))
89
+ y2 = parse_grad_coord(grad_elem.get('y2', '1'))
90
+
91
+ angle_rad = math.atan2(y2 - y1, x2 - x1)
92
+ angle_deg = math.degrees(angle_rad)
93
+ dml_angle = int((angle_deg % 360) * ANGLE_UNIT)
94
+
95
+ return f'''<a:gradFill>
96
+ <a:gsLst>{gs_list}</a:gsLst>
97
+ <a:lin ang="{dml_angle}" scaled="1"/>
98
+ </a:gradFill>'''
99
+
100
+ elif tag == 'radialGradient':
101
+ return f'''<a:gradFill>
102
+ <a:gsLst>{gs_list}</a:gsLst>
103
+ <a:path path="circle">
104
+ <a:fillToRect l="50000" t="50000" r="50000" b="50000"/>
105
+ </a:path>
106
+ </a:gradFill>'''
107
+
108
+ return ''
109
+
110
+
111
+ def build_fill_xml(
112
+ elem: ET.Element,
113
+ ctx: ConvertContext,
114
+ opacity: float | None = None,
115
+ ) -> str:
116
+ """Build fill XML for a shape element, with inherited style support."""
117
+ fill = _get_attr(elem, 'fill', ctx)
118
+ if fill is None:
119
+ fill = '#000000' # SVG default fill is black
120
+
121
+ if fill.strip().lower() in ('none', 'transparent'):
122
+ return '<a:noFill/>'
123
+
124
+ ref_id = resolve_url_id(fill)
125
+ if ref_id and ref_id in ctx.defs:
126
+ ref_elem = ctx.defs[ref_id]
127
+ ref_tag = ref_elem.tag.replace(f'{{{SVG_NS}}}', '')
128
+ if ref_tag == 'pattern':
129
+ patt_xml = build_pattern_fill(ref_elem, opacity)
130
+ if patt_xml:
131
+ return patt_xml
132
+ return '<a:noFill/>'
133
+ return build_gradient_fill(ref_elem, opacity)
134
+
135
+ color = parse_hex_color(fill)
136
+ if color:
137
+ return build_solid_fill(color, opacity)
138
+
139
+ return '<a:noFill/>'
140
+
141
+
142
+ def build_pattern_fill(
143
+ pattern_elem: ET.Element,
144
+ opacity: float | None = None,
145
+ ) -> str:
146
+ """Build <a:pattFill> from an SVG <pattern> emitted by pptx_to_svg.
147
+
148
+ Reads the round-trip annotations (data-pptx-pattern / data-pptx-fg /
149
+ data-pptx-bg) when present. Falls back to inspecting the inner stroke /
150
+ rect colors when annotations are absent (hand-authored SVG).
151
+ """
152
+ prst = pattern_elem.get('data-pptx-pattern') or 'ltUpDiag'
153
+
154
+ fg_color = pattern_elem.get('data-pptx-fg')
155
+ bg_color = pattern_elem.get('data-pptx-bg')
156
+
157
+ if not fg_color or not bg_color:
158
+ # Hand-authored fallback: derive from child elements.
159
+ for child in pattern_elem:
160
+ tag = child.tag.replace(f'{{{SVG_NS}}}', '')
161
+ if tag == 'rect' and not bg_color:
162
+ bg_color = child.get('fill')
163
+ elif tag == 'path' and not fg_color:
164
+ fg_color = child.get('stroke')
165
+
166
+ fg_hex = parse_hex_color(fg_color) if fg_color else None
167
+ bg_hex = parse_hex_color(bg_color) if bg_color else None
168
+ if not fg_hex:
169
+ return ''
170
+
171
+ alpha_xml = ''
172
+ if opacity is not None and opacity < 1.0:
173
+ alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
174
+
175
+ fg_xml = f'<a:srgbClr val="{fg_hex}">{alpha_xml}</a:srgbClr>'
176
+ if bg_hex:
177
+ bg_xml = f'<a:srgbClr val="{bg_hex}"/>'
178
+ else:
179
+ bg_xml = '<a:srgbClr val="FFFFFF"/>'
180
+
181
+ return (
182
+ f'<a:pattFill prst="{prst}">'
183
+ f'<a:fgClr>{fg_xml}</a:fgClr>'
184
+ f'<a:bgClr>{bg_xml}</a:bgClr>'
185
+ f'</a:pattFill>'
186
+ )
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Marker (arrow-head) support
191
+ # ---------------------------------------------------------------------------
192
+
193
+ # Matches an (x, y) pair in a path "d" attribute: "M 10, 20" / "L -5 7.5" / etc.
194
+ _MARKER_POINT_RE = re.compile(
195
+ r'[MLml]\s*(-?\d+(?:\.\d+)?)\s*[,\s]\s*(-?\d+(?:\.\d+)?)'
196
+ )
197
+ _MARKER_POLY_POINT_RE = re.compile(
198
+ r'(-?\d+(?:\.\d+)?)\s*[,\s]\s*(-?\d+(?:\.\d+)?)'
199
+ )
200
+
201
+
202
+ def _marker_size_buckets(w_attr: float, h_attr: float) -> tuple[str, str]:
203
+ """Map SVG markerWidth / markerHeight to DrawingML (w, len) buckets.
204
+
205
+ DrawingML arrow-end sizing is categorical: sm / med / lg.
206
+ Width (perpendicular to the line) maps from markerHeight;
207
+ length (along the line) maps from markerWidth.
208
+ """
209
+
210
+ def bucket(v: float) -> str:
211
+ if v < 6:
212
+ return 'sm'
213
+ if v > 12:
214
+ return 'lg'
215
+ return 'med'
216
+
217
+ return bucket(h_attr), bucket(w_attr)
218
+
219
+
220
+ def _classify_marker(marker_elem: ET.Element) -> tuple[str, str, str] | None:
221
+ """Classify an SVG <marker> into a DrawingML line-end preset.
222
+
223
+ Returns (type, w, len) where:
224
+ type in {'triangle', 'stealth', 'diamond', 'oval', 'arrow'}
225
+ w, len in {'sm', 'med', 'lg'}
226
+ or None if the marker cannot be classified.
227
+
228
+ Current coverage (80/20): triangles (3-vertex closed paths or polygons),
229
+ diamonds (4-vertex symmetric), and circles / ellipses. Anything else
230
+ returns None so the caller can warn and skip.
231
+ """
232
+ mw = _f(marker_elem.get('markerWidth'), 3.0)
233
+ mh = _f(marker_elem.get('markerHeight'), 3.0)
234
+ w_bucket, len_bucket = _marker_size_buckets(mw, mh)
235
+
236
+ for child in marker_elem:
237
+ tag = child.tag.replace(f'{{{SVG_NS}}}', '')
238
+
239
+ if tag in ('circle', 'ellipse'):
240
+ return ('oval', w_bucket, len_bucket)
241
+
242
+ if tag == 'path':
243
+ d = child.get('d', '')
244
+ if not d:
245
+ continue
246
+ points = _MARKER_POINT_RE.findall(d)
247
+ n = len(points)
248
+ closed = bool(re.search(r'[Zz]\s*$', d.strip()))
249
+ if n == 3 and closed:
250
+ return ('triangle', w_bucket, len_bucket)
251
+ if n == 4 and closed:
252
+ return ('diamond', w_bucket, len_bucket)
253
+ continue
254
+
255
+ if tag in ('polygon', 'polyline'):
256
+ pts_attr = child.get('points', '')
257
+ pts = _MARKER_POLY_POINT_RE.findall(pts_attr)
258
+ n = len(pts)
259
+ if n == 3:
260
+ return ('triangle', w_bucket, len_bucket)
261
+ if n == 4:
262
+ return ('diamond', w_bucket, len_bucket)
263
+ continue
264
+
265
+ return None
266
+
267
+
268
+ def _emit_line_end(
269
+ elem: ET.Element,
270
+ ctx: ConvertContext,
271
+ which: str,
272
+ ) -> str:
273
+ """Build <a:headEnd> or <a:tailEnd> XML for an element's marker reference.
274
+
275
+ Args:
276
+ which: 'head' (SVG marker-start) or 'tail' (SVG marker-end).
277
+
278
+ Returns empty string if no marker, cannot resolve, or cannot classify.
279
+ """
280
+ attr = 'marker-start' if which == 'head' else 'marker-end'
281
+ ref = _get_attr(elem, attr, ctx)
282
+ if not ref or ref == 'none':
283
+ return ''
284
+
285
+ marker_id = resolve_url_id(ref)
286
+ if not marker_id or marker_id not in ctx.defs:
287
+ return ''
288
+
289
+ marker_elem = ctx.defs[marker_id]
290
+ tag = marker_elem.tag.replace(f'{{{SVG_NS}}}', '')
291
+ if tag != 'marker':
292
+ # ID collision with non-marker defs entry; ignore.
293
+ return ''
294
+
295
+ cls = _classify_marker(marker_elem)
296
+ if cls is None:
297
+ print(
298
+ f' Warning: marker "{marker_id}" shape cannot be classified; '
299
+ f'skipping (supported: triangle, diamond, oval)'
300
+ )
301
+ return ''
302
+
303
+ typ, w_bucket, len_bucket = cls
304
+
305
+ # Reclassify size buckets based on markerUnits semantics:
306
+ #
307
+ # markerUnits="strokeWidth" (SVG default):
308
+ # markerWidth IS a ratio to stroke-width, and DrawingML headEnd/tailEnd
309
+ # also scale proportionally with line width. We should compare the ratio
310
+ # (markerWidth) directly against ratio-based thresholds — do NOT multiply
311
+ # by stroke-width, because that double-counts the scaling.
312
+ # Empirical DrawingML arrow ratios:
313
+ # sm ≈ 1.5× stroke-width → markerWidth ≤ 2.0
314
+ # med ≈ 2.5× stroke-width → markerWidth 2.0 – 3.5
315
+ # lg ≈ 3.5× stroke-width → markerWidth ≥ 3.5
316
+ #
317
+ # markerUnits="userSpaceOnUse":
318
+ # markerWidth/Height are absolute pixel values – keep the existing
319
+ # absolute-pixel thresholds from _marker_size_buckets (6 / 12).
320
+ marker_units = marker_elem.get('markerUnits', 'strokeWidth')
321
+ if marker_units != 'userSpaceOnUse':
322
+ mw = _f(marker_elem.get('markerWidth'), 3.0)
323
+ mh = _f(marker_elem.get('markerHeight'), 3.0)
324
+
325
+ def _ratio_bucket(v: float) -> str:
326
+ if v <= 2.0:
327
+ return 'sm'
328
+ if v >= 3.5:
329
+ return 'lg'
330
+ return 'med'
331
+
332
+ w_bucket = _ratio_bucket(mh) # h → perpendicular width
333
+ len_bucket = _ratio_bucket(mw) # w → length along line
334
+
335
+ dml_tag = 'headEnd' if which == 'head' else 'tailEnd'
336
+ return f'<a:{dml_tag} type="{typ}" w="{w_bucket}" len="{len_bucket}"/>'
337
+
338
+
339
+ def build_stroke_xml(
340
+ elem: ET.Element,
341
+ ctx: ConvertContext,
342
+ opacity: float | None = None,
343
+ ) -> str:
344
+ """Build <a:ln> XML for stroke, with inherited style support."""
345
+ stroke = _get_attr(elem, 'stroke', ctx)
346
+ if not stroke or stroke.strip().lower() in ('none', 'transparent'):
347
+ return '<a:ln><a:noFill/></a:ln>'
348
+
349
+ width = parse_svg_length(_get_attr(elem, 'stroke-width', ctx), 1.0)
350
+ width_emu = px_to_emu(width)
351
+
352
+ # Dash pattern
353
+ dash_xml = ''
354
+ dasharray = _get_attr(elem, 'stroke-dasharray', ctx)
355
+ if dasharray and dasharray != 'none':
356
+ preset = DASH_PRESETS.get(dasharray.strip())
357
+ if preset:
358
+ dash_xml = f'<a:prstDash val="{preset}"/>'
359
+ else:
360
+ # Unknown pattern → build custDash proportional to stroke width
361
+ try:
362
+ parts = re.split(r'[\s,]+', dasharray.strip())
363
+ d_raw = float(parts[0])
364
+ sp_raw = float(parts[1]) if len(parts) > 1 else d_raw
365
+ sw = max(width, 0.001)
366
+ d_pct = int(d_raw / sw * 100000)
367
+ sp_pct = int(sp_raw / sw * 100000)
368
+ dash_xml = f'<a:custDash><a:ds d="{d_pct}" sp="{sp_pct}"/></a:custDash>'
369
+ except (ValueError, IndexError):
370
+ dash_xml = '<a:prstDash val="sysDash"/>'
371
+
372
+ # Line cap
373
+ cap_map = {'round': 'rnd', 'square': 'sq', 'butt': 'flat'}
374
+ cap_attr = ''
375
+ linecap = _get_attr(elem, 'stroke-linecap', ctx)
376
+ if linecap and linecap in cap_map:
377
+ cap_attr = f' cap="{cap_map[linecap]}"'
378
+
379
+ # Line join
380
+ join_xml = ''
381
+ linejoin = _get_attr(elem, 'stroke-linejoin', ctx)
382
+ if linejoin == 'round':
383
+ join_xml = '<a:round/>'
384
+ elif linejoin == 'bevel':
385
+ join_xml = '<a:bevel/>'
386
+ elif linejoin == 'miter':
387
+ join_xml = '<a:miter lim="800000"/>'
388
+
389
+ # Line-end markers (SVG marker-start / marker-end → <a:headEnd>/<a:tailEnd>)
390
+ # DrawingML schema order is: fill → prstDash → join → headEnd → tailEnd,
391
+ # so these must be appended after join_xml.
392
+ head_end = _emit_line_end(elem, ctx, 'head')
393
+ tail_end = _emit_line_end(elem, ctx, 'tail')
394
+ line_ends = head_end + tail_end
395
+
396
+ # Gradient stroke
397
+ grad_id = resolve_url_id(stroke)
398
+ if grad_id and grad_id in ctx.defs:
399
+ grad_fill = build_gradient_fill(ctx.defs[grad_id], opacity)
400
+ return f'<a:ln w="{width_emu}"{cap_attr}>{grad_fill}{dash_xml}{join_xml}{line_ends}</a:ln>'
401
+
402
+ # Solid color stroke
403
+ color = parse_hex_color(stroke)
404
+ if not color:
405
+ return '<a:ln><a:noFill/></a:ln>'
406
+
407
+ alpha_xml = ''
408
+ if opacity is not None and opacity < 1.0:
409
+ alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
410
+
411
+ return f'''<a:ln w="{width_emu}"{cap_attr}>
412
+ <a:solidFill><a:srgbClr val="{color}">{alpha_xml}</a:srgbClr></a:solidFill>{dash_xml}{join_xml}{line_ends}
413
+ </a:ln>'''
414
+
415
+
416
+ def _parse_filter_params(
417
+ filter_elem: ET.Element,
418
+ ) -> dict[str, float | str]:
419
+ """Extract common parameters from an SVG filter element.
420
+
421
+ Returns:
422
+ Dict with keys: std_dev, dx, dy, opacity, color, has_offset.
423
+ """
424
+ std_dev = 4.0
425
+ dx = 0.0
426
+ dy = 0.0
427
+ opacity = 0.3
428
+ color = '000000'
429
+ has_offset = False
430
+
431
+ for child in filter_elem.iter():
432
+ tag = child.tag.replace(f'{{{SVG_NS}}}', '')
433
+ if tag == 'feDropShadow':
434
+ # Shorthand element: all params in one place
435
+ std_dev = _f(child.get('stdDeviation'), 4.0)
436
+ dx = _f(child.get('dx'), 0.0)
437
+ dy = _f(child.get('dy'), 0.0)
438
+ if abs(dx) > 0.01 or abs(dy) > 0.01:
439
+ has_offset = True
440
+ opacity = _f(child.get('flood-opacity'), 0.3)
441
+ raw_color = child.get('flood-color', '').strip().lstrip('#')
442
+ if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
443
+ color = raw_color.upper()
444
+ elif tag == 'feGaussianBlur':
445
+ std_dev = _f(child.get('stdDeviation'), 4.0)
446
+ elif tag == 'feOffset':
447
+ dx = _f(child.get('dx'), 0.0)
448
+ dy = _f(child.get('dy'), 0.0)
449
+ if abs(dx) > 0.01 or abs(dy) > 0.01:
450
+ has_offset = True
451
+ elif tag == 'feFlood':
452
+ opacity = _f(child.get('flood-opacity'), 0.3)
453
+ raw_color = child.get('flood-color', '').strip().lstrip('#')
454
+ if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
455
+ color = raw_color.upper()
456
+ elif tag == 'feFuncA':
457
+ if child.get('type') == 'linear':
458
+ opacity = _f(child.get('slope'), 0.3)
459
+
460
+ return {
461
+ 'std_dev': std_dev, 'dx': dx, 'dy': dy,
462
+ 'opacity': opacity, 'color': color, 'has_offset': has_offset,
463
+ }
464
+
465
+
466
+ def _infer_shadow_alignment(dx: float, dy: float, threshold: float = 0.5) -> str:
467
+ """Infer outer shadow alignment from the SVG offset vector.
468
+
469
+ DrawingML applies alignment before blur/offset transforms, so we anchor the
470
+ shadow opposite to the dominant offset direction:
471
+ - diagonal offsets map to the opposite corner
472
+ - pure vertical offsets stay centered, matching common PPT shadow presets
473
+ - pure horizontal offsets anchor to the opposite side
474
+ """
475
+ if abs(dx) < threshold and abs(dy) < threshold:
476
+ return 'ctr'
477
+ if abs(dx) < threshold:
478
+ return 'ctr'
479
+ if abs(dy) < threshold:
480
+ return 'l' if dx > 0 else 'r'
481
+ if dx > 0 and dy > 0:
482
+ return 'tl'
483
+ if dx < 0 and dy > 0:
484
+ return 'tr'
485
+ if dx > 0 and dy < 0:
486
+ return 'bl'
487
+ return 'br'
488
+
489
+
490
+ def _shadow_dir_angle(dx: float, dy: float) -> int:
491
+ """Convert an SVG offset vector to DrawingML clockwise angle units.
492
+
493
+ OOXML angles are expressed in 60,000ths of a degree, with positive angles
494
+ rotating clockwise toward the positive Y axis. SVG uses the same screen
495
+ coordinate orientation (positive Y points downward), so the raw screen-space
496
+ vector angle can be mapped directly with atan2(dy, dx).
497
+ """
498
+ if abs(dx) < 0.001 and abs(dy) < 0.001:
499
+ return 0
500
+ angle_deg = math.degrees(math.atan2(dy, dx)) % 360
501
+ return int(angle_deg * ANGLE_UNIT)
502
+
503
+
504
+ def build_shadow_xml(filter_elem: ET.Element) -> str:
505
+ """Build <a:effectLst> with <a:outerShdw> from SVG filter element.
506
+
507
+ SVG-to-DrawingML shadow mapping notes:
508
+ - SVG feGaussianBlur stdDeviation (σ) maps to DrawingML blurRad using a
509
+ 2.0× scale. Rationale: σ is a standard deviation whose visual radius
510
+ is ~3σ, while DrawingML blurRad is an outer-spread pixel distance.
511
+ A 1.0× scale makes PowerPoint render sharp, concentrated shadows
512
+ ("heavy" visual). 2.0× matches the CSS drop-shadow↔box-shadow
513
+ convention and produces softer diffusion closer to the SVG preview.
514
+ - The algn attribute is inferred from the offset direction so that
515
+ the shadow aligns naturally with the shape edge.
516
+ """
517
+ if filter_elem is None:
518
+ return ''
519
+
520
+ p = _parse_filter_params(filter_elem)
521
+ std_dev = p['std_dev']
522
+ dx = p['dx']
523
+ dy = p['dy']
524
+ # For shadow, default dy to 4 if no offset was found
525
+ if not p['has_offset']:
526
+ dy = 4.0
527
+
528
+ blur_rad = px_to_emu(std_dev * 2.0)
529
+ dist = px_to_emu(math.sqrt(dx * dx + dy * dy))
530
+ dir_angle = _shadow_dir_angle(dx, dy)
531
+ # PowerPoint renders outerShdw alpha slightly heavier than SVG's filter
532
+ # composite (different blending path). Scale by 0.75 to match the SVG
533
+ # preview after blur has been corrected to 2.0× σ.
534
+ alpha_val = int(p['opacity'] * 75000)
535
+ algn = _infer_shadow_alignment(dx, dy)
536
+
537
+ return f'''<a:effectLst>
538
+ <a:outerShdw blurRad="{blur_rad}" dist="{dist}" dir="{dir_angle}" algn="{algn}" rotWithShape="0">
539
+ <a:srgbClr val="{p['color']}"><a:alpha val="{alpha_val}"/></a:srgbClr>
540
+ </a:outerShdw>
541
+ </a:effectLst>'''
542
+
543
+
544
+ def build_glow_xml(filter_elem: ET.Element) -> str:
545
+ """Build <a:effectLst> with <a:glow> from SVG filter element.
546
+
547
+ Used for filters that have feGaussianBlur without meaningful feOffset,
548
+ typically title glow or highlight effects.
549
+ """
550
+ if filter_elem is None:
551
+ return ''
552
+
553
+ p = _parse_filter_params(filter_elem)
554
+ rad = px_to_emu(p['std_dev'])
555
+ alpha_val = int(p['opacity'] * 100000)
556
+
557
+ return f'''<a:effectLst>
558
+ <a:glow rad="{rad}">
559
+ <a:srgbClr val="{p['color']}"><a:alpha val="{alpha_val}"/></a:srgbClr>
560
+ </a:glow>
561
+ </a:effectLst>'''
562
+
563
+
564
+ def classify_filter_effect(filter_elem: ET.Element) -> str | None:
565
+ """Classify an SVG filter into a supported DrawingML effect kind."""
566
+ if filter_elem is None:
567
+ return None
568
+
569
+ p = _parse_filter_params(filter_elem)
570
+ return 'shadow' if p['has_offset'] else 'glow'
571
+
572
+
573
+ def build_effect_xml(filter_elem: ET.Element) -> str:
574
+ """Build effect XML by classifying the SVG filter as shadow or glow.
575
+
576
+ Classification rules:
577
+ - feOffset with non-zero dx/dy → outer shadow
578
+ - No feOffset or zero offset → glow effect
579
+ """
580
+ if filter_elem is None:
581
+ return ''
582
+
583
+ effect_kind = classify_filter_effect(filter_elem)
584
+ if effect_kind == 'shadow':
585
+ return build_shadow_xml(filter_elem)
586
+ if effect_kind == 'glow':
587
+ return build_glow_xml(filter_elem)
588
+ return ''
589
+
590
+
591
+ def get_element_opacity(elem: ET.Element) -> float | None:
592
+ """Get opacity value from element. Returns None if 1.0 or not set."""
593
+ op = elem.get('opacity')
594
+ if op is None:
595
+ return None
596
+ try:
597
+ val = float(op)
598
+ return val if val < 1.0 else None
599
+ except ValueError:
600
+ return None
601
+
602
+
603
+ def get_fill_opacity(
604
+ elem: ET.Element,
605
+ ctx: ConvertContext | None = None,
606
+ ) -> float | None:
607
+ """Get effective fill opacity combining 'opacity' and 'fill-opacity'.
608
+
609
+ Returns:
610
+ Combined opacity value, or None if fully opaque.
611
+ """
612
+ base = 1.0
613
+
614
+ op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
615
+ if op:
616
+ try:
617
+ base = float(op)
618
+ except ValueError:
619
+ pass
620
+
621
+ fill_op = _get_attr(elem, 'fill-opacity', ctx) if ctx else elem.get('fill-opacity')
622
+ if fill_op:
623
+ try:
624
+ base *= float(fill_op)
625
+ except ValueError:
626
+ pass
627
+
628
+ return base if base < 1.0 else None
629
+
630
+
631
+ def get_stroke_opacity(
632
+ elem: ET.Element,
633
+ ctx: ConvertContext | None = None,
634
+ ) -> float | None:
635
+ """Get effective stroke opacity combining 'opacity' and 'stroke-opacity'.
636
+
637
+ Returns:
638
+ Combined opacity value, or None if fully opaque.
639
+ """
640
+ base = 1.0
641
+
642
+ op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
643
+ if op:
644
+ try:
645
+ base = float(op)
646
+ except ValueError:
647
+ pass
648
+
649
+ stroke_op = _get_attr(elem, 'stroke-opacity', ctx) if ctx else elem.get('stroke-opacity')
650
+ if stroke_op:
651
+ try:
652
+ base *= float(stroke_op)
653
+ except ValueError:
654
+ pass
655
+
656
+ return base if base < 1.0 else None