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): enforce closed opacity contracts

hugohe3e6030b78e56e
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 07e69dc3..0d5b8715 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -628,8 +628,8 @@ alias for `rgba()` on a fill-only object.
accepts finite numeric values that SVG/CSS clamps into that interval;
`stop-opacity` and `flood-opacity` additionally accept finite percentages. The
checker reports those supported non-default spellings as recommendation warnings.
-Malformed or non-finite values remain errors because the exporter cannot
-preserve their intent.
+Malformed or non-finite values are errors in both Checker and exporter
+preflight; neither substitutes an opaque default for unknown intent.
`fill="transparent"` / `stroke="transparent"` become no fill/line; use a color
plus alpha when a painted transparent layer must remain represented. Prefer
descendant alpha over group opacity when isolated compositing matters (§2.2).
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index b2f58db7..01c5dd3f 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -57,12 +57,17 @@ try:
DRAWINGML_TEXT_FONT_SIZE_MAX as _DRAWINGML_TEXT_FONT_SIZE_MAX,
DRAWINGML_TEXT_FONT_SIZE_MIN as _DRAWINGML_TEXT_FONT_SIZE_MIN,
IDENTITY_MATRIX as _IDENTITY_MATRIX,
+ PROJECT_OPACITY_PROPERTIES as _OPACITY_PROPERTIES,
+ PROJECT_PERCENTAGE_OPACITY_PROPERTIES as _PERCENTAGE_OPACITY_PROPERTIES,
format_project_geometry_length as _format_project_geometry_length,
format_project_image_aspect_ratio as _format_project_image_aspect_ratio,
+ format_project_opacity as _format_project_opacity,
font_px_to_hpt as _font_px_to_hpt,
is_canonical_project_geometry_length as _is_canonical_project_geometry_length,
+ is_project_opacity_default_form as _is_project_opacity_default_form,
iter_project_geometry_lengths as _iter_project_geometry_lengths,
iter_project_image_aspect_ratios as _iter_project_image_aspect_ratios,
+ iter_project_opacities as _iter_project_opacities,
iter_project_stroke_styles as _iter_project_stroke_styles,
iter_project_transforms as _iter_project_transforms,
matrix_multiply as _matrix_multiply,
@@ -73,11 +78,13 @@ try:
parse_inline_style as _parse_inline_style,
parse_project_geometry_length as _parse_project_geometry_length,
parse_project_image_aspect_ratio as _parse_project_image_aspect_ratio,
+ parse_project_opacity as _parse_project_opacity,
parse_project_stroke_dasharray as _parse_project_stroke_dasharray,
parse_project_stroke_enum as _parse_project_stroke_enum,
parse_svg_color as _parse_export_color,
parse_svg_length as _parse_export_length,
project_image_aspect_ratio_errors as _project_image_aspect_ratio_errors,
+ project_opacity_errors as _project_opacity_errors,
project_stroke_style_errors as _project_stroke_style_errors,
project_transform_errors as _project_transform_errors,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
@@ -87,12 +94,17 @@ except ImportError:
_DRAWINGML_TEXT_FONT_SIZE_MAX = None
_DRAWINGML_TEXT_FONT_SIZE_MIN = None
_IDENTITY_MATRIX = None
+ _OPACITY_PROPERTIES = None
+ _PERCENTAGE_OPACITY_PROPERTIES = None
_format_project_geometry_length = None
_format_project_image_aspect_ratio = None
+ _format_project_opacity = None
_font_px_to_hpt = None
_is_canonical_project_geometry_length = None
+ _is_project_opacity_default_form = None
_iter_project_geometry_lengths = None
_iter_project_image_aspect_ratios = None
+ _iter_project_opacities = None
_iter_project_stroke_styles = None
_iter_project_transforms = None
_matrix_multiply = None
@@ -103,11 +115,13 @@ except ImportError:
_parse_inline_style = None
_parse_project_geometry_length = None
_parse_project_image_aspect_ratio = None
+ _parse_project_opacity = None
_parse_project_stroke_dasharray = None
_parse_project_stroke_enum = None
_parse_export_color = None
_parse_export_length = None
_project_image_aspect_ratio_errors = None
+ _project_opacity_errors = None
_project_stroke_style_errors = None
_project_transform_errors = None
_rect_to_dml_xfrm = None
@@ -372,13 +386,6 @@ _DEFINITION_TAGS = frozenset({
'pattern',
'radialGradient',
})
-_ALPHA_PROPERTIES = (
- 'opacity',
- 'fill-opacity',
- 'stroke-opacity',
- 'stop-opacity',
- 'flood-opacity',
-)
_SUPPORTED_INLINE_STYLE_PROPERTIES = frozenset({
'cx', 'cy', 'fill', 'fill-opacity', 'filter', 'flood-color',
'flood-opacity', 'font-family', 'font-size', 'font-style', 'font-weight',
@@ -804,49 +811,6 @@ def _element_label(elem: ET.Element) -> str:
return f'<{tag} id="{elem_id}">' if elem_id else f'<{tag}>'
-def _finite_unit_interval(raw: str) -> float | None:
- """Parse a finite unitless number in the closed interval ``0..1``."""
- if re.fullmatch(_NUMBER_TOKEN, raw.strip()) is None:
- return None
- try:
- value = float(raw)
- except ValueError:
- return None
- if not math.isfinite(value) or not 0.0 <= value <= 1.0:
- return None
- return value
-
-
-def _compatible_opacity(
- raw: str,
- *,
- allow_percentage: bool = False,
-) -> float | None:
- """Parse a finite opacity form supported by the matching converter path.
-
- Every exported opacity path accepts and clamps unitless numbers. Gradient
- stops and filter flood alpha additionally accept percentages; ordinary
- element, fill, stroke, text, picture, and group opacity paths do not.
- """
- value_text = raw.strip()
- is_percent = value_text.endswith('%')
- if is_percent and not allow_percentage:
- return None
- if is_percent:
- value_text = value_text[:-1].strip()
- if re.fullmatch(_NUMBER_TOKEN, value_text) is None:
- return None
- try:
- value = float(value_text)
- except ValueError:
- return None
- if not math.isfinite(value):
- return None
- if is_percent:
- value /= 100.0
- return max(0.0, min(1.0, value))
-
-
def _normalized_gradient_value(raw: str) -> float | None:
"""Parse a normalized gradient coordinate or percentage."""
value_text = raw.strip()
@@ -1114,7 +1078,10 @@ class SVGQualityChecker:
# 2e. Validate complete transform grammar and native mappings.
self._check_transform_values(root, result)
- # 2f. Validate the closed authoring-property surface and
+ # 2f. Validate opacity grammar and native alpha mappings.
+ self._check_opacity_values(root, result)
+
+ # 2g. Validate the closed authoring-property surface and
# conditional definition interfaces before export.
self._check_authoring_property_contract(root, result)
self._check_paint_compatibility(root, result)
@@ -1123,10 +1090,10 @@ class SVGQualityChecker:
self._check_marker_contract(root, result)
self._check_clip_path_contract(root, result)
- # 2g. Validate the supported shadow/glow filter interface.
+ # 2h. Validate the supported shadow/glow filter interface.
self._check_filter_effects(root, result)
- # 2h. Validate gradient definitions, stops, and coordinates.
+ # 2i. Validate gradient definitions, stops, and coordinates.
self._check_gradient_interfaces(root, result)
# 3. Check font-size values
@@ -1437,12 +1404,6 @@ class SVGQualityChecker:
)
result['errors'].extend(sorted(paint_reference_errors))
- @staticmethod
- def _canonical_alpha_literal(value: float) -> str:
- """Return a compact deterministic alpha literal in the closed interval."""
- bounded = max(0.0, min(1.0, value))
- return f'{bounded:.6f}'.rstrip('0').rstrip('.') or '0'
-
def _check_paint_compatibility(
self,
root: ET.Element,
@@ -1454,9 +1415,14 @@ class SVGQualityChecker:
valid input; the checker only warns when that spelling differs from the
generated-SVG default (uppercase ``#RRGGBB`` plus explicit alpha).
"""
- if _parse_export_color is None:
+ if (
+ _PERCENTAGE_OPACITY_PROPERTIES is None
+ or _format_project_opacity is None
+ or _parse_export_color is None
+ or _parse_project_opacity is None
+ ):
result['warnings'].append(
- "Unable to import svg_to_pptx color parser; skipped paint syntax check"
+ "Unable to import svg_to_pptx paint parsers; skipped paint syntax check"
)
return
@@ -1530,23 +1496,25 @@ class SVGQualityChecker:
existing_alpha_raw = (
style_values.get(alpha_name) or elem.get(alpha_name)
)
- existing_alpha = (
- _compatible_opacity(
- existing_alpha_raw,
- allow_percentage=alpha_name in {
- 'stop-opacity',
- 'flood-opacity',
- },
- )
- if existing_alpha_raw is not None else 1.0
- )
+ if existing_alpha_raw is None:
+ existing_alpha = 1.0
+ else:
+ try:
+ existing_alpha = _parse_project_opacity(
+ existing_alpha_raw,
+ allow_percentage=(
+ alpha_name in _PERCENTAGE_OPACITY_PROPERTIES
+ ),
+ )
+ except ValueError:
+ existing_alpha = None
effective_alpha = (
color_alpha * existing_alpha
if existing_alpha is not None else color_alpha
)
replacement += (
f' {alpha_name}=\"'
- f'{self._canonical_alpha_literal(effective_alpha)}\"'
+ f'{_format_project_opacity(effective_alpha)}\"'
)
elif color_alpha < 1.0:
replacement += (
@@ -1597,36 +1565,122 @@ class SVGQualityChecker:
"href. No change is required for export."
)
+ def _check_opacity_values(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Reject malformed opacity and advise generated-SVG values."""
+ helpers = (
+ _PERCENTAGE_OPACITY_PROPERTIES,
+ _format_project_opacity,
+ _is_project_opacity_default_form,
+ _iter_project_opacities,
+ _parse_inline_style,
+ _parse_project_opacity,
+ _project_opacity_errors,
+ )
+ if any(helper is None for helper in helpers):
+ result['warnings'].append(
+ "Unable to import svg_to_pptx opacity validators; native "
+ "export will still validate opacity syntax."
+ )
+ return
+
+ result['errors'].extend(_project_opacity_errors(root))
+ recommendations: Counter[tuple[str, str, str]] = Counter()
+ examples: Dict[tuple[str, str, str], List[str]] = defaultdict(list)
+ fidelity_warnings: set[str] = set()
+
+ for elem, property_name, raw, source in _iter_project_opacities(root):
+ try:
+ value = _parse_project_opacity(
+ raw,
+ allow_percentage=(
+ property_name in _PERCENTAGE_OPACITY_PROPERTIES
+ ),
+ )
+ except ValueError:
+ continue
+ if _is_project_opacity_default_form(raw):
+ continue
+ normalized = _format_project_opacity(value)
+ key = (property_name, raw, normalized)
+ recommendations[key] += 1
+ label = f'{_element_label(elem)} {source}'
+ if label not in examples[key] and len(examples[key]) < 3:
+ examples[key].append(label)
+
+ for elem in root.iter():
+ if _local_name(elem).lower() != 'g':
+ continue
+ style_values = _parse_inline_style(elem.get('style'))
+ raw_opacity = (
+ style_values['opacity']
+ if 'opacity' in style_values else elem.get('opacity')
+ )
+ if raw_opacity is None:
+ continue
+ try:
+ opacity = _parse_project_opacity(raw_opacity)
+ except ValueError:
+ continue
+ if opacity < 1.0:
+ fidelity_warnings.add(
+ f"Fidelity warning: {_element_label(elem)} uses group "
+ f"opacity={raw_opacity!r}. The converter distributes this "
+ "alpha to descendants and cannot preserve isolated group "
+ "compositing; generated SVG should prefer descendant alpha. "
+ "Existing input remains convertible and does not require "
+ "modification."
+ )
+
+ for (property_name, raw, normalized), count in sorted(
+ recommendations.items()
+ ):
+ shown_examples = ', '.join(
+ examples[(property_name, raw, normalized)]
+ )
+ result['warnings'].append(
+ f"Recommendation: {property_name}={raw!r} is "
+ f"converter-compatible in {count} location(s) "
+ f"({shown_examples}); generated SVG should prefer "
+ f'{property_name}="{normalized}". No change is required '
+ "for export."
+ )
+ result['warnings'].extend(sorted(fidelity_warnings))
+
def _check_authoring_property_contract(
self,
root: ET.Element,
result: Dict,
) -> None:
- """Validate inline CSS and alpha values against the authoring surface."""
+ """Validate inline CSS and attributes against the authoring surface."""
errors: set[str] = set()
- recommendations: set[str] = set()
- fidelity_warnings: set[str] = set()
+ opacity_properties = _OPACITY_PROPERTIES or ()
for elem in root.iter():
label = _element_label(elem)
- style_declarations: list[tuple[str, str]] = []
for fragment in (elem.get('style') or '').split(';'):
fragment = fragment.strip()
if not fragment:
continue
if ':' not in fragment:
- errors.add(
- f"{label} has malformed inline style declaration {fragment!r}"
- )
+ if fragment.lower() not in opacity_properties:
+ errors.add(
+ f"{label} has malformed inline style declaration "
+ f"{fragment!r}"
+ )
continue
name, value = fragment.split(':', 1)
name = name.strip().lower()
value = value.strip()
if not name or not value:
- errors.add(
- f"{label} has malformed inline style declaration {fragment!r}"
- )
+ if name not in opacity_properties:
+ errors.add(
+ f"{label} has malformed inline style declaration "
+ f"{fragment!r}"
+ )
continue
- style_declarations.append((name, value))
if name in _BAKE_REQUIRED_VISUAL_PROPERTIES:
errors.add(
f"{label} uses Bake-required visual property {name!r}; "
@@ -1650,63 +1704,7 @@ class SVGQualityChecker:
"bake the effect or rebuild it with supported geometry"
)
- for name in _ALPHA_PROPERTIES:
- direct_value = elem.get(name)
- alpha_entries = []
- if direct_value is not None:
- alpha_entries.append((name, direct_value))
- alpha_entries.extend(
- (f'style {name}', style_value)
- for style_name, style_value in style_declarations
- if style_name == name
- )
- for entry_name, raw_value in alpha_entries:
- allow_percentage = name in {'stop-opacity', 'flood-opacity'}
- compatible_value = _compatible_opacity(
- raw_value,
- allow_percentage=allow_percentage,
- )
- if compatible_value is None:
- accepted_form = (
- 'a finite number or percentage opacity'
- if allow_percentage
- else 'a finite unitless numeric opacity'
- )
- errors.add(
- f"{label} {entry_name} must be {accepted_form}; "
- f"got {raw_value!r}"
- )
- elif _finite_unit_interval(raw_value) is None:
- recommendations.add(
- f"Recommendation: {label} {entry_name}={raw_value!r} "
- "is converter-compatible; generated SVG should prefer "
- f"the unitless 0..1 value "
- f"{self._canonical_alpha_literal(compatible_value)!r}. "
- "No change is required for export."
- )
-
- if _local_name(elem).lower() != 'g':
- continue
- style_opacity = next((
- value for name, value in reversed(style_declarations)
- if name == 'opacity'
- ), None)
- raw_opacity = style_opacity if style_opacity is not None else elem.get('opacity')
- if raw_opacity is None:
- continue
- opacity = _compatible_opacity(raw_opacity)
- if opacity is not None and opacity < 1.0:
- fidelity_warnings.add(
- f"Fidelity warning: {label} uses group opacity={raw_opacity!r}. "
- "The converter distributes this alpha to descendants and "
- "cannot preserve isolated group compositing; generated SVG "
- "should prefer descendant alpha. Existing input remains "
- "convertible and does not require modification."
- )
-
result['errors'].extend(sorted(errors))
- result['warnings'].extend(sorted(recommendations))
- result['warnings'].extend(sorted(fidelity_warnings))
def _check_definition_contract(
self,
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 98c6a2c8..a43c67c4 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -40,6 +40,7 @@ from .utils import (
parse_transform_matrix,
project_geometry_length_errors,
project_image_aspect_ratio_errors,
+ project_opacity_errors,
project_stroke_style_errors,
project_transform_errors,
resolve_url_id,
@@ -133,6 +134,22 @@ def _require_project_image_aspect_ratios(
)
+def _require_project_opacities(
+ root: ET.Element,
+ svg_path: Path | str,
+) -> None:
+ """Reject malformed opacity values before native conversion."""
+ errors = project_opacity_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 opacity value(s): '
+ f'{preview}{suffix}'
+ )
+
+
# ---------------------------------------------------------------------------
# Transform & layout helpers
# ---------------------------------------------------------------------------
@@ -1178,6 +1195,7 @@ def convert_svg_to_slide_shapes(
_require_project_freeform_geometry(root, svg_path)
_require_project_stroke_styles(root, svg_path)
+ _require_project_opacities(root, svg_path)
_require_project_image_aspect_ratios(root, svg_path)
_require_project_transforms(root, svg_path)
@@ -1239,6 +1257,7 @@ def convert_svg_to_slide_shapes(
# Recheck compiler-injected icon/use wrappers and cloned definition trees.
_require_project_stroke_styles(root, svg_path)
+ _require_project_opacities(root, svg_path)
_require_project_image_aspect_ratios(root, svg_path)
_require_project_transforms(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.py
index 74453aef..25587b1c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -41,6 +41,7 @@ from .utils import (
detect_text_lang, font_px_to_hpt, resolve_text_run_fonts,
is_thick_circle_shorthand, parse_project_geometry_length,
parse_project_image_aspect_ratio,
+ parse_project_opacity,
parse_project_stroke_dasharray,
matrix_multiply, parse_transform_matrix, parse_transform_operations,
transform_point, _xml_escape,
@@ -1923,10 +1924,7 @@ def _text_opacity_ratio(value: str | None) -> float:
"""Parse a text opacity component and clamp it to the SVG ``0..1`` range."""
if value is None:
return 1.0
- try:
- return max(0.0, min(1.0, float(value)))
- except ValueError:
- return 1.0
+ return parse_project_opacity(value)
def _override_run_attrs(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
index 661f2da0..5bcacdb8 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
@@ -72,7 +72,10 @@ def build_gradient_fill(
direct_stop_op = child.get('stop-opacity')
if direct_stop_op is not None and 'stop-opacity' not in style_values:
- stop_opacity *= parse_opacity(direct_stop_op)
+ stop_opacity *= parse_opacity(
+ direct_stop_op,
+ allow_percentage=True,
+ )
alpha_xml = ''
effective_opacity = combine_opacity(stop_opacity, opacity)
@@ -598,7 +601,11 @@ def _parse_filter_params(
dy = _f(child.get('dy'), 0.0)
if abs(dx) > 0.01 or abs(dy) > 0.01:
has_offset = True
- paint_opacity = parse_opacity(effect_attr('flood-opacity'), 0.3)
+ paint_opacity = parse_opacity(
+ effect_attr('flood-opacity'),
+ 0.3,
+ allow_percentage=True,
+ )
parsed_color, parsed_alpha = parse_svg_color(
effect_attr('flood-color', '#000000')
)
@@ -613,7 +620,11 @@ def _parse_filter_params(
if abs(dx) > 0.01 or abs(dy) > 0.01:
has_offset = True
elif tag == 'feFlood':
- paint_opacity = parse_opacity(effect_attr('flood-opacity'), 0.3)
+ paint_opacity = parse_opacity(
+ effect_attr('flood-opacity'),
+ 0.3,
+ allow_percentage=True,
+ )
parsed_color, parsed_alpha = parse_svg_color(
effect_attr('flood-color', '#000000')
)
@@ -791,11 +802,8 @@ def get_element_opacity(
op = parse_inline_style(elem.get('style')).get('opacity') or elem.get('opacity')
if op is None:
return base if base < 1.0 else None
- try:
- val = base * max(0.0, min(1.0, float(op)))
- return val if val < 1.0 else None
- except ValueError:
- return base if base < 1.0 else None
+ val = base * parse_opacity(op)
+ return val if val < 1.0 else None
def get_fill_opacity(
@@ -810,18 +818,12 @@ def get_fill_opacity(
base = ctx.opacity_multiplier if ctx is not None else 1.0
op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
- if op:
- try:
- base *= max(0.0, min(1.0, float(op)))
- except ValueError:
- pass
+ if op is not None:
+ base *= parse_opacity(op)
fill_op = _get_attr(elem, 'fill-opacity', ctx) if ctx else elem.get('fill-opacity')
- if fill_op:
- try:
- base *= max(0.0, min(1.0, float(fill_op)))
- except ValueError:
- pass
+ if fill_op is not None:
+ base *= parse_opacity(fill_op)
return base if base < 1.0 else None
@@ -838,17 +840,11 @@ def get_stroke_opacity(
base = ctx.opacity_multiplier if ctx is not None else 1.0
op = _get_attr(elem, 'opacity', ctx) if ctx else elem.get('opacity')
- if op:
- try:
- base *= max(0.0, min(1.0, float(op)))
- except ValueError:
- pass
+ if op is not None:
+ base *= parse_opacity(op)
stroke_op = _get_attr(elem, 'stroke-opacity', ctx) if ctx else elem.get('stroke-opacity')
- if stroke_op:
- try:
- base *= max(0.0, min(1.0, float(stroke_op)))
- except ValueError:
- pass
+ if stroke_op is not None:
+ base *= parse_opacity(stroke_op)
return base if base < 1.0 else None
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index 6424e08b..84ae37a6 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -1,7 +1,8 @@
"""Coordinate, transform, color, and font helpers for DrawingML conversion.
-See references/shared-standards.md §2.1, §6.5, §6.6, and §6.8 for project
-geometry, image-fit, line-presentation, and transform authoring contracts.
+See references/shared-standards.md §2.1, §6.2, §6.5, §6.6, and §6.8 for
+project geometry, opacity, image-fit, line-presentation, and transform
+authoring contracts.
"""
from __future__ import annotations
@@ -161,6 +162,17 @@ PROJECT_IMAGE_ASPECT_RATIO_ANCHORS = {
'xMaxYMax': (1.0, 1.0),
}
PROJECT_IMAGE_ASPECT_RATIO_MODES = frozenset({'meet', 'slice'})
+PROJECT_OPACITY_PROPERTIES = (
+ 'opacity',
+ 'fill-opacity',
+ 'stroke-opacity',
+ 'stop-opacity',
+ 'flood-opacity',
+)
+PROJECT_PERCENTAGE_OPACITY_PROPERTIES = frozenset({
+ 'stop-opacity',
+ 'flood-opacity',
+})
THICK_CIRCLE_COVERAGE_TOLERANCE = 1.0
@@ -327,6 +339,41 @@ def format_project_geometry_length(value: float) -> str:
return '0' if text in {'', '-0'} else text
+def parse_project_opacity(
+ raw: str,
+ *,
+ allow_percentage: bool = False,
+) -> float:
+ """Parse and clamp one opacity value from the closed project grammar."""
+ try:
+ number, unit = _parse_svg_length_parts(raw)
+ except ValueError as exc:
+ raise ValueError('must be one finite numeric opacity') from exc
+
+ if unit == '%':
+ if not allow_percentage:
+ raise ValueError('must be unitless; percentages are not supported')
+ number /= 100.0
+ elif unit:
+ raise ValueError(f'uses unsupported unit {unit!r}')
+ return max(0.0, min(1.0, number))
+
+
+def is_project_opacity_default_form(raw: str) -> bool:
+ """Return whether opacity uses the generated finite unitless ``0..1`` form."""
+ try:
+ number, unit = _parse_svg_length_parts(raw)
+ except ValueError:
+ return False
+ return unit == '' and 0.0 <= number <= 1.0
+
+
+def format_project_opacity(value: float) -> str:
+ """Format one parsed opacity as a compact unitless ``0..1`` value."""
+ bounded = max(0.0, min(1.0, value))
+ return f'{bounded:.6f}'.rstrip('0').rstrip('.') or '0'
+
+
def parse_project_image_aspect_ratio(raw: str | None) -> tuple[str, str]:
"""Parse the closed project ``<image>`` aspect-ratio grammar."""
if raw is None:
@@ -1321,6 +1368,52 @@ def project_image_aspect_ratio_errors(root: ET.Element) -> list[str]:
return errors
+def iter_project_opacities(
+ root: ET.Element,
+) -> Iterator[tuple[ET.Element, str, str, str]]:
+ """Yield project opacity values as element, property, raw value, source."""
+ for elem in root.iter():
+ for property_name in PROJECT_OPACITY_PROPERTIES:
+ raw = elem.get(property_name)
+ if raw is not None:
+ yield elem, property_name, raw, 'attribute'
+
+ for fragment in (elem.get('style') or '').split(';'):
+ fragment = fragment.strip()
+ if not fragment:
+ continue
+ if ':' in fragment:
+ name, raw = fragment.split(':', 1)
+ name = name.strip().lower()
+ raw = raw.strip()
+ else:
+ name = fragment.lower()
+ raw = ''
+ if name in PROJECT_OPACITY_PROPERTIES:
+ yield elem, name, raw, 'inline style'
+
+
+def project_opacity_errors(root: ET.Element) -> list[str]:
+ """Return blocking project opacity errors for converter preflight."""
+ errors: list[str] = []
+ for elem, property_name, raw, source in iter_project_opacities(root):
+ tag = _svg_element_tag(elem) or str(elem.tag)
+ elem_id = elem.get('id')
+ label = f'<{tag} id={elem_id!r}>' if elem_id else f'<{tag}>'
+ try:
+ parse_project_opacity(
+ raw,
+ allow_percentage=(
+ property_name in PROJECT_PERCENTAGE_OPACITY_PROPERTIES
+ ),
+ )
+ except ValueError as exc:
+ errors.append(
+ f'{label} {source} {property_name}={raw!r}: {exc}'
+ )
+ return errors
+
+
def _finite_float(raw: str) -> float:
"""Parse a finite floating-point number."""
value = float(raw)
@@ -1349,14 +1442,16 @@ def _parse_alpha_channel(raw: str) -> float:
return max(0.0, min(1.0, value))
-def parse_opacity(raw: str | None, default: float = 1.0) -> float:
- """Parse a number or percentage opacity, falling back to ``default``."""
+def parse_opacity(
+ raw: str | None,
+ default: float = 1.0,
+ *,
+ allow_percentage: bool = False,
+) -> float:
+ """Parse one project opacity or return the code-owned missing default."""
if raw is None:
return max(0.0, min(1.0, default))
- try:
- return _parse_alpha_channel(raw)
- except ValueError:
- return max(0.0, min(1.0, default))
+ return parse_project_opacity(raw, allow_percentage=allow_percentage)
def _functional_color_parts(body: str) -> tuple[list[str], str | None]:
@@ -1482,7 +1577,10 @@ def parse_stop_style(style_str: str) -> tuple[str | None, float]:
if 'stop-color' in style_values:
color, color_alpha = parse_svg_color(style_values['stop-color'])
if 'stop-opacity' in style_values:
- stop_opacity = parse_opacity(style_values['stop-opacity'])
+ stop_opacity = parse_opacity(
+ style_values['stop-opacity'],
+ allow_percentage=True,
+ )
return color, color_alpha * stop_opacity