Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(svg-authoring): normalize preview hrefs and enforce closed SVG contracts

hugohe37bcf80ad18ec
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 0a29c285..2169a891 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -40,7 +40,7 @@ The past two months' structural capability growth. Single flags / incremental po
- **Kubernetes Blueprint example deck shipped** ([`examples/ppt169_kubernetes_blueprint_2026/`](../examples/ppt169_kubernetes_blueprint_2026/)) — second of the three P0 capability-backing demos: isometric technical-drawing aesthetic + blueprint cyan/amber palette + hand-authored SVG geometry (no raster images) + custom drawing-in animation; 10-page Kubernetes architecture walkthrough stressing geometric shape generalization and chart-structure extensibility
- **AI image `custom` escape hatch** — `rendering` / `palette` / hero composition each accept `custom` + a one-paragraph `*_behavior` prose, replacing the false "default to vector-illustration / cool-corporate" fallback; end-to-end contract spans [`image-renderings/_index.md`](../skills/ppt-master/references/image-renderings/_index.md) §1.5, [`image-palettes/_index.md`](../skills/ppt-master/references/image-palettes/_index.md) §2, Strategist h.5 hard-rule (≤1 custom per dimension; one candidate may carry both), spec_lock fields, and Image_Generator Step 2 consumption branch
- **Template architecture: three-kind consolidation** ([`docs/templates-architecture.md`](./templates-architecture.md)) — brand / layout / deck split into three independent dirs with per-kind schemas + segment-level fusion + git-style conflict resolution; SKILL.md Step 3 dispatches per `kind`, trigger rule remains "explicit path only"
-- **Pattern fill PPTX safety net** — `svg_quality_checker.py` now warns on `<pattern>` without `data-pptx-pattern` (silent fallback to `ltUpDiag`) and errors on values outside OOXML `ST_PresetPatternVal` (schema-failed PPTX that won't open); `shared-standards.md §7` documents the closed preset enum and color resolution from importer metadata or child paint
+- **Pattern fill PPTX safety net** — `svg_quality_checker.py` rejects a referenced `<pattern>` that lacks `data-pptx-pattern`, uses `patternTransform`, or names a value outside OOXML `ST_PresetPatternVal`; the converter keeps its `ltUpDiag` fallback for historical input only. `shared-standards.md §7` documents the closed preset enum and color resolution from importer metadata or child paint
- **LaTeX math formula rendering shipped** ([`scripts/latex_render.py`](../skills/ppt-master/scripts/latex_render.py)) — Strategist locks one of three policies (`mixed` / `render-all` / `text-only`) inside the Typography confirmation and writes an explicit `images/formula_manifest.json`; the renderer walks a codecogs → quicklatex → mathpad → wikimedia fallback chain and emits transparent PNGs that land in §VIII as `Acquire Via: formula` / `Status: Rendered` rows; formula-heavy decks (academic / engineering / educational) finally have a native rendering route. Formula selection is a Strategist decision — the renderer never scans source files for `$...$` markers
- **Live preview direct editing — L1 / L2 / L3** ([`workflows/live-preview.md`](../skills/ppt-master/workflows/live-preview.md)) — the browser editor gains deterministic in-place edits with no AI round-trip: text content (L1), presentation attributes like fill / stroke / font-size (L2), and on-canvas geometry (L3) — drag a selected element to move it, arrow-key nudge (`Shift` = 10px), multi-select, plus a right-click overlap picker for stacked shapes. Edits stage with `Ctrl+Z` undo + coalescing and write to `svg_output/` on **Apply changes**; moves persist through finalize / export (moved text frames, promoted multi-line tspans, repositioned icons all reproduce in the PPTX). Re-export stays chat-driven; on-canvas resize handles are not yet implemented (resize via the geometry inputs)
diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.md
index d3736d6a..9ef3708f 100644
--- a/docs/zh/roadmap.md
+++ b/docs/zh/roadmap.md
@@ -40,7 +40,7 @@
- **Kubernetes Blueprint 示例 deck 交付**([`examples/ppt169_kubernetes_blueprint_2026/`](../../examples/ppt169_kubernetes_blueprint_2026/)) — P0 三档第二档落地:等距工程图美学 + 蓝图青/琥珀色板 + 全手写 SVG 几何(无 raster 图)+ 自定义"逐笔绘制"动画,10 页 Kubernetes 架构走读实压「几何形状泛化 + chart 结构扩展性」
- **AI 图 `custom` 兜底出口** — `rendering` / `palette` / hero 构图三处允许声明 `custom` + 一段 `*_behavior` prose,替换原"找不到匹配就硬塞 vector-illustration / cool-corporate"的假兜底;端到端契约:[`image-renderings/_index.md`](../../skills/ppt-master/references/image-renderings/_index.md) §1.5 + [`image-palettes/_index.md`](../../skills/ppt-master/references/image-palettes/_index.md) §2 + Strategist h.5 hard-rule(每维 ≤1 custom,单候选可双 custom)+ spec_lock 字段 + Image_Generator Step 2 消费分支
- **Template 架构三分类收口**([`docs/zh/templates-architecture.md`](./templates-architecture.md)) — brand / layout / deck 三独立目录 + 每类独立 schema + 段级合成 + git-style 冲突解决;SKILL.md Step 3 按 kind 分支处理,触发规则仍是「显式路径才触发」
-- **Pattern 填充 PPTX 安全网** — `svg_quality_checker.py` 现在对未标 `data-pptx-pattern` 的 `<pattern>` 元素发 warning(会静默回退 `ltUpDiag` 斜纹)、对超出 OOXML `ST_PresetPatternVal` 枚举的值发 error(schema 校验失败 PPT 无法打开);`shared-standards.md §7` 落地了完整 preset 清单,以及从导入元数据或子元素 paint 解析颜色的合同
+- **Pattern 填充 PPTX 安全网** — `svg_quality_checker.py` 现在拒绝被引用但缺少 `data-pptx-pattern`、使用 `patternTransform`,或命名超出 OOXML `ST_PresetPatternVal` 枚举值的 `<pattern>`;转换器仅为历史输入保留 `ltUpDiag` 回退。`shared-standards.md §7` 落地了完整 preset 清单,以及从导入元数据或子元素 paint 解析颜色的合同
- **LaTeX 数学公式渲染上线**([`scripts/latex_render.py`](../../skills/ppt-master/scripts/latex_render.py)) — Strategist 在 Typography 确认中锁定 `mixed` / `render-all` / `text-only` 三档策略,显式写 `images/formula_manifest.json`;脚本走 codecogs → quicklatex → mathpad → wikimedia 四源 fallback chain,输出透明 PNG 进 §VIII 表的 `Acquire Via: formula` / `Status: Rendered` 行;公式密集型 deck(学术 / 工程 / 教学)首次拥有原生渲染路径,规则面禁止扫源文件 `$...$` 自动渲染(公式选取是 Strategist 决策)
- **实时预览直接编辑 — L1 / L2 / L3**([`workflows/live-preview.md`](../../skills/ppt-master/workflows/live-preview.md)) — 浏览器编辑器新增无需 AI 往返的确定性就地编辑:文字内容(L1)、fill / stroke / font-size 等样式属性(L2)、以及画布上的几何操作(L3)——在选中元素上拖拽即移动、方向键微调(`Shift` = 10px)、多选、加右键重叠选择器选取堆叠元素。编辑支持 `Ctrl+Z` 撤销 + 合并,点 **Apply changes** 写回 `svg_output/`;移动经 finalize / 导出保位(移动的 text、提升的多行 tspan、重定位的 icon 都在 PPTX 中如实再现)。重新导出仍由对话触发;画布上的缩放手柄尚未实现(缩放走几何输入框)
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index eb688902..b421870b 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -7,8 +7,8 @@ Other files link here instead of restating its contracts.
| Section | Owns | Strength |
|---|---|---|
-| §1 Required Foundation, Forbidden Features, and Conditional Interfaces | XML validity, the exhaustive structural blacklist, native line ends, image clipping, static local reuse, and imported/authored native-shape semantics | Required / Forbidden / Conditional |
-| §2 Conditional Compatibility Mappings | Inline geometry and approximate group opacity | Conditional |
+| §1 Required Foundation, Forbidden Features, and Conditional Interfaces | XML validity, the closed generated-authoring surface, structural blacklist, native line ends, image clipping, static local reuse, and imported/authored native-shape semantics | Required / Forbidden / Conditional |
+| §2 Conditional Compatibility Mappings | Literal inline geometry and the converter-only group-opacity boundary | Conditional / Forbidden |
| §3 Canvas Format Quick Reference | Pointer to the complete canvas catalog | Reference |
| §4 Required Page Contract and Conditional Packaging | Complete-page authority, semantic markers, editable text/grouping, and package promotion | Required / Conditional |
| §5 Workflow Authority | Pointer to the serial post-processing/export procedure | Workflow pointer |
@@ -20,7 +20,7 @@ Other files link here instead of restating its contracts.
| Capability family | Available authoring vocabulary | Detail |
|---|---|---|
-| Color and transparency | CSS alpha colors; fill, stroke, text, picture, stop, element, and group opacity | §2.2, §6.2 |
+| Color and transparency | CSS alpha colors; fill, stroke, text, picture, stop, and element opacity; converter-only group-opacity compatibility | §2.2, §6.2 |
| Gradients and paint | Linear/radial fills, transparent stops, gradient text, gradient strokes, and preset patterns | §6.3, §7 |
| Depth and light | Soft/colored/directional shadow, glow, layered-geometry fallback, and paper-layer elevation | §6.4 |
| Image treatment | Directional scrim, bottom fade, vignette, spotlight, brand wash, picture fading, and glass-like surfaces | §1.2, §6.5 |
@@ -51,6 +51,17 @@ Other files link here instead of restating its contracts.
- **Reference — not a constraint** passages expose capabilities and recipes; they do not require every page or visual style to use them.
- The locked `visual_style` controls whether and how strongly a compatible effect is used. It never expands the technical boundary.
+**Hard rule — generated authoring is fail-closed**: `svg_output/` and reusable
+template SVGs may use only properties and conditional interfaces explicitly
+listed in this file. `svg_quality_checker.py` rejects unknown inline visual
+properties and incomplete conditional contracts before export.
+
+**Hard rule — compatibility is not authoring permission**: the converter may
+retain broader read compatibility for imported or historical SVG, including
+normalization and documented approximation. That compatibility does not add a
+feature to the generated-authoring surface. Do not remove converter support
+merely to enforce a narrower authoring contract.
+
**Hard rule — one-way fidelity vocabulary**: the labels above describe the
`svg_output/` → generated PPTX path. They do not promise reconstruction of the
original SVG syntax, `<defs>` graph, `<use>` structure, path commands, or
@@ -92,9 +103,25 @@ One offending character invalidates the file and aborts export.
| `<script>` / event attributes | Scripts and interactivity |
| `<iframe>` | Embedded frames |
-The blacklist above is exhaustive for globally forbidden SVG syntax. Features
-that require a restricted form are not globally forbidden; they are documented
-under the conditional contracts below.
+The blacklist above is exhaustive for globally forbidden structural syntax.
+It is not a positive allowlist for every browser-rendered property. Features
+that require a restricted form are valid only under the conditional contracts
+below; unlisted visual properties are unsupported.
+
+**Hard rule — inline visual-property allowlist**:
+
+| Property family | Allowed inline `style` properties |
+|---|---|
+| Paint and line | `fill`, `stroke`, `stroke-width`, `stroke-dasharray`, `stroke-linecap`, `stroke-linejoin`, `fill-opacity`, `stroke-opacity`, `vector-effect` |
+| Text | `font-family`, `font-size`, `font-weight`, `font-style`, `text-anchor`, `letter-spacing`, `text-decoration` |
+| Alpha and definition paint | `opacity`, `stop-color`, `stop-opacity`, `flood-color`, `flood-opacity` |
+| Literal geometry | The element-specific properties in §2.1 |
+| Preview-only | `shape-rendering`; it does not change native geometry |
+
+Conditional properties with a required XML form stay out of inline style:
+write `filter="url(#id)"`, `clip-path="url(#id)"`, and
+`marker-start` / `marker-end` as direct attributes. `!important`, unknown CSS
+properties, blend modes, isolation, and backdrop filters fail quality check.
> **`marker-start` / `marker-end` is conditional** — see §1.1.
>
@@ -106,8 +133,8 @@ under the conditional contracts below.
>
> **Authored native preset fragments are conditional** — see §1.5.
>
-> **Inline CSS geometry, group opacity, simple gradients, and filters are
-> conditional** — see §2 and §6.
+> **Inline CSS geometry, simple gradients, and filters are conditional;
+> generated group opacity is forbidden** — see §2 and §6.
>
> **PPT preset patterns and native chart/table/template metadata are
> conditional** — see §7.
@@ -171,13 +198,13 @@ the original `<use>` / `<symbol>` structure.
| Concern | Required form |
|---|---|
-| Reference syntax | Exact same-document fragment: `href="#id"` or `xlink:href="#id"`. If both attributes exist, their values MUST match. |
+| Reference syntax | Author new SVG with the SVG 2 form `href="#id"`. Legacy `xlink:href="#id"` remains read-compatible and Live Preview normalizes it to `href`; if both attributes exist, their values MUST match. |
| Referenced target | One of `<symbol>`, `<g>`, `<use>`, `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<path>`, `<polygon>`, `<polyline>`, `<text>`, or `<image>`. Nested local `<use>` is recursively expanded. |
| Instance position | `<use x>` / `<use y>` are finite unitless or `px` values; omitted values default to `0`. |
| Symbol viewport | A referenced `<symbol>` MUST have a finite four-number `viewBox` with positive width/height. Its `<use>` MUST have positive finite unitless or `px` `width` and `height`. |
| Aspect ratio | Default/aligned `meet` values and plain `preserveAspectRatio="none"` are supported. `slice`, `refX`, and `refY` are forbidden. |
| Viewport boundary | Symbol artwork MUST stay inside its `viewBox`; expansion does not reproduce symbol overflow clipping. |
-| Internal references | Reusable subtrees use exact fragment forms: `href="#id"`, `xlink:href="#id"`, and `url(#id)`. The expander rewrites these references together with instance-local cloned IDs. |
+| Internal references | Author exact `href="#id"` and `url(#id)` fragments. The expander also reads legacy `xlink:href="#id"` and rewrites all instance-local cloned IDs. |
| Structural metadata | Neither the `<use>` instance nor its referenced subtree may carry `data-pptx-layer*`, `data-pptx-native*`, or `data-pptx-placeholder*`. Author those objects directly instead of reusing them. |
| Safety limits | A reachable reference chain may contain at most 64 instances, and one SVG may expand at most 10,000 local `<use>` instances. |
@@ -193,8 +220,7 @@ the original `<use>` / `<symbol>` structure.
**Contract example**:
```xml
-<svg xmlns="http://www.w3.org/2000/svg"
- xmlns:xlink="http://www.w3.org/1999/xlink">
+<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<symbol id="statusDot" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet">
<circle cx="10" cy="10" r="8" fill="#16A34A"/>
@@ -205,7 +231,7 @@ the original `<use>` / `<symbol>` structure.
</g>
</defs>
<use href="#statusDot" x="80" y="120" width="32" height="32"/>
- <use xlink:href="#legendRow" x="120" y="120"/>
+ <use href="#legendRow" x="120" y="120"/>
</svg>
```
@@ -382,14 +408,19 @@ only for literal declarations in an element's own `style` attribute; PPT Master
does not compute CSS cascade or custom properties. Root canvas authority remains
the `viewBox`, regardless of root `<svg>` compatibility width/height values.
-### 2.2 Group Opacity Is Approximate
+### 2.2 Group Opacity Is Converter-Only Compatibility
-`<g opacity="0.3">...</g>` maps the group alpha onto each descendant shape,
-text run, picture, and supported
-shadow/glow effect. Nested group and child opacity values multiply. Overlapping
-children may differ from SVG isolated-group compositing because DrawingML has no
-equivalent group-alpha model. With `--native-objects`, transparent native
-table/chart markers are rejected; omit that flag to export their SVG fallback.
+**Forbidden — generated group opacity**: Do not author `<g opacity="...">` or
+inline group `opacity` below `1` in `svg_output/` or reusable templates. Put the
+required alpha on each descendant paint, text run, picture, or supported effect.
+The quality checker rejects generated group opacity because DrawingML has no
+isolated group-alpha model and overlapping descendants produce a different
+result.
+
+The converter retains direct-read compatibility for historical/imported SVG by
+multiplying group alpha into descendants. That path is `Approximate`; nested
+group/child alpha multiplies, and `--native-objects` rejects transparent native
+table/chart markers. It is not an authoring permission.
---
@@ -443,7 +474,7 @@ These forms are needed only when the stated PPT behavior matters:
### 4.3 Element Grouping (Mandatory)
-Wrap logically related Slide-local elements in top-level `<g id="...">` groups. This is **required on every generated page**, not an optional convenience: it produces real PowerPoint groups in the exported PPTX and gives each content unit a stable animation anchor. Plain `<g>` is the normal grouping primitive; `<g opacity="0..1">` additionally maps to the per-descendant alpha approximation in §2.2. Flat free-design/brand-only pages use only ordinary semantic groups. On structured template pages, direct atomic Master/Layout elements are the required exception and a top-level slot `<g>` is already a semantic group.
+Wrap logically related Slide-local elements in top-level `<g id="...">` groups. This is **required on every generated page**, not an optional convenience: it produces real PowerPoint groups in the exported PPTX and gives each content unit a stable animation anchor. Plain `<g>` is the grouping primitive; keep alpha on individual descendants per §2.2. Flat free-design/brand-only pages use only ordinary semantic groups. On structured template pages, direct atomic Master/Layout elements are the required exception and a top-level slot `<g>` is already a semantic group.
**Semantic-group rule**: direct Slide content uses semantic groups. Aim for **3–8 ordinary top-level content `<g id>` groups per slide**; on structured template pages, slot groups and atomic Master/Layout objects are excluded. Each ordinary group becomes one entrance step under the chosen animation trigger. Leaving Slide-local titles, body lines, list items, cards, or decorative clusters as ungrouped top-level atoms is a contract violation.
@@ -527,22 +558,23 @@ without `#` is invalid.
| Element `opacity` | Alpha compiled into supported paint/effect channels | `Native-normalized` |
| `<image opacity>` | Picture `<a:alphaModFix>` | `Native-stable` |
| `<stop stop-opacity>` | Per-stop gradient alpha | `Native-stable` |
-| `<g opacity>` | Alpha multiplied into each supported descendant shape, text run, picture, and effect | `Approximate` |
+| `<g opacity>` | Direct-converter compatibility only; generated SVG authoring is forbidden | `Approximate`; §2.2 |
| Pattern child/color alpha | Preset-pattern foreground/background alpha | Conditional; §7 |
```text
effective fill alpha
-= color alpha × element opacity × fill-opacity × ancestor group opacity
+= color alpha × element opacity × fill-opacity
```
+The converter-only historical path may additionally multiply ancestor group
+opacity; generated SVG never depends on that approximation.
+
**Hard rule — alpha grammar**: write `opacity`, `fill-opacity`,
-`stroke-opacity`, and `stop-opacity` as finite numbers from `0` to `1`.
+`stroke-opacity`, `stop-opacity`, and `flood-opacity` as finite unitless numbers
+from `0` to `1`.
`fill="transparent"` / `stroke="transparent"` become no fill/line; use a color
plus alpha when a painted transparent layer must remain represented. Group
-alpha is not isolated compositing, so overlapping descendants may differ from
-the browser. Transparent groups around `data-pptx-native` chart/table markers
-cannot be promoted under `--native-objects`; export the SVG fallback or remove
-the group opacity.
+opacity below `1` is forbidden in generated SVG; assign alpha to descendants.
---
@@ -597,12 +629,12 @@ Filters are native-effect metadata, not a general pixel-filter surface.
| Classification | Meaningful non-zero offset → one outer shadow; zero/no offset → one glow |
| Fidelity | `Approximate`; one filter becomes one DrawingML effect |
-Flood/color alpha, linear `feFuncA slope`, element opacity, and ancestor opacity
-multiply. Native export does not preserve filter-region, `in/in2/result`, merge
-order, or composite topology. Other primitives, multiple independent effects,
-filters on `<image>` / `<tspan>` / unsupported targets are forbidden. Do not
-put a filter on a multi-element `<g>`; apply it to supported objects or use
-explicit layers.
+Flood/color alpha, linear `feFuncA slope`, and element opacity multiply. The
+converter-only historical path may also multiply ancestor group opacity.
+Native export does not preserve filter-region, `in/in2/result`, merge order, or
+composite topology. Other primitives, multiple independent effects, filters on
+`<image>` / `<tspan>` / `<g>` / unsupported targets are forbidden; apply the
+effect to supported objects or use explicit layers.
```xml
<defs>
@@ -746,7 +778,7 @@ modes, generated effects, and text-image knockouts are outside editable text.
| Positive scale / negative mirror | Geometry/image only; explicit pivot; `Native-normalized` |
| `matrix(a b c d e f)` | Geometry/image only; transformed axes finite, non-zero, orthogonal; excludes rounded rects; `Native-normalized` |
| Source order | Back-to-front PPT z-order; `Native-stable` |
-| `<g opacity>` | Descendant alpha; `Approximate`, §2.2 |
+| `<g opacity>` | Converter-only historical compatibility; forbidden in generated SVG, §2.2 |
| Local `<use>` | §1.3 compile-time reuse; `Native-normalized` |
Set text size/position directly; do not scale or general-matrix text. `skewX`,
@@ -970,7 +1002,8 @@ the tile's arbitrary geometry. Use this interface only when that preset mapping
is intended.
`data-pptx-pattern="<preset>"` is required to select the intended preset from
-the enum below; without it, export falls back to `ltUpDiag`.
+the enum below. The converter retains an `ltUpDiag` fallback for historical
+input, but generated authoring without the annotation fails quality check.
Pattern colors may come from importer metadata (`data-pptx-fg` /
`data-pptx-bg`) or from the pattern's child paint. Without metadata, the first
@@ -990,8 +1023,8 @@ itself is never used as a repeatable tile.
| Checks & confetti | `smCheck` · `lgCheck` · `smConfetti` · `lgConfetti` |
| Decorative | `horzBrick` · `diagBrick` · `weave` · `plaid` · `trellis` · `zigZag` · `wave` · `sphere` · `divot` · `shingle` · `solidDmnd` · `openDmnd` · `dotDmnd` |
-`svg_quality_checker.py` warns when the annotation is missing and errors when
-the preset is outside this enum.
+`svg_quality_checker.py` errors when a referenced pattern lacks the annotation,
+uses `patternTransform`, or names a preset outside this enum.
### Native PPTX Table / Chart Markers (Opt-in)
diff --git a/skills/ppt-master/scripts/svg_editor/annotations.py b/skills/ppt-master/scripts/svg_editor/annotations.py
index 7a02353c..d7e252ef 100644
--- a/skills/ppt-master/scripts/svg_editor/annotations.py
+++ b/skills/ppt-master/scripts/svg_editor/annotations.py
@@ -19,9 +19,11 @@ from copy import deepcopy
from typing import Optional
SVG_NS = 'http://www.w3.org/2000/svg'
+XLINK_NS = 'http://www.w3.org/1999/xlink'
-# Register namespace to avoid ns0: prefix in output
+# Register namespaces to avoid generated ns0/ns1 prefixes in saved SVGs.
ET.register_namespace('', SVG_NS)
+ET.register_namespace('xlink', XLINK_NS)
def assign_temp_ids(root: ET.Element) -> None:
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index d1d74a74..25cf747c 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -97,6 +97,7 @@ from svg_to_pptx.geometry_properties import ( # noqa: E402
_ICONS_DIR = _SCRIPTS_DIR.parent.parent / 'templates' / 'icons'
_USE_ICON_PATTERN = re.compile(r'<use\s+[^>]*data-icon="[^"]*"[^>]*/>')
+_XLINK_HREF = '{http://www.w3.org/1999/xlink}href'
# Per-path mtime caches: key = absolute path str, value = (mtime, payload).
# Entry is evicted/replaced when the file's mtime changes, so stale data
@@ -136,6 +137,24 @@ def _cache_put(cache: dict, lock: threading.Lock, path: str, mtime: float, value
cache[path] = (mtime, value)
+def _normalize_preview_hrefs(root: ET.Element) -> None:
+ """Normalize legacy XLink references in the browser-only SVG copy.
+
+ ElementTree otherwise serializes an unregistered/legacy namespace with an
+ arbitrary prefix. The HTML SVG parser only gives special namespace handling
+ to ``xlink:href``; an arbitrary prefix can therefore render as an inert
+ attribute after ``innerHTML`` insertion. SVG 2 ``href`` works for both
+ images and local ``use`` references and avoids that parser boundary.
+ """
+ for elem in root.iter():
+ legacy_href = elem.get(_XLINK_HREF)
+ if legacy_href is None:
+ continue
+ if elem.get('href') is None:
+ elem.set('href', legacy_href)
+ elem.attrib.pop(_XLINK_HREF, None)
+
+
# Lock / liveness helpers are shared with confirm_ui via server_common.
@@ -648,6 +667,7 @@ def create_app(
if '}' in tag:
tag = tag.split('}', 1)[1]
id_to_tag[eid] = tag
+ _normalize_preview_hrefs(root)
content = ET.tostring(root, encoding='unicode', xml_declaration=False)
content, warnings = _inline_icons(content)
if not pending_edits:
diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.js
index 6327536e..6a6647a1 100644
--- a/skills/ppt-master/scripts/svg_editor/static/app.js
+++ b/skills/ppt-master/scripts/svg_editor/static/app.js
@@ -1730,10 +1730,10 @@
Array.from(el.attributes).forEach(function (attr) {
if (attr.name.indexOf("on") === 0) el.removeAttribute(attr.name);
// Strip dangerous URI protocols from href/xlink:href
- if ((attr.name === "href" || attr.name === "xlink:href") &&
+ if (attr.localName === "href" &&
(/^\s*javascript\s*:/i.test(attr.value) ||
/^\s*data\s*:/i.test(attr.value))) {
- el.removeAttribute(attr.name);
+ el.removeAttributeNode(attr);
}
});
});
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 48c08494..0ffa79aa 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -294,6 +294,47 @@ _SUPPORTED_FILTER_PRIMITIVES = frozenset({
'feFuncA',
})
_FILTER_EFFECT_PRIMITIVES = frozenset({'feDropShadow', 'feGaussianBlur'})
+_FILTER_PUBLIC_TARGETS = frozenset({'rect', 'circle', 'path', 'text'})
+_CLIP_SHAPE_TAGS = frozenset({'circle', 'ellipse', 'rect', 'path', 'polygon'})
+_DEFINITION_TAGS = frozenset({
+ 'clipPath',
+ 'filter',
+ 'linearGradient',
+ 'marker',
+ 'pattern',
+ 'radialGradient',
+})
+_ALPHA_PROPERTIES = (
+ 'opacity',
+ 'fill-opacity',
+ 'stroke-opacity',
+ 'stop-opacity',
+ 'flood-opacity',
+)
+_SUPPORTED_INLINE_STYLE_PROPERTIES = frozenset({
+ 'cx', 'cy', 'fill', 'fill-opacity', 'filter', 'flood-color',
+ 'flood-opacity', 'font-family', 'font-size', 'font-style', 'font-weight',
+ 'height', 'letter-spacing', 'opacity', 'r', 'rx', 'ry',
+ 'shape-rendering', 'stop-color', 'stop-opacity', 'stroke',
+ 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity',
+ 'stroke-width', 'text-anchor', 'text-decoration', 'vector-effect',
+ 'width', 'x', 'y',
+})
+_BAKE_REQUIRED_VISUAL_PROPERTIES = frozenset({
+ 'backdrop-filter',
+ 'isolation',
+ 'mix-blend-mode',
+})
+_NUMBER_TOKEN = r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?'
+_POINT_TOKEN = rf'{_NUMBER_TOKEN}(?:\s*,\s*|\s+){_NUMBER_TOKEN}'
+_MARKER_TRIANGLE_PATH_RE = re.compile(
+ rf'^\s*M\s*{_POINT_TOKEN}(?:\s*L\s*{_POINT_TOKEN}){{2}}\s*Z\s*$',
+ re.IGNORECASE,
+)
+_MARKER_DIAMOND_PATH_RE = re.compile(
+ rf'^\s*M\s*{_POINT_TOKEN}(?:\s*L\s*{_POINT_TOKEN}){{3}}\s*Z\s*$',
+ re.IGNORECASE,
+)
def _declared_pptx_structure_mode(project_path: Path) -> str | None:
@@ -663,6 +704,98 @@ def _local_name(elem: ET.Element) -> str:
return tag.rsplit('}', 1)[-1] if '}' in tag else tag
+def _direct_defs_index(
+ root: ET.Element,
+) -> tuple[Dict[str, ET.Element], set[str]]:
+ """Return direct ``<defs>`` children by id plus duplicate ids."""
+ definitions: Dict[str, ET.Element] = {}
+ duplicates: set[str] = set()
+ for defs_elem in root.iter():
+ if _local_name(defs_elem) != 'defs':
+ continue
+ for child in defs_elem:
+ definition_id = (child.get('id') or '').strip()
+ if not definition_id:
+ continue
+ if definition_id in definitions:
+ duplicates.add(definition_id)
+ definitions[definition_id] = child
+ return definitions, duplicates
+
+
+def _element_label(elem: ET.Element) -> str:
+ """Return a compact element label for validation messages."""
+ tag = _local_name(elem)
+ elem_id = (elem.get('id') or '').strip()
+ return f'<{tag} id="{elem_id}">' if elem_id else f'<{tag}>'
+
+
+def _finite_unit_interval(raw: str) -> float | None:
+ """Parse a finite unitless number in the closed interval ``0..1``."""
+ if re.fullmatch(_NUMBER_TOKEN, raw.strip()) is None:
+ return None
+ try:
+ value = float(raw)
+ except ValueError:
+ return None
+ if not math.isfinite(value) or not 0.0 <= value <= 1.0:
+ return None
+ return value
+
+
+def _normalized_gradient_value(raw: str) -> float | None:
+ """Parse a normalized gradient coordinate or percentage."""
+ value_text = raw.strip()
+ is_percent = value_text.endswith('%')
+ if is_percent:
+ value_text = value_text[:-1].strip()
+ if re.fullmatch(_NUMBER_TOKEN, value_text) is None:
+ return None
+ try:
+ value = float(value_text)
+ except ValueError:
+ return None
+ if not math.isfinite(value):
+ return None
+ value = value / 100.0 if is_percent else value
+ return value if 0.0 <= value <= 1.0 else None
+
+
+def _marker_polygon_vertex_count(raw: str) -> int | None:
+ """Return the number of finite polygon vertices, or ``None``."""
+ tokens = [token for token in re.split(r'[\s,]+', raw.strip()) if token]
+ if not tokens or len(tokens) % 2:
+ return None
+ try:
+ values = [float(token) for token in tokens]
+ except ValueError:
+ return None
+ if not all(math.isfinite(value) for value in values):
+ return None
+ return len(values) // 2
+
+
+def _effective_presentation_value(
+ elem: ET.Element,
+ name: str,
+ parent_by_id: Dict[int, ET.Element],
+) -> str | None:
+ """Resolve one inherited presentation property for validation."""
+ current: ET.Element | None = elem
+ while current is not None:
+ style_values = (
+ _parse_inline_style(current.get('style'))
+ if _parse_inline_style is not None else {}
+ )
+ if name in style_values:
+ return style_values[name]
+ direct = current.get(name)
+ if direct is not None:
+ return direct
+ current = parent_by_id.get(id(current))
+ return None
+
+
def _parse_viewbox_values(viewbox: str) -> Tuple[float, float, float, float] | None:
"""Parse a root viewBox into four numeric values."""
parts = re.split(r'[\s,]+', viewbox.strip())
@@ -862,10 +995,17 @@ class SVGQualityChecker:
# 2. Check forbidden elements
self._check_forbidden_elements(content, root, result)
- # 2b. Validate the supported shadow/glow filter interface.
+ # 2b. Validate the closed authoring-property surface and
+ # conditional definition interfaces before export.
+ self._check_authoring_property_contract(root, result)
+ self._check_definition_contract(root, result)
+ self._check_marker_contract(root, result)
+ self._check_clip_path_contract(root, result)
+
+ # 2c. Validate the supported shadow/glow filter interface.
self._check_filter_effects(root, result)
- # 2c. Reject gradient inheritance and transform semantics.
+ # 2d. Validate gradient definitions, stops, and coordinates.
self._check_gradient_interfaces(root, result)
# 3. Check font-size values
@@ -1019,28 +1159,8 @@ class SVGQualityChecker:
# Forbidden elements blocklist - PPT incompatible
# ============================================================
- # Clipping / masking
- # clipPath is allowed on <image> elements and on pptx_to_svg-generated
- # nested crop <svg data-pptx-crop="1"> wrappers. Both map back to
- # DrawingML picture geometry in the native converter.
- if 'clippath' in local_names:
- ids = {elem.get('id') for elem in elems if elem.get('id')}
- for elem in elems:
- clip_ref = elem.get('clip-path')
- if not clip_ref:
- continue
- tag = _local_name(elem).lower()
- is_crop_svg = tag == 'svg' and elem.get('data-pptx-crop') == '1'
- if tag != 'image' and not is_crop_svg:
- result['errors'].append(
- "clip-path is only allowed on <image> elements or "
- "pptx_to_svg crop wrappers — for shapes, draw the target "
- "shape directly instead of clipping")
- match = re.search(r'url\(#([^)]+)\)', clip_ref)
- if match and match.group(1) not in ids:
- result['errors'].append(
- f"clip-path references #{match.group(1)} but no matching "
- f"<clipPath id=\"{match.group(1)}\"> definition found")
+ # Clipping / masking. The closed image clip-path contract is validated
+ # separately by _check_clip_path_contract.
if 'mask' in local_names:
result['errors'].append("Detected forbidden <mask> element (PPT does not support SVG masks)")
@@ -1091,15 +1211,6 @@ class SVGQualityChecker:
else:
for error in _validate_local_use_references(root):
result['errors'].append(f"Invalid local <use> reference: {error}")
- # marker-start / marker-end are conditionally allowed (see shared-standards.md §1.1).
- # The converter maps qualifying <marker> defs to native DrawingML <a:headEnd>/<a:tailEnd>.
- # We only warn when a marker is used without an obvious <defs> definition in the same file.
- if re.search(r'\bmarker-(?:start|end)\s*=\s*["\']url\(#([^)]+)\)', content_lower):
- if 'marker' not in local_names:
- result['errors'].append(
- "Detected marker-start/marker-end referencing a marker id, "
- "but no <marker> element found in the file")
-
# Text / fonts
if 'textpath' in local_names:
result['errors'].append("Detected forbidden <textPath> element (path text is incompatible with PPT)")
@@ -1243,81 +1354,382 @@ class SVGQualityChecker:
f"{shown}{suffix}. Use a supported named color, rgb()/rgba(), "
"hsl()/hsla(), or #RGB/#RGBA/#RRGGBB/#RRGGBBAA."
)
- for elem in elems:
- tag = _local_name(elem).lower()
- if tag not in {'g', 'image'}:
+
+ def _check_authoring_property_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Validate inline CSS and alpha values against the authoring surface."""
+ issues: set[str] = set()
+ for elem in root.iter():
+ label = _element_label(elem)
+ style_declarations: list[tuple[str, str]] = []
+ for fragment in (elem.get('style') or '').split(';'):
+ fragment = fragment.strip()
+ if not fragment:
+ continue
+ if ':' not in fragment:
+ issues.add(
+ f"{label} has malformed inline style declaration {fragment!r}"
+ )
+ continue
+ name, value = fragment.split(':', 1)
+ name = name.strip().lower()
+ value = value.strip()
+ if not name or not value:
+ issues.add(
+ f"{label} has malformed inline style declaration {fragment!r}"
+ )
+ continue
+ style_declarations.append((name, value))
+ if name in _BAKE_REQUIRED_VISUAL_PROPERTIES:
+ issues.add(
+ f"{label} uses Bake-required visual property {name!r}; "
+ "bake the effect or rebuild it with supported geometry"
+ )
+ elif name not in _SUPPORTED_INLINE_STYLE_PROPERTIES:
+ issues.add(
+ f"{label} uses unsupported inline style property {name!r}; "
+ "native PPTX export would ignore it"
+ )
+ if '!important' in value.lower():
+ issues.add(
+ f"{label} inline style property {name!r} cannot use !important"
+ )
+
+ for attr_name in elem.attrib:
+ local_attr = attr_name.rsplit('}', 1)[-1]
+ if local_attr in _BAKE_REQUIRED_VISUAL_PROPERTIES:
+ issues.add(
+ f"{label} uses Bake-required visual attribute {local_attr!r}; "
+ "bake the effect or rebuild it with supported geometry"
+ )
+
+ for name in _ALPHA_PROPERTIES:
+ direct_value = elem.get(name)
+ if direct_value is not None and _finite_unit_interval(direct_value) is None:
+ issues.add(
+ f"{label} {name} must be a finite unitless number from "
+ f"0 to 1; got {direct_value!r}"
+ )
+ for style_name, style_value in style_declarations:
+ if style_name == name and _finite_unit_interval(style_value) is None:
+ issues.add(
+ f"{label} style {name} must be a finite unitless number "
+ f"from 0 to 1; got {style_value!r}"
+ )
+
+ if _local_name(elem).lower() != 'g':
continue
- raw_opacity = elem.get('opacity')
+ style_opacity = next((
+ value for name, value in reversed(style_declarations)
+ if name == 'opacity'
+ ), None)
+ raw_opacity = style_opacity if style_opacity is not None else elem.get('opacity')
if raw_opacity is None:
- style_match = re.search(
- r'(?:^|;)\s*opacity\s*:\s*([^;]+)',
- elem.get('style', ''),
- flags=re.IGNORECASE,
+ continue
+ opacity = _finite_unit_interval(raw_opacity)
+ if opacity is not None and opacity < 1.0:
+ issues.add(
+ f"{label} uses <g opacity={raw_opacity!r}>; generated SVG "
+ "must put alpha on individual descendants because native "
+ "PPTX export cannot preserve isolated group compositing"
)
- raw_opacity = style_match.group(1).strip() if style_match else None
- if raw_opacity is None:
+
+ result['errors'].extend(sorted(issues))
+
+ def _check_definition_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Require conditional definitions to be direct, uniquely identified defs."""
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ definitions, duplicate_definition_ids = _direct_defs_index(root)
+ issues = {
+ f'Duplicate direct <defs> id {definition_id!r} makes local references ambiguous'
+ for definition_id in duplicate_definition_ids
+ }
+ all_id_counts = Counter(
+ elem.get('id')
+ for elem in root.iter()
+ if (elem.get('id') or '').strip()
+ )
+ for definition_id in definitions:
+ if all_id_counts[definition_id] > 1:
+ issues.add(
+ f'Definition id {definition_id!r} is duplicated in the SVG; '
+ 'local references require one unique target'
+ )
+
+ for elem in root.iter():
+ tag = _local_name(elem)
+ if tag not in _DEFINITION_TAGS:
continue
- try:
- opacity = float(raw_opacity)
- except ValueError:
- opacity = -1.0
- if not 0.0 <= opacity <= 1.0:
- result['errors'].append(
- f"<{tag} opacity> must be a numeric value from 0 to 1, got {raw_opacity!r}"
+ label = _element_label(elem)
+ parent = parent_by_id.get(id(elem))
+ if parent is None or _local_name(parent) != 'defs':
+ issues.add(
+ f"{label} must be a direct child of <defs>"
)
- if tag == 'g' and opacity < 1.0 and any(
- descendant.tag.rsplit('}', 1)[-1] != 'metadata'
- and descendant.get('data-pptx-native')
- for descendant in elem.iter()
- ):
- result['warnings'].append(
- "<g opacity> around data-pptx-native content uses the SVG "
- "fallback; --native-objects export rejects that combination"
+ if not (elem.get('id') or '').strip():
+ issues.add(f"{label} requires a non-empty unique id")
+
+ result['errors'].extend(sorted(issues))
+
+ def _check_marker_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Validate marker references against the native line-end contract."""
+ definitions, _duplicates = _direct_defs_index(root)
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ issues: set[str] = set()
+ checked_markers: set[str] = set()
+
+ for elem in root.iter():
+ for attr in ('marker-start', 'marker-end'):
+ raw_ref = elem.get(attr)
+ if raw_ref is None or raw_ref.strip().lower() == 'none':
+ continue
+ label = _element_label(elem)
+ tag = _local_name(elem).lower()
+ if tag not in {'line', 'path'}:
+ issues.add(
+ f"{label} {attr} is allowed only on <line> or <path>"
+ )
+ match = re.fullmatch(r'url\(#([^)]+)\)', raw_ref.strip())
+ if match is None:
+ issues.add(
+ f"{label} {attr} must be an exact local url(#id) reference; "
+ f"got {raw_ref!r}"
+ )
+ continue
+ marker_id = match.group(1)
+ marker = definitions.get(marker_id)
+ if marker is None or _local_name(marker) != 'marker':
+ issues.add(
+ f"{label} {attr}=url(#{marker_id}) has no matching direct "
+ f"<defs><marker id=\"{marker_id}\"> definition"
+ )
+ continue
+
+ visual_children = [
+ child for child in list(marker)
+ if _local_name(child) not in _NON_VISUAL_SVG_TAGS
+ ]
+ shape = visual_children[0] if len(visual_children) == 1 else None
+ if marker_id not in checked_markers:
+ checked_markers.add(marker_id)
+ marker_label = f'<marker id="{marker_id}">'
+ if marker.get('orient') != 'auto':
+ issues.add(f'{marker_label} requires orient="auto"')
+ marker_units = marker.get('markerUnits', 'strokeWidth')
+ if marker_units not in {'strokeWidth', 'userSpaceOnUse'}:
+ issues.add(
+ f"{marker_label} has unsupported markerUnits={marker_units!r}"
+ )
+ for size_attr in ('markerWidth', 'markerHeight'):
+ raw_size = marker.get(size_attr)
+ if raw_size is None:
+ continue
+ try:
+ size = float(raw_size)
+ except ValueError:
+ size = math.nan
+ if not math.isfinite(size) or size <= 0:
+ issues.add(
+ f"{marker_label} {size_attr} must be a positive "
+ f"finite number; got {raw_size!r}"
+ )
+ if shape is None:
+ issues.add(
+ f"{marker_label} must contain exactly one direct "
+ "triangle/diamond path or polygon, circle, or ellipse"
+ )
+ else:
+ shape_tag = _local_name(shape).lower()
+ if shape.get('transform'):
+ issues.add(
+ f"{marker_label} child <{shape_tag}> cannot use transform"
+ )
+ if shape_tag == 'path':
+ path_data = shape.get('d', '')
+ if not (
+ _MARKER_TRIANGLE_PATH_RE.fullmatch(path_data)
+ or _MARKER_DIAMOND_PATH_RE.fullmatch(path_data)
+ ):
+ issues.add(
+ f"{marker_label} path must be a closed 3- or "
+ "4-vertex path with one explicit M/L command "
+ "per vertex"
+ )
+ elif shape_tag == 'polygon':
+ vertex_count = _marker_polygon_vertex_count(
+ shape.get('points', '')
+ )
+ if vertex_count not in {3, 4}:
+ issues.add(
+ f"{marker_label} polygon must contain exactly "
+ "3 or 4 finite vertices"
+ )
+ elif shape_tag not in {'circle', 'ellipse'}:
+ issues.add(
+ f"{marker_label} child <{shape_tag}> has no native "
+ "line-end mapping"
+ )
+
+ if shape is None or _parse_export_color is None:
+ continue
+ stroke_value = _effective_presentation_value(
+ elem, 'stroke', parent_by_id,
+ )
+ marker_fill = _effective_presentation_value(
+ shape, 'fill', parent_by_id,
+ ) or '#000000'
+ stroke_color, _stroke_alpha = _parse_export_color(stroke_value or '')
+ fill_color, _fill_alpha = _parse_export_color(marker_fill)
+ if stroke_color is None or fill_color is None:
+ issues.add(
+ f"{label} {attr} marker fill and line stroke must both be "
+ "supported solid colors"
+ )
+ elif stroke_color != fill_color:
+ issues.add(
+ f"{label} {attr}=url(#{marker_id}) marker fill "
+ f"{marker_fill!r} does not match effective line stroke "
+ f"{stroke_value!r}"
+ )
+
+ result['errors'].extend(sorted(issues))
+
+ def _check_clip_path_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Validate image clip paths against the native picture geometry mapping."""
+ definitions, _duplicates = _direct_defs_index(root)
+ issues: set[str] = set()
+ checked_clips: set[str] = set()
+ for elem in root.iter():
+ raw_ref = elem.get('clip-path')
+ if raw_ref is None or raw_ref.strip().lower() == 'none':
+ continue
+ label = _element_label(elem)
+ tag = _local_name(elem).lower()
+ is_imported_crop = tag == 'svg' and elem.get('data-pptx-crop') == '1'
+ if tag != 'image' and not is_imported_crop:
+ issues.add(
+ f"{label} clip-path is allowed only on <image> or an imported "
+ "data-pptx-crop=\"1\" wrapper"
+ )
+ match = re.fullmatch(r'url\(#([^)]+)\)', raw_ref.strip())
+ if match is None:
+ issues.add(
+ f"{label} clip-path must be an exact local url(#id) "
+ f"reference; got {raw_ref!r}"
+ )
+ continue
+ clip_id = match.group(1)
+ clip = definitions.get(clip_id)
+ if clip is None or _local_name(clip) != 'clipPath':
+ issues.add(
+ f"{label} clip-path=url(#{clip_id}) has no matching direct "
+ f"<defs><clipPath id=\"{clip_id}\"> definition"
+ )
+ continue
+ if clip_id in checked_clips:
+ continue
+ checked_clips.add(clip_id)
+ clip_label = f'<clipPath id="{clip_id}">'
+ clip_units = clip.get('clipPathUnits', 'userSpaceOnUse')
+ if clip_units not in {'userSpaceOnUse', 'objectBoundingBox'}:
+ issues.add(
+ f"{clip_label} has unsupported clipPathUnits={clip_units!r}"
+ )
+ if clip.get('transform'):
+ issues.add(f"{clip_label} cannot use transform")
+ visual_children = [
+ child for child in list(clip)
+ if _local_name(child) not in _NON_VISUAL_SVG_TAGS
+ ]
+ if len(visual_children) != 1:
+ issues.add(
+ f"{clip_label} must contain exactly one direct supported shape"
+ )
+ continue
+ shape = visual_children[0]
+ shape_tag = _local_name(shape).lower()
+ if shape_tag not in _CLIP_SHAPE_TAGS:
+ issues.add(
+ f"{clip_label} child <{shape_tag}> is unsupported; use "
+ "circle, ellipse, rect, path, or polygon"
+ )
+ if shape.get('transform'):
+ issues.add(
+ f"{clip_label} child <{shape_tag}> cannot use transform"
)
+ result['errors'].extend(sorted(issues))
+
def _check_filter_effects(self, root: ET.Element, result: Dict) -> None:
"""Validate filters against the native shadow/glow approximation."""
elems = list(root.iter())
- direct_filters = []
- filters_by_id = {}
- for defs_elem in elems:
- if _local_name(defs_elem) != 'defs':
- continue
- for child in defs_elem:
- if _local_name(child) != 'filter':
- continue
- direct_filters.append(child)
- filter_id = child.get('id')
- if filter_id:
- filters_by_id[filter_id] = child
+ definitions, _duplicates = _direct_defs_index(root)
+ direct_filters = [
+ elem for elem in definitions.values()
+ if _local_name(elem) == 'filter'
+ ]
+ filters_by_id = {
+ filter_id: elem
+ for filter_id, elem in definitions.items()
+ if _local_name(elem) == 'filter'
+ }
issues = set()
for elem in elems:
- tag = _local_name(elem)
+ tag = _local_name(elem).lower()
+ label = _element_label(elem)
style_values = (
_parse_inline_style(elem.get('style'))
if _parse_inline_style is not None else {}
)
if style_values.get('filter'):
issues.add(
- f"<{tag}> filter must use a direct filter=\"url(#id)\" "
+ f"{label} filter must use a direct filter=\"url(#id)\" "
"attribute; inline style filters are not supported"
)
raw_filter = elem.get('filter')
if raw_filter is None:
continue
+ if tag not in _FILTER_PUBLIC_TARGETS:
+ issues.add(
+ f"{label} cannot use filter; supported native targets are "
+ "rect, circle, path, and text"
+ )
match = re.fullmatch(r'url\(#([^)]+)\)', raw_filter.strip())
if match is None:
issues.add(
- f"<{tag}> filter must be an exact local url(#id) reference; "
+ f"{label} filter must be an exact local url(#id) reference; "
f"got {raw_filter!r}"
)
continue
filter_id = match.group(1)
if filter_id not in filters_by_id:
issues.add(
- f"<{tag}> filter=url(#{filter_id}) has no matching direct "
+ f"{label} filter=url(#{filter_id}) has no matching direct "
f"<defs><filter id=\"{filter_id}\"> definition"
)
@@ -1337,10 +1749,19 @@ class SVGQualityChecker:
f"{label} uses unsupported filter primitive(s): "
f"{', '.join(unsupported)}"
)
- if not _FILTER_EFFECT_PRIMITIVES.intersection(primitives):
+ effect_primitives = [
+ primitive for primitive in primitives
+ if primitive in _FILTER_EFFECT_PRIMITIVES
+ ]
+ if not effect_primitives:
issues.add(
f"{label} must contain feDropShadow or feGaussianBlur"
)
+ elif len(effect_primitives) > 1:
+ issues.add(
+ f"{label} contains multiple shadow/glow primitives; one "
+ "filter must map to exactly one native effect"
+ )
if any(
_local_name(descendant) == 'feFuncA'
and descendant.get('type') != 'linear'
@@ -1348,10 +1769,44 @@ class SVGQualityChecker:
):
issues.add(f"{label} requires feFuncA type=\"linear\"")
+ for primitive in filter_elem.iter():
+ primitive_tag = _local_name(primitive)
+ numeric_attrs: tuple[tuple[str, bool], ...] = ()
+ if primitive_tag in {'feDropShadow', 'feGaussianBlur'}:
+ numeric_attrs = (('stdDeviation', True),)
+ elif primitive_tag == 'feOffset':
+ numeric_attrs = (('dx', False), ('dy', False))
+ elif primitive_tag == 'feFuncA':
+ numeric_attrs = (('slope', True),)
+ if primitive_tag == 'feDropShadow':
+ numeric_attrs += (('dx', False), ('dy', False))
+ for attr_name, non_negative in numeric_attrs:
+ raw_value = primitive.get(attr_name)
+ if raw_value is None:
+ continue
+ try:
+ value = float(raw_value)
+ except ValueError:
+ value = math.nan
+ if (
+ not math.isfinite(value)
+ or (non_negative and value < 0)
+ or (
+ primitive_tag == 'feFuncA'
+ and attr_name == 'slope'
+ and value > 1
+ )
+ ):
+ qualifier = ' from 0 to 1' if primitive_tag == 'feFuncA' else ''
+ issues.add(
+ f"{label} <{primitive_tag}> {attr_name} must be a "
+ f"finite number{qualifier}; got {raw_value!r}"
+ )
+
result['errors'].extend(sorted(issues))
def _check_gradient_interfaces(self, root: ET.Element, result: Dict) -> None:
- """Reject gradient inheritance, transforms, and spread modes."""
+ """Validate the normalized native gradient authoring interface."""
issues = set()
for gradient in root.iter():
tag = _local_name(gradient)
@@ -1372,6 +1827,59 @@ class SVGQualityChecker:
issues.add(f"{label} cannot use gradientTransform")
if 'spreadMethod' in attribute_names:
issues.add(f"{label} cannot use spreadMethod")
+ gradient_units = gradient.get('gradientUnits')
+ if gradient_units not in {None, 'objectBoundingBox'}:
+ issues.add(
+ f"{label} cannot use gradientUnits={gradient_units!r}; "
+ "use normalized objectBoundingBox coordinates"
+ )
+
+ coordinate_names = (
+ ('x1', 'y1', 'x2', 'y2')
+ if tag == 'linearGradient'
+ else ('cx', 'cy', 'r', 'fx', 'fy')
+ )
+ for coordinate_name in coordinate_names:
+ raw_coordinate = gradient.get(coordinate_name)
+ if raw_coordinate is None:
+ continue
+ coordinate = _normalized_gradient_value(raw_coordinate)
+ if coordinate is None:
+ issues.add(
+ f"{label} {coordinate_name} must be a normalized finite "
+ f"value from 0 to 1 or 0% to 100%; got {raw_coordinate!r}"
+ )
+ elif coordinate_name == 'r' and coordinate <= 0:
+ issues.add(f"{label} r must be greater than 0")
+
+ stops = []
+ for child in list(gradient):
+ child_tag = _local_name(child)
+ if child_tag in _NON_VISUAL_SVG_TAGS:
+ continue
+ if child_tag != 'stop':
+ issues.add(
+ f"{label} has unsupported direct child <{child_tag}>; "
+ "gradient definitions may contain only direct <stop> children"
+ )
+ continue
+ stops.append(child)
+ if not stops:
+ issues.add(f"{label} requires at least one direct <stop> child")
+ for index, stop in enumerate(stops, start=1):
+ stop_label = f"{label} stop #{index}"
+ raw_offset = stop.get('offset')
+ if raw_offset is None or _normalized_gradient_value(raw_offset) is None:
+ issues.add(
+ f"{stop_label} offset must be explicit and within 0..1 "
+ f"or 0%..100%; got {raw_offset!r}"
+ )
+ style_values = (
+ _parse_inline_style(stop.get('style'))
+ if _parse_inline_style is not None else {}
+ )
+ if not (style_values.get('stop-color') or stop.get('stop-color')):
+ issues.add(f"{stop_label} requires an explicit stop-color")
result['errors'].extend(sorted(issues))
@@ -1876,9 +2384,8 @@ class SVGQualityChecker:
preset name comes from `data-pptx-pattern` (e.g. `lgGrid` / `smGrid` /
`dkUpDiag`). Two failure modes worth catching pre-export:
- 1. Missing annotation → converter silently falls back to `ltUpDiag`
- (diagonal stripes). Color metadata or child paints still resolve,
- with white as the final background fallback.
+ 1. Missing annotation → the converter compatibility fallback chooses
+ `ltUpDiag` (diagonal stripes), which is not an authoring contract.
2. Invalid preset name → PPTX schema rejects the file; PowerPoint
opens it with "needs to be repaired". OOXML
`ST_PresetPatternVal` is a closed enum — only the names in
@@ -1886,19 +2393,44 @@ class SVGQualityChecker:
value) is the canonical mistake; the only grids are `smGrid` /
`lgGrid` / `dotGrid`.
"""
- for pattern in root.iter(f'{{{SVG_NS}}}pattern'):
+ definitions, _duplicates = _direct_defs_index(root)
+ referenced_patterns: set[str] = set()
+ for elem in root.iter():
+ style_values = (
+ _parse_inline_style(elem.get('style'))
+ if _parse_inline_style is not None else {}
+ )
+ fill = style_values.get('fill') or elem.get('fill')
+ match = re.fullmatch(r'url\(#([^)]+)\)', (fill or '').strip())
+ if match is None:
+ continue
+ definition = definitions.get(match.group(1))
+ if definition is not None and _local_name(definition) == 'pattern':
+ referenced_patterns.add(match.group(1))
+
+ for pattern in (
+ elem for elem in root.iter()
+ if _local_name(elem) == 'pattern'
+ ):
pat_id = pattern.get('id', '<unnamed>')
prst = pattern.get('data-pptx-pattern')
- if not prst:
- result['warnings'].append(
+ if pat_id in referenced_patterns and not prst:
+ result['errors'].append(
f"<pattern id=\"{pat_id}\"> has no data-pptx-pattern attribute — "
- "PPTX export will fall back to `ltUpDiag` (diagonal stripes), "
- "not your custom geometry. Add a valid data-pptx-pattern; "
+ "generated SVG cannot rely on the converter's `ltUpDiag` "
+ "compatibility fallback. Add a valid data-pptx-pattern; "
"set data-pptx-fg/data-pptx-bg or matching child paints "
"when explicit pattern colors are required."
)
continue
+ if pat_id in referenced_patterns and pattern.get('patternTransform'):
+ result['errors'].append(
+ f"<pattern id=\"{pat_id}\"> cannot use patternTransform; "
+ "the native preset mapping does not preserve custom tile transforms"
+ )
if prst not in self._OOXML_PATTERN_PRESETS:
+ if not prst:
+ continue
result['errors'].append(
f"<pattern id=\"{pat_id}\"> uses data-pptx-pattern=\"{prst}\" "
"which is not in OOXML ST_PresetPatternVal — exported PPTX "