aboutsummaryrefslogtreecommitdiff
path: root/thcolor/_ref.py
blob: 8a39cbbcf909416c854070f2db3259e7c999cfd8 (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
#!/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.
#******************************************************************************
""" Named color reference, parent class. """

from inspect import (getfullargspec as _getfullargspec,
	getmembers as _getmembers, ismethod as _ismethod)
from itertools import count as _count
from warnings import warn as _warn

from ._angle import Angle as _Angle
from ._sys import netscape_color as _netscape_color
from ._exc import (NotEnoughArgumentsError as _NotEnoughArgumentsError,
	TooManyArgumentsError as _TooManyArgumentsError,
	InvalidArgumentTypeError as _InvalidArgumentTypeError)

__all__ = ["Reference"]

_default_reference = None
_color_cls = None

def _get_color_class():
	global _color_cls

	if _color_cls is not None:
		return _color_cls

	from ._color import Color
	_color_cls = Color
	return _color_cls

class _type_or:
	""" A type or another. """

	def __init__(self, type1, type2):
		self._type1 = type1
		self._type2 = type2

	@property
	def type1(self):
		return self._type1

	@property
	def type2(self):
		return self._type2

	def __repr__(self):
		return f"{repr(self._type1)} | {repr(self._type2)}"

	def __str__(self):
		return f"{self._type1} or {self._type2}"

	def __or__(self, other):
		return type_or(self, other)

	def __contains__(self, other):
		return other in self._type1 or other in self._type2

# ---
# Main reference definition.
# ---

class Reference:
	""" Function reference for color parsing and operations. """

	def __init__(self):
		pass

	# ---
	# Base type and function definitions for parsing.
	# ---

	class base_type(type):
		""" The metaclass for all types used below. """

		def __new__(mcls, name, bases, attrs):
			return super().__new__(mcls, name, bases, attrs)

		def __init__(self, name, bases, attrs):
			self.__name = name

		def __contains__(self, other):
			return self if other == self else None

		def __or__(self, other):
			return _type_or(self, other)

		def __repr__(self):
			return f"<class {repr(self.__name)}>"

		def __str__(self):
			return self.__name

	class number(metaclass = base_type):
		""" Syntaxical element for expression decoding, representing
			a number, integer or decimal, positive or negative.

			This element is usually used to represent a byte value,
			a factor (usually from 0.0 to 1.0), a color or an angle
			in degrees. """

		def __init__(self, value):
			if   type(value) == str:
				self._strvalue = value
				self._value = float(value)
			else:
				self._value = float(value)
				if self._value == int(self._value):
					self._strvalue = str(int(self._value))
				else:
					self._strvalue = str(value)

		def __str__(self):
			return self._strvalue

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

		def to_byte(self):
			""" Make a byte (from 0 to 255) out of the number. """

			try:
				value = int(self._value)

				assert value == self._value
				assert 0 <= value < 256
			except:
				raise ValueError("unsuitable value for byte conversion: " \
					f"{repr(self._value)}")

			return value

		def to_factor(self, min = 0.0, max = 1.0):
			""" Make a factor (usually from 0.0 to 1.0) out of the number. """

			if (min is not None and self._value < min) \
			or (max is not None and self._value > max):
				if   max is None:
					msg = f"above {min}"
				elif min is None:
					msg = f"under {max}"
				else:
					msg = f"between {min} and {max}"

				raise ValueError(f"expected a value {msg}, got {self._value}")

			try:
				assert 0.0 <= self._value <= 1.0
			except:
				raise ValueError("expected a value between 0.0 and 1.0, got " \
					f"{self._value}")

			return self._value

		def to_hue(self):
			""" Make an angle in degrees out of the number. """

			return _Angle(_Angle.Type.DEG, self._value)

	class percentage(metaclass = base_type):
		""" Syntaxical element for expression decoding, representing
			a percentage (number followed by a '%' sign).

			This element is usually used to represent a factor (usually
			from 0% to 100%) or anything that can be factored such as a
			byte value (where 0% represents 0 and 100% represents 255). """

		def __init__(self, value):
			self._value = value

			if value < 0:
				value = 0

			# value can actually be more than 100.

		def __repr__(self):
			return f"{self._value} %"

		def to_factor(self, min = 0.0, max = 1.0):
			""" Make a factor (usually from 0.0 to 1.0) out of the number. """

			value = self._value / 100
			if (min is not None and value < min) \
			or (max is not None and value > max):
				if   max is None:
					msg = f"above {min * 100}%"
				elif min is None:
					msg = f"under {max * 100}%"
				else:
					msg = f"between {min * 100}% and {max * 100}%"

				raise ValueError(f"expected a percentage {msg}, " \
					f"got {self._value}%")

			return value

		def to_byte(self):
			""" Make a byte (from 0 to 255) out of the number. """

			if  self._value < 0:
				self._value = 0
			if  self._value > 100:
				self._value = 100

			return int(min(self._value / 100, 1.0) * 255)

	class angle(metaclass = base_type):
		""" Syntaxical element for expression decoding, representing
			an angle (a number followed by an angle unit: degrees, gradiants,
			radiants or turns). """

		def __init__(self, value):
			if not isinstance(value, _Angle):
				raise TypeError("expected an Angle instance")

			self._value = value

		def __repr__(self):
			return repr(self._value)

		def to_hue(self):
			""" Get the :class:`thcolor.Angle` object. """

			return self._value

	class color(metaclass = base_type):
		""" Syntaxical element for expression decoding, representing
			a color using several methods:

			- a hexadecimal code preceeded by a '#', e.g. "#123ABC".
			- a natural color (see
			  `NCol <https://www.w3schools.com/colors/colors_ncol.asp>`_).
			- a color name as defined by a :class:`Reference`.
			- a legacy color name using the legacy color algorithm (or
			  'Netscape' color algorithm). """

		def __init__(self, value):
			if not isinstance(value, _get_color_class()):
				raise ValueError("expected a Color instance")

			self._value = value

		def __repr__(self):
			return repr(self._value)

		def to_color(self):
			""" Get the :class:`thcolor.Color` object. """

			return self._value

	# ---
	# Function helper.
	# ---

	def alias(*names):
		""" Decorator for aliasing with another name. Defines a lot, you
			know. """

		def _decorator(func):
			if not hasattr(func, '_ref_aliases'):
				func._ref_aliases = ()

			func._ref_aliases += names
			return func

		return _decorator

	# ---
	# Function and named color getters.
	# ---

	def _get_functions(self):
		""" Function getter, which can be used as ``.functions[name](args…)``.

			Provides a wrapper to the method which checks the argument
			types and perform the necessary conversions before passing
			them to the functions.

			For example, with a classical CSS reference named ``ref``:

			>>> ref.functions['rgb'](ref.number(18), ref.number(52), """ \
				"""ref.number(86))
			... Color(type = Color.Type.RGB, red = 18, green = 52, """ \
				"""blue = 86, alpha = 1.0) """

		class _FunctionGetter:
			def __init__(self, ref):
				self._fref = ref

			def __getitem__(self, name):
				fref = self._fref
				found = False

				# First, check if the function name is valid and if the
				# method exists.

				members = dict(_getmembers(fref, predicate = _ismethod))
				validname = lambda n: type(n) == str and n[0:1] != '_' \
					and n not in ('functions', 'named', 'default', 'alias')

				if validname(name):
					try:
						method = members[name]
						found = True
					except (KeyError, AssertionError):
						pass

				# Then, if we haven't found the method, check the aliases.

				if not found:
					for member in members.values():
						try:
							aliases = member._ref_aliases
						except (AttributeError, AssertionError):
							continue

						if name not in aliases:
							continue
						method = member
						found = True
						break

				# If we still haven't found the method, well… time to raise
				# the not found exception.

				if not found:
					raise KeyError(repr(name))

				# Make a function separated from the class, copy the
				# annotations and add the type check on each argument.

				class _MethodCaller:
					def __init__(self, fref, name, func):
						self._fref = fref
						self._name = name
						self._func = func

						self.__annotations__ = func.__annotations__
						try:
							del self.__annotations__['self']
						except:
							pass

						spec = _getfullargspec(func)

						def annotate(arg_name):
							try:
								return spec.annotations[arg_name]
							except:
								return None

						self._args = list(map(annotate, spec.args[1:]))
						self._optargs = []
						if spec.defaults:
							self._optargs = self._args[-len(spec.defaults):]
							self._args = self._args[:-len(self._optargs)]

					def __call__(self, *args):
						if len(args) < len(self._args):
							raise _NotEnoughArgumentsError(len(self._args),
								self._name)
						if len(args) > len(self._args) + len(self._optargs):
							raise _TooManyArgumentsError(len(self._args),
								self._name)

						arg_types = self._args \
							+ self._optargs[:len(args) - len(self._args)]
						arg_source = args
						args = []

						lit = zip(_count(), arg_source, arg_types)
						for index, arg, exp in lit:
							args.append(arg)
							if exp is None:
								continue
							if type(arg) in exp:
								continue

							# If we haven't got a color but a color is one
							# of the accepted types, try to transform into
							# a color to manage number colors using the
							# Netscape transformation such as '123'.

							if Reference.color in exp:
								try:
									args[-1] = self._fref.colors[arg]
								except:
									pass
								else:
									continue

							raise _InvalidArgumentTypeError(index,
								exp, type(arg), self._name)

						return self._func(*args)

				return _MethodCaller(self, name, method)

		return _FunctionGetter(self)

	def _get_colors(self):
		""" Colors getter, which can be used as ``.colors[value]``.
			For example, with a classical CSS reference named ``ref``:

				>>> ref.colors['blue']
				... Color(type = Color.Type.RGB, red = 0, green = 0, """ \
					"""blue = 255, alpha = 1.0)
				>>> ref.colors[thcolor.Reference.color(""" \
					"""thcolor.Color.from_text('#123456'))]
				... Color(type = Color.Type.RGB, red = 18, green = 52, """ \
					"""blue = 86, alpha = 1.0) """

		class _ColorGetter:
			def __init__(self, ref):
				self._cref = ref

			def __getitem__(self, key):
				try:
					return key.to_color()
				except AttributeError:
					pass

				try:
					name = str(key)
				except:
					raise KeyError(repr(key))

				try:
					value = self._cref._color(name)
				except KeyError:
					pass
				except Exception as e:
					_warn(RuntimeWarning, f"{self.__class__.__name__} " \
						f"returned exception {e.__class__.__name__} instead " \
						f"of KeyError for color name {repr(name)}.")
					pass
				else:
					try:
						assert isinstance(value, _get_color_class())
					except AssertionError:
						_warn(RuntimeWarning, f"{self.__class__.__name__} " \
							f"returned non-Color value {repr(value)} for " \
							f"color name {repr(name)}, ignoring.")
					else:
						return value

				try:
					r, g, b = _netscape_color(name)
				except:
					pass
				else:
					Color = _get_color_class()
					return Color(Color.Type.RGB, r, g, b)

				raise KeyError(repr(key))

		return _ColorGetter(self)

	functions = property(_get_functions)
	colors = property(_get_colors)

	# ---
	# Default methods.
	# ---

	def _color(self, name):
		""" Name color getter used behind the
			:attr:`thcolor.Reference.colors` getter, ought to be overriden
			by superseeding classes.

			These classes should return ``super()._color(name)`` in case
			they have no match for the given name. """

		raise KeyError(f'{name}: no such color')

	def default():
		""" Static method for gathering the default reference, by
			default :class:`thcolor.DefaultReference`. Is only used on
			the base :class:`thcolor.Reference` type and shall not be
			overriden. """

		global _default_reference

		if _default_reference is not None:
			return _default_reference

		from .builtin import DefaultReference
		_default_reference = DefaultReference()
		return _default_reference

# End of file.