Coverage for app / documents / visuals / colors.py: 88%
56 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 colour a fence names, read strictly.
3A fence's colours are model text. reportlab's own ``colors.toColor`` once
4evaluated what it was given (CVE-2023-33733), so it is never handed one:
5this reads the CSS forms a chart is written with — ``#rgb``, ``#rrggbb``,
6``#rrggbbaa``, ``rgb[a]()``, ``hsl[a]()`` and the common names — and gives
7the fallback for anything else.
8"""
10from __future__ import annotations
12import colorsys
13import re
14from typing import Any
16from reportlab.lib.colors import Color
18#: CSS names a model writes; anything else takes the fallback.
19NAMED: dict[str, str] = {
20 "black": "#000000",
21 "white": "#ffffff",
22 "gray": "#808080",
23 "grey": "#808080",
24 "silver": "#c0c0c0",
25 "red": "#ff0000",
26 "maroon": "#800000",
27 "crimson": "#dc143c",
28 "orange": "#ffa500",
29 "darkorange": "#ff8c00",
30 "gold": "#ffd700",
31 "yellow": "#ffff00",
32 "olive": "#808000",
33 "lime": "#00ff00",
34 "green": "#008000",
35 "darkgreen": "#006400",
36 "seagreen": "#2e8b57",
37 "teal": "#008080",
38 "cyan": "#00ffff",
39 "aqua": "#00ffff",
40 "turquoise": "#40e0d0",
41 "skyblue": "#87ceeb",
42 "steelblue": "#4682b4",
43 "dodgerblue": "#1e90ff",
44 "royalblue": "#4169e1",
45 "blue": "#0000ff",
46 "navy": "#000080",
47 "indigo": "#4b0082",
48 "purple": "#800080",
49 "violet": "#ee82ee",
50 "magenta": "#ff00ff",
51 "fuchsia": "#ff00ff",
52 "pink": "#ffc0cb",
53 "hotpink": "#ff69b4",
54 "brown": "#a52a2a",
55 "chocolate": "#d2691e",
56 "tan": "#d2b48c",
57 "salmon": "#fa8072",
58 "coral": "#ff7f50",
59 "tomato": "#ff6347",
60 "slategray": "#708090",
61 "slategrey": "#708090",
62 "lightgray": "#d3d3d3",
63 "lightgrey": "#d3d3d3",
64 "darkgray": "#a9a9a9",
65 "darkgrey": "#a9a9a9",
66}
68_HEX = re.compile(r"#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})")
69_FUNC = re.compile(r"(rgba?|hsla?)\(([^)]*)\)")
72def _channel(token: str, scale: float) -> float | None:
73 token = token.strip()
74 try:
75 if token.endswith("%"):
76 value = float(token[:-1]) / 100
77 else:
78 value = float(token) / scale
79 except ValueError:
80 return None
81 return min(1.0, max(0.0, value))
84def _from_hex(digits: str) -> Color:
85 if len(digits) in (3, 4):
86 digits = "".join(c * 2 for c in digits)
87 r, g, b = (int(digits[i : i + 2], 16) / 255 for i in (0, 2, 4))
88 alpha = int(digits[6:8], 16) / 255 if len(digits) == 8 else 1.0
89 return Color(r, g, b, alpha)
92def _from_function(name: str, args: str) -> Color | None:
93 parts = [p for p in re.split(r"[\s,/]+", args.strip()) if p]
94 if len(parts) not in (3, 4):
95 return None
96 alpha = _channel(parts[3], 1) if len(parts) == 4 else 1.0
97 if alpha is None:
98 return None
99 if name.startswith("rgb"):
100 channels = [_channel(p, 255) for p in parts[:3]]
101 if any(c is None for c in channels):
102 return None
103 return Color(*channels, alpha) # type: ignore[arg-type]
104 try:
105 hue = float(parts[0].removesuffix("deg")) % 360 / 360
106 except ValueError:
107 return None
108 sat, light = _channel(parts[1], 100), _channel(parts[2], 100)
109 if sat is None or light is None:
110 return None
111 r, g, b = colorsys.hls_to_rgb(hue, light, sat)
112 return Color(r, g, b, alpha)
115def parse_color(value: Any, fallback: Color) -> Color:
116 """The colour ``value`` names, or ``fallback``."""
117 if not isinstance(value, str):
118 return fallback
119 text = value.strip().lower()
120 if not text or len(text) > 64:
121 return fallback
122 text = NAMED.get(text, text)
123 if match := _HEX.fullmatch(text):
124 return _from_hex(match.group(1))
125 if match := _FUNC.fullmatch(text):
126 return _from_function(match.group(1), match.group(2)) or fallback
127 return fallback