Debian Codegraph @

src/tinycss/color3.py

raw
1 # coding: utf8
2 """
3 tinycss.colors3
4 ---------------
5
6 Parser for CSS 3 color values
7 http://www.w3.org/TR/css3-color/
8
9 This module does not provide anything that integrates in a parser class,
10 only functions that parse single tokens from (eg.) a property value.
11
12 :copyright: (c) 2012 by Simon Sapin.
13 :license: BSD, see LICENSE for more details.
14 """
15
16
17 import collections
18 import itertools
19 import re
20
21 from .tokenizer import tokenize_grouped
22
23
24 class RGBA(collections.namedtuple('RGBA', ['red', 'green', 'blue', 'alpha'])):
25 """An RGBA color.
26
27 A tuple of four floats in the 0..1 range: ``(r, g, b, a)``.
28 Also has ``red``, ``green``, ``blue`` and ``alpha`` attributes to access
29 the same values.
30
31 """
32
33
34 def parse_color_string(css_string):
35 """Parse a CSS string as a color value.
36
37 This is a convenience wrapper around :func:`parse_color` in case you
38 have a string that is not from a CSS stylesheet.
39
40 :param css_string:
41 An unicode string in CSS syntax.
42 :returns:
43 Same as :func:`parse_color`.
44
45 """
46 tokens = list(tokenize_grouped(css_string.strip()))
47 if len(tokens) == 1:
48 return parse_color(tokens[0])
49
50
51 def parse_color(token):
52 """Parse single token as a color value.
53
54 :param token:
55 A single :class:`~.token_data.Token` or
56 :class:`~.token_data.ContainerToken`, as found eg. in a
57 property value.
58 :returns:
59 * ``None``, if the token is not a valid CSS 3 color value.
60 (No exception is raised.)
61 * For the *currentColor* keyword: the string ``'currentColor'``
62 * Every other values (including keywords, HSL and HSLA) is converted
63 to RGBA and returned as an :class:`RGBA` object (a 4-tuple with
64 attribute access).
65 The alpha channel is clipped to [0, 1], but R, G, or B can be
66 out of range (eg. ``rgb(-51, 306, 0)`` is represented as
67 ``(-.2, 1.2, 0, 1)``.)
68
69 """
70 if token.type == 'IDENT':
71 return COLOR_KEYWORDS.get(token.value.lower())
72 elif token.type == 'HASH':
73 for multiplier, regexp in HASH_REGEXPS:
74 match = regexp(token.value)
75 if match:
76 r, g, b = [int(group * multiplier, 16) / 255
77 for group in match.groups()]
78 return RGBA(r, g, b, 1.)
79 elif token.type == 'FUNCTION':
80 args = parse_comma_separated(token.content)
81 if args:
82 name = token.function_name.lower()
83 if name == 'rgb':
84 return parse_rgb(args, alpha=1.)
85 elif name == 'rgba':
86 alpha = parse_alpha(args[3:])
87 if alpha is not None:
88 return parse_rgb(args[:3], alpha)
89 elif name == 'hsl':
90 return parse_hsl(args, alpha=1.)
91 elif name == 'hsla':
92 alpha = parse_alpha(args[3:])
93 if alpha is not None:
94 return parse_hsl(args[:3], alpha)
95
96
97 def parse_alpha(args):
98 """
99 If args is a list of a single INTEGER or NUMBER token,
100 return its value clipped to the 0..1 range
101 Otherwise, return None.
102 """
103 if len(args) == 1 and args[0].type in ('NUMBER', 'INTEGER'):
104 return min(1, max(0, args[0].value))
105
106
107 def parse_rgb(args, alpha):
108 """
109 If args is a list of 3 INTEGER tokens or 3 PERCENTAGE tokens,
110 return RGB values as a tuple of 3 floats in 0..1.
111 Otherwise, return None.
112 """
113 types = [arg.type for arg in args]
114 if types == ['INTEGER', 'INTEGER', 'INTEGER']:
115 r, g, b = [arg.value / 255 for arg in args[:3]]
116 return RGBA(r, g, b, alpha)
117 elif types == ['PERCENTAGE', 'PERCENTAGE', 'PERCENTAGE']:
118 r, g, b = [arg.value / 100 for arg in args[:3]]
119 return RGBA(r, g, b, alpha)
120
121
122 def parse_hsl(args, alpha):
123 """
124 If args is a list of 1 INTEGER token and 2 PERCENTAGE tokens,
125 return RGB values as a tuple of 3 floats in 0..1.
126 Otherwise, return None.
127 """
128 types = [arg.type for arg in args]
129 if types == ['INTEGER', 'PERCENTAGE', 'PERCENTAGE']:
130 hsl = [arg.value for arg in args[:3]]
131 r, g, b = hsl_to_rgb(*hsl)
132 return RGBA(r, g, b, alpha)
133
134
135 def hsl_to_rgb(hue, saturation, lightness):
136 """
137 :param hue: degrees
138 :param saturation: percentage
139 :param lightness: percentage
140 :returns: (r, g, b) as floats in the 0..1 range
141 """
142 hue = (hue / 360) % 1
143 saturation = min(1, max(0, saturation / 100))
144 lightness = min(1, max(0, lightness / 100))
145
146 # Translated from ABC: http://www.w3.org/TR/css3-color/#hsl-color
147 def hue_to_rgb(m1, m2, h):
148 if h < 0:
149 h += 1
150 if h > 1:
151 h -= 1
152 if h * 6 < 1:
153 return m1 + (m2 - m1) * h * 6
154 if h * 2 < 1:
155 return m2
156 if h * 3 < 2:
157 return m1 + (m2 - m1) * (2 / 3 - h) * 6
158 return m1
159
160 if lightness <= 0.5:
161 m2 = lightness * (saturation + 1)
162 else:
163 m2 = lightness + saturation - lightness * saturation
164 m1 = lightness * 2 - m2
165 return (
166 hue_to_rgb(m1, m2, hue + 1 / 3),
167 hue_to_rgb(m1, m2, hue),
168 hue_to_rgb(m1, m2, hue - 1 / 3),
169 )
170
171
172 def parse_comma_separated(tokens):
173 """Parse a list of tokens (typically the content of a function token)
174 as arguments made of a single token each, separated by mandatory commas,
175 with optional white space around each argument.
176
177 return the argument list without commas or white space;
178 or None if the function token content do not match the description above.
179
180 """
181 tokens = [token for token in tokens if token.type != 'S']
182 if not tokens:
183 return []
184 if len(tokens) % 2 == 1 and all(
185 token.type == 'DELIM' and token.value == ','
186 for token in tokens[1::2]):
187 return tokens[::2]
188
189
190 HASH_REGEXPS = (
191 (2, re.compile(r'^#([\da-f])([\da-f])([\da-f])$', re.I).match),
192 (1, re.compile(r'^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$', re.I).match),
193 )
194
195
196 # (r, g, b) in 0..255
197 BASIC_COLOR_KEYWORDS = [
198 ('black', (0, 0, 0)),
199 ('silver', (192, 192, 192)),
200 ('gray', (128, 128, 128)),
201 ('white', (255, 255, 255)),
202 ('maroon', (128, 0, 0)),
203 ('red', (255, 0, 0)),
204 ('purple', (128, 0, 128)),
205 ('fuchsia', (255, 0, 255)),
206 ('green', (0, 128, 0)),
207 ('lime', (0, 255, 0)),
208 ('olive', (128, 128, 0)),
209 ('yellow', (255, 255, 0)),
210 ('navy', (0, 0, 128)),
211 ('blue', (0, 0, 255)),
212 ('teal', (0, 128, 128)),
213 ('aqua', (0, 255, 255)),
214 ]
215
216
217 # (r, g, b) in 0..255
218 EXTENDED_COLOR_KEYWORDS = [
219 ('aliceblue', (240, 248, 255)),
220 ('antiquewhite', (250, 235, 215)),
221 ('aqua', (0, 255, 255)),
222 ('aquamarine', (127, 255, 212)),
223 ('azure', (240, 255, 255)),
224 ('beige', (245, 245, 220)),
225 ('bisque', (255, 228, 196)),
226 ('black', (0, 0, 0)),
227 ('blanchedalmond', (255, 235, 205)),
228 ('blue', (0, 0, 255)),
229 ('blueviolet', (138, 43, 226)),
230 ('brown', (165, 42, 42)),
231 ('burlywood', (222, 184, 135)),
232 ('cadetblue', (95, 158, 160)),
233 ('chartreuse', (127, 255, 0)),
234 ('chocolate', (210, 105, 30)),
235 ('coral', (255, 127, 80)),
236 ('cornflowerblue', (100, 149, 237)),
237 ('cornsilk', (255, 248, 220)),
238 ('crimson', (220, 20, 60)),
239 ('cyan', (0, 255, 255)),
240 ('darkblue', (0, 0, 139)),
241 ('darkcyan', (0, 139, 139)),
242 ('darkgoldenrod', (184, 134, 11)),
243 ('darkgray', (169, 169, 169)),
244 ('darkgreen', (0, 100, 0)),
245 ('darkgrey', (169, 169, 169)),
246 ('darkkhaki', (189, 183, 107)),
247 ('darkmagenta', (139, 0, 139)),
248 ('darkolivegreen', (85, 107, 47)),
249 ('darkorange', (255, 140, 0)),
250 ('darkorchid', (153, 50, 204)),
251 ('darkred', (139, 0, 0)),
252 ('darksalmon', (233, 150, 122)),
253 ('darkseagreen', (143, 188, 143)),
254 ('darkslateblue', (72, 61, 139)),
255 ('darkslategray', (47, 79, 79)),
256 ('darkslategrey', (47, 79, 79)),
257 ('darkturquoise', (0, 206, 209)),
258 ('darkviolet', (148, 0, 211)),
259 ('deeppink', (255, 20, 147)),
260 ('deepskyblue', (0, 191, 255)),
261 ('dimgray', (105, 105, 105)),
262 ('dimgrey', (105, 105, 105)),
263 ('dodgerblue', (30, 144, 255)),
264 ('firebrick', (178, 34, 34)),
265 ('floralwhite', (255, 250, 240)),
266 ('forestgreen', (34, 139, 34)),
267 ('fuchsia', (255, 0, 255)),
268 ('gainsboro', (220, 220, 220)),
269 ('ghostwhite', (248, 248, 255)),
270 ('gold', (255, 215, 0)),
271 ('goldenrod', (218, 165, 32)),
272 ('gray', (128, 128, 128)),
273 ('green', (0, 128, 0)),
274 ('greenyellow', (173, 255, 47)),
275 ('grey', (128, 128, 128)),
276 ('honeydew', (240, 255, 240)),
277 ('hotpink', (255, 105, 180)),
278 ('indianred', (205, 92, 92)),
279 ('indigo', (75, 0, 130)),
280 ('ivory', (255, 255, 240)),
281 ('khaki', (240, 230, 140)),
282 ('lavender', (230, 230, 250)),
283 ('lavenderblush', (255, 240, 245)),
284 ('lawngreen', (124, 252, 0)),
285 ('lemonchiffon', (255, 250, 205)),
286 ('lightblue', (173, 216, 230)),
287 ('lightcoral', (240, 128, 128)),
288 ('lightcyan', (224, 255, 255)),
289 ('lightgoldenrodyellow', (250, 250, 210)),
290 ('lightgray', (211, 211, 211)),
291 ('lightgreen', (144, 238, 144)),
292 ('lightgrey', (211, 211, 211)),
293 ('lightpink', (255, 182, 193)),
294 ('lightsalmon', (255, 160, 122)),
295 ('lightseagreen', (32, 178, 170)),
296 ('lightskyblue', (135, 206, 250)),
297 ('lightslategray', (119, 136, 153)),
298 ('lightslategrey', (119, 136, 153)),
299 ('lightsteelblue', (176, 196, 222)),
300 ('lightyellow', (255, 255, 224)),
301 ('lime', (0, 255, 0)),
302 ('limegreen', (50, 205, 50)),
303 ('linen', (250, 240, 230)),
304 ('magenta', (255, 0, 255)),
305 ('maroon', (128, 0, 0)),
306 ('mediumaquamarine', (102, 205, 170)),
307 ('mediumblue', (0, 0, 205)),
308 ('mediumorchid', (186, 85, 211)),
309 ('mediumpurple', (147, 112, 219)),
310 ('mediumseagreen', (60, 179, 113)),
311 ('mediumslateblue', (123, 104, 238)),
312 ('mediumspringgreen', (0, 250, 154)),
313 ('mediumturquoise', (72, 209, 204)),
314 ('mediumvioletred', (199, 21, 133)),
315 ('midnightblue', (25, 25, 112)),
316 ('mintcream', (245, 255, 250)),
317 ('mistyrose', (255, 228, 225)),
318 ('moccasin', (255, 228, 181)),
319 ('navajowhite', (255, 222, 173)),
320 ('navy', (0, 0, 128)),
321 ('oldlace', (253, 245, 230)),
322 ('olive', (128, 128, 0)),
323 ('olivedrab', (107, 142, 35)),
324 ('orange', (255, 165, 0)),
325 ('orangered', (255, 69, 0)),
326 ('orchid', (218, 112, 214)),
327 ('palegoldenrod', (238, 232, 170)),
328 ('palegreen', (152, 251, 152)),
329 ('paleturquoise', (175, 238, 238)),
330 ('palevioletred', (219, 112, 147)),
331 ('papayawhip', (255, 239, 213)),
332 ('peachpuff', (255, 218, 185)),
333 ('peru', (205, 133, 63)),
334 ('pink', (255, 192, 203)),
335 ('plum', (221, 160, 221)),
336 ('powderblue', (176, 224, 230)),
337 ('purple', (128, 0, 128)),
338 ('red', (255, 0, 0)),
339 ('rosybrown', (188, 143, 143)),
340 ('royalblue', (65, 105, 225)),
341 ('saddlebrown', (139, 69, 19)),
342 ('salmon', (250, 128, 114)),
343 ('sandybrown', (244, 164, 96)),
344 ('seagreen', (46, 139, 87)),
345 ('seashell', (255, 245, 238)),
346 ('sienna', (160, 82, 45)),
347 ('silver', (192, 192, 192)),
348 ('skyblue', (135, 206, 235)),
349 ('slateblue', (106, 90, 205)),
350 ('slategray', (112, 128, 144)),
351 ('slategrey', (112, 128, 144)),
352 ('snow', (255, 250, 250)),
353 ('springgreen', (0, 255, 127)),
354 ('steelblue', (70, 130, 180)),
355 ('tan', (210, 180, 140)),
356 ('teal', (0, 128, 128)),
357 ('thistle', (216, 191, 216)),
358 ('tomato', (255, 99, 71)),
359 ('turquoise', (64, 224, 208)),
360 ('violet', (238, 130, 238)),
361 ('wheat', (245, 222, 179)),
362 ('white', (255, 255, 255)),
363 ('whitesmoke', (245, 245, 245)),
364 ('yellow', (255, 255, 0)),
365 ('yellowgreen', (154, 205, 50)),
366 ]
367
368
369 # (r, g, b, a) in 0..1 or a string marker
370 SPECIAL_COLOR_KEYWORDS = {
371 'currentcolor': 'currentColor',
372 'transparent': RGBA(0., 0., 0., 0.),
373 }
374
375
376 # RGBA namedtuples of (r, g, b, a) in 0..1 or a string marker
377 COLOR_KEYWORDS = SPECIAL_COLOR_KEYWORDS.copy()
378 COLOR_KEYWORDS.update(
379 # 255 maps to 1, 0 to 0, the rest is linear.
380 (keyword, RGBA(r / 255., g / 255., b / 255., 1.))
381 for keyword, (r, g, b) in itertools.chain(
382 BASIC_COLOR_KEYWORDS, EXTENDED_COLOR_KEYWORDS))