Coverage for app / documents / visuals / maps / visual.py: 99%
173 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 ```map fence drawn: its features over Natural Earth's outlines.
3The view is fe-core's (``_MapView``): the fence's ``center`` and ``zoom``
4(13 when only a centre is given), else fitted to the features with 24 px of
5padding, else London. The basemap is what a PDF can carry without fetching:
6country outlines and lakes at 1:110m for a view 30° across or wider, at
71:50m down to 2° — below that they would mislead, and the map is drawn on
8the plain background fe-core shows without tiles. Everything is cut to the
9frame before it is drawn (``clip``), so the PDF holds only what shows.
10"""
12from __future__ import annotations
14import math
15from typing import Any
17from reportlab.graphics.shapes import (
18 FILL_EVEN_ODD,
19 Circle,
20 Drawing,
21 Group,
22 Path,
23 PolyLine,
24 Rect,
25)
26from reportlab.lib.colors import Color, HexColor
28from ..fence import VisualError
29from ..primitives import LegendEntry, label, legend, rule
30from ..registry import Layout, Visual, register_visual
31from ..text import ellipsize, measure
32from ..theme import INK, PX, RULE, WHITE, Theme
33from . import outlines as natural_earth
34from .clip import clip_line, clip_ring, thinned
35from .features import MapSpec, read
36from .projection import FALLBACK_CENTRE, FALLBACK_ZOOM, CENTRE_ZOOM, View, centred, fit
38WATER = HexColor("#e5edf5")
39LAND = HexColor("#f9fafb")
40BORDER = HexColor("#cbd5e1")
41#: What fe-core shows with no tiles (``!bg-gray-100``).
42PLAIN = HexColor("#f3f4f6")
43#: The view spans, in degrees of longitude, from which each outline set is
44#: drawn: below the last, none.
45RESOLUTIONS: tuple[tuple[float, str], ...] = ((30.0, "110m"), (2.0, "50m"))
46#: The most point labels a map writes, and the legend's entries.
47MAX_LABELS = 60
48MAX_LEGEND = 12
49LABEL_SIZE = 7.0
52def resolution(view: View) -> str | None:
53 lng0, _, lng1, _ = view.bounds()
54 span = lng1 - lng0
55 return next((name for floor, name in RESOLUTIONS if span >= floor), None)
58def _path(rings: list[list[tuple[float, float]]], **style: Any) -> Path | None:
59 path = Path(fillMode=FILL_EVEN_ODD, **style)
60 drawn = False
61 for ring in rings:
62 if len(ring) < 3:
63 continue
64 path.moveTo(*ring[0])
65 for point in ring[1:]:
66 path.lineTo(*point)
67 path.closePath()
68 drawn = True
69 return path if drawn else None
72def _polyline(
73 points: list[tuple[float, float]], color: Color, width: float, opacity: float
74) -> PolyLine:
75 line = PolyLine(
76 [c for p in points for c in p],
77 strokeColor=color,
78 strokeWidth=width,
79 strokeLineJoin=1,
80 strokeLineCap=1,
81 )
82 if opacity < 1:
83 line.strokeOpacity = opacity
84 return line
87def _area(
88 rings: list[list[tuple[float, float]]],
89 frame: tuple[float, float, float, float],
90 fill: Color | None,
91 fill_opacity: float,
92 stroke: Color | None,
93 stroke_width: float,
94 stroke_opacity: float,
95) -> list[object]:
96 """An area cut to the frame: its fill, then its outline drawn as lines,
97 so where the frame cut it no edge is drawn along the frame."""
98 shapes: list[object] = []
99 if fill is not None:
100 clipped = [thinned(clip_ring(ring, frame)) for ring in rings]
101 path = _path(clipped, fillColor=fill, strokeColor=None)
102 if path is not None:
103 if fill_opacity < 1:
104 path.fillOpacity = fill_opacity
105 shapes.append(path)
106 if stroke is not None and stroke_width > 0:
107 for ring in rings:
108 for piece in clip_line([*ring, ring[0]], frame):
109 piece = thinned(piece)
110 if len(piece) > 1:
111 shapes.append(
112 _polyline(piece, stroke, stroke_width, stroke_opacity)
113 )
114 return shapes
117def _basemap(
118 view: View, frame: tuple[float, float, float, float]
119) -> tuple[list[object], bool]:
120 """The outlines the view shows, and whether any were drawn."""
121 scale = resolution(view)
122 if scale is None:
123 return [Rect(*frame, fillColor=PLAIN, strokeColor=None)], False
124 data = natural_earth.load()
125 lng0, lat0, lng1, lat1 = view.bounds()
126 shapes: list[object] = [Rect(*frame, fillColor=WATER, strokeColor=None)]
127 for part in data.parts(f"{scale}-countries", lng0, lat0, lng1, lat1):
128 rings = [
129 [view.place(lng, lat) for lng, lat in data.ring(offset, count)]
130 for offset, count in part.rings
131 ]
132 shapes += _area(rings, frame, LAND, 1.0, BORDER, 0.4, 1.0)
133 for part in data.parts(f"{scale}-lakes", lng0, lat0, lng1, lat1):
134 rings = [
135 [view.place(lng, lat) for lng, lat in data.ring(offset, count)]
136 for offset, count in part.rings
137 ]
138 shapes += _area(rings, frame, WATER, 1.0, None, 0, 1.0)
139 return shapes, True
142def _features(
143 spec: MapSpec, view: View, frame: tuple[float, float, float, float]
144) -> list[object]:
145 shapes: list[object] = []
146 for polygon in spec.polygons:
147 rings = [[view.place(lng, lat) for lng, lat in ring] for ring in polygon.rings]
148 s = polygon.style
149 shapes += _area(
150 rings, frame, s.fill, s.fill_opacity, s.stroke, s.weight, s.opacity
151 )
152 for line in spec.lines:
153 s = line.style
154 points = [view.place(lng, lat) for lng, lat in line.points]
155 for piece in clip_line(points, frame):
156 shapes.append(_polyline(thinned(piece, 0.2), s.stroke, s.weight, s.opacity))
157 x0, y0, x1, y1 = frame
158 for point in spec.points:
159 x, y = view.place(*point.at)
160 if (
161 x0 - point.radius <= x <= x1 + point.radius
162 and y0 - point.radius <= y <= y1 + point.radius
163 ):
164 shapes.append(
165 Circle(
166 x,
167 y,
168 point.radius,
169 fillColor=point.fill,
170 fillOpacity=0.9,
171 strokeColor=WHITE,
172 strokeWidth=1.5 * PX,
173 )
174 )
175 return shapes
178def _overlaps(
179 a: tuple[float, float, float, float], b: tuple[float, float, float, float]
180) -> bool:
181 return not (a[2] <= b[0] or a[0] >= b[2] or a[3] <= b[1] or a[1] >= b[3])
184def _labels(
185 spec: MapSpec, view: View, frame: tuple[float, float, float, float], theme: Theme
186) -> list[object]:
187 """Named points' labels, each beside its marker where it overlaps
188 nothing already placed: right, left, above, below, else not written."""
189 x0, y0, x1, y1 = frame
190 placed: list[tuple[float, float, float, float]] = []
191 markers = []
192 for point in spec.points:
193 x, y = view.place(*point.at)
194 if x0 <= x <= x1 and y0 <= y <= y1:
195 markers.append((point, x, y))
196 placed.append(
197 (x - point.radius, y - point.radius, x + point.radius, y + point.radius)
198 )
199 shapes: list[object] = []
200 written = 0
201 for point, x, y in markers:
202 if not point.name or written >= MAX_LABELS:
203 continue
204 text = ellipsize(point.name, theme.regular, LABEL_SIZE, (x1 - x0) * 0.4)
205 w, h = measure(text, theme.regular, LABEL_SIZE), LABEL_SIZE
206 r = point.radius + 2
207 for bx, by in (
208 (x + r, y - h / 2 + 1),
209 (x - r - w, y - h / 2 + 1),
210 (x - w / 2, y + r),
211 (x - w / 2, y - r - h),
212 ):
213 box = (bx - 1.5, by - 1.5, bx + w + 1.5, by + h + 0.5)
214 if box[0] < x0 or box[2] > x1 or box[1] < y0 or box[3] > y1:
215 continue
216 if any(_overlaps(box, other) for other in placed):
217 continue
218 placed.append(box)
219 shapes.append(
220 Rect(
221 box[0],
222 box[1],
223 box[2] - box[0],
224 box[3] - box[1],
225 fillColor=WHITE,
226 fillOpacity=0.85,
227 strokeColor=None,
228 ) # fmt: skip
229 )
230 shapes.append(label(bx, by + 1, text, theme.regular, LABEL_SIZE, INK))
231 written += 1
232 break
233 return shapes
236def _nice_length(metres: float) -> float:
237 power = 10 ** math.floor(math.log10(metres))
238 return max(m * power for m in (1, 2, 5) if m * power <= metres)
241def _scale_bar(
242 view: View, frame: tuple[float, float, float, float], theme: Theme
243) -> list[object]:
244 """A 1-2-5 scale bar, bottom left; none for a view so wide the scale
245 changes across it."""
246 _, lat0, _, lat1 = view.bounds()
247 if lat1 - lat0 > 30 or view.zoom < 2:
248 return []
249 per_point = view.metres_per_point()
250 metres = _nice_length(per_point * (frame[2] - frame[0]) * 0.18)
251 length = metres / per_point
252 caption = f"{metres / 1000:g} km" if metres >= 1000 else f"{metres:g} m"
253 x, y = frame[0] + 8, frame[1] + 8
254 width = max(length, measure(caption, theme.regular, 6.5)) + 6
255 return [
256 Rect(
257 x - 3, y - 3, width, 15, fillColor=WHITE, fillOpacity=0.8, strokeColor=None
258 ),
259 rule(x, y, x + length, y, INK, 0.8),
260 rule(x, y, x, y + 3, INK, 0.8),
261 rule(x + length, y, x + length, y + 3, INK, 0.8),
262 label(x, y + 4.5, caption, theme.regular, 6.5, INK),
263 ]
266def view_of(spec: MapSpec, width: float, max_height: float) -> View:
267 """fe-core's view: a centre the fence names, else the features fitted."""
268 if spec.center is not None:
269 lat, lng = spec.center
270 zoom = spec.zoom if spec.zoom is not None else CENTRE_ZOOM
271 return centred(lat, lng, zoom, width, max_height)
272 positions = spec.positions()
273 if positions:
274 return fit(positions, width, max_height)
275 return centred(*FALLBACK_CENTRE, FALLBACK_ZOOM, width, max_height)
278@register_visual
279class MapVisual(Visual):
280 kind = "map"
281 noun = "Map"
283 def read(self, source: str) -> MapSpec:
284 return read(source)
286 def title(self, spec: MapSpec) -> str | None:
287 return spec.title
289 def layout(
290 self, spec: MapSpec, width: float, max_height: float, theme: Theme
291 ) -> Layout:
292 named = [
293 LegendEntry(
294 item.name,
295 item.style.fill if hasattr(item, "rings") else item.style.stroke,
296 "square" if hasattr(item, "rings") else "line",
297 ) # fmt: skip
298 for item in [*spec.polygons, *spec.lines]
299 if item.name
300 ][:MAX_LEGEND]
301 legend_shapes, legend_height = (
302 legend(named, width, theme) if named else ([], 0.0)
303 )
304 gap = 4.0 if named else 0.0
305 view = view_of(spec, width, max_height - legend_height - gap)
306 if view.height < 60:
307 raise VisualError("there is no room to draw it")
308 frame = (0.0, 0.0, width, view.height)
309 basemap, outlined = _basemap(view, frame)
310 shapes = [
311 *basemap,
312 *_features(spec, view, frame),
313 *_labels(spec, view, frame, theme),
314 ]
315 shapes += _scale_bar(view, frame, theme)
316 shapes.append(Rect(*frame, fillColor=None, strokeColor=RULE, strokeWidth=0.6))
317 drawing = Drawing(width, legend_height + gap + view.height)
318 map_group = Group(*shapes)
319 map_group.translate(0, legend_height + gap)
320 drawing.add(map_group)
321 if legend_shapes:
322 legend_group = Group(*legend_shapes)
323 legend_group.translate(0, legend_height)
324 drawing.add(legend_group)
325 return Layout(
326 drawing,
327 width,
328 legend_height + gap + view.height,
329 credit=natural_earth.CREDIT if outlined else None,
330 )