@hfyjq/crannia 0.0.0-stage → 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 (477) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +45 -0
  3. package/README.md +3 -3
  4. package/THIRD-PARTY-FRONTEND.md +5266 -0
  5. package/THIRD-PARTY-PYTHON.md +162 -0
  6. package/THIRD-PARTY.md +316 -0
  7. package/apps/desktop/quotes.txt +56 -0
  8. package/bus/__init__.py +0 -0
  9. package/bus/core.py +671 -0
  10. package/bus/loaders/__init__.py +0 -0
  11. package/bus/loaders/channel_loader.py +64 -0
  12. package/bus/loaders/provider_loader.py +338 -0
  13. package/bus/loaders/skill_loader.py +769 -0
  14. package/bus/loaders/skill_md.py +676 -0
  15. package/bus/mcp_disabled.py +190 -0
  16. package/bus/quarantine.py +468 -0
  17. package/bus/registry.py +2284 -0
  18. package/bus/skill_state.py +124 -0
  19. package/channels/__init__.py +0 -0
  20. package/channels/base.py +275 -0
  21. package/channels/capabilities.py +77 -0
  22. package/channels/cli_channel/__init__.py +0 -0
  23. package/channels/cli_channel/handler.py +299 -0
  24. package/channels/cli_channel/manifest.yaml +5 -0
  25. package/channels/converter.py +54 -0
  26. package/channels/dingtalk_channel/handler.py +690 -0
  27. package/channels/dingtalk_channel/manifest.yaml +12 -0
  28. package/channels/dingtalk_channel/media.py +299 -0
  29. package/channels/feishu_channel/handler.py +947 -0
  30. package/channels/feishu_channel/manifest.yaml +12 -0
  31. package/channels/feishu_channel/media.py +183 -0
  32. package/channels/message.py +300 -0
  33. package/channels/qq_bot_channel/__init__.py +1 -0
  34. package/channels/qq_bot_channel/handler.py +881 -0
  35. package/channels/qq_bot_channel/manifest.yaml +4 -0
  36. package/channels/telegram_channel/__init__.py +1 -0
  37. package/channels/telegram_channel/handler.py +813 -0
  38. package/channels/telegram_channel/manifest.yaml +4 -0
  39. package/channels/telegram_channel/media.py +231 -0
  40. package/channels/textfmt.py +58 -0
  41. package/channels/wechat_channel/__init__.py +1 -0
  42. package/channels/wechat_channel/auth.py +290 -0
  43. package/channels/wechat_channel/converter.py +148 -0
  44. package/channels/wechat_channel/handler.py +971 -0
  45. package/channels/wechat_channel/manifest.yaml +5 -0
  46. package/channels/wechat_channel/media.py +178 -0
  47. package/config.yaml +172 -0
  48. package/core/__init__.py +0 -0
  49. package/core/activity.py +709 -0
  50. package/core/agent_loop.py +7523 -0
  51. package/core/allowlist.py +279 -0
  52. package/core/approval.py +1000 -0
  53. package/core/approval_timeout.py +228 -0
  54. package/core/artifacts.py +566 -0
  55. package/core/ask_user.py +238 -0
  56. package/core/async_loop.py +264 -0
  57. package/core/attachment_gc.py +235 -0
  58. package/core/auto_review.py +1531 -0
  59. package/core/browser/__init__.py +10 -0
  60. package/core/browser/cdp.py +198 -0
  61. package/core/browser/discover.py +97 -0
  62. package/core/browser/session.py +595 -0
  63. package/core/browser/tools.py +191 -0
  64. package/core/cancellation.py +244 -0
  65. package/core/capabilities.py +105 -0
  66. package/core/channel_configs.py +434 -0
  67. package/core/channel_health.py +66 -0
  68. package/core/channel_turns.py +759 -0
  69. package/core/child_approval.py +150 -0
  70. package/core/chunker.py +119 -0
  71. package/core/code_intel.py +1205 -0
  72. package/core/command_policy.py +912 -0
  73. package/core/compaction_tool.py +54 -0
  74. package/core/computer/__init__.py +21 -0
  75. package/core/computer/annotate.py +164 -0
  76. package/core/computer/capture.py +202 -0
  77. package/core/computer/guard.py +209 -0
  78. package/core/computer/input.py +500 -0
  79. package/core/computer/session.py +381 -0
  80. package/core/computer/tools.py +928 -0
  81. package/core/computer/uia.py +508 -0
  82. package/core/computer/watch.py +270 -0
  83. package/core/computer/win32.py +954 -0
  84. package/core/config_requirements.py +205 -0
  85. package/core/content_sanitizer.py +340 -0
  86. package/core/context_pressure.py +173 -0
  87. package/core/context_report.py +236 -0
  88. package/core/cron/__init__.py +8 -0
  89. package/core/cron/expr.py +411 -0
  90. package/core/cron/runner.py +898 -0
  91. package/core/cron/store.py +443 -0
  92. package/core/cron/tools.py +283 -0
  93. package/core/daily_log.py +109 -0
  94. package/core/dedup.py +310 -0
  95. package/core/delivery_outbox.py +121 -0
  96. package/core/egress_gate.py +183 -0
  97. package/core/egress_preapproved.py +338 -0
  98. package/core/endpoint.py +141 -0
  99. package/core/events.py +908 -0
  100. package/core/extension.py +461 -0
  101. package/core/externals.py +144 -0
  102. package/core/file_history.py +960 -0
  103. package/core/file_tools.py +1656 -0
  104. package/core/framework_preset.py +133 -0
  105. package/core/github_config.py +96 -0
  106. package/core/group_digest.py +140 -0
  107. package/core/group_dispatch.py +362 -0
  108. package/core/group_minutes.py +349 -0
  109. package/core/group_reply.py +526 -0
  110. package/core/groups.py +513 -0
  111. package/core/history_tools.py +390 -0
  112. package/core/hooks.py +653 -0
  113. package/core/i18n.py +329 -0
  114. package/core/ice/__init__.py +122 -0
  115. package/core/ice/boundary.py +252 -0
  116. package/core/ice/canary.py +143 -0
  117. package/core/ice/detect.py +123 -0
  118. package/core/ice/guard.py +185 -0
  119. package/core/ice/handles.py +226 -0
  120. package/core/ice/net_heuristics.py +198 -0
  121. package/core/ice/pseudonym.py +215 -0
  122. package/core/ice/reveal.py +229 -0
  123. package/core/ice/rules/builtin.toml +68 -0
  124. package/core/ice/rules.py +268 -0
  125. package/core/ice/store.py +191 -0
  126. package/core/ice/types.py +97 -0
  127. package/core/im_routing.py +389 -0
  128. package/core/image_input.py +1815 -0
  129. package/core/inbound.py +193 -0
  130. package/core/incidents.py +291 -0
  131. package/core/jobs.py +783 -0
  132. package/core/last_good.py +150 -0
  133. package/core/leaf_md.py +312 -0
  134. package/core/llm_errors.py +227 -0
  135. package/core/llm_retry.py +230 -0
  136. package/core/loop_health.py +221 -0
  137. package/core/mail_config.py +150 -0
  138. package/core/memory/__init__.py +0 -0
  139. package/core/memory/compressor.py +1214 -0
  140. package/core/memory/manager.py +1845 -0
  141. package/core/memory/output_trim.py +98 -0
  142. package/core/memory/session_memory.py +367 -0
  143. package/core/memory/short_term.py +1423 -0
  144. package/core/memory_extract.py +491 -0
  145. package/core/memory_organize.py +667 -0
  146. package/core/memory_store.py +860 -0
  147. package/core/memory_transfer.py +410 -0
  148. package/core/message_history.py +234 -0
  149. package/core/model_capabilities.py +138 -0
  150. package/core/model_configs.py +1388 -0
  151. package/core/modes.py +361 -0
  152. package/core/net_proxy.py +614 -0
  153. package/core/outbound.py +199 -0
  154. package/core/partial_read.py +65 -0
  155. package/core/paths.py +478 -0
  156. package/core/pdf_text_repair.py +545 -0
  157. package/core/persistent_shell.py +294 -0
  158. package/core/pipeline/__init__.py +18 -0
  159. package/core/pipeline/scheduler.py +1700 -0
  160. package/core/pipeline/stage.py +233 -0
  161. package/core/pipeline/stages/__init__.py +1 -0
  162. package/core/pipeline/stages/agent_loop.py +1075 -0
  163. package/core/pipeline/stages/group_reply.py +598 -0
  164. package/core/pipeline/stages/post_process.py +141 -0
  165. package/core/pipeline/stages/pre_process.py +3471 -0
  166. package/core/plan.py +688 -0
  167. package/core/plugin_packages.py +166 -0
  168. package/core/program_discipline.py +192 -0
  169. package/core/promote.py +166 -0
  170. package/core/prompt_assembler.py +680 -0
  171. package/core/recycle.py +295 -0
  172. package/core/request_snapshot.py +215 -0
  173. package/core/response_language.py +170 -0
  174. package/core/retention.py +203 -0
  175. package/core/retriever.py +97 -0
  176. package/core/rg.py +255 -0
  177. package/core/security.py +1544 -0
  178. package/core/services.py +188 -0
  179. package/core/session_date.py +98 -0
  180. package/core/session_key.py +81 -0
  181. package/core/session_model.py +230 -0
  182. package/core/session_pool.py +441 -0
  183. package/core/session_recap.py +181 -0
  184. package/core/session_workspace.py +362 -0
  185. package/core/settings_baseline.py +203 -0
  186. package/core/settings_transfer.py +497 -0
  187. package/core/shell.py +1771 -0
  188. package/core/side_call.py +130 -0
  189. package/core/skill_doctor.py +766 -0
  190. package/core/skill_factory.py +391 -0
  191. package/core/skill_guidance.py +346 -0
  192. package/core/skill_index.py +404 -0
  193. package/core/skill_load_report.py +47 -0
  194. package/core/skill_settings.py +262 -0
  195. package/core/skill_sources.py +313 -0
  196. package/core/state_registry.py +1236 -0
  197. package/core/steer.py +97 -0
  198. package/core/subagent.py +559 -0
  199. package/core/subagent_defs.py +200 -0
  200. package/core/subagent_model.py +114 -0
  201. package/core/summarizer.py +344 -0
  202. package/core/task_events.py +95 -0
  203. package/core/task_tool.py +148 -0
  204. package/core/tasks_notify.py +404 -0
  205. package/core/tiers.py +666 -0
  206. package/core/todos.py +230 -0
  207. package/core/token_calibrator.py +173 -0
  208. package/core/tokenizer.py +77 -0
  209. package/core/tool_names.py +61 -0
  210. package/core/tool_outcome.py +108 -0
  211. package/core/tool_output_kind.py +185 -0
  212. package/core/tool_permission.py +398 -0
  213. package/core/tool_program.py +317 -0
  214. package/core/tool_program_child.py +78 -0
  215. package/core/touched_files.py +141 -0
  216. package/core/trace.py +170 -0
  217. package/core/unlock.py +138 -0
  218. package/core/update_tui.py +158 -0
  219. package/core/updater.py +1463 -0
  220. package/core/version.py +14 -0
  221. package/core/walk_scope.py +207 -0
  222. package/core/web_cache.py +152 -0
  223. package/core/window_estimate.py +298 -0
  224. package/core/workflow.py +282 -0
  225. package/core/workspace.py +3189 -0
  226. package/core/worktree.py +115 -0
  227. package/crannia_tray.py +278 -0
  228. package/creators/models.json +394 -0
  229. package/data/settings.example.json +67 -0
  230. package/licenses/GPL-3.0.txt +619 -0
  231. package/licenses/LGPL-2.1.txt +502 -0
  232. package/licenses/LGPL-3.0.txt +165 -0
  233. package/licenses/MIT-chat-on-wechat.txt +19 -0
  234. package/licenses/MIT-deepseek-harness.txt +21 -0
  235. package/licenses/MPL-2.0.txt +373 -0
  236. package/licenses/Molio-LICENSE.txt +44 -0
  237. package/locales/en.json +1762 -0
  238. package/main.py +154 -0
  239. package/mcpx/__init__.py +14 -0
  240. package/mcpx/bridge.py +156 -0
  241. package/mcpx/client.py +546 -0
  242. package/mcpx/manager.py +522 -0
  243. package/mcpx/servers/__init__.py +22 -0
  244. package/mcpx/servers/web_search.py +943 -0
  245. package/package.json +38 -5
  246. package/providers/__init__.py +0 -0
  247. package/providers/anthropic/__init__.py +1 -0
  248. package/providers/anthropic/client.py +772 -0
  249. package/providers/anthropic/manifest.yaml +16 -0
  250. package/providers/azure/__init__.py +1 -0
  251. package/providers/azure/client.py +2 -0
  252. package/providers/azure/manifest.yaml +16 -0
  253. package/providers/base.py +1080 -0
  254. package/providers/cost_table.json +3779 -0
  255. package/providers/deepseek/__init__.py +1 -0
  256. package/providers/deepseek/client.py +20 -0
  257. package/providers/deepseek/manifest.yaml +16 -0
  258. package/providers/factory.py +136 -0
  259. package/providers/gemini/__init__.py +1 -0
  260. package/providers/gemini/client.py +2 -0
  261. package/providers/gemini/manifest.yaml +16 -0
  262. package/providers/grok/__init__.py +1 -0
  263. package/providers/grok/client.py +2 -0
  264. package/providers/grok/manifest.yaml +16 -0
  265. package/providers/hunyuan/__init__.py +1 -0
  266. package/providers/hunyuan/client.py +2 -0
  267. package/providers/hunyuan/manifest.yaml +16 -0
  268. package/providers/key_rotation.py +114 -0
  269. package/providers/lmstudio/__init__.py +1 -0
  270. package/providers/lmstudio/client.py +2 -0
  271. package/providers/lmstudio/manifest.yaml +14 -0
  272. package/providers/metadata.py +80 -0
  273. package/providers/minimax/__init__.py +1 -0
  274. package/providers/minimax/client.py +2 -0
  275. package/providers/minimax/manifest.yaml +16 -0
  276. package/providers/model_capabilities.json +6665 -0
  277. package/providers/moonshot/__init__.py +1 -0
  278. package/providers/moonshot/client.py +12 -0
  279. package/providers/moonshot/manifest.yaml +16 -0
  280. package/providers/ollama/__init__.py +1 -0
  281. package/providers/ollama/client.py +2 -0
  282. package/providers/ollama/manifest.yaml +16 -0
  283. package/providers/openai/__init__.py +1 -0
  284. package/providers/openai/client.py +13 -0
  285. package/providers/openai/manifest.yaml +16 -0
  286. package/providers/openai_compat.py +1010 -0
  287. package/providers/openrouter/__init__.py +1 -0
  288. package/providers/openrouter/client.py +2 -0
  289. package/providers/openrouter/manifest.yaml +16 -0
  290. package/providers/qwen/__init__.py +1 -0
  291. package/providers/qwen/client.py +2 -0
  292. package/providers/qwen/manifest.yaml +16 -0
  293. package/providers/rate_limiter.py +144 -0
  294. package/providers/siliconflow/__init__.py +1 -0
  295. package/providers/siliconflow/client.py +2 -0
  296. package/providers/siliconflow/manifest.yaml +16 -0
  297. package/providers/validation.py +171 -0
  298. package/providers/volcengine/__init__.py +1 -0
  299. package/providers/volcengine/client.py +2 -0
  300. package/providers/volcengine/manifest.yaml +16 -0
  301. package/providers/window_table.json +8909 -0
  302. package/providers/zhipu/__init__.py +1 -0
  303. package/providers/zhipu/client.py +2 -0
  304. package/providers/zhipu/manifest.yaml +16 -0
  305. package/requirements.txt +51 -0
  306. package/sbom.json +4413 -0
  307. package/skills/__init__.py +0 -0
  308. package/skills/entertainment/SKILL.md +35 -0
  309. package/skills/entertainment/__init__.py +1 -0
  310. package/skills/entertainment/handler.py +91 -0
  311. package/skills/entertainment/manifest.yaml +26 -0
  312. package/skills/file_parser/GUIDANCE.md +10 -0
  313. package/skills/file_parser/SKILL.md +62 -0
  314. package/skills/file_parser/__init__.py +0 -0
  315. package/skills/file_parser/handler.py +2726 -0
  316. package/skills/file_parser/manifest.yaml +667 -0
  317. package/skills/github/SKILL.md +32 -0
  318. package/skills/github/__init__.py +1 -0
  319. package/skills/github/handler.py +338 -0
  320. package/skills/github/manifest.yaml +210 -0
  321. package/skills/mail_parser/SKILL.md +68 -0
  322. package/skills/mail_parser/__init__.py +1 -0
  323. package/skills/mail_parser/handler.py +806 -0
  324. package/skills/mail_parser/manifest.yaml +320 -0
  325. package/skills/media_gen/GUIDANCE.md +19 -0
  326. package/skills/media_gen/SKILL.md +43 -0
  327. package/skills/media_gen/__init__.py +1 -0
  328. package/skills/media_gen/handler.py +430 -0
  329. package/skills/media_gen/manifest.yaml +93 -0
  330. package/skills/office_parser/GUIDANCE.md +20 -0
  331. package/skills/office_parser/SKILL.md +82 -0
  332. package/skills/office_parser/__init__.py +0 -0
  333. package/skills/office_parser/_excel_io.py +420 -0
  334. package/skills/office_parser/cell_validation.py +127 -0
  335. package/skills/office_parser/excel_query.py +566 -0
  336. package/skills/office_parser/excel_tools.py +2267 -0
  337. package/skills/office_parser/excel_transform.py +936 -0
  338. package/skills/office_parser/handler.py +3219 -0
  339. package/skills/office_parser/layout_spec.py +243 -0
  340. package/skills/office_parser/manifest.yaml +3060 -0
  341. package/skills/office_parser/ppt_tools.py +697 -0
  342. package/skills/office_parser/pptx_export/__init__.py +20 -0
  343. package/skills/office_parser/pptx_export/console_encoding.py +27 -0
  344. package/skills/office_parser/pptx_export/resource_paths.py +88 -0
  345. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -0
  346. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -0
  347. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -0
  348. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -0
  349. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -0
  350. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -0
  351. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -0
  352. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -0
  353. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -0
  354. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -0
  355. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -0
  356. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -0
  357. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -0
  358. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -0
  359. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -0
  360. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +770 -0
  361. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -0
  362. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -0
  363. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -0
  364. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -0
  365. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -0
  366. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -0
  367. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -0
  368. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -0
  369. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -0
  370. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -0
  371. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +21 -0
  372. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -0
  373. package/skills/office_parser/references/layout_library.md +816 -0
  374. package/skills/office_parser/references/ppt-master/LICENSE +21 -0
  375. package/skills/office_parser/references/ppt-master/SKILL.md +765 -0
  376. package/skills/office_parser/references/ppt-master/SOURCE.md +102 -0
  377. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -0
  378. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -0
  379. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -0
  380. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -0
  381. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -0
  382. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -0
  383. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -0
  384. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -0
  385. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -0
  386. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -0
  387. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -0
  388. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -0
  389. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -0
  390. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -0
  391. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -0
  392. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -0
  393. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -0
  394. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -0
  395. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -0
  396. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -0
  397. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -0
  398. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -0
  399. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -0
  400. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -0
  401. package/skills/office_parser/references/ppt-master/workflows/beautify-pptx.md +278 -0
  402. package/skills/office_parser/references/ppt-master/workflows/customize-animations.md +287 -0
  403. package/skills/office_parser/references/ppt-master/workflows/native-enhance-pptx.md +323 -0
  404. package/skills/office_parser/references/ppt-master/workflows/template-fill-pptx.md +364 -0
  405. package/skills/office_parser/references/ppt-master/workflows/visual-review.md +190 -0
  406. package/skills/office_parser/references/spec_lock.md +235 -0
  407. package/skills/office_parser/session.py +274 -0
  408. package/skills/office_parser/soffice.py +68 -0
  409. package/skills/office_parser/word_tools.py +2909 -0
  410. package/skills/ppt-master/SKILL.md +47 -0
  411. package/tui/crannia.cmd +134 -0
  412. package/tui/crannia_tui/__init__.py +1 -0
  413. package/tui/crannia_tui/__main__.py +223 -0
  414. package/tui/crannia_tui/app.py +1318 -0
  415. package/tui/crannia_tui/app.tcss +153 -0
  416. package/tui/crannia_tui/approval.py +85 -0
  417. package/tui/crannia_tui/backend.py +279 -0
  418. package/tui/crannia_tui/channel.py +472 -0
  419. package/tui/crannia_tui/client.py +125 -0
  420. package/tui/crannia_tui/clipboard.py +62 -0
  421. package/tui/crannia_tui/commands.py +65 -0
  422. package/tui/crannia_tui/doctor.py +304 -0
  423. package/tui/crannia_tui/events.py +84 -0
  424. package/tui/crannia_tui/headless.py +152 -0
  425. package/tui/crannia_tui/i18n.py +164 -0
  426. package/tui/crannia_tui/locales/en.json +263 -0
  427. package/tui/crannia_tui/outcome.py +62 -0
  428. package/tui/crannia_tui/paths.py +181 -0
  429. package/tui/crannia_tui/probe.py +53 -0
  430. package/tui/crannia_tui/profile.py +169 -0
  431. package/tui/crannia_tui/render.py +209 -0
  432. package/tui/crannia_tui/settings.py +134 -0
  433. package/tui/crannia_tui/setup.py +380 -0
  434. package/tui/crannia_tui/term.py +116 -0
  435. package/tui/crannia_tui/ui.py +1236 -0
  436. package/tui/crannia_tui/update.py +389 -0
  437. package/vendor/ripgrep/COPYING.txt +3 -0
  438. package/vendor/ripgrep/LICENSE-MIT.txt +21 -0
  439. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -0
  440. package/vendor/ripgrep/README.md +51 -0
  441. package/vendor/ripgrep/UNLICENSE.txt +24 -0
  442. package/vendor/ripgrep/package-source.json +19 -0
  443. package/vendor/ripgrep/win32-x64/rg.exe +0 -0
  444. package/web/__init__.py +0 -0
  445. package/web/__main__.py +77 -0
  446. package/web/server.py +8585 -0
  447. package/web/static/audio/safety-mode.mp3 +0 -0
  448. package/web/static/img/channel-dingtalk.png +0 -0
  449. package/web/static/img/channel-feishu.png +0 -0
  450. package/web/static/img/channel-qq.svg +1 -0
  451. package/web/static/img/channel-telegram.svg +1 -0
  452. package/web/static/img/channel-wechat.svg +1 -0
  453. package/web/static/img/logo.svg +12 -0
  454. package/web/static/img/provider-anthropic.svg +1 -0
  455. package/web/static/img/provider-azure.svg +1 -0
  456. package/web/static/img/provider-deepseek.svg +1 -0
  457. package/web/static/img/provider-gemini.svg +1 -0
  458. package/web/static/img/provider-grok.svg +1 -0
  459. package/web/static/img/provider-hunyuan.svg +1 -0
  460. package/web/static/img/provider-lmstudio.svg +1 -0
  461. package/web/static/img/provider-minimax.svg +1 -0
  462. package/web/static/img/provider-moonshot.svg +1 -0
  463. package/web/static/img/provider-ollama.svg +1 -0
  464. package/web/static/img/provider-openai.svg +1 -0
  465. package/web/static/img/provider-openrouter.svg +1 -0
  466. package/web/static/img/provider-qwen.svg +1 -0
  467. package/web/static/img/provider-siliconflow.svg +1 -0
  468. package/web/static/img/provider-volcengine.svg +1 -0
  469. package/web/static/img/provider-zhipu.svg +1 -0
  470. package/web/static/style.css +2029 -0
  471. package/web/templates/base.html +985 -0
  472. package/web/templates/chat.html +2462 -0
  473. package/web/templates/dashboard.html +821 -0
  474. package/web/templates/logs.html +49 -0
  475. package/web/templates/models.html +46 -0
  476. package/web/templates/security.html +2760 -0
  477. package/web/templates/skills.html +891 -0
@@ -0,0 +1,2490 @@
1
+ """SVG element converters: rect, circle, line, path, polygon, polyline, text, image, ellipse."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import math
7
+ import re
8
+ import base64
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import unquote_to_bytes
12
+ from xml.etree import ElementTree as ET
13
+
14
+ from ...resource_paths import resolve_external_image_reference
15
+
16
+ from .context import ConvertContext, ShapeResult
17
+ from .utils import (
18
+ SVG_NS, XLINK_NS, ANGLE_UNIT, FONT_PX_TO_HUNDREDTHS_PT, DASH_PRESETS,
19
+ px_to_emu, _f, _get_attr, parse_svg_length,
20
+ svg_length_x, svg_length_y, svg_length_size,
21
+ ctx_x, ctx_y, ctx_w, ctx_h,
22
+ rect_to_dml_xfrm,
23
+ parse_hex_color, resolve_url_id, get_effective_filter_id,
24
+ parse_inline_style, parse_font_family, is_cjk_char, estimate_text_width,
25
+ detect_text_lang, resolve_text_run_fonts,
26
+ matrix_multiply, parse_transform_matrix, transform_point, _xml_escape,
27
+ )
28
+ from .styles import (
29
+ build_solid_fill, build_gradient_fill,
30
+ build_fill_xml, build_stroke_xml, build_effect_xml, classify_filter_effect,
31
+ get_fill_opacity, get_stroke_opacity,
32
+ )
33
+ from .paths import (
34
+ PathCommand, parse_svg_path, svg_path_to_absolute,
35
+ normalize_path_commands, path_commands_to_drawingml,
36
+ )
37
+
38
+
39
+ def _resolve_external_image(svg_dir: Path, href: str) -> Path:
40
+ """Resolve a non-data-URI image href to a file on disk.
41
+
42
+ Search order: next to the SVG (`svg_output/`), the project root, the
43
+ project's `images/` (the single runtime image pool — template-bundled
44
+ bitmaps plus AI / web / user images all live here), then `templates/`
45
+ (legacy flat-copied template assets). Raises `FileNotFoundError` if none
46
+ of these exist.
47
+ """
48
+ candidate = resolve_external_image_reference(svg_dir, href)
49
+ if candidate is not None:
50
+ return candidate
51
+ raise FileNotFoundError(f'External image not found: {href}')
52
+
53
+
54
+ def _decode_data_image_uri(href: str) -> tuple[str, bytes] | None:
55
+ """Decode SVG image data URIs, including URL-encoded non-base64 payloads."""
56
+ if not href.startswith('data:') or ',' not in href:
57
+ return None
58
+
59
+ header, payload = href.split(',', 1)
60
+ match = re.match(r'data:image/([^;,]+)', header, flags=re.IGNORECASE)
61
+ if not match:
62
+ return None
63
+
64
+ img_format = match.group(1).lower()
65
+ if img_format == 'svg+xml':
66
+ img_format = 'svg'
67
+ elif img_format == 'jpeg':
68
+ img_format = 'jpg'
69
+
70
+ is_base64 = any(
71
+ part.strip().lower() == 'base64'
72
+ for part in header.split(';')[1:]
73
+ )
74
+ if is_base64:
75
+ img_data = base64.b64decode(payload)
76
+ else:
77
+ img_data = unquote_to_bytes(payload)
78
+ return img_format, img_data
79
+
80
+
81
+ def _wrap_shape(
82
+ shape_id: int, name: str,
83
+ off_x: int, off_y: int,
84
+ ext_cx: int, ext_cy: int,
85
+ geom_xml: str, fill_xml: str, stroke_xml: str,
86
+ effect_xml: str = '', extra_xml: str = '',
87
+ rot: int = 0,
88
+ xfrm_attr: str = '',
89
+ ) -> str:
90
+ """Wrap DrawingML content into a <p:sp> shape element."""
91
+ rot_attr = f' rot="{rot}"' if rot else ''
92
+ xfrm_attrs = f'{xfrm_attr}{rot_attr}'
93
+ return f'''<p:sp>
94
+ <p:nvSpPr>
95
+ <p:cNvPr id="{shape_id}" name="{_xml_escape(name)}"/>
96
+ <p:cNvSpPr/><p:nvPr/>
97
+ </p:nvSpPr>
98
+ <p:spPr>
99
+ <a:xfrm{xfrm_attrs}><a:off x="{off_x}" y="{off_y}"/><a:ext cx="{ext_cx}" cy="{ext_cy}"/></a:xfrm>
100
+ {geom_xml}
101
+ {fill_xml}
102
+ {stroke_xml}
103
+ {effect_xml}
104
+ </p:spPr>
105
+ {extra_xml}
106
+ </p:sp>'''
107
+
108
+
109
+ def _context_transform_matrix(ctx: ConvertContext) -> tuple[float, float, float, float, float, float]:
110
+ """Return the current context as a full SVG affine matrix."""
111
+ if ctx.use_transform_matrix:
112
+ return ctx.transform_matrix
113
+ return (
114
+ ctx.scale_x, 0.0,
115
+ 0.0, ctx.scale_y,
116
+ ctx.translate_x, ctx.translate_y,
117
+ )
118
+
119
+
120
+ def _combined_transform_matrix(
121
+ ctx: ConvertContext,
122
+ transform: str | None,
123
+ ) -> tuple[float, float, float, float, float, float]:
124
+ """Compose context transform with an element-level transform attribute."""
125
+ matrix = _context_transform_matrix(ctx)
126
+ if transform:
127
+ matrix = matrix_multiply(matrix, parse_transform_matrix(transform))
128
+ return matrix
129
+
130
+
131
+ def _uses_full_transform(ctx: ConvertContext, transform: str | None) -> bool:
132
+ return ctx.use_transform_matrix or bool(transform)
133
+
134
+
135
+ def _transformed_point(
136
+ ctx: ConvertContext,
137
+ x: float,
138
+ y: float,
139
+ transform: str | None,
140
+ ) -> tuple[float, float]:
141
+ if _uses_full_transform(ctx, transform):
142
+ return transform_point(_combined_transform_matrix(ctx, transform), x, y)
143
+ return ctx_x(x, ctx), ctx_y(y, ctx)
144
+
145
+
146
+ def _shape_xfrm_from_svg_rect(
147
+ ctx: ConvertContext,
148
+ raw_x: float,
149
+ raw_y: float,
150
+ raw_w: float,
151
+ raw_h: float,
152
+ resolved_x: float,
153
+ resolved_y: float,
154
+ resolved_w: float,
155
+ resolved_h: float,
156
+ transform: str | None,
157
+ ) -> tuple[str, int, int, int, int, tuple[int, int, int, int]]:
158
+ """Build DrawingML xfrm data for an SVG rectangle-like element."""
159
+ if _uses_full_transform(ctx, transform):
160
+ return rect_to_dml_xfrm(
161
+ raw_x, raw_y, raw_w, raw_h,
162
+ _combined_transform_matrix(ctx, transform),
163
+ )
164
+
165
+ off_x = px_to_emu(resolved_x)
166
+ off_y = px_to_emu(resolved_y)
167
+ ext_cx = px_to_emu(resolved_w)
168
+ ext_cy = px_to_emu(resolved_h)
169
+ return '', off_x, off_y, ext_cx, ext_cy, (off_x, off_y, off_x + ext_cx, off_y + ext_cy)
170
+
171
+
172
+ def _transform_path_commands(
173
+ commands: list[PathCommand],
174
+ matrix: tuple[float, float, float, float, float, float],
175
+ ) -> list[PathCommand]:
176
+ """Apply an affine transform to normalized M/L/C/Z path commands."""
177
+ transformed: list[PathCommand] = []
178
+ for cmd in commands:
179
+ if cmd.cmd in ('M', 'L'):
180
+ x, y = transform_point(matrix, cmd.args[0], cmd.args[1])
181
+ transformed.append(PathCommand(cmd.cmd, [x, y]))
182
+ elif cmd.cmd == 'C':
183
+ args: list[float] = []
184
+ for i in range(0, 6, 2):
185
+ x, y = transform_point(matrix, cmd.args[i], cmd.args[i + 1])
186
+ args.extend([x, y])
187
+ transformed.append(PathCommand(cmd.cmd, args))
188
+ else:
189
+ transformed.append(cmd)
190
+ return transformed
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # rect
195
+ # ---------------------------------------------------------------------------
196
+
197
+ # Cubic-Bézier control distance for approximating a quarter circle / ellipse.
198
+ # Distance from corner to control point along the tangent, expressed as a
199
+ # fraction of the radius. Standard "magic number" for a 90° arc (max error
200
+ # ~0.027% of the radius).
201
+ _BEZIER_QUARTER_K = 0.5522847498
202
+
203
+
204
+ def _build_preset_geom_from_meta(elem: ET.Element) -> str | None:
205
+ """Build native DrawingML preset geometry from SVG metadata."""
206
+ prst = elem.get('data-pptx-prst')
207
+ if prst != 'round2SameRect':
208
+ return None
209
+
210
+ def _adj_attr(name: str, default: int) -> int:
211
+ try:
212
+ return int(float(elem.get(name, str(default))))
213
+ except ValueError:
214
+ return default
215
+
216
+ adj1 = max(0, min(100000, _adj_attr('data-pptx-adj1', 16667)))
217
+ adj2 = max(0, min(100000, _adj_attr('data-pptx-adj2', 0)))
218
+ return (
219
+ '<a:prstGeom prst="round2SameRect">'
220
+ '<a:avLst>'
221
+ f'<a:gd name="adj1" fmla="val {adj1}"/>'
222
+ f'<a:gd name="adj2" fmla="val {adj2}"/>'
223
+ '</a:avLst>'
224
+ '</a:prstGeom>'
225
+ )
226
+
227
+
228
+ def _build_round_rect_custgeom(w: float, h: float, rx: float, ry: float) -> str:
229
+ """Build a DrawingML `custGeom` for a rectangle with elliptical corners.
230
+
231
+ Used when `<rect>` has rx ≠ ry, which DrawingML's preset `roundRect`
232
+ cannot express (the preset takes a single `adj` shared by all four
233
+ corners and is implicitly symmetric). Each 90° elliptical arc is
234
+ approximated by one cubic Bézier — within 0.03% of the true ellipse, far
235
+ below any visible threshold at slide resolution.
236
+
237
+ Trade-off vs. the symmetric prstGeom roundRect path: this geometry
238
+ is custom, so PowerPoint's yellow corner-radius handle is gone and the
239
+ shape can no longer be retuned in-place. That matches the underlying
240
+ reality — rx ≠ ry has no single "radius" to drag — and remains far
241
+ better than the previous behaviour (silently dropping all corners and
242
+ rendering a hard rectangle).
243
+
244
+ Args:
245
+ w, h: Pixel dimensions of the rectangle (post ctx-scale).
246
+ rx, ry: Pixel corner radii along x and y. Will be clamped to half
247
+ of w / h respectively per the SVG spec.
248
+
249
+ Returns:
250
+ A complete `<a:custGeom>...</a:custGeom>` XML string. Coordinates
251
+ are emitted in EMU within a path-local coordinate system whose
252
+ `w` / `h` equal the rectangle's pixel-converted dimensions.
253
+ """
254
+ # Clamp radii (SVG spec): rx > w/2 collapses to a half-circle end.
255
+ rx = min(max(rx, 0.0), w / 2)
256
+ ry = min(max(ry, 0.0), h / 2)
257
+
258
+ width_emu = px_to_emu(w)
259
+ height_emu = px_to_emu(h)
260
+ rx_emu = px_to_emu(rx)
261
+ ry_emu = px_to_emu(ry)
262
+
263
+ cx_off = int(round(rx_emu * _BEZIER_QUARTER_K))
264
+ cy_off = int(round(ry_emu * _BEZIER_QUARTER_K))
265
+
266
+ def pt(x: int, y: int) -> str:
267
+ return f'<a:pt x="{x}" y="{y}"/>'
268
+
269
+ def cubic(c1: tuple[int, int], c2: tuple[int, int], end: tuple[int, int]) -> str:
270
+ return (
271
+ f'<a:cubicBezTo>{pt(*c1)}{pt(*c2)}{pt(*end)}</a:cubicBezTo>'
272
+ )
273
+
274
+ # Path traversed clockwise, starting just past the top-left corner.
275
+ parts = [
276
+ f'<a:moveTo>{pt(rx_emu, 0)}</a:moveTo>',
277
+ f'<a:lnTo>{pt(width_emu - rx_emu, 0)}</a:lnTo>',
278
+ # Top-right corner: (W-Rx, 0) → (W, Ry)
279
+ cubic(
280
+ (width_emu - rx_emu + cx_off, 0),
281
+ (width_emu, ry_emu - cy_off),
282
+ (width_emu, ry_emu),
283
+ ),
284
+ f'<a:lnTo>{pt(width_emu, height_emu - ry_emu)}</a:lnTo>',
285
+ # Bottom-right corner: (W, H-Ry) → (W-Rx, H)
286
+ cubic(
287
+ (width_emu, height_emu - ry_emu + cy_off),
288
+ (width_emu - rx_emu + cx_off, height_emu),
289
+ (width_emu - rx_emu, height_emu),
290
+ ),
291
+ f'<a:lnTo>{pt(rx_emu, height_emu)}</a:lnTo>',
292
+ # Bottom-left corner: (Rx, H) → (0, H-Ry)
293
+ cubic(
294
+ (rx_emu - cx_off, height_emu),
295
+ (0, height_emu - ry_emu + cy_off),
296
+ (0, height_emu - ry_emu),
297
+ ),
298
+ f'<a:lnTo>{pt(0, ry_emu)}</a:lnTo>',
299
+ # Top-left corner: (0, Ry) → (Rx, 0)
300
+ cubic(
301
+ (0, ry_emu - cy_off),
302
+ (rx_emu - cx_off, 0),
303
+ (rx_emu, 0),
304
+ ),
305
+ '<a:close/>',
306
+ ]
307
+
308
+ path_xml = '\n'.join(parts)
309
+ return (
310
+ '<a:custGeom>'
311
+ '<a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>'
312
+ '<a:rect l="l" t="t" r="r" b="b"/>'
313
+ f'<a:pathLst><a:path w="{width_emu}" h="{height_emu}">'
314
+ f'\n{path_xml}\n'
315
+ '</a:path></a:pathLst>'
316
+ '</a:custGeom>'
317
+ )
318
+
319
+
320
+ def convert_rect(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
321
+ """Convert SVG <rect> to DrawingML shape.
322
+
323
+ Symmetric rounded corners (rx == ry) are emitted as prstGeom roundRect
324
+ so PowerPoint treats them as a native rounded-rectangle shape: the yellow
325
+ adjustment handle stays draggable, and "Reset Picture / Shape" works as
326
+ expected. Elliptical corners (rx != ry) fall back to plain rect geometry
327
+ for now — current corpora contain none, but the branch keeps callers from
328
+ silently producing distorted custom geometry if one ever appears.
329
+ """
330
+ raw_x = svg_length_x(elem.get('x'), ctx)
331
+ raw_y = svg_length_y(elem.get('y'), ctx)
332
+ raw_w = svg_length_x(elem.get('width'), ctx)
333
+ raw_h = svg_length_y(elem.get('height'), ctx)
334
+ x = ctx_x(raw_x, ctx)
335
+ y = ctx_y(raw_y, ctx)
336
+ w = ctx_w(raw_w, ctx)
337
+ h = ctx_h(raw_h, ctx)
338
+
339
+ if w <= 0 or h <= 0:
340
+ return None
341
+
342
+ # SVG spec: when only one of rx/ry is specified, the other inherits its
343
+ # value. Real-world svg_output decks always write only `rx`, so ry must
344
+ # be inferred to keep round corners from collapsing to zero on one axis.
345
+ rx_attr = elem.get('rx')
346
+ ry_attr = elem.get('ry')
347
+ rx_raw = svg_length_x(rx_attr, ctx) if rx_attr is not None else 0.0
348
+ ry_raw = svg_length_y(ry_attr, ctx) if ry_attr is not None else 0.0
349
+ if rx_attr is not None and ry_attr is None:
350
+ ry_raw = rx_raw
351
+ elif ry_attr is not None and rx_attr is None:
352
+ rx_raw = ry_raw
353
+ rx = rx_raw * ctx.scale_x
354
+ ry = ry_raw * ctx.scale_y
355
+
356
+ fill_op = get_fill_opacity(elem, ctx)
357
+ stroke_op = get_stroke_opacity(elem, ctx)
358
+ fill = build_fill_xml(elem, ctx, fill_op)
359
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
360
+
361
+ effect = ''
362
+ filt_id = get_effective_filter_id(elem, ctx)
363
+ if filt_id and filt_id in ctx.defs:
364
+ effect = build_effect_xml(ctx.defs[filt_id])
365
+
366
+ transform = elem.get('transform')
367
+
368
+ if rx > 0 and abs(rx - ry) < 0.5:
369
+ # Symmetric corners → native PowerPoint rounded rectangle. adj is
370
+ # the corner radius as a fraction of the shorter side, in 1/1000-
371
+ # percent units, capped at 50000 (= radius equals half the shorter
372
+ # side, i.e. capsule end).
373
+ short_side = min(w, h)
374
+ radius = min(rx, short_side / 2)
375
+ adj = max(0, min(50000, int(round(radius / short_side * 100000))))
376
+ geom = (
377
+ '<a:prstGeom prst="roundRect">'
378
+ f'<a:avLst><a:gd name="adj" fmla="val {adj}"/></a:avLst>'
379
+ '</a:prstGeom>'
380
+ )
381
+ elif rx > 0 or ry > 0:
382
+ # Asymmetric corners (rx != ry) → DrawingML has no preset for
383
+ # elliptical-corner rectangles, so emit a custGeom with one cubic
384
+ # Bézier per 90° arc. We lose the prstGeom roundRect adjustment
385
+ # handle, but symmetric and asymmetric cases now both render with
386
+ # rounded corners instead of one of them silently flattening to
387
+ # a hard rectangle.
388
+ geom = _build_round_rect_custgeom(w, h, rx, ry)
389
+ else:
390
+ geom = '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
391
+
392
+ shape_id = ctx.next_id()
393
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _shape_xfrm_from_svg_rect(
394
+ ctx,
395
+ raw_x,
396
+ raw_y,
397
+ raw_w,
398
+ raw_h,
399
+ x,
400
+ y,
401
+ w,
402
+ h,
403
+ transform,
404
+ )
405
+ return ShapeResult(
406
+ xml=_wrap_shape(
407
+ shape_id, f'Rectangle {shape_id}',
408
+ off_x, off_y, ext_cx, ext_cy,
409
+ geom, fill, stroke, effect, xfrm_attr=xfrm_attr,
410
+ ),
411
+ bounds_emu=bounds_emu,
412
+ )
413
+
414
+
415
+ # ---------------------------------------------------------------------------
416
+ # circle (including donut-chart arc segments)
417
+ # ---------------------------------------------------------------------------
418
+
419
+ def _build_arc_ring_path(
420
+ cx: float, cy: float, r: float,
421
+ stroke_width: float,
422
+ dash_len: float, dash_offset: float,
423
+ rotate_deg: float,
424
+ sx: float, sy: float,
425
+ ) -> tuple[str, int, int, int, int]:
426
+ """Build a filled annular-sector (donut segment) as DrawingML custGeom.
427
+
428
+ SVG donut charts use stroke-dasharray on a circle to draw arc segments.
429
+ DrawingML cannot reproduce this, so we convert each arc segment into a
430
+ filled ring shape (outer arc -> line -> inner arc -> close).
431
+
432
+ Returns:
433
+ (geom_xml, min_x_emu, min_y_emu, w_emu, h_emu).
434
+ """
435
+ circumference = 2 * math.pi * r
436
+ if circumference <= 0:
437
+ return '', 0, 0, 0, 0
438
+
439
+ start_frac = -dash_offset / circumference
440
+ end_frac = start_frac + dash_len / circumference
441
+
442
+ start_angle = start_frac * 2 * math.pi + math.radians(rotate_deg)
443
+ end_angle = end_frac * 2 * math.pi + math.radians(rotate_deg)
444
+
445
+ half_sw = stroke_width / 2
446
+ r_outer = r + half_sw
447
+ r_inner = r - half_sw
448
+
449
+ num_segments = max(16, int(abs(end_angle - start_angle) / (math.pi / 32)))
450
+ angles = [
451
+ start_angle + (end_angle - start_angle) * i / num_segments
452
+ for i in range(num_segments + 1)
453
+ ]
454
+
455
+ outer_pts = [(cx + r_outer * math.sin(a), cy - r_outer * math.cos(a)) for a in angles]
456
+ inner_pts = [(cx + r_inner * math.sin(a), cy - r_inner * math.cos(a)) for a in reversed(angles)]
457
+
458
+ all_pts = [(px * sx, py * sy) for px, py in outer_pts + inner_pts]
459
+
460
+ xs = [p[0] for p in all_pts]
461
+ ys = [p[1] for p in all_pts]
462
+ min_x, max_x = min(xs), max(xs)
463
+ min_y, max_y = min(ys), max(ys)
464
+ width = max_x - min_x
465
+ height = max_y - min_y
466
+
467
+ if width < 0.5 or height < 0.5:
468
+ return '', 0, 0, 0, 0
469
+
470
+ w_emu = px_to_emu(width)
471
+ h_emu = px_to_emu(height)
472
+
473
+ lines: list[str] = []
474
+ for i, (px, py) in enumerate(all_pts):
475
+ lx = px_to_emu(px - min_x)
476
+ ly = px_to_emu(py - min_y)
477
+ if i == 0:
478
+ lines.append(f'<a:moveTo><a:pt x="{lx}" y="{ly}"/></a:moveTo>')
479
+ else:
480
+ lines.append(f'<a:lnTo><a:pt x="{lx}" y="{ly}"/></a:lnTo>')
481
+ lines.append('<a:close/>')
482
+
483
+ path_xml = '\n'.join(lines)
484
+ geom = f'''<a:custGeom>
485
+ <a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>
486
+ <a:rect l="l" t="t" r="r" b="b"/>
487
+ <a:pathLst><a:path w="{w_emu}" h="{h_emu}">
488
+ {path_xml}
489
+ </a:path></a:pathLst>
490
+ </a:custGeom>'''
491
+
492
+ return geom, px_to_emu(min_x), px_to_emu(min_y), w_emu, h_emu
493
+
494
+
495
+ def _is_donut_circle(elem: ET.Element, ctx: ConvertContext) -> bool:
496
+ """Detect if a circle uses stroke-dasharray to simulate an arc segment."""
497
+ dasharray = _get_attr(elem, 'stroke-dasharray', ctx)
498
+ if not dasharray or dasharray == 'none':
499
+ return False
500
+ stroke = _get_attr(elem, 'stroke', ctx)
501
+ if not stroke or stroke == 'none':
502
+ return False
503
+
504
+ sw = svg_length_size(_get_attr(elem, 'stroke-width', ctx), ctx, 0)
505
+ r = svg_length_size(elem.get('r'), ctx, 0)
506
+ if sw <= 0 or r <= 0:
507
+ return False
508
+
509
+ # Standard dash presets are not donut segments
510
+ if dasharray.strip() in DASH_PRESETS:
511
+ return False
512
+
513
+ # Thin strokes relative to radius are decorative dashed rings, not donut arcs.
514
+ # Real donut arcs need sw/r >= 0.15 (e.g. sw=40 on r=100 → 0.40).
515
+ if sw / r < 0.15:
516
+ return False
517
+
518
+ return True
519
+
520
+
521
+ def convert_circle(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
522
+ """Convert SVG <circle> to DrawingML ellipse or donut-arc shape."""
523
+ cx_ = svg_length_x(elem.get('cx'), ctx)
524
+ cy_ = svg_length_y(elem.get('cy'), ctx)
525
+ r = svg_length_size(elem.get('r'), ctx)
526
+
527
+ if r <= 0:
528
+ return None
529
+
530
+ # --- Donut-chart arc segment detection ---
531
+ if _is_donut_circle(elem, ctx):
532
+ dasharray = _get_attr(elem, 'stroke-dasharray', ctx)
533
+ dash_vals = re.split(r'[\s,]+', dasharray.strip())
534
+ dash_len = float(dash_vals[0]) if dash_vals else 0
535
+ dash_offset = svg_length_size(elem.get('stroke-dashoffset'), ctx, 0)
536
+ stroke_width = svg_length_size(_get_attr(elem, 'stroke-width', ctx), ctx, 1)
537
+
538
+ rotate_deg = 0.0
539
+ transform = elem.get('transform', '')
540
+ r_match = re.search(r'rotate\(\s*([-\d.]+)', transform)
541
+ if r_match:
542
+ rotate_deg = float(r_match.group(1))
543
+
544
+ geom, min_x, min_y, w_emu, h_emu = _build_arc_ring_path(
545
+ ctx_x(cx_, ctx) / ctx.scale_x,
546
+ ctx_y(cy_, ctx) / ctx.scale_y,
547
+ r, stroke_width, dash_len, dash_offset, rotate_deg,
548
+ ctx.scale_x, ctx.scale_y,
549
+ )
550
+ if not geom:
551
+ return None
552
+
553
+ # Use the stroke color/gradient as fill for the arc shape
554
+ stroke_val = _get_attr(elem, 'stroke', ctx)
555
+ op = get_fill_opacity(elem, ctx)
556
+ grad_id = resolve_url_id(stroke_val) if stroke_val else None
557
+ if grad_id and grad_id in ctx.defs:
558
+ fill = build_gradient_fill(ctx.defs[grad_id], op)
559
+ elif stroke_val:
560
+ color = parse_hex_color(stroke_val)
561
+ fill = build_solid_fill(color, op) if color else '<a:noFill/>'
562
+ else:
563
+ fill = '<a:noFill/>'
564
+
565
+ stroke_xml = '<a:ln><a:noFill/></a:ln>'
566
+
567
+ effect = ''
568
+ filt_id = get_effective_filter_id(elem, ctx)
569
+ if filt_id and filt_id in ctx.defs:
570
+ effect = build_effect_xml(ctx.defs[filt_id])
571
+
572
+ shape_id = ctx.next_id()
573
+ return ShapeResult(
574
+ xml=_wrap_shape(
575
+ shape_id, f'Arc {shape_id}',
576
+ min_x, min_y, w_emu, h_emu,
577
+ geom, fill, stroke_xml, effect,
578
+ ),
579
+ bounds_emu=(min_x, min_y, min_x + w_emu, min_y + h_emu),
580
+ )
581
+
582
+ # --- Normal circle ---
583
+ transform = elem.get('transform')
584
+ cx_s = ctx_x(cx_, ctx)
585
+ cy_s = ctx_y(cy_, ctx)
586
+ r_x = r * ctx.scale_x
587
+ r_y = r * ctx.scale_y
588
+
589
+ x = cx_s - r_x
590
+ y = cy_s - r_y
591
+ w = r_x * 2
592
+ h = r_y * 2
593
+
594
+ fill_op = get_fill_opacity(elem, ctx)
595
+ stroke_op = get_stroke_opacity(elem, ctx)
596
+ fill = build_fill_xml(elem, ctx, fill_op)
597
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
598
+
599
+ effect = ''
600
+ filt_id = get_effective_filter_id(elem, ctx)
601
+ if filt_id and filt_id in ctx.defs:
602
+ effect = build_effect_xml(ctx.defs[filt_id])
603
+
604
+ geom = '<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>'
605
+
606
+ shape_id = ctx.next_id()
607
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _shape_xfrm_from_svg_rect(
608
+ ctx,
609
+ cx_ - r,
610
+ cy_ - r,
611
+ r * 2,
612
+ r * 2,
613
+ x,
614
+ y,
615
+ w,
616
+ h,
617
+ transform,
618
+ )
619
+ return ShapeResult(
620
+ xml=_wrap_shape(
621
+ shape_id, f'Ellipse {shape_id}',
622
+ off_x, off_y, ext_cx, ext_cy,
623
+ geom, fill, stroke, effect, xfrm_attr=xfrm_attr,
624
+ ),
625
+ bounds_emu=bounds_emu,
626
+ )
627
+
628
+
629
+ # ---------------------------------------------------------------------------
630
+ # line
631
+ # ---------------------------------------------------------------------------
632
+
633
+ def convert_line(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
634
+ """Convert SVG <line> to DrawingML shape.
635
+
636
+ Lines with marker-start / marker-end are converted using the 'line' preset
637
+ geometry (prstGeom prst="line") so that PowerPoint renders native arrow
638
+ heads (headEnd / tailEnd) correctly. Plain lines (no markers) continue to
639
+ use custom geometry which is sufficient and avoids flipH/flipV complexity.
640
+ """
641
+ transform = elem.get('transform')
642
+ x1, y1 = _transformed_point(
643
+ ctx,
644
+ svg_length_x(elem.get('x1'), ctx),
645
+ svg_length_y(elem.get('y1'), ctx),
646
+ transform,
647
+ )
648
+ x2, y2 = _transformed_point(
649
+ ctx,
650
+ svg_length_x(elem.get('x2'), ctx),
651
+ svg_length_y(elem.get('y2'), ctx),
652
+ transform,
653
+ )
654
+
655
+ min_x = min(x1, x2)
656
+ min_y = min(y1, y2)
657
+
658
+ stroke_op = get_stroke_opacity(elem, ctx)
659
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
660
+
661
+ shape_id = ctx.next_id()
662
+ off_x = px_to_emu(min_x)
663
+ off_y = px_to_emu(min_y)
664
+
665
+ # Determine if this line carries arrow markers.
666
+ has_marker = bool(
667
+ _get_attr(elem, 'marker-start', ctx) or
668
+ _get_attr(elem, 'marker-end', ctx)
669
+ )
670
+
671
+ if has_marker:
672
+ # ----------------------------------------------------------------
673
+ # Preset geometry approach: prstGeom prst="line"
674
+ # PowerPoint only renders headEnd / tailEnd on lines whose geometry
675
+ # it can intrinsically understand as a "line" (i.e. preset or
676
+ # connector shapes). Custom geometry shapes silently ignore
677
+ # headEnd / tailEnd in most PowerPoint versions.
678
+ #
679
+ # The "line" preset draws from (0,0) to (w,h).
680
+ # headEnd → placed at the start of the line = (x1, y1)
681
+ # tailEnd → placed at the end of the line = (x2, y2)
682
+ # We set flipH / flipV so that the preset start/end align with the
683
+ # original SVG endpoints:
684
+ # default (no flip) : top-left → bottom-right (x1≤x2, y1≤y2)
685
+ # flipH : top-right → bottom-left (x1>x2, y1≤y2)
686
+ # flipV : bottom-left → top-right (x1≤x2, y1>y2)
687
+ # flipH + flipV : bottom-right → top-left (x1>x2, y1>y2)
688
+ # ----------------------------------------------------------------
689
+ w = abs(x2 - x1)
690
+ h = abs(y2 - y1)
691
+ # DrawingML requires ext cx/cy ≥ 1 EMU
692
+ w_emu = px_to_emu(w) if w > 0 else 1
693
+ h_emu = px_to_emu(h) if h > 0 else 1
694
+
695
+ flip_h = x1 > x2
696
+ flip_v = y1 > y2
697
+ flip_attr = ''
698
+ if flip_h and flip_v:
699
+ flip_attr = ' flipH="1" flipV="1"'
700
+ elif flip_h:
701
+ flip_attr = ' flipH="1"'
702
+ elif flip_v:
703
+ flip_attr = ' flipV="1"'
704
+
705
+ xml = (
706
+ f'<p:sp>'
707
+ f'<p:nvSpPr>'
708
+ f'<p:cNvPr id="{shape_id}" name="{_xml_escape(f"Line {shape_id}")}"/>'
709
+ f'<p:cNvSpPr/><p:nvPr/>'
710
+ f'</p:nvSpPr>'
711
+ f'<p:spPr>'
712
+ f'<a:xfrm{flip_attr}>'
713
+ f'<a:off x="{off_x}" y="{off_y}"/>'
714
+ f'<a:ext cx="{w_emu}" cy="{h_emu}"/>'
715
+ f'</a:xfrm>'
716
+ f'<a:prstGeom prst="line"><a:avLst/></a:prstGeom>'
717
+ f'<a:noFill/>'
718
+ f'{stroke}'
719
+ f'</p:spPr>'
720
+ f'</p:sp>'
721
+ )
722
+ else:
723
+ # ----------------------------------------------------------------
724
+ # Custom geometry (original behaviour) for plain lines.
725
+ # ----------------------------------------------------------------
726
+ w = max(abs(x2 - x1), 1)
727
+ h = max(abs(y2 - y1), 1)
728
+ w_emu = px_to_emu(w)
729
+ h_emu = px_to_emu(h)
730
+
731
+ lx1 = px_to_emu(x1 - min_x)
732
+ ly1 = px_to_emu(y1 - min_y)
733
+ lx2 = px_to_emu(x2 - min_x)
734
+ ly2 = px_to_emu(y2 - min_y)
735
+
736
+ geom = (
737
+ f'<a:custGeom>'
738
+ f'<a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>'
739
+ f'<a:rect l="l" t="t" r="r" b="b"/>'
740
+ f'<a:pathLst><a:path w="{w_emu}" h="{h_emu}">'
741
+ f'<a:moveTo><a:pt x="{lx1}" y="{ly1}"/></a:moveTo>'
742
+ f'<a:lnTo><a:pt x="{lx2}" y="{ly2}"/></a:lnTo>'
743
+ f'</a:path></a:pathLst>'
744
+ f'</a:custGeom>'
745
+ )
746
+ xml = _wrap_shape(
747
+ shape_id, f'Line {shape_id}',
748
+ off_x, off_y, w_emu, h_emu,
749
+ geom, '<a:noFill/>', stroke,
750
+ )
751
+
752
+ return ShapeResult(
753
+ xml=xml,
754
+ bounds_emu=(off_x, off_y, off_x + w_emu, off_y + h_emu),
755
+ )
756
+
757
+
758
+ # ---------------------------------------------------------------------------
759
+ # path
760
+ # ---------------------------------------------------------------------------
761
+
762
+ def convert_path(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
763
+ """Convert SVG <path> to DrawingML custom geometry shape."""
764
+ d = elem.get('d', '')
765
+ if not d:
766
+ return None
767
+
768
+ commands = parse_svg_path(d)
769
+ commands = svg_path_to_absolute(commands)
770
+ commands = normalize_path_commands(commands)
771
+
772
+ transform = elem.get('transform')
773
+ if _uses_full_transform(ctx, transform):
774
+ commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
775
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
776
+ commands, 0, 0, 1.0, 1.0,
777
+ )
778
+ else:
779
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
780
+ commands, ctx.translate_x, ctx.translate_y,
781
+ ctx.scale_x, ctx.scale_y,
782
+ )
783
+
784
+ if not path_xml:
785
+ return None
786
+
787
+ w_emu = px_to_emu(width)
788
+ h_emu = px_to_emu(height)
789
+
790
+ geom = None if _uses_full_transform(ctx, transform) else _build_preset_geom_from_meta(elem)
791
+ if geom is None:
792
+ geom = f'''<a:custGeom>
793
+ <a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>
794
+ <a:rect l="l" t="t" r="r" b="b"/>
795
+ <a:pathLst><a:path w="{w_emu}" h="{h_emu}">
796
+ {path_xml}
797
+ </a:path></a:pathLst>
798
+ </a:custGeom>'''
799
+
800
+ fill_op = get_fill_opacity(elem, ctx)
801
+ stroke_op = get_stroke_opacity(elem, ctx)
802
+ fill = build_fill_xml(elem, ctx, fill_op)
803
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
804
+
805
+ effect = ''
806
+ filt_id = get_effective_filter_id(elem, ctx)
807
+ if filt_id and filt_id in ctx.defs:
808
+ effect = build_effect_xml(ctx.defs[filt_id])
809
+
810
+ shape_id = ctx.next_id()
811
+ off_x = px_to_emu(min_x)
812
+ off_y = px_to_emu(min_y)
813
+ return ShapeResult(
814
+ xml=_wrap_shape(
815
+ shape_id, f'Freeform {shape_id}',
816
+ off_x, off_y, w_emu, h_emu,
817
+ geom, fill, stroke, effect,
818
+ ),
819
+ bounds_emu=(off_x, off_y, off_x + w_emu, off_y + h_emu),
820
+ )
821
+
822
+
823
+ # ---------------------------------------------------------------------------
824
+ # polygon / polyline
825
+ # ---------------------------------------------------------------------------
826
+
827
+ def _parse_points(points_str: str) -> list[tuple[float, float]]:
828
+ """Parse SVG points attribute into a list of (x, y) tuples."""
829
+ nums = re.findall(r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?', points_str)
830
+ if len(nums) < 4:
831
+ return []
832
+ return [(float(nums[i]), float(nums[i + 1])) for i in range(0, len(nums) - 1, 2)]
833
+
834
+
835
+ def convert_polygon(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
836
+ """Convert SVG <polygon> to DrawingML custom geometry shape."""
837
+ points = _parse_points(elem.get('points', ''))
838
+ if not points:
839
+ return None
840
+
841
+ commands = [PathCommand('M', [points[0][0], points[0][1]])]
842
+ for px_, py_ in points[1:]:
843
+ commands.append(PathCommand('L', [px_, py_]))
844
+ commands.append(PathCommand('Z', []))
845
+
846
+ transform = elem.get('transform')
847
+ if _uses_full_transform(ctx, transform):
848
+ commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
849
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
850
+ commands, 0, 0, 1.0, 1.0,
851
+ )
852
+ else:
853
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
854
+ commands, ctx.translate_x, ctx.translate_y,
855
+ ctx.scale_x, ctx.scale_y,
856
+ )
857
+
858
+ if not path_xml:
859
+ return None
860
+
861
+ w_emu = px_to_emu(width)
862
+ h_emu = px_to_emu(height)
863
+
864
+ geom = f'''<a:custGeom>
865
+ <a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>
866
+ <a:rect l="l" t="t" r="r" b="b"/>
867
+ <a:pathLst><a:path w="{w_emu}" h="{h_emu}">
868
+ {path_xml}
869
+ </a:path></a:pathLst>
870
+ </a:custGeom>'''
871
+
872
+ fill_op = get_fill_opacity(elem, ctx)
873
+ stroke_op = get_stroke_opacity(elem, ctx)
874
+ fill = build_fill_xml(elem, ctx, fill_op)
875
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
876
+
877
+ shape_id = ctx.next_id()
878
+ off_x = px_to_emu(min_x)
879
+ off_y = px_to_emu(min_y)
880
+ return ShapeResult(
881
+ xml=_wrap_shape(
882
+ shape_id, f'Polygon {shape_id}',
883
+ off_x, off_y, w_emu, h_emu,
884
+ geom, fill, stroke,
885
+ ),
886
+ bounds_emu=(off_x, off_y, off_x + w_emu, off_y + h_emu),
887
+ )
888
+
889
+
890
+ def convert_polyline(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
891
+ """Convert SVG <polyline> to DrawingML custom geometry shape."""
892
+ points = _parse_points(elem.get('points', ''))
893
+ if not points:
894
+ return None
895
+
896
+ commands = [PathCommand('M', [points[0][0], points[0][1]])]
897
+ for px_, py_ in points[1:]:
898
+ commands.append(PathCommand('L', [px_, py_]))
899
+
900
+ transform = elem.get('transform')
901
+ if _uses_full_transform(ctx, transform):
902
+ commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
903
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
904
+ commands, 0, 0, 1.0, 1.0,
905
+ )
906
+ else:
907
+ path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
908
+ commands, ctx.translate_x, ctx.translate_y,
909
+ ctx.scale_x, ctx.scale_y,
910
+ )
911
+
912
+ if not path_xml:
913
+ return None
914
+
915
+ w_emu = px_to_emu(width)
916
+ h_emu = px_to_emu(height)
917
+
918
+ geom = f'''<a:custGeom>
919
+ <a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>
920
+ <a:rect l="l" t="t" r="r" b="b"/>
921
+ <a:pathLst><a:path w="{w_emu}" h="{h_emu}">
922
+ {path_xml}
923
+ </a:path></a:pathLst>
924
+ </a:custGeom>'''
925
+
926
+ fill_op = get_fill_opacity(elem, ctx)
927
+ stroke_op = get_stroke_opacity(elem, ctx)
928
+ fill = build_fill_xml(elem, ctx, fill_op)
929
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
930
+
931
+ shape_id = ctx.next_id()
932
+ off_x = px_to_emu(min_x)
933
+ off_y = px_to_emu(min_y)
934
+ return ShapeResult(
935
+ xml=_wrap_shape(
936
+ shape_id, f'Polyline {shape_id}',
937
+ off_x, off_y, w_emu, h_emu,
938
+ geom, '<a:noFill/>', stroke,
939
+ ),
940
+ bounds_emu=(off_x, off_y, off_x + w_emu, off_y + h_emu),
941
+ )
942
+
943
+
944
+ # ---------------------------------------------------------------------------
945
+ # text
946
+ # ---------------------------------------------------------------------------
947
+
948
+ _SERIF_WIDTH_FAMILIES = {
949
+ 'book antiqua',
950
+ 'cambria',
951
+ 'fangsong',
952
+ 'garamond',
953
+ 'georgia',
954
+ 'kaiti',
955
+ 'palatino',
956
+ 'palatino linotype',
957
+ 'serif',
958
+ 'simsun',
959
+ 'songti',
960
+ 'times',
961
+ 'times new roman',
962
+ }
963
+
964
+ _TEXTBOX_PADDING_MIN_PX = 0.5
965
+ _TEXTBOX_PADDING_MAX_PX = 2.0
966
+ _TEXTBOX_PADDING_RATIO = 0.04
967
+ # Single-line auto-fit headroom interpolates between a low-caps base and an
968
+ # all-caps ceiling by the fraction of cased letters that are uppercase. The
969
+ # crude per-char width estimate undercounts capitals most, so all-caps lines
970
+ # need the ceiling to keep wrap-ignoring renderers (LibreOffice) from folding;
971
+ # mixed-case titles only need the base, so they no longer inherit the worst-
972
+ # case width. Values are calibrated against LibreOffice renders of all-caps
973
+ # bold lines (the case the per-char estimate undercounts most) with bases left
974
+ # above the mixed-case and CJK render ratios; exact ratios shift with the
975
+ # renderer's font substitution, so these carry deliberate margin rather than
976
+ # tracking one environment's numbers.
977
+ _TEXT_WIDTH_HEADROOM_BASE = 1.06
978
+ _TEXT_WIDTH_HEADROOM_CAPS = 1.12
979
+ _SERIF_TEXT_WIDTH_HEADROOM_BASE = 1.12
980
+ _SERIF_TEXT_WIDTH_HEADROOM_CAPS = 1.36
981
+
982
+
983
+ def _normalize_text(text: str, *, preserve_space: bool = False) -> str:
984
+ """Collapse runs of whitespace into a single space; do NOT strip the ends.
985
+
986
+ Stripping at this layer would silently delete the inline boundary
987
+ spaces in nested-tspan structures like
988
+ <tspan>foo <tspan>bar</tspan> baz</tspan>: the parent's text
989
+ ("foo ") and the child's tail (" baz") would each lose the only space
990
+ that separated them from the inner run, producing "foobarbaz".
991
+
992
+ The paragraph's overall leading / trailing whitespace is removed once
993
+ in `_build_text_runs` after all inline runs have been concatenated.
994
+ """
995
+ if not text:
996
+ return ''
997
+ if preserve_space:
998
+ return text
999
+ return re.sub(r'\s+', ' ', text)
1000
+
1001
+
1002
+ def _preserves_space(elem: ET.Element) -> bool:
1003
+ xml_space = elem.get('{http://www.w3.org/XML/1998/namespace}space') or elem.get('xml:space')
1004
+ return xml_space == 'preserve'
1005
+
1006
+
1007
+ def _parse_letter_spacing_px(
1008
+ value: str | None,
1009
+ *,
1010
+ font_size: float,
1011
+ scale_x: float = 1.0,
1012
+ ) -> float:
1013
+ """Parse an SVG letter-spacing value into scaled pixels."""
1014
+ if not value:
1015
+ return 0.0
1016
+ raw = value.strip().lower()
1017
+ if raw in {'normal', 'inherit', 'initial', 'unset'}:
1018
+ return 0.0
1019
+
1020
+ match = re.fullmatch(r'([-+]?(?:\d*\.\d+|\d+\.?))(px|pt|em)?', raw)
1021
+ if not match:
1022
+ return 0.0
1023
+
1024
+ amount = float(match.group(1))
1025
+ unit = match.group(2) or 'px'
1026
+ if unit == 'em':
1027
+ return amount * font_size
1028
+ if unit == 'pt':
1029
+ return amount * 4.0 / 3.0 * scale_x
1030
+ return amount * scale_x
1031
+
1032
+
1033
+ def _letter_spacing_to_drawingml_spc(letter_spacing_px: float) -> str:
1034
+ """Convert SVG px letter spacing into DrawingML rPr@spc."""
1035
+ if abs(letter_spacing_px) < 1e-9:
1036
+ return ''
1037
+ spc_val = round(letter_spacing_px * FONT_PX_TO_HUNDREDTHS_PT)
1038
+ return f' spc="{spc_val}"'
1039
+
1040
+
1041
+ def _is_serif_run(run: dict[str, Any]) -> bool:
1042
+ """Return whether a text run uses a serif-like family."""
1043
+ for family in str(run.get('font_family', '')).split(','):
1044
+ name = family.strip().strip("'\"").lower()
1045
+ if not name or name in {'sans-serif', 'sans serif'}:
1046
+ continue
1047
+ if name in _SERIF_WIDTH_FAMILIES:
1048
+ return True
1049
+ if 'serif' in name and 'sans' not in name:
1050
+ return True
1051
+ return False
1052
+
1053
+
1054
+ def _estimate_run_text_width(run: dict[str, Any]) -> float:
1055
+ """Estimate one text run's rendered width, including tracking."""
1056
+ text = str(run.get('text', ''))
1057
+ base_width = estimate_text_width(
1058
+ text,
1059
+ float(run.get('font_size', 16)),
1060
+ str(run.get('font_weight', '400')),
1061
+ )
1062
+ letter_spacing_px = float(run.get('letter_spacing', 0.0) or 0.0)
1063
+ return base_width + letter_spacing_px * max(len(text) - 1, 0)
1064
+
1065
+
1066
+ def _uppercase_fraction(runs: list[dict[str, Any]]) -> float:
1067
+ """Fraction of cased letters across `runs` that are uppercase.
1068
+
1069
+ Caseless scripts (CJK, digits, punctuation) are ignored, so a Chinese or
1070
+ numeric line reports 0.0 and takes the low-caps headroom base.
1071
+ """
1072
+ upper = 0
1073
+ cased = 0
1074
+ for run in runs:
1075
+ for ch in str(run.get('text', '')):
1076
+ if ch.lower() != ch.upper():
1077
+ cased += 1
1078
+ if ch.isupper():
1079
+ upper += 1
1080
+ if not cased:
1081
+ return 0.0
1082
+ return upper / cased
1083
+
1084
+
1085
+ def _estimate_text_runs_width(
1086
+ runs: list[dict[str, Any]],
1087
+ *,
1088
+ include_headroom: bool = True,
1089
+ ) -> float:
1090
+ """Estimate a line of text runs.
1091
+
1092
+ `include_headroom` is useful for single-line auto-fit boxes where a
1093
+ renderer that measures text slightly wider would otherwise wrap. The
1094
+ headroom scales with the line's uppercase fraction: all-caps lines (whose
1095
+ width the per-char estimate undercounts most) get the full ceiling, while
1096
+ mixed-case titles take a small base instead of inheriting the worst case.
1097
+ Paragraph boxes use this value as a wrapping constraint, so adding headroom
1098
+ there stretches the merged text frame beyond the author's source line width.
1099
+ """
1100
+ width = sum(_estimate_run_text_width(run) for run in runs)
1101
+ if not include_headroom:
1102
+ return width
1103
+ caps = _uppercase_fraction(runs)
1104
+ if any(_is_serif_run(run) for run in runs):
1105
+ base, ceiling = _SERIF_TEXT_WIDTH_HEADROOM_BASE, _SERIF_TEXT_WIDTH_HEADROOM_CAPS
1106
+ else:
1107
+ base, ceiling = _TEXT_WIDTH_HEADROOM_BASE, _TEXT_WIDTH_HEADROOM_CAPS
1108
+ return width * (base + (ceiling - base) * caps)
1109
+
1110
+
1111
+ def _textbox_padding(font_size: float) -> float:
1112
+ """Return small text-frame slack without visibly lengthening the box."""
1113
+ return max(
1114
+ _TEXTBOX_PADDING_MIN_PX,
1115
+ min(_TEXTBOX_PADDING_MAX_PX, font_size * _TEXTBOX_PADDING_RATIO),
1116
+ )
1117
+
1118
+
1119
+ def _override_run_attrs(
1120
+ parent_attrs: dict[str, Any],
1121
+ tspan: ET.Element,
1122
+ ) -> dict[str, Any]:
1123
+ """Layer a tspan's styling attributes over the inherited run attrs."""
1124
+ run_attrs = dict(parent_attrs)
1125
+ inline_style = parse_inline_style(tspan.get('style'))
1126
+
1127
+ def tspan_attr(name: str) -> str | None:
1128
+ return inline_style.get(name) or tspan.get(name)
1129
+
1130
+ if tspan_attr('font-weight'):
1131
+ run_attrs['font_weight'] = tspan_attr('font-weight')
1132
+ if tspan_attr('fill'):
1133
+ child_fill = tspan_attr('fill')
1134
+ run_attrs['fill_raw'] = child_fill
1135
+ c = parse_hex_color(child_fill)
1136
+ if c:
1137
+ run_attrs['fill'] = c
1138
+ if tspan_attr('stroke'):
1139
+ run_attrs['stroke_raw'] = tspan_attr('stroke')
1140
+ if tspan_attr('stroke-width'):
1141
+ run_attrs['stroke_width'] = parse_svg_length(
1142
+ tspan_attr('stroke-width'),
1143
+ run_attrs.get('stroke_width', 1.0),
1144
+ font_size=float(run_attrs.get('font_size', 16)),
1145
+ )
1146
+ if tspan_attr('stroke-opacity'):
1147
+ try:
1148
+ run_attrs['stroke_opacity'] = float(tspan_attr('stroke-opacity') or '1')
1149
+ except ValueError:
1150
+ pass
1151
+ if tspan_attr('font-size'):
1152
+ run_attrs['font_size'] = parse_svg_length(
1153
+ tspan_attr('font-size'),
1154
+ run_attrs['font_size'],
1155
+ font_size=float(run_attrs.get('font_size', 16)),
1156
+ )
1157
+ if tspan_attr('font-family'):
1158
+ run_attrs['font_family'] = tspan_attr('font-family')
1159
+ if tspan_attr('font-style'):
1160
+ run_attrs['font_style'] = tspan_attr('font-style')
1161
+ if tspan_attr('text-decoration'):
1162
+ run_attrs['text_decoration'] = tspan_attr('text-decoration')
1163
+ if tspan_attr('letter-spacing'):
1164
+ run_attrs['letter_spacing'] = _parse_letter_spacing_px(
1165
+ tspan_attr('letter-spacing'),
1166
+ font_size=float(run_attrs.get('font_size', 16)),
1167
+ scale_x=float(run_attrs.get('_scale_x', 1.0)),
1168
+ )
1169
+ return run_attrs
1170
+
1171
+
1172
+ def _collect_tspan_runs(
1173
+ tspan: ET.Element,
1174
+ inherited_attrs: dict[str, Any],
1175
+ preserve_space: bool = False,
1176
+ ) -> list[dict[str, Any]]:
1177
+ """Recursively turn a tspan subtree into runs, propagating styling through nested tspans.
1178
+
1179
+ Order: tspan.text → (each nested child tspan's runs → that child's tail under THIS tspan's attrs).
1180
+ """
1181
+ runs: list[dict[str, Any]] = []
1182
+ own_attrs = _override_run_attrs(inherited_attrs, tspan)
1183
+ child_preserve_space = preserve_space or _preserves_space(tspan)
1184
+
1185
+ if tspan.text:
1186
+ t = _normalize_text(tspan.text, preserve_space=child_preserve_space)
1187
+ if t:
1188
+ runs.append({**own_attrs, 'text': t})
1189
+
1190
+ for child in tspan:
1191
+ child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
1192
+ if child_tag == 'tspan':
1193
+ runs.extend(_collect_tspan_runs(child, own_attrs, child_preserve_space))
1194
+ if child.tail:
1195
+ t = _normalize_text(child.tail, preserve_space=child_preserve_space)
1196
+ if t:
1197
+ runs.append({**own_attrs, 'text': t})
1198
+
1199
+ return runs
1200
+
1201
+
1202
+ def _build_text_runs(
1203
+ elem: ET.Element,
1204
+ parent_attrs: dict[str, Any],
1205
+ ) -> list[dict[str, Any]]:
1206
+ """Build a list of text runs from a <text> element, handling <tspan> children.
1207
+
1208
+ Each run is a dict with keys: text, fill, fill_raw, font_weight,
1209
+ font_style, font_family, font_size, letter_spacing. Nested tspans are walked
1210
+ recursively so inline format changes inside a tspan still produce distinct runs.
1211
+ """
1212
+ runs: list[dict[str, Any]] = []
1213
+ preserve_space = _preserves_space(elem)
1214
+
1215
+ if elem.text:
1216
+ t = _normalize_text(elem.text, preserve_space=preserve_space)
1217
+ if t:
1218
+ runs.append({**parent_attrs, 'text': t})
1219
+
1220
+ for child in elem:
1221
+ child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
1222
+ if child_tag == 'tspan':
1223
+ runs.extend(_collect_tspan_runs(child, parent_attrs, preserve_space))
1224
+ if child.tail:
1225
+ t = _normalize_text(child.tail, preserve_space=preserve_space)
1226
+ if t:
1227
+ runs.append({**parent_attrs, 'text': t})
1228
+
1229
+ # Strip the paragraph's overall leading / trailing whitespace once unless
1230
+ # xml:space="preserve" asks us to keep source indentation.
1231
+ if runs and not preserve_space:
1232
+ runs[0]['text'] = runs[0]['text'].lstrip(' ')
1233
+ runs[-1]['text'] = runs[-1]['text'].rstrip(' ')
1234
+ runs = [r for r in runs if r['text']]
1235
+
1236
+ return runs
1237
+
1238
+
1239
+ def _build_text_fill_xml(
1240
+ fill: str,
1241
+ fill_raw: str,
1242
+ opacity: float | None,
1243
+ ctx: ConvertContext | None,
1244
+ ) -> str:
1245
+ """Build DrawingML fill XML for a text run."""
1246
+ if fill_raw.strip().lower() in ('none', 'transparent'):
1247
+ return '<a:noFill/>'
1248
+
1249
+ grad_id = resolve_url_id(fill_raw)
1250
+ if grad_id and ctx and grad_id in ctx.defs:
1251
+ return build_gradient_fill(ctx.defs[grad_id], opacity)
1252
+
1253
+ alpha_xml = ''
1254
+ if opacity is not None and opacity < 1.0:
1255
+ alpha_xml = f'<a:alphaMod val="{int(opacity * 100000)}"/>'
1256
+ return f'<a:solidFill><a:srgbClr val="{fill}">{alpha_xml}</a:srgbClr></a:solidFill>'
1257
+
1258
+
1259
+ def _build_text_outline_xml(run: dict[str, Any]) -> str:
1260
+ """Build DrawingML outline XML for a text run from SVG stroke attributes."""
1261
+ stroke_raw = run.get('stroke_raw')
1262
+ if not stroke_raw or stroke_raw.strip().lower() in ('none', 'transparent'):
1263
+ return ''
1264
+
1265
+ color = parse_hex_color(stroke_raw)
1266
+ if not color:
1267
+ return ''
1268
+
1269
+ stroke_width = _f(str(run.get('stroke_width', 1.0)), 1.0)
1270
+ stroke_opacity = run.get('stroke_opacity')
1271
+ alpha_xml = ''
1272
+ if stroke_opacity is not None and stroke_opacity < 1.0:
1273
+ alpha_xml = f'<a:alphaMod val="{int(stroke_opacity * 100000)}"/>'
1274
+
1275
+ return (
1276
+ f'<a:ln w="{px_to_emu(stroke_width)}">'
1277
+ f'<a:solidFill><a:srgbClr val="{color}">{alpha_xml}</a:srgbClr></a:solidFill>'
1278
+ '</a:ln>'
1279
+ )
1280
+
1281
+
1282
+ def _build_run_xml(
1283
+ run: dict[str, Any],
1284
+ default_fonts: dict[str, str],
1285
+ ctx: ConvertContext | None = None,
1286
+ effect_xml: str = '',
1287
+ ) -> str:
1288
+ """Build a single <a:r> XML from a run dict. Supports gradient fills on text."""
1289
+ text = run['text']
1290
+ fill = run.get('fill', '000000')
1291
+ fill_raw = run.get('fill_raw', '')
1292
+ fw = run.get('font_weight', '400')
1293
+ fs_px = run.get('font_size', 16)
1294
+ fstyle = run.get('font_style', '')
1295
+ ff = run.get('font_family', '')
1296
+ letter_spacing_px = float(run.get('letter_spacing', 0.0) or 0.0)
1297
+ opacity = run.get('opacity')
1298
+
1299
+ text_dec = run.get('text_decoration', '')
1300
+
1301
+ # Exported font size = fs_px * FONT_PX_TO_HUNDREDTHS_PT hundredths-of-pt,
1302
+ # rounded to one decimal place of pt (the nearest 10 hundredths). No 0.5pt
1303
+ # / integer snapping — whatever the px works out to is the size, e.g.
1304
+ # 18px -> 13.5pt, 24px -> 18.0pt, 42px -> 31.5pt.
1305
+ sz = int(round(fs_px * FONT_PX_TO_HUNDREDTHS_PT / 10.0)) * 10
1306
+ b_attr = ' b="1"' if fw in ('bold', '600', '700', '800', '900') else ''
1307
+ i_attr = ' i="1"' if fstyle == 'italic' else ''
1308
+ u_attr = ' u="sng"' if 'underline' in text_dec else ''
1309
+ strike_attr = ' strike="sngStrike"' if 'line-through' in text_dec else ''
1310
+ spc_attr = _letter_spacing_to_drawingml_spc(letter_spacing_px)
1311
+
1312
+ fonts = parse_font_family(ff) if ff else default_fonts
1313
+ run_fonts = resolve_text_run_fonts(text, fonts)
1314
+ lang = detect_text_lang(text)
1315
+
1316
+ fill_xml = _build_text_fill_xml(fill, fill_raw, opacity, ctx)
1317
+ outline_xml = _build_text_outline_xml(run)
1318
+
1319
+ space_attr = ' xml:space="preserve"' if text != text.strip() or ' ' in text else ''
1320
+
1321
+ return f'''<a:r>
1322
+ <a:rPr lang="{lang}" sz="{sz}"{b_attr}{i_attr}{u_attr}{strike_attr}{spc_attr} dirty="0">
1323
+ {outline_xml}
1324
+ {fill_xml}
1325
+ {effect_xml}
1326
+ <a:latin typeface="{_xml_escape(run_fonts['latin'])}"/>
1327
+ <a:ea typeface="{_xml_escape(run_fonts['ea'])}"/>
1328
+ <a:cs typeface="{_xml_escape(run_fonts['cs'])}"/>
1329
+ </a:rPr>
1330
+ <a:t{space_attr}>{_xml_escape(text)}</a:t>
1331
+ </a:r>'''
1332
+
1333
+
1334
+ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
1335
+ """Convert SVG <text> to DrawingML text shape with multi-run support."""
1336
+ x = ctx_x(svg_length_x(elem.get('x'), ctx), ctx)
1337
+ y = ctx_y(svg_length_y(elem.get('y'), ctx), ctx)
1338
+ font_size = (
1339
+ parse_svg_length(_get_attr(elem, 'font-size', ctx), 16, font_size=16)
1340
+ * ctx.scale_y
1341
+ )
1342
+ font_weight = _get_attr(elem, 'font-weight', ctx) or '400'
1343
+ font_family_str = _get_attr(elem, 'font-family', ctx) or ''
1344
+ text_anchor = _get_attr(elem, 'text-anchor', ctx) or 'start'
1345
+ fill_raw = _get_attr(elem, 'fill', ctx) or '#000000'
1346
+ fill_color = parse_hex_color(fill_raw) or '000000'
1347
+ opacity = get_fill_opacity(elem, ctx)
1348
+ stroke_raw = _get_attr(elem, 'stroke', ctx) or ''
1349
+ stroke_width = svg_length_size(_get_attr(elem, 'stroke-width', ctx), ctx, 1.0)
1350
+ stroke_opacity = get_stroke_opacity(elem, ctx)
1351
+ font_style = _get_attr(elem, 'font-style', ctx) or ''
1352
+ text_decoration = _get_attr(elem, 'text-decoration', ctx) or ''
1353
+ letter_spacing_px = _parse_letter_spacing_px(
1354
+ _get_attr(elem, 'letter-spacing', ctx),
1355
+ font_size=font_size,
1356
+ scale_x=ctx.scale_x or 1.0,
1357
+ )
1358
+
1359
+ fonts = parse_font_family(font_family_str)
1360
+
1361
+ parent_attrs: dict[str, Any] = {
1362
+ 'fill': fill_color,
1363
+ 'fill_raw': fill_raw,
1364
+ 'font_weight': font_weight,
1365
+ 'font_size': font_size,
1366
+ 'font_family': font_family_str,
1367
+ 'font_style': font_style,
1368
+ 'text_decoration': text_decoration,
1369
+ 'letter_spacing': letter_spacing_px,
1370
+ '_scale_x': ctx.scale_x or 1.0,
1371
+ 'opacity': opacity,
1372
+ 'stroke_raw': stroke_raw,
1373
+ 'stroke_width': stroke_width,
1374
+ 'stroke_opacity': stroke_opacity,
1375
+ }
1376
+
1377
+ # Paragraph mode: flatten_tspan marks <text> with data-paragraph-line-height
1378
+ # when its direct-child tspans form a mergeable paragraph (same x, dy
1379
+ # clustered around one base line-height). Each direct tspan becomes one
1380
+ # <a:p> so the paragraph survives as a single editable text frame.
1381
+ # Per-line data-paragraph-space-before encodes paragraph gaps (extra dy
1382
+ # above the base line-height) for the corresponding <a:p>.
1383
+ # Paragraph mode is controlled by ctx.merge_paragraphs. When off, ignore
1384
+ # any data-paragraph-* markers and fall through to the original
1385
+ # one-text-per-tspan path so the SVG's pixel layout is preserved.
1386
+ line_height_attr = elem.get('data-paragraph-line-height') if ctx.merge_paragraphs else None
1387
+ line_height_px = _f(line_height_attr) if line_height_attr is not None else None
1388
+ paragraph_runs: list[list[dict[str, Any]]] | None = None
1389
+ paragraph_space_before: list[float] = []
1390
+ # Per-tspan widths (visual lines as the deck author drew them) regardless
1391
+ # of how many merge into one <a:p>; used to size the textbox so PowerPoint
1392
+ # has room to wrap text to the SVG's original line widths.
1393
+ visual_line_widths: list[float] = []
1394
+ if line_height_px is not None and line_height_px > 0:
1395
+ preserve_space = _preserves_space(elem)
1396
+ paragraph_runs = []
1397
+ for child in elem:
1398
+ if child.tag != f'{{{SVG_NS}}}tspan':
1399
+ continue
1400
+ line_runs = _collect_tspan_runs(child, parent_attrs, preserve_space)
1401
+ if line_runs and not preserve_space:
1402
+ line_runs[0]['text'] = line_runs[0]['text'].lstrip(' ')
1403
+ line_runs[-1]['text'] = line_runs[-1]['text'].rstrip(' ')
1404
+ line_runs = [r for r in line_runs if r['text']]
1405
+ if not line_runs:
1406
+ continue
1407
+ visual_line_widths.append(
1408
+ _estimate_text_runs_width(line_runs, include_headroom=False)
1409
+ )
1410
+ soft_break = child.get('data-paragraph-soft-break') == '1'
1411
+ if soft_break and paragraph_runs:
1412
+ # Append to the previous paragraph. A Latin line-wrap needs a
1413
+ # space to keep two words apart (SVG used a dy break, not
1414
+ # punctuation); CJK wraps mid-sentence with no inter-character
1415
+ # space, so a joining space there is a spurious artifact.
1416
+ prev = paragraph_runs[-1]
1417
+ prev_text = prev[-1]['text'] if prev else ''
1418
+ next_text = line_runs[0]['text']
1419
+ boundary_is_cjk = (
1420
+ (prev_text and is_cjk_char(prev_text[-1]))
1421
+ or (next_text and is_cjk_char(next_text[0]))
1422
+ )
1423
+ if prev and not prev_text.endswith(' ') \
1424
+ and not next_text.startswith(' ') \
1425
+ and not boundary_is_cjk:
1426
+ prev[-1] = {**prev[-1], 'text': prev_text + ' '}
1427
+ prev.extend(line_runs)
1428
+ else:
1429
+ paragraph_runs.append(line_runs)
1430
+ sb_attr = child.get('data-paragraph-space-before')
1431
+ paragraph_space_before.append(_f(sb_attr) if sb_attr else 0.0)
1432
+ if not paragraph_runs:
1433
+ paragraph_runs = None
1434
+ paragraph_space_before = []
1435
+ visual_line_widths = []
1436
+
1437
+ if paragraph_runs is not None:
1438
+ runs = [r for line in paragraph_runs for r in line]
1439
+ else:
1440
+ runs = _build_text_runs(elem, parent_attrs)
1441
+
1442
+ if not runs:
1443
+ return None
1444
+
1445
+ full_text = ''.join(r['text'] for r in runs)
1446
+ if not full_text.strip():
1447
+ return None
1448
+
1449
+ # Estimate text dimensions
1450
+ if paragraph_runs is not None:
1451
+ # Use the WIDEST visual line (per-tspan as the deck author drew it),
1452
+ # not the joined-up paragraph: soft-broken paragraphs concatenate
1453
+ # many lines into one <a:p>, and measuring the joined string would
1454
+ # blow the textbox past the canvas.
1455
+ text_width = max(visual_line_widths) if visual_line_widths else 0.0
1456
+ # Total height assumes the visual line count from the SVG source;
1457
+ # if PowerPoint wraps to more or fewer lines after the user resizes,
1458
+ # the user resizes the height accordingly.
1459
+ text_height = (
1460
+ line_height_px * (len(visual_line_widths) - 1)
1461
+ + sum(paragraph_space_before)
1462
+ + font_size * 1.5
1463
+ )
1464
+ else:
1465
+ text_width = _estimate_text_runs_width(runs)
1466
+ text_height = font_size * 1.5
1467
+ padding = _textbox_padding(font_size)
1468
+
1469
+ # Adjust position based on text-anchor
1470
+ if text_anchor == 'middle':
1471
+ box_x = x - text_width / 2 - padding
1472
+ elif text_anchor == 'end':
1473
+ box_x = x - text_width - padding
1474
+ else:
1475
+ box_x = x - padding
1476
+
1477
+ box_y = y - font_size * 0.85
1478
+ box_w = text_width + padding * 2
1479
+ box_h = text_height + padding
1480
+
1481
+ text_transform = elem.get('transform', '')
1482
+ if text_transform and 'rotate' not in text_transform and not ctx.use_transform_matrix:
1483
+ try:
1484
+ a, b, c, d, e, f = parse_transform_matrix(text_transform)
1485
+ except Exception:
1486
+ a, b, c, d, e, f = 1.0, 0.0, 0.0, 1.0, 0.0, 0.0
1487
+ # A pure-translate transform on a text element (hand-authored, or written
1488
+ # by a live-preview move) was otherwise ignored here, drifting the text.
1489
+ # Absorb the translation into the frame position; a scaling transform
1490
+ # would also need to scale font size / line metrics, so leave
1491
+ # non-translate transforms alone.
1492
+ if (
1493
+ abs(a - 1.0) < 1e-9 and abs(b) < 1e-9
1494
+ and abs(c) < 1e-9 and abs(d - 1.0) < 1e-9
1495
+ ):
1496
+ sx = ctx.scale_x or 1.0
1497
+ sy = ctx.scale_y or 1.0
1498
+ raw_box_x = (box_x - ctx.translate_x) / sx
1499
+ raw_box_y = (box_y - ctx.translate_y) / sy
1500
+ box_x = ctx.translate_x + sx * (a * raw_box_x + e)
1501
+ box_y = ctx.translate_y + sy * (d * raw_box_y + f)
1502
+
1503
+ # Text rotation. SVG's rotate(angle [cx cy]) rotates around (cx, cy), but
1504
+ # DrawingML's <a:xfrm rot="..."> rotates the shape around its own center.
1505
+ # When a pivot is given (and differs from the box center), translate the
1506
+ # box so its center lands where SVG would place the rotated visual center —
1507
+ # otherwise rotated y-axis labels etc. drift to the wrong location.
1508
+ text_rot = 0
1509
+ if text_transform:
1510
+ rot_match = re.search(
1511
+ r'rotate\(\s*([-\d.]+)(?:[\s,]+([-\d.]+)[\s,]+([-\d.]+))?',
1512
+ text_transform,
1513
+ )
1514
+ if rot_match:
1515
+ angle_deg = float(rot_match.group(1))
1516
+ text_rot = int(angle_deg * ANGLE_UNIT)
1517
+ if rot_match.group(2) is not None:
1518
+ pivot_x = ctx_x(float(rot_match.group(2)), ctx)
1519
+ pivot_y = ctx_y(float(rot_match.group(3)), ctx)
1520
+ cx_box = box_x + box_w / 2
1521
+ cy_box = box_y + box_h / 2
1522
+ rad = math.radians(angle_deg)
1523
+ dx = cx_box - pivot_x
1524
+ dy = cy_box - pivot_y
1525
+ new_cx = pivot_x + dx * math.cos(rad) - dy * math.sin(rad)
1526
+ new_cy = pivot_y + dx * math.sin(rad) + dy * math.cos(rad)
1527
+ box_x = new_cx - box_w / 2
1528
+ box_y = new_cy - box_h / 2
1529
+
1530
+ # Alignment
1531
+ algn_map = {'start': 'l', 'middle': 'ctr', 'end': 'r'}
1532
+ algn = algn_map.get(text_anchor, 'l')
1533
+
1534
+ # Shadow effect
1535
+ shape_effect_xml = ''
1536
+ text_effect_xml = ''
1537
+ filt_id = get_effective_filter_id(elem, ctx)
1538
+ if filt_id and filt_id in ctx.defs:
1539
+ filter_elem = ctx.defs[filt_id]
1540
+ effect_kind = classify_filter_effect(filter_elem)
1541
+ if effect_kind == 'glow':
1542
+ text_effect_xml = build_effect_xml(filter_elem)
1543
+ elif effect_kind == 'shadow':
1544
+ shape_effect_xml = build_effect_xml(filter_elem)
1545
+
1546
+ shape_id = ctx.next_id()
1547
+ rot_attr = f' rot="{text_rot}"' if text_rot else ''
1548
+
1549
+ if paragraph_runs is not None:
1550
+ # SVG dy(px) -> hundredths-of-a-point: dy_pt = dy_px * 0.75, then x100.
1551
+ line_spc_val = round(line_height_px * FONT_PX_TO_HUNDREDTHS_PT)
1552
+ ln_spc_xml = f'<a:lnSpc><a:spcPts val="{line_spc_val}"/></a:lnSpc>'
1553
+ paragraph_xml_chunks = []
1554
+ for line, extra_px in zip(paragraph_runs, paragraph_space_before):
1555
+ spc_bef_xml = ''
1556
+ if extra_px > 0:
1557
+ spc_bef_val = round(extra_px * FONT_PX_TO_HUNDREDTHS_PT)
1558
+ spc_bef_xml = f'<a:spcBef><a:spcPts val="{spc_bef_val}"/></a:spcBef>'
1559
+ runs_inner = '\n'.join(_build_run_xml(r, fonts, ctx, text_effect_xml) for r in line)
1560
+ paragraph_xml_chunks.append(
1561
+ f'<a:p>\n<a:pPr algn="{algn}">{ln_spc_xml}{spc_bef_xml}</a:pPr>\n'
1562
+ f'{runs_inner}\n</a:p>'
1563
+ )
1564
+ paragraphs_xml = '\n'.join(paragraph_xml_chunks)
1565
+ else:
1566
+ runs_xml = '\n'.join(_build_run_xml(r, fonts, ctx, text_effect_xml) for r in runs)
1567
+ paragraphs_xml = f'<a:p>\n<a:pPr algn="{algn}"/>\n{runs_xml}\n</a:p>'
1568
+
1569
+ off_x = px_to_emu(box_x)
1570
+ off_y = px_to_emu(box_y)
1571
+ ext_cx = px_to_emu(box_w)
1572
+ ext_cy = px_to_emu(box_h)
1573
+
1574
+ # Paragraph mode: wrap="square" so text reflows when the user resizes,
1575
+ # but NO spAutoFit — otherwise PowerPoint expands the frame to fit a
1576
+ # long joined-up <a:p> on one line, blowing past the canvas. The cx we
1577
+ # write below is the longest source SVG line without single-line renderer
1578
+ # headroom; PowerPoint wraps long paragraphs inside this design width.
1579
+ # Single-line text keeps wrap="none" + spAutoFit for tight fidelity.
1580
+ if paragraph_runs is not None:
1581
+ body_pr_xml = (
1582
+ '<a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" '
1583
+ 'anchor="t" anchorCtr="0"/>'
1584
+ )
1585
+ else:
1586
+ body_pr_xml = (
1587
+ '<a:bodyPr wrap="none" lIns="0" tIns="0" rIns="0" bIns="0" '
1588
+ 'anchor="t" anchorCtr="0">\n<a:spAutoFit/>\n</a:bodyPr>'
1589
+ )
1590
+
1591
+ return ShapeResult(xml=f'''<p:sp>
1592
+ <p:nvSpPr>
1593
+ <p:cNvPr id="{shape_id}" name="TextBox {shape_id}"/>
1594
+ <p:cNvSpPr txBox="1"/><p:nvPr/>
1595
+ </p:nvSpPr>
1596
+ <p:spPr>
1597
+ <a:xfrm{rot_attr}><a:off x="{off_x}" y="{off_y}"/>
1598
+ <a:ext cx="{ext_cx}" cy="{ext_cy}"/></a:xfrm>
1599
+ <a:prstGeom prst="rect"><a:avLst/></a:prstGeom>
1600
+ <a:noFill/>
1601
+ <a:ln><a:noFill/></a:ln>
1602
+ {shape_effect_xml}
1603
+ </p:spPr>
1604
+ <p:txBody>
1605
+ {body_pr_xml}
1606
+ <a:lstStyle/>
1607
+ {paragraphs_xml}
1608
+ </p:txBody>
1609
+ </p:sp>''', bounds_emu=(off_x, off_y, off_x + ext_cx, off_y + ext_cy))
1610
+
1611
+
1612
+ # ---------------------------------------------------------------------------
1613
+ # clipPath support (image clipping)
1614
+ # ---------------------------------------------------------------------------
1615
+
1616
+ def _clip_commands_to_geom(
1617
+ commands: list[PathCommand],
1618
+ img_x: float, img_y: float,
1619
+ img_w: float, img_h: float,
1620
+ object_bbox: bool,
1621
+ ) -> str:
1622
+ """Convert clip path commands to DrawingML custGeom XML.
1623
+
1624
+ Coordinates are transformed relative to the image bounding box so that
1625
+ (img_x, img_y) maps to (0, 0) and (img_x+img_w, img_y+img_h) maps to
1626
+ (w_emu, h_emu).
1627
+ """
1628
+ w_emu = px_to_emu(img_w)
1629
+ h_emu = px_to_emu(img_h)
1630
+
1631
+ if w_emu <= 0 or h_emu <= 0:
1632
+ return '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
1633
+
1634
+ def _tx(x: float) -> int:
1635
+ if object_bbox:
1636
+ return int(x * w_emu)
1637
+ return px_to_emu(x - img_x)
1638
+
1639
+ def _ty(y: float) -> int:
1640
+ if object_bbox:
1641
+ return int(y * h_emu)
1642
+ return px_to_emu(y - img_y)
1643
+
1644
+ parts: list[str] = []
1645
+ for cmd in commands:
1646
+ if cmd.cmd == 'M':
1647
+ parts.append(
1648
+ f'<a:moveTo><a:pt x="{_tx(cmd.args[0])}" '
1649
+ f'y="{_ty(cmd.args[1])}"/></a:moveTo>'
1650
+ )
1651
+ elif cmd.cmd == 'L':
1652
+ parts.append(
1653
+ f'<a:lnTo><a:pt x="{_tx(cmd.args[0])}" '
1654
+ f'y="{_ty(cmd.args[1])}"/></a:lnTo>'
1655
+ )
1656
+ elif cmd.cmd == 'C':
1657
+ pts = ''.join(
1658
+ f'<a:pt x="{_tx(cmd.args[i])}" y="{_ty(cmd.args[i + 1])}"/>'
1659
+ for i in range(0, 6, 2)
1660
+ )
1661
+ parts.append(f'<a:cubicBezTo>{pts}</a:cubicBezTo>')
1662
+ elif cmd.cmd == 'Z':
1663
+ parts.append('<a:close/>')
1664
+
1665
+ path_inner = '\n'.join(parts)
1666
+ return f'''<a:custGeom>
1667
+ <a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/>
1668
+ <a:rect l="l" t="t" r="r" b="b"/>
1669
+ <a:pathLst><a:path w="{w_emu}" h="{h_emu}">
1670
+ {path_inner}
1671
+ </a:path></a:pathLst>
1672
+ </a:custGeom>'''
1673
+
1674
+
1675
+ def _resolve_clip_geometry(
1676
+ elem: ET.Element,
1677
+ ctx: ConvertContext,
1678
+ raw_x: float, raw_y: float,
1679
+ raw_w: float, raw_h: float,
1680
+ ) -> str:
1681
+ """Resolve clip-path on an image element to DrawingML geometry XML.
1682
+
1683
+ Supports:
1684
+ - circle / ellipse → prstGeom ellipse
1685
+ - rect with rx/ry → prstGeom roundRect
1686
+ - path / polygon → custGeom
1687
+
1688
+ Args:
1689
+ elem: SVG element bearing a clip-path attribute.
1690
+ ctx: Conversion context (carries defs).
1691
+ raw_x, raw_y: Image position in SVG space (pre-ctx-transform).
1692
+ raw_w, raw_h: Image dimensions in SVG space (pre-ctx-transform).
1693
+
1694
+ Returns:
1695
+ DrawingML geometry XML string.
1696
+ """
1697
+ DEFAULT = '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
1698
+
1699
+ clip_ref = elem.get('clip-path', '')
1700
+ if not clip_ref or clip_ref == 'none':
1701
+ return DEFAULT
1702
+
1703
+ clip_id = resolve_url_id(clip_ref)
1704
+ if not clip_id or clip_id not in ctx.defs:
1705
+ return DEFAULT
1706
+
1707
+ clip_elem = ctx.defs[clip_id]
1708
+ clip_tag = clip_elem.tag.replace(f'{{{SVG_NS}}}', '')
1709
+ if clip_tag != 'clipPath':
1710
+ return DEFAULT
1711
+
1712
+ # Find the first shape child of the clipPath
1713
+ shape = None
1714
+ for child in clip_elem:
1715
+ child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
1716
+ if child_tag in ('circle', 'ellipse', 'rect', 'path', 'polygon'):
1717
+ shape = child
1718
+ break
1719
+
1720
+ if shape is None:
1721
+ return DEFAULT
1722
+
1723
+ shape_tag = shape.tag.replace(f'{{{SVG_NS}}}', '')
1724
+ is_obb = clip_elem.get('clipPathUnits') == 'objectBoundingBox'
1725
+
1726
+ # --- Circle / Ellipse → preset ellipse ---
1727
+ if shape_tag in ('circle', 'ellipse'):
1728
+ return '<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>'
1729
+
1730
+ # --- Rect with rx/ry → preset roundRect ---
1731
+ if shape_tag == 'rect':
1732
+ rx = _f(shape.get('rx'))
1733
+ ry = _f(shape.get('ry'), rx)
1734
+ if rx <= 0 and ry <= 0:
1735
+ return DEFAULT # plain rect clip is a no-op
1736
+ r = max(rx, ry)
1737
+ if is_obb:
1738
+ r = r * min(raw_w, raw_h)
1739
+ shorter = min(raw_w, raw_h)
1740
+ if shorter <= 0:
1741
+ return DEFAULT
1742
+ adj = int(min(r / (shorter / 2), 1.0) * 50000)
1743
+ return (
1744
+ f'<a:prstGeom prst="roundRect"><a:avLst>'
1745
+ f'<a:gd name="adj" fmla="val {adj}"/>'
1746
+ f'</a:avLst></a:prstGeom>'
1747
+ )
1748
+
1749
+ # --- Path → custGeom ---
1750
+ if shape_tag == 'path':
1751
+ d = shape.get('d', '')
1752
+ if not d:
1753
+ return DEFAULT
1754
+ commands = parse_svg_path(d)
1755
+ commands = svg_path_to_absolute(commands)
1756
+ commands = normalize_path_commands(commands)
1757
+ if not commands:
1758
+ return DEFAULT
1759
+ return _clip_commands_to_geom(
1760
+ commands, raw_x, raw_y, raw_w, raw_h, is_obb,
1761
+ )
1762
+
1763
+ # --- Polygon → custGeom ---
1764
+ if shape_tag == 'polygon':
1765
+ pts = _parse_points(shape.get('points', ''))
1766
+ if not pts:
1767
+ return DEFAULT
1768
+ commands = [PathCommand('M', [pts[0][0], pts[0][1]])]
1769
+ for px_, py_ in pts[1:]:
1770
+ commands.append(PathCommand('L', [px_, py_]))
1771
+ commands.append(PathCommand('Z', []))
1772
+ return _clip_commands_to_geom(
1773
+ commands, raw_x, raw_y, raw_w, raw_h, is_obb,
1774
+ )
1775
+
1776
+ return DEFAULT
1777
+
1778
+
1779
+ # ---------------------------------------------------------------------------
1780
+ # image
1781
+ # ---------------------------------------------------------------------------
1782
+
1783
+ def _picture_xfrm_from_rect(
1784
+ ctx: ConvertContext,
1785
+ x: float,
1786
+ y: float,
1787
+ w: float,
1788
+ h: float,
1789
+ ) -> tuple[str, int, int, int, int, tuple[int, int, int, int]]:
1790
+ """Build DrawingML xfrm data for a picture rectangle.
1791
+
1792
+ Coordinates `x`, `y`, `w`, `h` MUST already be in ctx-resolved
1793
+ space (i.e. callers have applied `ctx_x` / `ctx_w` upstream). When
1794
+ `ctx.use_transform_matrix` is set, raw SVG-space coordinates are
1795
+ expected and the matrix path applies the transform itself.
1796
+ """
1797
+ if ctx.use_transform_matrix:
1798
+ return rect_to_dml_xfrm(x, y, w, h, ctx.transform_matrix)
1799
+
1800
+ off_x = px_to_emu(x)
1801
+ off_y = px_to_emu(y)
1802
+ ext_cx = px_to_emu(w)
1803
+ ext_cy = px_to_emu(h)
1804
+ return '', off_x, off_y, ext_cx, ext_cy, (off_x, off_y, off_x + ext_cx, off_y + ext_cy)
1805
+
1806
+
1807
+ def _picture_xfrm_from_svg_rect(
1808
+ ctx: ConvertContext,
1809
+ raw_x: float,
1810
+ raw_y: float,
1811
+ raw_w: float,
1812
+ raw_h: float,
1813
+ resolved_x: float,
1814
+ resolved_y: float,
1815
+ resolved_w: float,
1816
+ resolved_h: float,
1817
+ transform: str | None,
1818
+ ) -> tuple[str, int, int, int, int, tuple[int, int, int, int]]:
1819
+ """Build picture xfrm data, honoring element-level SVG transforms.
1820
+
1821
+ `raw_*` values stay in the element's source SVG coordinate space for
1822
+ matrix decomposition; `resolved_*` values are the existing scalar path.
1823
+ """
1824
+ if ctx.use_transform_matrix:
1825
+ matrix = ctx.transform_matrix
1826
+ if transform:
1827
+ matrix = matrix_multiply(matrix, parse_transform_matrix(transform))
1828
+ return rect_to_dml_xfrm(raw_x, raw_y, raw_w, raw_h, matrix)
1829
+
1830
+ if transform:
1831
+ context_matrix = (
1832
+ ctx.scale_x, 0.0,
1833
+ 0.0, ctx.scale_y,
1834
+ ctx.translate_x, ctx.translate_y,
1835
+ )
1836
+ matrix = matrix_multiply(context_matrix, parse_transform_matrix(transform))
1837
+ return rect_to_dml_xfrm(raw_x, raw_y, raw_w, raw_h, matrix)
1838
+
1839
+ return _picture_xfrm_from_rect(ctx, resolved_x, resolved_y, resolved_w, resolved_h)
1840
+
1841
+
1842
+ def _read_image_size(data: bytes) -> tuple[int | None, int | None]:
1843
+ """Read intrinsic image dimensions (width, height) from raw bytes.
1844
+
1845
+ Used by `convert_image` to translate SVG `preserveAspectRatio` into
1846
+ DrawingML `<a:srcRect>` so the original image is preserved and remains
1847
+ croppable inside PowerPoint.
1848
+
1849
+ Returns (None, None) on any failure — callers fall back to the
1850
+ legacy stretch behaviour.
1851
+ """
1852
+ try:
1853
+ from PIL import Image, UnidentifiedImageError # type: ignore
1854
+ except ImportError:
1855
+ return (None, None)
1856
+ try:
1857
+ with Image.open(io.BytesIO(data)) as img:
1858
+ return img.size
1859
+ except (UnidentifiedImageError, OSError, ValueError):
1860
+ return (None, None)
1861
+
1862
+
1863
+ def _parse_preserve_aspect_ratio(par: str | None) -> tuple[str, str]:
1864
+ """Parse SVG preserveAspectRatio into (align, mode)."""
1865
+ parts = (par or 'xMidYMid meet').strip().split()
1866
+ align = parts[0] if parts else 'xMidYMid'
1867
+ mode = parts[1] if len(parts) > 1 else 'meet'
1868
+ return align, mode
1869
+
1870
+
1871
+ def _image_has_alpha(img: Any) -> bool:
1872
+ """Return whether a PIL image carries useful transparency."""
1873
+ if img.mode in ('RGBA', 'LA'):
1874
+ return True
1875
+ if img.mode == 'P':
1876
+ return 'transparency' in getattr(img, 'info', {})
1877
+ return False
1878
+
1879
+
1880
+ def _image_target_size(
1881
+ display_w: float,
1882
+ display_h: float,
1883
+ *,
1884
+ max_dimension: int | None,
1885
+ scale: float,
1886
+ ) -> tuple[int, int]:
1887
+ """Resolve optimized pixel dimensions from rendered SVG dimensions."""
1888
+ target_w = max(1, int(round(display_w * max(scale, 1.0))))
1889
+ target_h = max(1, int(round(display_h * max(scale, 1.0))))
1890
+ if max_dimension and max(target_w, target_h) > max_dimension:
1891
+ ratio = max_dimension / max(target_w, target_h)
1892
+ target_w = max(1, int(round(target_w * ratio)))
1893
+ target_h = max(1, int(round(target_h * ratio)))
1894
+ return target_w, target_h
1895
+
1896
+
1897
+ def _fit_full_image_target(
1898
+ img_w: int,
1899
+ img_h: int,
1900
+ box_w: float,
1901
+ box_h: float,
1902
+ align: str,
1903
+ mode: str,
1904
+ *,
1905
+ sizing: str,
1906
+ max_dimension: int | None,
1907
+ scale: float,
1908
+ ) -> tuple[int, int]:
1909
+ """Size the full source image; never crop pixels.
1910
+
1911
+ `cap` mode only limits oversized source images by maximum dimension.
1912
+ `display` mode sizes to the rendered SVG box budget.
1913
+ """
1914
+ if img_w <= 0 or img_h <= 0:
1915
+ return (1, 1)
1916
+
1917
+ if sizing == 'cap':
1918
+ target_w, target_h = img_w, img_h
1919
+ if max_dimension and max(target_w, target_h) > max_dimension:
1920
+ ratio = max_dimension / max(target_w, target_h)
1921
+ target_w = max(1, int(round(target_w * ratio)))
1922
+ target_h = max(1, int(round(target_h * ratio)))
1923
+ return target_w, target_h
1924
+
1925
+ target_box_w, target_box_h = _image_target_size(
1926
+ box_w,
1927
+ box_h,
1928
+ max_dimension=None,
1929
+ scale=scale,
1930
+ )
1931
+ img_ratio = img_w / img_h
1932
+ box_ratio = box_w / box_h if box_h else img_ratio
1933
+
1934
+ if align != 'none' and mode == 'slice':
1935
+ if box_ratio >= img_ratio:
1936
+ target_w = target_box_w
1937
+ target_h = int(round(target_w / img_ratio))
1938
+ else:
1939
+ target_h = target_box_h
1940
+ target_w = int(round(target_h * img_ratio))
1941
+ else:
1942
+ ratio = min(target_box_w / img_w, target_box_h / img_h, 1.0)
1943
+ target_w = int(round(img_w * ratio))
1944
+ target_h = int(round(img_h * ratio))
1945
+
1946
+ target_w = max(1, target_w)
1947
+ target_h = max(1, target_h)
1948
+ if max_dimension and max(target_w, target_h) > max_dimension:
1949
+ ratio = max_dimension / max(target_w, target_h)
1950
+ target_w = max(1, int(round(target_w * ratio)))
1951
+ target_h = max(1, int(round(target_h * ratio)))
1952
+ return target_w, target_h
1953
+
1954
+
1955
+ def _resize_for_target(img: Any, target_w: int, target_h: int) -> Any:
1956
+ """Downscale a PIL image to the target dimensions without upsampling."""
1957
+ width, height = img.size
1958
+ if target_w >= width and target_h >= height:
1959
+ return img
1960
+ ratio = min(target_w / width, target_h / height)
1961
+ if ratio >= 1.0:
1962
+ return img
1963
+ try:
1964
+ from PIL import Image # type: ignore
1965
+ except ImportError:
1966
+ return img
1967
+ new_size = (max(1, int(round(width * ratio))), max(1, int(round(height * ratio))))
1968
+ return img.resize(new_size, Image.Resampling.LANCZOS)
1969
+
1970
+
1971
+ def _encode_optimized_image(img: Any, *, prefer_jpeg: bool, quality: int) -> tuple[bytes, str] | None:
1972
+ """Encode a PIL image for PPTX media."""
1973
+ buf = io.BytesIO()
1974
+ try:
1975
+ if prefer_jpeg and not _image_has_alpha(img):
1976
+ if img.mode != 'RGB':
1977
+ img = img.convert('RGB')
1978
+ img.save(buf, format='JPEG', quality=max(1, min(quality, 100)), optimize=True)
1979
+ return buf.getvalue(), 'jpg'
1980
+ if img.mode == 'P':
1981
+ img = img.convert('RGBA' if _image_has_alpha(img) else 'RGB')
1982
+ img.save(buf, format='PNG', optimize=True)
1983
+ return buf.getvalue(), 'png'
1984
+ except (OSError, ValueError):
1985
+ return None
1986
+
1987
+
1988
+ def _optimize_image_for_pptx(
1989
+ elem: ET.Element,
1990
+ ctx: ConvertContext,
1991
+ img_data: bytes,
1992
+ img_format: str,
1993
+ box_w: float,
1994
+ box_h: float,
1995
+ ) -> tuple[bytes, str]:
1996
+ """Optimize full raster image bytes for native PPTX embedding."""
1997
+ if not ctx.image_optimize:
1998
+ return img_data, img_format
1999
+ if img_format.lower() in {'svg', 'emf', 'wmf'}:
2000
+ return img_data, img_format
2001
+
2002
+ try:
2003
+ from PIL import Image, UnidentifiedImageError # type: ignore
2004
+ except ImportError:
2005
+ return img_data, img_format
2006
+
2007
+ try:
2008
+ img = Image.open(io.BytesIO(img_data))
2009
+ img.load()
2010
+ except (UnidentifiedImageError, OSError, ValueError):
2011
+ return img_data, img_format
2012
+
2013
+ # Multi-frame images (animated GIF / WebP / APNG): resize/re-encode
2014
+ # below keeps frame 0 only, flattening the animation in the exported
2015
+ # PPTX. Pass the original bytes through — animations are exempt from
2016
+ # optimization and the size cap (before this optimizer existed, the
2017
+ # native path embedded raster bytes verbatim and animations survived).
2018
+ if getattr(img, 'is_animated', False):
2019
+ return img_data, img_format
2020
+
2021
+ align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
2022
+ target_w, target_h = _fit_full_image_target(
2023
+ img.size[0],
2024
+ img.size[1],
2025
+ box_w,
2026
+ box_h,
2027
+ align,
2028
+ mode,
2029
+ sizing=ctx.image_sizing,
2030
+ max_dimension=ctx.image_max_dimension,
2031
+ scale=ctx.image_scale,
2032
+ )
2033
+
2034
+ original_size = img.size
2035
+ img = _resize_for_target(img, target_w, target_h)
2036
+ resized = img.size != original_size
2037
+ prefer_jpeg = img_format.lower() in {'png', 'jpg', 'jpeg', 'bmp', 'tif', 'tiff'}
2038
+ encoded = _encode_optimized_image(img, prefer_jpeg=prefer_jpeg, quality=ctx.image_quality)
2039
+ if encoded is None:
2040
+ return img_data, img_format
2041
+
2042
+ optimized_data, optimized_format = encoded
2043
+ if not resized and len(optimized_data) >= len(img_data):
2044
+ return img_data, img_format
2045
+
2046
+ return optimized_data, optimized_format
2047
+
2048
+
2049
+ def _compute_slice_src_rect(
2050
+ img_w: float, img_h: float,
2051
+ box_w: float, box_h: float,
2052
+ align: str,
2053
+ ) -> tuple[int, int, int, int] | None:
2054
+ """Compute DrawingML `<a:srcRect>` (l, t, r, b) for SVG slice mode.
2055
+
2056
+ SVG preserveAspectRatio="<align> slice" means: scale the image so it
2057
+ fully covers the box (CSS object-fit: cover) and crop the overflow at the
2058
+ given alignment anchor. DrawingML `srcRect` expresses the same intent
2059
+ by specifying which sub-rectangle of the source image to display, in
2060
+ units of 1/1000 of a percent (0–100000).
2061
+
2062
+ Returns `None` when no cropping is required (image and box already
2063
+ match) or when inputs are degenerate.
2064
+ """
2065
+ if img_w <= 0 or img_h <= 0 or box_w <= 0 or box_h <= 0:
2066
+ return None
2067
+
2068
+ # Scale factor that makes the image cover the box (cover semantics).
2069
+ scale = max(box_w / img_w, box_h / img_h)
2070
+ visible_w = box_w / scale # ≤ img_w
2071
+ visible_h = box_h / scale # ≤ img_h
2072
+
2073
+ if abs(visible_w - img_w) < 0.5 and abs(visible_h - img_h) < 0.5:
2074
+ return None # No crop needed
2075
+
2076
+ crop_w_total = max(0.0, img_w - visible_w)
2077
+ crop_h_total = max(0.0, img_h - visible_h)
2078
+
2079
+ x_anchor = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}.get(align[:4], 0.5)
2080
+ y_anchor = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}.get(align[4:], 0.5)
2081
+
2082
+ crop_l = crop_w_total * x_anchor
2083
+ crop_r = crop_w_total - crop_l
2084
+ crop_t = crop_h_total * y_anchor
2085
+ crop_b = crop_h_total - crop_t
2086
+
2087
+ l = max(0, min(100000, int(round(crop_l / img_w * 100000))))
2088
+ t = max(0, min(100000, int(round(crop_t / img_h * 100000))))
2089
+ r = max(0, min(100000, int(round(crop_r / img_w * 100000))))
2090
+ b = max(0, min(100000, int(round(crop_b / img_h * 100000))))
2091
+
2092
+ return (l, t, r, b)
2093
+
2094
+
2095
+ def _resolve_image_src_rect(
2096
+ elem: ET.Element,
2097
+ img_data: bytes,
2098
+ box_w: float, box_h: float,
2099
+ ) -> str:
2100
+ """Build <a:srcRect .../> XML for an SVG <image> based on its
2101
+ preserveAspectRatio. Returns an empty string when no srcRect is needed
2102
+ (meet mode, none mode, or already-aligned content).
2103
+
2104
+ Slice mode is resolved into a srcRect so the original image is embedded
2105
+ intact and PowerPoint's crop tool / "Reset Picture" continue to work.
2106
+ Meet mode is handled separately by `_resolve_image_meet_fit` (which
2107
+ shrinks the picture frame to match image aspect ratio); none mode keeps
2108
+ the legacy stretch behaviour intentionally.
2109
+ """
2110
+ align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
2111
+
2112
+ if align == 'none' or mode != 'slice':
2113
+ return '' # meet handled by frame fit; none → stretch is correct per SVG spec
2114
+
2115
+ img_w, img_h = _read_image_size(img_data)
2116
+ if img_w is None or img_h is None:
2117
+ return ''
2118
+
2119
+ rect = _compute_slice_src_rect(float(img_w), float(img_h), box_w, box_h, align)
2120
+ if rect is None:
2121
+ return ''
2122
+
2123
+ l, t, r, b = rect
2124
+ return f'<a:srcRect l="{l}" t="{t}" r="{r}" b="{b}"/>'
2125
+
2126
+
2127
+ def _resolve_image_meet_fit(
2128
+ elem: ET.Element,
2129
+ img_data: bytes,
2130
+ box_w: float, box_h: float,
2131
+ ) -> tuple[float, float, float, float] | None:
2132
+ """For SVG preserveAspectRatio="<align> meet", compute the letterboxed
2133
+ sub-rectangle (dx, dy, fit_w, fit_h) inside the original box that
2134
+ matches the image's intrinsic aspect ratio.
2135
+
2136
+ PowerPoint has no native `meet` semantic — `<a:stretch><a:fillRect/>`
2137
+ fills the entire frame and would distort the image whenever the SVG
2138
+ container ratio differs from the source image ratio. The fix is to shrink
2139
+ the `<p:pic>` frame itself (off + ext) so the frame and image share an
2140
+ aspect ratio; the stretch then fills a correctly-shaped frame.
2141
+
2142
+ Returns `None` when the adjustment is not applicable:
2143
+ - mode is `slice` (handled by srcRect path)
2144
+ - align is `none` (SVG spec says: stretch — do not adjust)
2145
+ - intrinsic image dimensions cannot be read
2146
+ - frame already matches image ratio (no-op)
2147
+ """
2148
+ align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
2149
+
2150
+ if align == 'none' or mode == 'slice':
2151
+ return None
2152
+
2153
+ img_w, img_h = _read_image_size(img_data)
2154
+ if img_w is None or img_h is None or img_w <= 0 or img_h <= 0:
2155
+ return None
2156
+ if box_w <= 0 or box_h <= 0:
2157
+ return None
2158
+
2159
+ scale = min(box_w / img_w, box_h / img_h)
2160
+ fit_w = img_w * scale
2161
+ fit_h = img_h * scale
2162
+
2163
+ if abs(fit_w - box_w) < 0.5 and abs(fit_h - box_h) < 0.5:
2164
+ return None # already matches — no adjustment
2165
+
2166
+ x_anchor = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}.get(align[:4], 0.5)
2167
+ y_anchor = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}.get(align[4:], 0.5)
2168
+
2169
+ dx = (box_w - fit_w) * x_anchor
2170
+ dy = (box_h - fit_h) * y_anchor
2171
+
2172
+ return (dx, dy, fit_w, fit_h)
2173
+
2174
+
2175
+ def convert_image(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
2176
+ """Convert SVG <image> to DrawingML picture element.
2177
+
2178
+ Supports clip-path attribute: when present, the clipPath shape is mapped
2179
+ to DrawingML picture geometry (prstGeom or custGeom) so the image is
2180
+ natively clipped in PowerPoint.
2181
+ """
2182
+ href = elem.get('href') or elem.get(f'{{{XLINK_NS}}}href')
2183
+ if not href:
2184
+ return None
2185
+
2186
+ # Raw coordinates (pre-context-transform) for clip path calculations
2187
+ raw_x = svg_length_x(elem.get('x'), ctx)
2188
+ raw_y = svg_length_y(elem.get('y'), ctx)
2189
+ raw_w = svg_length_x(elem.get('width'), ctx)
2190
+ raw_h = svg_length_y(elem.get('height'), ctx)
2191
+
2192
+ if ctx.use_transform_matrix:
2193
+ x = raw_x
2194
+ y = raw_y
2195
+ w = raw_w
2196
+ h = raw_h
2197
+ else:
2198
+ x = ctx_x(raw_x, ctx)
2199
+ y = ctx_y(raw_y, ctx)
2200
+ w = ctx_w(raw_w, ctx)
2201
+ h = ctx_h(raw_h, ctx)
2202
+
2203
+ if w <= 0 or h <= 0:
2204
+ return None
2205
+
2206
+ # Extract image data
2207
+ if href.startswith('data:'):
2208
+ decoded = _decode_data_image_uri(href)
2209
+ if decoded is None:
2210
+ return None
2211
+ img_format, img_data = decoded
2212
+ else:
2213
+ if ctx.svg_dir is None:
2214
+ return None
2215
+ img_path = _resolve_external_image(ctx.svg_dir, href)
2216
+ img_format = img_path.suffix.lstrip('.').lower()
2217
+ if img_format == 'jpeg':
2218
+ img_format = 'jpg'
2219
+ img_data = img_path.read_bytes()
2220
+
2221
+ img_data, img_format = _optimize_image_for_pptx(
2222
+ elem, ctx, img_data, img_format, w, h,
2223
+ )
2224
+
2225
+ img_idx = len(ctx.media_files) + 1
2226
+ img_filename = f's{ctx.slide_num}_img{img_idx}.{img_format}'
2227
+ ctx.media_files[img_filename] = img_data
2228
+
2229
+ r_id = ctx.next_rel_id()
2230
+ ctx.rel_entries.append({
2231
+ 'id': r_id,
2232
+ 'type': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
2233
+ 'target': f'../media/{img_filename}',
2234
+ })
2235
+
2236
+ transform = elem.get('transform')
2237
+
2238
+ # Resolve clip-path → DrawingML geometry
2239
+ clip_geom = _resolve_clip_geometry(elem, ctx, raw_x, raw_y, raw_w, raw_h)
2240
+
2241
+ # Resolve preserveAspectRatio="<align> slice" as DrawingML crop metadata.
2242
+ # Image optimization only downscales the full source image; it never crops
2243
+ # pixels out of the embedded media.
2244
+ src_rect_xml = _resolve_image_src_rect(elem, img_data, w, h)
2245
+
2246
+ # Resolve preserveAspectRatio="<align> meet" by shrinking the picture
2247
+ # frame to match the image's aspect ratio. Skipped when a real clip-path
2248
+ # produces non-trivial geometry: such clip rectangles are defined against
2249
+ # the original box and would no longer line up after a frame shift.
2250
+ # A clip-path that resolves back to the default rect geometry (e.g. plain
2251
+ # <rect> without rx/ry) is a no-op and must not block meet adjustment.
2252
+ clip_is_noop = clip_geom == '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
2253
+ meet_fit = None if not clip_is_noop else _resolve_image_meet_fit(elem, img_data, w, h)
2254
+
2255
+ shape_id = ctx.next_id()
2256
+ if meet_fit is not None:
2257
+ dx, dy, fit_w, fit_h = meet_fit
2258
+ if ctx.use_transform_matrix:
2259
+ raw_fit_x = raw_x + dx
2260
+ raw_fit_y = raw_y + dy
2261
+ raw_fit_w = fit_w
2262
+ raw_fit_h = fit_h
2263
+ else:
2264
+ raw_fit_x = raw_x + (dx / ctx.scale_x if ctx.scale_x else dx)
2265
+ raw_fit_y = raw_y + (dy / ctx.scale_y if ctx.scale_y else dy)
2266
+ raw_fit_w = fit_w / ctx.scale_x if ctx.scale_x else fit_w
2267
+ raw_fit_h = fit_h / ctx.scale_y if ctx.scale_y else fit_h
2268
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _picture_xfrm_from_svg_rect(
2269
+ ctx,
2270
+ raw_fit_x,
2271
+ raw_fit_y,
2272
+ raw_fit_w,
2273
+ raw_fit_h,
2274
+ x + dx,
2275
+ y + dy,
2276
+ fit_w,
2277
+ fit_h,
2278
+ transform,
2279
+ )
2280
+ else:
2281
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _picture_xfrm_from_svg_rect(
2282
+ ctx,
2283
+ raw_x,
2284
+ raw_y,
2285
+ raw_w,
2286
+ raw_h,
2287
+ x,
2288
+ y,
2289
+ w,
2290
+ h,
2291
+ transform,
2292
+ )
2293
+
2294
+ return ShapeResult(xml=f'''<p:pic>
2295
+ <p:nvPicPr>
2296
+ <p:cNvPr id="{shape_id}" name="Image {shape_id}"/>
2297
+ <p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr>
2298
+ <p:nvPr/>
2299
+ </p:nvPicPr>
2300
+ <p:blipFill>
2301
+ <a:blip r:embed="{r_id}"/>
2302
+ {src_rect_xml}<a:stretch><a:fillRect/></a:stretch>
2303
+ </p:blipFill>
2304
+ <p:spPr>
2305
+ <a:xfrm{xfrm_attr}><a:off x="{off_x}" y="{off_y}"/>
2306
+ <a:ext cx="{ext_cx}" cy="{ext_cy}"/></a:xfrm>
2307
+ {clip_geom}
2308
+ </p:spPr>
2309
+ </p:pic>''', bounds_emu=bounds_emu)
2310
+
2311
+
2312
+ # ---------------------------------------------------------------------------
2313
+ # ellipse
2314
+ # ---------------------------------------------------------------------------
2315
+
2316
+ def convert_ellipse(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
2317
+ """Convert SVG <ellipse> to DrawingML ellipse shape."""
2318
+ raw_cx = svg_length_x(elem.get('cx'), ctx)
2319
+ raw_cy = svg_length_y(elem.get('cy'), ctx)
2320
+ raw_rx = svg_length_x(elem.get('rx'), ctx)
2321
+ raw_ry = svg_length_y(elem.get('ry'), ctx)
2322
+ cx_ = ctx_x(raw_cx, ctx)
2323
+ cy_ = ctx_y(raw_cy, ctx)
2324
+ rx = raw_rx * ctx.scale_x
2325
+ ry = raw_ry * ctx.scale_y
2326
+
2327
+ if rx <= 0 or ry <= 0:
2328
+ return None
2329
+
2330
+ x = cx_ - rx
2331
+ y = cy_ - ry
2332
+ w = rx * 2
2333
+ h = ry * 2
2334
+
2335
+ fill_op = get_fill_opacity(elem, ctx)
2336
+ stroke_op = get_stroke_opacity(elem, ctx)
2337
+ fill = build_fill_xml(elem, ctx, fill_op)
2338
+ stroke = build_stroke_xml(elem, ctx, stroke_op)
2339
+
2340
+ geom = '<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>'
2341
+
2342
+ transform = elem.get('transform')
2343
+
2344
+ shape_id = ctx.next_id()
2345
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _shape_xfrm_from_svg_rect(
2346
+ ctx,
2347
+ raw_cx - raw_rx,
2348
+ raw_cy - raw_ry,
2349
+ raw_rx * 2,
2350
+ raw_ry * 2,
2351
+ x,
2352
+ y,
2353
+ w,
2354
+ h,
2355
+ transform,
2356
+ )
2357
+ return ShapeResult(
2358
+ xml=_wrap_shape(
2359
+ shape_id, f'Ellipse {shape_id}',
2360
+ off_x, off_y, ext_cx, ext_cy,
2361
+ geom, fill, stroke, xfrm_attr=xfrm_attr,
2362
+ ),
2363
+ bounds_emu=bounds_emu,
2364
+ )
2365
+
2366
+
2367
+ # ---------------------------------------------------------------------------
2368
+ # nested <svg> sprite (template-import round-trip)
2369
+ # ---------------------------------------------------------------------------
2370
+
2371
+ # Inverse of pptx_to_svg/pic_to_svg.py:101-113 — that path writes a cropped
2372
+ # DrawingML picture as an outer <svg viewBox> wrapping a unit-rectangle <image>.
2373
+ # Without this converter, every cropped picture in a template-import SVG is
2374
+ # silently dropped on re-export.
2375
+
2376
+ def convert_nested_svg(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
2377
+ """Convert a nested <svg> sprite-crop wrapper to a DrawingML picture.
2378
+
2379
+ Pattern produced by pptx_to_svg::
2380
+
2381
+ <svg x="10" y="20" width="200" height="300" viewBox="0.5 0.3 0.5 0.7">
2382
+ <image href="..." x="0" y="0" width="1" height="1" preserveAspectRatio="none"/>
2383
+ </svg>
2384
+
2385
+ The viewBox crops the unit-rectangle inner image; that crop is mapped to a
2386
+ DrawingML <a:srcRect> so PowerPoint can re-crop / "Reset Picture".
2387
+ """
2388
+ image_elem = elem.find(f'{{{SVG_NS}}}image')
2389
+ if image_elem is None:
2390
+ image_elem = elem.find('image')
2391
+ if image_elem is None:
2392
+ return None
2393
+
2394
+ href = image_elem.get('href') or image_elem.get(f'{{{XLINK_NS}}}href')
2395
+ if not href:
2396
+ return None
2397
+
2398
+ svg_x = svg_length_x(elem.get('x'), ctx)
2399
+ svg_y = svg_length_y(elem.get('y'), ctx)
2400
+ svg_w = svg_length_x(elem.get('width'), ctx)
2401
+ svg_h = svg_length_y(elem.get('height'), ctx)
2402
+ if svg_w <= 0 or svg_h <= 0:
2403
+ return None
2404
+
2405
+ if ctx.use_transform_matrix:
2406
+ x = svg_x
2407
+ y = svg_y
2408
+ w = svg_w
2409
+ h = svg_h
2410
+ else:
2411
+ x = ctx_x(svg_x, ctx)
2412
+ y = ctx_y(svg_y, ctx)
2413
+ w = ctx_w(svg_w, ctx)
2414
+ h = ctx_h(svg_h, ctx)
2415
+
2416
+ src_rect_xml = ''
2417
+ view_box = elem.get('viewBox', '')
2418
+ if view_box:
2419
+ parts = view_box.strip().split()
2420
+ if len(parts) == 4:
2421
+ vb_x, vb_y, vb_w, vb_h = (float(p) for p in parts)
2422
+ l = max(0, min(int(round(vb_x * 100000)), 100000))
2423
+ t = max(0, min(int(round(vb_y * 100000)), 100000))
2424
+ r = max(0, min(int(round((1.0 - vb_x - vb_w) * 100000)), 100000))
2425
+ b = max(0, min(int(round((1.0 - vb_y - vb_h) * 100000)), 100000))
2426
+ if l or t or r or b:
2427
+ src_rect_xml = f'<a:srcRect l="{l}" t="{t}" r="{r}" b="{b}"/>'
2428
+
2429
+ if href.startswith('data:'):
2430
+ decoded = _decode_data_image_uri(href)
2431
+ if decoded is None:
2432
+ return None
2433
+ img_format, img_data = decoded
2434
+ else:
2435
+ if ctx.svg_dir is None:
2436
+ return None
2437
+ img_path = _resolve_external_image(ctx.svg_dir, href)
2438
+ img_format = img_path.suffix.lstrip('.').lower()
2439
+ if img_format == 'jpeg':
2440
+ img_format = 'jpg'
2441
+ img_data = img_path.read_bytes()
2442
+
2443
+ img_data, img_format = _optimize_image_for_pptx(
2444
+ image_elem, ctx, img_data, img_format, w, h,
2445
+ )
2446
+
2447
+ img_idx = len(ctx.media_files) + 1
2448
+ img_filename = f's{ctx.slide_num}_img{img_idx}.{img_format}'
2449
+ ctx.media_files[img_filename] = img_data
2450
+
2451
+ r_id = ctx.next_rel_id()
2452
+ ctx.rel_entries.append({
2453
+ 'id': r_id,
2454
+ 'type': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
2455
+ 'target': f'../media/{img_filename}',
2456
+ })
2457
+
2458
+ transform = elem.get('transform')
2459
+
2460
+ shape_id = ctx.next_id()
2461
+ xfrm_attr, off_x, off_y, ext_cx, ext_cy, bounds_emu = _picture_xfrm_from_svg_rect(
2462
+ ctx,
2463
+ svg_x,
2464
+ svg_y,
2465
+ svg_w,
2466
+ svg_h,
2467
+ x,
2468
+ y,
2469
+ w,
2470
+ h,
2471
+ transform,
2472
+ )
2473
+ clip_geom = _resolve_clip_geometry(elem, ctx, svg_x, svg_y, svg_w, svg_h)
2474
+
2475
+ return ShapeResult(xml=f'''<p:pic>
2476
+ <p:nvPicPr>
2477
+ <p:cNvPr id="{shape_id}" name="Image {shape_id}"/>
2478
+ <p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr>
2479
+ <p:nvPr/>
2480
+ </p:nvPicPr>
2481
+ <p:blipFill>
2482
+ <a:blip r:embed="{r_id}"/>
2483
+ {src_rect_xml}<a:stretch><a:fillRect/></a:stretch>
2484
+ </p:blipFill>
2485
+ <p:spPr>
2486
+ <a:xfrm{xfrm_attr}><a:off x="{off_x}" y="{off_y}"/>
2487
+ <a:ext cx="{ext_cx}" cy="{ext_cy}"/></a:xfrm>
2488
+ {clip_geom}
2489
+ </p:spPr>
2490
+ </p:pic>''', bounds_emu=bounds_emu)