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

feat(shape-boolean): add editable merge-shapes materialization

hugohe37f1dbd5b194f
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index 1cbaf024..cc3244a5 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -95,6 +95,7 @@ Internal identifiers and PowerPoint display names are separate concerns: Master
| Arrowhead line | `<line>` or supported path with registered triangle, stealth, arrow, diamond, or oval start/end markers | Native DrawingML line head/tail ends | `Native-normalized`; marker size is approximate | Marker definitions must follow the conditional marker contract |
| Native connector | Compact project-authored preset group with connector metadata and direct visible paths | `p:cxnSp` | Imported connectors retain the expanded round-trip evidence needed for source topology | `Native-stable` for the registered preset/connector schema |
| Freeform shape | `<path>` | `p:sp` with `a:custGeom` | Imported custom geometry reconstructs as a path | `Native-normalized`; SVG arcs are converted to cubic segments |
+| Materialized Merge Shapes result | Ordinary `<path>` output from `shape_boolean_svg.py`; Fragment returns sibling paths | One `p:sp` with `a:custGeom` per returned path | `Native-normalized`; imports as final freeform geometry, not replayable operation history | Closed supported operands only; the first source owns style/order, and no clip, mask, or explicit fill rule is emitted |
| Polygon | `<polygon>` | Closed custom geometry | `Native-normalized` | Points must be finite and valid |
| Polyline | `<polyline>` | Open custom geometry | `Native-normalized` | Points use the same finite, registered grammar as other generated geometry |
| PowerPoint preset shape | Registry-generated compact `<g>` with preset intent/base paint and direct visible `<path>` children | One editable preset `p:sp` | Preset identity and adjustments can survive import/export | Quality check and export rerender the registry dynamically; canonical authoring has no hidden carrier, preview wrapper, or stored preview hash |
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index eb2ccc18..4c9dfb20 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -95,6 +95,7 @@ PowerPoint 意图
| 带箭头的线 | 带已登记 triangle、stealth、arrow、diamond 或 oval 起点/终点 marker 的 `<line>` 或受支持 path | 原生 DrawingML 线首/线尾 | `Native-normalized`;marker 大小为近似 | marker 定义必须遵循条件 marker 合同 |
| 原生连接符 | 带 connector metadata 和直接可见 path 的项目创作 compact preset 组 | `p:cxnSp` | 导入 connector 保留源拓扑往返所需的 expanded 证据 | 已登记 preset/connector schema 内为 `Native-stable` |
| 任意多边形 | `<path>` | 带 `a:custGeom` 的 `p:sp` | 导入自定义几何重建为 path | `Native-normalized`;SVG arc 转为三次曲线段 |
+| 已物化的合并形状结果 | `shape_boolean_svg.py` 输出的普通 `<path>`;“拆分”返回多个同级 path | 每个返回 path 对应一个带 `a:custGeom` 的 `p:sp` | `Native-normalized`;回导为最终自由形状几何,不保留可重放的操作历史 | 仅接受受支持的闭合 operands;第一个 source 决定样式与顺序,且不输出 clip、mask 或显式 fill rule |
| 多边形 | `<polygon>` | 闭合自定义几何 | `Native-normalized` | points 必须有限且合法 |
| 折线 | `<polyline>` | 开放自定义几何 | `Native-normalized` | points 使用与其他生成几何相同的有限、已登记语法 |
| PowerPoint 预设形状 | 由 registry 生成的 compact `<g>`,由该组承载 preset 意图与基础 paint,并直接包含可见 `<path>` 子元素 | 一个可编辑 preset `p:sp` | preset 身份与 adjustment 可以经导入/导出保留 | 质检与导出动态重渲染 registry;规范创作表达不含隐藏 carrier、preview wrapper 或已存储 preview hash |
diff --git a/skills/ppt-master/references/native-shape-authoring.md b/skills/ppt-master/references/native-shape-authoring.md
index 62670f13..73f66db6 100644
--- a/skills/ppt-master/references/native-shape-authoring.md
+++ b/skills/ppt-master/references/native-shape-authoring.md
@@ -1,11 +1,12 @@
> See [`shared-standards-core.md`](./shared-standards-core.md) §§1.4–1.5 for the native-shape metadata and validation contracts.
-# Native Preset Shape Authoring Reference
+# Native Shape Authoring Reference
Use this reference during Executor SVG construction or project-owned canonical
template maintenance when one standard PowerPoint shape can express one
-complete geometric object. The helper does not create the preset shape's own
-`p:txBody`; keep visible text outside the atomic fragment.
+complete object or multiple closed shapes require a PowerPoint-style Boolean
+result. Neither helper writes a page. The preset helper does not create the
+shape's own `p:txBody`; keep visible text outside the atomic fragment.
## 1. Selection Gate
@@ -20,6 +21,7 @@ Apply this decision order before drawing a stock geometric object.
|---|---|
| Plain rectangle, symmetric rounded rectangle, circle, or ellipse | Write the ordinary SVG primitive; the exporter already emits an editable native shape. |
| One DrawingML preset exactly expresses the intended object | Run `preset_shape_svg.py render`, then insert its complete stdout fragment into the hand-authored page or canonical template. |
+| Two or more closed authored shapes require Union, Combine, Fragment, Intersect, or Subtract | Run `shape_boolean_svg.py render`, then replace the operands with every stdout path; the result remains ordinary editable custom geometry. |
| The visual meaning or contour exceeds one stock shape | Write ordinary `<path>` / `<polygon>` geometry; export keeps it as editable custom geometry. |
| The shape only resembles a preset | Keep ordinary SVG; never infer a preset from contour similarity. |
| Mirror/preserve input already owns native-shape metadata | Keep the existing object and metadata; never reselect its preset. |
@@ -190,3 +192,39 @@ and paint. The exporter performs the same validation, then expands the compact
group only in memory to reuse the lossless native-shape conversion path.
Compatible expanded authored input remains under its separate carrier/preview
freshness contract.
+
+---
+
+## 6. Shape Boolean Materialization
+
+**Trigger**: The authored design explicitly requires a PowerPoint-style Union,
+Combine, Fragment, Intersect, or Subtract operation over two or more closed
+vector shapes.
+
+```bash
+python3 ${SKILL_DIR}/scripts/shape_boolean_svg.py render <svg-file> \
+ --operation subtract \
+ --source body \
+ --source cutout \
+ --id result
+```
+
+| Concern | Contract |
+|---|---|
+| Sources | Closed `path`, `polygon`, `rect`, `circle`, `ellipse`, or one validated compact authored shape preset. Open ordinary geometry, connectors, ordinary groups, text, images, definitions, and nested SVG viewports fail closed. |
+| Primary shape | The first `--source` supplies result paint. For `subtract`, all later operands are removed from that primary geometry. Explicit paint flags override only their named channels. |
+| Coordinates | Ancestor and local transforms are baked into SVG-root coordinates. Insert stdout at the root in the primary operand's z-order; never reinsert it under an original transformed ancestor. |
+| Result | `union`, `combine`, `intersect`, and `subtract` emit one ordinary `<path>`. `fragment` emits stable sibling paths named `<id>-1`, `<id>-2`, ... in top/left/bottom/right/area order. |
+| Winding | Results use explicit nonzero contour direction and never emit `fill-rule`, `clip-rule`, `clip-path`, `mask`, or Merge Shapes metadata. Operands that depend on even-odd fill, clipping, or masking fail closed. |
+| Preservation | This helper authors new geometry only. Never use it to merge or split mirror/preserve source structure. |
+
+Operation semantics match PowerPoint's visible Merge Shapes result: `union`
+keeps every covered region, `combine` keeps the symmetric difference,
+`intersect` keeps only common coverage, `subtract` removes every later source
+from the primary, and `fragment` returns each atomic filled region. The PPTX
+stores the materialized freeform geometry, not replayable operation history.
+
+**Hard rule — stdout-only replacement**: The helper never writes the source
+page. In one normal `apply_patch` edit, remove every selected operand and insert
+every returned path at the SVG root in the primary operand's z-order. Fragment
+paths remain separate shapes; do not wrap them to claim one structural atom.
diff --git a/skills/ppt-master/requirements.txt b/skills/ppt-master/requirements.txt
index 273f5123..3f46a2a6 100644
--- a/skills/ppt-master/requirements.txt
+++ b/skills/ppt-master/requirements.txt
@@ -16,6 +16,8 @@
# 将受支持的 SVG 元素转换为可编辑的原生 DrawingML 形状
python-pptx>=0.6.21
XlsxWriter>=3.0.0
+# PowerPoint-style Merge Shapes materialization / PowerPoint 风格合并形状物化
+skia-pathops>=0.9.2
# Recorded narration / 录制计时和旁白
# notes_to_audio.py generates per-slide narration audio on macOS/Linux/Windows.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 5e2e7046..45dea1b4 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -46,7 +46,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `page_context.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
+| SVG pipeline | `preset_shape_svg.py`, `shape_boolean_svg.py`, `svg_authoring_view.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native shape authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Spec maintenance | `update_spec.py`, `chart_recall.py` | [docs/update_spec.md](./docs/update_spec.md); [docs/chart-recall.md](./docs/chart-recall.md) |
@@ -207,6 +207,24 @@ the normative contract and
[`references/native-shape-authoring.md`](../references/native-shape-authoring.md)
for selection and authoring guidance.
+PowerPoint-style Merge Shapes materialization (source read-only; result paths
+on stdout):
+
+```bash
+python3 scripts/shape_boolean_svg.py render slide.svg \
+ --operation intersect \
+ --source circle \
+ --source card \
+ --id overlap
+```
+
+The first source owns result paint and is the primary geometry for `subtract`.
+Local and ancestor transforms are baked into SVG-root coordinates. Replace the
+operands with every returned path at the root in the primary operand's z-order;
+`fragment` returns multiple stable sibling paths. See
+[`references/native-shape-authoring.md`](../references/native-shape-authoring.md)
+§6 for the closed operand and failure contract.
+
Create-template/source normalization (optional; never part of automatic export):
```bash
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index fa367942..bba32afd 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -12,7 +12,7 @@
"skills/ppt-master/templates/schemas/*.json"
],
"exclude": [],
- "max_tokens": 365000
+ "max_tokens": 365400
},
"file_budgets": {
"AGENTS.md": 2350,
@@ -670,12 +670,12 @@
"max_tokens": 800
},
"stage.create-template.authored-preset": {
- "description": "Conditional native-preset authoring reference for Create Layout/Create Deck.",
+ "description": "Conditional native preset and Boolean shape authoring reference for Create Layout/Create Deck.",
"scope": "incremental",
"files": [
"skills/ppt-master/references/native-shape-authoring.md"
],
- "max_tokens": 2600
+ "max_tokens": 3100
},
"route.generate.planning-template": {
"description": "Generate-PPTX planning context after an explicit template workspace is installed.",
@@ -771,12 +771,12 @@
"max_tokens": 900
},
"stage.generate.executor.native-shape": {
- "description": "Conditional stock PowerPoint shape selection and fragment contract.",
+ "description": "Conditional stock PowerPoint shape selection and Boolean materialization contract.",
"scope": "incremental",
"files": [
"skills/ppt-master/references/native-shape-authoring.md"
],
- "max_tokens": 2600
+ "max_tokens": 3100
},
"stage.shared.svg-effects": {
"description": "Conditional advanced SVG paint, effects, transforms, and geometry for Generate Executor or Create Template.",
diff --git a/skills/ppt-master/scripts/shape_boolean_svg.py b/skills/ppt-master/scripts/shape_boolean_svg.py
new file mode 100644
index 00000000..94e43664
--- /dev/null
+++ b/skills/ppt-master/scripts/shape_boolean_svg.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Shape Boolean SVG Fragment Tool
+
+Combine closed SVG shapes and print the resulting canonical SVG path fragment
+to stdout. Result geometry is baked into SVG root coordinates: replace the
+operands at the SVG root while preserving the primary operand's z-order, and
+never reinsert the result into an original transformed ancestor. The source
+SVG is read-only; this tool never rewrites the page.
+
+Usage:
+ python3 scripts/shape_boolean_svg.py render SVG_FILE \
+ --operation OPERATION --source ID --source ID --id OUTPUT_ID
+
+Examples:
+ python3 scripts/shape_boolean_svg.py render slide.svg \
+ --operation intersect --source circle --source card --id overlap
+ python3 scripts/shape_boolean_svg.py render slide.svg \
+ --operation subtract --source body --source cutout --id result \
+ --fill "#2563EB" --stroke none
+
+Dependencies:
+ skia-pathops and local PPT Master modules
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+import sys
+from pathlib import Path
+from typing import Sequence
+
+from console_encoding import configure_utf8_stdio
+
+
+configure_utf8_stdio()
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Print the Boolean result of closed SVG shapes as canonical SVG "
+ "path fragments in SVG root coordinates. Insert the result at the "
+ "SVG root in the primary operand's z-order, not under an original "
+ "transformed ancestor. The source file is never modified."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ render_parser = subparsers.add_parser(
+ "render",
+ help="Print root-coordinate Boolean-result SVG paths to stdout.",
+ )
+ render_parser.add_argument(
+ "svg_file",
+ type=Path,
+ help="Source SVG containing the operand elements.",
+ )
+ render_parser.add_argument(
+ "--operation",
+ required=True,
+ choices=("union", "combine", "fragment", "intersect", "subtract"),
+ help="PowerPoint-compatible merge-shapes operation.",
+ )
+ render_parser.add_argument(
+ "--source",
+ action="append",
+ required=True,
+ dest="source_ids",
+ metavar="ID",
+ help=(
+ "Operand element id in merge order; repeat at least twice. "
+ "The first operand is primary for subtract and style inheritance."
+ ),
+ )
+ render_parser.add_argument(
+ "--id",
+ required=True,
+ dest="output_id",
+ help="Stable id for the result, or the base id for fragment results.",
+ )
+ render_parser.add_argument(
+ "--fill",
+ help="Override the primary shape's solid SVG fill, or use none.",
+ )
+ render_parser.add_argument(
+ "--fill-opacity",
+ type=float,
+ help="Override fill opacity from 0 to 1.",
+ )
+ render_parser.add_argument(
+ "--stroke",
+ help="Override the primary shape's solid SVG stroke, or use none.",
+ )
+ render_parser.add_argument(
+ "--stroke-width",
+ type=float,
+ help="Override stroke width in SVG page units.",
+ )
+ render_parser.add_argument(
+ "--stroke-opacity",
+ type=float,
+ help="Override stroke opacity from 0 to 1.",
+ )
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+
+ try:
+ style = _style_from_args(args)
+ _validate_render_args(args)
+ from svg_to_pptx.shape_boolean import (
+ render_boolean_svg_fragments,
+ )
+
+ fragment = render_boolean_svg_fragments(
+ args.svg_file,
+ operation=args.operation,
+ source_ids=args.source_ids,
+ output_id=args.output_id,
+ style=style or None,
+ )
+ except (OSError, RuntimeError, ValueError) as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+ print(fragment)
+ return 0
+
+
+def _validate_render_args(args: argparse.Namespace) -> None:
+ if len(args.source_ids) < 2:
+ raise ValueError("--source must be repeated at least twice")
+ if len(set(args.source_ids)) != len(args.source_ids):
+ raise ValueError("--source ids must be unique")
+ if not args.output_id.strip():
+ raise ValueError("--id must not be empty")
+
+
+def _style_from_args(args: argparse.Namespace) -> dict[str, str]:
+ style: dict[str, str] = {}
+ if args.fill is not None:
+ style["fill"] = args.fill
+ if args.fill_opacity is not None:
+ _validate_opacity("--fill-opacity", args.fill_opacity)
+ style["fill-opacity"] = str(args.fill_opacity)
+ if args.stroke is not None:
+ style["stroke"] = args.stroke
+ if args.stroke_width is not None:
+ if not math.isfinite(args.stroke_width) or args.stroke_width < 0:
+ raise ValueError("--stroke-width must be greater than or equal to 0")
+ style["stroke-width"] = str(args.stroke_width)
+ if args.stroke_opacity is not None:
+ _validate_opacity("--stroke-opacity", args.stroke_opacity)
+ style["stroke-opacity"] = str(args.stroke_opacity)
+ return style
+
+
+def _validate_opacity(option: str, value: float) -> None:
+ if not math.isfinite(value) or not 0 <= value <= 1:
+ raise ValueError(f"{option} must be between 0 and 1")
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index 59aa4a97..5be5109e 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -70,6 +70,7 @@ from .styles import (
from .paths import (
PathCommand, parse_svg_path, parse_svg_points, svg_path_to_absolute,
normalize_path_commands, path_commands_to_drawingml,
+ transform_path_commands,
)
@@ -683,27 +684,6 @@ def _shape_xfrm_from_svg_rect(
return '', off_x, off_y, ext_cx, ext_cy, (off_x, off_y, off_x + ext_cx, off_y + ext_cy)
-def _transform_path_commands(
- commands: list[PathCommand],
- matrix: tuple[float, float, float, float, float, float],
-) -> list[PathCommand]:
- """Apply an affine transform to normalized M/L/C/Z path commands."""
- transformed: list[PathCommand] = []
- for cmd in commands:
- if cmd.cmd in ('M', 'L'):
- x, y = transform_point(matrix, cmd.args[0], cmd.args[1])
- transformed.append(PathCommand(cmd.cmd, [x, y]))
- elif cmd.cmd == 'C':
- args: list[float] = []
- for i in range(0, 6, 2):
- x, y = transform_point(matrix, cmd.args[i], cmd.args[i + 1])
- args.extend([x, y])
- transformed.append(PathCommand(cmd.cmd, args))
- else:
- transformed.append(cmd)
- return transformed
-
-
# ---------------------------------------------------------------------------
# rect
# ---------------------------------------------------------------------------
@@ -1714,7 +1694,7 @@ def convert_path(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
transform = elem.get('transform')
if _uses_full_transform(ctx, transform):
- commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
+ commands = transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
commands, 0, 0, 1.0, 1.0,
)
@@ -1797,7 +1777,7 @@ def convert_polygon(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
transform = elem.get('transform')
if _uses_full_transform(ctx, transform):
- commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
+ commands = transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
commands, 0, 0, 1.0, 1.0,
)
@@ -1865,7 +1845,7 @@ def convert_polyline(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | Non
transform = elem.get('transform')
if _uses_full_transform(ctx, transform):
- commands = _transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
+ commands = transform_path_commands(commands, _combined_transform_matrix(ctx, transform))
path_xml, min_x, min_y, width, height = path_commands_to_drawingml(
commands, 0, 0, 1.0, 1.0,
)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py
index aba92947..a12a6594 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py
@@ -12,6 +12,7 @@ from collections.abc import Iterator
from dataclasses import dataclass, field
from xml.etree import ElementTree as ET
+from .context import AffineMatrix
from .utils import (
SVG_NS,
parse_inline_style,
@@ -19,6 +20,7 @@ from .utils import (
project_definition_index,
px_to_emu,
resolve_url_id,
+ transform_point,
)
@@ -750,6 +752,35 @@ def normalize_path_commands(commands: list[PathCommand]) -> list[PathCommand]:
return result
+def transform_path_commands(
+ commands: list[PathCommand],
+ matrix: AffineMatrix,
+) -> list[PathCommand]:
+ """Apply an affine transform to normalized M/L/C/Z path commands."""
+ transformed: list[PathCommand] = []
+ for command in commands:
+ if command.cmd in {'M', 'L'}:
+ x, y = transform_point(
+ matrix,
+ command.args[0],
+ command.args[1],
+ )
+ transformed.append(PathCommand(command.cmd, [x, y]))
+ elif command.cmd == 'C':
+ args: list[float] = []
+ for index in range(0, 6, 2):
+ x, y = transform_point(
+ matrix,
+ command.args[index],
+ command.args[index + 1],
+ )
+ args.extend([x, y])
+ transformed.append(PathCommand(command.cmd, args))
+ else:
+ transformed.append(command)
+ return transformed
+
+
def path_commands_to_drawingml(
commands: list[PathCommand],
offset_x: float = 0,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/shape_boolean.py b/skills/ppt-master/scripts/svg_to_pptx/shape_boolean.py
new file mode 100644
index 00000000..1b772070
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/shape_boolean.py
@@ -0,0 +1,1249 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Shape Boolean Core
+
+Resolve closed SVG operands into root-coordinate paths and apply
+PowerPoint-compatible merge-shapes operations without mutating the source SVG.
+Callers insert returned paths at the SVG root in the primary operand's z-order;
+reinserting them below an original transformed ancestor would transform twice.
+
+Usage:
+ Import render_boolean_svg_fragments from svg_to_pptx.shape_boolean.
+
+Examples:
+ fragment = render_boolean_svg_fragments(
+ "projects/demo/svg_output/slide-01.svg",
+ operation="intersect",
+ source_ids=("shape-a", "shape-b"),
+ output_id="shape-overlap",
+ )
+
+Dependencies:
+ skia-pathops and local PPT Master modules
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import Any
+from xml.etree import ElementTree as ET
+
+from pptx_to_svg.emu_units import Xfrm
+from pptx_to_svg.preset_authoring import (
+ authored_preset_encoding,
+ validate_authored_preset_group,
+)
+from pptx_to_svg.preset_registry_to_svg import render_preset_geometry
+from pptx_to_svg.preset_svg_markup import attrs_to_xml
+
+from .drawingml.context import AffineMatrix, IDENTITY_MATRIX
+from .drawingml.paths import (
+ PathCommand,
+ normalize_path_commands,
+ parse_svg_path,
+ parse_svg_points,
+ svg_path_to_absolute,
+ transform_path_commands,
+)
+from .drawingml.utils import (
+ matrix_multiply,
+ parse_inline_style,
+ parse_opacity,
+ parse_project_geometry_length,
+ parse_transform_matrix,
+)
+
+
+BOOLEAN_OPERATIONS = frozenset({
+ "combine",
+ "fragment",
+ "intersect",
+ "subtract",
+ "union",
+})
+
+_BOOLEAN_TAGS = frozenset({"circle", "ellipse", "path", "polygon", "rect"})
+_DEFINITION_TAGS = frozenset({
+ "clipPath",
+ "defs",
+ "marker",
+ "mask",
+ "pattern",
+ "symbol",
+})
+_ID_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_.:-]*")
+_PRESENTATION_ATTRS = (
+ "fill",
+ "fill-opacity",
+ "opacity",
+ "stroke",
+ "stroke-dasharray",
+ "stroke-width",
+ "stroke-opacity",
+ "stroke-linecap",
+ "stroke-linejoin",
+)
+_ROUNDTRIP_TRANSPORT_ATTRS = frozenset({
+ "data-pptx-custgeom",
+ "data-pptx-custgeom-ref",
+ "data-pptx-geometry-kind",
+ "data-pptx-native",
+ "data-pptx-native-ref",
+ "data-pptx-native-source",
+ "data-pptx-native-status",
+ "data-pptx-part",
+ "data-pptx-shape-id",
+ "data-pptx-shape-scope",
+ "data-pptx-source-ref",
+})
+_RESULT_PRECISION = 6
+_BEZIER_QUARTER_K = 0.5522847498307936
+
+
+def render_boolean_svg_fragments(
+ svg_file: str | Path,
+ *,
+ operation: str,
+ source_ids: Sequence[str],
+ output_id: str,
+ style: Mapping[str, str] | None = None,
+) -> str:
+ """Return canonical SVG path fragments for one merge-shapes operation.
+
+ The first source is the primary shape: subtract removes all later sources
+ from it, and every result inherits its effective presentation attributes.
+ All transforms are baked into root SVG coordinates, so callers must insert
+ the result at the root in the primary operand's z-order. Fragment returns
+ top-to-bottom, left-to-right sibling paths named ``<output_id>-1`` onward;
+ every other operation returns one path named exactly ``output_id``.
+ """
+ if not isinstance(operation, str):
+ raise ValueError("Shape Boolean operation must be a string")
+ normalized_operation = operation.strip().lower()
+ if normalized_operation not in BOOLEAN_OPERATIONS:
+ allowed = ", ".join(sorted(BOOLEAN_OPERATIONS))
+ raise ValueError(
+ f"Unsupported shape Boolean operation {operation!r}; use {allowed}"
+ )
+ source_id_list = _validate_source_ids(source_ids)
+ _validate_output_id(output_id)
+ style_overrides = _validate_style_overrides(style)
+
+ source_path = Path(svg_file)
+ try:
+ root = ET.parse(source_path).getroot()
+ except ET.ParseError as exc:
+ raise ValueError(f"Cannot parse SVG {source_path}: {exc}") from exc
+ if _local_name(root.tag) != "svg":
+ raise ValueError(f"Shape Boolean source must have an SVG root: {source_path}")
+ if any(_local_name(element.tag) == "style" for element in root.iter()):
+ raise ValueError(
+ "Shape Boolean does not resolve embedded CSS; use explicit SVG "
+ "presentation attributes on the operands"
+ )
+
+ parents = {
+ child: parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ elements_by_id, duplicate_ids = _index_element_ids(root)
+ selected: list[ET.Element] = []
+ for source_id in source_id_list:
+ if source_id in duplicate_ids:
+ raise ValueError(
+ f"Shape Boolean source id {source_id!r} is not unique"
+ )
+ element = elements_by_id.get(source_id)
+ if element is None:
+ raise ValueError(f"Shape Boolean source id not found: {source_id!r}")
+ selected.append(element)
+
+ pathops = _load_pathops()
+ operands = [
+ _element_to_pathops(element, parents, pathops)
+ for element in selected
+ ]
+ inherited_style = _effective_style(selected[0], parents)
+ inherited_style.update(style_overrides)
+
+ if normalized_operation == "fragment":
+ results = _fragment_paths(operands, pathops)
+ fragments: list[str] = []
+ for index, result in enumerate(results, start=1):
+ result_id = f"{output_id}-{index}"
+ _validate_result_id_collision(
+ result_id,
+ elements_by_id,
+ source_id_list,
+ )
+ fragments.append(
+ _serialize_result_path(
+ result,
+ result_id,
+ inherited_style,
+ pathops,
+ )
+ )
+ return "\n".join(fragments)
+
+ result = _merge_paths(normalized_operation, operands, pathops)
+ if _path_is_empty(result):
+ raise ValueError(
+ f"Shape Boolean {normalized_operation} produced no filled area"
+ )
+ _validate_result_id_collision(output_id, elements_by_id, source_id_list)
+ return _serialize_result_path(
+ result,
+ output_id,
+ inherited_style,
+ pathops,
+ )
+
+
+def _validate_source_ids(source_ids: Sequence[str]) -> list[str]:
+ if isinstance(source_ids, (str, bytes)):
+ raise ValueError("Shape Boolean source_ids must be a sequence of ids")
+ values = list(source_ids)
+ if len(values) < 2:
+ raise ValueError("Shape Boolean requires at least two source ids")
+ if any(not isinstance(value, str) or not value for value in values):
+ raise ValueError("Shape Boolean source ids must be non-empty strings")
+ if len(set(values)) != len(values):
+ raise ValueError("Shape Boolean source ids must be unique")
+ return values
+
+
+def _validate_output_id(output_id: str) -> None:
+ if not isinstance(output_id, str) or _ID_RE.fullmatch(output_id) is None:
+ raise ValueError(f"Invalid SVG output id: {output_id!r}")
+
+
+def _validate_style_overrides(
+ style: Mapping[str, str] | None,
+) -> dict[str, str]:
+ if style is None:
+ return {}
+ unknown = sorted(set(style) - set(_PRESENTATION_ATTRS))
+ if unknown:
+ raise ValueError(
+ "Unsupported shape Boolean style override(s): "
+ + ", ".join(unknown)
+ )
+ normalized: dict[str, str] = {}
+ for name in _PRESENTATION_ATTRS:
+ if name not in style:
+ continue
+ value = style[name]
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(
+ f"Shape Boolean style override {name!r} must be a non-empty string"
+ )
+ normalized[name] = value.strip()
+ return normalized
+
+
+def _index_element_ids(
+ root: ET.Element,
+) -> tuple[dict[str, ET.Element], set[str]]:
+ elements: dict[str, ET.Element] = {}
+ duplicates: set[str] = set()
+ for element in root.iter():
+ element_id = element.get("id")
+ if not element_id:
+ continue
+ if element_id in elements:
+ duplicates.add(element_id)
+ else:
+ elements[element_id] = element
+ return elements, duplicates
+
+
+def _validate_result_id_collision(
+ result_id: str,
+ elements_by_id: Mapping[str, ET.Element],
+ source_ids: Sequence[str],
+) -> None:
+ if result_id in elements_by_id and result_id not in source_ids:
+ raise ValueError(
+ f"Shape Boolean result id already exists outside the sources: "
+ f"{result_id!r}"
+ )
+
+
+def _load_pathops() -> Any:
+ try:
+ import pathops
+ except ImportError as exc:
+ raise RuntimeError(
+ "Shape Boolean operations require skia-pathops. Install the "
+ "project requirements, or run: pip install skia-pathops"
+ ) from exc
+ required = (
+ "FillType",
+ "Path",
+ "PathOp",
+ "PathOpsError",
+ "PathVerb",
+ "op",
+ "simplify",
+ )
+ missing = [name for name in required if not hasattr(pathops, name)]
+ if missing:
+ raise RuntimeError(
+ "Installed skia-pathops is incompatible; missing: "
+ + ", ".join(missing)
+ )
+ return pathops
+
+
+def _element_to_pathops(
+ element: ET.Element,
+ parents: Mapping[ET.Element, ET.Element],
+ pathops: Any,
+) -> Any:
+ chain = _element_chain(element, parents)
+ _validate_source_location(element, chain)
+ matrix = _combined_transform(chain)
+ tag = _local_name(element.tag)
+
+ if tag == "g":
+ commands = _compact_preset_commands(element, matrix)
+ elif tag in _BOOLEAN_TAGS:
+ commands = _shape_commands(element)
+ commands = transform_path_commands(commands, matrix)
+ else:
+ supported = ", ".join(sorted(_BOOLEAN_TAGS))
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} must be a closed "
+ f"{supported}, or a compact authored preset group"
+ )
+
+ result = _simplify_path(_commands_to_pathops(commands, pathops), pathops)
+ if _path_is_empty(result):
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} has no filled area"
+ )
+ return result
+
+
+def _element_chain(
+ element: ET.Element,
+ parents: Mapping[ET.Element, ET.Element],
+) -> list[ET.Element]:
+ chain = [element]
+ current = element
+ while current in parents:
+ current = parents[current]
+ chain.append(current)
+ chain.reverse()
+ return chain
+
+
+def _validate_source_location(
+ element: ET.Element,
+ chain: Sequence[ET.Element],
+) -> None:
+ definition_ancestor = next(
+ (
+ ancestor
+ for ancestor in chain[:-1]
+ if _local_name(ancestor.tag) in _DEFINITION_TAGS
+ ),
+ None,
+ )
+ if definition_ancestor is not None:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} is inside "
+ f"<{_local_name(definition_ancestor.tag)}>"
+ )
+ nested_svg_count = sum(
+ 1 for ancestor in chain if _local_name(ancestor.tag) == "svg"
+ )
+ if nested_svg_count > 1:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} is inside a nested "
+ "<svg>; materialize its viewport transform first"
+ )
+ for ancestor in chain[:-1]:
+ if (
+ _local_name(ancestor.tag) == "g"
+ and authored_preset_encoding(ancestor) is not None
+ ):
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} is inside an "
+ "authored preset; select the preset group's id"
+ )
+ _validate_geometry_presentation(element, chain)
+
+
+def _validate_geometry_presentation(
+ element: ET.Element,
+ chain: Sequence[ET.Element],
+) -> None:
+ fill_rule = "nonzero"
+ for current in chain:
+ if current.get("class") is not None:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} uses class; "
+ "materialize its computed presentation first"
+ )
+ transport_attrs = sorted(
+ name
+ for name in _ROUNDTRIP_TRANSPORT_ATTRS
+ if current.get(name) is not None
+ )
+ if transport_attrs:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} carries "
+ "PPTX import/round-trip metadata "
+ f"({', '.join(transport_attrs)}); author or materialize an "
+ "ordinary SVG shape first"
+ )
+ inline = parse_inline_style(current.get("style"))
+ inline_transform = inline.get("transform")
+ if (
+ inline_transform is not None
+ and inline_transform.strip().lower() not in {"", "none"}
+ ):
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} uses a CSS "
+ "transform; write it as an SVG transform attribute first"
+ )
+ display = inline.get("display", current.get("display"))
+ if display is not None and display.strip().lower() == "none":
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} is not "
+ "displayed"
+ )
+ visibility = inline.get("visibility", current.get("visibility"))
+ if visibility is not None and visibility.strip().lower() in {
+ "collapse",
+ "hidden",
+ }:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} is not visible"
+ )
+ for name in ("clip-path", "mask"):
+ raw = inline.get(name, current.get(name))
+ if raw is not None and raw.strip().lower() not in {"", "none"}:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} uses "
+ f"{name}; materialize the visible contour first"
+ )
+ raw_filter = inline.get("filter", current.get("filter"))
+ if raw_filter is not None and raw_filter.strip().lower() not in {
+ "",
+ "none",
+ }:
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} uses filter; "
+ "reapply the effect after materializing the result"
+ )
+ raw_fill_rule = inline.get("fill-rule", current.get("fill-rule"))
+ if (
+ raw_fill_rule is not None
+ and raw_fill_rule.strip().lower() != "inherit"
+ ):
+ fill_rule = raw_fill_rule.strip().lower()
+ if fill_rule != "nonzero":
+ raise ValueError(
+ f"Shape Boolean source {_element_label(element)} uses "
+ f"fill-rule={fill_rule!r}; use explicit nonzero contour direction"
+ )
+
+
+def _combined_transform(chain: Sequence[ET.Element]) -> AffineMatrix:
+ matrix = IDENTITY_MATRIX
+ for element in chain[1:]:
+ transform = element.get("transform")
+ if transform:
+ matrix = matrix_multiply(
+ matrix,
+ parse_transform_matrix(transform),
+ )
+ return matrix
+
+
+def _shape_commands(element: ET.Element) -> list[PathCommand]:
+ tag = _local_name(element.tag)
+ if tag == "path":
+ raw_path = element.get("d")
+ if raw_path is None:
+ raise ValueError(f"{_element_label(element)} requires d")
+ commands = normalize_path_commands(
+ svg_path_to_absolute(parse_svg_path(raw_path))
+ )
+ _require_closed_commands(commands, _element_label(element))
+ return commands
+
+ if tag == "polygon":
+ points = parse_svg_points(
+ element.get("points", ""),
+ min_points=3,
+ )
+ commands = [PathCommand("M", [*points[0]])]
+ commands.extend(
+ PathCommand("L", [x, y])
+ for x, y in points[1:]
+ )
+ commands.append(PathCommand("Z", []))
+ return commands
+
+ if tag == "rect":
+ return _rect_commands(element)
+
+ if tag == "circle":
+ cx = _geometry_value(element, "cx", default=0.0)
+ cy = _geometry_value(element, "cy", default=0.0)
+ radius = _geometry_value(element, "r", required=True)
+ if radius <= 0:
+ raise ValueError(f"{_element_label(element)} r must be greater than 0")
+ return _ellipse_commands(cx, cy, radius, radius)
+
+ if tag == "ellipse":
+ cx = _geometry_value(element, "cx", default=0.0)
+ cy = _geometry_value(element, "cy", default=0.0)
+ radius_x = _geometry_value(element, "rx", required=True)
+ radius_y = _geometry_value(element, "ry", required=True)
+ if radius_x <= 0 or radius_y <= 0:
+ raise ValueError(
+ f"{_element_label(element)} rx and ry must be greater than 0"
+ )
+ return _ellipse_commands(cx, cy, radius_x, radius_y)
+
+ raise AssertionError(f"Unhandled Boolean source tag: {tag}")
+
+
+def _geometry_value(
+ element: ET.Element,
+ attribute: str,
+ *,
+ default: float | None = None,
+ required: bool = False,
+) -> float:
+ raw = element.get(attribute)
+ if raw is None:
+ if required:
+ raise ValueError(f"{_element_label(element)} requires {attribute}")
+ if default is None:
+ raise AssertionError("Geometry attribute requires a default")
+ return default
+ try:
+ return parse_project_geometry_length(raw, attribute)
+ except ValueError as exc:
+ raise ValueError(
+ f"{_element_label(element)} {attribute}: {exc}"
+ ) from exc
+
+
+def _rect_commands(element: ET.Element) -> list[PathCommand]:
+ x = _geometry_value(element, "x", default=0.0)
+ y = _geometry_value(element, "y", default=0.0)
+ width = _geometry_value(element, "width", required=True)
+ height = _geometry_value(element, "height", required=True)
+ if width <= 0 or height <= 0:
+ raise ValueError(
+ f"{_element_label(element)} width and height must be greater than 0"
+ )
+
+ raw_rx = element.get("rx")
+ raw_ry = element.get("ry")
+ radius_x = (
+ _geometry_value(element, "rx", required=True)
+ if raw_rx is not None else 0.0
+ )
+ radius_y = (
+ _geometry_value(element, "ry", required=True)
+ if raw_ry is not None else 0.0
+ )
+ if raw_rx is not None and raw_ry is None:
+ radius_y = radius_x
+ elif raw_ry is not None and raw_rx is None:
+ radius_x = radius_y
+ if radius_x < 0 or radius_y < 0:
+ raise ValueError(
+ f"{_element_label(element)} rx and ry must not be negative"
+ )
+
+ radius_x = min(radius_x, width / 2.0)
+ radius_y = min(radius_y, height / 2.0)
+ if radius_x <= 0 or radius_y <= 0:
+ return [
+ PathCommand("M", [x, y]),
+ PathCommand("L", [x + width, y]),
+ PathCommand("L", [x + width, y + height]),
+ PathCommand("L", [x, y + height]),
+ PathCommand("Z", []),
+ ]
+
+ kx = radius_x * _BEZIER_QUARTER_K
+ ky = radius_y * _BEZIER_QUARTER_K
+ right = x + width
+ bottom = y + height
+ return [
+ PathCommand("M", [x + radius_x, y]),
+ PathCommand("L", [right - radius_x, y]),
+ PathCommand(
+ "C",
+ [
+ right - radius_x + kx,
+ y,
+ right,
+ y + radius_y - ky,
+ right,
+ y + radius_y,
+ ],
+ ),
+ PathCommand("L", [right, bottom - radius_y]),
+ PathCommand(
+ "C",
+ [
+ right,
+ bottom - radius_y + ky,
+ right - radius_x + kx,
+ bottom,
+ right - radius_x,
+ bottom,
+ ],
+ ),
+ PathCommand("L", [x + radius_x, bottom]),
+ PathCommand(
+ "C",
+ [
+ x + radius_x - kx,
+ bottom,
+ x,
+ bottom - radius_y + ky,
+ x,
+ bottom - radius_y,
+ ],
+ ),
+ PathCommand("L", [x, y + radius_y]),
+ PathCommand(
+ "C",
+ [
+ x,
+ y + radius_y - ky,
+ x + radius_x - kx,
+ y,
+ x + radius_x,
+ y,
+ ],
+ ),
+ PathCommand("Z", []),
+ ]
+
+
+def _ellipse_commands(
+ center_x: float,
+ center_y: float,
+ radius_x: float,
+ radius_y: float,
+) -> list[PathCommand]:
+ kx = radius_x * _BEZIER_QUARTER_K
+ ky = radius_y * _BEZIER_QUARTER_K
+ return [
+ PathCommand("M", [center_x + radius_x, center_y]),
+ PathCommand(
+ "C",
+ [
+ center_x + radius_x,
+ center_y + ky,
+ center_x + kx,
+ center_y + radius_y,
+ center_x,
+ center_y + radius_y,
+ ],
+ ),
+ PathCommand(
+ "C",
+ [
+ center_x - kx,
+ center_y + radius_y,
+ center_x - radius_x,
+ center_y + ky,
+ center_x - radius_x,
+ center_y,
+ ],
+ ),
+ PathCommand(
+ "C",
+ [
+ center_x - radius_x,
+ center_y - ky,
+ center_x - kx,
+ center_y - radius_y,
+ center_x,
+ center_y - radius_y,
+ ],
+ ),
+ PathCommand(
+ "C",
+ [
+ center_x + kx,
+ center_y - radius_y,
+ center_x + radius_x,
+ center_y - ky,
+ center_x + radius_x,
+ center_y,
+ ],
+ ),
+ PathCommand("Z", []),
+ ]
+
+
+def _compact_preset_commands(
+ group: ET.Element,
+ matrix: AffineMatrix,
+) -> list[PathCommand]:
+ encoding = authored_preset_encoding(group)
+ if encoding != "compact":
+ raise ValueError(
+ f"Shape Boolean source {_element_label(group)} must be a compact "
+ "authored preset group"
+ )
+ errors = validate_authored_preset_group(group)
+ if errors:
+ raise ValueError(
+ f"Invalid compact authored preset {_element_label(group)}: "
+ + "; ".join(errors)
+ )
+ if group.get("data-pptx-object") != "shape":
+ raise ValueError(
+ f"Shape Boolean source {_element_label(group)} must be a shape, "
+ "not a connector"
+ )
+
+ frame = tuple(
+ float(value)
+ for value in (group.get("data-pptx-frame") or "").split()
+ )
+ if len(frame) != 4:
+ raise ValueError(
+ f"Compact authored preset {_element_label(group)} has an invalid "
+ "data-pptx-frame"
+ )
+ adjustments = {
+ name[len("data-pptx-av-"):]: value
+ for name, value in group.attrib.items()
+ if name.startswith("data-pptx-av-")
+ }
+ rendered = render_preset_geometry(
+ group.get("data-pptx-prst") or "",
+ Xfrm(x=frame[0], y=frame[1], w=frame[2], h=frame[3]),
+ adjustments,
+ )
+ children = list(group)
+ if len(children) != len(rendered.paths):
+ raise ValueError(
+ f"Compact authored preset {_element_label(group)} layer count "
+ "differs from its registry geometry"
+ )
+
+ commands: list[PathCommand] = []
+ for child, layer in zip(children, rendered.paths):
+ if layer.fill == "none":
+ continue
+ raw_path = child.get("d")
+ if raw_path is None:
+ raise ValueError(
+ f"Compact authored preset {_element_label(group)} contains a "
+ "path without d"
+ )
+ child_commands = normalize_path_commands(
+ svg_path_to_absolute(parse_svg_path(raw_path))
+ )
+ child_commands = _close_filled_commands(
+ child_commands,
+ f"{_element_label(group)} preset layer",
+ )
+ commands.extend(transform_path_commands(child_commands, matrix))
+ if not commands:
+ raise ValueError(
+ f"Compact authored preset {_element_label(group)} has no filled "
+ "silhouette"
+ )
+ return commands
+
+
+def _close_filled_commands(
+ commands: Sequence[PathCommand],
+ label: str,
+) -> list[PathCommand]:
+ closed: list[PathCommand] = []
+ open_subpath = False
+ drew_segment = False
+ for command in commands:
+ if command.cmd == "M":
+ if open_subpath:
+ if not drew_segment:
+ raise ValueError(f"{label} has an empty subpath")
+ closed.append(PathCommand("Z", []))
+ open_subpath = True
+ drew_segment = False
+ elif command.cmd in {"L", "C"}:
+ if not open_subpath:
+ raise ValueError(f"{label} draws before its first move")
+ drew_segment = True
+ elif command.cmd == "Z":
+ if not open_subpath:
+ raise ValueError(f"{label} closes without an open subpath")
+ if not drew_segment:
+ raise ValueError(f"{label} has an empty subpath")
+ open_subpath = False
+ closed.append(command)
+ if open_subpath:
+ if not drew_segment:
+ raise ValueError(f"{label} has an empty subpath")
+ closed.append(PathCommand("Z", []))
+ if not closed:
+ raise ValueError(f"{label} has no drawable contour")
+ return closed
+
+
+def _require_closed_commands(
+ commands: Sequence[PathCommand],
+ label: str,
+) -> None:
+ open_subpath = False
+ drew_segment = False
+ closed_contour = False
+ for command in commands:
+ if command.cmd == "M":
+ if open_subpath:
+ raise ValueError(f"{label} contains an open subpath")
+ open_subpath = True
+ drew_segment = False
+ elif command.cmd in {"L", "C"}:
+ if not open_subpath:
+ raise ValueError(f"{label} draws before its first move")
+ drew_segment = True
+ elif command.cmd == "Z":
+ if not open_subpath:
+ raise ValueError(f"{label} closes without an open subpath")
+ if not drew_segment:
+ raise ValueError(f"{label} has an empty subpath")
+ open_subpath = False
+ closed_contour = True
+ if open_subpath:
+ raise ValueError(f"{label} contains an open subpath")
+ if not closed_contour:
+ raise ValueError(f"{label} has no drawable closed contour")
+
+
+def _commands_to_pathops(
+ commands: Sequence[PathCommand],
+ pathops: Any,
+) -> Any:
+ result = pathops.Path(fillType=pathops.FillType.WINDING)
+ for command in commands:
+ args = command.args
+ if command.cmd == "M":
+ result.moveTo(args[0], args[1])
+ elif command.cmd == "L":
+ result.lineTo(args[0], args[1])
+ elif command.cmd == "C":
+ result.cubicTo(*args)
+ elif command.cmd == "Z":
+ result.close()
+ else:
+ raise AssertionError(
+ f"Unexpected normalized path command: {command.cmd}"
+ )
+ return result
+
+
+def _merge_paths(
+ operation: str,
+ operands: Sequence[Any],
+ pathops: Any,
+) -> Any:
+ operator_by_name = {
+ "combine": pathops.PathOp.XOR,
+ "intersect": pathops.PathOp.INTERSECTION,
+ "subtract": pathops.PathOp.DIFFERENCE,
+ "union": pathops.PathOp.UNION,
+ }
+ operator = operator_by_name[operation]
+ result = operands[0]
+ for operand in operands[1:]:
+ result = _path_op(result, operand, operator, pathops)
+ if _path_is_empty(result) and operation in {"intersect", "subtract"}:
+ break
+ return result
+
+
+def _path_op(
+ first: Any,
+ second: Any,
+ operator: Any,
+ pathops: Any,
+) -> Any:
+ try:
+ return pathops.op(
+ first,
+ second,
+ operator,
+ fix_winding=True,
+ keep_starting_points=False,
+ clockwise=False,
+ )
+ except pathops.PathOpsError as exc:
+ raise ValueError(f"Skia path Boolean operation failed: {exc}") from exc
+
+
+def _simplify_path(path: Any, pathops: Any) -> Any:
+ """Resolve winding and self-intersections before filled-area checks."""
+ try:
+ return pathops.simplify(
+ path,
+ fix_winding=True,
+ keep_starting_points=False,
+ clockwise=False,
+ )
+ except pathops.PathOpsError as exc:
+ raise ValueError(f"Skia path simplification failed: {exc}") from exc
+
+
+def _fragment_paths(
+ operands: Sequence[Any],
+ pathops: Any,
+) -> list[Any]:
+ pieces: list[Any] = []
+ covered: Any | None = None
+ for operand in operands:
+ split_pieces: list[Any] = []
+ for piece in pieces:
+ difference = _path_op(
+ piece,
+ operand,
+ pathops.PathOp.DIFFERENCE,
+ pathops,
+ )
+ intersection = _path_op(
+ piece,
+ operand,
+ pathops.PathOp.INTERSECTION,
+ pathops,
+ )
+ if not _path_is_empty(difference):
+ split_pieces.append(difference)
+ if not _path_is_empty(intersection):
+ split_pieces.append(intersection)
+
+ unique = (
+ operand
+ if covered is None
+ else _path_op(
+ operand,
+ covered,
+ pathops.PathOp.DIFFERENCE,
+ pathops,
+ )
+ )
+ if not _path_is_empty(unique):
+ split_pieces.append(unique)
+ pieces = split_pieces
+ covered = (
+ operand
+ if covered is None
+ else _path_op(
+ covered,
+ operand,
+ pathops.PathOp.UNION,
+ pathops,
+ )
+ )
+
+ components = [
+ component
+ for piece in pieces
+ for component in _connected_components(piece, pathops)
+ if not _path_is_empty(component)
+ ]
+ if not components:
+ raise ValueError("Shape Boolean fragment produced no filled area")
+ components.sort(key=_path_sort_key)
+ return components
+
+
+def _connected_components(path: Any, pathops: Any) -> list[Any]:
+ contours = [
+ contour
+ for contour in path.contours
+ if not _path_is_empty(contour)
+ ]
+ if len(contours) <= 1:
+ return contours
+
+ parents: list[int | None] = [None] * len(contours)
+ for child_index, child in enumerate(contours):
+ child_bounds = child.bounds
+ child_points = child.firstPoints
+ if child_bounds is None or not child_points:
+ continue
+ candidates: list[tuple[float, int]] = []
+ for parent_index, candidate in enumerate(contours):
+ if child_index == parent_index:
+ continue
+ candidate_bounds = candidate.bounds
+ if candidate_bounds is None:
+ continue
+ if not _bounds_contain(candidate_bounds, child_bounds):
+ continue
+ if candidate.area <= child.area:
+ continue
+ if candidate.contains(child_points[0]):
+ candidates.append((candidate.area, parent_index))
+ if candidates:
+ parents[child_index] = min(candidates)[1]
+
+ depths = [
+ _contour_depth(index, parents)
+ for index in range(len(contours))
+ ]
+ components: list[Any] = []
+ for index, contour in enumerate(contours):
+ if depths[index] % 2:
+ continue
+ component = pathops.Path(fillType=pathops.FillType.WINDING)
+ component.addPath(contour)
+ for child_index, parent_index in enumerate(parents):
+ if parent_index == index and depths[child_index] % 2:
+ component.addPath(contours[child_index])
+ components.append(component)
+ return components
+
+
+def _bounds_contain(
+ outer: tuple[float, float, float, float],
+ inner: tuple[float, float, float, float],
+) -> bool:
+ scale = max(
+ *(abs(value) for value in outer),
+ *(abs(value) for value in inner),
+ 1.0,
+ )
+ tolerance = scale * 1e-7
+ return (
+ outer[0] <= inner[0] + tolerance
+ and outer[1] <= inner[1] + tolerance
+ and outer[2] >= inner[2] - tolerance
+ and outer[3] >= inner[3] - tolerance
+ )
+
+
+def _contour_depth(
+ index: int,
+ parents: Sequence[int | None],
+) -> int:
+ depth = 0
+ seen = {index}
+ parent = parents[index]
+ while parent is not None:
+ if parent in seen:
+ raise ValueError("Shape Boolean fragment produced cyclic contours")
+ seen.add(parent)
+ depth += 1
+ parent = parents[parent]
+ return depth
+
+
+def _path_is_empty(path: Any) -> bool:
+ bounds = path.bounds
+ if bounds is None or len(path) == 0:
+ return True
+ width = bounds[2] - bounds[0]
+ height = bounds[3] - bounds[1]
+ scale = max(abs(width), abs(height), 1.0)
+ return (
+ width <= 0
+ or height <= 0
+ or not math.isfinite(path.area)
+ or path.area <= scale * scale * 1e-12
+ )
+
+
+def _path_sort_key(
+ path: Any,
+) -> tuple[
+ float,
+ float,
+ float,
+ float,
+ float,
+ tuple[tuple[str, tuple[float, ...]], ...],
+]:
+ bounds = path.bounds
+ signature = tuple(
+ (
+ str(verb),
+ tuple(
+ round(coordinate, _RESULT_PRECISION)
+ for point in points
+ for coordinate in point
+ ),
+ )
+ for verb, points in path
+ )
+ if bounds is None:
+ return (
+ math.inf,
+ math.inf,
+ math.inf,
+ math.inf,
+ math.inf,
+ signature,
+ )
+ return (
+ round(bounds[1], _RESULT_PRECISION),
+ round(bounds[0], _RESULT_PRECISION),
+ round(bounds[3], _RESULT_PRECISION),
+ round(bounds[2], _RESULT_PRECISION),
+ round(path.area, _RESULT_PRECISION),
+ signature,
+ )
+
+
+def _effective_style(
+ element: ET.Element,
+ parents: Mapping[ET.Element, ET.Element],
+) -> dict[str, str]:
+ values: dict[str, str] = {}
+ opacity = 1.0
+ parent_opacity = 1.0
+ chain = _element_chain(element, parents)
+ for index, current in enumerate(chain):
+ inline = parse_inline_style(current.get("style"))
+ raw_opacity = inline.get("opacity", current.get("opacity"))
+ if raw_opacity is None:
+ local_opacity = 1.0
+ elif raw_opacity.strip() == "inherit":
+ local_opacity = parent_opacity
+ else:
+ local_opacity = parse_opacity(raw_opacity)
+ if index > 0:
+ opacity *= local_opacity
+ parent_opacity = local_opacity
+ for name in _PRESENTATION_ATTRS:
+ if name == "opacity":
+ continue
+ raw = inline.get(name, current.get(name))
+ if raw is not None and raw.strip() != "inherit":
+ values[name] = raw.strip()
+ if opacity < 1.0:
+ values["opacity"] = _format_number(opacity)
+ return {
+ name: values[name]
+ for name in _PRESENTATION_ATTRS
+ if name in values
+ }
+
+
+def _serialize_result_path(
+ path: Any,
+ result_id: str,
+ style: Mapping[str, str],
+ pathops: Any,
+) -> str:
+ path_data = _pathops_to_svg_path(path, pathops)
+ attributes = {
+ "id": result_id,
+ "d": path_data,
+ **style,
+ }
+ return f"<path{attrs_to_xml(attributes)}/>"
+
+
+def _pathops_to_svg_path(path: Any, pathops: Any) -> str:
+ path.convertConicsToQuads(0.05)
+ parts: list[str] = []
+ current: tuple[float, float] | None = None
+ subpath_start: tuple[float, float] | None = None
+ open_subpath = False
+
+ for verb, points in path:
+ if verb == pathops.PathVerb.MOVE:
+ point = points[0]
+ parts.append(
+ f"M {_format_number(point[0])} {_format_number(point[1])}"
+ )
+ current = point
+ subpath_start = point
+ open_subpath = True
+ elif verb == pathops.PathVerb.LINE:
+ point = points[0]
+ parts.append(
+ f"L {_format_number(point[0])} {_format_number(point[1])}"
+ )
+ current = point
+ elif verb == pathops.PathVerb.QUAD:
+ if current is None:
+ raise ValueError("Shape Boolean result quadratic has no start point")
+ control, end = points
+ control_1 = (
+ current[0] + (control[0] - current[0]) * 2.0 / 3.0,
+ current[1] + (control[1] - current[1]) * 2.0 / 3.0,
+ )
+ control_2 = (
+ end[0] + (control[0] - end[0]) * 2.0 / 3.0,
+ end[1] + (control[1] - end[1]) * 2.0 / 3.0,
+ )
+ parts.append(
+ "C "
+ f"{_format_point(control_1)} "
+ f"{_format_point(control_2)} "
+ f"{_format_point(end)}"
+ )
+ current = end
+ elif verb == pathops.PathVerb.CUBIC:
+ control_1, control_2, end = points
+ parts.append(
+ "C "
+ f"{_format_point(control_1)} "
+ f"{_format_point(control_2)} "
+ f"{_format_point(end)}"
+ )
+ current = end
+ elif verb == pathops.PathVerb.CLOSE:
+ parts.append("Z")
+ current = subpath_start
+ open_subpath = False
+ else:
+ raise ValueError(f"Unsupported skia-pathops result verb: {verb}")
+
+ if open_subpath:
+ raise ValueError("Shape Boolean engine returned an open contour")
+ if not parts:
+ raise ValueError("Shape Boolean engine returned no path commands")
+ return " ".join(parts)
+
+
+def _format_point(point: tuple[float, float]) -> str:
+ return f"{_format_number(point[0])} {_format_number(point[1])}"
+
+
+def _format_number(value: float) -> str:
+ if not math.isfinite(value):
+ raise ValueError("Shape Boolean result contains a non-finite coordinate")
+ rounded = round(value, _RESULT_PRECISION)
+ if abs(rounded) < 10 ** (-_RESULT_PRECISION):
+ return "0"
+ if rounded == int(rounded):
+ return str(int(rounded))
+ return f"{rounded:.{_RESULT_PRECISION}f}".rstrip("0").rstrip(".")
+
+
+def _local_name(tag: object) -> str:
+ raw = str(tag)
+ return raw.rsplit("}", 1)[-1] if "}" in raw else raw
+
+
+def _element_label(element: ET.Element) -> str:
+ tag = _local_name(element.tag)
+ element_id = element.get("id")
+ return f"<{tag} id={element_id!r}>" if element_id else f"<{tag}>"
diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.md
index dd41e674..be17a582 100644
--- a/skills/ppt-master/workflows/generate-pptx.md
+++ b/skills/ppt-master/workflows/generate-pptx.md
@@ -12,7 +12,7 @@ description: Generate PPTX route authority for source intake, planning, SVG auth
- The current main agent hand-writes every SVG page; never delegate page generation or run a Python, Node, or shell generator over `svg_output/`.
- Initial SVG cadence: P01 → first-page gate → uninterrupted remaining pages → final gate. Grouped batches and mid-run checker calls are forbidden.
-- `preset_shape_svg.py` may provide one stdout fragment only after the main agent chooses its semantic role, frame, and paint; it cannot choose layout or write a page.
+- `preset_shape_svg.py` and `shape_boolean_svg.py` may provide only their documented stdout fragment(s) after the main agent chooses the object's role, operands, paint, and z-order; neither helper chooses layout or writes a page.
- Gate checklists are internal verification, not user-facing output. On success, continue automatically and emit at most one compact status line when useful; on failure, report only the blocking items and required recovery.
### SVG Page-Design Boundary
@@ -345,7 +345,7 @@ Read references/visual-styles/<resolved-id>.md # one preset id, or each `visu
| `spec_lock.md images` or §VIII contains at least one image/formula row, or an active template carries bundled images | `executor-image.md` + `image-layout-patterns.md` + `image-layout-spec.md` + `svg-image-embedding.md` |
| At least one placed image has `Status: Sourced` | `executor-web-image.md` after the image branch |
| The locked style/current page calls for noncanonical or alpha paint, dash/cap/join, tracking/decoration/outline, gradient/filter/glow/shadow, path/transform/clipping, or another constructed effect | `svg-effects.md` before authoring that value or effect |
-| A page calls for a literal PowerPoint stock shape | `native-shape-authoring.md` before selecting or emitting that shape |
+| A page calls for a literal PowerPoint stock shape or an explicit Merge Shapes operation | `native-shape-authoring.md` before selecting or materializing that geometry |
| All SVG pages and SVG quality gates are complete | `executor-notes.md` before generating speaker notes |
No branch is loaded by analogy. Evaluate these triggers from `spec_lock.md`, §VII/§VIII, the selected style, and the current page plan.
@@ -374,7 +374,7 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemon
**Visual Construction Phase**: generate SVG pages sequentially, one at a time, in one continuous pass → `<project_path>/svg_output/`
-Each completed SVG MUST be a standalone, complete representation of that slide's visible design. Template SVGs and locked planning artifacts may guide construction, but export must not reach back to them to add visible objects omitted from `svg_output/`. Speaker notes, animation, narration, transitions, and direct native-PPTX workflows remain separately owned artifacts/capabilities. When a page actually needs a literal stock shape, load and apply [`native-shape-authoring.md`](../references/native-shape-authoring.md) before drawing it. Diagram relationships remain Shape-first; do not infer a preset from contour similarity.
+Each completed SVG MUST be a standalone, complete representation of that slide's visible design. Template SVGs and locked planning artifacts may guide construction, but export must not reach back to them to add visible objects omitted from `svg_output/`. Speaker notes, animation, narration, transitions, and direct native-PPTX workflows remain separately owned artifacts/capabilities. When a page actually needs a literal stock shape or an explicit Merge Shapes operation, load and apply [`native-shape-authoring.md`](../references/native-shape-authoring.md) before drawing or materializing it. Diagram relationships remain Shape-first; do not infer a preset from contour similarity.
`template_reuse_scope: mirror|layout` pages MUST start from the complete `page_layouts` SVG, keep inherited visible objects, and preserve root Master/Layout identity plus stable atoms/slots. Strict preserves that reusable contract; under `layout`, the once-loaded Design Spec's `Template Application` may still authorize carrier text/tspan reflow inside unchanged slot bounds. Adaptive uses the current or new Layout key/name already declared by Strategist. If construction proves that fixed atoms or slot topology/bounds must change, stop and return upstream for Strategist to repair the owning plan and lock, validate and read back the affected fragments, then resume; Executor never mutates `spec_lock.md`. `mirror` changes only visible text values while preserving text/tspan topology and attributes. `style` follows the flat paragraph below without structure metadata.