Coverage for app / documents / visuals / text.py: 100%
46 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"""Text in a drawing: measured with the PDF's fonts, shortened to fit, and
2numbers formatted as fe-core formats them.
4A drawing's ``String`` never wraps, so every label is fitted here first.
5"""
7from __future__ import annotations
9from decimal import ROUND_HALF_UP, Decimal
11from reportlab.pdfbase.pdfmetrics import stringWidth
13ELLIPSIS = "…"
16def measure(text: str, font: str, size: float) -> float:
17 return stringWidth(text, font, size)
20def ellipsize(text: str, font: str, size: float, max_width: float) -> str:
21 """``text`` cut to fit ``max_width``, ending in an ellipsis when cut."""
22 if measure(text, font, size) <= max_width:
23 return text
24 lo, hi = 0, len(text)
25 while lo < hi:
26 mid = (lo + hi + 1) // 2
27 if measure(text[:mid].rstrip() + ELLIPSIS, font, size) <= max_width:
28 lo = mid
29 else:
30 hi = mid - 1
31 return text[:lo].rstrip() + ELLIPSIS if lo else ELLIPSIS
34def wrap_lines(
35 text: str, font: str, size: float, max_width: float, max_lines: int = 3
36) -> list[str]:
37 """``text`` broken into lines that fit ``max_width``: at spaces, and
38 within a word too long for a line (or a script written without spaces);
39 the last line ends in an ellipsis when text is left over."""
40 lines: list[str] = []
41 current = ""
42 for word in text.split():
43 candidate = f"{current} {word}" if current else word
44 if measure(candidate, font, size) <= max_width:
45 current = candidate
46 continue
47 if current:
48 lines.append(current)
49 current = word
50 while measure(current, font, size) > max_width and len(current) > 1:
51 cut = len(current)
52 while cut > 1 and measure(current[:cut], font, size) > max_width:
53 cut -= 1
54 lines.append(current[:cut])
55 current = current[cut:]
56 if current:
57 lines.append(current)
58 if len(lines) > max_lines:
59 lines = lines[:max_lines]
60 lines[-1] = ellipsize(lines[-1] + ELLIPSIS, font, size, max_width)
61 return lines
64def js_to_fixed(value: float, digits: int) -> str:
65 """``value.toFixed(digits)`` as JavaScript writes it: the exact binary
66 value rounded, ties away from zero (``(0.125).toFixed(2)`` is "0.13",
67 ``(1.005).toFixed(2)`` "1.00"), where Python's rounding goes to even."""
68 quantum = Decimal(1).scaleb(-digits)
69 return f"{Decimal(value).quantize(quantum, rounding=ROUND_HALF_UP):f}"
72def format_tick(value: float, decimals: int) -> str:
73 """A tick's label: as many decimals as its step needs, no float noise."""
74 if decimals <= 0:
75 return str(int(round(value)))
76 return f"{value:.{decimals}f}"