deckkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. deckkit/__init__.py +12 -0
  2. deckkit/_bundled_fonts.py +54 -0
  3. deckkit/_diagnostics.py +48 -0
  4. deckkit/_font_assets/SOURCES.txt +9 -0
  5. deckkit/_font_assets/SourceCodePro-Bold.ttf +0 -0
  6. deckkit/_font_assets/SourceCodePro-BoldIt.ttf +0 -0
  7. deckkit/_font_assets/SourceCodePro-It.ttf +0 -0
  8. deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
  9. deckkit/_font_assets/SourceCodePro-Regular.ttf +0 -0
  10. deckkit/_font_assets/SourceSans3-Bold.ttf +0 -0
  11. deckkit/_font_assets/SourceSans3-BoldIt.ttf +0 -0
  12. deckkit/_font_assets/SourceSans3-It.ttf +0 -0
  13. deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
  14. deckkit/_font_assets/SourceSans3-Regular.ttf +0 -0
  15. deckkit/_variable_evaluation.py +82 -0
  16. deckkit/animation.py +211 -0
  17. deckkit/annotations.py +161 -0
  18. deckkit/backends/__init__.py +1 -0
  19. deckkit/backends/_font_embedding.py +41 -0
  20. deckkit/backends/_pptx_fonts.py +230 -0
  21. deckkit/backends/_pptx_shadows.py +241 -0
  22. deckkit/backends/_pptx_tables.py +251 -0
  23. deckkit/backends/pptx.py +1225 -0
  24. deckkit/backends/pptx_animation.py +175 -0
  25. deckkit/backends/svg.py +527 -0
  26. deckkit/canvas/__init__.py +40 -0
  27. deckkit/canvas/_geometry.py +49 -0
  28. deckkit/canvas/clipping.py +336 -0
  29. deckkit/canvas/context.py +34 -0
  30. deckkit/canvas/elements.py +306 -0
  31. deckkit/canvas/path.py +250 -0
  32. deckkit/canvas/scene.py +74 -0
  33. deckkit/canvas/style.py +31 -0
  34. deckkit/charts/__init__.py +59 -0
  35. deckkit/charts/axes.py +249 -0
  36. deckkit/charts/chart.py +244 -0
  37. deckkit/charts/content.py +132 -0
  38. deckkit/charts/context.py +45 -0
  39. deckkit/charts/interval.py +166 -0
  40. deckkit/charts/legends.py +82 -0
  41. deckkit/charts/marks.py +410 -0
  42. deckkit/charts/scales.py +205 -0
  43. deckkit/citations.py +200 -0
  44. deckkit/compiler.py +410 -0
  45. deckkit/context.py +72 -0
  46. deckkit/deck.py +168 -0
  47. deckkit/drawables/__init__.py +42 -0
  48. deckkit/drawables/bounds.py +17 -0
  49. deckkit/drawables/connector.py +22 -0
  50. deckkit/drawables/drawable.py +38 -0
  51. deckkit/drawables/ellipse.py +21 -0
  52. deckkit/drawables/group.py +10 -0
  53. deckkit/drawables/image.py +14 -0
  54. deckkit/drawables/line.py +18 -0
  55. deckkit/drawables/path.py +78 -0
  56. deckkit/drawables/rectangle.py +24 -0
  57. deckkit/drawables/rich_text.py +176 -0
  58. deckkit/drawables/table.py +42 -0
  59. deckkit/drawables/text.py +29 -0
  60. deckkit/effects.py +84 -0
  61. deckkit/expanded_views.py +561 -0
  62. deckkit/fonts.py +329 -0
  63. deckkit/geometry.py +48 -0
  64. deckkit/identity.py +72 -0
  65. deckkit/layout.py +398 -0
  66. deckkit/layouts/__init__.py +20 -0
  67. deckkit/layouts/_content.py +27 -0
  68. deckkit/layouts/annotations.py +217 -0
  69. deckkit/layouts/containers.py +202 -0
  70. deckkit/layouts/grid.py +299 -0
  71. deckkit/layouts/modifiers.py +200 -0
  72. deckkit/layouts/primitives.py +213 -0
  73. deckkit/layouts/table.py +139 -0
  74. deckkit/measurement.py +420 -0
  75. deckkit/paint.py +73 -0
  76. deckkit/py.typed +0 -0
  77. deckkit/reconcile.py +119 -0
  78. deckkit/semantic.py +47 -0
  79. deckkit/theme.py +364 -0
  80. deckkit/themes/__init__.py +91 -0
  81. deckkit/themes/clarity.py +98 -0
  82. deckkit/tokens.py +226 -0
  83. deckkit/units.py +73 -0
  84. deckkit/variables.py +212 -0
  85. deckkit/view_expansion.py +185 -0
  86. deckkit/views/__init__.py +100 -0
  87. deckkit/views/_code_source.py +42 -0
  88. deckkit/views/_drawing.py +52 -0
  89. deckkit/views/canvas.py +27 -0
  90. deckkit/views/code.py +481 -0
  91. deckkit/views/code_evolution.py +284 -0
  92. deckkit/views/composite_view.py +19 -0
  93. deckkit/views/divider.py +38 -0
  94. deckkit/views/ellipse.py +38 -0
  95. deckkit/views/grid.py +156 -0
  96. deckkit/views/hstack.py +43 -0
  97. deckkit/views/image.py +43 -0
  98. deckkit/views/layout_view.py +30 -0
  99. deckkit/views/line.py +31 -0
  100. deckkit/views/modifier_views.py +281 -0
  101. deckkit/views/path.py +36 -0
  102. deckkit/views/primitive_view.py +16 -0
  103. deckkit/views/pygments_highlighter.py +67 -0
  104. deckkit/views/rectangle.py +61 -0
  105. deckkit/views/section_number.py +21 -0
  106. deckkit/views/semantic/__init__.py +51 -0
  107. deckkit/views/semantic/before_after.py +109 -0
  108. deckkit/views/semantic/bullet_graph.py +216 -0
  109. deckkit/views/semantic/card.py +129 -0
  110. deckkit/views/semantic/code_block.py +41 -0
  111. deckkit/views/semantic/diff.py +642 -0
  112. deckkit/views/semantic/estimate_interval.py +137 -0
  113. deckkit/views/semantic/figure.py +55 -0
  114. deckkit/views/semantic/item_list.py +171 -0
  115. deckkit/views/semantic/metric.py +74 -0
  116. deckkit/views/semantic/pill.py +69 -0
  117. deckkit/views/semantic/pipeline.py +94 -0
  118. deckkit/views/semantic/pipeline_stage.py +59 -0
  119. deckkit/views/semantic/semantic_view.py +76 -0
  120. deckkit/views/semantic/sparkline.py +164 -0
  121. deckkit/views/semantic/table.py +439 -0
  122. deckkit/views/semantic/terminal.py +361 -0
  123. deckkit/views/semantic/timeline.py +158 -0
  124. deckkit/views/slide.py +37 -0
  125. deckkit/views/slide_number.py +20 -0
  126. deckkit/views/slides/__init__.py +16 -0
  127. deckkit/views/slides/section_slide.py +89 -0
  128. deckkit/views/slides/slide_margins.py +32 -0
  129. deckkit/views/slides/slide_with_margins.py +22 -0
  130. deckkit/views/slides/title_and_content.py +49 -0
  131. deckkit/views/slides/title_and_content_slide.py +55 -0
  132. deckkit/views/spacer.py +45 -0
  133. deckkit/views/stack.py +36 -0
  134. deckkit/views/text.py +142 -0
  135. deckkit/views/view.py +229 -0
  136. deckkit/views/vstack.py +31 -0
  137. deckkit/views/zstack.py +27 -0
  138. deckkit-0.1.0.dist-info/METADATA +123 -0
  139. deckkit-0.1.0.dist-info/RECORD +144 -0
  140. deckkit-0.1.0.dist-info/WHEEL +5 -0
  141. deckkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  142. deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
  143. deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
  144. deckkit-0.1.0.dist-info/top_level.txt +1 -0
deckkit/annotations.py ADDED
@@ -0,0 +1,161 @@
1
+ """Anchor-relative overlays resolved after their content has been measured."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass
7
+ from typing import Callable, Literal
8
+
9
+ from .canvas import Stroke
10
+ from .context import Context
11
+ from .drawables.connector import DEFAULT_CONNECTOR_WIDTH
12
+ from .expanded_views import ExpandedConnector, ExpandedMetadata
13
+ from .geometry import RelativePoint
14
+ from .identity import ViewIdentity
15
+ from .layout import ExportedAnchor
16
+ from .layouts import AnnotatedLayout, ConnectorLayout
17
+ from .layouts.annotations import (
18
+ ResolvedAnchor,
19
+ ResolvedAnnotation,
20
+ ResolvedConnector,
21
+ ResolvedLabel,
22
+ )
23
+ from .theme import Color, ColorStyle, PrimaryColor
24
+ from .units import Length, pt, require_length
25
+ from .views.layout_view import LayoutView
26
+ from .views.primitive_view import PrimitiveView
27
+ from .views.view import View
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Anchor:
32
+ target: str
33
+ position: RelativePoint = RelativePoint.center
34
+ offset_x: Length = pt(0)
35
+ offset_y: Length = pt(0)
36
+ exported: str | None = None
37
+
38
+ def __post_init__(self) -> None:
39
+ if not self.target:
40
+ raise ValueError("Anchor target must not be empty")
41
+ if self.exported is not None and not self.exported:
42
+ raise ValueError("Exported anchor name must not be empty")
43
+ require_length(self.offset_x)
44
+ require_length(self.offset_y)
45
+
46
+ def resolve(self, lookup: Callable[[str], ViewIdentity]) -> ResolvedAnchor:
47
+ owner = lookup(self.target)
48
+ return ResolvedAnchor(
49
+ ExportedAnchor(owner, self.exported)
50
+ if self.exported is not None
51
+ else owner,
52
+ self.position,
53
+ self.offset_x,
54
+ self.offset_y,
55
+ )
56
+
57
+ @classmethod
58
+ def descendant(
59
+ cls,
60
+ owner: str,
61
+ name: str,
62
+ position: RelativePoint = RelativePoint.center,
63
+ *,
64
+ offset_x: Length = pt(0),
65
+ offset_y: Length = pt(0),
66
+ ) -> Anchor:
67
+ """Target named geometry exported by a keyed descendant layout."""
68
+ return cls(owner, position, offset_x, offset_y, name)
69
+
70
+
71
+ class Annotation(ABC):
72
+ @property
73
+ @abstractmethod
74
+ def view(self) -> View:
75
+ raise NotImplementedError
76
+
77
+ @abstractmethod
78
+ def resolve(self, lookup: Callable[[str], ViewIdentity]) -> ResolvedAnnotation:
79
+ raise NotImplementedError
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class _Connector(PrimitiveView):
84
+ start_cap: Literal["none", "arrow"]
85
+ end_cap: Literal["none", "arrow"]
86
+ stroke: Stroke
87
+
88
+ def expand(self, context: Context, metadata: ExpandedMetadata) -> ExpandedConnector:
89
+ style = self.stroke.style
90
+ color = style if isinstance(style, Color) else context.environment[style]
91
+ return ExpandedConnector(
92
+ metadata,
93
+ ConnectorLayout(),
94
+ color.hex,
95
+ self.start_cap,
96
+ self.end_cap,
97
+ self.stroke.width,
98
+ self.stroke.dash,
99
+ self.stroke.opacity,
100
+ self.stroke.line_cap,
101
+ self.stroke.line_join,
102
+ )
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Connector(Annotation):
107
+ """An anchor-to-anchor line. An explicit stroke overrides the default 2 pt style."""
108
+
109
+ start: Anchor
110
+ end: Anchor
111
+ start_cap: Literal["none", "arrow"] = "none"
112
+ end_cap: Literal["none", "arrow"] = "arrow"
113
+ style: ColorStyle = PrimaryColor
114
+ stroke: Stroke | None = None
115
+
116
+ @property
117
+ def view(self) -> View:
118
+ stroke = self.stroke
119
+ if stroke is None:
120
+ stroke = Stroke(style=self.style, width=DEFAULT_CONNECTOR_WIDTH)
121
+ return _Connector(self.start_cap, self.end_cap, stroke)
122
+
123
+ def resolve(self, lookup: Callable[[str], ViewIdentity]) -> ResolvedConnector:
124
+ return ResolvedConnector(self.start.resolve(lookup), self.end.resolve(lookup))
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Label(Annotation):
129
+ anchor: Anchor
130
+ content: View
131
+ alignment: RelativePoint = RelativePoint.center
132
+
133
+ def __post_init__(self) -> None:
134
+ if not isinstance(self.content, View):
135
+ raise TypeError("Label.content must be a View")
136
+
137
+ @property
138
+ def view(self) -> View:
139
+ return self.content
140
+
141
+ def resolve(self, lookup: Callable[[str], ViewIdentity]) -> ResolvedLabel:
142
+ return ResolvedLabel(self.anchor.resolve(lookup), self.alignment)
143
+
144
+
145
+ @dataclass(frozen=True, init=False)
146
+ class Annotated(LayoutView):
147
+ annotations: tuple[Annotation, ...]
148
+
149
+ def __init__(self, content: View, *annotations: Annotation) -> None:
150
+ if not isinstance(content, View):
151
+ raise TypeError("Annotated.content must be a View")
152
+ if not all(isinstance(annotation, Annotation) for annotation in annotations):
153
+ raise TypeError("Annotated annotations must inherit Annotation")
154
+ object.__setattr__(self, "annotations", tuple(annotations))
155
+ super().__init__(
156
+ content,
157
+ *(annotation.view for annotation in annotations),
158
+ )
159
+
160
+ def resolve_layout(self, lookup: Callable[[str], ViewIdentity]) -> AnnotatedLayout:
161
+ return AnnotatedLayout(tuple(a.resolve(lookup) for a in self.annotations))
@@ -0,0 +1 @@
1
+ """Output backends consume resolved layouts or compiled presentation sequences."""
@@ -0,0 +1,41 @@
1
+ """OpenType embedding permissions shared by the two exporters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+
9
+ from fontTools.ttLib import TTFont, TTLibError
10
+
11
+ from ..fonts import FontEmbeddingError
12
+
13
+
14
+ @contextmanager
15
+ def open_embeddable_font(
16
+ path: str | Path, index: int = 0, *, allow_preview_print: bool = False
17
+ ) -> Iterator[TTFont]:
18
+ try:
19
+ with TTFont(path, fontNumber=index, lazy=True, recalcTimestamp=False) as font:
20
+ if "OS/2" not in font:
21
+ raise FontEmbeddingError(
22
+ f"{path}: font lacks OS/2 embedding permissions"
23
+ )
24
+ os2 = font["OS/2"]
25
+ flags = os2.fsType
26
+ permission = flags & 0x000F
27
+ if os2.version < 3:
28
+ # Legacy versions allow multiple levels with the least restrictive
29
+ # one taking precedence. Version 0 and 1 omit the higher flags.
30
+ permission = next((bit for bit in (8, 4, 2, 1) if permission & bit), 0)
31
+ if permission not in (0, 4, 8):
32
+ raise FontEmbeddingError(f"{path}: font permissions forbid embedding")
33
+ if os2.version >= 2 and flags & 0x0200:
34
+ raise FontEmbeddingError(f"{path}: font permits bitmap embedding only")
35
+ if permission == 4 and not allow_preview_print:
36
+ raise FontEmbeddingError(
37
+ f"{path}: font permits Preview & Print embedding only"
38
+ )
39
+ yield font
40
+ except (OSError, TTLibError) as error:
41
+ raise FontEmbeddingError(f"Cannot embed font {str(path)!r}: {error}") from error
@@ -0,0 +1,230 @@
1
+ """Package full OpenType faces as Embedded OpenType parts in PowerPoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping, Sequence
6
+ from contextlib import nullcontext
7
+ from io import BytesIO
8
+ from os import PathLike
9
+ from pathlib import Path
10
+ from struct import Struct, pack
11
+ from typing import TYPE_CHECKING
12
+
13
+ from fontTools.ttLib import TTFont
14
+
15
+ from .._bundled_fonts import is_bundled_face
16
+ from .._diagnostics import SlideLocation
17
+ from ..drawables import Drawable, DrawableText
18
+ from ..fonts import EmbeddedFont, FontEmbeddingError, FontFile
19
+ from ._font_embedding import open_embeddable_font
20
+
21
+ if TYPE_CHECKING:
22
+ from pptx.presentation import Presentation
23
+
24
+
25
+ # EOT 2.1 fixed header through Reserved4, followed by UTF-16LE name records.
26
+ _EOT_HEADER = Struct("<4I10sBBIHH11I")
27
+ _FONT_CONTENT_TYPE = "application/x-fontdata"
28
+ _FontUse = tuple[SlideLocation, int]
29
+ _FontKey = tuple[str, bool, bool]
30
+
31
+
32
+ def collect_embedded_fonts(
33
+ scenes: Iterable[tuple[SlideLocation, int, Drawable]],
34
+ explicit: Sequence[EmbeddedFont],
35
+ *,
36
+ include_custom: bool,
37
+ ) -> tuple[tuple[EmbeddedFont, ...], dict[_FontKey, _FontUse]]:
38
+ """Collect measured faces for each typeface the caller has not supplied."""
39
+ explicit_names = {font.typeface.casefold() for font in explicit}
40
+ families: dict[str, tuple[str, dict[tuple[bool, bool], FontFile]]] = {}
41
+ uses: dict[_FontKey, _FontUse] = {}
42
+ for location, step, scene in scenes:
43
+ for node in scene.walk():
44
+ if not isinstance(node, DrawableText):
45
+ continue
46
+ face = node.font
47
+ typeface = face.powerpoint_typeface
48
+ name_key = typeface.name.casefold()
49
+ style = (typeface.bold, typeface.italic)
50
+ if name_key in explicit_names:
51
+ uses.setdefault((name_key, *style), (location, step))
52
+ continue
53
+ if not include_custom and not is_bundled_face(face):
54
+ continue
55
+ uses.setdefault((name_key, *style), (location, step))
56
+ _, styles = families.setdefault(name_key, (typeface.name, {}))
57
+ source = FontFile(face.path, face.index)
58
+ previous = styles.setdefault(style, source)
59
+ if previous != source:
60
+ style_name = ("Bold " if typeface.bold else "") + (
61
+ "Italic" if typeface.italic else ""
62
+ )
63
+ with location.context(step):
64
+ raise FontEmbeddingError(
65
+ f"PowerPoint typeface {typeface.name!r} ({style_name.strip() or 'Regular'}) "
66
+ f"uses two faces: {previous.path!r} (index {previous.index}) and "
67
+ f"{source.path!r} (index {source.index}). "
68
+ "Select one with embedded_fonts or use distinct typeface names."
69
+ )
70
+ fonts = (
71
+ *explicit,
72
+ *(
73
+ EmbeddedFont(
74
+ name,
75
+ regular=faces.get((False, False)),
76
+ bold=faces.get((True, False)),
77
+ italic=faces.get((False, True)),
78
+ bold_italic=faces.get((True, True)),
79
+ )
80
+ for name, faces in families.values()
81
+ ),
82
+ )
83
+ return fonts, uses
84
+
85
+
86
+ def _font_part(source: FontFile | str | PathLike[str], typeface: str) -> bytes:
87
+ path = Path(source.path if isinstance(source, FontFile) else source).expanduser()
88
+ index = source.index if isinstance(source, FontFile) else 0
89
+
90
+ with open_embeddable_font(path, index, allow_preview_print=True) as font:
91
+ if "head" not in font or "name" not in font or "fvar" in font:
92
+ raise FontEmbeddingError(
93
+ f"{path}: PowerPoint embedding requires a static OpenType face"
94
+ )
95
+ names = font["name"]
96
+ aliases = set()
97
+ for record in names.names:
98
+ if record.nameID in (1, 4):
99
+ try:
100
+ aliases.add(record.toUnicode().casefold())
101
+ except UnicodeError:
102
+ continue
103
+ if typeface.casefold() not in aliases:
104
+ raise FontEmbeddingError(
105
+ f"{path}: font names do not match PowerPoint typeface {typeface!r}"
106
+ )
107
+
108
+ os2 = font["OS/2"]
109
+ panose = Struct(">10B").pack(
110
+ os2.panose.bFamilyType,
111
+ os2.panose.bSerifStyle,
112
+ os2.panose.bWeight,
113
+ os2.panose.bProportion,
114
+ os2.panose.bContrast,
115
+ os2.panose.bStrokeVariation,
116
+ os2.panose.bArmStyle,
117
+ os2.panose.bLetterForm,
118
+ os2.panose.bMidline,
119
+ os2.panose.bXHeight,
120
+ )
121
+ records = bytearray()
122
+ for name_id in (1, 2, 5, 4):
123
+ name = (names.getDebugName(name_id) or "").encode("utf-16le")
124
+ records.extend(pack("<HH", 0, len(name)))
125
+ records.extend(name)
126
+ records.extend(pack("<HH", 0, 0)) # Padding and empty document root string.
127
+
128
+ font.reader.file.seek(0)
129
+ payload: bytes = font.reader.file.read()
130
+ checksum = font["head"].checkSumAdjustment
131
+ if payload.startswith(b"ttcf"):
132
+ buffer = BytesIO()
133
+ font.save(buffer)
134
+ payload = buffer.getvalue()
135
+ buffer.seek(0)
136
+ with TTFont(buffer, lazy=True) as extracted:
137
+ checksum = extracted["head"].checkSumAdjustment
138
+ if payload[:4] not in (b"\x00\x01\x00\x00", b"OTTO", b"true"):
139
+ raise FontEmbeddingError(
140
+ f"{path}: expected a TrueType or OpenType font file"
141
+ )
142
+
143
+ return (
144
+ _EOT_HEADER.pack(
145
+ _EOT_HEADER.size + len(records) + len(payload),
146
+ len(payload),
147
+ 0x00020001,
148
+ 0, # Uncompressed plaintext OpenType data.
149
+ panose,
150
+ 1, # DEFAULT_CHARSET
151
+ int(bool(os2.fsSelection & 0x0001)),
152
+ os2.usWeightClass,
153
+ os2.fsType,
154
+ 0x504C,
155
+ os2.ulUnicodeRange1,
156
+ os2.ulUnicodeRange2,
157
+ os2.ulUnicodeRange3,
158
+ os2.ulUnicodeRange4,
159
+ getattr(os2, "ulCodePageRange1", 0),
160
+ getattr(os2, "ulCodePageRange2", 0),
161
+ checksum,
162
+ 0,
163
+ 0,
164
+ 0,
165
+ 0,
166
+ )
167
+ + records
168
+ + payload
169
+ )
170
+
171
+
172
+ def embed_font_parts(
173
+ presentation: Presentation,
174
+ fonts: Sequence[EmbeddedFont],
175
+ uses: Mapping[_FontKey, _FontUse],
176
+ ) -> None:
177
+ """Add the font list and the relationships to its font parts."""
178
+ from pptx.opc.constants import RELATIONSHIP_TYPE as RT
179
+ from pptx.opc.package import Part
180
+ from pptx.oxml.ns import qn
181
+ from pptx.oxml.xmlchemy import OxmlElement
182
+
183
+ if not fonts:
184
+ return
185
+ part = presentation.part
186
+ package = part.package
187
+ names = set()
188
+ font_list = OxmlElement("p:embeddedFontLst")
189
+ for font in fonts:
190
+ name = font.typeface.casefold()
191
+ if name in names:
192
+ raise FontEmbeddingError(
193
+ f"Duplicate embedded PowerPoint typeface {font.typeface!r}"
194
+ )
195
+ names.add(name)
196
+ item = OxmlElement("p:embeddedFont")
197
+ family = OxmlElement("p:font")
198
+ family.set("typeface", font.typeface)
199
+ item.append(family)
200
+ for style, bold, italic, source in (
201
+ ("regular", False, False, font.regular),
202
+ ("bold", True, False, font.bold),
203
+ ("italic", False, True, font.italic),
204
+ ("boldItalic", True, True, font.bold_italic),
205
+ ):
206
+ if source is None:
207
+ continue
208
+ use = uses.get((name, bold, italic))
209
+ with use[0].context(use[1]) if use is not None else nullcontext():
210
+ blob = _font_part(source, font.typeface)
211
+ path = package.next_partname("/ppt/fonts/font%d.fntdata")
212
+ font_part = Part(path, _FONT_CONTENT_TYPE, package, blob)
213
+ child = OxmlElement(f"p:{style}")
214
+ child.set(qn("r:id"), part.relate_to(font_part, RT.FONT))
215
+ item.append(child)
216
+ font_list.append(item)
217
+
218
+ root = presentation.element
219
+ root.insert_element_before(
220
+ font_list,
221
+ "p:custShowLst",
222
+ "p:photoAlbum",
223
+ "p:custDataLst",
224
+ "p:kinsoku",
225
+ "p:defaultTextStyle",
226
+ "p:modifyVerifier",
227
+ "p:extLst",
228
+ )
229
+ root.set("embedTrueTypeFonts", "1")
230
+ root.set("saveSubsetFonts", "0")
@@ -0,0 +1,241 @@
1
+ """Prepare PowerPoint shadows and optional per-state shadow images."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from io import BytesIO
7
+ from shutil import which
8
+ from subprocess import run
9
+
10
+ from PIL import Image
11
+
12
+ from .._diagnostics import SlideLocation
13
+ from ..animation import AnimationProgram, EffectInstance, EffectKind, VisualState
14
+ from ..compiler import CompiledSlide, _visual_properties
15
+ from ..drawables import (
16
+ Bounds,
17
+ Drawable,
18
+ DrawableConnector,
19
+ DrawableEllipse,
20
+ DrawableGroup,
21
+ DrawableImage,
22
+ DrawableLine,
23
+ DrawableMetadata,
24
+ DrawablePath,
25
+ DrawableRectangle,
26
+ DrawableRichText,
27
+ DrawableText,
28
+ )
29
+ from ..effects import ShadowFallback
30
+ from . import svg
31
+
32
+
33
+ def _visible(node: Drawable) -> bool:
34
+ if node.metadata.opacity == 0:
35
+ return False
36
+ if isinstance(node, (DrawableGroup, DrawableRichText)):
37
+ return any(_visible(child) for child in node.children)
38
+ if isinstance(node, (DrawableRectangle, DrawableEllipse, DrawablePath)):
39
+ fill = node.color if isinstance(node, DrawableRectangle) else node.fill
40
+ return (fill is not None and node.fill_opacity > 0) or (
41
+ node.stroke is not None
42
+ and node.stroke_width.points > 0
43
+ and node.stroke_opacity > 0
44
+ )
45
+ if isinstance(node, DrawableText):
46
+ return bool(node.text.strip())
47
+ if isinstance(node, (DrawableConnector, DrawableLine)):
48
+ return node.width.points > 0 and node.opacity > 0
49
+ return True
50
+
51
+
52
+ def _shadow_image(
53
+ node: Drawable,
54
+ viewport: Bounds,
55
+ cache: dict[str, tuple[Bounds, bytes, tuple[int, int]] | None],
56
+ ) -> DrawableImage | None:
57
+ markup = svg._render(node, viewport, shadow_only=True)
58
+ if markup not in cache:
59
+ converter = which("rsvg-convert")
60
+ if converter is None:
61
+ raise ValueError("Rasterized PPTX shadows require rsvg-convert (librsvg)")
62
+ result = run(
63
+ [converter, "--dpi-x", "144", "--dpi-y", "144"],
64
+ input=markup.encode(),
65
+ capture_output=True,
66
+ check=False,
67
+ )
68
+ if result.returncode:
69
+ raise ValueError(
70
+ f"Could not rasterize shadow on {node.identity}: "
71
+ f"{result.stderr.decode(errors='replace').strip()}"
72
+ )
73
+ with Image.open(BytesIO(result.stdout)) as source:
74
+ rgba = source.convert("RGBA")
75
+ edges = rgba.getchannel("A").getbbox()
76
+ cache[markup] = None
77
+ if edges is not None:
78
+ x, y, right, bottom = edges
79
+ pixel_width = viewport.width / rgba.width
80
+ pixel_height = viewport.height / rgba.height
81
+ bounds = Bounds(
82
+ viewport.x + pixel_width * x,
83
+ viewport.y + pixel_height * y,
84
+ pixel_width * (right - x),
85
+ pixel_height * (bottom - y),
86
+ )
87
+ picture = rgba.crop(edges)
88
+ data = BytesIO()
89
+ picture.save(data, format="PNG")
90
+ cache[markup] = bounds, data.getvalue(), picture.size
91
+ asset = cache[markup]
92
+ if asset is None:
93
+ return None
94
+ bounds, png, pixels = asset
95
+ return DrawableImage(
96
+ f"{node.identity}/shadow",
97
+ bounds,
98
+ DrawableMetadata(),
99
+ bounds,
100
+ png,
101
+ "image/png",
102
+ pixels,
103
+ "contain",
104
+ )
105
+
106
+
107
+ def prepare(
108
+ slide: CompiledSlide, fallback: ShadowFallback, location: SlideLocation
109
+ ) -> CompiledSlide:
110
+ pictures: dict[str, tuple[Bounds, bytes, tuple[int, int]] | None] = {}
111
+ snapshots: list[dict[str, DrawableImage]] = []
112
+ stripped: list[dict[str, Drawable]] = []
113
+ states = []
114
+
115
+ def lower(
116
+ node: Drawable,
117
+ viewport: Bounds,
118
+ images: dict[str, DrawableImage],
119
+ clean_leaves: dict[str, Drawable],
120
+ ) -> Drawable:
121
+ shadow = node.metadata.shadow
122
+ visible = _visible(node) if shadow is not None else False
123
+ rasterize = node.metadata.shadow_clip is not None or (
124
+ fallback is ShadowFallback.RASTERIZE
125
+ and isinstance(
126
+ node, (DrawableGroup, DrawableImage, DrawableText, DrawableRichText)
127
+ )
128
+ )
129
+ if shadow is not None and (rasterize or not visible):
130
+ if visible:
131
+ if fallback is ShadowFallback.ERROR:
132
+ raise ValueError(
133
+ f"PPTX cannot render a native shadow on {node.identity}; "
134
+ "use shadow_fallback=ShadowFallback.RASTERIZE"
135
+ )
136
+ image = _shadow_image(node, viewport, pictures)
137
+ if image is not None:
138
+ images[image.identity] = image
139
+ else:
140
+ image = None
141
+ clean = replace(
142
+ node, metadata=replace(node.metadata, shadow=None, shadow_clip=None)
143
+ )
144
+ if isinstance(clean, DrawableGroup):
145
+ children = tuple(
146
+ lower(child, viewport, images, clean_leaves)
147
+ for child in clean.children
148
+ )
149
+ return replace(clean, children=((image,) if image else ()) + children)
150
+ clean_leaves[clean.identity] = clean
151
+ if image is not None:
152
+ return DrawableGroup(
153
+ f"{clean.identity}/effects",
154
+ clean.bounds,
155
+ DrawableMetadata(),
156
+ (image, clean),
157
+ )
158
+ return clean
159
+ if isinstance(node, DrawableGroup):
160
+ children = tuple(
161
+ lower(child, viewport, images, clean_leaves) for child in node.children
162
+ )
163
+ if any(a is not b for a, b in zip(children, node.children)):
164
+ return replace(node, children=children)
165
+ return node
166
+
167
+ for step, state in enumerate(slide.states):
168
+ images: dict[str, DrawableImage] = {}
169
+ clean_leaves: dict[str, Drawable] = {}
170
+
171
+ with location.context(step):
172
+ states.append(
173
+ replace(
174
+ state,
175
+ drawable=lower(
176
+ state.drawable, state.drawable.bounds, images, clean_leaves
177
+ ),
178
+ )
179
+ )
180
+ snapshots.append(images)
181
+ stripped.append(clean_leaves)
182
+
183
+ if not any(snapshots) and not any(stripped):
184
+ return replace(slide, states=tuple(states))
185
+
186
+ builds = []
187
+ for i, build in enumerate(slide.animation.builds):
188
+ effects = []
189
+ for effect in build.effects:
190
+ identity = effect.identity
191
+ left, right = effect.before, effect.after
192
+ if (
193
+ left is not None
194
+ and (clean_left := stripped[i].get(identity)) is not None
195
+ ):
196
+ left = replace(left, drawable=clean_left)
197
+ if (
198
+ right is not None
199
+ and (clean_right := stripped[i + 1].get(identity)) is not None
200
+ ):
201
+ right = replace(right, drawable=clean_right)
202
+ if left is effect.before and right is effect.after:
203
+ effects.append(effect)
204
+ elif left is not None and right is not None:
205
+ if type(left.drawable) is not type(
206
+ right.drawable
207
+ ) or _visual_properties(left.drawable) != _visual_properties(
208
+ right.drawable
209
+ ):
210
+ effects.append(
211
+ replace(
212
+ effect, kind=EffectKind.CHANGE, before=left, after=right
213
+ )
214
+ )
215
+ elif left.bounds != right.bounds:
216
+ effects.append(
217
+ replace(effect, kind=EffectKind.MOVE, before=left, after=right)
218
+ )
219
+ else:
220
+ effects.append(replace(effect, before=left, after=right))
221
+ before, after = snapshots[i], snapshots[i + 1]
222
+ for identity in sorted(before.keys() | after.keys()):
223
+ old, new = before.get(identity), after.get(identity)
224
+ if old == new:
225
+ continue
226
+ effects.append(
227
+ EffectInstance(
228
+ identity,
229
+ EffectKind.INSERT
230
+ if old is None
231
+ else EffectKind.REMOVE
232
+ if new is None
233
+ else EffectKind.CHANGE,
234
+ VisualState(old.bounds, old) if old is not None else None,
235
+ VisualState(new.bounds, new) if new is not None else None,
236
+ )
237
+ )
238
+ builds.append(replace(build, effects=tuple(effects)))
239
+ return replace(
240
+ slide, states=tuple(states), animation=AnimationProgram(tuple(builds))
241
+ )