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,306 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass, field
5
+ from math import cos, isfinite, pi, sin
6
+ from typing import Literal
7
+
8
+ from ..drawables import (
9
+ Bounds,
10
+ Drawable,
11
+ DrawableEllipse,
12
+ DrawableLine,
13
+ DrawableMetadata,
14
+ DrawableRectangle,
15
+ )
16
+ from ..drawables.rich_text import measured_text_drawable
17
+ from ..effects import ShadowStyle
18
+ from ..geometry import Point
19
+ from ..measurement import (
20
+ MeasuredRichText,
21
+ StyledTextLine,
22
+ StyledTextSpan,
23
+ layout_styled_text,
24
+ )
25
+ from ..theme import ColorStyle, ForegroundColor, TextStyle, Typography
26
+ from ..tokens import DesignToken
27
+ from ..units import Length, pt, require_length
28
+ from ._geometry import (
29
+ point_bounds,
30
+ translate_bounds,
31
+ translate_point,
32
+ validate_bounds,
33
+ validate_key,
34
+ validate_opacity,
35
+ )
36
+ from .context import CanvasContext
37
+ from .style import Stroke
38
+
39
+
40
+ class CanvasElement(ABC):
41
+ key: str | None
42
+ shadow: ShadowStyle | None = None
43
+
44
+ @property
45
+ @abstractmethod
46
+ def anchor_bounds(self) -> Bounds:
47
+ """Return this element's visible bounds in Canvas-local coordinates."""
48
+ raise NotImplementedError
49
+
50
+ @abstractmethod
51
+ def make_drawable(
52
+ self,
53
+ identity: str,
54
+ origin: Point,
55
+ context: CanvasContext,
56
+ metadata: DrawableMetadata,
57
+ ) -> Drawable:
58
+ raise NotImplementedError
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class CanvasText(CanvasElement):
63
+ text: str
64
+ position: Point
65
+ typography: DesignToken[Typography] | Typography = TextStyle
66
+ color: ColorStyle = ForegroundColor
67
+ horizontal_alignment: Literal["left", "center", "right"] = "left"
68
+ vertical_alignment: Literal["top", "center", "bottom"] = "top"
69
+ key: str | None = None
70
+ rotation: float = 0.0
71
+ shadow: ShadowStyle | None = None
72
+
73
+ def __post_init__(self) -> None:
74
+ validate_key(self.key)
75
+ if not isinstance(self.text, str):
76
+ raise TypeError("CanvasText.text must be a string")
77
+ if "\n" in self.text:
78
+ raise ValueError("CanvasText currently supports one line")
79
+ if self.horizontal_alignment not in ("left", "center", "right"):
80
+ raise ValueError("Unknown horizontal CanvasText alignment")
81
+ if self.vertical_alignment not in ("top", "center", "bottom"):
82
+ raise ValueError("Unknown vertical CanvasText alignment")
83
+ if not isfinite(self.rotation):
84
+ raise ValueError("CanvasText rotation must be finite")
85
+
86
+ def _measure(self, context: CanvasContext) -> MeasuredRichText:
87
+ typography = (
88
+ self.typography
89
+ if isinstance(self.typography, Typography)
90
+ else context.environment[self.typography]
91
+ )
92
+ span = StyledTextSpan(
93
+ self.text,
94
+ typography.font,
95
+ typography.size,
96
+ typography.line_spacing,
97
+ context.color(self.color).hex,
98
+ line_height=typography.line_height,
99
+ fallback_fonts=typography.fallback_fonts,
100
+ )
101
+ return layout_styled_text(
102
+ context.measurer,
103
+ context.font_resolver,
104
+ (StyledTextLine((span,)),),
105
+ pt(1_000_000_000),
106
+ "verbatim",
107
+ )
108
+
109
+ def _local_bounds(self, metrics: MeasuredRichText) -> Bounds:
110
+ horizontal = {"left": 0.0, "center": 0.5, "right": 1.0}[
111
+ self.horizontal_alignment
112
+ ]
113
+ vertical = {"top": 0.0, "center": 0.5, "bottom": 1.0}[self.vertical_alignment]
114
+ return Bounds(
115
+ self.position.x - metrics.width * horizontal,
116
+ self.position.y - metrics.height * vertical,
117
+ metrics.width,
118
+ metrics.height,
119
+ )
120
+
121
+ @property
122
+ def anchor_bounds(self) -> Bounds:
123
+ return Bounds(self.position.x, self.position.y, pt(0), pt(0))
124
+
125
+ def measured_anchor_bounds(self, context: CanvasContext) -> Bounds:
126
+ return _rotated_bounds(
127
+ self._local_bounds(self._measure(context)), self.rotation
128
+ )
129
+
130
+ def make_drawable(
131
+ self,
132
+ identity: str,
133
+ origin: Point,
134
+ context: CanvasContext,
135
+ metadata: DrawableMetadata,
136
+ ) -> Drawable:
137
+ metrics = self._measure(context)
138
+ content_bounds = translate_bounds(self._local_bounds(metrics), origin)
139
+ bounds = _rotated_bounds(content_bounds, self.rotation)
140
+ return measured_text_drawable(
141
+ identity,
142
+ bounds,
143
+ metadata,
144
+ content_bounds,
145
+ self.text,
146
+ metrics,
147
+ metrics.width,
148
+ rotation=self.rotation,
149
+ )
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class Rect(CanvasElement):
154
+ bounds: Bounds
155
+ fill: ColorStyle = ForegroundColor
156
+ stroke: Stroke | None = None
157
+ corner_radius: Length = pt(0)
158
+ fill_opacity: float = 1.0
159
+ key: str | None = None
160
+ shadow: ShadowStyle | None = None
161
+
162
+ def __post_init__(self) -> None:
163
+ validate_key(self.key)
164
+ validate_bounds(self.bounds)
165
+ require_length(self.corner_radius)
166
+ if self.corner_radius < pt(0):
167
+ raise ValueError("Rectangle corner radius must be non-negative")
168
+ validate_opacity(self.fill_opacity)
169
+
170
+ @property
171
+ def anchor_bounds(self) -> Bounds:
172
+ return self.bounds
173
+
174
+ def make_drawable(self, identity, origin, context, metadata): # type: ignore[no-untyped-def]
175
+ bounds = translate_bounds(self.bounds, origin)
176
+ radius = Length(
177
+ min(
178
+ self.corner_radius.points,
179
+ bounds.width.points / 2,
180
+ bounds.height.points / 2,
181
+ )
182
+ )
183
+ return DrawableRectangle(
184
+ identity,
185
+ bounds,
186
+ metadata,
187
+ bounds,
188
+ context.color(self.fill).hex,
189
+ radius,
190
+ context.color(self.stroke.style).hex if self.stroke else None,
191
+ self.stroke.width if self.stroke else pt(0),
192
+ self.stroke.dash if self.stroke else (),
193
+ self.fill_opacity,
194
+ self.stroke.opacity if self.stroke else 1.0,
195
+ self.stroke.line_cap if self.stroke else "butt",
196
+ self.stroke.line_join if self.stroke else "miter",
197
+ )
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class Line(CanvasElement):
202
+ start: Point
203
+ end: Point
204
+ stroke: Stroke = field(default_factory=Stroke)
205
+ key: str | None = None
206
+ shadow: ShadowStyle | None = None
207
+
208
+ def __post_init__(self) -> None:
209
+ validate_key(self.key)
210
+
211
+ @property
212
+ def anchor_bounds(self) -> Bounds:
213
+ return point_bounds(self.start, self.end)
214
+
215
+ def make_drawable(
216
+ self,
217
+ identity: str,
218
+ origin: Point,
219
+ context: CanvasContext,
220
+ metadata: DrawableMetadata,
221
+ ) -> DrawableLine:
222
+ start = translate_point(self.start, origin)
223
+ end = translate_point(self.end, origin)
224
+ bounds = point_bounds(start, end)
225
+ return DrawableLine(
226
+ identity,
227
+ bounds,
228
+ metadata,
229
+ start,
230
+ end,
231
+ context.color(self.stroke.style).hex,
232
+ self.stroke.width,
233
+ self.stroke.dash,
234
+ self.stroke.opacity,
235
+ self.stroke.line_cap,
236
+ self.stroke.line_join,
237
+ )
238
+
239
+
240
+ @dataclass(frozen=True)
241
+ class Ellipse(CanvasElement):
242
+ bounds: Bounds
243
+ fill: ColorStyle | None = ForegroundColor
244
+ stroke: Stroke | None = None
245
+ fill_opacity: float = 1.0
246
+ key: str | None = None
247
+ shadow: ShadowStyle | None = None
248
+
249
+ def __post_init__(self) -> None:
250
+ validate_key(self.key)
251
+ validate_bounds(self.bounds)
252
+ validate_opacity(self.fill_opacity)
253
+
254
+ @property
255
+ def anchor_bounds(self) -> Bounds:
256
+ return self.bounds
257
+
258
+ def make_drawable(
259
+ self,
260
+ identity: str,
261
+ origin: Point,
262
+ context: CanvasContext,
263
+ metadata: DrawableMetadata,
264
+ ) -> DrawableEllipse:
265
+ bounds = translate_bounds(self.bounds, origin)
266
+ return DrawableEllipse(
267
+ identity,
268
+ bounds,
269
+ metadata,
270
+ bounds,
271
+ context.color(self.fill).hex if self.fill is not None else None,
272
+ context.color(self.stroke.style).hex if self.stroke else None,
273
+ self.stroke.width if self.stroke else pt(0),
274
+ self.stroke.dash if self.stroke else (),
275
+ self.fill_opacity,
276
+ self.stroke.opacity if self.stroke else 1.0,
277
+ self.stroke.line_cap if self.stroke else "butt",
278
+ self.stroke.line_join if self.stroke else "miter",
279
+ )
280
+
281
+
282
+ def _rotated_bounds(bounds: Bounds, rotation: float) -> Bounds:
283
+ if rotation % 360 == 0:
284
+ return bounds
285
+ angle = rotation * pi / 180
286
+ cosine, sine = cos(angle), sin(angle)
287
+ center_x = bounds.x + bounds.width / 2
288
+ center_y = bounds.y + bounds.height / 2
289
+ corners = (
290
+ (bounds.x, bounds.y),
291
+ (bounds.x + bounds.width, bounds.y),
292
+ (bounds.x + bounds.width, bounds.y + bounds.height),
293
+ (bounds.x, bounds.y + bounds.height),
294
+ )
295
+ rotated = tuple(
296
+ Point(
297
+ center_x + (x - center_x) * cosine - (y - center_y) * sine,
298
+ center_y + (x - center_x) * sine + (y - center_y) * cosine,
299
+ )
300
+ for x, y in corners
301
+ )
302
+ left = min(point.x for point in rotated)
303
+ top = min(point.y for point in rotated)
304
+ right = max(point.x for point in rotated)
305
+ bottom = max(point.y for point in rotated)
306
+ return Bounds(left, top, right - left, bottom - top)
deckkit/canvas/path.py ADDED
@@ -0,0 +1,250 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass, field
5
+ from math import cos, isfinite, pi, sin, tan
6
+
7
+ from ..drawables import (
8
+ Bounds,
9
+ DrawableMetadata,
10
+ DrawablePath,
11
+ DrawablePathCommand,
12
+ PathClose,
13
+ PathCubic,
14
+ PathLine,
15
+ PathMove,
16
+ PathQuadratic,
17
+ )
18
+ from ..effects import ShadowStyle
19
+ from ..geometry import Point
20
+ from ..theme import ColorStyle
21
+ from ..units import Length, pt, require_length
22
+ from ._geometry import points_bounds, translate_point, validate_key, validate_opacity
23
+ from .context import CanvasContext
24
+ from .elements import CanvasElement
25
+ from .style import Stroke
26
+
27
+
28
+ class CanvasPathCommand(ABC):
29
+ """A path command expressed in Canvas-local coordinates."""
30
+
31
+ @property
32
+ @abstractmethod
33
+ def points(self) -> tuple[Point, ...]:
34
+ """Return the points that determine this command's geometry."""
35
+ raise NotImplementedError
36
+
37
+ @property
38
+ def draws(self) -> bool:
39
+ return True
40
+
41
+ @abstractmethod
42
+ def resolve(self) -> tuple[ResolvedPathCommand, ...]:
43
+ """Resolve the command to primitives supported by every backend."""
44
+ raise NotImplementedError
45
+
46
+
47
+ class ResolvedPathCommand(CanvasPathCommand, ABC):
48
+ """A Canvas path command that can lower directly to a drawable command."""
49
+
50
+ def resolve(self) -> tuple[ResolvedPathCommand, ...]:
51
+ return (self,)
52
+
53
+ @abstractmethod
54
+ def make_drawable(self, origin: Point) -> DrawablePathCommand:
55
+ raise NotImplementedError
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class MoveTo(ResolvedPathCommand):
60
+ point: Point
61
+
62
+ @property
63
+ def points(self) -> tuple[Point, ...]:
64
+ return (self.point,)
65
+
66
+ @property
67
+ def draws(self) -> bool:
68
+ return False
69
+
70
+ def make_drawable(self, origin: Point) -> PathMove:
71
+ return PathMove(translate_point(self.point, origin))
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class LineTo(ResolvedPathCommand):
76
+ point: Point
77
+
78
+ @property
79
+ def points(self) -> tuple[Point, ...]:
80
+ return (self.point,)
81
+
82
+ def make_drawable(self, origin: Point) -> PathLine:
83
+ return PathLine(translate_point(self.point, origin))
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class QuadraticTo(ResolvedPathCommand):
88
+ control: Point
89
+ end: Point
90
+
91
+ @property
92
+ def points(self) -> tuple[Point, ...]:
93
+ return self.control, self.end
94
+
95
+ def make_drawable(self, origin: Point) -> PathQuadratic:
96
+ return PathQuadratic(
97
+ translate_point(self.control, origin), translate_point(self.end, origin)
98
+ )
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class CubicTo(ResolvedPathCommand):
103
+ control1: Point
104
+ control2: Point
105
+ end: Point
106
+
107
+ @property
108
+ def points(self) -> tuple[Point, ...]:
109
+ return self.control1, self.control2, self.end
110
+
111
+ def make_drawable(self, origin: Point) -> PathCubic:
112
+ return PathCubic(
113
+ translate_point(self.control1, origin),
114
+ translate_point(self.control2, origin),
115
+ translate_point(self.end, origin),
116
+ )
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class ArcTo(CanvasPathCommand):
121
+ """An elliptical arc using center geometry and a clockwise sweep in degrees."""
122
+
123
+ center: Point
124
+ radius_x: Length
125
+ radius_y: Length
126
+ start_angle: float
127
+ sweep_angle: float
128
+
129
+ def __post_init__(self) -> None:
130
+ require_length(self.radius_x)
131
+ require_length(self.radius_y)
132
+ if self.radius_x <= pt(0) or self.radius_y <= pt(0):
133
+ raise ValueError("Canvas arc radii must be positive")
134
+ if not isfinite(self.start_angle) or not isfinite(self.sweep_angle):
135
+ raise ValueError("Canvas arc angles must be finite")
136
+ if self.sweep_angle == 0 or abs(self.sweep_angle) > 360:
137
+ raise ValueError("Canvas arc sweep must be nonzero and at most 360 degrees")
138
+
139
+ @property
140
+ def points(self) -> tuple[Point, ...]:
141
+ return tuple(point for command in self.resolve() for point in command.points)
142
+
143
+ def resolve(self) -> tuple[ResolvedPathCommand, ...]:
144
+ result: list[ResolvedPathCommand] = []
145
+ segment_count = max(1, int(abs(self.sweep_angle) / 90 + 0.999999))
146
+ start = self.start_angle * pi / 180
147
+ delta = self.sweep_angle * pi / 180 / segment_count
148
+ for index in range(segment_count):
149
+ a = start + delta * index
150
+ b = a + delta
151
+ factor = 4 / 3 * tan(delta / 4)
152
+ start_point = Point(
153
+ self.center.x + self.radius_x * cos(a),
154
+ self.center.y + self.radius_y * sin(a),
155
+ )
156
+ end_point = Point(
157
+ self.center.x + self.radius_x * cos(b),
158
+ self.center.y + self.radius_y * sin(b),
159
+ )
160
+ result.append(
161
+ CubicTo(
162
+ Point(
163
+ start_point.x - self.radius_x * (factor * sin(a)),
164
+ start_point.y + self.radius_y * (factor * cos(a)),
165
+ ),
166
+ Point(
167
+ end_point.x + self.radius_x * (factor * sin(b)),
168
+ end_point.y - self.radius_y * (factor * cos(b)),
169
+ ),
170
+ end_point,
171
+ )
172
+ )
173
+ return tuple(result)
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class ClosePath(ResolvedPathCommand):
178
+ @property
179
+ def points(self) -> tuple[Point, ...]:
180
+ return ()
181
+
182
+ @property
183
+ def draws(self) -> bool:
184
+ return False
185
+
186
+ def make_drawable(self, origin: Point) -> PathClose:
187
+ return PathClose()
188
+
189
+
190
+ @dataclass(frozen=True)
191
+ class Path(CanvasElement):
192
+ commands: tuple[CanvasPathCommand, ...]
193
+ fill: ColorStyle | None = None
194
+ stroke: Stroke | None = field(default_factory=Stroke)
195
+ fill_opacity: float = 1.0
196
+ key: str | None = None
197
+ shadow: ShadowStyle | None = None
198
+
199
+ def __post_init__(self) -> None:
200
+ validate_key(self.key)
201
+ if not self.commands or not isinstance(self.commands[0], MoveTo):
202
+ raise ValueError("A Canvas path must begin with MoveTo")
203
+ if any(isinstance(command, MoveTo) for command in self.commands[1:]):
204
+ raise ValueError("Canvas paths currently support one subpath")
205
+ if not any(command.draws for command in self.commands):
206
+ raise ValueError("A Canvas path requires at least one drawing command")
207
+ if self.fill is None and self.stroke is None:
208
+ raise ValueError("A Canvas path requires a fill or stroke")
209
+ validate_opacity(self.fill_opacity)
210
+
211
+ @property
212
+ def anchor_bounds(self) -> Bounds:
213
+ commands = _resolve_path_commands(self.commands)
214
+ return points_bounds(
215
+ tuple(point for command in commands for point in command.points)
216
+ )
217
+
218
+ def make_drawable(
219
+ self,
220
+ identity: str,
221
+ origin: Point,
222
+ context: CanvasContext,
223
+ metadata: DrawableMetadata,
224
+ ) -> DrawablePath:
225
+ commands = _resolve_path_commands(self.commands)
226
+ points = tuple(point for command in commands for point in command.points)
227
+ translated = tuple(command.make_drawable(origin) for command in commands)
228
+ bounds = points_bounds(
229
+ tuple(translate_point(point, origin) for point in points)
230
+ )
231
+ return DrawablePath(
232
+ identity,
233
+ bounds,
234
+ metadata,
235
+ translated,
236
+ context.color(self.fill).hex if self.fill is not None else None,
237
+ context.color(self.stroke.style).hex if self.stroke else None,
238
+ self.stroke.width if self.stroke else pt(0),
239
+ self.stroke.dash if self.stroke else (),
240
+ self.fill_opacity,
241
+ self.stroke.opacity if self.stroke else 1.0,
242
+ self.stroke.line_cap if self.stroke else "butt",
243
+ self.stroke.line_join if self.stroke else "miter",
244
+ )
245
+
246
+
247
+ def _resolve_path_commands(
248
+ commands: tuple[CanvasPathCommand, ...],
249
+ ) -> tuple[ResolvedPathCommand, ...]:
250
+ return tuple(resolved for command in commands for resolved in command.resolve())
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Iterable, Mapping
4
+ from dataclasses import dataclass
5
+ from types import MappingProxyType
6
+ from typing import Union
7
+
8
+ from typing_extensions import TypeAlias
9
+
10
+ from ..drawables import Bounds
11
+ from ._geometry import validate_bounds
12
+ from .context import CanvasContext, CanvasSize
13
+ from .elements import CanvasElement, CanvasText
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class CanvasScene:
18
+ elements: tuple[CanvasElement, ...]
19
+ anchors: Mapping[str, Bounds]
20
+ clip: Bounds | None
21
+
22
+ def __init__(
23
+ self,
24
+ *elements: CanvasElement,
25
+ anchors: Mapping[str, Bounds] | None = None,
26
+ clip: Bounds | None = None,
27
+ ) -> None:
28
+ if not all(isinstance(element, CanvasElement) for element in elements):
29
+ raise TypeError("CanvasScene elements must be CanvasElement values")
30
+ if clip is not None:
31
+ if not isinstance(clip, Bounds):
32
+ raise TypeError("CanvasScene.clip must be Bounds")
33
+ validate_bounds(clip)
34
+ keys = [element.key for element in elements if element.key is not None]
35
+ if len(keys) != len(set(keys)):
36
+ raise ValueError("Canvas element keys must be unique within a scene")
37
+ exported = dict(anchors or {})
38
+ if any(not name for name in exported):
39
+ raise ValueError("Canvas anchor names must not be empty")
40
+ duplicates = set(keys) & set(exported)
41
+ if duplicates:
42
+ raise ValueError(
43
+ "Canvas anchors conflict with element keys: "
44
+ + ", ".join(sorted(duplicates))
45
+ )
46
+ exported.update(
47
+ (element.key, element.anchor_bounds)
48
+ for element in elements
49
+ if element.key is not None
50
+ )
51
+ object.__setattr__(self, "elements", tuple(elements))
52
+ object.__setattr__(self, "anchors", MappingProxyType(exported))
53
+ object.__setattr__(self, "clip", clip)
54
+
55
+ def measured_anchors(self, context: CanvasContext) -> Mapping[str, Bounds]:
56
+ return MappingProxyType(
57
+ {
58
+ **self.anchors,
59
+ **{
60
+ element.key: element.measured_anchor_bounds(context)
61
+ for element in self.elements
62
+ if isinstance(element, CanvasText) and element.key is not None
63
+ },
64
+ }
65
+ )
66
+
67
+
68
+ CanvasRenderer: TypeAlias = Callable[
69
+ [CanvasContext, CanvasSize], Union[CanvasScene, Iterable[CanvasElement]]
70
+ ]
71
+
72
+
73
+ def scene_from(value: CanvasScene | Iterable[CanvasElement]) -> CanvasScene:
74
+ return value if isinstance(value, CanvasScene) else CanvasScene(*tuple(value))
@@ -0,0 +1,31 @@
1
+ from dataclasses import dataclass
2
+ from math import isfinite
3
+ from typing import Literal
4
+
5
+ from ..theme import ColorStyle, ForegroundColor
6
+ from ..units import Length, pt, require_length
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Stroke:
11
+ style: ColorStyle = ForegroundColor
12
+ width: Length = pt(1)
13
+ dash: tuple[Length, ...] = ()
14
+ opacity: float = 1.0
15
+ line_cap: Literal["butt", "round", "square"] = "butt"
16
+ line_join: Literal["miter", "round", "bevel"] = "miter"
17
+
18
+ def __post_init__(self) -> None:
19
+ require_length(self.width)
20
+ if self.width <= pt(0):
21
+ raise ValueError("Stroke width must be positive")
22
+ for segment in self.dash:
23
+ require_length(segment)
24
+ if segment <= pt(0):
25
+ raise ValueError("Stroke dash lengths must be positive")
26
+ if not isfinite(self.opacity) or not 0 <= self.opacity <= 1:
27
+ raise ValueError("Canvas opacity must be between zero and one")
28
+ if self.line_cap not in ("butt", "round", "square"):
29
+ raise ValueError("Unknown Canvas stroke line cap")
30
+ if self.line_join not in ("miter", "round", "bevel"):
31
+ raise ValueError("Unknown Canvas stroke line join")