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/layout.py ADDED
@@ -0,0 +1,398 @@
1
+ """Layout contracts and layout assembly. All geometry is measured in points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from dataclasses import dataclass, field, replace
7
+ from functools import cache
8
+ from types import MappingProxyType
9
+ from typing import TYPE_CHECKING, Any, Literal, Protocol, cast
10
+
11
+ from .effects import ResolvedShadow
12
+ from .fonts import FontResolver
13
+ from .identity import ViewIdentity
14
+ from .measurement import TextMeasurer
15
+ from .units import Length, pt, require_length
16
+
17
+ if TYPE_CHECKING:
18
+ from .expanded_views import ExpandedView
19
+
20
+ from .drawables import (
21
+ Bounds,
22
+ Drawable,
23
+ DrawableGroup,
24
+ DrawableMetadata,
25
+ )
26
+
27
+ StackAxis = Literal["horizontal", "vertical"]
28
+ VerticalAlignmentName = Literal[
29
+ "top", "center", "bottom", "first_baseline", "last_baseline", "cap_center"
30
+ ]
31
+
32
+
33
+ def _mean(guides: Sequence[Length]) -> Length:
34
+ return sum(guides, pt(0)) / len(guides)
35
+
36
+
37
+ @dataclass(frozen=True, eq=False)
38
+ class VerticalAlignment:
39
+ """A vertical guide with a fallback and a rule for merging child guides."""
40
+
41
+ default_value: Callable[[LayoutPlan], Length]
42
+ combine: Callable[[Sequence[Length]], Length] = _mean
43
+
44
+
45
+ _TOP = VerticalAlignment(lambda plan: pt(0))
46
+ _CENTER = VerticalAlignment(lambda plan: plan.height / 2)
47
+ _BOTTOM = VerticalAlignment(lambda plan: plan.height)
48
+ FIRST_BASELINE = VerticalAlignment(_BOTTOM.default_value, min)
49
+ LAST_BASELINE = VerticalAlignment(_BOTTOM.default_value, max)
50
+ CAP_CENTER = VerticalAlignment(_CENTER.default_value, min)
51
+
52
+ _VERTICAL_ALIGNMENTS = {
53
+ "top": _TOP,
54
+ "center": _CENTER,
55
+ "bottom": _BOTTOM,
56
+ "first_baseline": FIRST_BASELINE,
57
+ "last_baseline": LAST_BASELINE,
58
+ "cap_center": CAP_CENTER,
59
+ }
60
+
61
+
62
+ def resolve_vertical_alignment(
63
+ alignment: VerticalAlignmentName | VerticalAlignment,
64
+ ) -> VerticalAlignment:
65
+ if isinstance(alignment, VerticalAlignment):
66
+ return alignment
67
+ if not isinstance(alignment, str) or alignment not in _VERTICAL_ALIGNMENTS:
68
+ raise ValueError(f"Unknown vertical alignment {alignment!r}")
69
+ return _VERTICAL_ALIGNMENTS[alignment]
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ProposedSize:
74
+ """A parent's suggested size; ``None`` requests the child's ideal size."""
75
+
76
+ width: Length | None = None
77
+ height: Length | None = None
78
+ stack_axis: StackAxis | None = None
79
+
80
+ def __post_init__(self) -> None:
81
+ for value in (self.width, self.height):
82
+ if value is not None:
83
+ require_length(value)
84
+ if value < pt(0):
85
+ raise ValueError("Proposed dimensions must be nonnegative")
86
+
87
+
88
+ class _SharedWidthGroup:
89
+ """An identity shared by the layout nodes that use one width."""
90
+
91
+ __slots__ = ()
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class LayoutContext:
96
+ """Services available while views respond to layout proposals."""
97
+
98
+ measurer: TextMeasurer
99
+ font_resolver: FontResolver
100
+ _shared_width: Callable[[_SharedWidthGroup], Length] | None = field(
101
+ default=None, repr=False, compare=False
102
+ )
103
+
104
+
105
+ class LayoutOverflow(ValueError):
106
+ def __init__(
107
+ self,
108
+ identity: str | None,
109
+ available: tuple[Length, Length],
110
+ required: tuple[Length | None, Length | None],
111
+ ) -> None:
112
+ self.identity, self.available, self.required = identity, available, required
113
+ component = (
114
+ identity.rsplit("/", 1)[-1].rsplit(".", 1)[-1] if identity else "View"
115
+ )
116
+ dimensions = [
117
+ f"{component} needs {needed.points:,.6g} pt of {axis}, "
118
+ f"but only {room.points:,.6g} pt is available."
119
+ for axis, room, needed in zip(("width", "height"), available, required)
120
+ if needed is not None
121
+ ]
122
+ details = " ".join(dimensions) or f"{component} exceeds the available space."
123
+ path = f"\nView path: {identity}" if identity else ""
124
+ super().__init__(
125
+ f"{details} Shorten content, increase its frame, or allocate flexible space."
126
+ f"{path}"
127
+ )
128
+
129
+
130
+ class LayoutChild(Protocol):
131
+ """A layout's opaque child: identity, allocation weight and cached measurement."""
132
+
133
+ identity: str
134
+ view_identity: ViewIdentity
135
+ flex: float
136
+ flex_minimum: tuple[Length, Length] | None
137
+
138
+ def measure(self, proposal: ProposedSize) -> LayoutPlan: ...
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class Placement:
143
+ child: LayoutChild
144
+ plan: LayoutPlan
145
+ x: Length = pt(0)
146
+ y: Length = pt(0)
147
+ propagates_guides: bool = True
148
+
149
+ def __post_init__(self) -> None:
150
+ require_length(self.x)
151
+ require_length(self.y)
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class ExportedAnchor:
156
+ """The identity of named geometry exported by a layout node."""
157
+
158
+ owner: ViewIdentity
159
+ name: str
160
+
161
+ def __post_init__(self) -> None:
162
+ if not self.name:
163
+ raise ValueError("Exported anchor names must not be empty")
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class LayoutPlan:
168
+ width: Length
169
+ height: Length
170
+ placements: tuple[Placement, ...] = ()
171
+ properties: Mapping[str, Any] = field(default_factory=dict)
172
+ anchors: Mapping[str, Bounds] = field(default_factory=dict)
173
+ vertical_guides: Mapping[VerticalAlignment, Length] = field(default_factory=dict)
174
+
175
+ def __post_init__(self) -> None:
176
+ require_length(self.width)
177
+ require_length(self.height)
178
+ if any(not name for name in self.anchors):
179
+ raise ValueError("Layout anchor names must not be empty")
180
+ if not all(isinstance(bounds, Bounds) for bounds in self.anchors.values()):
181
+ raise TypeError("Layout anchors must map names to Bounds")
182
+ object.__setattr__(self, "properties", MappingProxyType(dict(self.properties)))
183
+ object.__setattr__(self, "anchors", MappingProxyType(dict(self.anchors)))
184
+ inherited: dict[VerticalAlignment, list[Length]] = {}
185
+ for placement in self.placements:
186
+ if placement.propagates_guides:
187
+ for guide, value in placement.plan.vertical_guides.items():
188
+ inherited.setdefault(guide, []).append(placement.y + value)
189
+ guides = {
190
+ guide: guide.combine(values)
191
+ for guide, values in inherited.items()
192
+ if guide not in self.vertical_guides
193
+ }
194
+ guides.update(self.vertical_guides)
195
+ for value in guides.values():
196
+ require_length(value)
197
+ object.__setattr__(self, "vertical_guides", MappingProxyType(guides))
198
+
199
+ def vertical_guide(
200
+ self, alignment: VerticalAlignmentName | VerticalAlignment
201
+ ) -> Length:
202
+ guide = resolve_vertical_alignment(alignment)
203
+ if guide in self.vertical_guides:
204
+ return self.vertical_guides[guide]
205
+ value = guide.default_value(self)
206
+ require_length(value)
207
+ return value
208
+
209
+
210
+ class Layout(Protocol):
211
+ """Policies measure children and return placements; they never create layout nodes."""
212
+
213
+ def measure(
214
+ self,
215
+ proposal: ProposedSize,
216
+ children: Sequence[LayoutChild],
217
+ context: LayoutContext,
218
+ ) -> LayoutPlan: ...
219
+
220
+
221
+ def checked(plan: LayoutPlan, identity: str | None) -> LayoutPlan:
222
+ for value in (plan.width, plan.height):
223
+ require_length(value)
224
+ if not all(v >= pt(0) for v in (plan.width, plan.height)):
225
+ raise ValueError(
226
+ f"Invalid layout size at {identity}: {(plan.width, plan.height)}"
227
+ )
228
+ return plan
229
+
230
+
231
+ @dataclass(frozen=True)
232
+ class _SharedWidthLayout:
233
+ """Center one child within the widest ideal width in its group."""
234
+
235
+ group: _SharedWidthGroup
236
+
237
+ def measure(
238
+ self,
239
+ proposal: ProposedSize,
240
+ children: Sequence[LayoutChild],
241
+ context: LayoutContext,
242
+ ) -> LayoutPlan:
243
+ (child,) = children
244
+ plan = child.measure(ProposedSize())
245
+ assert context._shared_width is not None
246
+ width = context._shared_width(self.group)
247
+ return LayoutPlan(
248
+ width, plan.height, (Placement(child, plan, (width - plan.width) / 2),)
249
+ )
250
+
251
+
252
+ class _Child:
253
+ def __init__(
254
+ self,
255
+ node: ExpandedView,
256
+ context: LayoutContext,
257
+ shared_widths: dict[_SharedWidthGroup, list[_Child]],
258
+ ) -> None:
259
+ self.node = node
260
+ self.context = context
261
+ self.identity = node.identity
262
+ self.view_identity = node.view_identity
263
+ self.flex = node.metadata.flex
264
+ self.flex_minimum = node.metadata.flex_minimum
265
+ self.stretches_cross_axis = node.metadata.stretches_cross_axis
266
+ self.children = tuple(
267
+ _Child(child, context, shared_widths) for child in node.children
268
+ )
269
+ if isinstance(node.layout, _SharedWidthLayout):
270
+ (child,) = self.children
271
+ shared_widths.setdefault(node.layout.group, []).append(child)
272
+ self._cache: dict[ProposedSize, LayoutPlan] = {}
273
+
274
+ def measure(self, proposal: ProposedSize) -> LayoutPlan:
275
+ if proposal not in self._cache:
276
+ try:
277
+ plan = self.node.layout.measure(proposal, self.children, self.context)
278
+ plan = checked(plan, self.identity)
279
+ for modifier in self.node.modifiers:
280
+ if modifier[0] == "alignment_guide":
281
+ guide, compute = modifier[1]
282
+ plan = replace(
283
+ plan,
284
+ vertical_guides={
285
+ **plan.vertical_guides,
286
+ guide: compute(plan),
287
+ },
288
+ )
289
+ for placement in plan.placements:
290
+ if not any(placement.child is child for child in self.children):
291
+ raise ValueError(
292
+ f"Layout at {self.identity} placed an unrelated child"
293
+ )
294
+ self._cache[proposal] = plan
295
+ except LayoutOverflow as error:
296
+ if error.identity is not None:
297
+ raise
298
+ raise LayoutOverflow(
299
+ self.identity, error.available, error.required
300
+ ) from error
301
+ return self._cache[proposal]
302
+
303
+ def place(
304
+ self,
305
+ plan: LayoutPlan,
306
+ x: Length = pt(0),
307
+ y: Length = pt(0),
308
+ opacity: float = 1.0,
309
+ shadow: ResolvedShadow | None = None,
310
+ ) -> Drawable:
311
+ bounds = Bounds(x, y, plan.width, plan.height)
312
+ opacity *= self.node.metadata.opacity
313
+ metadata = DrawableMetadata(
314
+ self.node.animation,
315
+ self.node.transition,
316
+ self.node.animation_boundary,
317
+ opacity,
318
+ )
319
+ if self.node.metadata.hidden:
320
+ return DrawableGroup(self.identity, bounds, metadata, ())
321
+ shadow = shadow or self.node.metadata.shadow
322
+ child_shadow = None
323
+ if shadow is not None and len(plan.placements) == 1:
324
+ from .layouts.containers import PassthroughLayout
325
+ from .layouts.modifiers import FrameLayout, PaddingLayout, PlacementLayout
326
+
327
+ placement = plan.placements[0]
328
+ child = cast(_Child, placement.child)
329
+ if child.node.metadata.shadow is None and isinstance(
330
+ self.node.layout,
331
+ (FrameLayout, PaddingLayout, PlacementLayout, PassthroughLayout),
332
+ ):
333
+ child_shadow, shadow = shadow, None
334
+ dx, dy = plan.properties.get("content_offset", (pt(0), pt(0)))
335
+ w, h = plan.properties.get("content_size", (plan.width, plan.height))
336
+ content_bounds = Bounds(x + dx, y + dy, w, h)
337
+ children = tuple(
338
+ cast(_Child, placement.child).place(
339
+ placement.plan, x + placement.x, y + placement.y, opacity, child_shadow
340
+ )
341
+ for placement in plan.placements
342
+ )
343
+ drawable = self.node.make_drawable(
344
+ plan,
345
+ bounds,
346
+ content_bounds,
347
+ metadata,
348
+ children,
349
+ )
350
+ if shadow is None and not self.node.metadata.grouped:
351
+ return drawable
352
+ return replace(
353
+ drawable,
354
+ metadata=replace(
355
+ drawable.metadata,
356
+ shadow=shadow,
357
+ grouped=self.node.metadata.grouped,
358
+ group_name=self.node.metadata.key
359
+ if self.node.metadata.grouped
360
+ else None,
361
+ ),
362
+ )
363
+
364
+
365
+ class LayoutEngine:
366
+ """Coordinate measurement, validate plans, then materialize the layout once."""
367
+
368
+ def __init__(self, context: LayoutContext) -> None:
369
+ self.context = context
370
+
371
+ def measure(self, node: ExpandedView, proposal: ProposedSize) -> Drawable:
372
+ shared_widths: dict[_SharedWidthGroup, list[_Child]] = {}
373
+
374
+ @cache
375
+ def shared_width(group: _SharedWidthGroup) -> Length:
376
+ return max(
377
+ child.measure(ProposedSize()).width for child in shared_widths[group]
378
+ )
379
+
380
+ context = replace(self.context, _shared_width=shared_width)
381
+ child = _Child(node, context, shared_widths)
382
+ try:
383
+ return child.place(child.measure(proposal))
384
+ finally:
385
+ shared_widths.clear()
386
+ shared_width.cache_clear()
387
+
388
+ def layout_view(
389
+ self, node: ExpandedView, width: Length = pt(960), height: Length = pt(540)
390
+ ) -> Drawable:
391
+ require_length(width)
392
+ require_length(height)
393
+ return DrawableGroup(
394
+ "canvas",
395
+ Bounds(pt(0), pt(0), width, height),
396
+ DrawableMetadata(),
397
+ (self.measure(node, ProposedSize(width, height)),),
398
+ )
@@ -0,0 +1,20 @@
1
+ """Composable layout policies, independent of views and rendering backends."""
2
+
3
+ from .annotations import AnnotatedLayout, ConnectorLayout
4
+ from .containers import OverlayLayout, PassthroughLayout, StackLayout
5
+ from .modifiers import FrameLayout, PaddingLayout
6
+ from .primitives import CanvasLayout, ImageLayout, ShapeLayout, TextLayout
7
+
8
+ __all__ = [
9
+ "AnnotatedLayout",
10
+ "CanvasLayout",
11
+ "ConnectorLayout",
12
+ "FrameLayout",
13
+ "ImageLayout",
14
+ "OverlayLayout",
15
+ "PaddingLayout",
16
+ "PassthroughLayout",
17
+ "ShapeLayout",
18
+ "StackLayout",
19
+ "TextLayout",
20
+ ]
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+ from ..drawables import Bounds
7
+ from ..layout import LayoutPlan, Placement, VerticalAlignment
8
+ from ..units import Length
9
+
10
+
11
+ def content(
12
+ width: Length,
13
+ height: Length,
14
+ placements: tuple[Placement, ...] = (),
15
+ *,
16
+ anchors: Mapping[str, Bounds] | None = None,
17
+ vertical_guides: Mapping[VerticalAlignment, Length] | None = None,
18
+ **properties: Any,
19
+ ) -> LayoutPlan:
20
+ return LayoutPlan(
21
+ width,
22
+ height,
23
+ placements,
24
+ dict(properties, content_size=(width, height)),
25
+ anchors or {},
26
+ vertical_guides or {},
27
+ )
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Mapping, Sequence
5
+ from dataclasses import dataclass, replace
6
+ from typing import Union
7
+
8
+ from ..drawables import Bounds
9
+ from ..geometry import Point, RelativePoint
10
+ from ..identity import ViewIdentity
11
+ from ..layout import (
12
+ ExportedAnchor,
13
+ LayoutChild,
14
+ LayoutContext,
15
+ LayoutPlan,
16
+ Placement,
17
+ ProposedSize,
18
+ )
19
+ from ..units import Length, pt
20
+ from ._content import content
21
+
22
+ AnchorTarget = Union[ViewIdentity, ExportedAnchor]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ResolvedAnchor:
27
+ target: AnchorTarget
28
+ position: RelativePoint
29
+ offset_x: Length
30
+ offset_y: Length
31
+
32
+
33
+ class ResolvedAnnotation(ABC):
34
+ @property
35
+ @abstractmethod
36
+ def dependencies(self) -> tuple[AnchorTarget, ...]:
37
+ raise NotImplementedError
38
+
39
+ @abstractmethod
40
+ def place(
41
+ self,
42
+ child: LayoutChild,
43
+ bounds: Mapping[AnchorTarget, Bounds],
44
+ container: Bounds,
45
+ ) -> Placement:
46
+ raise NotImplementedError
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ResolvedConnector(ResolvedAnnotation):
51
+ start: ResolvedAnchor
52
+ end: ResolvedAnchor
53
+
54
+ @property
55
+ def dependencies(self) -> tuple[AnchorTarget, ...]:
56
+ return self.start.target, self.end.target
57
+
58
+ def place(
59
+ self,
60
+ child: LayoutChild,
61
+ bounds: Mapping[AnchorTarget, Bounds],
62
+ container: Bounds,
63
+ ) -> Placement:
64
+ start = _point(self.start, bounds)
65
+ end = _point(self.end, bounds)
66
+ x, y = min(start.x, end.x), min(start.y, end.y)
67
+ width = max(start.x, end.x) - x
68
+ height = max(start.y, end.y) - y
69
+ plan = child.measure(ProposedSize(width, height))
70
+ plan = replace(
71
+ plan,
72
+ properties=dict(
73
+ plan.properties,
74
+ start=Point(start.x - x, start.y - y),
75
+ end=Point(end.x - x, end.y - y),
76
+ ),
77
+ )
78
+ return Placement(child, plan, x, y)
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class ResolvedLabel(ResolvedAnnotation):
83
+ anchor: ResolvedAnchor
84
+ alignment: RelativePoint
85
+
86
+ @property
87
+ def dependencies(self) -> tuple[AnchorTarget, ...]:
88
+ return (self.anchor.target,)
89
+
90
+ def place(
91
+ self,
92
+ child: LayoutChild,
93
+ bounds: Mapping[AnchorTarget, Bounds],
94
+ container: Bounds,
95
+ ) -> Placement:
96
+ target = _point(self.anchor, bounds)
97
+ plan = child.measure(ProposedSize(container.width, container.height))
98
+ x = target.x - plan.width * self.alignment.x
99
+ y = target.y - plan.height * self.alignment.y
100
+ return Placement(child, plan, x, y)
101
+
102
+
103
+ def _collect_bounds(
104
+ child: LayoutChild,
105
+ plan: LayoutPlan,
106
+ x: Length,
107
+ y: Length,
108
+ result: dict[AnchorTarget, Bounds],
109
+ ) -> None:
110
+ result[child.view_identity] = Bounds(x, y, plan.width, plan.height)
111
+ for name, anchor in plan.anchors.items():
112
+ result[ExportedAnchor(child.view_identity, name)] = Bounds(
113
+ x + anchor.x,
114
+ y + anchor.y,
115
+ anchor.width,
116
+ anchor.height,
117
+ )
118
+ for placement in plan.placements:
119
+ _collect_bounds(
120
+ placement.child,
121
+ placement.plan,
122
+ x + placement.x,
123
+ y + placement.y,
124
+ result,
125
+ )
126
+
127
+
128
+ def _point(anchor: ResolvedAnchor, bounds: Mapping[AnchorTarget, Bounds]) -> Point:
129
+ try:
130
+ target = bounds[anchor.target]
131
+ except KeyError:
132
+ raise ValueError(
133
+ f"Anchor target is outside this Annotated: {anchor.target}"
134
+ ) from None
135
+ return Point(
136
+ target.x + target.width * anchor.position.x + anchor.offset_x,
137
+ target.y + target.height * anchor.position.y + anchor.offset_y,
138
+ )
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class AnnotatedLayout:
143
+ annotations: tuple[ResolvedAnnotation, ...]
144
+
145
+ def measure(
146
+ self,
147
+ proposal: ProposedSize,
148
+ children: Sequence[LayoutChild],
149
+ context: LayoutContext,
150
+ ) -> LayoutPlan:
151
+ content_child, *annotation_children = children
152
+ if len(annotation_children) != len(self.annotations):
153
+ raise ValueError("Annotated child and annotation counts differ")
154
+ main = content_child.measure(proposal)
155
+ bounds: dict[AnchorTarget, Bounds] = {}
156
+ _collect_bounds(content_child, main, pt(0), pt(0), bounds)
157
+ container = Bounds(pt(0), pt(0), main.width, main.height)
158
+ pending = list(enumerate(zip(self.annotations, annotation_children)))
159
+ annotation_placements: dict[int, Placement] = {}
160
+ while pending:
161
+ deferred: list[tuple[int, tuple[ResolvedAnnotation, LayoutChild]]] = []
162
+ for index, (annotation, child) in pending:
163
+ if any(target not in bounds for target in annotation.dependencies):
164
+ deferred.append((index, (annotation, child)))
165
+ continue
166
+ placement = annotation.place(child, bounds, container)
167
+ plan, x, y = placement.plan, placement.x, placement.y
168
+ annotation_placements[index] = placement
169
+ _collect_bounds(child, plan, x, y, bounds)
170
+ if len(deferred) == len(pending):
171
+ unresolved = sorted(
172
+ {
173
+ str(anchor)
174
+ for _, (annotation, _) in deferred
175
+ for anchor in annotation.dependencies
176
+ if anchor not in bounds
177
+ }
178
+ )
179
+ raise ValueError(
180
+ "Annotation dependencies could not be resolved; "
181
+ "there may be a cycle involving: " + ", ".join(unresolved)
182
+ )
183
+ pending = deferred
184
+ placements = [Placement(content_child, main)]
185
+ placements.extend(
186
+ annotation_placements[index] for index in range(len(self.annotations))
187
+ )
188
+ min_x = min((placement.x for placement in placements), default=pt(0))
189
+ min_y = min((placement.y for placement in placements), default=pt(0))
190
+ max_x = max(
191
+ (placement.x + placement.plan.width for placement in placements),
192
+ default=main.width,
193
+ )
194
+ max_y = max(
195
+ (placement.y + placement.plan.height for placement in placements),
196
+ default=main.height,
197
+ )
198
+ shifted = tuple(
199
+ replace(
200
+ placement,
201
+ x=placement.x - min_x,
202
+ y=placement.y - min_y,
203
+ )
204
+ for placement in placements
205
+ )
206
+ return content(max_x - min_x, max_y - min_y, shifted)
207
+
208
+
209
+ @dataclass(frozen=True)
210
+ class ConnectorLayout:
211
+ def measure(
212
+ self,
213
+ proposal: ProposedSize,
214
+ children: Sequence[LayoutChild],
215
+ context: LayoutContext,
216
+ ) -> LayoutPlan:
217
+ return content(proposal.width or pt(0), proposal.height or pt(0))