Skip to content

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

fix(svg-to-pptx): reject non-positive text frame extents

hugohe34d6af12a59f8
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index d4cfbd36..bd4d88da 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -121,7 +121,7 @@ preset selection and authoring behavior are documented in
| Text outline | Registered stroke on text | DrawingML run outline | `Native-normalized` | Review when outline carries fine visual meaning |
| Text alignment | Registered `text-anchor` and paragraph semantics | Paragraph alignment plus normalized text-frame position | `Native-normalized` | Run-level anchoring and browser baseline heuristics are unsupported; exact placement belongs to [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
| Vertical text-frame alignment | No canonical generated-SVG control; generated text boxes use top anchoring | Top-anchored DrawingML text body | Imported vertical text may be normalized, but the main route does not expose a general authoring control | Do not infer vertical alignment from SVG baseline or browser layout behavior |
-| Character spacing | Registered `letter-spacing` | DrawingML character spacing | `Native-normalized` | Unsupported CSS typography and out-of-range DrawingML spacing are rejected under [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
+| Character spacing | Registered `letter-spacing` | DrawingML character spacing | `Native-normalized` | Unsupported CSS typography, out-of-range DrawingML spacing, and negative tracking that collapses a generated text frame to a non-positive extent are rejected under [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
| Bulleted paragraph | Recognized leading bullet form | Native DrawingML bullet | `Native-normalized` | Only the registered bullet grammar is promoted |
| Rotated text | Supported transform on the text object | Rotated text shape | `Native-normalized` | Skewed text and browser-only transforms are unsupported |
| Text shadow or glow | Supported filter/effect contract | One native outer shadow or glow | `Approximate` | One supported effect graph only; review material effects |
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index 337333f3..44ec1205 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -116,7 +116,7 @@ PowerPoint 意图
| 文本轮廓 | 文本上已登记 stroke | DrawingML run outline | `Native-normalized` | 轮廓承载精细视觉意义时需复核 |
| 文本对齐 | 已登记的 `text-anchor` 与段落语义 | 段落对齐加归一化文本框位置 | `Native-normalized` | 不支持 run 级锚定与浏览器 baseline 启发式;精确放置属于 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
| 文本框垂直对齐 | 无规范生成 SVG 控制;生成文本框使用顶部对齐 | 顶部对齐的 DrawingML text body | 导入的垂直文本可能被归一化,但主路线不公开通用创作控制 | 不得从 SVG baseline 或浏览器排版行为推断垂直对齐 |
-| 字符间距 | 已登记 `letter-spacing` | DrawingML 字符间距 | `Native-normalized` | 按 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) 拒绝不受支持的 CSS 排版与超出 DrawingML 范围的间距 |
+| 字符间距 | 已登记 `letter-spacing` | DrawingML 字符间距 | `Native-normalized` | 按 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) 拒绝不受支持的 CSS 排版、超出 DrawingML 范围的间距,以及导致生成文本框 extent 非正的负字距 |
| 项目符号段落 | 已识别的前导项目符号形式 | 原生 DrawingML bullet | `Native-normalized` | 仅提升已登记 bullet 语法 |
| 旋转文本 | 文本对象上受支持的 transform | 旋转文本 shape | `Native-normalized` | 倾斜文本与浏览器专属 transform 不受支持 |
| 文本阴影或发光 | 受支持 filter/effect 合同 | 一个原生外阴影或发光 | `Approximate` | 仅支持一个已登记效果图;实质效果需复核 |
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 7800da81..2100f89e 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -895,7 +895,7 @@ other value is invalid; the converter must not replace it with a default.
| `font-style` | `normal` or `italic` | None | `italic` maps to `i="1"`; oblique, angle, relative, and CSS-wide values are invalid |
| `text-anchor` | `start`, `middle`, or `end` on `<svg>`, `<g>`, or `<text>` | None | Maps to left/center/right paragraph alignment plus normalized frame position; it is invalid on `<tspan>` because run-level anchoring has no mapping |
| `text-decoration` | `none`, `underline`, `line-through`, or `underline line-through` | `line-through underline` → canonical order | Maps to the single underline and strike run properties; unknown, repeated, or substring-like tokens are invalid |
-| `letter-spacing` | Finite unitless ordinary decimal SVG px | The same ordinary decimal with `px`, `pt`, or `em`; normalize to unitless px | Maps to `a:rPr@spc`; the final value must fit DrawingML `-400000..400000`; keywords, percentages, exponents, leading plus signs, trailing decimal points, non-finite values, and other units are invalid |
+| `letter-spacing` | Finite unitless ordinary decimal SVG px | The same ordinary decimal with `px`, `pt`, or `em`; normalize to unitless px | Maps to `a:rPr@spc`; the final value must fit DrawingML `-400000..400000`, and negative tracking must still leave the generated DrawingML text frame with a positive extent; keywords, percentages, exponents, leading plus signs, trailing decimal points, non-finite values, and other units are invalid |
The registered text properties follow SVG inheritance, including declarations
on the root `<svg>`: inline `style` overrides the same element's direct
@@ -904,6 +904,15 @@ resolve against the same effective inherited size in Checker and converter.
Every declaration is validated even when a later declaration overrides it, so
hidden garbage cannot bypass preflight.
+The DrawingML character-spacing range is necessary but not sufficient for
+negative tracking. After run assembly, the generated text frame must retain a
+positive horizontal and vertical extent. Checker rejects directly measurable
+single-line violations, and the converter revalidates every generated text
+frame before writing OOXML. It must not clamp, take the absolute value of, or
+otherwise hide a non-positive extent. An unchanged imported native text body
+reuses the geometry carrier's positive shape frame and attaches the preserved
+`txBody` payload instead of regenerating a text frame from the SVG estimate.
+
**Hard rule — element-specific text surface**:
- Inheritable text declarations belong only on `<svg>`, `<g>`, `<text>`, or
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 835e3f03..f9bd476c 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -164,16 +164,24 @@ except ImportError:
try:
from svg_to_pptx.drawingml.converter import (
+ SvgNativeConversionError as _SvgNativeConversionError,
collect_unsupported_visuals as _collect_unsupported_visuals,
+ preserved_native_text_body as _preserved_native_text_body,
)
except ImportError:
+ _SvgNativeConversionError = None
_collect_unsupported_visuals = None
+ _preserved_native_text_body = None
try:
from svg_to_pptx.drawingml.elements import (
+ drawingml_text_frame_width_emu as _drawingml_text_frame_width_emu,
+ estimate_single_line_text_frame_width as _estimate_single_line_text_frame_width,
validate_preset_geometry_metadata as _validate_preset_geometry_metadata,
)
except ImportError:
+ _drawingml_text_frame_width_emu = None
+ _estimate_single_line_text_frame_width = None
_validate_preset_geometry_metadata = None
try:
@@ -2442,6 +2450,7 @@ class SVGQualityChecker:
result['info']['text_elements'] = text_count
result['info']['tspan_elements'] = tspan_count
+ self._check_text_frame_extents(root, result)
self._check_single_line_text_bounds(root, result)
self._check_unmergeable_leading_text(root, result)
@@ -2496,6 +2505,155 @@ class SVGQualityChecker:
runs[-1] = (owner, text.rstrip(' '))
return [(owner, text) for owner, text in runs if text]
+ @staticmethod
+ def _unchanged_txbody_group_ids(
+ root: ET.Element,
+ errors: List[str] | None = None,
+ ) -> set[int]:
+ """Return imported shape groups whose original text body will survive."""
+ if _preserved_native_text_body is None:
+ return set()
+ unchanged: set[int] = set()
+ for group in root.iter(f'{{{SVG_NS}}}g'):
+ try:
+ if _preserved_native_text_body(
+ group,
+ trust_runtime_snapshot=False,
+ ) is not None:
+ unchanged.add(id(group))
+ except _SvgNativeConversionError as exc:
+ if errors is not None:
+ errors.append(
+ f'{_element_label(group)} has invalid preserved '
+ f'txBody metadata: {exc}'
+ )
+ return unchanged
+
+ @staticmethod
+ def _has_ancestor_id(
+ elem: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ ancestor_ids: set[int],
+ ) -> bool:
+ current = parent_by_id.get(id(elem))
+ while current is not None:
+ if id(current) in ancestor_ids:
+ return True
+ current = parent_by_id.get(id(current))
+ return False
+
+ @classmethod
+ def _resolved_single_line_text_runs(
+ cls,
+ text_el: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ ) -> List[Dict] | None:
+ """Resolve the same run metrics used by generated text-frame sizing."""
+ source_runs = cls._single_line_text_runs(text_el)
+ if source_runs is None:
+ return None
+ resolved: List[Dict] = []
+ for owner, text in source_runs:
+ raw_weight = (
+ _effective_presentation_value(
+ owner,
+ 'font-weight',
+ parent_by_id,
+ )
+ or 'normal'
+ ).strip().lower()
+ weight = _parse_project_font_weight(raw_weight).canonical
+ family = (
+ _effective_presentation_value(
+ owner,
+ 'font-family',
+ parent_by_id,
+ )
+ or ''
+ )
+ resolved.append({
+ 'owner': owner,
+ 'text': text,
+ 'font_size': font_sizes[id(owner)],
+ 'font_weight': weight,
+ 'font_family': family,
+ 'letter_spacing': letter_spacings[id(owner)],
+ })
+ return resolved
+
+ def _check_text_frame_extents(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Reject measurable generated text that would emit a non-positive cx."""
+ helpers = (
+ _drawingml_text_frame_width_emu,
+ _estimate_single_line_text_frame_width,
+ _parse_project_font_weight,
+ _resolve_project_font_sizes,
+ _resolve_project_letter_spacings,
+ )
+ if any(helper is None for helper in helpers):
+ return
+ try:
+ font_sizes = _resolve_project_font_sizes(root)
+ letter_spacings = _resolve_project_letter_spacings(root, font_sizes)
+ except ValueError:
+ return
+
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ unchanged_groups = self._unchanged_txbody_group_ids(
+ root,
+ result['errors'],
+ )
+ errors: List[str] = []
+ for text_el in root.iter(f'{{{SVG_NS}}}text'):
+ chain: List[ET.Element] = []
+ current: ET.Element | None = text_el
+ while current is not None:
+ chain.append(current)
+ current = parent_by_id.get(id(current))
+ if any(
+ _local_name(current) in _NON_VISUAL_SVG_TAGS
+ for current in chain
+ ):
+ continue
+ if self._has_ancestor_id(text_el, parent_by_id, unchanged_groups):
+ continue
+ try:
+ runs = self._resolved_single_line_text_runs(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ if not runs:
+ continue
+ if not ''.join(str(run['text']) for run in runs).strip():
+ continue
+ text_width = _estimate_single_line_text_frame_width(runs)
+ ext_cx = _drawingml_text_frame_width_emu(
+ text_width,
+ font_sizes[id(text_el)],
+ )
+ except (KeyError, TypeError, ValueError):
+ continue
+ if ext_cx >= 1:
+ continue
+ errors.append(
+ f'{_element_label(text_el)} negative letter-spacing produces '
+ 'a non-positive DrawingML text-frame extent '
+ f'(cx={ext_cx})'
+ )
+ result['errors'].extend(errors)
+
def _check_single_line_text_bounds(
self,
root: ET.Element,
@@ -2503,6 +2661,8 @@ class SVGQualityChecker:
) -> None:
"""Warn only when an estimable single line exceeds the viewBox."""
helpers = (
+ _drawingml_text_frame_width_emu,
+ _estimate_single_line_text_frame_width,
_estimate_text_width,
_IDENTITY_MATRIX,
_matrix_multiply,
@@ -2533,6 +2693,7 @@ class SVGQualityChecker:
for parent in root.iter()
for child in list(parent)
}
+ unchanged_groups = self._unchanged_txbody_group_ids(root)
issues: List[str] = []
for text_el in root.iter(f'{{{SVG_NS}}}text'):
chain: List[ET.Element] = []
@@ -2547,36 +2708,41 @@ class SVGQualityChecker:
continue
if text_el.get('data-paragraph-line-height') is not None:
continue
+ if self._has_ancestor_id(text_el, parent_by_id, unchanged_groups):
+ continue
- runs = self._single_line_text_runs(text_el)
+ try:
+ runs = self._resolved_single_line_text_runs(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ except (KeyError, TypeError, ValueError):
+ continue
if not runs:
continue
- visible_text = ''.join(text for _owner, text in runs)
+ visible_text = ''.join(str(run['text']) for run in runs)
if '{{' in visible_text and '}}' in visible_text:
continue
try:
x = _parse_project_geometry_length(text_el.get('x') or '0', 'x')
y = _parse_project_geometry_length(text_el.get('y') or '0', 'y')
+ frame_width = _estimate_single_line_text_frame_width(runs)
+ if _drawingml_text_frame_width_emu(
+ frame_width,
+ font_sizes[id(text_el)],
+ ) < 1:
+ continue
text_advance = 0.0
text_left = math.inf
text_right = -math.inf
- for owner, text in runs:
- raw_weight = (
- _effective_presentation_value(
- owner,
- 'font-weight',
- parent_by_id,
- )
- or 'normal'
- ).strip().lower()
- weight = (
- 'bold'
- if _parse_project_font_weight(raw_weight).value
- else 'normal'
- )
- font_size = font_sizes[id(owner)]
- spacing = letter_spacings[id(owner)]
+ for run in runs:
+ text = str(run['text'])
+ weight = str(run['font_weight'])
+ font_size = float(run['font_size'])
+ spacing = float(run['letter_spacing'])
for index, character in enumerate(text):
character_width = _estimate_text_width(
character,
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 aefe19b9..5d917eb6 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -455,11 +455,16 @@ def _require_unchanged_preset_preview(group: ET.Element) -> None:
def _decode_unchanged_txbody(
group: ET.Element,
metadata: ET.Element,
+ *,
+ trust_runtime_snapshot: bool = True,
) -> str | None:
expected_hash = metadata.get('data-pptx-text-sha256')
if not expected_hash:
raise SvgNativeConversionError('txbody metadata requires a text hash')
- snapshot = group.get(_TXBODY_UNCHANGED_ATTR)
+ snapshot = (
+ group.get(_TXBODY_UNCHANGED_ATTR)
+ if trust_runtime_snapshot else None
+ )
if snapshot == '0':
return None
if snapshot != '1' and svg_text_fingerprint(group) != expected_hash:
@@ -501,6 +506,50 @@ def _append_shape_text(
)
+def preserved_native_text_body(
+ group: ET.Element,
+ *,
+ trust_runtime_snapshot: bool = True,
+) -> tuple[ET.Element, str] | None:
+ """Return the geometry carrier and unchanged native text body, if usable."""
+ metadata = _txbody_metadata(group)
+ logical_text_shape = (
+ group.get('data-pptx-object') == 'shape'
+ and (
+ group.get('data-pptx-prst') is not None
+ or group.get('data-pptx-geometry-kind') == 'custom'
+ )
+ and metadata is not None
+ )
+ if not logical_text_shape:
+ return None
+ native_text = _decode_unchanged_txbody(
+ group,
+ metadata,
+ trust_runtime_snapshot=trust_runtime_snapshot,
+ )
+ carrier_children = [
+ child for child in group
+ if child.get('data-pptx-part') == 'geometry'
+ ]
+ allowed_parts = {
+ 'geometry',
+ 'geometry-detail',
+ 'geometry-preview',
+ 'txbody',
+ }
+ has_foreign_visual = any(
+ child.tag.replace(f'{{{SVG_NS}}}', '') not in {'text', 'metadata'}
+ and child.get('data-pptx-part') not in allowed_parts
+ for child in group
+ )
+ if len(carrier_children) != 1 or has_foreign_visual:
+ return None
+ if native_text is None:
+ return None
+ return carrier_children[0], native_text
+
+
# ---------------------------------------------------------------------------
# Group handling
# ---------------------------------------------------------------------------
@@ -623,57 +672,33 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
):
_require_unchanged_preset_preview(elem)
- txbody_meta = _txbody_metadata(elem)
- logical_text_shape = (
- elem.get('data-pptx-object') == 'shape'
- and (
- elem.get('data-pptx-prst') is not None
- or elem.get('data-pptx-geometry-kind') == 'custom'
- )
- and txbody_meta is not None
- )
- if logical_text_shape:
- carrier_children = [
- child for child in elem
- if child.get('data-pptx-part') == 'geometry'
- ]
- allowed_parts = {
- 'geometry',
- 'geometry-detail',
- 'geometry-preview',
- 'txbody',
- }
- has_foreign_visual = any(
- child.tag.replace(f'{{{SVG_NS}}}', '') not in {'text', 'metadata'}
- and child.get('data-pptx-part') not in allowed_parts
- for child in elem
- )
- native_text = _decode_unchanged_txbody(elem, txbody_meta)
- if len(carrier_children) == 1 and not has_foreign_visual and native_text is not None:
- geometry_ctx = child_ctx
- if transform and not native_subtree_active:
- geometry_ctx = ctx.child(
- 0, 0, 1.0, 1.0,
- transform_matrix=parse_transform_matrix(transform),
- filter_id=filter_id,
- style_overrides=style_overrides,
- opacity_multiplier=local_opacity,
- )
- geometry_result = convert_element(carrier_children[0], geometry_ctx)
- ctx.sync_from_child(geometry_ctx)
- if geometry_result is None:
- raise SvgNativeConversionError(
- 'Logical text shape has no convertible geometry carrier'
- )
- restored = _append_shape_text(
- geometry_result,
- native_text,
+ preserved_text = preserved_native_text_body(elem)
+ if preserved_text is not None:
+ geometry_carrier, native_text = preserved_text
+ geometry_ctx = child_ctx
+ if transform and not native_subtree_active:
+ geometry_ctx = ctx.child(
+ 0, 0, 1.0, 1.0,
+ transform_matrix=parse_transform_matrix(transform),
+ filter_id=filter_id,
+ style_overrides=style_overrides,
+ opacity_multiplier=local_opacity,
)
- if should_animate_group and elem_id:
- shape_match = re.search(r'<p:cNvPr id="(\d+)"', restored.xml)
- if shape_match:
- ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
- return restored
+ geometry_result = convert_element(geometry_carrier, geometry_ctx)
+ ctx.sync_from_child(geometry_ctx)
+ if geometry_result is None:
+ raise SvgNativeConversionError(
+ 'Logical text shape has no convertible geometry carrier'
+ )
+ restored = _append_shape_text(
+ geometry_result,
+ native_text,
+ )
+ if should_animate_group and elem_id:
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', restored.xml)
+ if shape_match:
+ ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
+ return restored
child_results: list[ShapeResult] = []
for child in elem:
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 bbf108af..9471d156 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -1749,6 +1749,21 @@ def _estimate_text_runs_width(
return width * (base + (ceiling - base) * caps)
+def estimate_single_line_text_frame_width(
+ runs: list[dict[str, Any]],
+) -> float:
+ """Estimate the content width used by one generated DrawingML textbox."""
+ content_runs, bullet = _extract_text_bullet(runs)
+ width = _estimate_text_runs_width(content_runs)
+ if bullet:
+ font_size = (
+ float(content_runs[0].get('font_size', 16))
+ if content_runs else 16.0
+ )
+ width += _bullet_margin_px(bullet, font_size)
+ return width
+
+
def _first_nonspace_run(runs: list[dict[str, Any]]) -> dict[str, Any] | None:
for run in runs:
if str(run.get('text', '')).strip():
@@ -1902,6 +1917,14 @@ def _textbox_padding(font_size: float) -> float:
)
+def drawingml_text_frame_width_emu(
+ text_width: float,
+ font_size: float,
+) -> int:
+ """Return the exact horizontal extent used by a generated text frame."""
+ return px_to_emu(text_width + _textbox_padding(font_size) * 2)
+
+
def _text_opacity_ratio(value: str | None) -> float:
"""Parse a text opacity component and clamp it to the SVG ``0..1`` range."""
if value is None:
@@ -2498,8 +2521,14 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
off_x = px_to_emu(box_x)
off_y = px_to_emu(box_y)
- ext_cx = px_to_emu(box_w)
+ ext_cx = drawingml_text_frame_width_emu(text_width, font_size)
ext_cy = px_to_emu(box_h)
+ if ext_cx < 1 or ext_cy < 1:
+ raise ValueError(
+ 'negative letter-spacing produces a non-positive DrawingML '
+ f'text-frame extent (cx={ext_cx}, cy={ext_cy})'
+ )
+ validate_ooxml_xfrm(off_x, off_y, ext_cx, ext_cy)
# Paragraph mode: wrap="square" so text reflows when the user resizes,
# but NO spAutoFit — otherwise PowerPoint expands the frame to fit a
diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.py
index 55be080a..56e2b91c 100644
--- a/skills/ppt-master/scripts/test_svg_quality_checker.py
+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3
"""Regression tests for SVG checker compatibility severity."""
+import base64
import io
import json
import math
+import re
import sys
import tempfile
import unittest
@@ -16,7 +18,11 @@ if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from svg_quality_checker import SVGQualityChecker
-from pptx_shapes import CONNECTOR_PRESET_TYPES, get_preset_registry
+from pptx_shapes import (
+ CONNECTOR_PRESET_TYPES,
+ get_preset_registry,
+ svg_text_fingerprint,
+)
from pptx_to_svg.preset_authoring import (
materialize_compact_authored_preset_tree,
render_preset_shape_fragment,
@@ -70,6 +76,18 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
if 'estimated horizontal bounds exceed the viewBox' in warning
]
+ @staticmethod
+ def _native_txbody_payload() -> str:
+ native_txbody = (
+ '<p:txBody '
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" '
+ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'
+ '<a:bodyPr/><a:lstStyle/><a:p><a:r>'
+ '<a:rPr lang="en-US" sz="1500" spc="-7500"/>'
+ '<a:t>AB</a:t></a:r></a:p></p:txBody>'
+ )
+ return base64.b64encode(native_txbody.encode('utf-8')).decode('ascii')
+
def _assert_checker_and_exporter_reject(
self,
content: str,
@@ -1475,14 +1493,236 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
result = self._check(
'''<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 200 100">
- <text x="50" y="25" font-size="20" letter-spacing="-100">AB</text>
- <text x="300" y="50" font-size="20" letter-spacing="-100">AB</text>
+ <text x="5" y="25" font-size="20" letter-spacing="-20">AB</text>
+ <text x="195" y="50" font-size="20" letter-spacing="-20">AB</text>
</svg>'''
)
bounds_warnings = self._text_bound_warnings(result)
self.assertEqual(len(bounds_warnings), 1)
self.assertIn('Detected 2 single-line text element(s)', bounds_warnings[0])
+ def test_non_positive_text_frame_extents_block_checker_and_exporter(self):
+ for anchor in ('start', 'middle', 'end'):
+ source = (
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="320" y="100" font-size="20" '
+ f'text-anchor="{anchor}" letter-spacing="-30">AB</text>'
+ '</svg>'
+ )
+ with self.subTest(anchor=anchor):
+ self._assert_checker_and_exporter_reject(
+ source,
+ 'non-positive DrawingML text-frame extent',
+ 'non-positive DrawingML text-frame extent',
+ )
+
+ def test_zero_emu_text_frame_extent_is_rejected(self):
+ self._assert_checker_and_exporter_reject(
+ '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360">
+ <text x="40" y="100" font-size="20"
+ letter-spacing="-23.4285714285714">AB</text>
+</svg>''',
+ 'non-positive DrawingML text-frame extent (cx=0)',
+ r'non-positive DrawingML text-frame extent \(cx=0',
+ )
+
+ def test_representable_negative_tracking_keeps_positive_text_frames(self):
+ source = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360">
+ <text x="40" y="100" font-size="20" letter-spacing="-20">AB</text>
+ <text x="40" y="160" font-size="20" letter-spacing="-100">A</text>
+</svg>'''
+ result = self._check(source)
+ self.assertTrue(result['passed'])
+ self.assertEqual(result['errors'], [])
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'negative-tracking.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertIn(' spc="-1500"', slide_xml)
+ self.assertIn(' spc="-7500"', slide_xml)
+ extents = [
+ int(value)
+ for value in re.findall(r'<a:ext cx="(-?\d+)" cy="\d+"', slide_xml)
+ if int(value) != 0
+ ]
+ self.assertEqual(len(extents), 2)
+ self.assertTrue(all(value >= 1 for value in extents))
+
+ def test_inherited_inline_tracking_cannot_hide_collapsed_text_frame(self):
+ self._assert_checker_and_exporter_reject(
+ '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360" font-size="20">
+ <g letter-spacing="-30">
+ <text x="40" y="100">A<tspan style="letter-spacing:-100">BC</tspan></text>
+ </g>
+</svg>''',
+ 'non-positive DrawingML text-frame extent',
+ 'non-positive DrawingML text-frame extent',
+ )
+
+ def test_positioned_paragraph_tracking_is_still_blocked_by_exporter(self):
+ source = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360" font-size="20" letter-spacing="-30">
+ <text x="40" y="80">
+ <tspan x="40" y="80">AB</tspan>
+ <tspan x="40" dy="24">AB</tspan>
+ </text>
+</svg>'''
+ result = self._check(source)
+ self.assertTrue(result['passed'])
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'paragraph-negative-tracking.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ with self.assertRaisesRegex(
+ SvgNativeConversionError,
+ 'non-positive DrawingML text-frame extent',
+ ):
+ convert_svg_to_slide_shapes(svg_path)
+
+ def test_bullet_text_uses_the_same_positive_frame_boundary(self):
+ safe = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360">
+ <text x="40" y="100" font-size="20" letter-spacing="-20">• AB</text>
+</svg>'''
+ safe_result = self._check(safe)
+ self.assertTrue(safe_result['passed'])
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'safe-bullet.svg'
+ svg_path.write_text(safe, encoding='utf-8')
+ safe_xml = convert_svg_to_slide_shapes(svg_path)[0]
+ self.assertIn('<a:buChar char="•"/>', safe_xml)
+ self.assertIn(' spc="-1500"', safe_xml)
+
+ self._assert_checker_and_exporter_reject(
+ safe.replace('letter-spacing="-20"', 'letter-spacing="-100"'),
+ 'non-positive DrawingML text-frame extent',
+ 'non-positive DrawingML text-frame extent',
+ )
+
+ def test_whitespace_only_text_does_not_create_a_false_frame_error(self):
+ source = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360">
+ <text x="40" y="100" font-size="20" letter-spacing="-100"
+ xml:space="preserve"> </text>
+</svg>'''
+ result = self._check(source)
+ self.assertTrue(result['passed'])
+ self.assertEqual(result['errors'], [])
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'whitespace-only.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertNotIn('<p:txBody>', slide_xml)
+
+ def test_unchanged_imported_txbody_bypasses_generated_frame_check(self):
+ root = ET.fromstring(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360">
+ <g id="imported-shape" data-pptx-object="shape" data-pptx-prst="rect">
+ <rect data-pptx-part="geometry" x="20" y="40" width="160" height="80"
+ fill="#FFFFFF"/>
+ <text x="40" y="100" font-size="20" letter-spacing="-100">AB</text>
+ </g>
+</svg>'''
+ )
+ group = next(root.iter('{http://www.w3.org/2000/svg}g'))
+ digest = svg_text_fingerprint(group)
+ metadata = ET.SubElement(
+ group,
+ '{http://www.w3.org/2000/svg}metadata',
+ {
+ 'data-pptx-part': 'txbody',
+ 'data-pptx-encoding': 'base64',
+ 'data-pptx-text-sha256': digest,
+ },
+ )
+ metadata.text = self._native_txbody_payload()
+ result = {'errors': [], 'warnings': []}
+
+ SVGQualityChecker()._check_text_frame_extents(root, result)
+
+ self.assertEqual(result['errors'], [])
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'imported-txbody.svg'
+ svg_path.write_text(
+ ET.tostring(root, encoding='unicode'),
+ encoding='utf-8',
+ )
+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertEqual(slide_xml.count('<p:txBody'), 1)
+ self.assertIn(' spc="-7500"', slide_xml)
+ self.assertNotIn('cx="-816864"', slide_xml)
+
+ def test_invalid_unchanged_txbody_payload_does_not_bypass_checker(self):
+ root = ET.fromstring(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360">
+ <g id="imported-shape" data-pptx-object="shape" data-pptx-prst="rect">
+ <text x="40" y="100" font-size="20" letter-spacing="-100">AB</text>
+ </g>
+</svg>'''
+ )
+ group = next(root.iter('{http://www.w3.org/2000/svg}g'))
+ digest = svg_text_fingerprint(group)
+ metadata = ET.SubElement(
+ group,
+ '{http://www.w3.org/2000/svg}metadata',
+ {
+ 'data-pptx-part': 'txbody',
+ 'data-pptx-encoding': 'base64',
+ 'data-pptx-text-sha256': digest,
+ },
+ )
+ metadata.text = 'not-base64'
+ result = {'errors': [], 'warnings': []}
+
+ SVGQualityChecker()._check_text_frame_extents(root, result)
+
+ self.assertIn('invalid preserved txBody metadata', '\n'.join(result['errors']))
+
+ def test_checker_does_not_trust_authored_runtime_txbody_snapshot(self):
+ root = ET.fromstring(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360">
+ <g id="imported-shape" data-pptx-object="shape" data-pptx-prst="rect"
+ data-pptx-runtime-txbody-unchanged="1">
+ <rect data-pptx-part="geometry" x="20" y="40" width="160" height="80"
+ fill="#FFFFFF"/>
+ <text x="40" y="100" font-size="20" letter-spacing="-100">AB</text>
+ <metadata data-pptx-part="txbody" data-pptx-encoding="base64"
+ data-pptx-text-sha256="0000000000000000000000000000000000000000000000000000000000000000"/>
+ </g>
+</svg>'''
+ )
+ metadata = next(root.iter('{http://www.w3.org/2000/svg}metadata'))
+ metadata.text = self._native_txbody_payload()
+ result = {'errors': [], 'warnings': []}
+
+ SVGQualityChecker()._check_text_frame_extents(root, result)
+
+ self.assertIn(
+ 'non-positive DrawingML text-frame extent',
+ '\n'.join(result['errors']),
+ )
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'forged-runtime-snapshot.svg'
+ svg_path.write_text(
+ ET.tostring(root, encoding='unicode'),
+ encoding='utf-8',
+ )
+ with self.assertRaisesRegex(
+ SvgNativeConversionError,
+ 'non-positive DrawingML text-frame extent',
+ ):
+ convert_svg_to_slide_shapes(svg_path)
+
def test_text_property_contract_preserves_registered_drawingml_semantics(self):
source = '''<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 640 360" font-style="italic">