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 picture source and crop contracts
hugohe34c66c04c1a58
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.mdindex c3226c82..4fd0fc39 100644--- a/docs/powerpoint-svg-mapping.md+++ b/docs/powerpoint-svg-mapping.md@@ -131,13 +131,13 @@ preset selection and authoring behavior are documented in| PowerPoint feature | Project representation | PPTX result | Import and fidelity | Validation boundary ||---|---|---|---|---|-| Picture | `<image>` with a project asset or data URI | `p:pic`, media part, and relationship | Reconstructed as `<image>` | Source must resolve, and dimensions must be valid |+| Picture | `<image>` with explicit positive dimensions and exactly one project-asset or image data-URI source | `p:pic`, media part, and relationship | Reconstructed as `<image>` | Source must resolve, use a registered format, and contain decodable bytes matching its MIME/extension; invalid frames or media fail before packaging || Stretch picture to frame | `preserveAspectRatio="none"` | Stretched native picture frame | `Native-stable` | `none` must stand alone; it intentionally changes the source aspect ratio || Crop picture to fill | One registered alignment plus explicit `slice` | Native `a:srcRect` crop | `Native-stable` when source dimensions are readable | Alignment is case-sensitive; unknown modes and extra tokens are errors || Fit picture inside frame | Omitted default, or one registered alignment plus explicit `meet` | Native fitted picture frame | `Native-normalized` | Alignment-only shorthand is compatible input that receives a normalization recommendation || Picture transparency | Atomic image `opacity` | Native `a:alphaModFix` | `Native-stable` | Value must be finite and within the accepted opacity grammar |-| Picture clipped to a shape | Image-only registered `clip-path` | Picture preset or custom geometry | `Native-normalized` | Arbitrary masks are not accepted |-| Imported cropped picture | Nested crop SVG representation produced by import | Native `a:srcRect` on re-export | `Native-stable` within the crop contract | Do not manually generalize nested SVG into an unrestricted feature |+| Picture clipped to a shape | Registered image/crop-wrapper `clip-path` with one SVG-namespace shape | Picture preset or custom geometry | `Native-normalized` | Circle/ellipse/rect presets must cover the complete picture frame; use path/polygon for partial or offset contours; masks and winding-rule-dependent contours are not accepted |+| Imported cropped picture | Exact SVG-namespace nested crop wrapper produced by import, containing one direct unit-frame image in the visual root/`g` tree | Native signed `a:srcRect` on re-export | `Native-stable` within the crop contract, including negative crop values | Any generalized nested viewport, non-visual/render-only owner, extra visual child, unrepresentable crop window, redundant uncropped wrapper, or unresolved clip-marker pair is rejected || Picture recolor, artistic filter, blur, or complex mask | No general authoring mapping | Rebuild with supported overlays or pre-render | `Bake-required` | Arbitrary SVG filters and blend modes fail the main contract |## 6. PowerPoint fill, line, and effect featuresdiff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.mdindex 7345d5cf..51a2617c 100644--- a/docs/zh/powerpoint-svg-mapping.md+++ b/docs/zh/powerpoint-svg-mapping.md@@ -126,13 +126,13 @@ PowerPoint 意图| PowerPoint 功能 | 项目表达 | PPTX 结果 | 回导与保真度 | 校验边界 ||---|---|---|---|---|-| 图片 | 引用项目资产或 data URI 的 `<image>` | `p:pic`、media part 与 relationship | 重建为 `<image>` | 源必须可解析,尺寸必须合法 |+| 图片 | 具有显式正尺寸且只含一个项目资产或图片 data URI 源的 `<image>` | `p:pic`、media part 与 relationship | 重建为 `<image>` | 源必须可解析、采用已登记格式,并包含与 MIME/扩展名相符的可解码字节;非法 frame 或媒体会在封装前失败 || 图片拉伸填满框 | `preserveAspectRatio="none"` | 原生拉伸 picture frame | `Native-stable` | `none` 必须单独出现;它会有意改变源宽高比 || 图片裁剪填充 | 一个已登记对齐值加显式 `slice` | 原生 `a:srcRect` 裁剪 | 源尺寸可读时为 `Native-stable` | 对齐值区分大小写;未知模式与额外 token 为 error || 图片适应框 | 省略时使用默认值,或一个已登记对齐值加显式 `meet` | 原生 fitted picture frame | `Native-normalized` | 仅写对齐值是兼容输入,Checker 会给出规范化建议 || 图片透明度 | 原子 image `opacity` | 原生 `a:alphaModFix` | `Native-stable` | 值必须有限,并在可接受 opacity 语法内 |-| 图片裁成形状 | 仅作用于 image 的已登记 `clip-path` | picture preset 或 custom geometry | `Native-normalized` | 不接受任意 mask |-| 导入的裁剪图片 | 导入器产生的嵌套 crop SVG 表达 | 重新导出为原生 `a:srcRect` | crop 合同内为 `Native-stable` | 不得手工将嵌套 SVG 泛化为不受限功能 |+| 图片裁成形状 | 作用于 image/crop wrapper 且只含一个 SVG 命名空间形状的已登记 `clip-path` | picture preset 或 custom geometry | `Native-normalized` | circle/ellipse/rect preset 必须覆盖完整图片 frame;局部或偏移轮廓使用 path/polygon;不接受任意 mask 或依赖绕组规则(winding rule)的轮廓 |+| 导入的裁剪图片 | 导入器产生的精确 SVG 命名空间嵌套 crop wrapper,在可视根/`g` 树中内含一个直接 unit-frame image | 重新导出为原生 signed `a:srcRect` | crop 合同内为 `Native-stable`,包括负裁剪值 | 拒绝通用嵌套 viewport、非可视或仅渲染所属容器、额外可视子元素、不可表示的 crop window、无裁剪的冗余 wrapper,以及无法解析的 clip-marker 配对 || 图片重着色、艺术滤镜、模糊或复杂 mask | 无通用创作映射 | 使用受支持 overlay 重建或预渲染 | `Bake-required` | 任意 SVG filter 和 blend mode 违反主合同 |## 6. PowerPoint 填充、线条与效果功能diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex 03074e43..65b18a92 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -181,25 +181,29 @@ dropped with a warning.### 1.2 Image Clipping (Conditional Contract)-`clip-path` has a native picture-geometry mapping only on `<image>` elements and-only under this contract:+`clip-path` has a native picture-geometry mapping only on SVG-namespace+`<image>` elements (plus the exact imported crop wrapper defined under Images)+and only under this contract:| Concern | Required form ||---|---|-| `<clipPath>` element defined inside `<defs>` | Converter looks up clip defs via id index |-| Contains a **single supported** shape child | The converter uses the first supported child; multiple shapes are not composited |-| Shape is one of: `<circle>`, `<ellipse>`, `<rect>` (with rx/ry), `<path>`, `<polygon>` | These map to DrawingML geometry (preset or custom) |-| Used **only on `<image>` elements** | Non-image elements with clip-path are **forbidden** |+| SVG-namespace `<clipPath>` defined inside `<defs>` | Converter looks up one exact local id; missing, duplicate, foreign-namespace, or malformed references fail |+| Contains exactly one direct SVG-namespace supported shape child | Multiple shapes are not composited |+| Shape is one of: `<circle>`, `<ellipse>`, `<rect>` (optional rx/ry), `<path>`, `<polygon>` | These map to DrawingML geometry (preset or custom) |+| No `clip-rule` or `fill-rule`, whether direct or in inline `style` | DrawingML picture geometry has no equivalent winding-rule control |+| Used only on `<image>` or an exact imported crop wrapper | Shapes, groups, text, and generalized nested SVG targets are **forbidden** || SVG clip shape | DrawingML output ||---|---|-| `<circle>` / `<ellipse>` | Full-frame `<a:prstGeom prst="ellipse"/>`; child center/radii are not preserved |-| `<rect rx="..."/>` | Full-frame `<a:prstGeom prst="roundRect"/>` with one radius adjustment; child x/y/width/height are not preserved |+| `<circle>` / `<ellipse>` | Full-frame `<a:prstGeom prst="ellipse"/>`; the child must exactly cover the image frame. A `userSpaceOnUse` circle requires a square physical frame; a normalized `objectBoundingBox` circle may fill any frame |+| `<rect>` / `<rect rx="..."/>` | A plain full-frame rect is a compatible no-op; rounded form maps to full-frame `<a:prstGeom prst="roundRect"/>` with one physical radius adjustment. The rect must exactly cover the image frame and cannot express non-uniform physical corner radii || `<path>` / `<polygon>` | `<a:custGeom>` with coordinates mapped into the image frame |`clip-path` on shapes, groups, or text is forbidden; author the target geometrydirectly instead. Use a path/polygon clip when the intended contour does not-cover the full picture frame.+cover the full picture frame. A contour that depends on even-odd or another+explicit winding rule is outside this mapping and must be rebuilt as one+unambiguous visible contour or pre-rendered.---@@ -828,6 +832,47 @@ guesses a fallback.frame-fit. Match the image box to the source ratio or use `slice`. Do not applyfilters directly to `<image>`.+**Hard rule — picture frames and sources are explicit and decodable**: every+SVG `<image>` has explicit positive `width`/`height` and exactly one non-empty+`href` or compatible `xlink:href`. A data URI must use a supported `image/*`+MIME type, valid strict base64 when marked+`base64`, a non-empty payload, and bytes that decode as the declared format.+An external asset must resolve, use a supported extension, be non-empty, and+decode as that extension. The registered formats are PNG, JPEG, GIF, WebP,+BMP, TIFF, SVG, EMF, and WMF. Explicit template substitution tokens may remain+unresolved only during template checking; export requires the resolved image.+Missing, ambiguous, corrupt, mislabeled, or unsupported sources are errors and+must never be dropped or packaged as invalid zero-byte media.++**Hard rule — nested SVG is an imported crop transport, not a general+viewport**: every non-root `<svg>` must be the exact picture-crop wrapper emitted+by `pptx_to_svg`. The outer element has explicit registered project-geometry+`x`, `y`, positive `width`/`height`, a unit-coordinate `viewBox` made of four+ordinary decimal values, and+`preserveAspectRatio="none"`; it contains exactly one direct, empty `<image>`+with exactly one non-empty `href` or `xlink:href`, `x="0"`, `y="0"`, `width="1"`,+`height="1"`, and `preserveAspectRatio="none"`. Its ancestor chain contains+only the root SVG and ordinary visual `<g>` wrappers; definitions, text,+render-only geometry details, and other non-visual containers cannot own this+transport. The outer wrapper may additionally carry `id`, a supported+`transform`, registered structure metadata (`data-pptx-layer` or+`data-pptx-placeholder-carrier`), and the importer metadata+`data-pptx-frame`, `data-pptx-object`, `data-pptx-shape-id`,+`data-pptx-shape-name`, and `data-pptx-shape-scope`. A shape clip is present+only when exact `data-pptx-crop="1"` and a registered image-only `clip-path`+occur together and the local clip definition resolves. The inner image may+add only registered `opacity`. The `viewBox` must quantize without clamping to+a DrawingML `srcRect` with a positive visible region: each signed crop value+must fit the OOXML percentage integer range `-2147483648..2147483647`, while+`l + r < 100000` and+`t + b < 100000` preserve a positive visible region. Negative crop values and+crop windows extending outside the source unit rectangle are retained exactly,+not clamped. `0 0 1 1` is redundant and must be written as a plain `<image>`.+Extra visual children, indirect images, character data, unknown attributes,+malformed or unrepresentable crop coordinates, and generalized nested+viewports are errors. Checker and the converter share this parser so a nested+subtree cannot pass validation and then silently disappear during export.+| Overlay | Construction | Typical stops / alpha ||---|---|---|| Directional scrim | Linear rect, darkest beside text | `0%: 0.88; 55%: 0.30; 100%: 0` |diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex f17875a0..7e30b475 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -181,12 +181,18 @@ 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,+ project_clip_path_errors as _project_clip_path_errors,+ project_image_errors as _project_image_errors,+ project_nested_svg_crop_errors as _project_nested_svg_crop_errors,validate_single_line_text_run_advances as _validate_single_line_text_run_advances,validate_preset_geometry_metadata as _validate_preset_geometry_metadata,)except ImportError:_drawingml_text_frame_width_emu = None_estimate_single_line_text_frame_width = None+ _project_clip_path_errors = None+ _project_image_errors = None+ _project_nested_svg_crop_errors = None_validate_single_line_text_run_advances = None_validate_preset_geometry_metadata = None@@ -359,14 +365,12 @@ try:icon_search_dirs_for_svg as _icon_search_dirs_for_svg,project_root_for_svg_path as _project_root_for_svg_path,resolve_external_image_reference as _resolve_external_image_reference,- unresolved_external_image_reference_path as _unresolved_external_image_reference_path,)except ImportError:_SVG_WORK_DIR_NAMES = frozenset()_icon_search_dirs_for_svg = None_project_root_for_svg_path = None_resolve_external_image_reference = None- _unresolved_external_image_reference_path = NoneHEX_VALUE_RE = re.compile(@@ -427,7 +431,6 @@ _PPTX_STRUCTURE_SECTION_RE = re.compile(_PPTX_STRUCTURE_MODE_RE = re.compile(r"(?m)^-[ \t]+mode[ \t]*:[ \t]*([^\s#]+)[ \t]*(?:#.*)?$")-_CLIP_SHAPE_TAGS = frozenset({'circle', 'ellipse', 'rect', 'path', 'polygon'})_SUPPORTED_INLINE_STYLE_PROPERTIES = frozenset({'cx', 'cy', 'fill', 'fill-opacity', 'filter', 'flood-color','flood-opacity', 'font-family', 'font-size', 'font-style', 'font-weight',@@ -1158,6 +1161,10 @@ class SVGQualityChecker:# 1. Check viewBoxself._check_viewbox(root, result, expected_format)+ # 1a. Validate exact importer transport before compatible+ # inline geometry is materialized on the shared tree.+ self._check_nested_svg_crop_contract(root, result)+# 2. Check forbidden elementsself._check_forbidden_elements(content, root, result)@@ -1168,6 +1175,7 @@ class SVGQualityChecker:self._check_stroke_style_values(root, result)# 2c. Validate image fit/crop grammar and mappings.+ self._check_image_contract(root, svg_path, result)self._check_image_aspect_ratio_values(root, result)# 2d. Validate complete path-data and point-list grammar.@@ -1896,69 +1904,13 @@ class SVGQualityChecker:result: Dict,) -> None:"""Validate image clip paths against the native picture geometry mapping."""- definitions, _duplicates = _direct_defs_index(root)- issues: set[str] = set()- checked_clips: set[str] = set()- for elem in root.iter():- raw_ref = elem.get('clip-path')- if raw_ref is None or raw_ref.strip().lower() == 'none':- continue- label = _element_label(elem)- tag = _local_name(elem).lower()- is_imported_crop = tag == 'svg' and elem.get('data-pptx-crop') == '1'- if tag != 'image' and not is_imported_crop:- issues.add(- f"{label} clip-path is allowed only on <image> or an imported "- "data-pptx-crop=\"1\" wrapper"- )- match = re.fullmatch(r'url\(#([^)]+)\)', raw_ref.strip())- if match is None:- issues.add(- f"{label} clip-path must be an exact local url(#id) "- f"reference; got {raw_ref!r}"- )- continue- clip_id = match.group(1)- clip = definitions.get(clip_id)- if clip is None or _local_name(clip) != 'clipPath':- issues.add(- f"{label} clip-path=url(#{clip_id}) has no matching direct "- f"<defs><clipPath id=\"{clip_id}\"> definition"- )- continue- if clip_id in checked_clips:- continue- checked_clips.add(clip_id)- clip_label = f'<clipPath id="{clip_id}">'- clip_units = clip.get('clipPathUnits', 'userSpaceOnUse')- if clip_units not in {'userSpaceOnUse', 'objectBoundingBox'}:- issues.add(- f"{clip_label} has unsupported clipPathUnits={clip_units!r}"- )- if clip.get('transform'):- issues.add(f"{clip_label} cannot use transform")- visual_children = [- child for child in list(clip)- if _local_name(child) not in _NON_VISUAL_SVG_TAGS- ]- if len(visual_children) != 1:- issues.add(- f"{clip_label} must contain exactly one direct supported shape"- )- continue- shape = visual_children[0]- shape_tag = _local_name(shape).lower()- if shape_tag not in _CLIP_SHAPE_TAGS:- issues.add(- f"{clip_label} child <{shape_tag}> is unsupported; use "- "circle, ellipse, rect, path, or polygon"- )- if shape.get('transform'):- issues.add(- f"{clip_label} child <{shape_tag}> cannot use transform"- )-- result['errors'].extend(sorted(issues))+ if _project_clip_path_errors is None:+ result['errors'].append(+ 'Unable to import the clip-path validator; cannot verify '+ 'native picture geometry references'+ )+ return+ result['errors'].extend(_project_clip_path_errors(root))def _check_filter_effects(self, root: ET.Element, result: Dict) -> None:"""Validate filters against the native shadow/glow approximation."""@@ -2195,6 +2147,41 @@ class SVGQualityChecker:"for export.")+ def _check_nested_svg_crop_contract(+ self,+ root: ET.Element,+ result: Dict,+ ) -> None:+ """Reserve nested SVG for the imported picture-crop transport."""+ if _project_nested_svg_crop_errors is None:+ result['errors'].append(+ 'Unable to import the nested SVG crop validator; cannot '+ 'verify imported picture-crop wrappers'+ )+ return+ result['errors'].extend(_project_nested_svg_crop_errors(root))++ def _check_image_contract(+ self,+ root: ET.Element,+ svg_path: Path,+ result: Dict,+ ) -> None:+ """Validate picture frames, references, and bytes before export."""+ if _project_image_errors is None:+ result['errors'].append(+ 'Unable to import the image validator; cannot verify picture '+ 'frames or media'+ )+ return+ result['errors'].extend(+ _project_image_errors(+ root,+ svg_path.parent,+ allow_template_placeholders=self.template_mode,+ )+ )+def _check_freeform_geometry_values(self,root: ET.Element,@@ -2992,9 +2979,14 @@ class SVGQualityChecker:"""Check image file existence and resolution vs display size."""svg_dir = svg_path.parentchecked = set()+ parent_by_id = {+ id(child): parent+ for parent in root.iter()+ for child in list(parent)+ }for image in root.iter():- if _local_name(image).lower() != 'image':+ if image.tag != f'{{{SVG_NS}}}image':continuehref = image.get('href') or image.get(f'{{{XLINK_NS}}}href')@@ -3002,7 +2994,7 @@ class SVGQualityChecker:continueif self.template_mode and '{{' in href and '}}' in href:continue- if _resolve_external_image_reference is None or _unresolved_external_image_reference_path is None:+ if _resolve_external_image_reference is None:result['warnings'].append("Detected image references, but shared image resolver could not be imported; ""export will still validate them."@@ -3014,14 +3006,24 @@ class SVGQualityChecker:img_path = _resolve_external_image_reference(svg_dir, href)if img_path is None:- resolved_path = _unresolved_external_image_reference_path(svg_dir, href)- result['errors'].append(- f"Image file not found: {href} (resolved to {resolved_path})")+ # The shared image-source contract already reports the+ # blocking resolution failure. This pass adds quality advice+ # only for valid, resolved images.continue# Check resolution vs display size- display_w_str = image.get('width')- display_h_str = image.get('height')+ display_owner = image+ parent = parent_by_id.get(id(image))+ if (+ parent is not None+ and parent is not root+ and parent.tag == f'{{{SVG_NS}}}svg'+ ):+ # Imported crops use a unit-frame inner image. Quality advice+ # must compare the source against the visible outer frame.+ display_owner = parent+ display_w_str = display_owner.get('width')+ display_h_str = display_owner.get('height')if not display_w_str or not display_h_str:continuediff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 5d917eb6..97f78b93 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -69,6 +69,9 @@ from .elements import (convert_line, convert_path,convert_polygon, convert_polyline,convert_text, convert_image, convert_nested_svg,+ project_clip_path_errors,+ project_image_errors,+ project_nested_svg_crop_errors,)from ..animation_config import is_chrome_idfrom ..native_objects import (@@ -138,6 +141,54 @@ def _require_project_freeform_geometry()+def _require_project_nested_svg_crops(+ root: ET.Element,+ svg_path: Path | str,+) -> None:+ """Reject nested SVG outside the imported picture-crop transport."""+ errors = project_nested_svg_crop_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 nested SVG crop wrapper(s): '+ f'{preview}{suffix}'+ )+++def _require_project_clip_paths(+ root: ET.Element,+ svg_path: Path | str,+) -> None:+ """Reject clip references that cannot produce native picture geometry."""+ errors = project_clip_path_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 clip-path(s): '+ f'{preview}{suffix}'+ )+++def _require_project_images(+ root: ET.Element,+ svg_path: Path | str,+) -> None:+ """Reject invalid picture frames and unresolved or corrupt sources."""+ path = Path(svg_path)+ errors = project_image_errors(root, path.parent)+ if not errors:+ return+ preview = '; '.join(errors[:8])+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'+ raise SvgNativeConversionError(+ f'{path.name}: invalid project image(s): {preview}{suffix}'+ )++def _require_project_transforms(root: ET.Element,svg_path: Path | str,@@ -1183,7 +1234,10 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | Nonedef _local_tag(elem: ET.Element) -> str:- return elem.tag.split('}', 1)[-1] if isinstance(elem.tag, str) and '}' in elem.tag else str(elem.tag)+ if not isinstance(elem.tag, str):+ return str(elem.tag)+ prefix = f'{{{SVG_NS}}}'+ return elem.tag[len(prefix):] if elem.tag.startswith(prefix) else elem.tagdef collect_unsupported_visuals(@@ -1306,6 +1360,8 @@ def convert_svg_to_slide_shapes(tree = ET.parse(str(svg_path))root = tree.getroot()_require_chart_table_marker_attributes(root, svg_path)+ _require_project_nested_svg_crops(root, svg_path)+ _require_project_clip_paths(root, svg_path)authored_errors = validate_authored_preset_tree(root)if authored_errors:raise SvgNativeConversionError(@@ -1435,6 +1491,9 @@ 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_nested_svg_crops(root, svg_path)+ _require_project_images(root, svg_path)+ _require_project_clip_paths(root, svg_path)_require_project_text_properties(root, svg_path)_require_project_stroke_styles(root, svg_path)_require_project_opacities(root, svg_path)diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex d1a260b4..188c3993 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -8,6 +8,7 @@ import hashlibimport ioimport mathimport re+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyfrom urllib.parse import unquote_to_bytes@@ -49,9 +50,11 @@ from .utils import (detect_text_lang, estimate_text_cluster_widths, font_px_to_hpt,resolve_text_run_fonts, split_project_text_clusters,is_thick_circle_shorthand, parse_project_geometry_length,+ is_canonical_project_geometry_length,parse_project_image_aspect_ratio,parse_project_opacity,parse_project_stroke_dasharray,+ project_definition_index,matrix_multiply, parse_transform_matrix, parse_transform_operations,transform_point, _xml_escape,)@@ -81,33 +84,353 @@ def _resolve_external_image(svg_dir: Path, href: str) -> Path:raise FileNotFoundError(f'External image not found: {href}')+_PROJECT_IMAGE_FORMATS = {+ 'bmp': 'bmp',+ 'emf': 'emf',+ 'gif': 'gif',+ 'jpeg': 'jpg',+ 'jpg': 'jpg',+ 'png': 'png',+ 'svg': 'svg',+ 'svg+xml': 'svg',+ 'tif': 'tif',+ 'tiff': 'tiff',+ 'webp': 'webp',+ 'wmf': 'wmf',+ 'x-emf': 'emf',+ 'x-wmf': 'wmf',+}+_PIL_IMAGE_FORMATS = {+ 'bmp': 'BMP',+ 'gif': 'GIF',+ 'jpg': 'JPEG',+ 'png': 'PNG',+ 'tif': 'TIFF',+ 'tiff': 'TIFF',+ 'webp': 'WEBP',+}+++def _normalize_project_image_format(raw: str) -> str | None:+ return _PROJECT_IMAGE_FORMATS.get(raw.strip().lower().lstrip('.'))+++def _little_uint(data: bytes, offset: int, size: int) -> int:+ return int.from_bytes(data[offset:offset + size], 'little', signed=False)+++def _valid_emf_payload(data: bytes) -> bool:+ """Validate the EMF header and complete bounded record stream."""+ if len(data) < 88:+ return False+ header_size = _little_uint(data, 4, 4)+ total_size = _little_uint(data, 48, 4)+ record_count = _little_uint(data, 52, 4)+ header_palette_entries = _little_uint(data, 68, 4)+ if (+ _little_uint(data, 0, 4) != 1+ or data[40:44] != b' EMF'+ or header_size < 88+ or header_size > total_size+ or total_size != len(data)+ or record_count < 1+ ):+ return False++ offset = 0+ count = 0+ last_type = 0+ last_size = 0+ while offset < total_size:+ if offset + 8 > total_size:+ return False+ record_type = _little_uint(data, offset, 4)+ record_size = _little_uint(data, offset + 4, 4)+ if record_size < 8 or record_size % 4 or offset + record_size > total_size:+ return False+ record_end = offset + record_size+ if count == 0 and (record_type != 1 or record_size != header_size):+ return False+ if count > 0 and record_type == 1:+ return False+ if record_type == 14:+ if (+ record_size < 20+ or record_end != total_size+ or _little_uint(data, record_end - 4, 4) != record_size+ ):+ return False+ palette_entries = _little_uint(data, offset + 8, 4)+ palette_offset = _little_uint(data, offset + 12, 4)+ if (+ palette_entries != header_palette_entries+ or palette_entries and (+ palette_offset < 16+ or palette_offset + palette_entries * 4 > record_size - 4+ )+ ):+ return False+ offset = record_end+ count += 1+ last_type = record_type+ last_size = record_size+ return (+ offset == total_size+ # MS-EMF counts all records. LibreOffice-generated EMF files in the+ # wild count records after the header, so retain that interoperable+ # spelling while keeping the complete stream bounded.+ and count in {record_count, record_count + 1}+ and last_type == 14+ and last_size >= 20+ )+++def _valid_wmf_payload(data: bytes) -> bool:+ """Validate a standard or placeable WMF header and record stream."""+ meta_offset = 0+ if data.startswith(b'\xd7\xcd\xc6\x9a'):+ if len(data) < 40:+ return False+ checksum = 0+ for offset in range(0, 20, 2):+ checksum ^= _little_uint(data, offset, 2)+ if checksum != _little_uint(data, 20, 2):+ return False+ meta_offset = 22+ if len(data) < meta_offset + 24:+ return False+ meta_type = _little_uint(data, meta_offset, 2)+ header_words = _little_uint(data, meta_offset + 2, 2)+ version = _little_uint(data, meta_offset + 4, 2)+ total_words = _little_uint(data, meta_offset + 6, 4)+ max_record_words = _little_uint(data, meta_offset + 12, 4)+ if (+ meta_type not in {1, 2}+ or header_words != 9+ or version not in {0x0100, 0x0300}+ or total_words < 12+ or max_record_words < 3+ ):+ return False+ total_end = meta_offset + total_words * 2+ if total_end != len(data):+ return False++ offset = meta_offset + header_words * 2+ last_function = -1+ last_record_words = 0+ observed_max_record_words = 0+ while offset < total_end:+ if offset + 6 > total_end:+ return False+ record_words = _little_uint(data, offset, 4)+ function = _little_uint(data, offset + 4, 2)+ if (+ record_words < 3+ or record_words > max_record_words+ or offset + record_words * 2 > total_end+ ):+ return False+ record_end = offset + record_words * 2+ if function == 0 and (record_words != 3 or record_end != total_end):+ return False+ offset = record_end+ last_function = function+ last_record_words = record_words+ observed_max_record_words = max(+ observed_max_record_words,+ record_words,+ )+ return (+ offset == total_end+ and last_function == 0+ and last_record_words == 3+ and observed_max_record_words == max_record_words+ )+++def _valid_project_image_payload(img_format: str, img_data: bytes) -> bool:+ """Return whether bytes are a supported image of the declared format."""+ if not img_data:+ return False+ if img_format == 'svg':+ try:+ root = ET.fromstring(img_data)+ except ET.ParseError:+ return False+ return root.tag == f'{{{SVG_NS}}}svg'+ if img_format == 'emf':+ return _valid_emf_payload(img_data)+ if img_format == 'wmf':+ return _valid_wmf_payload(img_data)++ expected = _PIL_IMAGE_FORMATS.get(img_format)+ if expected is None:+ return False+ try:+ from PIL import Image, UnidentifiedImageError # type: ignore+ except ImportError:+ return False+ try:+ with Image.open(io.BytesIO(img_data)) as image:+ actual = (image.format or '').upper()+ image.verify()+ except (UnidentifiedImageError, OSError, ValueError, SyntaxError):+ return False+ return actual == expected++def _decode_data_image_uri(href: str) -> tuple[str, bytes] | None:- """Decode SVG image data URIs, including URL-encoded non-base64 payloads."""+ """Decode and validate one closed-project image data URI."""if not href.startswith('data:') or ',' not in href:return Noneheader, payload = href.split(',', 1)- match = re.match(r'data:image/([^;,]+)', header, flags=re.IGNORECASE)+ match = re.fullmatch(+ r'data:image/([A-Za-z0-9.+-]+)(?:;[^;,]*)*?(?:;base64)?',+ header,+ flags=re.IGNORECASE,+ )if not match:return None- img_format = match.group(1).lower()- if img_format == 'svg+xml':- img_format = 'svg'- elif img_format == 'jpeg':- img_format = 'jpg'+ img_format = _normalize_project_image_format(match.group(1))+ if img_format is None:+ return Noneis_base64 = any(part.strip().lower() == 'base64'for part in header.split(';')[1:])- if is_base64:- img_data = base64.b64decode(payload)- else:- img_data = unquote_to_bytes(payload)+ try:+ if is_base64:+ img_data = base64.b64decode(payload, validate=True)+ else:+ img_data = unquote_to_bytes(payload)+ except (ValueError, binascii.Error):+ return None+ if not _valid_project_image_payload(img_format, img_data):+ return Nonereturn img_format, img_data+@dataclass(frozen=True)+class ProjectImageSource:+ """Validated bytes and package extension for one SVG image reference."""++ img_format: str+ img_data: bytes+++def _project_image_href(elem: ET.Element) -> str:+ href_keys = tuple(+ key for key in ('href', f'{{{XLINK_NS}}}href')+ if key in elem.attrib+ )+ if len(href_keys) != 1:+ raise ValueError('requires exactly one href or xlink:href')+ href = elem.get(href_keys[0])+ if href is None or not href.strip():+ raise ValueError('href cannot be empty')+ return href+++def load_project_image_source(+ elem: ET.Element,+ svg_dir: Path | None,+) -> ProjectImageSource:+ """Load one exact SVG image source or raise a contract error."""+ if elem.tag != f'{{{SVG_NS}}}image':+ raise ValueError('expected an SVG-namespace <image> element')+ href = _project_image_href(elem)+ if href.startswith('data:'):+ decoded = _decode_data_image_uri(href)+ if decoded is None:+ raise ValueError(+ 'data URI must contain a supported, non-empty image with '+ 'valid encoding and bytes'+ )+ img_format, img_data = decoded+ return ProjectImageSource(img_format, img_data)++ if svg_dir is None:+ raise ValueError('external image requires an SVG directory context')+ try:+ img_path = _resolve_external_image(svg_dir, href)+ except FileNotFoundError as exc:+ raise ValueError(str(exc)) from exc+ img_format = _normalize_project_image_format(img_path.suffix)+ if img_format is None:+ raise ValueError(+ f'external image has unsupported file extension {img_path.suffix!r}'+ )+ try:+ img_data = img_path.read_bytes()+ except OSError as exc:+ raise ValueError(f'cannot read external image {href!r}: {exc}') from exc+ if not _valid_project_image_payload(img_format, img_data):+ raise ValueError(+ f'external image {href!r} is empty, corrupt, or does not match '+ f'its {img_path.suffix} extension'+ )+ return ProjectImageSource(img_format, img_data)+++def project_image_errors(+ root: ET.Element,+ svg_dir: Path | None,+ *,+ allow_template_placeholders: bool = False,+) -> list[str]:+ """Return source and frame errors for exact SVG image elements."""+ errors: list[str] = []+ for elem in root.iter():+ if elem.tag.rsplit('}', 1)[-1] != 'image':+ continue+ label = _element_contract_label(elem)+ if elem.tag != f'{{{SVG_NS}}}image':+ errors.append(+ f'{label} must use the SVG namespace '+ f'{SVG_NS!r}'+ )+ continue+ style_values = parse_inline_style(elem.get('style'))+ for attribute in ('width', 'height'):+ raw = style_values.get(attribute)+ if raw is None:+ raw = elem.get(attribute)+ if raw is None:+ errors.append(+ f'{label} requires explicit positive {attribute}'+ )+ continue+ try:+ value = parse_project_geometry_length(raw, attribute)+ except ValueError:+ # The shared geometry-length contract owns syntax diagnostics.+ continue+ if value <= 0:+ errors.append(+ f'{label} {attribute} must be positive; got {raw!r}'+ )+ try:+ raw_href = _project_image_href(elem)+ except ValueError as exc:+ errors.append(f'{label} invalid image source: {exc}')+ continue+ if (+ allow_template_placeholders+ and '{{' in raw_href+ and '}}' in raw_href+ ):+ continue+ try:+ load_project_image_source(elem, svg_dir)+ except ValueError as exc:+ errors.append(f'{label} invalid image source: {exc}')+ return sorted(errors)++def _wrap_shape(shape_id: int, name: str,off_x: int, off_y: int,@@ -2733,6 +3056,244 @@ def _clip_commands_to_geom(</a:custGeom>'''+_CLIP_SHAPE_TAGS = frozenset({'circle', 'ellipse', 'rect', 'path', 'polygon'})+_CLIP_NON_VISUAL_ELEMENTS = frozenset({+ f'{{{SVG_NS}}}{tag}' for tag in ('desc', 'metadata', 'style', 'title')+})+++def _element_contract_label(elem: ET.Element) -> str:+ tag = elem.tag.rsplit('}', 1)[-1]+ elem_id = (elem.get('id') or '').strip()+ return f'<{tag} id="{elem_id}">' if elem_id else f'<{tag}>'+++def _unsupported_clip_rule_properties(elem: ET.Element) -> tuple[str, ...]:+ style_values = parse_inline_style(elem.get('style'))+ return tuple(+ name for name in ('clip-rule', 'fill-rule')+ if elem.get(name) is not None or name in style_values+ )+++def _effective_clip_geometry_length(+ elem: ET.Element,+ attribute: str,+ *,+ default: float | None = None,+) -> float:+ style_values = parse_inline_style(elem.get('style'))+ raw = style_values.get(attribute)+ if raw is None:+ raw = elem.get(attribute)+ if raw is None:+ if default is None:+ raise ValueError(f'requires {attribute}')+ return default+ return parse_project_geometry_length(raw, attribute)+++def _clip_preset_geometry_error(+ target: ET.Element,+ shape: ET.Element,+ clip_units: str,+) -> str | None:+ """Reject primitive clips that cannot map to a full-frame preset."""+ shape_tag = shape.tag.rsplit('}', 1)[-1].lower()+ if shape_tag not in {'circle', 'ellipse', 'rect'}:+ return None+ target_label = _element_contract_label(target)+ try:+ target_x = _effective_clip_geometry_length(target, 'x', default=0.0)+ target_y = _effective_clip_geometry_length(target, 'y', default=0.0)+ target_w = _effective_clip_geometry_length(target, 'width')+ target_h = _effective_clip_geometry_length(target, 'height')+ except ValueError as exc:+ return f'cannot validate {shape_tag} against {target_label}: {exc}'+ if target_w <= 0 or target_h <= 0:+ return (+ f'cannot validate {shape_tag} against {target_label}: target '+ 'width and height must be positive'+ )++ object_bbox = clip_units == 'objectBoundingBox'+ expected_x = 0.0 if object_bbox else target_x+ expected_y = 0.0 if object_bbox else target_y+ expected_w = 1.0 if object_bbox else target_w+ expected_h = 1.0 if object_bbox else target_h++ def close(actual: float, expected: float) -> bool:+ return math.isclose(actual, expected, rel_tol=1e-9, abs_tol=1e-6)++ try:+ if shape_tag == 'circle':+ cx = _effective_clip_geometry_length(shape, 'cx', default=0.0)+ cy = _effective_clip_geometry_length(shape, 'cy', default=0.0)+ radius = _effective_clip_geometry_length(shape, 'r', default=0.0)+ fits = (+ close(expected_w, expected_h)+ and close(cx, expected_x + expected_w / 2.0)+ and close(cy, expected_y + expected_h / 2.0)+ and close(radius, expected_w / 2.0)+ )+ elif shape_tag == 'ellipse':+ cx = _effective_clip_geometry_length(shape, 'cx', default=0.0)+ cy = _effective_clip_geometry_length(shape, 'cy', default=0.0)+ rx = _effective_clip_geometry_length(shape, 'rx', default=0.0)+ ry = _effective_clip_geometry_length(shape, 'ry', default=0.0)+ fits = (+ close(cx, expected_x + expected_w / 2.0)+ and close(cy, expected_y + expected_h / 2.0)+ and close(rx, expected_w / 2.0)+ and close(ry, expected_h / 2.0)+ )+ else:+ rect_x = _effective_clip_geometry_length(shape, 'x', default=0.0)+ rect_y = _effective_clip_geometry_length(shape, 'y', default=0.0)+ rect_w = _effective_clip_geometry_length(shape, 'width', default=0.0)+ rect_h = _effective_clip_geometry_length(shape, 'height', default=0.0)+ fits = (+ close(rect_x, expected_x)+ and close(rect_y, expected_y)+ and close(rect_w, expected_w)+ and close(rect_h, expected_h)+ )+ if fits:+ rx_raw = (+ parse_inline_style(shape.get('style')).get('rx')+ or shape.get('rx')+ )+ ry_raw = (+ parse_inline_style(shape.get('style')).get('ry')+ or shape.get('ry')+ )+ rx = (+ parse_project_geometry_length(rx_raw, 'rx')+ if rx_raw is not None else None+ )+ ry = (+ parse_project_geometry_length(ry_raw, 'ry')+ if ry_raw is not None else None+ )+ if rx is None and ry is not None:+ rx = ry+ elif ry is None and rx is not None:+ ry = rx+ rx = rx or 0.0+ ry = ry or 0.0+ if rx > 0 or ry > 0:+ if object_bbox:+ fits = close(rx * target_w, ry * target_h)+ else:+ fits = close(rx, ry)+ except ValueError as exc:+ return f'{shape_tag} geometry for {target_label} is invalid: {exc}'++ if fits:+ return None+ return (+ f'{shape_tag} geometry must cover the complete frame of {target_label} '+ 'for native preset mapping; use path or polygon for partial, offset, '+ 'or non-uniform clips'+ )+++def project_clip_path_errors(root: ET.Element) -> list[str]:+ """Return clip-path errors that would otherwise degrade picture geometry."""+ definitions, duplicates = project_definition_index(root)+ errors: set[str] = set()+ for elem in root.iter():+ raw_ref = elem.get('clip-path')+ if raw_ref is None or raw_ref.strip().lower() == 'none':+ continue+ label = _element_contract_label(elem)+ is_svg_image = elem.tag == f'{{{SVG_NS}}}image'+ is_imported_crop = (+ elem.tag == f'{{{SVG_NS}}}svg'+ and elem.get('data-pptx-crop') == '1'+ )+ if not is_svg_image and not is_imported_crop:+ errors.add(+ f'{label} clip-path is allowed only on <image> or an imported '+ 'data-pptx-crop="1" wrapper'+ )+ match = re.fullmatch(r'url\(#([^)]+)\)', raw_ref.strip())+ if match is None:+ errors.add(+ f'{label} clip-path must be an exact local url(#id) '+ f'reference; got {raw_ref!r}'+ )+ continue+ clip_id = match.group(1)+ if clip_id in duplicates:+ errors.add(+ f'{label} clip-path=url(#{clip_id}) is ambiguous because the '+ 'definition id is duplicated'+ )+ continue+ clip = definitions.get(clip_id)+ if clip is None or clip.tag != f'{{{SVG_NS}}}clipPath':+ errors.add(+ f'{label} clip-path=url(#{clip_id}) has no matching direct '+ f'<defs><clipPath id="{clip_id}"> definition'+ )+ continue+ clip_label = f'<clipPath id="{clip_id}">'+ clip_units = clip.get('clipPathUnits', 'userSpaceOnUse')+ if clip_units not in {'userSpaceOnUse', 'objectBoundingBox'}:+ errors.add(+ f'{clip_label} has unsupported clipPathUnits={clip_units!r}'+ )+ if clip.get('transform'):+ errors.add(f'{clip_label} cannot use transform')+ clip_rules = _unsupported_clip_rule_properties(clip)+ if clip_rules:+ errors.add(+ f'{clip_label} cannot use {", ".join(clip_rules)}; native '+ 'picture geometry has no equivalent winding-rule control'+ )+ visual_children = [+ child for child in list(clip)+ if child.tag not in _CLIP_NON_VISUAL_ELEMENTS+ ]+ if len(visual_children) != 1:+ errors.add(+ f'{clip_label} must contain exactly one direct supported shape'+ )+ continue+ shape = visual_children[0]+ shape_tag = shape.tag.rsplit('}', 1)[-1].lower()+ if (+ shape_tag not in _CLIP_SHAPE_TAGS+ or shape.tag != f'{{{SVG_NS}}}{shape_tag}'+ ):+ errors.add(+ f'{clip_label} child <{shape_tag}> is unsupported; use '+ 'circle, ellipse, rect, path, or polygon'+ )+ continue+ if shape.get('transform'):+ errors.add(f'{clip_label} child <{shape_tag}> cannot use transform')+ continue+ shape_rules = _unsupported_clip_rule_properties(shape)+ if shape_rules:+ errors.add(+ f'{clip_label} child <{shape_tag}> cannot use '+ f'{", ".join(shape_rules)}; native picture geometry has no '+ 'equivalent winding-rule control'+ )+ continue+ if clip_units in {'userSpaceOnUse', 'objectBoundingBox'}:+ geometry_error = _clip_preset_geometry_error(+ elem,+ shape,+ clip_units,+ )+ if geometry_error is not None:+ errors.add(f'{clip_label} {geometry_error}')+ return sorted(errors)++def _resolve_clip_geometry(elem: ET.Element,ctx: ConvertContext,@@ -2917,7 +3478,13 @@ def _read_image_size(data: bytes) -> tuple[int | None, int | None]:try:with Image.open(io.BytesIO(data)) as img:return img.size- except (UnidentifiedImageError, OSError, ValueError):+ except (+ UnidentifiedImageError,+ OSError,+ SyntaxError,+ ValueError,+ ZeroDivisionError,+ ):return (None, None)@@ -3248,9 +3815,7 @@ def convert_image(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:to DrawingML picture geometry (prstGeom or custGeom) so the image isnatively clipped in PowerPoint."""- href = elem.get('href') or elem.get(f'{{{XLINK_NS}}}href')- if not href:- return None+ source = load_project_image_source(elem, ctx.svg_dir)# Raw coordinates (pre-context-transform) for clip path calculationsraw_x = svg_length_x(elem.get('x'), ctx)@@ -3270,22 +3835,10 @@ def convert_image(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:h = ctx_h(raw_h, ctx)if w <= 0 or h <= 0:- return None+ raise ValueError('image width and height must be positive')- # Extract image data- if href.startswith('data:'):- decoded = _decode_data_image_uri(href)- if decoded is None:- return None- img_format, img_data = decoded- else:- if ctx.svg_dir is None:- return None- img_path = _resolve_external_image(ctx.svg_dir, href)- img_format = img_path.suffix.lstrip('.').lower()- if img_format == 'jpeg':- img_format = 'jpg'- img_data = img_path.read_bytes()+ img_format = source.img_format+ img_data = source.img_dataimg_data, img_format = _optimize_image_for_pptx(elem, ctx, img_data, img_format, w, h,@@ -3462,7 +4015,277 @@ def convert_ellipse(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None# Without this converter, every cropped picture in a template-import SVG is# silently dropped on re-export.-def convert_nested_svg(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:+@dataclass(frozen=True)+class NestedSvgCropSpec:+ """Validated transport fields for one imported cropped picture."""++ image: ET.Element+ x: float+ y: float+ width: float+ height: float+ src_l: int+ src_t: int+ src_r: int+ src_b: int+++_NESTED_CROP_OUTER_ATTRIBUTES = frozenset({+ 'clip-path',+ 'data-pptx-crop',+ 'data-pptx-frame',+ 'data-pptx-layer',+ 'data-pptx-object',+ 'data-pptx-placeholder-carrier',+ 'data-pptx-shape-id',+ 'data-pptx-shape-name',+ 'data-pptx-shape-scope',+ 'id',+ 'preserveAspectRatio',+ 'transform',+ 'viewBox',+ 'x',+ 'y',+ 'width',+ 'height',+})+_NESTED_CROP_IMAGE_ATTRIBUTES = frozenset({+ 'href',+ f'{{{XLINK_NS}}}href',+ 'opacity',+ 'preserveAspectRatio',+ 'x',+ 'y',+ 'width',+ 'height',+})+_DRAWINGML_PERCENTAGE_MIN = -(2 ** 31)+_DRAWINGML_PERCENTAGE_MAX = 2 ** 31 - 1+++def _unsupported_nested_crop_attributes(+ elem: ET.Element,+ allowed: frozenset[str],+) -> list[str]:+ unsupported = []+ for name in elem.attrib:+ if name in allowed:+ continue+ unsupported.append(name.rsplit('}', 1)[-1])+ return sorted(unsupported)+++def parse_project_nested_svg_crop(elem: ET.Element) -> NestedSvgCropSpec:+ """Parse the closed nested-SVG transport written by ``pptx_to_svg``."""+ if elem.tag != f'{{{SVG_NS}}}svg':+ raise ValueError('expected an SVG-namespace nested <svg> crop wrapper')++ unsupported = _unsupported_nested_crop_attributes(+ elem,+ _NESTED_CROP_OUTER_ATTRIBUTES,+ )+ if unsupported:+ raise ValueError(+ 'nested crop <svg> has unsupported attribute(s): '+ + ', '.join(unsupported)+ )+ crop_marker = elem.get('data-pptx-crop')+ clip_path = elem.get('clip-path')+ if crop_marker is not None and crop_marker != '1':+ raise ValueError('nested crop data-pptx-crop must be exactly "1"')+ if clip_path is None:+ if crop_marker is not None:+ raise ValueError(+ 'nested crop data-pptx-crop="1" requires clip-path'+ )+ elif clip_path.strip().lower() == 'none':+ raise ValueError('nested crop clip-path cannot be "none"')+ elif crop_marker != '1':+ raise ValueError(+ 'nested crop clip-path requires data-pptx-crop="1"'+ )+ if elem.text and elem.text.strip():+ raise ValueError(+ 'nested crop <svg> cannot contain non-whitespace character data'+ )++ children = list(elem)+ if (+ len(children) != 1+ or children[0].tag != f'{{{SVG_NS}}}image'+ ):+ raise ValueError(+ 'nested <svg> is reserved for imported picture crops; expected '+ 'exactly one direct SVG-namespace <image> child'+ )+ image_elem = children[0]+ if image_elem.tail and image_elem.tail.strip():+ raise ValueError(+ 'nested crop <svg> cannot contain non-whitespace character data'+ )+ if list(image_elem) or (image_elem.text and image_elem.text.strip()):+ raise ValueError('nested crop <image> must be an empty element')++ unsupported = _unsupported_nested_crop_attributes(+ image_elem,+ _NESTED_CROP_IMAGE_ATTRIBUTES,+ )+ if unsupported:+ raise ValueError(+ 'nested crop <image> has unsupported attribute(s): '+ + ', '.join(unsupported)+ )++ try:+ _project_image_href(image_elem)+ except ValueError as exc:+ raise ValueError(f'nested crop <image> {exc}') from exc++ required_outer = (+ 'x',+ 'y',+ 'width',+ 'height',+ 'viewBox',+ 'preserveAspectRatio',+ )+ missing = [name for name in required_outer if elem.get(name) is None]+ if missing:+ raise ValueError(+ 'nested crop <svg> requires explicit x, y, width, height, '+ 'viewBox, and preserveAspectRatio="none"; missing '+ + ', '.join(missing)+ )+ if elem.get('preserveAspectRatio') != 'none':+ raise ValueError(+ 'nested crop <svg> preserveAspectRatio must be exactly "none"'+ )++ frame_values: dict[str, float] = {}+ for name in ('x', 'y', 'width', 'height'):+ raw = elem.get(name)+ assert raw is not None+ try:+ frame_values[name] = parse_project_geometry_length(raw, name)+ except ValueError as exc:+ raise ValueError(+ f'nested crop <svg> {name}={raw!r}: {exc}'+ ) from exc+ if frame_values['width'] <= 0 or frame_values['height'] <= 0:+ raise ValueError('nested crop <svg> width and height must be positive')++ view_box = elem.get('viewBox') or ''+ view_box_tokens = view_box.strip().split()+ if (+ len(view_box_tokens) != 4+ or any(+ not is_canonical_project_geometry_length(token)+ for token in view_box_tokens+ )+ ):+ raise ValueError(+ 'nested crop viewBox must contain four finite unitless ordinary '+ 'decimals separated by whitespace'+ )+ vb_x, vb_y, vb_w, vb_h = (+ parse_project_geometry_length(token, 'x')+ for token in view_box_tokens+ )+ if vb_w <= 0 or vb_h <= 0:+ raise ValueError('nested crop viewBox width and height must be positive')+ src_l = round(vb_x * 100000)+ src_t = round(vb_y * 100000)+ src_r = round((1.0 - vb_x - vb_w) * 100000)+ src_b = round((1.0 - vb_y - vb_h) * 100000)+ src_values = (src_l, src_t, src_r, src_b)+ if (+ any(+ value < _DRAWINGML_PERCENTAGE_MIN+ or value > _DRAWINGML_PERCENTAGE_MAX+ for value in src_values+ )+ or src_l + src_r >= 100000+ or src_t + src_b >= 100000+ ):+ raise ValueError(+ 'nested crop viewBox cannot be represented as a DrawingML '+ 'srcRect with a positive visible region within the signed '+ 'percentage range'+ )+ if not any(src_values):+ raise ValueError(+ 'nested crop viewBox="0 0 1 1" is redundant; use a plain <image>'+ )++ required_image_values = {+ 'x': '0',+ 'y': '0',+ 'width': '1',+ 'height': '1',+ 'preserveAspectRatio': 'none',+ }+ invalid_image_values = [+ f'{name}={image_elem.get(name)!r}'+ for name, expected in required_image_values.items()+ if image_elem.get(name) != expected+ ]+ if invalid_image_values:+ raise ValueError(+ 'nested crop <image> must use x="0", y="0", width="1", '+ 'height="1", and preserveAspectRatio="none"; got '+ + ', '.join(invalid_image_values)+ )++ return NestedSvgCropSpec(+ image=image_elem,+ x=frame_values['x'],+ y=frame_values['y'],+ width=frame_values['width'],+ height=frame_values['height'],+ src_l=src_l,+ src_t=src_t,+ src_r=src_r,+ src_b=src_b,+ )+++def project_nested_svg_crop_errors(root: ET.Element) -> list[str]:+ """Return contract errors for every nested SVG transport wrapper."""+ errors: list[str] = []+ parent_by_id = {+ id(child): parent+ for parent in root.iter()+ for child in list(parent)+ }+ for elem in root.iter():+ if elem is root or elem.tag.rsplit('}', 1)[-1] != 'svg':+ continue+ elem_id = (elem.get('id') or '').strip()+ label = f'<svg id="{elem_id}">' if elem_id else '<svg>'+ ancestor = parent_by_id.get(id(elem))+ invalid_ancestor: ET.Element | None = None+ while ancestor is not None and ancestor is not root:+ if (+ ancestor.tag != f'{{{SVG_NS}}}g'+ or ancestor.get('data-pptx-part') is not None+ ):+ invalid_ancestor = ancestor+ break+ ancestor = parent_by_id.get(id(ancestor))+ if invalid_ancestor is not None:+ errors.append(+ f'{label} invalid imported crop wrapper: visual ancestor chain '+ 'may contain only ordinary <g> elements'+ )+ continue+ try:+ parse_project_nested_svg_crop(elem)+ except ValueError as exc:+ errors.append(f'{label} invalid imported crop wrapper: {exc}')+ return sorted(errors)+++def convert_nested_svg(elem: ET.Element, ctx: ConvertContext) -> ShapeResult:"""Convert a nested <svg> sprite-crop wrapper to a DrawingML picture.Pattern produced by pptx_to_svg::@@ -3474,22 +4297,14 @@ def convert_nested_svg(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | NThe viewBox crops the unit-rectangle inner image; that crop is mapped to aDrawingML <a:srcRect> so PowerPoint can re-crop / "Reset Picture"."""- image_elem = elem.find(f'{{{SVG_NS}}}image')- if image_elem is None:- image_elem = elem.find('image')- if image_elem is None:- return None-- href = image_elem.get('href') or image_elem.get(f'{{{XLINK_NS}}}href')- if not href:- return None+ crop = parse_project_nested_svg_crop(elem)+ image_elem = crop.image+ source = load_project_image_source(image_elem, ctx.svg_dir)- svg_x = svg_length_x(elem.get('x'), ctx)- svg_y = svg_length_y(elem.get('y'), ctx)- svg_w = svg_length_x(elem.get('width'), ctx)- svg_h = svg_length_y(elem.get('height'), ctx)- if svg_w <= 0 or svg_h <= 0:- return None+ svg_x = crop.x+ svg_y = crop.y+ svg_w = crop.width+ svg_h = crop.heightif ctx.use_transform_matrix:x = svg_x@@ -3502,32 +4317,13 @@ def convert_nested_svg(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | Nw = ctx_w(svg_w, ctx)h = ctx_h(svg_h, ctx)- src_rect_xml = ''- view_box = elem.get('viewBox', '')- if view_box:- parts = view_box.strip().split()- if len(parts) == 4:- vb_x, vb_y, vb_w, vb_h = (float(p) for p in parts)- l = max(0, min(int(round(vb_x * 100000)), 100000))- t = max(0, min(int(round(vb_y * 100000)), 100000))- r = max(0, min(int(round((1.0 - vb_x - vb_w) * 100000)), 100000))- b = max(0, min(int(round((1.0 - vb_y - vb_h) * 100000)), 100000))- if l or t or r or b:- src_rect_xml = f'<a:srcRect l="{l}" t="{t}" r="{r}" b="{b}"/>'+ src_rect_xml = (+ f'<a:srcRect l="{crop.src_l}" t="{crop.src_t}" '+ f'r="{crop.src_r}" b="{crop.src_b}"/>'+ )- if href.startswith('data:'):- decoded = _decode_data_image_uri(href)- if decoded is None:- return None- img_format, img_data = decoded- else:- if ctx.svg_dir is None:- return None- img_path = _resolve_external_image(ctx.svg_dir, href)- img_format = img_path.suffix.lstrip('.').lower()- if img_format == 'jpeg':- img_format = 'jpg'- img_data = img_path.read_bytes()+ img_format = source.img_format+ img_data = source.img_dataimg_data, img_format = _optimize_image_for_pptx(image_elem, ctx, img_data, img_format, w, h,diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.pyindex 9d07cacf..772c27cb 100644--- a/skills/ppt-master/scripts/test_svg_quality_checker.py+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py@@ -32,6 +32,7 @@ from svg_to_pptx.drawingml.converter import (SvgNativeConversionError,convert_svg_to_slide_shapes,)+from svg_to_pptx.drawingml.elements import parse_project_nested_svg_cropfrom svg_to_pptx.drawingml.utils import (estimate_text_width,parse_inline_style,@@ -56,6 +57,12 @@ from svg_to_pptx.use_expander import UseExpansionError, expand_local_use_referenclass SVGQualityCheckerCompatibilityTests(unittest.TestCase):"""Keep supported aliases advisory and unsupported input blocking."""+ _TINY_PNG_URI = (+ 'data:image/png;base64,'+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'+ '+A8AAQUBAScY42YAAAAASUVORK5CYII='+ )+def _check(self, content: str) -> dict:with tempfile.TemporaryDirectory() as tmp_dir:svg_path = Path(tmp_dir) / 'fixture.svg'@@ -110,6 +117,773 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):):convert_svg_to_slide_shapes(svg_path)+ def _nested_crop_source(+ self,+ *,+ view_box: str = '0.1 0.2 0.7 0.6',+ outer_extra: str = '',+ inner: str | None = None,+ definitions: str = '',+ ancestor_start: str = '',+ ancestor_end: str = '',+ ) -> str:+ inner_markup = inner or (+ f'<image href="{self._TINY_PNG_URI}" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none"/>'+ )+ return (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink" '+ 'viewBox="0 0 640 360">'+ f'{definitions}{ancestor_start}'+ '<svg x="100" y="80" width="200" height="100" '+ f'viewBox="{view_box}" preserveAspectRatio="none"'+ f'{outer_extra}>{inner_markup}</svg>{ancestor_end}</svg>'+ )++ def test_imported_nested_crop_round_trips_to_native_src_rect(self):+ source = self._nested_crop_source(+ inner=(+ f'<image href="{self._TINY_PNG_URI}" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none" '+ 'opacity="0.8"/>'+ ),+ )+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'nested-crop.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<p:pic>'), 1)+ self.assertIn(+ '<a:srcRect l="10000" t="20000" r="20000" b="20000"/>',+ slide_xml,+ )+ self.assertIn('<a:alphaModFix amt="80000"/>', slide_xml)++ def test_nested_crop_accepts_registered_import_and_structure_metadata(self):+ source = self._nested_crop_source(+ outer_extra=(+ ' id="picture-carrier" data-pptx-frame="100 80 200 100"'+ ' data-pptx-layer="layout" data-pptx-object="picture"'+ ' data-pptx-placeholder-carrier="true"'+ ' data-pptx-shape-id="7" data-pptx-shape-name="Picture 7"'+ ' data-pptx-shape-scope="layout"'+ ),+ )+ root = ET.fromstring(source)+ wrappers = list(root.iter('{http://www.w3.org/2000/svg}svg'))+ crop = parse_project_nested_svg_crop(wrappers[1])+ self.assertEqual((crop.width, crop.height), (200.0, 100.0))++ def test_imported_nested_crop_preserves_signed_src_rect_values(self):+ cases = {+ '-0.1 0.2 1.05 0.7': (+ '<a:srcRect l="-10000" t="20000" r="5000" b="10000"/>'+ ),+ '1.2 0 0.1 1': (+ '<a:srcRect l="120000" t="0" r="-30000" b="0"/>'+ ),+ }+ for view_box, expected_src_rect in cases.items():+ with self.subTest(view_box=view_box):+ source = self._nested_crop_source(view_box=view_box)+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'signed-crop.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertIn(expected_src_rect, slide_xml)++ def test_generic_nested_svg_is_not_silently_dropped(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360">+ <svg x="100" y="80" width="200" height="100" viewBox="0 0 200 100">+ <rect x="0" y="0" width="200" height="100" fill="#FF0000"/>+ <text x="20" y="55" font-size="20">Nested</text>+ </svg>+</svg>'''+ self._assert_checker_and_exporter_reject(+ source,+ 'invalid imported crop wrapper',+ 'invalid nested SVG crop wrapper',+ )++ def test_nested_crop_cannot_hide_extra_visual_siblings(self):+ valid_inner = (+ f'<image href="{self._TINY_PNG_URI}" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none"/>'+ )+ source = self._nested_crop_source(+ inner=valid_inner + '<rect x="0" y="0" width="1" height="1"/>',+ )+ self._assert_checker_and_exporter_reject(+ source,+ 'expected exactly one direct SVG-namespace <image> child',+ 'expected exactly one direct SVG-namespace <image> child',+ )++ def test_nested_crop_clip_marker_and_reference_are_one_closed_contract(self):+ definitions = (+ '<defs><clipPath id="crop-clip" '+ 'clipPathUnits="objectBoundingBox">'+ '<ellipse cx="0.5" cy="0.5" rx="0.5" ry="0.5"/>'+ '</clipPath></defs>'+ )+ source = self._nested_crop_source(+ definitions=definitions,+ outer_extra=(+ ' data-pptx-crop="1" clip-path="url(#crop-clip)"'+ ),+ )+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'clipped-crop.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertIn('<a:prstGeom prst="ellipse">', slide_xml)++ invalid_sources = {+ 'clip without marker': self._nested_crop_source(+ definitions=definitions,+ outer_extra=' clip-path="url(#crop-clip)"',+ ),+ 'marker without clip': self._nested_crop_source(+ definitions=definitions,+ outer_extra=' data-pptx-crop="1"',+ ),+ 'missing clip': self._nested_crop_source(+ outer_extra=(+ ' data-pptx-crop="1" clip-path="url(#missing)"'+ ),+ ),+ 'malformed clip': self._nested_crop_source(+ outer_extra=' data-pptx-crop="1" clip-path="crop-clip"',+ ),+ }+ for name, invalid_source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ invalid_source,+ 'clip',+ 'clip',+ )++ def test_preset_clip_geometry_must_cover_the_complete_image_frame(self):+ def source_for(shape: str, *, units: str = 'userSpaceOnUse') -> str:+ return (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 100 100"><defs>'+ f'<clipPath id="clip" clipPathUnits="{units}">{shape}'+ '</clipPath></defs>'+ f'<image href="{self._TINY_PNG_URI}" x="10" y="20" '+ 'width="40" height="40" clip-path="url(#clip)"/></svg>'+ )++ valid_source = source_for(+ '<circle cx="30" cy="40" r="20"/>'+ )+ result = self._check(valid_source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'full-circle-clip.svg'+ svg_path.write_text(valid_source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertIn('<a:prstGeom prst="ellipse">', slide_xml)++ invalid_sources = {+ 'partial circle': source_for(+ '<circle cx="30" cy="40" r="10"/>'+ ),+ 'offset rect': source_for(+ '<rect x="15" y="20" width="35" height="40"/>'+ ),+ 'non-uniform rounded rect': source_for(+ '<rect x="10" y="20" width="40" height="40" '+ 'rx="4" ry="8"/>'+ ),+ }+ for name, source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'must cover the complete frame',+ 'invalid project clip-path',+ )++ def test_clip_definition_and_shape_require_the_svg_namespace(self):+ foreign_definition = (+ '<svg xmlns="http://www.w3.org/2000/svg" xmlns:q="urn:foreign" '+ 'viewBox="0 0 100 100"><defs>'+ '<q:clipPath id="clip"><q:circle cx="30" cy="40" r="20"/>'+ '</q:clipPath></defs>'+ f'<image href="{self._TINY_PNG_URI}" x="10" y="20" '+ 'width="40" height="40" clip-path="url(#clip)"/></svg>'+ )+ foreign_child = foreign_definition.replace(+ '<q:clipPath id="clip"><q:circle',+ '<clipPath id="clip"><q:circle',+ ).replace('</q:clipPath>', '</clipPath>')+ for name, source in {+ 'foreign definition': foreign_definition,+ 'foreign child': foreign_child,+ }.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'clip',+ 'invalid project clip-path',+ )++ def test_picture_clip_cannot_depend_on_a_winding_rule(self):+ def source_for(clip_extra: str, shape_extra: str) -> str:+ return (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 100 100"><defs>'+ f'<clipPath id="clip"{clip_extra}>'+ '<path d="M 10 20 L 50 20 L 50 60 L 10 60 Z"'+ f'{shape_extra}/></clipPath></defs>'+ f'<image href="{self._TINY_PNG_URI}" x="10" y="20" '+ 'width="40" height="40" clip-path="url(#clip)"/></svg>'+ )++ invalid_sources = {+ 'clipPath attribute': source_for(+ ' clip-rule="evenodd"',+ '',+ ),+ 'shape attribute': source_for(+ '',+ ' fill-rule="evenodd"',+ ),+ 'inline style': source_for(+ '',+ ' style="clip-rule: evenodd"',+ ),+ }+ for name, source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'winding-rule control',+ 'invalid project clip-path',+ )++ def test_nested_crop_requires_svg_namespace_and_visual_ancestry(self):+ foreign_inner = (+ f'<q:image xmlns:q="urn:foreign" href="{self._TINY_PNG_URI}" '+ 'x="0" y="0" width="1" height="1" '+ 'preserveAspectRatio="none"/>'+ )+ invalid_sources = {+ 'foreign image': self._nested_crop_source(inner=foreign_inner),+ 'defs ancestor': self._nested_crop_source(+ ancestor_start='<defs>',+ ancestor_end='</defs>',+ ),+ 'text ancestor': self._nested_crop_source(+ ancestor_start='<text x="0" y="0">',+ ancestor_end='</text>',+ ),+ 'render-only ancestor': self._nested_crop_source(+ ancestor_start='<g data-pptx-part="geometry-detail">',+ ancestor_end='</g>',+ ),+ 'render-only self': self._nested_crop_source(+ outer_extra=' data-pptx-part="geometry-detail"',+ ),+ }+ for name, source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'invalid imported crop wrapper',+ 'invalid nested SVG crop wrapper',+ )++ def test_plain_and_nested_images_share_strict_source_validation(self):+ truncated_emf = bytearray(44)+ truncated_emf[0:4] = b'\x01\x00\x00\x00'+ truncated_emf[40:44] = b' EMF'+ truncated_emf_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(truncated_emf)).decode('ascii')+ )+ truncated_wmf_uri = (+ 'data:image/x-wmf;base64,'+ + base64.b64encode(b'\xd7\xcd\xc6\x9a').decode('ascii')+ )+ fake_emf_eof = bytearray(96)+ fake_emf_eof[0:4] = (1).to_bytes(4, 'little')+ fake_emf_eof[4:8] = (88).to_bytes(4, 'little')+ fake_emf_eof[40:44] = b' EMF'+ fake_emf_eof[44:48] = (0x00010000).to_bytes(4, 'little')+ fake_emf_eof[48:52] = (96).to_bytes(4, 'little')+ fake_emf_eof[52:56] = (2).to_bytes(4, 'little')+ fake_emf_eof[88:92] = (14).to_bytes(4, 'little')+ fake_emf_eof[92:96] = (8).to_bytes(4, 'little')+ fake_emf_eof_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(fake_emf_eof)).decode('ascii')+ )+ duplicate_header_emf = bytearray(196)+ duplicate_header_emf[0:88] = fake_emf_eof[0:88]+ duplicate_header_emf[48:52] = (196).to_bytes(4, 'little')+ duplicate_header_emf[52:56] = (3).to_bytes(4, 'little')+ duplicate_header_emf[88:92] = (1).to_bytes(4, 'little')+ duplicate_header_emf[92:96] = (88).to_bytes(4, 'little')+ duplicate_header_emf[176:180] = (14).to_bytes(4, 'little')+ duplicate_header_emf[180:184] = (20).to_bytes(4, 'little')+ duplicate_header_emf[188:192] = (16).to_bytes(4, 'little')+ duplicate_header_emf[192:196] = (20).to_bytes(4, 'little')+ duplicate_header_emf_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(duplicate_header_emf)).decode('ascii')+ )+ early_eof_emf = bytearray(128)+ early_eof_emf[0:88] = fake_emf_eof[0:88]+ early_eof_emf[48:52] = (128).to_bytes(4, 'little')+ early_eof_emf[52:56] = (3).to_bytes(4, 'little')+ for offset in (88, 108):+ early_eof_emf[offset:offset + 4] = (14).to_bytes(4, 'little')+ early_eof_emf[offset + 4:offset + 8] = (20).to_bytes(+ 4,+ 'little',+ )+ early_eof_emf[offset + 12:offset + 16] = (16).to_bytes(+ 4,+ 'little',+ )+ early_eof_emf[offset + 16:offset + 20] = (20).to_bytes(+ 4,+ 'little',+ )+ early_eof_emf_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(early_eof_emf)).decode('ascii')+ )+ bad_size_last_emf = bytearray(108)+ bad_size_last_emf[0:88] = fake_emf_eof[0:88]+ bad_size_last_emf[48:52] = (108).to_bytes(4, 'little')+ bad_size_last_emf[88:92] = (14).to_bytes(4, 'little')+ bad_size_last_emf[92:96] = (20).to_bytes(4, 'little')+ bad_size_last_emf[100:104] = (16).to_bytes(4, 'little')+ bad_size_last_emf[104:108] = (16).to_bytes(4, 'little')+ bad_size_last_emf_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(bad_size_last_emf)).decode('ascii')+ )+ palette_mismatch_emf = bytearray(112)+ palette_mismatch_emf[0:88] = fake_emf_eof[0:88]+ palette_mismatch_emf[48:52] = (112).to_bytes(4, 'little')+ palette_mismatch_emf[88:92] = (14).to_bytes(4, 'little')+ palette_mismatch_emf[92:96] = (24).to_bytes(4, 'little')+ palette_mismatch_emf[96:100] = (1).to_bytes(4, 'little')+ palette_mismatch_emf[100:104] = (16).to_bytes(4, 'little')+ palette_mismatch_emf[108:112] = (24).to_bytes(4, 'little')+ palette_mismatch_emf_uri = (+ 'data:image/x-emf;base64,'+ + base64.b64encode(bytes(palette_mismatch_emf)).decode('ascii')+ )+ valid_wmf = bytes.fromhex(+ '0100 0900 0003 0c000000 0000 03000000 0000 '+ '03000000 0000'+ )+ invalid_version_wmf = bytearray(valid_wmf)+ invalid_version_wmf[4:6] = b'\x00\x00'+ invalid_version_wmf_uri = (+ 'data:image/x-wmf;base64,'+ + base64.b64encode(bytes(invalid_version_wmf)).decode('ascii')+ )+ inflated_max_wmf = bytearray(valid_wmf)+ inflated_max_wmf[12:16] = (4).to_bytes(4, 'little')+ inflated_max_wmf_uri = (+ 'data:image/x-wmf;base64,'+ + base64.b64encode(bytes(inflated_max_wmf)).decode('ascii')+ )+ oversized_eof_wmf = bytes.fromhex(+ '0100 0900 0003 0d000000 0000 04000000 0000 '+ '04000000 0000 0000'+ )+ oversized_eof_wmf_uri = (+ 'data:image/x-wmf;base64,'+ + base64.b64encode(oversized_eof_wmf).decode('ascii')+ )+ early_eof_wmf = bytes.fromhex(+ '0100 0900 0003 0f000000 0000 03000000 0000 '+ '03000000 0000 03000000 0000'+ )+ early_eof_wmf_uri = (+ 'data:image/x-wmf;base64,'+ + base64.b64encode(early_eof_wmf).decode('ascii')+ )+ plain_sources = {+ 'missing href': (+ '<image x="10" y="10" width="40" height="40"/>'+ ),+ 'empty href': (+ '<image href="" x="10" y="10" width="40" height="40"/>'+ ),+ 'dual href': (+ f'<image href="{self._TINY_PNG_URI}" '+ f'xlink:href="{self._TINY_PNG_URI}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'invalid base64': (+ '<image href="data:image/png;base64,%%%" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'empty payload': (+ '<image href="data:image/png;base64," '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'wrong mime': (+ '<image href="data:text/plain;base64,QQ==" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'invalid image bytes': (+ '<image href="data:image/png;base64,QQ==" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'truncated emf': (+ f'<image href="{truncated_emf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'truncated wmf': (+ f'<image href="{truncated_wmf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'truncated emf eof record': (+ f'<image href="{fake_emf_eof_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'duplicate emf header': (+ f'<image href="{duplicate_header_emf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'nonfinal emf eof record': (+ f'<image href="{early_eof_emf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'mismatched emf eof size-last': (+ f'<image href="{bad_size_last_emf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'mismatched emf palette count': (+ f'<image href="{palette_mismatch_emf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'invalid wmf version': (+ f'<image href="{invalid_version_wmf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'inflated wmf maximum record': (+ f'<image href="{inflated_max_wmf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'oversized wmf eof record': (+ f'<image href="{oversized_eof_wmf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ 'nonfinal wmf eof record': (+ f'<image href="{early_eof_wmf_uri}" '+ 'x="10" y="10" width="40" height="40"/>'+ ),+ }+ for name, image_markup in plain_sources.items():+ with self.subTest(kind='plain', name=name):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink" '+ f'viewBox="0 0 100 100">{image_markup}</svg>'+ )+ self._assert_checker_and_exporter_reject(+ source,+ 'invalid image source',+ 'invalid project image',+ )++ nested_inner = (+ '<image href="data:image/png;base64,%%%" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none"/>'+ )+ self._assert_checker_and_exporter_reject(+ self._nested_crop_source(inner=nested_inner),+ 'invalid image source',+ 'invalid project image',+ )++ def test_external_image_bytes_must_match_their_extension(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ '<image href="broken.png" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'fixture.svg'+ svg_path.write_text(source, encoding='utf-8')+ (Path(tmp_dir) / 'broken.png').write_bytes(b'not a png')+ result = SVGQualityChecker().check_file(str(svg_path))+ self.assertFalse(result['passed'])+ self.assertIn('does not match', '\n'.join(result['errors']))+ with self.assertRaisesRegex(+ SvgNativeConversionError,+ 'invalid project image',+ ):+ convert_svg_to_slide_shapes(svg_path)++ def test_images_require_explicit_positive_dimensions(self):+ image_cases = {+ 'missing width': (+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'height="40"/>'+ ),+ 'missing height': (+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="40"/>'+ ),+ 'zero width': (+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="0" height="40"/>'+ ),+ 'zero height': (+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="40" height="0"/>'+ ),+ 'style overrides width with zero': (+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="40" height="40" style="width: 0"/>'+ ),+ }+ for name, image_markup in image_cases.items():+ with self.subTest(name=name):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ f'viewBox="0 0 100 100">{image_markup}</svg>'+ )+ self._assert_checker_and_exporter_reject(+ source,+ 'positive',+ 'invalid project image',+ )++ def test_compatible_inline_image_dimensions_remain_exportable(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'style="width: 40px; height: 40px"/></svg>'+ )+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'inline-image-frame.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<p:pic>'), 1)++ def test_external_svg_image_is_a_registered_source_format(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ '<image href="asset.svg" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ asset = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">'+ '<rect width="10" height="10" fill="#2563EB"/></svg>'+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'fixture.svg'+ svg_path.write_text(source, encoding='utf-8')+ (Path(tmp_dir) / 'asset.svg').write_text(asset, encoding='utf-8')+ result = SVGQualityChecker().check_file(str(svg_path))+ self.assertTrue(result['passed'])+ _slide_xml, media_files, *_rest = convert_svg_to_slide_shapes(+ svg_path+ )+ self.assertEqual(tuple(media_files), ('s1_img1.svg',))++ def test_complete_wmf_record_stream_is_a_registered_source_format(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ '<image href="asset.wmf" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ # Standard 18-byte METAHEADER plus one 6-byte META_EOF record.+ asset = bytes.fromhex(+ '0100 0900 0003 0c000000 0000 03000000 0000 '+ '03000000 0000'+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'fixture.svg'+ svg_path.write_text(source, encoding='utf-8')+ (Path(tmp_dir) / 'asset.wmf').write_bytes(asset)+ result = SVGQualityChecker().check_file(str(svg_path))+ self.assertTrue(result['passed'])+ _slide_xml, media_files, *_rest = convert_svg_to_slide_shapes(+ svg_path+ )+ self.assertEqual(tuple(media_files), ('s1_img1.wmf',))++ def test_complete_emf_record_stream_is_a_registered_source_format(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">'+ '<image href="asset.emf" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ # Minimal nondegenerate EMR_HEADER plus EMR_EOF. Accept both the+ # MS-EMF all-record count and LibreOffice's post-header count, plus a+ # legal EOF carrying one palette entry.+ cases = ((2, 0), (1, 0), (2, 1))+ for record_count, palette_entries in cases:+ with self.subTest(+ record_count=record_count,+ palette_entries=palette_entries,+ ):+ eof_size = 20 + palette_entries * 4+ asset = bytearray(88 + eof_size)+ asset[0:4] = (1).to_bytes(4, 'little')+ asset[4:8] = (88).to_bytes(4, 'little')+ asset[8:24] = b''.join(+ value.to_bytes(4, 'little', signed=True)+ for value in (0, 0, 100, 100)+ )+ asset[24:40] = b''.join(+ value.to_bytes(4, 'little', signed=True)+ for value in (0, 0, 2540, 2540)+ )+ asset[40:44] = b' EMF'+ asset[44:48] = (0x00010000).to_bytes(4, 'little')+ asset[48:52] = len(asset).to_bytes(4, 'little')+ asset[52:56] = record_count.to_bytes(4, 'little')+ asset[68:72] = palette_entries.to_bytes(4, 'little')+ asset[72:80] = b''.join(+ value.to_bytes(4, 'little') for value in (100, 100)+ )+ asset[80:88] = b''.join(+ value.to_bytes(4, 'little') for value in (25, 25)+ )+ asset[88:92] = (14).to_bytes(4, 'little')+ asset[92:96] = eof_size.to_bytes(4, 'little')+ asset[96:100] = palette_entries.to_bytes(4, 'little')+ asset[100:104] = (16).to_bytes(4, 'little')+ asset[-4:] = eof_size.to_bytes(4, 'little')+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'fixture.svg'+ svg_path.write_text(source, encoding='utf-8')+ (Path(tmp_dir) / 'asset.emf').write_bytes(asset)+ result = SVGQualityChecker().check_file(str(svg_path))+ self.assertTrue(result['passed'])+ _slide_xml, media_files, *_rest = (+ convert_svg_to_slide_shapes(svg_path)+ )+ self.assertEqual(tuple(media_files), ('s1_img1.emf',))++ def test_template_image_token_does_not_bypass_href_cardinality(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink" '+ 'viewBox="0 0 100 100">'+ '<image href="{{IMAGE}}" xlink:href="other.png" '+ 'x="10" y="10" width="40" height="40"/></svg>'+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'template.svg'+ svg_path.write_text(source, encoding='utf-8')+ result = SVGQualityChecker(template_mode=True).check_file(+ str(svg_path)+ )+ self.assertFalse(result['passed'])+ self.assertIn(+ 'requires exactly one href or xlink:href',+ '\n'.join(result['errors']),+ )++ def test_foreign_namespace_visuals_fail_checker_and_exporter_preflight(self):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:q="urn:foreign" viewBox="0 0 100 100">'+ f'<q:image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ self._assert_checker_and_exporter_reject(+ source,+ 'must use the SVG namespace',+ 'invalid project image',+ )++ def test_unnamespaced_image_fails_checker_and_exporter_preflight(self):+ source = (+ '<svg viewBox="0 0 100 100">'+ f'<image href="{self._TINY_PNG_URI}" x="10" y="10" '+ 'width="40" height="40"/></svg>'+ )+ self._assert_checker_and_exporter_reject(+ source,+ 'must use the SVG namespace',+ 'invalid project image',+ )++ def test_nested_crop_contract_rejects_malformed_transport_wrappers(self):+ valid_inner = (+ f'<image href="{self._TINY_PNG_URI}" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none"/>'+ )+ invalid_sources = {+ 'indirect image': self._nested_crop_source(+ inner=f'<g>{valid_inner}</g>',+ ),+ 'empty href': self._nested_crop_source(+ inner=(+ '<image href="" x="0" y="0" width="1" height="1" '+ 'preserveAspectRatio="none"/>'+ ),+ ),+ 'dual href': self._nested_crop_source(+ inner=(+ f'<image href="{self._TINY_PNG_URI}" '+ f'xlink:href="{self._TINY_PNG_URI}" x="0" y="0" '+ 'width="1" height="1" preserveAspectRatio="none"/>'+ ),+ ),+ 'non-unit image': self._nested_crop_source(+ inner=valid_inner.replace('width="1"', 'width="2"'),+ ),+ 'inner transform': self._nested_crop_source(+ inner=valid_inner.replace('/>', ' transform="translate(1 0)"/>'),+ ),+ 'inner style geometry': self._nested_crop_source(+ inner=valid_inner.replace('/>', ' style="width: 1px"/>'),+ ),+ 'outer paint': self._nested_crop_source(outer_extra=' fill="#FF0000"'),+ 'outer style geometry': self._nested_crop_source(+ outer_extra=' style="width: 200px; height: 100px"',+ ),+ 'unknown metadata': self._nested_crop_source(+ outer_extra=' data-pptx-unknown="value"',+ ),+ 'wrong outer fit': self._nested_crop_source().replace(+ 'viewBox="0.1 0.2 0.7 0.6" preserveAspectRatio="none"',+ 'viewBox="0.1 0.2 0.7 0.6" preserveAspectRatio="xMidYMid meet"',+ ),+ 'comma viewBox': self._nested_crop_source(view_box='0.1,0.2,0.7,0.6'),+ 'exponent viewBox': self._nested_crop_source(view_box='1e-1 0.2 0.7 0.6'),+ 'out-of-range percentage': self._nested_crop_source(+ view_box='21474.83648 0 0.1 1',+ ),+ 'collapsed crop': self._nested_crop_source(view_box='0 0 0.000001 1'),+ 'redundant crop': self._nested_crop_source(view_box='0 0 1 1'),+ }+ for name, source in invalid_sources.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ source,+ 'invalid imported crop wrapper',+ 'invalid nested SVG crop wrapper',+ )+def test_canonical_generated_spelling_has_no_compatibility_warning(self):result = self._check('''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">