aboutsummaryrefslogtreecommitdiff
path: root/thcolor/_color.py
blob: 1bc8f6e24b1180d7738a9db7e0385d64737b71ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2019 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the thcolor project, which is MIT-licensed.
#******************************************************************************
""" HTML/CSS like color parsing, mainly for the `[color]` tag.
	Defines the `get_color()` function which returns an rgba value. """

from enum import Enum as _Enum
from warnings import warn as _warn

_gg_no_re = False

try:
	import regex as _re
except ImportError:
	_warn("could not import regex, text parsing is disabled.",
		RuntimeWarning)
	_gg_no_re = True

from ._ref import Reference as _Reference
from ._angle import Angle as _Angle
from ._sys import (hls_to_rgb as _hls_to_rgb, rgb_to_hls as _rgb_to_hls,
	rgb_to_hwb as _rgb_to_hwb, hwb_to_rgb as _hwb_to_rgb,
	rgb_to_cmyk as _rgb_to_cmyk, cmyk_to_rgb as _cmyk_to_rgb,
	lab_to_rgb as _lab_to_rgb, rgb_to_lab as _rgb_to_lab,
	lab_to_lch as _lab_to_lch, lch_to_lab as _lch_to_lab,
	netscape_color as _netscape_color)
from ._exc import (\
	ColorExpressionDecodingError as _ColorExpressionDecodingError,
	NotEnoughArgumentsError as _NotEnoughArgumentsError,
	TooManyArgumentsError as _TooManyArgumentsError,
	InvalidArgumentTypeError as _InvalidArgumentTypeError,
	InvalidArgumentValueError as _InvalidArgumentValueError)

__all__ = ["Color"]

# ---
# Decoding utilities.
# ---

_color_pattern = None

def _get_color_pattern():
	global _color_pattern

	if _color_pattern is None:
		if _gg_no_re:
			raise ImportError("text parsing is disabled until you install " \
				"the 'regex' module, e.g. via `pip install regex`.")

		_color_pattern = _re.compile(r"""
			(
				((?P<agl_val>-? ([0-9]+\.?|[0-9]*\.[0-9]+)) \s*
				 (?P<agl_typ>deg|grad|rad|turn))
			  | ((?P<per>[0-9]+(\.[0-9]*)? | \.[0-9]+) \s* \%)
			  |  (?P<num>[0-9]+(\.[0-9]*)? | \.[0-9]+)
			  |  (?P<ncol>[RYGCBM] [0-9]{0,2} (\.[0-9]*)?)
			  |  (\# (?P<hex>[0-9a-f]{3} | [0-9a-f]{4} | [0-9a-f]{6} | [0-9a-f]{8}))
			  |  ((?P<name>[a-z]([a-z0-9\s_-]*[a-z0-9_-])?)
				  ( \s* \( \s* (?P<arg> (?0)? ) \s* \) )?)
			)

			\s* ((?P<sep>[,/\s])+ \s* (?P<nextargs> (?0))?)?
		""", _re.VERBOSE | _re.I | _re.M)

	return _color_pattern

# ---
# Color initialization varargs utilities.
# ---

def _color_profile(name, value):
	try:
		value = Color.Profile.from_value(value)
	except (TypeError, ValueError):
		raise ValueError(f"{name} is not a valid color profile " \
			f"(got {repr(value)}).")

	return value

def _byte(name, value):
	try:
		assert value == int(value)
		assert 0 <= value < 256
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a byte between 0 and 255") \
			from None

	return value

def _signed(name, value):
	try:
		value = float(value)
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a signed number")

	return round(value, 4)

def _unsigned(name, value):
	try:
		value = float(value)
		assert value >= 0
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a positive number")

	return round(value, 4)

def _unrestricted_percentage(name, value):
	try:
		value = float(value)
		assert 0.0 <= value
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a proportion starting from 0") \
			from None

	return round(value, 4)

def _percentage(name, value):
	try:
		value = float(value)
		assert 0.0 <= value <= 1.0
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a proportion between 0 " \
			"and 1.0") from None

	return round(value, 4)

def _hue(name, value):
	if isinstance(value, _Angle):
		pass
	else:
		try:
			value = _Angle(value)
		except:
			raise ValueError(f"{name} should be an Angle instance")

	return value

# ---
# Color class definition.
# ---

class Color:
	""" Class representing a color within thcolor. Its constructor depends
		on the first given argument, which represents the color type as one
		of the :class:`Color.Type` constants.

		.. function:: Color(Color.Type.RGB, red, green, blue, alpha = 1.0)

			Create a color using its red, green and blue components. Each is
			expressed as a byte value, from 0 (dark) to 255 (light).

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.RGB, profile, red, green, blue, """ \
			"""alpha = 1.0)

			Create a color using its profile, red, green and blue component.
			Each is expressed as a byte value, from 0 (dark) to 255 (light).

			The profile is one of the :class:`thcolor.Color.Profile`
			constants, and represents the RGB profile.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.HSL, hue, saturation, lightness, """ \
			"""alpha = 1.0)

			Create a color using its hue, saturation and lightness components.
			The hue is represented by an :class:`Angle` object, and the
			saturation and lightness are values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.HWB, hue, whiteness, blackness, """ \
			"""alpha = 1.0)

			Create a color using its hue, whiteness and blackness components.
			The hue is represented by an :class:`Angle` object, and the
			whiteness and lightness are values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.CMYK, cyan, magenta, yellow, """ \
			"""black, alpha = 1.0)

			Create a color using its cyan, magenta, yellow and blackness
			components, which are all values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.LAB, lightness, a, b, alpha = 1.0)

			Create a color using its CIE Lightness (similar to the lightness
			in the HSL representation) and the A and B axises in the Lab
			colorspace, represented by signed numbers.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.LCH, lightness, chroma, hue, """ \
			"""alpha = 1.0)

			Create a color using its CIE Lightness (similar to the lightness
			in the HSL representation), its chroma (as a positive number
			theoretically unbounded) and its hue.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.XYZ, x, y, z, alpha = 1.0)

			Create a color using its CIE XYZ components (as numbers between
			0 and 1).

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components. """

	class Type(_Enum):
		""" Class representing the type of a color, or how it is expressed.
			The following types are available:

			.. data:: INVALID

				An invalid color, for internal processing.

			.. data:: RGB

				A color expressed through its sRGB components: red, green
				and blue.

			.. data:: HSL

				A color expressed through its HSL components: hue, saturation
				and lightness.

			.. data:: HWB

				A color expressed through its HWB components: hue, whiteness
				and blackness.

			.. data:: CMYK

				A color expressed through its CMYK components: cyan, magenta,
				yellow and black.

			.. data:: LAB

				A color expressed through its lightness and Lab colorspace
				coordinates (A and B).

			.. data:: LCH

				A color expressed through its lightness, chroma and hue.

			.. data:: XYZ

				A color expressed through its CIE XYZ coordinates.

			An alpha component can be added to every single one of these
			types, so it is not included in the type names. """

		# Values start at 65600 in order not to infer with "normal" values
		# going up to 65535, just in case.

		INVALID = 65600

		RGB     = 65601
		HSL     = 65602
		HWB     = 65603
		CMYK    = 65604
		LAB     = 65605
		LCH     = 65606
		XYZ     = 65607

	class Profile(_Enum):
		""" Class representing the profile of a color, or how it is expressed.
			The following profiles are available:

			.. data:: SRGB

				A basic sRGB profile.

			.. data:: IMAGE_P3

				See `the description in CSS Module Level 4
				<https://drafts.csswg.org/css-color/#valdef-color-image-p3>`_.

			.. data:: A98RGB

				The Adobe® RGB (1998) color profile. See `the description
				in CSS Module Level 4
				<https://drafts.csswg.org/css-color/#valdef-color-a98rgb>`_.

			.. data:: PROPHOTORGB

				The ProPHOTO RGB color profile. See `the description in
				CSS Module Level 4
				<https://drafts.csswg.org/css-color/#valdef-color-prophotorgb>`_.

			.. data:: REC2020

				The REC.2020 colorspace. See `the description in CSS Module
				Level 4
				<https://drafts.csswg.org/css-color/#valdef-color-rec2020>`_. """

		SRGB        = 65700
		IMAGE_P3    = 65701
		A98RGB      = 65702
		PROPHOTORGB = 65703
		REC2020     = 65704

		def from_value(value):
			_profiles = {
				'srgb':        'SRGB',
				'imagep3':     'IMAGE_P3',
				'a98rgb':      'A98RGB',
				'prophotorgb': 'PROPHOTORGB',
				'rec2020':     'REC2020'}

			if type(value) == str:
				newval = ''.join(c for c in value.casefold() if c in \
					'0123456789abcdefghijklmnopqrstuvwxyz')
				try:
					value = _profiles[newval]
				except:
					pass

				return getattr(Color.Profile, value)

			return Color.Profile(value)

	# Properties to work with:
	#
	# `_type`: the type as one of the `Color.Type` constants.
	# `_alpha`: alpha value.
	#
	# RGB colors:
	# `_r`, `_g`, `_b`: rgb components, as bytes.
	# `_profile`: the color profile.
	#
	# HSL colors:
	# `_hue`: hue.
	# `_sat`, `_lgt`: saturation and light for HSL.
	#
	# HWB colors:
	# `_hue`: hue.
	# `_wht`, `_blk`: whiteness and blackness for HWB.
	#
	# CMYK colors:
	# `_cy`, `_ma`, `_ye`, `_bl`: CMYK components.
	#
	# LAB colors:
	# `_lgt`: lightness.
	# `_a`, `_b`: coordinates in the Lab colorspace.
	#
	# LCH colors:
	# `_lgt`: lightness.
	# `_hue`: the hue.
	# `_chr`: the chroma.
	#
	# XYZ colors:
	# `_x`, `_y`, `_z`: XYZ components.

	def __init__(self, *args, **kwargs):
		self._type = Color.Type.INVALID
		self.set(*args, **kwargs)

	def __repr__(self):
		args = (('type', f'{self.__class__.__name__}.{str(self._type)}'),)
		if   self._type == Color.Type.RGB:
			args += (('profile',
				f'{self.__class__.__name__}.{str(self._profile)}'),
				('red', repr(self._r)), ('green', repr(self._g)),
				('blue', repr(self._b)))
		elif self._type == Color.Type.HSL:
			args += (('hue', repr(self._hue)), ('saturation', repr(self._sat)),
				('lightness', repr(self._lgt)))
		elif self._type == Color.Type.HWB:
			args += (('hue', repr(self._hue)), ('whiteness', repr(self._wht)),
				('blackness', repr(self._blk)))
		elif self._type == Color.Type.CMYK:
			args += (('cyan', repr(self._cy)), ('magenta', repr(self._ma)),
				('yellow', repr(self._ye)), ('black', repr(self._bl)))
		elif self._type == Color.Type.LAB:
			args += (('lightness', repr(self._lgt)), ('a', repr(self._a)),
				('b', repr(self._b)))
		elif self._type == Color.Type.LCH:
			args += (('lightness', repr(self._lgt)),
				('chroma', repr(self._chr)), ('hue', repr(self._hue)))
		elif self._type == Color.Type.XYZ:
			args += (('x', repr(self._x)), ('y', repr(self._y)),
				('z', repr(self._z)))

		args += (('alpha', self._alpha),)

		argtext = ', '.join(f'{key} = {value}' for key, value in args)
		return f"{self.__class__.__name__}({argtext})"

	def __eq__(self, other):
		if not isinstance(other, Color):
			return super().__eq__(other)

		if   other.type == Color.Type.INVALID:
			return self._type == Color.Type.INVALID
		elif other.type == Color.Type.HSL:
			return self.hsla() == other.hsla()
		elif other.type == Color.Type.HWB:
			return self.hwba() == other.hwba()
		elif other.type == Color.Type.CMYK:
			return self.cmyka() == other.cmyka()
		elif other.type == Color.Type.LAB:
			return self.laba() == other.laba()
		elif other.type == Color.Type.LCH:
			return self.lcha() == other.lcha()
		elif other.type == Color.Type.XYZ:
			return self.xyza() == other.xyza()

		return self.rgba() == other.rgba()

	# ---
	# Management methods.
	# ---

	def set(self, *args, **kwargs):
		""" Set the color using its constructor arguments and keyword
			arguments. """

		args = list(args)

		def _decode_varargs(*keys):
			class _UNDEFINED_CLASS:
				pass
			_UNDEFINED = _UNDEFINED_CLASS()

			def _get_value(value_array):
				if not value_array:
					value = _UNDEFINED
				else:
					value = value_array[0] if len(value_array) == 1 \
						else value_array

				return value

			# Check for each key.

			results = ()

			left_args = len(keys)

			for names, convert_func, *value in keys:
				value = _get_value(value)

				for name in names:
					if name in kwargs:
						if value is _UNDEFINED and args:
							raise TypeError(f"{self.__class__.__name__}() " \
								f"got multiple values for argument {name}")

						raw_result = kwargs.pop(name)
						break
				else:
					name = names[0]
					if   value is not _UNDEFINED and len(args) < left_args:
						raw_result = value
					elif args:
						raw_result = args.pop(0)
					else:
						raise TypeError(f"{self.__class__.__name__}() " \
							"missing a required positional argument: " \
							f"{name}")

				result = convert_func(name, raw_result)
				results += (result,)

				left_args -= 1

			# Check for keyword arguments for which keys are not in the set.

			if kwargs:
				raise TypeError(f"{next(iter(kwargs.keys()))} is an invalid " \
					f"keyword argument for type {type}")

			return results

		# ---
		# Main function body.
		# ---

		# Check for the type.

		if args:
			try:
				type = kwargs.pop('type')
			except:
				type = args.pop(0)
			else:
				if isinstance(args[0], Color.Type):
					raise TypeError(f"{self.__class__.__name__}() got " \
						"multiple values for argument 'type'")
		else:
			try:
				type = kwargs.pop('type')
			except:
				type = self._type
				if type == Color.Type.INVALID:
					raise TypeError(f"{self.__class__.__name__}() missing " \
						"required argument: 'type'")

		try:
			type = Color.Type(type)
		except:
			type = Color.Type.RGB

		# Initialize the properties.

		if   type == Color.Type.RGB:
			self._profile, self._r, self._g, self._b, self._alpha = \
				_decode_varargs(\
				(('profile', 'p'), _color_profile, 'srgb'),
				(('red', 'r'),     _byte),
				(('green', 'g'),   _byte),
				(('blue', 'b'),    _byte),
				(('alpha', 'a'),   _percentage, 1.0))

			if self._profile != Color.Profile.SRGB:
				raise NotImplementedError("rgb profile " \
					f"{repr(self._profile)} isn't managed yet.")
		elif type == Color.Type.HSL:
			self._hue, self._sat, self._lgt, self._alpha = _decode_varargs(\
				(('hue', 'h'),                       _hue),
				(('saturation', 'sat', 's'),         _percentage),
				(('lightness', 'light', 'lig', 'l'), _percentage),
				(('alpha', 'a'),                     _percentage, 1.0))
		elif type == Color.Type.HWB:
			self._hue, self._wht, self._blk, self._alpha = _decode_varargs(\
				(('hue', 'h'),                _hue),
				(('whiteness', 'white', 'w'), _percentage),
				(('blackness', 'black', 'b'), _percentage),
				(('alpha', 'a'),              _percentage, 1.0))
		elif type == Color.Type.CMYK:
			self._cy, self._ma, self._ye, self._bl, self._alpha = \
				_decode_varargs(\
				(('cyan', 'c'),    _percentage),
				(('magenta', 'm'), _percentage),
				(('yellow', 'y'),  _percentage),
				(('black', 'b'),   _percentage),
				(('alpha', 'a'),   _percentage, 1.0))
		elif type == Color.Type.LAB:
			self._lgt, self._a, self._b, self._alpha = _decode_varargs(\
				(('lightness', 'light', 'lig', 'l'), _unrestricted_percentage),
				(('a',),                             _signed),
				(('b',),                             _signed),
				(('alpha', 'a'),                     _percentage, 1.0))
		elif type == Color.Type.LCH:
			self._lgt, self._chr, self._hue, self._alpha = _decode_varargs(\
				(('lightness', 'light', 'lig', 'l'), _percentage),
				(('chroma', 'chr', 'c'),             _unsigned),
				(('hue', 'h'),                       _hue),
				(('alpha', 'a'),                     _percentage, 1.0))
		elif type == Color.Type.XYZ:
			self._x, self._y, self._z, self._alpha = _decode_varargs(\
				(('x',),         _percentage),
				(('y',),         _percentage),
				(('z',),         _percentage),
				(('alpha', 'a'), _percentage, 1.0))
		else:
			raise ValueError(f"invalid color type: {type}")

		# Once the arguments have been tested to be valid, we can set the
		# type.

		self._type = type

	# ---
	# Properties.
	# ---

	@property
	def type(self):
		""" The read-only angle type as one of the :class:`Color.Type`
			constants. """

		return self._type

	# ---
	# Conversion methods.
	# ---

	def rgb(self):
		""" Get the sRGB (red, green, blue) components of the color.
			For example:

				>>> Color.from_text("#876543").rgb()
				... (135, 101, 67)

			If the color is not represented as sRGB internally, it will be
			converted. """

		if   self._type == Color.Type.RGB:
			return (self._r, self._g, self._b)
		elif self._type == Color.Type.HSL:
			return _hls_to_rgb(self._hue, self._lgt, self._sat)
		elif self._type == Color.Type.HWB:
			return _hwb_to_rgb(self._hue, self._wht, self._blk)
		elif self._type == Color.Type.CMYK:
			return _cmyk_to_rgb(self._cy, self._ma, self._ye, self._bl)
		elif self._type == Color.Type.LAB:
			return _lab_to_rgb(self._lgt, self._a, self._b)
		elif self._type == Color.Type.LCH:
			return _lch_to_rgb(self._lgt, self._chr, self._hue)

		raise ValueError(f"color type {self._type} doesn't translate to rgb")

	def hsl(self):
		""" Get the HSL (hue, saturation, lightness) components of the color.
			For example:

				>>> Color.from_text("hsl(90turn 0% 5%)").hls()
				... (Angle(type = Angle.Type.TURN, value = 90.0), 0.05, 0.0)

			If the color is not represented as HSL internally, it will be
			converted. """

		if self._type == Color.Type.HSL:
			return (self._hue, self._sat, self._lgt)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to hsl") from None

		return _rgb_to_hls(*rgb)

	def hwb(self):
		""" Get the HWB (hue, whiteness, blackness) components of the color.
			For example:

				>>> Color.from_text("hwb(.7 turn / 5% 10%)").hwb()
				... (Angle(type = Angle.Type.TURN, value = 0.7), 0.05, 0.1)

			If the color is not represented as HSL internally, it will be
			converted. """

		if self._type == Color.Type.HWB:
			return (self._hue, self._wht, self._blk)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to hwb") from None

		return _rgb_to_hwb(*rgb)

	def cmyk(self):
		""" Get the CMYK (cyan, magenta, yellow, black) components of the
			color. For example:

				>>> Color.from_text("cmyk(.1 .2 .3 .4)").cmyk()
				... (0.1, 0.2, 0.3, 0.4)

			If the color is not represented as CMYK internally, it will be
			converted naively. """

		if self._type == Color.Type.CMYK:
			return (self._cy, self._ma, self._ye, self._bl)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to cmyk") from None

		return _rgb_to_cmyk(*rgb)

	def lab(self):
		""" Get the LAB (lightness, Lab colorspace coordinates) components
			of the color. For example:

				>>> Color.from_text("lab(50 50 0)").lab()
				... (0.5, 50, 0)

			If the color is not represented as LAB internally, it will be
			converted. """

		if   self._type == Color.Type.LAB:
			return (self._lgt, self._a, self._b)
		elif self._type == Color.Type.LCH:
			return _lch_to_lab(self._lgt, self._chr, self._hue)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to lab") from None

		return _rgb_to_lab(*rgb)

	def lch(self):
		""" Get the LCH (lightness, chroma, hue) components of the color.
			For example:

				>>> Color.from_text("lch(50 230 0deg)").lch()
				... (0.5, 230, Angle(Angle.Type.DEG, 0))

			If the color is not represented as LCH internally, it will be
			converted. """

		if self._type == Color.Type.LCH:
			return (self._lgt, self._chr, self._hue)

		try:
			lab = self.lab()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to lch") from None

		return _lab_to_lch(*lab)

	def xyz(self):
		""" Get the XYZ components of the color.
			For example:

				>>> Color.from_text("xyz(0.2, 0.4, 0.5)")
				... (0.2, 0.4, 0.5)

			If the color is not represented as XYZ internally, it will be
			converted. """

		if   self._type == Color.Type.XYZ:
			return (self._x, self._y, self._z)

		raise NotImplementedError # TODO

	def rgba(self):
		""" Get the sRGB (red, green, blue) and alpha components of the color.
			For example:

				>>> Color.from_text("#87654321").rgb()
				... (135, 101, 67, 0.1294)

			If the color is not represented as sRGB internally, it will be
			converted. """

		r, g, b = self.rgb()
		alpha = self._alpha

		return (r, g, b, alpha)

	def hsla(self):
		""" Get the HSL (hue, saturation, lightness) and alpha components of
			the color. For example:

				>>> Color.from_text("hsl(90turn 0% 5% .8)").hlsa()
				... (Angle(type = Angle.Type.TURN, value = 90.0), 0.05, 0.0, 0.8)

			If the color is not represented as HSL internally, it will be
			converted. """

		h, s, l = self.hsl()
		alpha = self._alpha

		return (h, s, l, alpha)

	def hls(self):
		""" Alias for :meth:`hsl` but reverses the lightness and
			saturation for commodity. """

		h, s, l = self.hsl()
		return (h, l, s)

	def hlsa(self):
		""" Alias for :meth:`hsla` but reverses the lightness and
			saturation for commodity. """

		h, s, l, a = self.hsla()
		return (h, l, s, a)

	def hwba(self):
		""" Get the HWB (hue, whiteness, blackness) and alpha components of
			the color. For example:

				>>> Color.from_text("hwb(.7 turn / 5% 10% .2)").hwba()
				... (Angle(type = Angle.Type.TURN, value = 0.7), 0.05, 0.1, 0.2)

			If the color is not represented as HSL internally, it will be
			converted. """

		h, w, b = self.hwb()
		a = self._alpha

		return (h, w, b, a)

	def cmyka(self):
		""" Get the CMYK (cyan, magenta, yellow, black) and alpha components
			of the color. For example:

				>>> Color.from_text("cmyk(.1 .2 .3 .4 / 10%)").cmyka()
				... (0.1, 0.2, 0.3, 0.4, 0.1)

			If the color is not represented as CMYK internally, it will be
			converted naively. """

		c, m, y, k = self.cmyk()
		a = self._alpha

		return (c, m, y, k, a)

	def laba(self):
		""" Get the LAB (lightness, Lab colorspace coordinates) and alpha
			components of the color. For example:

				>>> Color.from_text("lab(50 50 0 / 0.75)").laba()
				... (0.5, 50, 0, 0.75)

			If the color is not represented as LAB internally, it will be
			converted naively. """

		l, a, b = self.lab()
		alpha = self._alpha

		return (l, a, b, alpha)

	def lcha(self):
		""" Get the LCH (lightness, chroma, hue) and alpha components
			of the color. For example:

				>>> Color.from_text("lch(50 230 0deg)").lcha()
				... (0.5, 230, Angle(Angle.Type.DEG, 0), 1.0)

			If the color is not represented as LCH internally, it will be
			converted. """

		l, c, h = self.lch()
		alpha = self._alpha

		return (l, c, h, alpha)

	def xyza(self):
		""" Get the XYZ and alpha components of the color.
			For example:

				>>> Color.from_text("xyz(0.2, 0.4, 0.5 / 65%)")
				... (0.2, 0.4, 0.5, 0.65)

			If the color is not represented as XYZ internally, it will be
			converted. """

		x, y, z = self.xyz()
		alpha = self._alpha

		return (x, y, z)

	def css(self):
		""" Get the CSS color descriptions, with older CSS specifications
			compatibility, as a list of strings.

			For example:

				>>> Color(Color.Type.RGB, 18, 52, 86, 0.82).css()
				... ["#123456", "rgba(18, 52, 86, 82%)"] """

		def _percent(prop):
			per = round(prop, 4) * 100
			if per == int(per):
				per = int(per)
			return per

		def _deg(agl):
			agl = round(agl.degrees, 2)
			if agl == int(agl):
				agl = int(agl)
			return agl

		def statements():
			# Start by yelling a #RRGGBB color, compatible with most
			# web browsers around the world, followed by the rgba()
			# notation if the alpha value isn't 1.0.

			r, g, b, a = self.rgba()
			a = round(a, 3)
			yield f'#{r:02X}{g:02X}{b:02X}'

			if a < 1.0:
				yield f'rgba({r}, {g}, {b}, {_percent(a)}%)'

			# Then yield more specific CSS declarations in case
			# they're supported (which would be neat!).

			if   self._type == Color.Type.HSL:
				args = f'{_deg(self._hue)}deg, ' \
					f'{_percent(self._sat)}%, {_percent(self._lgt)}%'

				if a < 1.0:
					yield f'hsla({args}, {_percent(a)}%)'
				else:
					yield f'hsl({args})'
			elif self._type == Color.Type.HWB:
				args = f'{_deg(self._hue)}deg, ' \
					f'{_percent(self._wht)}%, {_percent(self._blk)}%'

				if a < 1.0:
					yield f'hwba({args}, {_percent(a)}%)'
				else:
					yield f'hwb({args})'

		return tuple(statements())

	# ---
	# Static methods for decoding.
	# ---

	def from_str(*args, **kwargs):
		""" Alias for :meth:`from_text()`. """

		return Color.from_text(value)

	def from_string(*args, **kwargs):
		""" Alias for :meth:`from_text()`. """

		return Color.from_text(value)

	def from_text(expr, ref = None):
		""" Create a color from a string using a :class:`Reference` object.
			If the ``ref`` argument is ``None``, then the default reference
			is loaded.

			An example:

				>>> Color.from_text("#123456")
				... Color(type = Color.Type.RGB, red = 18, green = 52, """ \
				""" blue = 86, alpha = 1.0) """

		if ref is None:
			ref = _Reference.default()
		if not isinstance(ref, _Reference):
			raise ValueError("ref is expected to be a subclass of Reference")

		class argument:
			def __init__(self, column, value):
				self._column = column
				self._value = value

			def __repr__(self):
				return f"{self.__class__.__name__}(column = {self._column}, " \
					f"value = {repr(self._value)})"

			@property
			def column(self):
				return self._column

			@property
			def value(self):
				return self._value

		def recurse(column, match):
			if not match:
				return ()

			if   match['agl_val'] is not None:
				# The matched value is an angle.

				agl_typ = {
					'deg':  _Angle.Type.DEG,
					'grad': _Angle.Type.GRAD,
					'rad':  _Angle.Type.RAD,
					'turn': _Angle.Type.TURN}[match['agl_typ']]

				value = _Reference.angle(_Angle(agl_typ,
					float(match['agl_val'])))
			elif match['per'] is not None:
				# The matched value is a percentage.

				value = float(match['per'])
				value = _Reference.percentage(value)
			elif match['num'] is not None:
				# The matched value is a number.

				value = _Reference.number(match['num'])
			elif match['hex'] is not None:
				# The matched value is a hex color.

				name = match['hex']

				if len(name) <= 4:
					name = ''.join(map(lambda x: x + x, name))

				r = int(name[0:2], 16)
				g = int(name[2:4], 16)
				b = int(name[4:6], 16)
				a = int(name[6:8], 16) / 255.0 if len(name) == 8 else 1.0

				value = _Reference.color(Color(Color.Type.RGB, r, g, b, a))
			elif match['arg'] is not None:
				# The matched value is a function.

				name = match['name']

				# Get the arguments.

				args = recurse(column + match.start('arg'),
					_get_color_pattern().fullmatch(match['arg']))

				# Get the function and call it with the arguments.

				try:
					func = ref.functions[name]
				except KeyError:
					raise _ColorExpressionDecodingError("no such function " \
						f"{repr(name)}", column = column)

				try:
					value = func(*map(lambda x: x.value, args))
				except _NotEnoughArgumentsError as e:
					raise _ColorExpressionDecodingError("not enough " \
						f"arguments (expected at least {e.count} arguments)",
						column = column, func = name)
				except _TooManyArgumentsError as e:
					raise _ColorExpressionDecodingError("extraneous " \
						f"argument (expected {e.count} arguments at most)",
						column = args[e.count].column, func = name)
				except _InvalidArgumentTypeError as e:
					raise _ColorExpressionDecodingError("type mismatch for " \
						f"argument {e.index + 1}: expected {e.expected}, " \
						f"got {e.got}", column = args[e.index].column,
						func = name)
				except _InvalidArgumentValueError as e:
					raise _ColorExpressionDecodingError("erroneous value " \
						f"for argument {e.index + 1}: {e.text}",
						column = args[e.index].column, func = name)
				except NotImplementedError:
					raise _ColorExpressionDecodingError("not implemented",
						column = column, func = name)
			else:
				if match['ncol']:
					# The match is probably a natural color (ncol), we ought
					# to parse it and get the following arguments or, if
					# anything is invalid, to treat it as a color name.

					name = match['ncol']

					# First, get the letter and proportion.

					letter = name[0]
					number = float(name[1:])

					if number >= 0 and number < 100:
						# Get the following arguments and check.

						args = recurse(column + match.start('nextargs'),
							_get_color_pattern().fullmatch(match['nextargs'] \
							or ""))

						try:
							assert len(args) >= 2
							w = args[0].value.to_factor()
							b = args[1].value.to_factor()
						except:
							w = 0
							b = 0
						else:
							args = args[2:]

						# Calculate the color and return the args.

						color = Color(Color.Type.HWB,
							_Angle(_Angle.Type.DEG, 'RYGCBM'.find(letter) \
								* 60 + number / 100 * 60), w, b)

						# And finally, return the args.

						return (argument(column, _Reference.color(color)),) \
							+ args

				# The matched value is a named color.

				name = match['name']

				try:
					# Get the named color (e.g. 'blue').

					value = ref.colors[name]
					assert value != None
				except:
					r, g, b = _netscape_color(name)
					value = Color(Color.Type.RGB, r, g, b, 1.0)

				value = _Reference.color(value)

			return (argument(column, value),) \
				+ recurse(column + match.start('nextargs'),
				_get_color_pattern().fullmatch(match['nextargs'] or ""))

		# Strip the expression.

		lexpr = expr.strip()
		column = (len(expr) - len(lexpr))
		expr = lexpr
		del lexpr

		# Match the expression (and check it as a whole directly).

		match = _get_color_pattern().fullmatch(expr)
		if match is None:
			raise _ColorExpressionDecodingError("expression parsing failed")

		# Get the result and check its type.

		results = recurse(column, match)
		if len(results) > 1:
			raise _ColorExpressionDecodingError("extraneous value",
				column = results[1].column)

		result = results[0].value
		try:
			result = ref.colors[result]
		except AttributeError:
			raise _ColorExpressionDecodingError("expected a color",
				column = column)

		return result

# End of file.