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): close text property contracts

hugohe3641a60163cf2
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index 64d156ee..d4cfbd36 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -115,12 +115,13 @@ preset selection and authoring behavior are documented in
| Multiple paragraphs | Mergeable text/tspan structure | Multiple `a:p` paragraphs in one text frame | `Native-normalized` | Strict independently positioned lines may remain separate text boxes |
| Font family | Canonical `font-family` resolved against the project lock | Direct typeface or registered theme font | `Native-stable` within installed/font-substitution limits | Unlocked or unavailable fonts are reported by validation |
| Font size | Finite unitless SVG pixels, for example `font-size="24"` | DrawingML hundredths of a point; `1 px = 0.75 pt` | `Native-stable` after unit conversion | Generated authoring uses only unitless px; registered legacy units are compatible input and warn, while unknown units error; DrawingML minimum is 1 pt |
-| Bold, italic, underline, and strike | Registered text attributes on `<text>`/`<tspan>` | DrawingML run properties | `Native-stable` | Only documented values are accepted |
+| Font weight | Registered `font-weight` on `<text>`/`<tspan>` | DrawingML regular/bold run switch | `Native-normalized`; numeric weights collapse to the DrawingML boolean boundary | The exact value grammar and aliases belong to [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
+| Italic, underline, and strike | Registered `font-style` / `text-decoration` on `<text>`/`<tspan>` | DrawingML italic, underline, and strike run properties | `Native-stable` for registered tokens | Unknown tokens are rejected; the exact grammar belongs to [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
| Text fill and transparency | Canonical fill plus run alpha | DrawingML run fill and alpha | `Native-normalized` | Use the semantic alpha channel, not an unregistered CSS effect |
| Text outline | Registered stroke on text | DrawingML run outline | `Native-normalized` | Review when outline carries fine visual meaning |
-| Text alignment | `text-anchor` and registered paragraph semantics | Paragraph alignment plus normalized text-frame position | `Native-normalized` | Browser layout heuristics are not part of the contract |
+| 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 is rejected |
+| 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) |
| 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 49887b7b..337333f3 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -110,12 +110,13 @@ PowerPoint 意图
| 多段落 | 可合并的 text/tspan 结构 | 同一文本框内的多个 `a:p` 段落 | `Native-normalized` | 严格独立定位的行可保持为独立文本框 |
| 字体 | 根据项目 lock 解析的规范 `font-family` | 直接 typeface 或已登记 theme font | 在安装字体/替换边界内为 `Native-stable` | 校验会报告未锁定或不可用字体 |
| 字号 | 有限、无单位的 SVG px,例如 `font-size="24"` | DrawingML 百分之一磅;`1 px = 0.75 pt` | 单位转换后为 `Native-stable` | 生成创作只使用无单位 px;已登记历史单位是会产生 warning 的兼容输入,未知单位为 error;DrawingML 下限为 1 pt |
-| 粗体、斜体、下划线与删除线 | `<text>`/`<tspan>` 上的已登记文本属性 | DrawingML run 属性 | `Native-stable` | 仅接受文档化取值 |
+| 字重 | `<text>`/`<tspan>` 上已登记的 `font-weight` | DrawingML 常规/粗体 run 开关 | `Native-normalized`;数值字重会折叠到 DrawingML 布尔边界 | 精确取值语法与别名属于 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
+| 斜体、下划线与删除线 | `<text>`/`<tspan>` 上已登记的 `font-style` / `text-decoration` | DrawingML 斜体、下划线与删除线 run 属性 | 已登记 token 为 `Native-stable` | 拒绝未知 token;精确语法属于 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |
| 文本填充与透明度 | 规范 fill 加 run alpha | DrawingML run fill 与 alpha | `Native-normalized` | 使用语义 alpha 通道,不使用未登记 CSS 效果 |
| 文本轮廓 | 文本上已登记 stroke | DrawingML run outline | `Native-normalized` | 轮廓承载精细视觉意义时需复核 |
-| 文本对齐 | `text-anchor` 与已登记段落语义 | 段落对齐加归一化文本框位置 | `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` | 拒绝不受支持的 CSS 排版 |
+| 字符间距 | 已登记 `letter-spacing` | DrawingML 字符间距 | `Native-normalized` | 按 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) 拒绝不受支持的 CSS 排版与超出 DrawingML 范围的间距 |
| 项目符号段落 | 已识别的前导项目符号形式 | 原生 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 4d3696b3..7f699993 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -132,6 +132,11 @@ write `filter="url(#id)"`, `clip-path="url(#id)"`, and
`marker-start` / `marker-end` as direct attributes. `!important`, unknown CSS
properties, blend modes, isolation, and backdrop filters fail quality check.
+The table registers property names, not arbitrary CSS values. Text property
+values and their element-specific placement are a closed grammar owned by
+§6.7; unknown or unmapped declarations on `<text>` / `<tspan>`, and unsupported
+inherited text properties, fail both Checker preflight and native export.
+
> **`marker-start` / `marker-end` is conditional** — see §1.1.
>
> **`clipPath` on `<image>` is conditional** — see §1.2.
@@ -879,12 +884,58 @@ matters, use one multi-subpath path rather than a fixed-density preset pattern:
### 6.7 Advanced Text Treatments
+**Hard rule — closed text property grammar**: generated text uses only the
+values in the `Canonical authoring` column. Registered compatible input remains
+convertible and receives a non-blocking normalization recommendation. Every
+other value is invalid; the converter must not replace it with a default.
+
+| Property | Canonical authoring | Compatible input | DrawingML mapping / rejection boundary |
+|---|---|---|---|
+| `font-weight` | `normal`, `bold`, or an exact integer hundred from `100` through `900` | `medium` → `500`; `semibold` → `600` | `normal` and `100..500` map to regular; `bold` and `600..900` map to `b="1"`; therefore numeric weights are `Native-normalized` |
+| `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 |
+
+The registered text properties follow SVG inheritance, including declarations
+on the root `<svg>`: inline `style` overrides the same element's direct
+attribute, which overrides its ancestor. Relative font sizes and `em` tracking
+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.
+
+**Hard rule — element-specific text surface**:
+
+- Inheritable text declarations belong only on `<svg>`, `<g>`, `<text>`, or
+ `<tspan>`; placing them on geometry, image, definition, or reuse elements is
+ an error rather than ignored decoration.
+- `<text>` accepts `x`, `y`, registered paint/alpha/run properties, the text
+ properties above, `font-family`, `font-size`, direct `filter`, direct
+ `transform`, `xml:space`, `id`, and project `data-*` metadata.
+- `<tspan>` accepts `x`, `y`, `dx`, `dy`, registered paint/alpha/run
+ properties, `font-family`, `font-size`, `font-weight`, `font-style`,
+ `letter-spacing`, `text-decoration`, `xml:space`, `id`, and project `data-*`
+ metadata. It does not accept `text-anchor`, `filter`, or `transform`.
+- `word-spacing`, `dominant-baseline`, `alignment-baseline`, `baseline-shift`,
+ font shorthand/variant/stretch/feature/variation/synthesis controls,
+ `font-kerning`/`kerning`, `font-size-adjust`, `line-height`, text alignment,
+ indent/shadow/rendering controls, white-space/word-break/hyphenation
+ controls, `writing-mode`, `vertical-align`, `direction`, `unicode-bidi`, and
+ `text-transform` have no registered native mapping and are errors as direct
+ attributes or inline style.
+- Any other unregistered `font-*` or `text-*` property is also an error; the
+ closed grammar must not grow through an ignored CSS spelling.
+
+These allowlists are additive to the global structural blacklist and the
+paint, font-size, opacity, filter, and transform value contracts owned by their
+respective sections; they do not weaken those contracts.
+
| Treatment | SVG surface | Result / boundary |
|---|---|---|
| Underline / strike / both | `text-decoration="underline"`, `line-through`, or both | `Native-stable`; both emits both run properties |
| Mixed runs | Non-positional `<tspan>` | One `Native-normalized` editable frame; §4.2 |
| Font size | Generated default is a finite unitless SVG px value; compatible `px`, `pt`, `pc`/`pica`, `in`, `cm`, `mm`, `q`, `em`, and `rem` values receive a recommendation warning only | Converted to SVG px, then editable DrawingML point size; unsupported units/percentages error |
-| Tracking | Numeric `letter-spacing` | `Native-normalized`; unitless/`px` = SVG px, `pt` converts to px, `em` resolves against run size |
+| Tracking | §6.7 closed `letter-spacing` grammar | `Native-normalized`; compatible units normalize to SVG px before DrawingML conversion |
| Transparency | `opacity` / `fill-opacity` on text/run | `Native-normalized` run alpha, not isolated compositing |
| Gradient fill | §6.3 gradient on text/run | Editable fill; geometry normalizes |
| Outline | Solid `stroke`, `stroke-width`, `stroke-opacity` | `Native-normalized` editable run outline; re-import does not reconstruct it |
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index c87ca469..63004b26 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -172,6 +172,13 @@ try:
except ImportError:
_validate_preset_geometry_metadata = None
+try:
+ from svg_to_pptx.drawingml.text_properties import (
+ project_text_property_diagnostics as _project_text_property_diagnostics,
+ )
+except ImportError:
+ _project_text_property_diagnostics = None
+
try:
from pptx_to_svg.preset_authoring import (
AUTHORING_ATTR as _AUTHORING_ATTR,
@@ -1149,6 +1156,7 @@ class SVGQualityChecker:
# 2g. Validate the closed authoring-property surface and
# conditional definition interfaces before export.
self._check_authoring_property_contract(root, result)
+ self._check_text_property_contract(root, result)
self._check_paint_compatibility(root, result)
self._check_reference_spelling(root, result)
self._check_definition_contract(root, result)
@@ -1653,6 +1661,50 @@ class SVGQualityChecker:
result['errors'].extend(sorted(errors))
+ def _check_text_property_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Validate text property names and values with the export contract."""
+ if _project_text_property_diagnostics is None:
+ result['warnings'].append(
+ "Unable to import the shared text-property validator; native "
+ "export will still validate text properties."
+ )
+ return
+
+ errors: set[str] = set()
+ recommendations: Counter[tuple[str, str, str]] = Counter()
+ examples: Dict[tuple[str, str, str], List[str]] = defaultdict(list)
+ for diagnostic in _project_text_property_diagnostics(root):
+ if diagnostic.severity == 'error':
+ errors.add(diagnostic.message)
+ continue
+ if diagnostic.canonical is None:
+ continue
+ key = (
+ diagnostic.name,
+ diagnostic.raw,
+ diagnostic.canonical,
+ )
+ recommendations[key] += 1
+ if (
+ diagnostic.label not in examples[key]
+ and len(examples[key]) < 3
+ ):
+ examples[key].append(diagnostic.label)
+
+ result['errors'].extend(sorted(errors))
+ for (name, raw, canonical), count in sorted(recommendations.items()):
+ shown_examples = ', '.join(examples[(name, raw, canonical)])
+ result['warnings'].append(
+ f"Recommendation: text property {name}={raw!r} is "
+ f"converter-compatible in {count} location(s) "
+ f"({shown_examples}); generated SVG should prefer "
+ f'{name}="{canonical}". No change is required for export.'
+ )
+
def _check_definition_contract(
self,
root: ET.Element,
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 1b7cbc8b..386ce543 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
@@ -56,6 +56,11 @@ class ConvertContext:
rel_id_counter: int = 2 # rId1 reserved for slideLayout
svg_dir: Path | None = None
inherited_styles: dict[str, str] = 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)
+ # Effective source-pixel tracking resolved where each declaration occurs.
+ text_letter_spacings: dict[int, float] = field(default_factory=dict)
# SVG group opacity is post-compositing, not an inherited presentation
# property. DrawingML has no equivalent group alpha, so native export
# approximates it by multiplying this value into each descendant object.
@@ -222,6 +227,8 @@ class ConvertContext:
rel_id_counter=self.rel_id_counter,
svg_dir=self.svg_dir,
inherited_styles=merged,
+ text_font_sizes=self.text_font_sizes,
+ text_letter_spacings=self.text_letter_spacings,
opacity_multiplier=self.opacity_multiplier * local_opacity,
depth=self.depth + 1,
# anim_targets is intentionally a fresh list on the child;
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 f520ea42..aefe19b9 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -31,6 +31,12 @@ from .paths import (
)
from .theme_colors import ThemeColorSpec
from .theme_fonts import ThemeFontSpec
+from .text_properties import (
+ materialize_project_text_metrics,
+ project_text_property_errors,
+ resolve_project_font_sizes,
+ resolve_project_letter_spacings,
+)
from .utils import (
EMU_PER_PX,
SVG_NS,
@@ -276,6 +282,22 @@ def _require_project_filters(
)
+def _require_project_text_properties(
+ root: ET.Element,
+ svg_path: Path | str,
+) -> None:
+ """Reject text declarations outside the closed DrawingML mapping."""
+ errors = project_text_property_errors(root)
+ if not errors:
+ return
+ preview = '; '.join(errors[:8])
+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'
+ raise SvgNativeConversionError(
+ f'{Path(svg_path).name}: invalid project text property(s): '
+ f'{preview}{suffix}'
+ )
+
+
# ---------------------------------------------------------------------------
# Transform & layout helpers
# ---------------------------------------------------------------------------
@@ -1319,6 +1341,7 @@ def convert_svg_to_slide_shapes(
f'{preview}{suffix}'
)
+ _require_project_text_properties(root, svg_path)
_require_project_freeform_geometry(root, svg_path)
_require_project_stroke_styles(root, svg_path)
_require_project_opacities(root, svg_path)
@@ -1387,6 +1410,7 @@ def convert_svg_to_slide_shapes(
print(f' Expanded {expanded_local} local <use href="#..."/> instance(s)')
# Recheck compiler-injected icon/use wrappers and cloned definition trees.
+ _require_project_text_properties(root, svg_path)
_require_project_stroke_styles(root, svg_path)
_require_project_opacities(root, svg_path)
_require_project_paints(root, svg_path)
@@ -1397,6 +1421,13 @@ def convert_svg_to_slide_shapes(
_require_project_image_aspect_ratios(root, svg_path)
_require_project_transforms(root, svg_path)
+ try:
+ materialize_project_text_metrics(root)
+ except ValueError as exc:
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: text-metric materialization failed: {exc}'
+ ) from exc
+
# Flatten positional <tspan> (those with x/y/non-zero dy) into independent
# <text> elements. DrawingML runs cannot reposition mid-paragraph, so a
# dy-stacked block of tspans would otherwise collapse onto one baseline,
@@ -1415,6 +1446,18 @@ def convert_svg_to_slide_shapes(
if verbose:
print(' Flattened positional <tspan> into independent <text>')
+ _require_project_text_properties(root, svg_path)
+ try:
+ text_font_sizes = resolve_project_font_sizes(root)
+ text_letter_spacings = resolve_project_letter_spacings(
+ root,
+ text_font_sizes,
+ )
+ except ValueError as exc:
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: invalid project text-metric inheritance: {exc}'
+ ) from exc
+
unsupported = collect_unsupported_visuals(root)
if unsupported:
preview = '; '.join(unsupported[:8])
@@ -1444,6 +1487,9 @@ def convert_svg_to_slide_shapes(
trace_events=trace_events,
theme_font_spec=theme_font_spec,
theme_color_spec=theme_color_spec,
+ inherited_styles=_extract_inheritable_styles(root),
+ text_font_sizes=text_font_sizes,
+ text_letter_spacings=text_letter_spacings,
)
shapes: list[str] = []
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 25587b1c..bbf108af 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -28,6 +28,14 @@ from resource_paths import resolve_external_image_reference
from .context import ConvertContext, ShapeResult
from .theme_colors import color_node_xml
from .theme_fonts import theme_font_tokens
+from .text_properties import (
+ drawingml_letter_spacing,
+ parse_project_font_style,
+ parse_project_font_weight,
+ parse_project_letter_spacing,
+ parse_project_text_anchor,
+ parse_project_text_decoration,
+)
from .utils import (
SVG_NS, XLINK_NS, ANGLE_UNIT, FONT_PX_TO_HUNDREDTHS_PT,
PROJECT_IMAGE_ASPECT_RATIO_ANCHORS,
@@ -1663,38 +1671,12 @@ def _preserves_space(elem: ET.Element) -> bool:
return xml_space == 'preserve'
-def _parse_letter_spacing_px(
- value: str | None,
- *,
- font_size: float,
- scale_x: float = 1.0,
-) -> float:
- """Parse an SVG letter-spacing value into scaled pixels."""
- if not value:
- return 0.0
- raw = value.strip().lower()
- if raw in {'normal', 'inherit', 'initial', 'unset'}:
- return 0.0
-
- match = re.fullmatch(r'([-+]?(?:\d*\.\d+|\d+\.?))(px|pt|em)?', raw)
- if not match:
- return 0.0
-
- amount = float(match.group(1))
- unit = match.group(2) or 'px'
- if unit == 'em':
- return amount * font_size
- if unit == 'pt':
- return amount * 4.0 / 3.0 * scale_x
- return amount * scale_x
-
-
def _letter_spacing_to_drawingml_spc(letter_spacing_px: float) -> str:
"""Convert SVG px letter spacing into DrawingML rPr@spc."""
- if abs(letter_spacing_px) < 1e-9:
+ spacing = drawingml_letter_spacing(letter_spacing_px)
+ if spacing == 0:
return ''
- spc_val = round(letter_spacing_px * FONT_PX_TO_HUNDREDTHS_PT)
- return f' spc="{spc_val}"'
+ return f' spc="{spacing}"'
def _is_serif_run(run: dict[str, Any]) -> bool:
@@ -1930,6 +1912,7 @@ def _text_opacity_ratio(value: str | None) -> float:
def _override_run_attrs(
parent_attrs: dict[str, Any],
tspan: ET.Element,
+ ctx: ConvertContext,
) -> dict[str, Any]:
"""Layer a tspan's styling attributes over the inherited run attrs."""
run_attrs = dict(parent_attrs)
@@ -1960,7 +1943,9 @@ def _override_run_attrs(
)
if tspan_attr('font-weight'):
- run_attrs['font_weight'] = tspan_attr('font-weight')
+ run_attrs['font_weight'] = parse_project_font_weight(
+ tspan_attr('font-weight')
+ ).canonical
if tspan_attr('fill'):
child_fill = tspan_attr('fill')
run_attrs['fill_raw'] = child_fill
@@ -1975,7 +1960,10 @@ def _override_run_attrs(
run_attrs.get('stroke_width', 1.0),
font_size=float(run_attrs.get('font_size', 16)),
)
- if tspan_attr('font-size'):
+ resolved_font_size = ctx.text_font_sizes.get(id(tspan))
+ if resolved_font_size is not None:
+ run_attrs['font_size'] = resolved_font_size * ctx.scale_y
+ elif tspan_attr('font-size'):
run_attrs['font_size'] = parse_svg_length(
tspan_attr('font-size'),
run_attrs['font_size'],
@@ -1984,21 +1972,29 @@ def _override_run_attrs(
if tspan_attr('font-family'):
run_attrs['font_family'] = tspan_attr('font-family')
if tspan_attr('font-style'):
- run_attrs['font_style'] = tspan_attr('font-style')
+ run_attrs['font_style'] = parse_project_font_style(
+ tspan_attr('font-style')
+ ).canonical
if tspan_attr('text-decoration'):
- run_attrs['text_decoration'] = tspan_attr('text-decoration')
- if tspan_attr('letter-spacing'):
- run_attrs['letter_spacing'] = _parse_letter_spacing_px(
+ run_attrs['text_decoration'] = parse_project_text_decoration(
+ tspan_attr('text-decoration')
+ ).canonical
+ resolved_letter_spacing = ctx.text_letter_spacings.get(id(tspan))
+ if resolved_letter_spacing is not None:
+ run_attrs['letter_spacing'] = resolved_letter_spacing * ctx.scale_x
+ elif tspan_attr('letter-spacing'):
+ run_attrs['letter_spacing'] = parse_project_letter_spacing(
tspan_attr('letter-spacing'),
font_size=float(run_attrs.get('font_size', 16)),
scale_x=float(run_attrs.get('_scale_x', 1.0)),
- )
+ ).value
return run_attrs
def _collect_tspan_runs(
tspan: ET.Element,
inherited_attrs: dict[str, Any],
+ ctx: ConvertContext,
preserve_space: bool = False,
) -> list[dict[str, Any]]:
"""Recursively turn a tspan subtree into runs, propagating styling through nested tspans.
@@ -2006,7 +2002,7 @@ def _collect_tspan_runs(
Order: tspan.text → (each nested child tspan's runs → that child's tail under THIS tspan's attrs).
"""
runs: list[dict[str, Any]] = []
- own_attrs = _override_run_attrs(inherited_attrs, tspan)
+ own_attrs = _override_run_attrs(inherited_attrs, tspan, ctx)
child_preserve_space = preserve_space or _preserves_space(tspan)
if tspan.text:
@@ -2017,7 +2013,9 @@ def _collect_tspan_runs(
for child in tspan:
child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
if child_tag == 'tspan':
- runs.extend(_collect_tspan_runs(child, own_attrs, child_preserve_space))
+ runs.extend(
+ _collect_tspan_runs(child, own_attrs, ctx, child_preserve_space)
+ )
if child.tail:
t = _normalize_text(child.tail, preserve_space=child_preserve_space)
if t:
@@ -2029,6 +2027,7 @@ def _collect_tspan_runs(
def _build_text_runs(
elem: ET.Element,
parent_attrs: dict[str, Any],
+ ctx: ConvertContext,
) -> list[dict[str, Any]]:
"""Build a list of text runs from a <text> element, handling <tspan> children.
@@ -2047,7 +2046,9 @@ def _build_text_runs(
for child in elem:
child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
if child_tag == 'tspan':
- runs.extend(_collect_tspan_runs(child, parent_attrs, preserve_space))
+ runs.extend(
+ _collect_tspan_runs(child, parent_attrs, ctx, preserve_space)
+ )
if child.tail:
t = _normalize_text(child.tail, preserve_space=preserve_space)
if t:
@@ -2149,10 +2150,13 @@ def _build_run_xml(
# / integer snapping — whatever the px works out to is the size, e.g.
# 18px -> 13.5pt, 24px -> 18.0pt, 42px -> 31.5pt.
sz = font_px_to_hpt(fs_px)
- b_attr = ' b="1"' if fw in ('bold', '600', '700', '800', '900') else ''
+ b_attr = ' b="1"' if parse_project_font_weight(fw).value else ''
i_attr = ' i="1"' if fstyle == 'italic' else ''
- u_attr = ' u="sng"' if 'underline' in text_dec else ''
- strike_attr = ' strike="sngStrike"' if 'line-through' in text_dec else ''
+ underline, strike = parse_project_text_decoration(
+ text_dec or 'none'
+ ).value
+ u_attr = ' u="sng"' if underline else ''
+ strike_attr = ' strike="sngStrike"' if strike else ''
spc_attr = _letter_spacing_to_drawingml_spc(letter_spacing_px)
fonts = parse_font_family(ff) if ff else default_fonts
@@ -2184,13 +2188,23 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"""Convert SVG <text> to DrawingML text shape with multi-run support."""
x = ctx_x(svg_length_x(elem.get('x'), ctx), ctx)
y = ctx_y(svg_length_y(elem.get('y'), ctx), ctx)
+ resolved_font_size = ctx.text_font_sizes.get(id(elem))
font_size = (
- parse_svg_length(_get_attr(elem, 'font-size', ctx), 16, font_size=16)
- * ctx.scale_y
+ resolved_font_size * ctx.scale_y
+ if resolved_font_size is not None
+ else parse_svg_length(
+ _get_attr(elem, 'font-size', ctx),
+ 16,
+ font_size=16,
+ ) * ctx.scale_y
)
- font_weight = _get_attr(elem, 'font-weight', ctx) or '400'
+ font_weight = parse_project_font_weight(
+ _get_attr(elem, 'font-weight', ctx) or '400'
+ ).canonical
font_family_str = _get_attr(elem, 'font-family', ctx) or ''
- text_anchor = _get_attr(elem, 'text-anchor', ctx) or 'start'
+ text_anchor = parse_project_text_anchor(
+ _get_attr(elem, 'text-anchor', ctx) or 'start'
+ ).canonical
fill_raw = _get_attr(elem, 'fill', ctx) or '#000000'
fill_color = parse_hex_color(fill_raw) or '000000'
opacity = get_fill_opacity(elem, ctx)
@@ -2201,13 +2215,24 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
stroke_width = svg_length_size(_get_attr(elem, 'stroke-width', ctx), ctx, 1.0)
stroke_opacity = get_stroke_opacity(elem, ctx)
stroke_opacity_value = _text_opacity_ratio(_get_attr(elem, 'stroke-opacity', ctx))
- font_style = _get_attr(elem, 'font-style', ctx) or ''
- text_decoration = _get_attr(elem, 'text-decoration', ctx) or ''
- letter_spacing_px = _parse_letter_spacing_px(
- _get_attr(elem, 'letter-spacing', ctx),
- font_size=font_size,
- scale_x=ctx.scale_x or 1.0,
- )
+ font_style = parse_project_font_style(
+ _get_attr(elem, 'font-style', ctx) or 'normal'
+ ).canonical
+ text_decoration = parse_project_text_decoration(
+ _get_attr(elem, 'text-decoration', ctx) or 'none'
+ ).canonical
+ raw_letter_spacing = _get_attr(elem, 'letter-spacing', ctx)
+ resolved_letter_spacing = ctx.text_letter_spacings.get(id(elem))
+ if resolved_letter_spacing is not None:
+ letter_spacing_px = resolved_letter_spacing * ctx.scale_x
+ elif raw_letter_spacing is not None:
+ letter_spacing_px = parse_project_letter_spacing(
+ raw_letter_spacing,
+ font_size=font_size,
+ scale_x=ctx.scale_x or 1.0,
+ ).value
+ else:
+ letter_spacing_px = 0.0
fonts = parse_font_family(font_family_str)
@@ -2254,7 +2279,12 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
for child in elem:
if child.tag != f'{{{SVG_NS}}}tspan':
continue
- line_runs = _collect_tspan_runs(child, parent_attrs, preserve_space)
+ line_runs = _collect_tspan_runs(
+ child,
+ parent_attrs,
+ ctx,
+ preserve_space,
+ )
if line_runs and not preserve_space:
line_runs[0]['text'] = line_runs[0]['text'].lstrip(' ')
line_runs[-1]['text'] = line_runs[-1]['text'].rstrip(' ')
@@ -2299,7 +2329,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if paragraph_runs is not None:
runs = [r for line in paragraph_runs for r in line]
else:
- runs = _build_text_runs(elem, parent_attrs)
+ runs = _build_text_runs(elem, parent_attrs, ctx)
runs, single_bullet = _extract_text_bullet(runs)
full_text = ''.join(r['text'] for r in runs) if runs else ''
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py
new file mode 100644
index 00000000..ffb7bfe7
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/text_properties.py
@@ -0,0 +1,679 @@
+"""Closed project grammar for SVG text presentation properties.
+
+The project accepts a deliberately small SVG text surface that maps
+deterministically to editable DrawingML. This module is shared by the quality
+checker and the converter so unsupported values cannot be silently normalized
+by one route and rejected by the other.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from dataclasses import dataclass
+from xml.etree import ElementTree as ET
+
+from .utils import font_px_to_hpt, parse_svg_length
+
+
+_SVG_TEXT_PROPERTIES = frozenset({
+ 'font-weight',
+ 'font-style',
+ 'text-anchor',
+ 'letter-spacing',
+ 'text-decoration',
+})
+
+_TEXT_DECLARATION_PROPERTIES = _SVG_TEXT_PROPERTIES | {
+ 'font-family',
+ 'font-size',
+}
+
+_TEXT_INHERITANCE_TARGETS = frozenset({'svg', 'g', 'text', 'tspan'})
+
+_UNSUPPORTED_TEXT_PROPERTIES = frozenset({
+ 'alignment-baseline',
+ 'baseline-shift',
+ 'direction',
+ 'dominant-baseline',
+ 'font-kerning',
+ 'font-feature-settings',
+ 'font-size-adjust',
+ 'font-stretch',
+ 'font-synthesis',
+ 'font-variant',
+ 'font-variation-settings',
+ 'font',
+ 'hyphens',
+ 'kerning',
+ 'line-height',
+ 'overflow-wrap',
+ 'text-align',
+ 'text-align-last',
+ 'text-indent',
+ 'text-rendering',
+ 'text-shadow',
+ 'text-transform',
+ 'unicode-bidi',
+ 'vertical-align',
+ 'white-space',
+ 'word-spacing',
+ 'word-break',
+ 'writing-mode',
+})
+
+_TEXT_DIRECT_ATTRIBUTES = frozenset({
+ 'fill',
+ 'fill-opacity',
+ 'filter',
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'id',
+ 'letter-spacing',
+ 'opacity',
+ 'stroke',
+ 'stroke-opacity',
+ 'stroke-width',
+ 'style',
+ 'text-anchor',
+ 'text-decoration',
+ 'transform',
+ 'x',
+ 'xml:space',
+ 'y',
+})
+
+_TSPAN_DIRECT_ATTRIBUTES = frozenset({
+ 'dx',
+ 'dy',
+ 'fill',
+ 'fill-opacity',
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'id',
+ 'letter-spacing',
+ 'opacity',
+ 'stroke',
+ 'stroke-opacity',
+ 'stroke-width',
+ 'style',
+ 'text-decoration',
+ 'x',
+ 'xml:space',
+ 'y',
+})
+
+_TEXT_INLINE_PROPERTIES = frozenset({
+ 'fill',
+ 'fill-opacity',
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'letter-spacing',
+ 'opacity',
+ 'shape-rendering',
+ 'stroke',
+ 'stroke-opacity',
+ 'stroke-width',
+ 'text-anchor',
+ 'text-decoration',
+})
+
+_TSPAN_INLINE_PROPERTIES = _TEXT_INLINE_PROPERTIES - {'text-anchor'}
+
+_CANONICAL_DECIMAL_RE = re.compile(r'^-?(?:\d+(?:\.\d+)?|\.\d+)$')
+_COMPATIBLE_LETTER_SPACING_RE = re.compile(
+ r'(-?(?:\d+(?:\.\d+)?|\.\d+))(px|pt|em)',
+ re.IGNORECASE,
+)
+_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
+_DRAWINGML_TEXT_SPACING_MIN = -400_000
+_DRAWINGML_TEXT_SPACING_MAX = 400_000
+
+
+@dataclass(frozen=True)
+class ParsedTextProperty:
+ """One validated text-property value and its canonical representation."""
+
+ value: object
+ canonical: str
+ compatible: bool = False
+
+
+@dataclass(frozen=True)
+class TextPropertyDiagnostic:
+ """Stable checker/converter diagnostic for one text declaration."""
+
+ severity: str
+ label: str
+ source: str
+ name: str
+ raw: str
+ message: str
+ canonical: str | None = None
+
+
+def _local_name(value: object) -> str:
+ text = str(value)
+ return text.rsplit('}', 1)[-1] if '}' in text else text
+
+
+def _element_label(elem: ET.Element) -> str:
+ tag = _local_name(elem.tag)
+ elem_id = elem.get('id')
+ return f'<{tag} id="{elem_id}">' if elem_id else f'<{tag}>'
+
+
+def _attribute_name(raw_name: str) -> str:
+ if raw_name.startswith(f'{{{_XML_NAMESPACE}}}'):
+ return f'xml:{raw_name.rsplit("}", 1)[-1]}'
+ return _local_name(raw_name)
+
+
+def _is_unregistered_prefixed_text_property(name: str) -> bool:
+ lowered = name.lower()
+ return (
+ lowered.startswith(('font-', 'text-'))
+ and lowered not in _TEXT_DECLARATION_PROPERTIES
+ )
+
+
+def _format_decimal(value: float) -> str:
+ if abs(value) < 1e-15:
+ return '0'
+ text = f'{value:.15f}'.rstrip('0').rstrip('.')
+ return '0' if text in {'', '-0'} else text
+
+
+def parse_project_font_weight(raw: str) -> ParsedTextProperty:
+ """Parse the closed project font-weight grammar."""
+ if raw in {'normal', 'bold'}:
+ return ParsedTextProperty(raw == 'bold', raw)
+ if raw in {str(value) for value in range(100, 1000, 100)}:
+ return ParsedTextProperty(int(raw) >= 600, raw)
+ aliases = {'medium': '500', 'semibold': '600'}
+ if raw in aliases:
+ canonical = aliases[raw]
+ return ParsedTextProperty(int(canonical) >= 600, canonical, True)
+ raise ValueError(
+ "expected 'normal', 'bold', or an integer weight from 100 through 900"
+ )
+
+
+def parse_project_font_style(raw: str) -> ParsedTextProperty:
+ """Parse the closed project font-style grammar."""
+ if raw not in {'normal', 'italic'}:
+ raise ValueError("expected 'normal' or 'italic'")
+ return ParsedTextProperty(raw == 'italic', raw)
+
+
+def parse_project_text_anchor(raw: str) -> ParsedTextProperty:
+ """Parse the closed project text-anchor grammar."""
+ if raw not in {'start', 'middle', 'end'}:
+ raise ValueError("expected 'start', 'middle', or 'end'")
+ return ParsedTextProperty(raw, raw)
+
+
+def parse_project_text_decoration(raw: str) -> ParsedTextProperty:
+ """Parse text decoration without substring-based false positives."""
+ canonical = {
+ 'none': 'none',
+ 'underline': 'underline',
+ 'line-through': 'line-through',
+ 'underline line-through': 'underline line-through',
+ }
+ if raw in canonical:
+ value = (
+ 'underline' in raw.split(),
+ 'line-through' in raw.split(),
+ )
+ return ParsedTextProperty(value, canonical[raw])
+ if raw == 'line-through underline':
+ return ParsedTextProperty(
+ (True, True),
+ 'underline line-through',
+ True,
+ )
+ raise ValueError(
+ "expected 'none', 'underline', 'line-through', or "
+ "'underline line-through'"
+ )
+
+
+def parse_project_letter_spacing(
+ raw: str,
+ *,
+ font_size: float = 16.0,
+ scale_x: float = 1.0,
+) -> ParsedTextProperty:
+ """Parse project tracking into scaled SVG pixels and validate DML range."""
+ if _CANONICAL_DECIMAL_RE.fullmatch(raw):
+ amount = float(raw)
+ unit = ''
+ compatible = False
+ else:
+ match = _COMPATIBLE_LETTER_SPACING_RE.fullmatch(raw)
+ if match is None:
+ raise ValueError(
+ 'expected a finite ordinary decimal, optionally followed by '
+ 'the registered compatible unit px, pt, or em'
+ )
+ amount = float(match.group(1))
+ unit = match.group(2).lower()
+ compatible = True
+
+ if not math.isfinite(amount):
+ raise ValueError('must be finite')
+ if not math.isfinite(font_size) or font_size <= 0:
+ raise ValueError('requires a finite positive effective font size')
+ if not math.isfinite(scale_x) or scale_x <= 0:
+ raise ValueError('requires a finite positive horizontal scale')
+
+ if unit == 'em':
+ value_px = amount * font_size
+ elif unit == 'pt':
+ value_px = amount * 4.0 / 3.0 * scale_x
+ else:
+ value_px = amount * scale_x
+
+ spacing = round(value_px * 75)
+ if not _DRAWINGML_TEXT_SPACING_MIN <= spacing <= _DRAWINGML_TEXT_SPACING_MAX:
+ raise ValueError(
+ 'converts outside the DrawingML character-spacing range '
+ f'{_DRAWINGML_TEXT_SPACING_MIN}..{_DRAWINGML_TEXT_SPACING_MAX}'
+ )
+ return ParsedTextProperty(
+ value_px,
+ _format_decimal(value_px),
+ compatible,
+ )
+
+
+def drawingml_letter_spacing(value_px: float) -> int:
+ """Return validated DrawingML ``a:rPr@spc`` hundredths-of-a-point."""
+ if not math.isfinite(value_px):
+ raise ValueError('letter-spacing must be finite')
+ spacing = round(value_px * 75)
+ if not _DRAWINGML_TEXT_SPACING_MIN <= spacing <= _DRAWINGML_TEXT_SPACING_MAX:
+ raise ValueError(
+ 'letter-spacing converts outside the DrawingML range '
+ f'{_DRAWINGML_TEXT_SPACING_MIN}..{_DRAWINGML_TEXT_SPACING_MAX}'
+ )
+ return spacing
+
+
+def parse_project_text_property(
+ name: str,
+ raw: str,
+ *,
+ font_size: float = 16.0,
+) -> ParsedTextProperty:
+ """Parse one declaration from the shared text-property value contract."""
+ parsers = {
+ 'font-weight': parse_project_font_weight,
+ 'font-style': parse_project_font_style,
+ 'text-anchor': parse_project_text_anchor,
+ 'letter-spacing': parse_project_letter_spacing,
+ 'text-decoration': parse_project_text_decoration,
+ }
+ parser = parsers.get(name)
+ if parser is None:
+ raise ValueError(f'unsupported project text property {name!r}')
+ if name == 'letter-spacing':
+ return parser(raw, font_size=font_size)
+ return parser(raw)
+
+
+def _iter_style_declarations(
+ elem: ET.Element,
+) -> tuple[list[tuple[str, str]], list[str]]:
+ declarations: list[tuple[str, str]] = []
+ malformed: list[str] = []
+ for raw_fragment in (elem.get('style') or '').split(';'):
+ fragment = raw_fragment.strip()
+ if not fragment:
+ continue
+ if ':' not in fragment:
+ malformed.append(fragment)
+ continue
+ raw_name, raw_value = fragment.split(':', 1)
+ name = raw_name.strip().lower()
+ value = raw_value.strip()
+ if not name or not value:
+ malformed.append(fragment)
+ continue
+ declarations.append((name, value))
+ return declarations, malformed
+
+
+def _resolve_font_sizes(
+ root: ET.Element,
+) -> tuple[dict[int, float], list[TextPropertyDiagnostic]]:
+ """Resolve inherited font sizes and retain declaration-level failures."""
+ resolved: dict[int, float] = {}
+ diagnostics: list[TextPropertyDiagnostic] = []
+
+ def parse_declared_size(
+ elem: ET.Element,
+ raw: str,
+ source: str,
+ parent_size: float,
+ root_size: float,
+ ) -> float | None:
+ label = _element_label(elem)
+ relative_base = (
+ root_size
+ if raw.strip().lower().endswith('rem')
+ else parent_size
+ )
+ try:
+ value = parse_svg_length(
+ raw,
+ parent_size,
+ font_size=relative_base,
+ )
+ font_px_to_hpt(value)
+ except ValueError as exc:
+ diagnostics.append(TextPropertyDiagnostic(
+ 'error',
+ label,
+ source,
+ 'font-size',
+ raw,
+ f'{label} {source} font-size={raw!r}: {exc}',
+ ))
+ return None
+ return value
+
+ def walk(
+ elem: ET.Element,
+ parent_size: float,
+ root_size: float,
+ ) -> None:
+ declarations, _ = _iter_style_declarations(elem)
+ style_sizes = [
+ raw
+ for name, raw in declarations
+ if name == 'font-size'
+ ]
+ direct_raw = elem.get('font-size')
+ direct_size = (
+ parse_declared_size(
+ elem,
+ direct_raw,
+ 'attribute',
+ parent_size,
+ root_size,
+ )
+ if direct_raw is not None
+ else None
+ )
+ parsed_style_sizes = [
+ parse_declared_size(
+ elem,
+ raw,
+ 'inline style',
+ parent_size,
+ root_size,
+ )
+ for raw in style_sizes
+ ]
+ effective_size = parent_size
+ if style_sizes:
+ last_style_size = parsed_style_sizes[-1]
+ effective_size = (
+ last_style_size
+ if last_style_size is not None
+ else parent_size
+ )
+ elif direct_raw is not None:
+ effective_size = direct_size if direct_size is not None else parent_size
+ resolved[id(elem)] = effective_size
+ child_root_size = effective_size if elem is root else root_size
+ for child in elem:
+ walk(child, effective_size, child_root_size)
+
+ walk(root, 16.0, 16.0)
+ return resolved, diagnostics
+
+
+def resolve_project_font_sizes(root: ET.Element) -> dict[int, float]:
+ """Return effective SVG font sizes or reject an invalid declaration."""
+ resolved, diagnostics = _resolve_font_sizes(root)
+ if diagnostics:
+ raise ValueError('; '.join(item.message for item in diagnostics[:8]))
+ return resolved
+
+
+def resolve_project_letter_spacings(
+ root: ET.Element,
+ font_sizes: dict[int, float] | None = None,
+) -> dict[int, float]:
+ """Resolve tracking at its declaration site before it is inherited."""
+ effective_font_sizes = font_sizes or resolve_project_font_sizes(root)
+ resolved: dict[int, float] = {}
+
+ def walk(elem: ET.Element, parent_spacing: float) -> None:
+ declarations, _ = _iter_style_declarations(elem)
+ style = dict(declarations)
+ direct_raw = elem.get('letter-spacing')
+ style_raw = style.get('letter-spacing')
+ effective_spacing = parent_spacing
+ if style_raw is not None:
+ effective_spacing = float(parse_project_letter_spacing(
+ style_raw,
+ font_size=effective_font_sizes[id(elem)],
+ ).value)
+ elif direct_raw is not None:
+ effective_spacing = float(parse_project_letter_spacing(
+ direct_raw,
+ font_size=effective_font_sizes[id(elem)],
+ ).value)
+ resolved[id(elem)] = effective_spacing
+ for child in elem:
+ walk(child, effective_spacing)
+
+ walk(root, 0.0)
+ return resolved
+
+
+def materialize_project_text_metrics(root: ET.Element) -> int:
+ """Lower relative text metrics before positional tspan restructuring."""
+ font_sizes = resolve_project_font_sizes(root)
+ letter_spacings = resolve_project_letter_spacings(root, font_sizes)
+ materialized = 0
+ for elem in root.iter():
+ canonical_font_size = _format_decimal(font_sizes[id(elem)])
+ canonical_letter_spacing = _format_decimal(letter_spacings[id(elem)])
+ if elem.get('font-size') is not None:
+ elem.set('font-size', canonical_font_size)
+ materialized += 1
+ if elem.get('letter-spacing') is not None:
+ elem.set('letter-spacing', canonical_letter_spacing)
+ materialized += 1
+
+ style = elem.get('style')
+ if not style:
+ continue
+ retained: list[str] = []
+ changed = False
+ for raw_fragment in style.split(';'):
+ fragment = raw_fragment.strip()
+ if not fragment:
+ continue
+ if ':' not in fragment:
+ retained.append(fragment)
+ continue
+ raw_name, _ = fragment.split(':', 1)
+ name = raw_name.strip().lower()
+ if name == 'font-size':
+ retained.append(f'font-size:{canonical_font_size}')
+ changed = True
+ materialized += 1
+ elif name == 'letter-spacing':
+ retained.append(
+ f'letter-spacing:{canonical_letter_spacing}'
+ )
+ changed = True
+ materialized += 1
+ else:
+ retained.append(fragment)
+ if changed:
+ elem.set('style', '; '.join(retained))
+ return materialized
+
+
+def _diagnose_text_declaration(
+ elem: ET.Element,
+ *,
+ tag: str,
+ source: str,
+ name: str,
+ raw: str,
+ font_size: float,
+) -> tuple[bool, TextPropertyDiagnostic | None]:
+ """Return whether a declaration belongs to the text contract and its issue."""
+ label = _element_label(elem)
+ if _is_unregistered_prefixed_text_property(name):
+ return True, TextPropertyDiagnostic(
+ 'error', label, source, name, raw,
+ f'{label} uses unregistered inherited text property {name!r}; '
+ 'native PPTX export would ignore it',
+ )
+ if (
+ name in _TEXT_DECLARATION_PROPERTIES
+ and tag not in _TEXT_INHERITANCE_TARGETS
+ ):
+ return True, TextPropertyDiagnostic(
+ 'error', label, source, name, raw,
+ f'{label} cannot carry text property {name!r}; place it on '
+ '<svg>, <g>, <text>, or <tspan>',
+ )
+ if name in _UNSUPPORTED_TEXT_PROPERTIES:
+ return True, TextPropertyDiagnostic(
+ 'error', label, source, name, raw,
+ f'{label} uses unsupported text property {name!r}; '
+ 'it has no registered DrawingML mapping',
+ )
+ if name not in _SVG_TEXT_PROPERTIES:
+ return name in _TEXT_DECLARATION_PROPERTIES, None
+ if tag == 'tspan' and name == 'text-anchor':
+ return True, TextPropertyDiagnostic(
+ 'error', label, source, name, raw,
+ f'{label} cannot use text-anchor on <tspan>; place it on the '
+ 'containing <text> or an ancestor group',
+ )
+ try:
+ parsed = parse_project_text_property(
+ name,
+ raw,
+ font_size=font_size,
+ )
+ except ValueError as exc:
+ return True, TextPropertyDiagnostic(
+ 'error', label, source, name, raw,
+ f'{label} {source} {name}={raw!r}: {exc}',
+ )
+ if parsed.compatible:
+ return True, TextPropertyDiagnostic(
+ 'warning', label, source, name, raw,
+ f'{label} {source} {name}={raw!r} is compatible; '
+ f'prefer {name}={parsed.canonical!r}',
+ parsed.canonical,
+ )
+ return True, None
+
+
+def project_text_property_diagnostics(
+ root: ET.Element,
+) -> list[TextPropertyDiagnostic]:
+ """Validate the closed text attribute/value surface for one SVG tree."""
+ font_sizes, diagnostics = _resolve_font_sizes(root)
+
+ for elem in root.iter():
+ tag = _local_name(elem.tag)
+ label = _element_label(elem)
+ direct_allowlist = {
+ 'text': _TEXT_DIRECT_ATTRIBUTES,
+ 'tspan': _TSPAN_DIRECT_ATTRIBUTES,
+ }.get(tag)
+ inline_allowlist = {
+ 'text': _TEXT_INLINE_PROPERTIES,
+ 'tspan': _TSPAN_INLINE_PROPERTIES,
+ }.get(tag)
+
+ for raw_name, raw in elem.attrib.items():
+ name = _attribute_name(raw_name)
+ if name == 'style' or name.startswith('data-'):
+ continue
+ handled, diagnostic = _diagnose_text_declaration(
+ elem,
+ tag=tag,
+ source='attribute',
+ name=name,
+ raw=raw,
+ font_size=font_sizes[id(elem)],
+ )
+ if diagnostic is not None:
+ diagnostics.append(diagnostic)
+ elif (
+ not handled
+ and direct_allowlist is not None
+ and name not in direct_allowlist
+ ):
+ diagnostics.append(TextPropertyDiagnostic(
+ 'error', label, 'attribute', name, raw,
+ f'{label} uses unsupported text attribute {name!r}; '
+ 'native PPTX export would ignore it',
+ ))
+
+ declarations, malformed = _iter_style_declarations(elem)
+ for fragment in malformed:
+ property_hint = fragment.split(None, 1)[0].lower()
+ if (
+ inline_allowlist is not None
+ or property_hint in _TEXT_DECLARATION_PROPERTIES
+ or property_hint in _UNSUPPORTED_TEXT_PROPERTIES
+ or _is_unregistered_prefixed_text_property(property_hint)
+ ):
+ diagnostics.append(TextPropertyDiagnostic(
+ 'error', label, 'inline style', '<malformed>', fragment,
+ f'{label} has malformed inline style declaration {fragment!r}',
+ ))
+ for name, raw in declarations:
+ handled, diagnostic = _diagnose_text_declaration(
+ elem,
+ tag=tag,
+ source='inline style',
+ name=name,
+ raw=raw,
+ font_size=font_sizes[id(elem)],
+ )
+ if diagnostic is not None:
+ diagnostics.append(diagnostic)
+ elif (
+ not handled
+ and inline_allowlist is not None
+ and name not in inline_allowlist
+ ):
+ diagnostics.append(TextPropertyDiagnostic(
+ 'error', label, 'inline style', name, raw,
+ f'{label} uses unsupported inline text property {name!r}; '
+ 'native PPTX export would ignore it',
+ ))
+
+ return diagnostics
+
+
+def project_text_property_errors(root: ET.Element) -> list[str]:
+ """Return blocking diagnostics for the converter preflight."""
+ return [
+ diagnostic.message
+ for diagnostic in project_text_property_diagnostics(root)
+ if diagnostic.severity == 'error'
+ ]
diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.py
index 67245e55..f540085a 100644
--- a/skills/ppt-master/scripts/test_svg_quality_checker.py
+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py
@@ -1125,6 +1125,244 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
with self.assertRaises(UseExpansionError):
expand_local_use_references(root)
+ 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">
+ <g id="text-group" style="font-weight:600; text-anchor:end;
+ letter-spacing:2; text-decoration:underline line-through">
+ <text x="500" y="160" font-family="Arial" font-size="24">
+ <tspan font-weight="500">Regular</tspan><tspan font-weight="600">Bold</tspan>
+ </text>
+ </g>
+</svg>'''
+ result = self._check(source)
+ self.assertTrue(result['passed'])
+ self.assertEqual(result['errors'], [])
+ self.assertEqual(result['warnings'], [])
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'text-contract.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertEqual(slide_xml.count('<a:r>'), 2)
+ self.assertEqual(slide_xml.count(' b="1"'), 1)
+ self.assertEqual(slide_xml.count(' i="1"'), 2)
+ self.assertEqual(slide_xml.count(' u="sng"'), 2)
+ self.assertEqual(slide_xml.count(' strike="sngStrike"'), 2)
+ self.assertEqual(slide_xml.count(' spc="150"'), 2)
+ self.assertIn('algn="r"', slide_xml)
+
+ def test_text_property_compatibility_aliases_warn_and_normalize(self):
+ compatible = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360">
+ <text x="40" y="100" font-family="Arial" font-size="24"
+ font-weight="medium" letter-spacing="2px"
+ text-decoration="line-through underline">Medium</text>
+ <text x="40" y="180" font-family="Arial" font-size="24"
+ font-weight="semibold">Semibold</text>
+</svg>'''
+ canonical = compatible.replace(
+ 'font-weight="medium"', 'font-weight="500"'
+ ).replace(
+ 'letter-spacing="2px"', 'letter-spacing="2"'
+ ).replace(
+ 'text-decoration="line-through underline"',
+ 'text-decoration="underline line-through"',
+ ).replace('font-weight="semibold"', 'font-weight="600"')
+
+ result = self._check(compatible)
+ warning_text = '\n'.join(result['warnings'])
+ self.assertTrue(result['passed'])
+ self.assertEqual(result['errors'], [])
+ self.assertIn("font-weight='medium'", warning_text)
+ self.assertIn('font-weight="500"', warning_text)
+ self.assertIn("font-weight='semibold'", warning_text)
+ self.assertIn('font-weight="600"', warning_text)
+ self.assertIn("letter-spacing='2px'", warning_text)
+ self.assertIn('letter-spacing="2"', warning_text)
+ self.assertIn(
+ "text-decoration='line-through underline'",
+ warning_text,
+ )
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'text-compatible.svg'
+ svg_path.write_text(compatible, encoding='utf-8')
+ compatible_xml = convert_svg_to_slide_shapes(svg_path)[0]
+ svg_path.write_text(canonical, encoding='utf-8')
+ canonical_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertEqual(compatible_xml, canonical_xml)
+ self.assertEqual(compatible_xml.count(' b="1"'), 1)
+ self.assertIn(' spc="150"', compatible_xml)
+ self.assertIn(' u="sng"', compatible_xml)
+ self.assertIn(' strike="sngStrike"', compatible_xml)
+
+ def test_invalid_text_properties_block_checker_and_exporter(self):
+ cases = {
+ 'anchor': ('text-anchor="banana"', 'text-anchor'),
+ 'weight': ('font-weight="heavy"', 'font-weight'),
+ 'style': ('font-style="oblique"', 'font-style'),
+ 'decoration': ('text-decoration="notunderline"', 'text-decoration'),
+ 'spacing': ('letter-spacing="banana"', 'letter-spacing'),
+ 'spacing_keyword': ('letter-spacing="normal"', 'letter-spacing'),
+ 'word_spacing': ('word-spacing="2"', 'word-spacing'),
+ 'baseline': ('style="dominant-baseline:middle"', 'dominant-baseline'),
+ 'unknown_attribute': ('textLength="120"', 'textLength'),
+ 'inline_filter': ('style="filter:url(#shadow)"', 'filter'),
+ }
+ for name, (declaration, expected) in cases.items():
+ content = (
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ f'<text x="40" y="100" font-size="24" {declaration}>'
+ 'Broken</text></svg>'
+ )
+ with self.subTest(name=name):
+ self._assert_checker_and_exporter_reject(
+ content,
+ expected,
+ 'invalid project text property',
+ )
+
+ def test_compatible_letter_spacing_units_match_unitless_px(self):
+ cases = (
+ ('2px', '2', '150'),
+ ('3pt', '4', '300'),
+ ('1em', '24', '1800'),
+ )
+ for compatible, canonical, spacing in cases:
+ source = (
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="40" y="100" font-family="Arial" font-size="24" '
+ f'letter-spacing="{compatible}">Tracking</text></svg>'
+ )
+ normalized = source.replace(
+ f'letter-spacing="{compatible}"',
+ f'letter-spacing="{canonical}"',
+ )
+ with self.subTest(value=compatible):
+ result = self._check(source)
+ self.assertTrue(result['passed'])
+ self.assertIn(
+ f'letter-spacing="{canonical}"',
+ '\n'.join(result['warnings']),
+ )
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'tracking.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ compatible_xml = convert_svg_to_slide_shapes(svg_path)[0]
+ svg_path.write_text(normalized, encoding='utf-8')
+ canonical_xml = convert_svg_to_slide_shapes(svg_path)[0]
+ self.assertEqual(compatible_xml, canonical_xml)
+ self.assertIn(f' spc="{spacing}"', compatible_xml)
+
+ def test_relative_font_sizes_share_one_inheritance_model(self):
+ source = '''<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 360" font-size="20">
+ <g id="relative-text" font-size="1.5em" letter-spacing="1em">
+ <text x="40" y="100" font-family="Arial" font-size="2em">Parent<tspan
+ font-size=".5em">Child</tspan></text>
+ <text x="40" y="180" font-family="Arial" font-size="2em">
+ <tspan x="40" dy="60" font-size=".5em">Positioned child</tspan>
+ </text>
+ </g>
+</svg>'''
+ result = self._check(source)
+ warning_text = '\n'.join(result['warnings'])
+ self.assertTrue(result['passed'])
+ self.assertEqual(result['errors'], [])
+ self.assertIn('letter-spacing="30"', warning_text)
+ self.assertNotIn('letter-spacing="60"', warning_text)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'relative-text.svg'
+ svg_path.write_text(source, encoding='utf-8')
+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]
+
+ self.assertIn(' sz="4500"', slide_xml)
+ self.assertIn(' sz="2250"', slide_xml)
+ self.assertIn(' spc="2250"', slide_xml)
+ self.assertNotIn(' spc="4500"', slide_xml)
+
+ def test_invalid_inherited_and_overridden_text_values_cannot_hide(self):
+ cases = {
+ 'root_inheritance': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360" font-weight="heavy">'
+ '<text x="40" y="100" font-size="24">Broken</text></svg>'
+ ), 'font-weight'),
+ 'overridden_attribute': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="40" y="100" font-size="24" font-weight="heavy" '
+ 'style="font-weight:700">Broken</text></svg>'
+ ), 'font-weight'),
+ 'tspan_anchor': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="40" y="100" font-size="24">'
+ '<tspan text-anchor="end">Broken</tspan></text></svg>'
+ ), 'text-anchor'),
+ 'spacing_range': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="40" y="100" font-size="24" '
+ 'letter-spacing="5333.35">Broken</text></svg>'
+ ), 'letter-spacing'),
+ 'malformed_inheritance': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<g style="font-weight"><text x="40" y="100" '
+ 'font-size="24">Broken</text></g></svg>'
+ ), 'malformed inline style'),
+ 'hidden_invalid_font_size': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<text x="40" y="100" '
+ 'style="font-size:banana; font-size:24">Broken</text></svg>'
+ ), 'font-size'),
+ 'wrong_element': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<rect x="20" y="20" width="100" height="60" '
+ 'font-weight="bold"/></svg>'
+ ), 'cannot carry text property'),
+ 'unsupported_group_property': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<g line-height="2"><text x="40" y="100" '
+ 'font-size="24">Broken</text></g></svg>'
+ ), 'line-height'),
+ 'unsupported_group_style': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<g style="font-feature-settings:smcp"><text x="40" '
+ 'y="100" font-size="24">Broken</text></g></svg>'
+ ), 'font-feature-settings'),
+ 'unregistered_prefixed_property': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<g font-optical-sizing="auto"><text x="40" y="100" '
+ 'font-size="24">Broken</text></g></svg>'
+ ), 'font-optical-sizing'),
+ 'malformed_prefixed_property': ((
+ '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'viewBox="0 0 640 360">'
+ '<g style="font-optical-sizing"><text x="40" y="100" '
+ 'font-size="24">Broken</text></g></svg>'
+ ), 'malformed inline style'),
+ }
+ for name, (content, expected) in cases.items():
+ with self.subTest(name=name):
+ self._assert_checker_and_exporter_reject(
+ content,
+ expected,
+ 'invalid project text property',
+ )
+
if __name__ == '__main__':
unittest.main()