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(template): keep exact source frames and omit invisible unbounded roots

hugohe3e8ac905f7020
diff --git a/skills/ppt-master/scripts/compact_svg_coordinates.py b/skills/ppt-master/scripts/compact_svg_coordinates.py
index efc66e25..aea347ff 100644
--- a/skills/ppt-master/scripts/compact_svg_coordinates.py
+++ b/skills/ppt-master/scripts/compact_svg_coordinates.py
@@ -101,11 +101,16 @@ def format_coordinate(value: str | float) -> str:
return "0" if compact in {"", "-0"} else compact
-def _compact_coordinate_quad(value: str) -> str:
+def _compact_coordinate_quad(value: str, *, preserve_nonzero_extent: bool = False) -> str:
tokens = _number_tokens(value)
if tokens is None or len(tokens) != 4:
return value
- return " ".join(format_coordinate(token) for token in tokens)
+ compacted = [format_coordinate(token) for token in tokens]
+ if preserve_nonzero_extent:
+ for axis in (2, 3):
+ if float(tokens[axis]) > 0 and compacted[axis] == "0":
+ compacted[axis] = tokens[axis]
+ return " ".join(compacted)
def _compact_transform(value: str) -> str:
@@ -147,7 +152,9 @@ def _compact_attribute_value(
if name == "data-pptx-frame":
return _compact_coordinate_quad(value) if compact_native_frames else value
if name == "data-pptx-bounds":
- return _compact_coordinate_quad(value)
+ return _compact_coordinate_quad(
+ value, preserve_nonzero_extent=not compact_native_frames,
+ )
if name == "transform":
return _compact_transform(value)
return value
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
index 1d26a209..8f4e325c 100644
--- a/skills/ppt-master/scripts/mirror_template_materialize.py
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -69,9 +69,11 @@ from svg_authoring_view import (
semantic_subtree_sha256,
)
from svg_finalize.flatten_tspan import flatten_text_with_tspans
+from svg_to_pptx.drawingml.context import ConvertContext
from svg_to_pptx.drawingml.utils import (
is_stroked_zero_axis_shape,
parse_transform_matrix,
+ svg_hidden_reason,
transform_point,
)
from svg_to_pptx.pptx_package.template_structure import (
@@ -1461,7 +1463,7 @@ def _paint_value(element: ET.Element, name: str) -> str | None:
return _parse_style(element.get("style")).get(name)
-def _visible_leaf(element: ET.Element) -> bool:
+def _visible_leaf(element: ET.Element, *, check_dimensions: bool = True) -> bool:
if _hidden(element):
return False
tag = _local_name(element.tag)
@@ -1469,8 +1471,8 @@ def _visible_leaf(element: ET.Element) -> bool:
return False
if tag in {"g", "svg", "a"}:
return any(_visible_leaf(child) for child in element)
- if tag in {"rect", "image", "foreignObject"}:
- for dimension in ("width", "height"):
+ if tag in {"rect", "image", "foreignObject"} and (check_dimensions or tag != "rect"):
+ for dimension in ("width", "height") if check_dimensions else ():
raw = element.get(dimension)
if raw is not None:
try:
@@ -1482,7 +1484,7 @@ def _visible_leaf(element: ET.Element) -> bool:
if tag in {"line", "polyline"}:
stroke = _paint_value(element, "stroke")
return stroke not in {None, "none", "transparent"}
- if tag in {"path", "polygon", "circle", "ellipse"}:
+ if tag in {"rect", "path", "polygon", "circle", "ellipse"}:
fill = _paint_value(element, "fill")
stroke = _paint_value(element, "stroke")
return not (
@@ -1568,7 +1570,10 @@ def _flatten_fixed_group(group: ET.Element, *, context: str) -> list[ET.Element]
atoms.append(item)
if len(atoms) == 1:
atom = atoms[0]
- for name in ("data-pptx-frame", "data-pptx-object", "data-pptx-prst"):
+ for name in (
+ "data-pptx-frame", "data-pptx-object", "data-pptx-prst",
+ "data-pptx-geometry-kind",
+ ):
if group.get(name) is not None and atom.get(name) is None:
atom.set(name, group.get(name, ""))
return atoms
@@ -1594,6 +1599,7 @@ def _fixed_atoms(
scope: str,
key: str,
placeholder_source_refs: set[str] | None = None,
+ warnings: list[str] | None = None,
) -> list[ET.Element]:
atoms: list[ET.Element] = []
serial = 0
@@ -1606,6 +1612,13 @@ def _fixed_atoms(
or child.get(SOURCE_REF_ATTRIBUTE) in placeholder_source_refs
):
continue
+ if _invisible_degenerate_source(child):
+ if warnings is not None:
+ warnings.append(
+ f"{scope.title()} {key} element {child.get('id') or '<' + tag + '>'!r}: "
+ "omitted invisible content without a positive source frame"
+ )
+ continue
if not _visible_leaf(child):
continue
item = copy.deepcopy(child)
@@ -1648,6 +1661,39 @@ def _frame(element: ET.Element | None) -> tuple[float, float, float, float] | No
return values
+def _invisible_degenerate_source(element: ET.Element) -> bool:
+ """Omit only unbounded source content whose paint is known to be invisible."""
+ if _frame(element) is not None:
+ return False
+ preview = copy.deepcopy(element)
+ # Resolve local style precedence before propagating inherited paint on this
+ # disposable view. Source attributes and geometry remain unchanged.
+ for node in preview.iter():
+ node.attrib.update(_parse_style(node.get("style")))
+ node.attrib.pop("style", None)
+ if _hidden(preview) and _paint_value(preview, "visibility") not in {"hidden", "collapse"}:
+ return True
+ for parent in preview.iter():
+ for child in parent:
+ _merge_group_inheritance(parent, child)
+ parents = {id(child): parent for parent in preview.iter() for child in parent}
+ for leaf in preview.iter():
+ if _local_name(leaf.tag) in _NON_VISUAL_TAGS | {"g", "svg", "a"}:
+ continue
+ if svg_hidden_reason(leaf, parents):
+ continue
+ ancestor = parents.get(id(leaf))
+ while ancestor is not None and _local_name(ancestor.tag) not in _NON_VISUAL_TAGS:
+ ancestor = parents.get(id(ancestor))
+ if ancestor is not None:
+ continue
+ # Dimensions do not prove a source image or stroked shape is empty.
+ # Keep uncertain content for the existing geometry validation.
+ if _visible_leaf(leaf, check_dimensions=False):
+ return False
+ return True
+
+
def _source_bounds(
element: ET.Element,
stroke_width: float = 1.0,
@@ -1713,6 +1759,7 @@ def _root_group_bounds(
element: ET.Element,
canvas_width: float,
canvas_height: float,
+ ctx: ConvertContext | None = None,
) -> tuple[float, float, float, float] | None:
bounds = _frame(element)
if bounds is not None:
@@ -1720,7 +1767,7 @@ def _root_group_bounds(
if (
element.get("data-pptx-object") not in {"connector", "group"}
and element.get("data-pptx-prst") not in CONNECTOR_PRESET_TYPES
- and not is_stroked_zero_axis_shape(element)
+ and not is_stroked_zero_axis_shape(element, ctx)
):
return None
bounds = _source_bounds(element)
@@ -1893,7 +1940,10 @@ def _slot_plans(
raw.get("shapeId"),
context=f"layout {layout.get('key')} placeholder shapeId",
)
- bounds = _frame(_element_by_ref(layout_root, f"layout:{shape_id}"))
+ bounds = (
+ _frame(_element_by_ref(layout_root, f"layout:{shape_id}"))
+ or _native_geometry(raw)
+ )
if bounds is None:
for slide in source_slides:
matching = next(
@@ -1928,7 +1978,6 @@ def _slot_plans(
bounds = _frame(
_placeholder_guide_by_semantic(master_root, _semantic_role(raw))
)
- bounds = bounds or _native_geometry(raw)
if bounds is None:
raise MirrorMaterializationError(
f"Layout {layout.get('key')!r} placeholder {shape_id!r} has no "
@@ -1998,7 +2047,7 @@ def _copy_text_carrier(source: ET.Element | None) -> ET.Element | None:
if source_frame is not None:
carrier.set(
"data-pptx-frame",
- " ".join(format_coordinate(value) for value in source_frame),
+ _format_source_frame(source_frame),
)
carrier.set("data-pptx-carrier", "true")
return carrier
@@ -2253,6 +2302,9 @@ def _blank_text_carrier(
carrier = _copy_text_carrier(layout_guide)
if carrier is None:
carrier = _copy_text_carrier(master_guide)
+ if carrier is not None:
+ # The Master supplies typography here; the resolved slot owns its frame.
+ carrier.attrib.pop("data-pptx-frame", None)
if carrier is None:
x, y, _width, height = plan.bounds
carrier = ET.Element(
@@ -2268,24 +2320,24 @@ def _blank_text_carrier(
carrier.text = None
for child in list(carrier):
carrier.remove(child)
- if carrier.get("data-pptx-frame") is None:
+ if _frame(carrier) is None:
carrier.set(
"data-pptx-frame",
- " ".join(format_coordinate(value) for value in plan.bounds),
+ _format_source_frame(plan.bounds),
)
carrier.set("data-pptx-carrier", "true")
return carrier
def _blank_image_carrier(plan: SlotPlan) -> ET.Element:
- x, y, width, height = plan.bounds
+ x, y, width, height = _format_source_frame(plan.bounds).split()
return ET.Element(
f"{{{SVG_NS}}}image",
{
- "x": format_coordinate(x),
- "y": format_coordinate(y),
- "width": format_coordinate(width),
- "height": format_coordinate(height),
+ "x": x,
+ "y": y,
+ "width": width,
+ "height": height,
"href": TRANSPARENT_PIXEL_DATA_URI,
"preserveAspectRatio": "none",
"data-pptx-carrier": "true",
@@ -2297,6 +2349,15 @@ def _format_number(value: float) -> str:
return f"{value:.8f}".rstrip("0").rstrip(".") or "0"
+def _format_source_frame(values: tuple[float, float, float, float]) -> str:
+ """Keep a positive source extent when page-coordinate rounding would erase it."""
+ compacted = [format_coordinate(value) for value in values]
+ for axis in (2, 3):
+ if values[axis] > 0 and compacted[axis] == "0":
+ compacted[axis] = _format_number(values[axis])
+ return " ".join(compacted)
+
+
def _optional_float(value: str | None) -> float | None:
if value is None:
return None
@@ -2319,9 +2380,7 @@ def _slot_wrapper(
{
"id": plan.slot_id,
"data-pptx-placeholder": plan.semantic_role,
- "data-pptx-bounds": " ".join(
- format_coordinate(item) for item in plan.bounds
- ),
+ "data-pptx-bounds": _format_source_frame(plan.bounds),
},
)
if plan.idx is not None:
@@ -2493,6 +2552,7 @@ def _compose_template(
slide: dict[str, Any] | None,
slide_root: ET.Element | None,
slot_plans: list[SlotPlan],
+ warnings: list[str] | None = None,
) -> ET.Element:
width = float(native["slideSize"]["width_px"])
height = float(native["slideSize"]["height_px"])
@@ -2544,8 +2604,14 @@ def _compose_template(
root.append(defs)
for style in styles:
root.append(style)
+ geometry_context = ConvertContext(defs={
+ element.get("id"): element for element in root.iter() if element.get("id")
+ })
- master_atoms = _fixed_atoms(master_root, scope="master", key=str(master["key"]))
+ omission_warnings: list[str] = []
+ master_atoms = _fixed_atoms(
+ master_root, scope="master", key=str(master["key"]), warnings=omission_warnings,
+ )
layout_placeholder_refs = {
f"layout:{item['shapeId']}"
for item in layout.get("placeholders", [])
@@ -2556,6 +2622,7 @@ def _compose_template(
scope="layout",
key=str(layout["key"]),
placeholder_source_refs=layout_placeholder_refs,
+ warnings=omission_warnings,
)
master_backgrounds = [
atom for atom in master_atoms if _is_full_canvas_rect(atom, width, height)
@@ -2582,6 +2649,13 @@ def _compose_template(
continue
item = copy.deepcopy(child)
_merge_group_inheritance(slide_root, item)
+ if _invisible_degenerate_source(item):
+ element_id = item.get("id") or f"slide-{slide['index']}-node-{index + 1}"
+ omission_warnings.append(
+ f"element {element_id!r}: "
+ "omitted invisible content without a positive source frame"
+ )
+ continue
if _is_full_canvas_rect(item, width, height):
item.set("id", item.get("id") or f"slide-{slide['index']}-background")
item.set("data-pptx-layer", "slide")
@@ -2599,9 +2673,9 @@ def _compose_template(
if _local_name(item.tag) == "g" and (
_frame(item) is not None
or _visible_leaf(item)
- or is_stroked_zero_axis_shape(item)
+ or is_stroked_zero_axis_shape(item, geometry_context)
):
- bounds = _root_group_bounds(item, width, height)
+ bounds = _root_group_bounds(item, width, height, geometry_context)
if bounds is None:
raise MirrorMaterializationError(
f"Slide {slide['index']} root group "
@@ -2609,7 +2683,7 @@ def _compose_template(
)
item.set(
"data-pptx-bounds",
- " ".join(format_coordinate(value) for value in bounds),
+ _format_source_frame(bounds),
)
slide_content.append(item)
if len(slide_backgrounds) > 1:
@@ -2676,6 +2750,9 @@ def _compose_template(
_strip_source_refs(element)
root.append(element)
_strip_source_refs(root)
+ if warnings is not None:
+ context = f"Slide {slide['index']}" if slide else f"Layout {layout['key']}"
+ warnings.extend(f"{context}: {warning}" for warning in omission_warnings)
return root
@@ -3217,6 +3294,7 @@ def materialize_mirror_template(
)
materialized_roots: list[tuple[Path, ET.Element]] = []
+ warnings: list[str] = []
for slide in slides:
index = int(slide["index"])
layout = layouts[str(slide["layoutKey"])]
@@ -3231,6 +3309,7 @@ def materialize_mirror_template(
slide=slide,
slide_root=prepared_slides[index],
slot_plans=plans_by_layout[str(layout["key"])],
+ warnings=warnings,
)
materialized_roots.append((filename, root))
@@ -3440,6 +3519,7 @@ def materialize_mirror_template(
return {
"schema": "ppt-master.mirror-materialization-report.v2",
+ "warnings": warnings,
"import_workspace": str(import_workspace),
"template_workspace": str(template_workspace),
"source_slide_indexes": [int(item["index"]) for item in slides],
diff --git a/skills/ppt-master/scripts/template_import/manifest.py b/skills/ppt-master/scripts/template_import/manifest.py
index 071d049a..1f685c97 100644
--- a/skills/ppt-master/scripts/template_import/manifest.py
+++ b/skills/ppt-master/scripts/template_import/manifest.py
@@ -201,7 +201,7 @@ def resolve_first_rel(
return None
-def parse_xfrm_record(sp: ET.Element) -> dict[str, int] | None:
+def parse_xfrm_record(sp: ET.Element) -> dict[str, float] | None:
xfrm = sp.find("p:spPr/a:xfrm", NS)
if xfrm is None:
return None
@@ -217,10 +217,10 @@ def parse_xfrm_record(sp: ET.Element) -> dict[str, int] | None:
except ValueError:
return None
return {
- "x": emu_to_pixels(x),
- "y": emu_to_pixels(y),
- "width": emu_to_pixels(w),
- "height": emu_to_pixels(h),
+ "x": x / EMU_PER_INCH * 96,
+ "y": y / EMU_PER_INCH * 96,
+ "width": w / EMU_PER_INCH * 96,
+ "height": h / EMU_PER_INCH * 96,
}
diff --git a/skills/ppt-master/scripts/tests/test_template_degenerate_sweep.py b/skills/ppt-master/scripts/tests/test_template_degenerate_sweep.py
new file mode 100644
index 00000000..90f225b4
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_template_degenerate_sweep.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""Regressions for imported fixed geometry and placeholder source frames."""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+SCRIPTS = Path(__file__).resolve().parents[1]
+if str(SCRIPTS) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS))
+
+import mirror_template_materialize as mirror
+from compact_svg_coordinates import compact_svg_tree
+from pptx_gradients import native_gradient_metadata
+from svg_quality.checker import SVGQualityChecker
+from svg_to_pptx.drawingml.converter import SvgNativeConversionError, convert_svg_to_slide_shapes
+from template_import.manifest import extract_placeholders
+
+SVG = "http://www.w3.org/2000/svg"
+A = "http://schemas.openxmlformats.org/drawingml/2006/main"
+P = "http://schemas.openxmlformats.org/presentationml/2006/main"
+NS = {"a": A, "p": P}
+
+
+def _document(body: str = "") -> ET.Element:
+ return ET.fromstring(f'<svg xmlns="{SVG}" viewBox="0 0 960 720">{body}</svg>')
+
+
+def _compose(
+ content: str, scope: str = "slide", plans: list | None = None,
+ warnings: list[str] | None = None,
+) -> ET.Element:
+ empty = _document()
+ master = {"key": "m", "name": "Master", "placeholders": []}
+ layout = {"key": "l", "name": "Layout", "showMasterShapes": True, "placeholders": []}
+ return mirror._compose_template(
+ native={"slideSize": {"width_px": 960, "height_px": 720}},
+ master=master, layout=layout,
+ master_root=_document(content) if scope == "master" else empty,
+ layout_root=_document(content) if scope == "layout" else empty,
+ slide={"index": 1, "showInheritedShapes": True},
+ slide_root=_document(content) if scope == "slide" else empty,
+ slot_plans=plans or [],
+ warnings=warnings,
+ )
+
+
+def _source_placeholder(width_emu: int) -> dict:
+ source = ET.fromstring(
+ f'<p:sldLayout xmlns:p="{P}" xmlns:a="{A}"><p:cSld><p:spTree><p:sp>'
+ '<p:nvSpPr><p:cNvPr id="2" name="Body"/><p:cNvSpPr/><p:nvPr>'
+ '<p:ph type="body" idx="42"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm>'
+ f'<a:off x="1143000" y="1714500"/><a:ext cx="{width_emu}" cy="952500"/>'
+ '</a:xfrm></p:spPr></p:sp></p:spTree></p:cSld></p:sldLayout>'
+ )
+ return extract_placeholders(source)[0]
+
+
+class TemplateDegenerateSweepTests(unittest.TestCase):
+ def setUp(self) -> None:
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+
+ def _export(self, root: ET.Element) -> ET.Element:
+ path = self.root / "source.svg"
+ ET.ElementTree(root).write(path, encoding="utf-8")
+ xml, *_ = convert_svg_to_slide_shapes(path, resource_root=self.root)
+ return ET.fromstring(xml)
+
+ def test_fixed_custom_shapes_keep_kind_payload_and_zero_extent(self) -> None:
+ for scope in ("master", "layout"):
+ for width, height in ((300, 0), (0, 100)):
+ for count in (1, 2):
+ with self.subTest(scope=scope, frame=(width, height), paths=count):
+ custom = ET.fromstring(
+ f'<a:custGeom xmlns:a="{A}"><a:avLst/><a:gdLst/><a:ahLst/>'
+ '<a:cxnLst/><a:rect l="l" t="t" r="r" b="b"/><a:pathLst>'
+ + '<a:path w="300" h="100" fill="none"><a:moveTo><a:pt x="0" y="0"/>'
+ '</a:moveTo><a:lnTo><a:pt x="300" y="100"/></a:lnTo></a:path>' * count
+ + '</a:pathLst></a:custGeom>'
+ )
+ payload = base64.b64encode(ET.tostring(custom)).decode("ascii")
+ path = f"M 120 180 L {120 + width} {180 + height}"
+ digest = hashlib.sha256(path.encode()).hexdigest()
+ page = _compose(
+ '<g id="source" data-pptx-object="shape" data-pptx-geometry-kind="custom" '
+ f'data-pptx-frame="120 180 {width} {height}"><path d="{path}" '
+ f'data-pptx-custgeom="{payload}" data-pptx-geometry-sha256="{digest}" '
+ 'stroke="#3060C0" stroke-width="4" fill="none"/></g>', scope,
+ )
+ geometry = next(element for element in page if element.tag == f"{{{SVG}}}path")
+ self.assertEqual(geometry.get("data-pptx-geometry-kind"), "custom")
+ result = {"errors": []}
+ SVGQualityChecker(template_mode=True)._check_preset_geometry_metadata(page, result)
+ self.assertEqual(result["errors"], [])
+ exported = self._export(page)
+ self.assertEqual(
+ ET.tostring(exported.find(".//a:custGeom", NS)).strip(), ET.tostring(custom),
+ )
+ self.assertEqual(exported.find(".//p:sp/p:spPr/a:xfrm/a:ext", NS).attrib, {
+ "cx": str(width * 9525), "cy": str(height * 9525),
+ })
+
+ def test_fixed_custom_both_zero_stays_rejected(self) -> None:
+ page = _compose(
+ '<g id="source" data-pptx-object="shape" data-pptx-geometry-kind="custom" '
+ 'data-pptx-frame="120 180 0 0"><path d="M 120 180 L 120 180" '
+ 'stroke="#3060C0" fill="none"/></g>', "master",
+ )
+ with self.assertRaisesRegex(SvgNativeConversionError, "width and height must be positive"):
+ self._export(page)
+
+ def test_layout_native_frame_precedes_inherited_fallback(self) -> None:
+ placeholder = _source_placeholder(2857500)
+ master_placeholder = {"shapeId": "7", "type": "body", "idx": "42"}
+ plans = mirror._slot_plans(
+ {"key": "l", "placeholders": [placeholder]}, _document(), [], {},
+ {"placeholders": [master_placeholder]},
+ _document('<g data-pptx-source-ref="master:7" data-pptx-frame="48 168 864 475"/>'),
+ )
+ self.assertEqual(plans[0].bounds, (120, 180, 300, 100))
+ master_guide = ET.fromstring(
+ f'<g xmlns="{SVG}" data-pptx-frame="48 168 864 475">'
+ '<text x="58" y="195" font-size="24">Master sample</text></g>'
+ )
+ carrier = mirror._blank_text_carrier(plans[0], None, master_guide)
+ self.assertEqual(carrier.get("data-pptx-frame"), "120 180 300 100")
+ self.assertIsNone(carrier.text)
+
+ def test_single_emu_placeholder_keeps_positive_source_extent(self) -> None:
+ placeholder = _source_placeholder(1)
+ plans = mirror._slot_plans(
+ {"key": "l", "placeholders": [placeholder]}, _document(), [], {},
+ {"placeholders": []}, _document(),
+ )
+ self.assertEqual(round(plans[0].bounds[2] * 9525), 1)
+ wrapper, _extras = mirror._slot_wrapper(
+ plans[0], None, layout_guide=None, master_guide=None,
+ )
+ page = _document()
+ page.append(wrapper)
+ compact_svg_tree(page, compact_native_frames=False)
+ bounds = tuple(float(value) for value in wrapper.get("data-pptx-bounds").split())
+ self.assertEqual(round(bounds[2] * 9525), 1)
+ text = wrapper.find(f"{{{SVG}}}text")
+ self.assertEqual(round(float(text.get("data-pptx-frame").split()[2]) * 9525), 1)
+ result = {"errors": []}
+ SVGQualityChecker(template_mode=True)._check_preset_geometry_metadata(page, result)
+ self.assertEqual(result["errors"], [])
+ authored = _document('<g data-pptx-bounds="120 180 0.00010499 100"/>')
+ compact_svg_tree(authored)
+ self.assertEqual(authored[0].get("data-pptx-bounds"), "120 180 0 100")
+
+ def test_nonpositive_and_missing_placeholder_frames_still_fail(self) -> None:
+ for geometry in (
+ None,
+ {"x": 120, "y": 180, "width": 0, "height": 100},
+ {"x": 120, "y": 180, "width": 0, "height": 0},
+ {"x": 120, "y": 180, "width": -1, "height": 100},
+ ):
+ with self.subTest(geometry=geometry), self.assertRaisesRegex(
+ mirror.MirrorMaterializationError, "no positive deterministic bounds",
+ ):
+ mirror._slot_plans(
+ {"key": "l", "placeholders": [{"shapeId": "2", "geometry": geometry}]},
+ _document(), [], {}, {"placeholders": []}, _document(),
+ )
+
+ def test_nonempty_placeholder_recovers_from_slot_bounds(self) -> None:
+ plan = mirror.SlotPlan("slot", "body", "body", 42, "2", (120, 180, 300, 100))
+ for frame in ("120 180 300 0", "120 180 0 100", "120 180 0 0"):
+ with self.subTest(frame=frame):
+ source = ET.fromstring(
+ f'<g xmlns="{SVG}" data-pptx-frame="{frame}">'
+ '<text x="120" y="195" font-size="16">Visible source text</text></g>'
+ )
+ wrapper, _extras = mirror._slot_wrapper(
+ plan, source, layout_guide=None, master_guide=None,
+ )
+ self.assertIsNone(wrapper[0].get("data-pptx-frame"))
+ self.assertEqual(wrapper.get("data-pptx-bounds"), "120 180 300 100")
+ self.assertEqual("".join(wrapper[0].itertext()), "Visible source text")
+ page = _document()
+ page.append(wrapper)
+ result = {"errors": []}
+ SVGQualityChecker(template_mode=True)._check_preset_geometry_metadata(page, result)
+ self.assertEqual(result["errors"], [])
+ exported = self._export(page)
+ self.assertIn("Visible source text", [node.text for node in exported.findall(".//a:t", NS)])
+ blank = mirror._blank_text_carrier(plan, source, None)
+ self.assertEqual(blank.get("data-pptx-frame"), "120 180 300 100")
+ self.assertFalse("".join(blank.itertext()))
+
+ def test_gradient_source_bounds_use_resolved_document_definition(self) -> None:
+ for alpha in (0, 1):
+ with self.subTest(alpha=alpha):
+ gradient = ET.fromstring(
+ f'<linearGradient xmlns="{SVG}" id="stroke" gradientUnits="userSpaceOnUse" '
+ 'x1="120" y1="180" x2="420" y2="180">'
+ f'<stop offset="0" stop-color="#3060C0" stop-opacity="{alpha}"/>'
+ f'<stop offset="1" stop-color="#103050" stop-opacity="{alpha}"/></linearGradient>'
+ )
+ native = ET.fromstring(
+ f'<a:gradFill xmlns:a="{A}"><a:gsLst><a:gs pos="0"><a:srgbClr val="3060C0">'
+ f'<a:alpha val="{alpha * 100000}"/></a:srgbClr></a:gs><a:gs pos="100000">'
+ f'<a:srgbClr val="103050"><a:alpha val="{alpha * 100000}"/></a:srgbClr></a:gs>'
+ '</a:gsLst><a:lin ang="0" scaled="1"/></a:gradFill>'
+ )
+ gradient.attrib.update(native_gradient_metadata(native, gradient))
+ content = (
+ '<defs>' + ET.tostring(gradient, encoding="unicode") + '</defs>'
+ '<g id="source" data-pptx-object="shape" data-pptx-prst="rect" '
+ 'data-pptx-semantic-object="shape" data-pptx-frame="120 180 300 0">'
+ '<path data-pptx-part="geometry" d="M 120 180 L 420 180" '
+ 'stroke="url(#stroke)" stroke-width="4" fill="none"/></g>'
+ )
+ if alpha == 0:
+ with self.assertRaisesRegex(mirror.MirrorMaterializationError, "no positive source frame"):
+ _compose(content)
+ else:
+ page = _compose(content)
+ source = next(element for element in page if element.get("id") == "source")
+ self.assertEqual(source.get("data-pptx-bounds"), "120 178 300 4")
+ result = {"errors": []}
+ SVGQualityChecker(template_mode=True)._check_preset_geometry_metadata(page, result)
+ self.assertEqual(result["errors"], [])
+ exported = self._export(page)
+ self.assertEqual(exported.find(".//p:sp/p:spPr/a:xfrm/a:ext", NS).get("cy"), "0")
+
+ def test_authored_gradient_does_not_grant_source_zero_axis_exception(self) -> None:
+ with self.assertRaisesRegex(mirror.MirrorMaterializationError, "no positive source frame"):
+ _compose(
+ '<defs><linearGradient id="stroke"><stop offset="0" stop-color="#3060C0"/>'
+ '<stop offset="1" stop-color="#103050"/></linearGradient></defs>'
+ '<g id="source" data-pptx-object="shape" data-pptx-prst="rect" '
+ 'data-pptx-frame="120 180 300 0"><path d="M 120 180 L 420 180" '
+ 'stroke="url(#stroke)" stroke-width="4" fill="none"/></g>'
+ )
+
+ def test_invisible_degenerate_roots_are_omitted_with_context_in_all_layers(self) -> None:
+ for scope in ("slide", "master", "layout"):
+ for frame in ("", ' data-pptx-frame="120 180 640 0"', ' data-pptx-frame="120 180 0 0"'):
+ with self.subTest(scope=scope, frame=frame):
+ warnings = []
+ page = _compose(
+ f'<g id="invisible-rule" data-pptx-object="group"{frame}>'
+ '<g data-pptx-object="connector"><path d="M 120 180 L 420 180" '
+ 'fill="none" stroke="none"/></g></g>', scope, warnings=warnings,
+ )
+ self.assertFalse(any(element.get("id") == "invisible-rule" for element in page.iter()))
+ self.assertEqual(len(warnings), 1)
+ self.assertIn("Slide 1", warnings[0])
+ self.assertIn("invisible-rule", warnings[0])
+ self.assertIn("omitted invisible content", warnings[0])
+ if scope != "slide":
+ self.assertIn(scope.title(), warnings[0])
+ self.assertIsNone(self._export(page).find(".//p:sp", NS))
+
+ def test_invisible_positive_slide_frame_is_retained(self) -> None:
+ warnings = []
+ page = _compose(
+ '<g id="outline" data-pptx-frame="120 180 300 100">'
+ '<path d="M 120 180 L 420 180" fill="none" stroke="none"/></g>', warnings=warnings,
+ )
+ self.assertEqual(next(node for node in page if node.get("id") == "outline").get(
+ "data-pptx-bounds"), "120 180 300 100")
+ self.assertEqual(warnings, [])
+
+ def test_visible_unbounded_source_content_is_never_omitted(self) -> None:
+ for frame in ("", ' data-pptx-frame="120 180 0 0"'):
+ for content in (
+ '<path d="M 120 180 L 420 180" stroke="#123456" fill="none"/>',
+ '<text x="120" y="180">Visible text</text>',
+ '<image x="120" y="180" width="300" height="100" href="image.png"/>',
+ ):
+ with self.subTest(frame=frame, content=content):
+ warnings = []
+ with self.assertRaisesRegex(mirror.MirrorMaterializationError, "no positive source frame"):
+ _compose(f'<g id="visible"{frame}>{content}</g>', warnings=warnings)
+ self.assertEqual(warnings, [])
+
+ def test_omission_predicate_preserves_inherited_strokes_and_uncertain_images(self) -> None:
+ for content in (
+ '<g stroke="#123456"><path d="M 120 180 L 420 180" fill="none"/></g>',
+ '<g><rect x="120" y="180" width="300" height="0" fill="none" stroke="#123456"/></g>',
+ '<g><image x="120" y="180" width="0" height="0" href="image.png"/></g>',
+ '<g visibility="hidden"><text visibility="visible">Visible text</text></g>',
+ '<g fill="none"><path d="M 0 0 L 20 0 L 20 20 Z" style="fill:#ff0000"/></g>',
+ '<g style="visibility:hidden"><text visibility="visible">Visible text</text></g>',
+ '<g opacity="0" style="opacity:1"><text>Visible text</text></g>',
+ ):
+ with self.subTest(content=content):
+ self.assertFalse(mirror._invisible_degenerate_source(ET.fromstring(content)))
+ warnings = []
+ page = _compose(
+ '<g id="rule" data-pptx-object="connector" data-pptx-prst="straightConnector1" '
+ 'data-pptx-frame="120 180 300 0" stroke="#123456">'
+ '<path d="M 120 180 L 420 180" fill="none"/></g>', warnings=warnings,
+ )
+ self.assertEqual(next(node for node in page if node.get("id") == "rule").get(
+ "data-pptx-frame"), "120 180 300 0")
+ self.assertEqual(warnings, [])