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(scripts): reject out-of-range shape frames and incomplete patterns, and skip hidden SVG elements on export

hugohe38a45f10e43b5
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 8a6dafbf..dfa57080 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -104,6 +104,7 @@ try:
project_mask_errors as _project_mask_errors,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
split_project_text_clusters as _split_project_text_clusters,
+ svg_hidden_reason as _svg_hidden_reason,
transform_point as _transform_point,
unsafe_exported_font_faces as _unsafe_exported_font_faces,
validate_dml_shape_matrix as _validate_dml_shape_matrix,
@@ -124,6 +125,7 @@ except ImportError:
_project_mask_errors = None
_rect_to_dml_xfrm = None
_split_project_text_clusters = None
+ _svg_hidden_reason = None
_transform_point = None
_unsafe_exported_font_faces = None
_validate_dml_shape_matrix = None
@@ -140,14 +142,21 @@ except ImportError:
try:
from svg_to_pptx.drawingml.converter import (
SvgNativeConversionError as _SvgNativeConversionError,
+ collect_hidden_visuals as _collect_hidden_visuals,
collect_unsupported_visuals as _collect_unsupported_visuals,
preserved_native_text_body as _preserved_native_text_body,
)
except ImportError:
_SvgNativeConversionError = None
+ _collect_hidden_visuals = None
_collect_unsupported_visuals = None
_preserved_native_text_body = None
+try:
+ from svg_to_pptx.drawingml.styles import parse_pattern_colors as _parse_pattern_colors
+except ImportError:
+ _parse_pattern_colors = None
+
try:
from svg_to_pptx.drawingml.elements import (
drawingml_text_frame_width_emu as _drawingml_text_frame_width_emu,
@@ -1295,6 +1304,7 @@ class SVGQualityChecker:
# 2a. Validate direct geometry lengths and stroke widths.
svg_contracts.check_geometry_length_values(root, result)
+ self._check_shape_coordinate_ranges(root, result)
# 2b. Validate line-presentation grammar and mappings.
svg_contracts.check_stroke_style_values(root, result)
@@ -1351,6 +1361,7 @@ class SVGQualityChecker:
# 7b. Reject visual elements the native converter cannot dispatch.
self._check_unsupported_visual_elements(root, result)
+ self._check_hidden_elements(root, result)
# 7c. Fail closed on invalid PPTX preset/adjustment metadata.
self._check_preset_geometry_metadata(root, result)
@@ -3935,28 +3946,59 @@ class SVGQualityChecker:
parent_by_id: Dict[int, ET.Element],
) -> bool:
"""Return whether inherited display or visibility hides an element."""
- current: ET.Element | None = element
- while current is not None:
- style_values = (
- _parse_inline_style(current.get('style'))
- if _parse_inline_style is not None
- else {}
- )
- display = style_values.get('display')
- if display is None:
- display = current.get('display')
- if display and display.strip().lower() == 'none':
- return True
- current = parent_by_id.get(id(current))
- visibility = (
- _effective_presentation_value(
- element,
- 'visibility',
- parent_by_id,
+ return _svg_hidden_reason is not None and _svg_hidden_reason(element, parent_by_id) is not None
+
+ def _check_hidden_elements(self, root: ET.Element, result: Dict) -> None:
+ """Advise which hidden SVG objects will be omitted during native export."""
+ if _collect_hidden_visuals is None:
+ return
+ for element, reason in _collect_hidden_visuals(root):
+ result['warnings'].append(
+ f'Hidden element {_element_label(element)} will not be exported '
+ f'({reason}, including inherited state); advisory only'
)
- or ''
- ).strip().lower()
- return visibility in {'hidden', 'collapse'}
+
+ def _check_shape_coordinate_ranges(self, root: ET.Element, result: Dict) -> None:
+ """Check ordinary shape frames with the exporter's OOXML range validator."""
+ if _rect_to_dml_xfrm is None or _parse_project_geometry_length is None:
+ return
+ parents = {id(child): parent for parent in root.iter() for child in parent}
+
+ def visit(element: ET.Element) -> None:
+ tag = _local_name(element)
+ if tag in {'defs', 'metadata', 'title', 'desc', 'style'}:
+ return
+ if (
+ tag in {'rect', 'image', 'circle', 'ellipse'}
+ and element.get('data-pptx-frame') is None
+ and not self._is_hidden_element(element, parents)
+ ):
+ styles = _parse_inline_style(element.get('style')) if _parse_inline_style else {}
+
+ def length(name: str) -> float:
+ return _parse_project_geometry_length(styles.get(name, element.get(name, '0')), name)
+
+ try:
+ if tag in {'rect', 'image'}:
+ frame = (length('x'), length('y'), length('width'), length('height'))
+ else:
+ rx = length('r' if tag == 'circle' else 'rx')
+ ry = rx if tag == 'circle' else length('ry')
+ frame = (length('cx') - rx, length('cy') - ry, rx * 2, ry * 2)
+ matrix = self._accumulated_transform_matrix(element, parents)
+ if matrix is not None and frame[2] > 0 and frame[3] > 0:
+ _rect_to_dml_xfrm(*frame, matrix)
+ except ValueError as exc:
+ # Other geometry/transform grammar errors have their own checks.
+ if 'OOXML' in str(exc):
+ result['errors'].append(
+ f'{_element_label(element)}: {exc}; reduce the shape '
+ 'coordinates or dimensions before export'
+ )
+ for child in element:
+ visit(child)
+
+ visit(root)
@staticmethod
def _has_zero_opacity(
@@ -5410,6 +5452,11 @@ class SVGQualityChecker:
"horzBrick (others); see references/native-data-interface.md §1 "
"for the full authoring enum."
)
+ elif prst and _parse_pattern_colors is not None:
+ try:
+ _parse_pattern_colors(pattern)
+ except ValueError as exc:
+ result['errors'].append(str(exc))
def _check_native_object_markers(self, root: ET.Element, result: Dict) -> None:
"""Validate explicit native replacement markers before PPTX export."""
diff --git a/skills/ppt-master/scripts/svg_quality/svg_contracts.py b/skills/ppt-master/scripts/svg_quality/svg_contracts.py
index fd8c0ad4..ba6e829c 100644
--- a/skills/ppt-master/scripts/svg_quality/svg_contracts.py
+++ b/skills/ppt-master/scripts/svg_quality/svg_contracts.py
@@ -178,13 +178,13 @@ _CANONICAL_PAINT_ALPHA_PROPERTY = {
"flood-color": "flood-opacity",
}
_SUPPORTED_INLINE_STYLE_PROPERTIES = frozenset({
- "cx", "cy", "fill", "fill-opacity", "filter", "flood-color",
+ "cx", "cy", "display", "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",
+ "visibility", "width", "x", "y",
})
_BAKE_REQUIRED_VISUAL_PROPERTIES = frozenset({
"backdrop-filter",
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
index 1ccdb94f..c1534472 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
@@ -90,6 +90,8 @@ class ConvertContext:
# conversion entry points require it; recursive child contexts retain it.
resource_root: Path | None = None
inherited_styles: dict[str, str] = field(default_factory=dict)
+ # Shared ancestry for visibility overrides and native geometry carriers.
+ parent_by_id: dict[int, ET.Element] = field(default_factory=dict)
# Effective SVG font sizes keyed by element identity. Shared resolution
# keeps relative sizes and em tracking identical across checker/exporter.
text_font_sizes: dict[int, float] = field(default_factory=dict)
@@ -268,6 +270,7 @@ class ConvertContext:
svg_dir=self.svg_dir,
resource_root=self.resource_root,
inherited_styles=merged,
+ parent_by_id=self.parent_by_id,
text_font_sizes=self.text_font_sizes,
text_letter_spacings=self.text_letter_spacings,
opacity_multiplier=self.opacity_multiplier * local_opacity,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 3c9650e6..00d346ad 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -84,6 +84,7 @@ from .utils import (
project_stroke_style_errors,
project_transform_errors,
resolve_url_id,
+ svg_hidden_reason,
supports_full_project_transform,
validate_dml_shape_matrix,
)
@@ -1144,7 +1145,11 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
Uses identity coordinate mapping (chOff/chExt == off/ext) so child shapes
keep their absolute slide coordinates unchanged.
"""
- exact_graphic_frame = _roundtrip_graphic_frame(elem, ctx)
+ ctx.parent_by_id.update({id(child): elem for child in elem})
+ hidden_reason = svg_hidden_reason(elem, ctx.parent_by_id, preserve_native_carriers=True)
+ if hidden_reason == 'display:none':
+ return None
+ exact_graphic_frame = _roundtrip_graphic_frame(elem, ctx) if hidden_reason is None else None
if exact_graphic_frame is not None:
return exact_graphic_frame
@@ -1244,7 +1249,7 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"the subtree as ordinary SVG"
)
- if _native_replacement_enabled(elem, child_ctx):
+ if hidden_reason is None and _native_replacement_enabled(elem, child_ctx):
native_result = convert_native_object(elem, child_ctx)
if native_result:
ctx.sync_from_child(child_ctx)
@@ -1254,7 +1259,7 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
return native_result
- if elem.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND:
+ if hidden_reason is None and elem.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND:
geometry_ctx = child_ctx
if transform and not native_subtree_active:
geometry_ctx = ctx.child(
@@ -1277,12 +1282,13 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
return semantic_result
if (
- elem.get('data-pptx-object') in {'shape', 'connector'}
+ hidden_reason is None
+ and elem.get('data-pptx-object') in {'shape', 'connector'}
and elem.get('data-pptx-prst') is not None
):
_require_unchanged_preset_preview(elem)
- preserved_text = preserved_native_text_body(elem)
+ preserved_text = preserved_native_text_body(elem) if hidden_reason is None else None
if preserved_text is not None:
geometry_carrier, native_text = preserved_text
geometry_ctx = child_ctx
@@ -1573,6 +1579,9 @@ def _extract_background_candidate(
tag = child.tag.replace(f'{{{SVG_NS}}}', '')
if tag in _NON_VISUAL_TAGS:
continue
+ hidden_reason = svg_hidden_reason(child, ctx.parent_by_id, preserve_native_carriers=True)
+ if hidden_reason and (tag != 'g' or hidden_reason == 'display:none'):
+ continue
if tag == 'rect' and _is_full_canvas_rect(child, ctx, canvas):
bg_xml = _background_xml_from_rect(child, ctx)
@@ -1597,6 +1606,8 @@ def _extract_background_candidate(
if len(visual_children) != 1:
return '', None
only_child = visual_children[0]
+ if svg_hidden_reason(only_child, ctx.parent_by_id, preserve_native_carriers=True):
+ return '', None
only_tag = only_child.tag.replace(f'{{{SVG_NS}}}', '')
if only_tag == 'rect' and _is_full_canvas_rect(only_child, child_ctx, canvas):
bg_xml = _background_xml_from_rect(only_child, child_ctx)
@@ -1744,6 +1755,25 @@ def _geometry_trace_metadata(elem: ET.Element, result: ShapeResult) -> dict[str,
return {'output_geometry': 'unknown', 'fidelity': 'visual-only'}
+def collect_hidden_visuals(root: ET.Element) -> list[tuple[ET.Element, str]]:
+ """List suppressed visual objects while preserving native transport carriers."""
+ parents = {id(child): parent for parent in root.iter() for child in parent}
+ hidden: list[tuple[ET.Element, str]] = []
+
+ def visit(element: ET.Element) -> None:
+ tag = _local_tag(element)
+ if tag in _NON_VISUAL_TAGS:
+ return
+ reason = svg_hidden_reason(element, parents, preserve_native_carriers=True)
+ if reason and (tag not in {'g', 'a', 'svg'} or reason == 'display:none'):
+ hidden.append((element, reason))
+ for child in element:
+ visit(child)
+
+ visit(root)
+ return hidden
+
+
def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"""Dispatch an SVG element to the appropriate converter."""
tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
@@ -1798,6 +1828,11 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
trace('skip', reason='render-only-preset-geometry-detail')
return None
+ hidden_reason = svg_hidden_reason(elem, ctx.parent_by_id, preserve_native_carriers=True)
+ if hidden_reason and (tag not in {'g', 'a'} or hidden_reason == 'display:none'):
+ trace('skip', reason=hidden_reason)
+ return None
+
converter = _CONVERTERS.get(tag)
if converter:
try:
@@ -1807,7 +1842,8 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
result = apply_shape_hyperlink(result, ctx, shape_hyperlink)
except Exception as e:
trace('error', error=str(e))
- raise SvgNativeConversionError(f'Failed to convert <{tag}>: {e}') from e
+ label = f'<{tag} id="{elem_id}">' if elem_id else f'<{tag}>'
+ raise SvgNativeConversionError(f'Failed to convert {label}: {e}') from e
if result:
shape_match = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
metadata: dict[str, Any] = {}
@@ -2311,6 +2347,7 @@ def convert_svg_to_slide_shapes(
theme_color_spec=theme_color_spec,
primary_language=primary_language,
inherited_styles=_extract_inheritable_styles(root),
+ parent_by_id={id(child): parent for parent in root.iter() for child in parent},
text_font_sizes=text_font_sizes,
text_letter_spacings=text_letter_spacings,
)
@@ -2344,7 +2381,10 @@ def convert_svg_to_slide_shapes(
continue
if id(child) == background_skip_id:
continue
- result = convert_element(child, ctx)
+ try:
+ result = convert_element(child, ctx)
+ except SvgNativeConversionError as exc:
+ raise SvgNativeConversionError(f'{svg_path.name}: {exc}') from exc
if result:
shapes.append(result.xml)
converted += 1
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 b896ded9..2d4b6e17 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -765,6 +765,7 @@ def _shape_xfrm_from_svg_rect(
off_y = px_to_emu(resolved_y)
ext_cx = px_to_emu(resolved_w)
ext_cy = px_to_emu(resolved_h)
+ validate_ooxml_xfrm(off_x, off_y, ext_cx, ext_cy)
return '', off_x, off_y, ext_cx, ext_cy, (off_x, off_y, off_x + ext_cx, off_y + ext_cy)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
index 7d294053..adc833a2 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
@@ -196,20 +196,11 @@ def build_fill_xml(
return '<a:noFill/>'
-def build_pattern_fill(
+def parse_pattern_colors(
pattern_elem: ET.Element,
opacity: float | None = None,
- theme_color_spec: ThemeColorSpec | None = None,
- usage: str = "fill",
-) -> str:
- """Build <a:pattFill> from an SVG <pattern> emitted by pptx_to_svg.
-
- Reads the round-trip annotations (data-pptx-pattern / data-pptx-fg /
- data-pptx-bg) when present. Falls back to inspecting the inner stroke /
- rect colors when annotations are absent (hand-authored SVG).
- """
- prst = pattern_elem.get('data-pptx-pattern') or 'ltUpDiag'
-
+) -> tuple[str | None, str | None, float | None, float | None]:
+ """Resolve native pattern colors and alpha from metadata or child paints."""
paint_entries = []
for child in pattern_elem:
tag = child.tag.replace(f'{{{SVG_NS}}}', '')
@@ -262,7 +253,14 @@ def build_pattern_fill(
fg_hex, fg_alpha = parse_svg_color(fg_color) if fg_color else (None, 1.0)
bg_hex, bg_alpha = parse_svg_color(bg_color) if bg_color else (None, 1.0)
if not fg_hex:
- return ''
+ if pattern_elem.get('data-pptx-pattern') is not None:
+ pattern_id = pattern_elem.get('id') or '<unnamed>'
+ raise ValueError(
+ f'<pattern id="{pattern_id}"> is missing a valid foreground color; '
+ 'set data-pptx-fg or add a child stroke/fill after the first '
+ 'background rect fill'
+ )
+ return None, bg_hex, None, None
bg_source = next((
entry
@@ -298,6 +296,20 @@ def build_pattern_fill(
fg_opacity = combine_opacity(opacity, fg_alpha, fg_child_opacity)
bg_opacity = combine_opacity(opacity, bg_alpha, bg_child_opacity)
+ return fg_hex, bg_hex, fg_opacity, bg_opacity
+
+
+def build_pattern_fill(
+ pattern_elem: ET.Element,
+ opacity: float | None = None,
+ theme_color_spec: ThemeColorSpec | None = None,
+ usage: str = "fill",
+) -> str:
+ """Build native pattFill, retaining the unmarked-pattern compatibility fallback."""
+ prst = pattern_elem.get('data-pptx-pattern') or 'ltUpDiag'
+ fg_hex, bg_hex, fg_opacity, bg_opacity = parse_pattern_colors(pattern_elem, opacity)
+ if not fg_hex:
+ return ''
fg_alpha_xml = (
f'<a:alpha val="{quantize_ooxml_alpha(fg_opacity)}"/>'
if fg_opacity is not None else ''
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index da3532f2..284d1109 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -1470,6 +1470,36 @@ def parse_inline_style(style_str: str | None) -> dict[str, str]:
return styles
+def svg_hidden_reason(
+ element: ET.Element,
+ parent_by_id: dict[int, ET.Element],
+ *,
+ preserve_native_carriers: bool = False,
+) -> str | None:
+ """Resolve display suppression and inherited visibility, including overrides."""
+ visibility = None
+ current: ET.Element | None = element
+ while current is not None:
+ styles = parse_inline_style(current.get('style'))
+ display = styles.get('display', current.get('display', '')).strip().lower()
+ if display == 'none':
+ return 'display:none'
+ native_carrier = (
+ preserve_native_carriers
+ and current is element
+ and current.get('data-pptx-part') == 'geometry'
+ and current.get('data-pptx-object') in {'shape', 'connector'}
+ )
+ if visibility is None and not native_carrier:
+ value = styles.get('visibility', current.get('visibility', '')).strip().lower()
+ if value and value not in {'inherit', 'unset'}:
+ visibility = value
+ current = parent_by_id.get(id(current))
+ if visibility in {'hidden', 'collapse'}:
+ return f'visibility:{visibility}'
+ return None
+
+
def iter_project_geometry_lengths(
root: ET.Element,
) -> Iterator[tuple[ET.Element, str, str, str]]:
diff --git a/skills/ppt-master/scripts/tests/test_native_export_guards.py b/skills/ppt-master/scripts/tests/test_native_export_guards.py
new file mode 100644
index 00000000..b4536059
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_native_export_guards.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""Regression tests for coordinate, visibility, and pattern export guards."""
+
+from __future__ import annotations
+
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from pptx_shapes.formula import OOXML_COORDINATE_MAX # noqa: E402
+from svg_quality.checker import SVGQualityChecker # noqa: E402
+from svg_to_pptx.drawingml.converter import ( # noqa: E402
+ SvgNativeConversionError,
+ convert_svg_to_slide_shapes,
+)
+
+
+NS = {
+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',
+}
+
+
+class NativeExportGuardTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.svg_path = self.root / '01_fixture.svg'
+
+ def _svg(self, body: str, attributes: str = '') -> None:
+ self.svg_path.write_text(
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" '
+ f'data-pptx-page-role="content" {attributes}>{body}</svg>',
+ encoding='utf-8',
+ )
+
+ def _export(self) -> ET.Element:
+ xml, *_rest = convert_svg_to_slide_shapes(self.svg_path, resource_root=self.root)
+ return ET.fromstring(xml)
+
+ def _check(self) -> dict:
+ return SVGQualityChecker(quick_generate=True).check_file(str(self.svg_path))
+
+ @staticmethod
+ def _shape_colors(slide: ET.Element) -> list[str]:
+ return [
+ color.get('val')
+ for color in slide.findall('.//p:sp/p:spPr/a:solidFill/a:srgbClr', NS)
+ ]
+
+ def test_huge_coordinate_export_fails_with_page_and_element(self) -> None:
+ for transform in ('', 'transform="matrix(1 0 0 1 0 0)"'):
+ with self.subTest(transform=transform):
+ self._svg(
+ f'<rect id="huge" x="100000000000000000000000000000000000" y="100" width="200" height="100" '
+ f'fill="#FF0000" {transform}/>'
+ )
+ with self.assertRaises(SvgNativeConversionError) as caught:
+ self._export()
+ self.assertIn('01_fixture.svg', str(caught.exception))
+ self.assertIn('huge', str(caught.exception))
+ self.assertIn('OOXML coordinate range', str(caught.exception))
+
+ def test_checker_rejects_oversized_offsets_and_extents(self) -> None:
+ for attribute in ('x', 'y', 'width', 'height'):
+ with self.subTest(attribute=attribute):
+ values = dict(x='100', y='100', width='200', height='100')
+ values[attribute] = '100000000000000000000000000000000000'
+ geometry = ' '.join(f'{key}="{value}"' for key, value in values.items())
+ self._svg(f'<rect id="huge" {geometry} fill="#FF0000"/>')
+ errors = self._check()['errors']
+ self.assertTrue(any('huge' in error and 'OOXML' in error for error in errors), errors)
+ with self.assertRaises(SvgNativeConversionError):
+ self._export()
+
+ def test_coordinates_inside_ooxml_range_still_export(self) -> None:
+ for x in (-10, OOXML_COORDINATE_MAX // 9525):
+ with self.subTest(x=x):
+ self._svg(f'<rect id="valid" x="{x}" y="100" width="20" height="10" fill="#123456"/>')
+ self.assertFalse(self._check()['errors'])
+ self.assertEqual(self._shape_colors(self._export()), ['123456'])
+
+ def test_hidden_rect_is_omitted_for_attributes_and_style(self) -> None:
+ for hiding in ('visibility="hidden"', 'style="visibility:hidden"',
+ 'display="none"', 'style="display:none"'):
+ with self.subTest(hiding=hiding):
+ self._svg(
+ f'<rect id="hidden" x="100" y="100" width="200" height="100" fill="#FF0000" {hiding}/>'
+ '<rect id="shown" x="400" y="100" width="200" height="100" fill="#00FF00"/>'
+ )
+ self.assertEqual(self._shape_colors(self._export()), ['00FF00'])
+ report = self._check()
+ self.assertFalse(report['errors'])
+ self.assertTrue(any('hidden' in warning and 'not be exported' in warning
+ for warning in report['warnings']), report['warnings'])
+
+ def test_display_none_group_cannot_be_overridden_by_descendants(self) -> None:
+ for hiding in ('display="none"', 'style="display:none"'):
+ with self.subTest(hiding=hiding):
+ self._svg(
+ f'<g id="hidden-group" {hiding}>'
+ '<g display="inline" visibility="visible">'
+ '<rect id="child" x="100" y="100" width="200" height="100" fill="#FF0000"/>'
+ '</g></g>'
+ )
+ self.assertEqual(self._shape_colors(self._export()), [])
+ warnings = self._check()['warnings']
+ self.assertTrue(any('hidden-group' in warning and 'display:none' in warning
+ for warning in warnings), warnings)
+
+ def test_hidden_group_allows_explicitly_visible_descendant(self) -> None:
+ for hiding, showing in (
+ ('visibility="hidden"', 'visibility="visible"'),
+ ('style="visibility:hidden"', 'style="visibility:visible"'),
+ ):
+ with self.subTest(hiding=hiding):
+ self._svg(
+ f'<g id="hidden-group" {hiding}>'
+ '<rect id="hidden-child" x="100" y="100" width="200" height="100" fill="#FF0000"/>'
+ f'<g><rect id="shown" {showing} x="400" y="100" width="200" height="100" fill="#00FF00"/>'
+ '</g></g>'
+ )
+ self.assertEqual(self._shape_colors(self._export()), ['00FF00'])
+ warnings = self._check()['warnings']
+ self.assertTrue(any('hidden-child' in warning and 'visibility:hidden' in warning
+ for warning in warnings), warnings)
+ self.assertFalse(any('shown' in warning and 'not be exported' in warning for warning in warnings))
+
+ def test_style_visibility_overrides_presentation_attribute(self) -> None:
+ self._svg(
+ '<rect id="shown" x="100" y="100" width="200" height="100" fill="#123456" '
+ 'visibility="hidden" style="visibility:visible"/>'
+ )
+ self.assertEqual(self._shape_colors(self._export()), ['123456'])
+
+ def test_hidden_background_is_not_promoted(self) -> None:
+ for body, attributes in (
+ ('<rect width="1280" height="720" fill="#FF0000" visibility="hidden"/>', ''),
+ ('<g display="none"><rect width="1280" height="720" fill="#FF0000"/></g>', ''),
+ ('<rect width="1280" height="720" fill="#FF0000"/>', 'display="none"'),
+ ):
+ with self.subTest(body=body, attributes=attributes):
+ self._svg(body, attributes)
+ slide = self._export()
+ self.assertIsNone(slide.find('p:cSld/p:bg', NS))
+ self.assertEqual(self._shape_colors(slide), [])
+
+ def test_native_geometry_carrier_survives_but_ancestor_can_hide_it(self) -> None:
+ carrier = (
+ '<path id="carrier" d="M 100 100 L 300 100 L 300 200 L 100 200 Z" '
+ 'fill="#123456" data-pptx-prst="rect" data-pptx-frame="100 100 200 100" '
+ 'data-pptx-object="shape" data-pptx-shape-id="2" data-pptx-part="geometry" '
+ 'visibility="hidden" pointer-events="none"/>'
+ )
+ self._svg(carrier)
+ slide = self._export()
+ self.assertEqual(self._shape_colors(slide), ['123456'])
+ self.assertEqual(slide.find('.//p:sp/p:nvSpPr/p:cNvPr', NS).get('id'), '2')
+ self.assertFalse(any('carrier' in warning and 'not be exported' in warning
+ for warning in self._check()['warnings']))
+ self._svg(f'<g visibility="hidden">{carrier}</g>')
+ self.assertEqual(self._shape_colors(self._export()), [])
+
+ def _pattern(self, paints: str, attributes: str = 'data-pptx-pattern="smGrid"') -> None:
+ self._svg(
+ f'<defs><pattern id="pat" {attributes} patternUnits="userSpaceOnUse" '
+ f'width="10" height="10">{paints}</pattern></defs>'
+ '<rect id="pattern-shape" x="100" y="100" width="200" height="100" fill="url(#pat)"/>'
+ )
+
+ def test_pattern_missing_foreground_fails_checker_and_export(self) -> None:
+ self._pattern('<rect width="10" height="10" fill="#FF0000"/>')
+ errors = self._check()['errors']
+ self.assertTrue(any('pat' in error and 'foreground' in error and 'data-pptx-fg' in error
+ for error in errors), errors)
+ with self.assertRaisesRegex(SvgNativeConversionError, 'foreground'):
+ self._export()
+
+ def test_complete_pattern_exports_native_fill(self) -> None:
+ self._pattern(
+ '<rect width="10" height="10" fill="#FFFFFF"/>'
+ '<path d="M 0 0 L 10 10" stroke="#123456"/>'
+ )
+ self.assertFalse(self._check()['errors'])
+ pattern = self._export().find('.//a:pattFill', NS)
+ self.assertIsNotNone(pattern)
+ self.assertEqual(pattern.get('prst'), 'smGrid')
+ self.assertEqual(pattern.find('a:fgClr/a:srgbClr', NS).get('val'), '123456')
+ self.assertEqual(pattern.find('a:bgClr/a:srgbClr', NS).get('val'), 'FFFFFF')
+
+ def test_pattern_metadata_and_child_alpha_remain_supported(self) -> None:
+ self._pattern(
+ '<rect width="10" height="10" style="fill:#FFFFFF;fill-opacity:0.5"/>'
+ '<path d="M 0 0 L 10 10" style="stroke:#123456;stroke-opacity:0.25"/>',
+ 'data-pptx-pattern="smGrid" data-pptx-fg="#123456" data-pptx-bg="#FFFFFF"',
+ )
+ self.assertFalse(self._check()['errors'])
+ pattern = self._export().find('.//a:pattFill', NS)
+ self.assertEqual(pattern.find('a:fgClr/a:srgbClr/a:alpha', NS).get('val'), '25000')
+ self.assertEqual(pattern.find('a:bgClr/a:srgbClr/a:alpha', NS).get('val'), '50000')
+
+ def test_unmarked_pattern_keeps_missing_foreground_fallback(self) -> None:
+ self._pattern('<rect width="10" height="10" fill="#FF0000"/>', '')
+ self.assertFalse(self._check()['errors'])
+ slide = self._export()
+ self.assertIsNone(slide.find('.//a:pattFill', NS))
+ self.assertIsNotNone(slide.find('.//p:sp/p:spPr/a:noFill', NS))
+
+
+if __name__ == '__main__':
+ unittest.main()