Coverage for app / documents / visuals / flowable.py: 95%
135 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A visual as a flowable: fitted to the width it is given.
3reportlab's ``Drawing`` is a flowable too, but its ``wrap`` ignores the
4width it is offered, so a chart in a list item or a quote would run past
5its indent — as ``Image`` did before ``pdf._FittedImage``. This one lays the
6visual out again at a narrower width, or scales it down, and never takes the
7height left on the page: a visual that does not fit moves to the next one.
9A layout that says where it may be cut (``Layout.breaks``, between a
10diagram's rows) is scaled to the width alone and split across pages there:
11each part shows a window of the one drawing, and every part after the first
12draws the layout's header above it (a sequence diagram's participants).
13"""
15from __future__ import annotations
17from typing import Any
19from reportlab.graphics import renderPDF
20from reportlab.graphics.shapes import Drawing, Group
21from reportlab.platypus import Flowable
23from .registry import Layout, Visual
24from .theme import Theme
26#: The least of a diagram a part shows, in points of the drawing, unless
27#: the page is fresh: less, and the part moves to the next page whole.
28MIN_PART = 60.0
29#: How much of a tall diagram goes with its heading and title before the
30#: rest flows on: about the first few rows.
31LEAD = 160.0
34_IDENTITY = (1, 0, 0, 1, 0, 0)
37def _within(drawing: Drawing, low: float, high: float) -> Drawing:
38 """``drawing`` with only the shapes that reach between ``low`` and
39 ``high`` (points up from its foot): a part of a split diagram holds its
40 own text, not every other part's clipped out of sight."""
42 def reaches(shape: Any) -> bool:
43 try:
44 _, a, _, b = shape.getBounds()
45 except Exception: # noqa: BLE001 — a shape that cannot say is kept
46 return True
47 # A Line gives its ends as drawn, not lowest first.
48 return max(a, b) >= low and min(a, b) <= high
50 kept: list[Any] = []
51 for item in drawing.contents:
52 if isinstance(item, Group) and tuple(item.transform) == _IDENTITY:
53 kept.append(Group(*[shape for shape in item.contents if reaches(shape)]))
54 elif reaches(item):
55 kept.append(item)
56 part = Drawing(drawing.width, drawing.height)
57 for item in kept:
58 part.add(item)
59 return part
62class VisualFlowable(Flowable):
63 def __init__(
64 self,
65 visual: Visual,
66 spec: Any,
67 theme: Theme,
68 layout: Layout,
69 max_height: float,
70 window: tuple[float, float] | None = None,
71 ) -> None:
72 super().__init__()
73 self._visual = visual
74 self._spec = spec
75 self._theme = theme
76 self._max_height = max_height
77 self._layouts: dict[float, Layout] = {round(layout.width, 1): layout}
78 self._first = layout
79 self._current = layout
80 self._scale = 1.0
81 #: The part of the drawing shown, in points down from its top; a
82 #: part of a tall diagram is always laid out as one.
83 self._part_of = window is not None
84 self._window = window or (0.0, layout.height)
85 #: Drawn at the top of a frame after a cut: the header goes above.
86 self._continued = False
87 self.hAlign = "CENTER"
89 def _width_scale(self, width: float) -> float:
90 layout = self._first
91 return max(min(1.0, width / layout.width) if layout.width else 1.0, 0.05)
93 def _tall(self, width: float) -> bool:
94 """Split across pages: it says where it may be cut, and scaled to
95 the width it is taller than a page allows."""
96 layout = self._first
97 return bool(layout.breaks) and (
98 layout.height * self._width_scale(width) > self._max_height
99 )
101 def _splitting(self, width: float) -> bool:
102 return self._part_of or self._tall(width)
104 def _at_top(self, height: float) -> bool:
105 frame = getattr(self, "_frame", None)
106 return bool(getattr(frame, "_atTop", False)) or height >= self._max_height
108 def _header_height(self) -> float:
109 header = self._first.header
110 return float(header.height) if (self._continued and header) else 0.0
112 def tall(self, width: float) -> bool:
113 return self._splitting(width)
115 def lead_height(self, width: float) -> float:
116 """The height of its first rows at ``width``: what a heading and a
117 title kept with it need room for (``pdf._KeepTogether``)."""
118 scale = self._width_scale(width)
119 top, bottom = self._window
120 cut = next(
121 (
122 b
123 for b in self._first.breaks
124 if top < b < bottom and b - top >= LEAD / scale
125 ),
126 bottom,
127 )
128 return (cut - top) * scale
130 def _at(self, width: float) -> Layout:
131 key = round(width, 1)
132 if key not in self._layouts:
133 try:
134 self._layouts[key] = self._visual.layout(
135 self._spec, width, self._max_height, self._theme
136 )
137 except Exception: # noqa: BLE001 — wrap must not raise; scale instead
138 return self._first
139 return self._layouts[key]
141 def wrap(self, availWidth: float, availHeight: float) -> tuple[float, float]:
142 layout = self._first
143 if self._splitting(availWidth):
144 self._current, self._scale = layout, self._width_scale(availWidth)
145 top, bottom = self._window
146 self._continued = top > 0 and self._at_top(availHeight)
147 self.width = layout.width * self._scale
148 self.height = (bottom - top + self._header_height()) * self._scale
149 return self.width, self.height
150 if self._visual.fills_width and availWidth + 0.5 < layout.width:
151 layout = self._at(availWidth)
152 scale = 1.0
153 if layout.width > 0:
154 scale = min(scale, availWidth / layout.width)
155 if layout.height > 0:
156 scale = min(scale, self._max_height / layout.height)
157 self._current, self._scale = layout, max(scale, 0.05)
158 self.width = layout.width * self._scale
159 self.height = layout.height * self._scale
160 return self.width, self.height
162 def split(self, availWidth: float, availHeight: float) -> list[Flowable]:
163 """This part cut at the lowest break that fits ``availHeight``, as
164 two parts; none when nothing fits and the frame is not fresh."""
165 if not self._splitting(availWidth):
166 return []
167 self.wrap(availWidth, availHeight)
168 top, bottom = self._window
169 room = availHeight / self._scale - self._header_height()
170 fresh = self._at_top(availHeight)
171 fitting = [
172 b for b in self._first.breaks if top < b < bottom and b - top <= room
173 ]
174 if fitting and (fitting[-1] - top >= MIN_PART or fresh):
175 cut = fitting[-1]
176 elif fresh and room > MIN_PART:
177 cut = top + room # a single row taller than a page: cut through it
178 else:
179 return []
180 return [self._part(top, cut), self._part(cut, bottom)]
182 def _part(self, top: float, bottom: float) -> VisualFlowable:
183 part = VisualFlowable(
184 self._visual,
185 self._spec,
186 self._theme,
187 self._first,
188 self._max_height,
189 window=(top, bottom),
190 )
191 part.hAlign = self.hAlign
192 return part
194 def draw(self) -> None:
195 canvas = self.canv
196 layout = self._current
197 canvas.saveState()
198 if self._part_of or (layout.breaks and self._window != (0.0, layout.height)):
199 canvas.scale(self._scale, self._scale)
200 top, bottom = self._window
201 shown = bottom - top
202 header = self._first.header if self._continued else None
203 if header is not None:
204 renderPDF.draw(header, canvas, 0, shown)
205 path = canvas.beginPath()
206 path.rect(0, 0, layout.width, shown)
207 canvas.clipPath(path, stroke=0, fill=0)
208 low, high = layout.height - bottom, layout.height - top
209 drawing = _within(layout.drawing, low - 1.0, high + 1.0)
210 renderPDF.draw(drawing, canvas, 0, -low)
211 canvas.restoreState()
212 return
213 if layout.clip:
214 path = canvas.beginPath()
215 path.rect(0, 0, self.width, self.height)
216 canvas.clipPath(path, stroke=0, fill=0)
217 canvas.scale(self._scale, self._scale)
218 renderPDF.draw(layout.drawing, canvas, 0, 0)
219 canvas.restoreState()