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
@@ -0,0 +1,1225 @@
1
+ """Static slides and native PowerPoint presentation builds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Sequence
6
+ from dataclasses import dataclass, replace
7
+ from io import BytesIO
8
+ from math import atan2, cos, degrees, hypot, radians, sin
9
+ from os import PathLike
10
+ from typing import Any
11
+ from uuid import uuid4
12
+
13
+ from .._diagnostics import SlideLocation
14
+ from ..animation import (
15
+ AnimationProgram,
16
+ BuildProgram,
17
+ EffectInstance,
18
+ EffectKind,
19
+ VisualState,
20
+ )
21
+ from ..compiler import CompiledDeck, CompiledSlide
22
+ from ..drawables import (
23
+ Bounds,
24
+ Drawable,
25
+ DrawableConnector,
26
+ DrawableEllipse,
27
+ DrawableGroup,
28
+ DrawableImage,
29
+ DrawableLine,
30
+ DrawablePath,
31
+ DrawableRectangle,
32
+ DrawableRichText,
33
+ DrawableText,
34
+ PathClose,
35
+ PathCubic,
36
+ PathLine,
37
+ PathMove,
38
+ PathQuadratic,
39
+ )
40
+ from ..effects import ResolvedShadow, ShadowFallback
41
+ from ..fonts import EmbeddedFont, ResolvedFont
42
+ from ..geometry import Point
43
+ from ..paint import ResolvedLinearGradient
44
+ from ..units import Length, pt
45
+ from ._pptx_fonts import collect_embedded_fonts, embed_font_parts
46
+ from ._pptx_shadows import prepare as prepare_shadows
47
+ from ._pptx_tables import NativeTable, add_native_table, lower_native_tables
48
+ from .pptx_animation import PptxBehaviorKind, PptxTrigger, _same_size, plan_slide
49
+
50
+
51
+ def _color(value: str) -> Any:
52
+ from pptx.dml.color import RGBColor
53
+
54
+ return RGBColor.from_string(value[1:]) # type: ignore[no-untyped-call]
55
+
56
+
57
+ def _apply_font(
58
+ target: Any,
59
+ face: ResolvedFont,
60
+ size: Length,
61
+ color: str,
62
+ opacity: float,
63
+ gradient: ResolvedLinearGradient | None,
64
+ *,
65
+ explicit_typeface: bool = False,
66
+ shadow: ResolvedShadow | None = None,
67
+ ) -> None:
68
+ from pptx.util import Pt
69
+
70
+ typeface = face.powerpoint_typeface
71
+ target.name = typeface.name
72
+ if explicit_typeface:
73
+ # DrawingML chooses a font slot according to the script in the run.
74
+ latin = target._element.latin
75
+ for tag in ("a:sym", "a:cs", "a:ea"):
76
+ latin.addnext(_element(tag, typeface=typeface.name))
77
+ target.size = Pt(size.points)
78
+ target.bold = typeface.bold
79
+ target.italic = typeface.italic
80
+ _apply_fill(target.fill, color, opacity, gradient)
81
+ if shadow is not None:
82
+ _apply_shadow(target._element, shadow, "a:latin")
83
+
84
+
85
+ def _apply_shadow(properties: Any, shadow: ResolvedShadow, *successors: str) -> None:
86
+ from pptx.oxml.ns import qn
87
+
88
+ effects = properties.find(qn("a:effectLst"))
89
+ if effects is None:
90
+ effects = _element("a:effectLst")
91
+ properties.insert_element_before(effects, *successors)
92
+ angle = degrees(atan2(shadow.y.points, shadow.x.points)) % 360
93
+ native = _element(
94
+ "a:outerShdw",
95
+ blurRad=_path_coordinate(shadow.radius),
96
+ dist=round(hypot(shadow.x.points, shadow.y.points) * 12700),
97
+ dir=round(angle * 60000) % 21600000,
98
+ algn="ctr",
99
+ rotWithShape=0,
100
+ )
101
+ color = _element("a:srgbClr", val=shadow.color[1:])
102
+ color.append(_element("a:alpha", val=round(shadow.opacity * 100000)))
103
+ native.append(color)
104
+ effects.append(native)
105
+
106
+
107
+ def _apply_fill(
108
+ fill: Any,
109
+ color: str,
110
+ opacity: float,
111
+ gradient: ResolvedLinearGradient | None = None,
112
+ ) -> None:
113
+ if gradient is None:
114
+ fill.solid()
115
+ fill.fore_color.rgb = _color(color)
116
+ _apply_alpha(fill._xPr, opacity)
117
+ return
118
+ fill.gradient()
119
+ element = fill._xPr.get_or_change_to_gradFill()
120
+ element.set("rotWithShape", "1")
121
+ stops = _element("a:gsLst")
122
+ for stop in gradient.stops:
123
+ item = _element("a:gs", pos=round(stop.offset * 100000))
124
+ item.append(_element("a:srgbClr", val=stop.color[1:]))
125
+ _apply_alpha(item, stop.opacity * opacity)
126
+ stops.append(item)
127
+ element[:] = [
128
+ stops,
129
+ _element("a:lin", ang=round(gradient.angle * 60000) % 21600000, scaled="0"),
130
+ ]
131
+
132
+
133
+ def _apply_stroke(
134
+ line: Any,
135
+ color: str,
136
+ width: Any,
137
+ dash: tuple[Any, ...] = (),
138
+ opacity: float = 1.0,
139
+ line_cap: str = "butt",
140
+ line_join: str = "miter",
141
+ ) -> None:
142
+ from pptx.oxml.ns import qn
143
+ from pptx.oxml.xmlchemy import OxmlElement
144
+ from pptx.util import Pt
145
+
146
+ line.color.rgb = _color(color)
147
+ line.width = Pt(width.points)
148
+ element = line._get_or_add_ln()
149
+ _apply_alpha(element, opacity)
150
+ element.set("cap", {"butt": "flat", "round": "rnd", "square": "sq"}[line_cap])
151
+ for existing in tuple(element):
152
+ if existing.tag in (qn("a:round"), qn("a:bevel"), qn("a:miter")):
153
+ element.remove(existing)
154
+ for existing in tuple(element):
155
+ if existing.tag in (qn("a:prstDash"), qn("a:custDash")):
156
+ element.remove(existing)
157
+ if dash:
158
+ values = dash if len(dash) % 2 == 0 else dash + dash
159
+ custom = OxmlElement("a:custDash")
160
+ for index in range(0, len(values), 2):
161
+ item = OxmlElement("a:ds")
162
+ item.set(
163
+ "d", str(max(1, round(values[index].points / width.points * 100000)))
164
+ )
165
+ item.set(
166
+ "sp",
167
+ str(max(1, round(values[index + 1].points / width.points * 100000))),
168
+ )
169
+ custom.append(item)
170
+ element.append(custom)
171
+ join = OxmlElement(
172
+ {"miter": "a:miter", "round": "a:round", "bevel": "a:bevel"}[line_join]
173
+ )
174
+ if line_join == "miter":
175
+ join.set("lim", "800000")
176
+ element.append(join)
177
+
178
+
179
+ def _apply_alpha(element: Any, opacity: float) -> None:
180
+ from pptx.oxml.ns import qn
181
+ from pptx.oxml.xmlchemy import OxmlElement
182
+
183
+ color = element.find(".//" + qn("a:srgbClr"))
184
+ if color is None:
185
+ return
186
+ for existing in tuple(color):
187
+ if existing.tag == qn("a:alpha"):
188
+ color.remove(existing)
189
+ if opacity < 1:
190
+ alpha = OxmlElement("a:alpha")
191
+ alpha.set("val", str(round(opacity * 100000)))
192
+ color.append(alpha)
193
+
194
+
195
+ def _path_points(node: DrawablePath) -> list[Point]:
196
+ return [point for command in node.commands for point in command.points]
197
+
198
+
199
+ def _path_coordinate(value: Length) -> int:
200
+ return round(value.points * 12700)
201
+
202
+
203
+ def _replace_freeform_path(shape: Any, node: DrawablePath) -> None:
204
+ from pptx.oxml.ns import qn
205
+ from pptx.oxml.xmlchemy import OxmlElement
206
+
207
+ path = shape.element.find(".//" + qn("a:path"))
208
+ if path is None:
209
+ raise ValueError("PowerPoint freeform shape did not contain a path")
210
+ for command in tuple(path):
211
+ path.remove(command)
212
+ points = _path_points(node)
213
+ min_x = min(_path_coordinate(point.x) for point in points)
214
+ min_y = min(_path_coordinate(point.y) for point in points)
215
+
216
+ def point(parent: Any, value: Point) -> None:
217
+ item = OxmlElement("a:pt")
218
+ item.set("x", str(_path_coordinate(value.x) - min_x))
219
+ item.set("y", str(_path_coordinate(value.y) - min_y))
220
+ parent.append(item)
221
+
222
+ for command in node.commands:
223
+ if isinstance(command, PathMove):
224
+ item = OxmlElement("a:moveTo")
225
+ point(item, command.point)
226
+ elif isinstance(command, PathLine):
227
+ item = OxmlElement("a:lnTo")
228
+ point(item, command.point)
229
+ elif isinstance(command, PathQuadratic):
230
+ item = OxmlElement("a:quadBezTo")
231
+ point(item, command.control)
232
+ point(item, command.end)
233
+ elif isinstance(command, PathCubic):
234
+ item = OxmlElement("a:cubicBezTo")
235
+ point(item, command.control1)
236
+ point(item, command.control2)
237
+ point(item, command.end)
238
+ else:
239
+ item = OxmlElement("a:close")
240
+ path.append(item)
241
+
242
+
243
+ def _text_frame_bounds(node: DrawableText | DrawableRichText) -> Bounds:
244
+ bounds = node.content_bounds
245
+ # Some importers reflow premeasured text despite wrap="none". Allow room
246
+ # for their text insets and for small differences in measured font width.
247
+ extra = pt(16) + bounds.width * 0.08
248
+ x, y = bounds.x, bounds.y
249
+ if isinstance(node, DrawableText) and node.is_slide_number:
250
+ x -= extra
251
+ elif node.rotation:
252
+ # Widen from the left text edge in the rotated coordinate system.
253
+ angle = radians(node.rotation)
254
+ x += extra * ((cos(angle) - 1) / 2)
255
+ y += extra * (sin(angle) / 2)
256
+ return Bounds(x, y, bounds.width + extra, bounds.height)
257
+
258
+
259
+ def _text_frame(shape: Any, node: DrawableText | DrawableRichText) -> Any:
260
+ from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
261
+
262
+ shape.rotation = node.rotation
263
+ frame = shape.text_frame
264
+ frame.margin_left = frame.margin_right = frame.margin_top = frame.margin_bottom = 0
265
+ frame.word_wrap = False
266
+ frame.auto_size = MSO_AUTO_SIZE.NONE
267
+ if node.text_placement == "rows":
268
+ frame.vertical_anchor = MSO_ANCHOR.MIDDLE
269
+ return frame
270
+
271
+
272
+ def _solid_rule_bounds(node: DrawableLine) -> Bounds | None:
273
+ """Represent a flat, axis-aligned stroke as an equivalent filled rule."""
274
+ if node.dash or node.line_cap != "butt":
275
+ return None
276
+ start, end = node.start, node.end
277
+ if start.y == end.y and start.x != end.x:
278
+ return Bounds(
279
+ min(start.x, end.x),
280
+ start.y - node.width / 2,
281
+ max(start.x, end.x) - min(start.x, end.x),
282
+ node.width,
283
+ )
284
+ if start.x == end.x and start.y != end.y:
285
+ return Bounds(
286
+ start.x - node.width / 2,
287
+ min(start.y, end.y),
288
+ node.width,
289
+ max(start.y, end.y) - min(start.y, end.y),
290
+ )
291
+ return None
292
+
293
+
294
+ def _add_node(
295
+ shapes: Any, node: Drawable, slide_number: int, *, name: str | None = None
296
+ ) -> Any:
297
+ from pptx.enum.shapes import MSO_CONNECTOR, MSO_SHAPE
298
+ from pptx.enum.text import PP_ALIGN
299
+ from pptx.oxml.ns import qn
300
+ from pptx.oxml.xmlchemy import OxmlElement
301
+ from pptx.util import Pt
302
+
303
+ opacity = node.metadata.opacity
304
+ shadow = node.metadata.shadow
305
+ if isinstance(node, (DrawableText, DrawableRichText)):
306
+ b = _text_frame_bounds(node)
307
+ x, y, w, h = b.x.points, b.y.points, b.width.points, b.height.points
308
+ elif isinstance(
309
+ node,
310
+ (
311
+ DrawableRectangle,
312
+ DrawableEllipse,
313
+ DrawableImage,
314
+ ),
315
+ ):
316
+ b = node.content_bounds
317
+ x, y, w, h = b.x.points, b.y.points, b.width.points, b.height.points
318
+ if isinstance(node, DrawableRectangle):
319
+ radius = node.corner_radius.points
320
+ shape = shapes.add_shape(
321
+ MSO_SHAPE.ROUNDED_RECTANGLE if radius > 0 else MSO_SHAPE.RECTANGLE,
322
+ Pt(x),
323
+ Pt(y),
324
+ Pt(w),
325
+ Pt(h),
326
+ )
327
+ if radius > 0:
328
+ # DrawingML expresses this adjustment as a fraction of the shape's
329
+ # shorter side; Deckkit's public value is an absolute length.
330
+ shape.adjustments[0] = radius / min(w, h)
331
+ _apply_fill(shape.fill, node.color, node.fill_opacity * opacity, node.gradient)
332
+ shape.line.fill.background()
333
+ if node.stroke is not None:
334
+ _apply_stroke(
335
+ shape.line,
336
+ node.stroke,
337
+ node.stroke_width,
338
+ node.dash,
339
+ node.stroke_opacity * opacity,
340
+ node.line_cap,
341
+ node.line_join,
342
+ )
343
+ elif isinstance(node, DrawableEllipse):
344
+ shape = shapes.add_shape(MSO_SHAPE.OVAL, Pt(x), Pt(y), Pt(w), Pt(h))
345
+ if node.fill is None:
346
+ shape.fill.background()
347
+ else:
348
+ shape.fill.solid()
349
+ shape.fill.fore_color.rgb = _color(node.fill)
350
+ _apply_alpha(shape.fill._xPr, node.fill_opacity * opacity)
351
+ if node.stroke is None:
352
+ shape.line.fill.background()
353
+ else:
354
+ _apply_stroke(
355
+ shape.line,
356
+ node.stroke,
357
+ node.stroke_width,
358
+ node.dash,
359
+ node.stroke_opacity * opacity,
360
+ node.line_cap,
361
+ node.line_join,
362
+ )
363
+ elif isinstance(node, DrawableRichText):
364
+ shape = shapes.add_textbox(Pt(x), Pt(y), Pt(w), Pt(h))
365
+ tf = _text_frame(shape, node)
366
+ tf.clear()
367
+ for line_index, visual_line in enumerate(node.metrics.lines):
368
+ paragraph = tf.paragraphs[0] if line_index == 0 else tf.add_paragraph()
369
+ paragraph.space_before = paragraph.space_after = Pt(0)
370
+ paragraph.line_spacing = (
371
+ 1.0 if node.text_placement == "rows" else Pt(visual_line.height.points)
372
+ )
373
+ for measured_run in visual_line.runs:
374
+ run = paragraph.add_run()
375
+ run.text = measured_run.text
376
+ _apply_font(
377
+ run.font,
378
+ measured_run.font,
379
+ measured_run.font_size,
380
+ measured_run.color,
381
+ opacity,
382
+ node.gradient,
383
+ explicit_typeface=measured_run.explicit_typeface,
384
+ shadow=shadow,
385
+ )
386
+ elif isinstance(node, DrawableText):
387
+ m = node.metrics
388
+ shape = shapes.add_textbox(Pt(x), Pt(y), Pt(w), Pt(h))
389
+ tf = _text_frame(shape, node)
390
+ for i, line in enumerate(m.lines):
391
+ paragraph = tf.paragraphs[0] if i == 0 else tf.add_paragraph()
392
+ paragraph.text = str(slide_number) if node.is_slide_number else line
393
+ paragraph.space_before = paragraph.space_after = Pt(0)
394
+ paragraph.line_spacing = (
395
+ 1.0 if node.text_placement == "rows" else Pt(m.line_height.points)
396
+ )
397
+ _apply_font(
398
+ paragraph.font,
399
+ node.font,
400
+ node.font_size,
401
+ node.color,
402
+ opacity,
403
+ node.gradient,
404
+ explicit_typeface=node.explicit_typeface,
405
+ )
406
+ for run in paragraph.runs:
407
+ _apply_font(
408
+ run.font,
409
+ node.font,
410
+ node.font_size,
411
+ node.color,
412
+ opacity,
413
+ node.gradient,
414
+ explicit_typeface=node.explicit_typeface,
415
+ shadow=shadow,
416
+ )
417
+ if node.is_slide_number:
418
+ paragraph.alignment = PP_ALIGN.RIGHT
419
+ (run,) = paragraph.runs
420
+ field = _element(
421
+ "a:fld", id="{" + str(uuid4()).upper() + "}", type="slidenum"
422
+ )
423
+ field.extend(list(run._r))
424
+ paragraph._p.replace(run._r, field)
425
+ elif isinstance(node, DrawableImage):
426
+ iw, ih = node.intrinsic_pixels
427
+ if node.fit == "contain":
428
+ scale = min(w / iw, h / ih)
429
+ rw, rh = iw * scale, ih * scale
430
+ shape = shapes.add_picture(
431
+ BytesIO(node.data),
432
+ Pt(x + (w - rw) / 2),
433
+ Pt(y + (h - rh) / 2),
434
+ Pt(rw),
435
+ Pt(rh),
436
+ )
437
+ else:
438
+ shape = shapes.add_picture(BytesIO(node.data), Pt(x), Pt(y), Pt(w), Pt(h))
439
+ scale = max(w / iw, h / ih)
440
+ shape.crop_left = shape.crop_right = (1 - w / (iw * scale)) / 2
441
+ shape.crop_top = shape.crop_bottom = (1 - h / (ih * scale)) / 2
442
+ if opacity < 1:
443
+ blip = shape.element.find(".//" + qn("a:blip"))
444
+ blip.append(_element("a:alphaModFix", amt=round(opacity * 100000)))
445
+ elif isinstance(node, (DrawableConnector, DrawableLine)):
446
+ rule = _solid_rule_bounds(node) if isinstance(node, DrawableLine) else None
447
+ if rule is not None:
448
+ # Quick Look can render filled rules directly in its slide
449
+ # preview instead of caching a separate drawing for each line.
450
+ shape = shapes.add_shape(
451
+ MSO_SHAPE.RECTANGLE,
452
+ Pt(rule.x.points),
453
+ Pt(rule.y.points),
454
+ Pt(rule.width.points),
455
+ Pt(rule.height.points),
456
+ )
457
+ _apply_fill(shape.fill, node.color, node.opacity * opacity)
458
+ shape.line.fill.background()
459
+ else:
460
+ shape = shapes.add_connector(
461
+ MSO_CONNECTOR.STRAIGHT,
462
+ Pt(node.start.x.points),
463
+ Pt(node.start.y.points),
464
+ Pt(node.end.x.points),
465
+ Pt(node.end.y.points),
466
+ )
467
+ _apply_stroke(
468
+ shape.line,
469
+ node.color,
470
+ node.width,
471
+ node.dash,
472
+ node.opacity * opacity,
473
+ node.line_cap,
474
+ node.line_join,
475
+ )
476
+ if isinstance(node, DrawableConnector):
477
+ line = shape.line._get_or_add_ln()
478
+ if node.start_cap == "arrow":
479
+ start = OxmlElement("a:headEnd")
480
+ start.set("type", "triangle")
481
+ line.append(start)
482
+ if node.end_cap == "arrow":
483
+ end = OxmlElement("a:tailEnd")
484
+ end.set("type", "triangle")
485
+ line.append(end)
486
+ elif isinstance(node, DrawablePath):
487
+ points = _path_points(node)
488
+ if not points:
489
+ return None
490
+ builder = shapes.build_freeform(
491
+ _path_coordinate(points[0].x),
492
+ _path_coordinate(points[0].y),
493
+ scale=1,
494
+ )
495
+ builder.add_line_segments(
496
+ [
497
+ (_path_coordinate(point.x), _path_coordinate(point.y))
498
+ for point in points[1:]
499
+ ],
500
+ close=any(isinstance(command, PathClose) for command in node.commands),
501
+ )
502
+ shape = builder.convert_to_shape()
503
+ _replace_freeform_path(shape, node)
504
+ if node.fill is None:
505
+ shape.fill.background()
506
+ else:
507
+ shape.fill.solid()
508
+ shape.fill.fore_color.rgb = _color(node.fill)
509
+ _apply_alpha(shape.fill._xPr, node.fill_opacity * opacity)
510
+ if node.stroke is None:
511
+ shape.line.fill.background()
512
+ else:
513
+ _apply_stroke(
514
+ shape.line,
515
+ node.stroke,
516
+ node.stroke_width,
517
+ node.dash,
518
+ node.stroke_opacity * opacity,
519
+ node.line_cap,
520
+ node.line_join,
521
+ )
522
+ elif isinstance(node, DrawableGroup):
523
+ return None
524
+ else:
525
+ raise TypeError(f"PPTX cannot render {type(node).__name__}")
526
+ # Generated geometry takes its appearance from the scene, including the
527
+ # absence of effects. The default shape style can add a theme shadow.
528
+ style = shape.element.find(qn("p:style"))
529
+ if style is not None:
530
+ effect = style.find(qn("a:effectRef"))
531
+ if effect is not None:
532
+ effect.set("idx", "0")
533
+ if shadow is not None and not isinstance(node, (DrawableText, DrawableRichText)):
534
+ _apply_shadow(
535
+ shape.element.find(qn("p:spPr")), shadow, "a:scene3d", "a:sp3d", "a:extLst"
536
+ )
537
+ shape.name = name or node.identity
538
+ return shape
539
+
540
+
541
+ def _text_rows(
542
+ node: DrawableText | DrawableRichText,
543
+ ) -> Iterator[DrawableText | DrawableRichText]:
544
+ rows: Iterator[DrawableText | DrawableRichText]
545
+ if isinstance(node, DrawableText):
546
+ metrics = node.metrics
547
+ rows = (
548
+ replace(
549
+ node,
550
+ metrics=replace(metrics, lines=(line,), height=metrics.line_height),
551
+ )
552
+ for line in metrics.lines
553
+ )
554
+ else:
555
+ rich_metrics = node.metrics
556
+ rows = (
557
+ replace(
558
+ node, metrics=replace(rich_metrics, lines=(line,), height=line.height)
559
+ )
560
+ for line in rich_metrics.lines
561
+ )
562
+ bounds = node.content_bounds
563
+ y = bounds.y
564
+ for row in rows:
565
+ height = row.metrics.height
566
+ yield replace(row, content_bounds=replace(bounds, y=y, height=height))
567
+ y += height
568
+
569
+
570
+ def _add_shapes(
571
+ shapes: Any, node: Drawable, slide_number: int, *, name: str | None = None
572
+ ) -> tuple[Any, ...]:
573
+ if isinstance(node, NativeTable):
574
+ return (add_native_table(shapes, node, name),)
575
+ shadow = node.metadata.shadow
576
+ if (
577
+ shadow is not None
578
+ and isinstance(node, DrawableRichText)
579
+ and any(isinstance(child, DrawableRectangle) for child in node.children)
580
+ ):
581
+ # The text and its highlights paint a single silhouette.
582
+ group = shapes.add_group_shape()
583
+ group.name = name or node.identity
584
+ _apply_shadow(group.element.grpSpPr, shadow, "a:scene3d", "a:extLst")
585
+ plain = replace(node, metadata=replace(node.metadata, shadow=None))
586
+ _add_shapes(group.shapes, plain, slide_number, name=name)
587
+ return (group,)
588
+ backgrounds = (
589
+ tuple(
590
+ _add_node(shapes, child, slide_number)
591
+ for child in node.children
592
+ if isinstance(child, DrawableRectangle)
593
+ )
594
+ if isinstance(node, DrawableRichText)
595
+ else ()
596
+ )
597
+ if (
598
+ isinstance(node, (DrawableText, DrawableRichText))
599
+ and node.text_placement == "rows"
600
+ ):
601
+ row_name = name or node.identity
602
+ if len(node.metrics.lines) == 1:
603
+ return (*backgrounds, _add_node(shapes, node, slide_number, name=row_name))
604
+ textboxes = tuple(
605
+ _add_node(shapes, row, slide_number, name=f"{row_name}/row:{index}")
606
+ for index, row in enumerate(_text_rows(node))
607
+ )
608
+ return (*backgrounds, *textboxes)
609
+ return (*backgrounds, _add_node(shapes, node, slide_number, name=name))
610
+
611
+
612
+ def _new_presentation(width: float, height: float) -> Any:
613
+ from pptx import Presentation
614
+ from pptx.util import Pt
615
+
616
+ prs = Presentation()
617
+ prs.slide_width, prs.slide_height = Pt(width), Pt(height)
618
+ return prs
619
+
620
+
621
+ def render(
622
+ deck: CompiledDeck,
623
+ path: str | PathLike[str],
624
+ *,
625
+ embed_fonts: bool = False,
626
+ embedded_fonts: Sequence[EmbeddedFont] = (),
627
+ shadow_fallback: ShadowFallback = ShadowFallback.ERROR,
628
+ ) -> None:
629
+ """Render logical slides, optionally embedding all resolved text faces."""
630
+ if not isinstance(shadow_fallback, ShadowFallback):
631
+ raise TypeError("shadow_fallback must be a ShadowFallback")
632
+ if not deck.slides:
633
+ raise ValueError("At least one slide is required")
634
+ first = deck.slides[0].initial.drawable
635
+ prs = _new_presentation(first.bounds.width.points, first.bounds.height.points)
636
+ locations = [
637
+ SlideLocation(number, slide.label)
638
+ for number, slide in enumerate(deck.slides, start=1)
639
+ ]
640
+ for location, compiled_slide in zip(locations, deck.slides):
641
+ with location.context():
642
+ layout = compiled_slide.initial.drawable
643
+ if (layout.bounds.width, layout.bounds.height) != (
644
+ first.bounds.width,
645
+ first.bounds.height,
646
+ ):
647
+ raise ValueError("PPTX slides must share a canvas size")
648
+ lowered = lower_native_tables(compiled_slide, location)
649
+ _render_slide(
650
+ prs, prepare_shadows(lowered, shadow_fallback, location), location
651
+ )
652
+ scenes = (
653
+ (location, step, state.drawable)
654
+ for location, slide in zip(locations, deck.slides)
655
+ for step, state in enumerate(slide.states)
656
+ )
657
+ fonts, uses = collect_embedded_fonts(
658
+ scenes, embedded_fonts, include_custom=embed_fonts
659
+ )
660
+ embed_font_parts(prs, fonts, uses)
661
+ prs.save(str(path))
662
+
663
+
664
+ @dataclass(frozen=True)
665
+ class _GroupKey:
666
+ identity: str
667
+ shadow: ResolvedShadow | None
668
+
669
+
670
+ @dataclass(frozen=True)
671
+ class _ExportItem:
672
+ node: Drawable
673
+ parent: tuple[_GroupKey, ...]
674
+
675
+ @property
676
+ def group_address(self) -> tuple[_GroupKey, ...]:
677
+ return (*self.parent, _GroupKey(self.node.identity, self.node.metadata.shadow))
678
+
679
+
680
+ def _export_items(root: Drawable, shadow_groups: set[str]) -> dict[str, _ExportItem]:
681
+ """Retain authored groups and groups needed to carry a native shadow."""
682
+ items: dict[str, _ExportItem] = {}
683
+
684
+ def visit(node: Drawable, parent: tuple[_GroupKey, ...]) -> None:
685
+ if isinstance(node, DrawableGroup):
686
+ if node.metadata.grouped or node.identity in shadow_groups:
687
+ item = _ExportItem(node, parent)
688
+ items[node.identity] = item
689
+ parent = item.group_address
690
+ for child in node.children:
691
+ visit(child, parent)
692
+ else:
693
+ items[node.identity] = _ExportItem(node, parent)
694
+
695
+ visit(root, ())
696
+ return items
697
+
698
+
699
+ def _walk_shapes(shapes: Any) -> Iterator[Any]:
700
+ for shape in shapes:
701
+ yield shape
702
+ if hasattr(shape, "shapes"):
703
+ yield from _walk_shapes(shape.shapes)
704
+
705
+
706
+ def _element(name: str, **attributes: object) -> Any:
707
+ from pptx.oxml.xmlchemy import OxmlElement
708
+
709
+ result = OxmlElement(name)
710
+ for key, value in attributes.items():
711
+ result.set(key.rstrip("_"), str(value))
712
+ return result
713
+
714
+
715
+ def _common_behavior(
716
+ parent: Any,
717
+ node_id: int,
718
+ duration: int,
719
+ shape_id: int,
720
+ *,
721
+ delay: int | None = None,
722
+ hold: bool = True,
723
+ ) -> int:
724
+ behavior = _element("p:cBhvr")
725
+ parent.append(behavior)
726
+ attributes: dict[str, object] = {"id": node_id, "dur": max(duration, 1)}
727
+ if hold:
728
+ attributes["fill"] = "hold"
729
+ time_node = _element("p:cTn", **attributes)
730
+ if delay is not None:
731
+ conditions = _element("p:stCondLst")
732
+ conditions.append(_element("p:cond", delay=delay))
733
+ time_node.append(conditions)
734
+ behavior.append(time_node)
735
+ target = _element("p:tgtEl")
736
+ target.append(_element("p:spTgt", spid=shape_id))
737
+ behavior.append(target)
738
+ return node_id + 1
739
+
740
+
741
+ def _set_visibility(
742
+ shape_id: int, node_id: int, visible: bool, *, delay: int = 0
743
+ ) -> tuple[Any, int]:
744
+ result = _element("p:set")
745
+ node_id = _common_behavior(result, node_id, 1, shape_id, delay=delay)
746
+ behavior = result.find(
747
+ "{http://schemas.openxmlformats.org/presentationml/2006/main}cBhvr"
748
+ )
749
+ names = _element("p:attrNameLst")
750
+ name = _element("p:attrName")
751
+ name.text = "style.visibility"
752
+ names.append(name)
753
+ behavior.append(names)
754
+ destination = _element("p:to")
755
+ destination.append(_element("p:strVal", val=("visible" if visible else "hidden")))
756
+ result.append(destination)
757
+ return result, node_id
758
+
759
+
760
+ def _effect_elements(
761
+ kind: PptxBehaviorKind,
762
+ shape_id: int,
763
+ node_id: int,
764
+ duration: int,
765
+ motion_path: str | None = None,
766
+ ) -> tuple[list[Any], int]:
767
+ if kind is PptxBehaviorKind.MOTION:
768
+ assert motion_path is not None
769
+ result = _element(
770
+ "p:animMotion",
771
+ origin="layout",
772
+ path=motion_path,
773
+ pathEditMode="relative",
774
+ ptsTypes="",
775
+ )
776
+ node_id = _common_behavior(result, node_id, duration, shape_id)
777
+ behavior = result.find(
778
+ "{http://schemas.openxmlformats.org/presentationml/2006/main}cBhvr"
779
+ )
780
+ names = _element("p:attrNameLst")
781
+ for value in ("ppt_x", "ppt_y"):
782
+ item = _element("p:attrName")
783
+ item.text = value
784
+ names.append(item)
785
+ behavior.append(names)
786
+ return [result], node_id
787
+ if kind is PptxBehaviorKind.APPEAR:
788
+ result, node_id = _set_visibility(shape_id, node_id, True)
789
+ return [result], node_id
790
+ if kind is PptxBehaviorKind.DISAPPEAR:
791
+ result, node_id = _set_visibility(shape_id, node_id, False)
792
+ return [result], node_id
793
+ transition = "out" if kind is PptxBehaviorKind.FADE_OUT else "in"
794
+ result = _element("p:animEffect", transition=transition, filter="fade")
795
+ node_id = _common_behavior(result, node_id, duration, shape_id, hold=False)
796
+ if kind is PptxBehaviorKind.FADE_IN:
797
+ visibility, node_id = _set_visibility(shape_id, node_id, True)
798
+ return [visibility, result], node_id
799
+ visibility, node_id = _set_visibility(
800
+ shape_id, node_id, False, delay=max(duration - 1, 0)
801
+ )
802
+ return [result, visibility], node_id
803
+
804
+
805
+ def _preset(kind: PptxBehaviorKind) -> tuple[int | None, str | None]:
806
+ if kind is PptxBehaviorKind.MOTION:
807
+ # PowerPoint classifies native motion effects separately from generic
808
+ # behaviors. Without the path preset metadata, clients can retain the
809
+ # timing row but ignore the animMotion payload during playback.
810
+ return 42, "path"
811
+ if kind in (PptxBehaviorKind.FADE_IN, PptxBehaviorKind.FADE_OUT):
812
+ return 10, "exit" if kind is PptxBehaviorKind.FADE_OUT else "entr"
813
+ if kind in (PptxBehaviorKind.APPEAR, PptxBehaviorKind.DISAPPEAR):
814
+ return 1, "exit" if kind is PptxBehaviorKind.DISAPPEAR else "entr"
815
+ return None, None
816
+
817
+
818
+ def _append_timing(
819
+ slide: Any,
820
+ compiled_slide: CompiledSlide,
821
+ shape_ids: dict[tuple[str, int], tuple[int, ...]],
822
+ shape_origins: dict[tuple[str, int], Bounds],
823
+ location: SlideLocation,
824
+ ) -> None:
825
+ plan = plan_slide(compiled_slide, location=location)
826
+ slide_bounds = compiled_slide.initial.drawable.bounds
827
+ timing = _element("p:timing")
828
+ timing_list = _element("p:tnLst")
829
+ timing.append(timing_list)
830
+ root = _element("p:par")
831
+ timing_list.append(root)
832
+ root_time = _element(
833
+ "p:cTn", id=1, dur="indefinite", restart="never", nodeType="tmRoot"
834
+ )
835
+ root.append(root_time)
836
+ root_children = _element("p:childTnLst")
837
+ root_time.append(root_children)
838
+ sequence_node = _element("p:seq", concurrent=1, nextAc="seek")
839
+ root_children.append(sequence_node)
840
+ sequence_time = _element("p:cTn", id=2, dur="indefinite", nodeType="mainSeq")
841
+ sequence_node.append(sequence_time)
842
+ sequence_children = _element("p:childTnLst")
843
+ sequence_time.append(sequence_children)
844
+
845
+ node_id = 3
846
+ active_version = {identity: 0 for identity, version in shape_ids if version == 0}
847
+ effect_counts: dict[int, int] = {}
848
+ click_children: Any = None
849
+ effects_element: Any = None
850
+ group_start = build_start = build_end = 0
851
+ for build_index, (source, lowered) in enumerate(
852
+ zip(compiled_slide.animation.builds, plan.builds), start=1
853
+ ):
854
+ on_click = lowered.trigger is PptxTrigger.ON_CLICK
855
+ if on_click or click_children is None:
856
+ # The main sequence seeks between these groups on Back and Forward.
857
+ click_par = _element("p:par")
858
+ sequence_children.append(click_par)
859
+ click_time = _element("p:cTn", id=node_id, fill="hold")
860
+ node_id += 1
861
+ click_par.append(click_time)
862
+ conditions = _element("p:stCondLst")
863
+ conditions.append(_element("p:cond", delay="indefinite"))
864
+ if not on_click:
865
+ begin = _element("p:cond", evt="onBegin", delay=0)
866
+ begin.append(_element("p:tn", val=sequence_time.get("id")))
867
+ conditions.append(begin)
868
+ click_time.append(conditions)
869
+ click_children = _element("p:childTnLst")
870
+ click_time.append(click_children)
871
+ effects_element = None
872
+ build_start = build_end = 0
873
+
874
+ after_previous = lowered.trigger is PptxTrigger.AFTER_PREVIOUS
875
+ build_start = (build_end if after_previous else build_start) + lowered.delay_ms
876
+ build_end = build_start
877
+ # After Previous starts a new parallel group at an offset from the click.
878
+ # With Previous shares the last parallel group and offsets its effects.
879
+ if effects_element is None or after_previous:
880
+ group_start = build_start
881
+ synchronized = _element("p:par")
882
+ click_children.append(synchronized)
883
+ synchronized_time = _element("p:cTn", id=node_id, fill="hold")
884
+ node_id += 1
885
+ synchronized.append(synchronized_time)
886
+ conditions = _element("p:stCondLst")
887
+ conditions.append(_element("p:cond", delay=group_start))
888
+ synchronized_time.append(conditions)
889
+ effects_element = _element("p:childTnLst")
890
+ synchronized_time.append(effects_element)
891
+ effect_number = 0
892
+
893
+ for effect, behavior in zip(source.effects, lowered.behaviors):
894
+ targets: list[tuple[PptxBehaviorKind, int]] = []
895
+ current = active_version.get(effect.identity, 0)
896
+ if behavior.kind is PptxBehaviorKind.CROSSFADE:
897
+ targets.append((PptxBehaviorKind.FADE_OUT, current))
898
+ targets.append((PptxBehaviorKind.FADE_IN, build_index))
899
+ active_version[effect.identity] = build_index
900
+ elif (
901
+ behavior.kind is PptxBehaviorKind.DISCRETE
902
+ and effect.kind is EffectKind.CHANGE
903
+ ):
904
+ targets.append((PptxBehaviorKind.DISAPPEAR, current))
905
+ targets.append((PptxBehaviorKind.APPEAR, build_index))
906
+ active_version[effect.identity] = build_index
907
+ elif (
908
+ behavior.kind is PptxBehaviorKind.DISCRETE
909
+ and effect.kind is EffectKind.MOVE
910
+ ):
911
+ assert behavior.before is not None and behavior.after is not None
912
+ if not _same_size(behavior.before, behavior.after):
913
+ targets.append((PptxBehaviorKind.DISAPPEAR, current))
914
+ targets.append((PptxBehaviorKind.APPEAR, build_index))
915
+ active_version[effect.identity] = build_index
916
+ else:
917
+ targets.append((PptxBehaviorKind.MOTION, current))
918
+ else:
919
+ if effect.kind is EffectKind.INSERT:
920
+ current = build_index
921
+ active_version[effect.identity] = current
922
+ targets.append((behavior.kind, current))
923
+ with location.context(build_index):
924
+ target_shapes = [
925
+ (kind, version, shape_id)
926
+ for kind, version in targets
927
+ for shape_id in shape_ids[(effect.identity, version)]
928
+ ]
929
+ for target_kind, target_version, shape_id in target_shapes:
930
+ group_id = effect_counts.get(shape_id, 0)
931
+ effect_counts[shape_id] = group_id + 1
932
+ motion_path = None
933
+ if target_kind is PptxBehaviorKind.MOTION:
934
+ assert behavior.before is not None and behavior.after is not None
935
+ # PowerPoint anchors every path to the emitted shape's layout position.
936
+ with location.context(build_index):
937
+ origin = shape_origins[(effect.identity, target_version)]
938
+ width, height = (
939
+ slide_bounds.width.points,
940
+ slide_bounds.height.points,
941
+ )
942
+ start_x = (behavior.before.x - origin.x).points / width
943
+ start_y = (behavior.before.y - origin.y).points / height
944
+ end_x = (behavior.after.x - origin.x).points / width
945
+ end_y = (behavior.after.y - origin.y).points / height
946
+ motion_path = f"M {start_x:g} {start_y:g} L {end_x:g} {end_y:g} E"
947
+ preset_id, preset_class = _preset(target_kind)
948
+ effect_attributes: dict[str, object] = {
949
+ "id": node_id,
950
+ "fill": "hold",
951
+ "grpId": group_id,
952
+ "nodeType": (
953
+ "clickEffect"
954
+ if effect_number == 0 and on_click
955
+ else "afterEffect"
956
+ if effect_number == 0 and after_previous
957
+ else "withEffect"
958
+ ),
959
+ }
960
+ if preset_id is not None:
961
+ effect_attributes.update(
962
+ presetID=preset_id,
963
+ presetClass=preset_class,
964
+ presetSubtype=0,
965
+ )
966
+ effect_number += 1
967
+ effect_par = _element("p:par")
968
+ effect_time = _element("p:cTn", **effect_attributes)
969
+ node_id += 1
970
+ effect_par.append(effect_time)
971
+ effect_conditions = _element("p:stCondLst")
972
+ effect_start = build_start + behavior.delay_ms
973
+ effect_conditions.append(
974
+ _element("p:cond", delay=effect_start - group_start)
975
+ )
976
+ effect_time.append(effect_conditions)
977
+ behavior_list = _element("p:childTnLst")
978
+ effect_time.append(behavior_list)
979
+ # A visibility set takes 1 ms. Other effects run for their
980
+ # emitted duration, including the minimum nonzero duration.
981
+ duration = (
982
+ 1
983
+ if target_kind
984
+ in (PptxBehaviorKind.APPEAR, PptxBehaviorKind.DISAPPEAR)
985
+ else max(behavior.duration_ms, 1)
986
+ )
987
+ build_end = max(build_end, effect_start + duration)
988
+ elements, node_id = _effect_elements(
989
+ target_kind,
990
+ shape_id,
991
+ node_id,
992
+ duration,
993
+ motion_path,
994
+ )
995
+ for element in elements:
996
+ behavior_list.append(element)
997
+ effects_element.append(effect_par)
998
+ for name, event in (("p:prevCondLst", "onPrev"), ("p:nextCondLst", "onNext")):
999
+ navigation = _element(name)
1000
+ condition = _element("p:cond", evt=event, delay=0)
1001
+ target = _element("p:tgtEl")
1002
+ target.append(_element("p:sldTgt"))
1003
+ condition.append(target)
1004
+ navigation.append(condition)
1005
+ sequence_node.append(navigation)
1006
+ power_point_builds = _element("p:bldLst")
1007
+ # Paragraph builds target shapes with text. Other shapes animate through
1008
+ # their timing targets without an entry in the paragraph build list.
1009
+ for shape in _walk_shapes(slide.shapes):
1010
+ if shape.has_text_frame and shape.text:
1011
+ for group_id in range(effect_counts.get(shape.shape_id, 0)):
1012
+ power_point_builds.append(
1013
+ _element("p:bldP", spid=shape.shape_id, grpId=group_id)
1014
+ )
1015
+ if len(power_point_builds):
1016
+ timing.append(power_point_builds)
1017
+ slide._element.append(timing)
1018
+
1019
+
1020
+ def _add_group_visibility(
1021
+ builds: list[BuildProgram],
1022
+ states: list[dict[str, _ExportItem]],
1023
+ groups: dict[tuple[_GroupKey, ...], Any],
1024
+ shape_ids: dict[tuple[str, int], tuple[int, ...]],
1025
+ ) -> None:
1026
+ # Explicitly hide inactive versions so their shadows cannot show through
1027
+ # before their children enter or after their children leave.
1028
+ styles: dict[str, set[ResolvedShadow | None]] = {}
1029
+ for address in groups:
1030
+ key = address[-1]
1031
+ styles.setdefault(key.identity, set()).add(key.shadow)
1032
+ changing = {identity for identity, values in styles.items() if len(values) > 1}
1033
+ if not changing:
1034
+ return
1035
+
1036
+ active: list[dict[int, Drawable]] = []
1037
+ for state in states:
1038
+ active_groups: dict[int, Drawable] = {}
1039
+ for item in state.values():
1040
+ if isinstance(item.node, DrawableGroup):
1041
+ continue
1042
+ for depth, key in enumerate(item.parent, start=1):
1043
+ if key.identity not in changing:
1044
+ continue
1045
+ shape_id = groups[item.parent[:depth]].shape_id
1046
+ active_groups[shape_id] = state[key.identity].node
1047
+ active.append(active_groups)
1048
+ for shape_id in active[0]:
1049
+ shape_ids[(f"pptx:group:{shape_id}", 0)] = (shape_id,)
1050
+ for i, (before, after) in enumerate(zip(active, active[1:]), start=1):
1051
+ additional = []
1052
+ for shape_id in sorted(before.keys() ^ after.keys()):
1053
+ identity = f"pptx:group:{shape_id}"
1054
+ if shape_id in after:
1055
+ node = after[shape_id]
1056
+ shape_ids[(identity, i)] = (shape_id,)
1057
+ additional.append(
1058
+ EffectInstance(
1059
+ identity,
1060
+ EffectKind.INSERT,
1061
+ None,
1062
+ VisualState(node.bounds, node),
1063
+ )
1064
+ )
1065
+ else:
1066
+ node = before[shape_id]
1067
+ additional.append(
1068
+ EffectInstance(
1069
+ identity,
1070
+ EffectKind.REMOVE,
1071
+ VisualState(node.bounds, node),
1072
+ None,
1073
+ )
1074
+ )
1075
+ builds[i - 1] = replace(
1076
+ builds[i - 1], effects=(*builds[i - 1].effects, *additional)
1077
+ )
1078
+
1079
+
1080
+ def _render_slide(
1081
+ prs: Any, compiled_slide: CompiledSlide, location: SlideLocation
1082
+ ) -> None:
1083
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
1084
+ shadow_groups = {
1085
+ node.identity
1086
+ for state in compiled_slide.states
1087
+ for node in state.drawable.walk()
1088
+ if isinstance(node, DrawableGroup) and node.metadata.shadow is not None
1089
+ }
1090
+ states = [
1091
+ _export_items(state.drawable, shadow_groups) for state in compiled_slide.states
1092
+ ]
1093
+ shape_ids: dict[tuple[str, int], tuple[int, ...]] = {}
1094
+ shape_origins: dict[tuple[str, int], Bounds] = {}
1095
+ groups: dict[tuple[_GroupKey, ...], Any] = {}
1096
+
1097
+ def position(
1098
+ shapes: Any,
1099
+ added: tuple[Any, ...],
1100
+ item: _ExportItem,
1101
+ state: dict[str, _ExportItem],
1102
+ ) -> None:
1103
+ siblings = (
1104
+ identity
1105
+ for identity, sibling in state.items()
1106
+ if sibling.parent == item.parent
1107
+ )
1108
+ for identity in siblings:
1109
+ if identity == item.node.identity:
1110
+ break
1111
+ following = set(siblings)
1112
+ if not following:
1113
+ return
1114
+ later_ids = {
1115
+ shape_id
1116
+ for (identity, _), ids in shape_ids.items()
1117
+ if identity in following
1118
+ for shape_id in ids
1119
+ }
1120
+ later_ids.update(
1121
+ group.shape_id
1122
+ for address, group in groups.items()
1123
+ if address[:-1] == item.parent and address[-1].identity in following
1124
+ )
1125
+ for candidate in shapes:
1126
+ if candidate.shape_id in later_ids:
1127
+ for shape in added:
1128
+ candidate._element.addprevious(shape._element)
1129
+ break
1130
+
1131
+ def shape_tree(parent: tuple[_GroupKey, ...], build_index: int) -> Any:
1132
+ if not parent:
1133
+ return slide.shapes
1134
+ if parent not in groups:
1135
+ state = states[build_index]
1136
+ item = state[parent[-1].identity]
1137
+ containers = shape_tree(item.parent, build_index)
1138
+ group = containers.add_group_shape()
1139
+ group.name = item.node.metadata.group_name or item.node.identity
1140
+ if item.node.metadata.shadow is not None:
1141
+ _apply_shadow(
1142
+ group.element.grpSpPr,
1143
+ item.node.metadata.shadow,
1144
+ "a:scene3d",
1145
+ "a:extLst",
1146
+ )
1147
+ groups[parent] = group
1148
+ if build_index:
1149
+ position(containers, (group,), item, state)
1150
+ return groups[parent].shapes
1151
+
1152
+ def add_shape(node: Drawable, build_index: int, *, name: str | None = None) -> None:
1153
+ with location.context(build_index):
1154
+ state = states[build_index]
1155
+ item = state[node.identity]
1156
+ tree = shape_tree(item.parent, build_index)
1157
+ shapes = _add_shapes(tree, node, location.number, name=name)
1158
+ shape_ids[(node.identity, build_index)] = tuple(
1159
+ shape.shape_id for shape in shapes
1160
+ )
1161
+ shape_origins[(node.identity, build_index)] = node.bounds
1162
+ if build_index:
1163
+ position(tree, shapes, item, state)
1164
+
1165
+ for item in states[0].values():
1166
+ if not isinstance(item.node, DrawableGroup):
1167
+ add_shape(item.node, 0)
1168
+ if not compiled_slide.is_animated:
1169
+ return
1170
+
1171
+ builds = []
1172
+ for index, build in enumerate(compiled_slide.animation.builds):
1173
+ before, after = states[index], states[index + 1]
1174
+ effects = {effect.identity: effect for effect in build.effects}
1175
+ for identity in sorted(before.keys() & after.keys()):
1176
+ old, new = before[identity], after[identity]
1177
+ if old.parent == new.parent or isinstance(new.node, DrawableGroup):
1178
+ continue
1179
+ # The old shape stays in its group. Materialize a version in the
1180
+ # new group even if the underlying drawable has not changed.
1181
+ left = VisualState(old.node.bounds, old.node)
1182
+ right = VisualState(new.node.bounds, new.node)
1183
+ original = effects.get(identity)
1184
+ # Versions of a group with different shadow settings switch at the
1185
+ # build boundary. Descendants start at the new version's geometry.
1186
+ same_group_path = tuple(key.identity for key in old.parent) == tuple(
1187
+ key.identity for key in new.parent
1188
+ )
1189
+ effects[identity] = (
1190
+ EffectInstance(identity, EffectKind.CHANGE, left, right)
1191
+ if original is None or same_group_path
1192
+ else replace(original, kind=EffectKind.CHANGE)
1193
+ )
1194
+ builds.append(replace(build, effects=tuple(effects.values())))
1195
+ compiled_slide = replace(compiled_slide, animation=AnimationProgram(tuple(builds)))
1196
+ lowered = plan_slide(compiled_slide, location=location)
1197
+ for build_index, (build, planned) in enumerate(
1198
+ zip(compiled_slide.animation.builds, lowered.builds), start=1
1199
+ ):
1200
+ for effect, behavior in zip(build.effects, planned.behaviors):
1201
+ discrete_resize = (
1202
+ effect.kind is EffectKind.MOVE
1203
+ and behavior.kind is PptxBehaviorKind.DISCRETE
1204
+ and behavior.before is not None
1205
+ and behavior.after is not None
1206
+ and not _same_size(behavior.before, behavior.after)
1207
+ )
1208
+ if (
1209
+ effect.kind in (EffectKind.INSERT, EffectKind.CHANGE)
1210
+ or (
1211
+ effect.kind is EffectKind.MOVE
1212
+ and behavior.kind is PptxBehaviorKind.CROSSFADE
1213
+ )
1214
+ or discrete_resize
1215
+ ):
1216
+ assert effect.after is not None
1217
+ add_shape(
1218
+ effect.after.drawable,
1219
+ build_index,
1220
+ name=f"{effect.identity}#build-{build_index}",
1221
+ )
1222
+
1223
+ _add_group_visibility(builds, states, groups, shape_ids)
1224
+ compiled_slide = replace(compiled_slide, animation=AnimationProgram(tuple(builds)))
1225
+ _append_timing(slide, compiled_slide, shape_ids, shape_origins, location)