1
|
|
|
"""This module is about converting from/to Rainmeter RGB(A).""" |
2
|
|
|
|
3
|
|
|
class LetterCase(object): # pylint: disable=R0903; used as enum, but we only have Py3.3 |
4
|
|
|
""" |
5
|
|
|
Represent how a hex value should be displayed. |
6
|
|
|
|
7
|
|
|
Depending on the incoming String |
8
|
|
|
we need to convert it to upper case or lower case. |
9
|
|
|
""" |
10
|
|
|
|
11
|
|
|
Upper, Lower = range(1, 3) |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
def hex_to_int(hex_value): |
15
|
|
|
"""Convert single hex value into a dec value.""" |
16
|
|
|
int_value = int(hex_value, 16) |
17
|
|
|
|
18
|
|
|
assert 0 <= int_value <= 255 |
19
|
|
|
|
20
|
|
|
return int_value |
21
|
|
|
|
22
|
|
|
def hexes_to_rgbs(hexes): |
23
|
|
|
"""Convert a list of hex values into a list of dec values.""" |
24
|
|
|
assert 3 <= len(hexes) <= 4 |
25
|
|
|
|
26
|
|
|
return [hex_to_int(hex_value) for hex_value in hexes] |
27
|
|
|
|
28
|
|
|
def hexes_to_string(hexes): |
29
|
|
|
"""Convert hexes into a string representation.""" |
30
|
|
|
return "".join(hexes) |
31
|
|
|
|
32
|
|
|
def convert_hex_str_to_rgba_str(hex_string, has_alpha): |
33
|
|
|
"""Provided 'FFFFFFFF' it should return 255, 255, 255, 255.""" |
34
|
|
|
hexes = [hex_string[i:i+2] for i in range(0, len(hex_string), 2)] |
35
|
|
|
rgba = hexes_to_rgbs(hexes) |
36
|
|
|
alpha = rgba[-1] |
37
|
|
|
if alpha is 255 and not has_alpha: |
38
|
|
|
rgba = rgba[:-1] |
39
|
|
|
rgba_str = rgbs_to_string(rgba) |
40
|
|
|
|
41
|
|
|
return rgba_str |
42
|
|
|
|
43
|
|
|
def convert_hex_to_hex_with_alpha(hexes): |
44
|
|
|
"""If no alpha value is provided it defaults to FF.""" |
45
|
|
|
if len(hexes) == 6: |
46
|
|
|
if hexes.islower(): |
47
|
|
|
return hexes + "ff" |
48
|
|
|
else: |
49
|
|
|
# we default to upper case if user chose upper and lower |
50
|
|
|
return hexes + "FF" |
51
|
|
|
else: |
52
|
|
|
return hexes |
53
|
|
|
|
54
|
|
|
def int_to_hex(int_value, letter_case=LetterCase.Upper): |
55
|
|
|
"""Convert single int value in a specific letter case to hex value.""" |
56
|
|
|
assert 0 <= int_value <= 255 |
57
|
|
|
|
58
|
|
|
# returns lower case hex values |
59
|
|
|
hex_value = hex(int_value) |
60
|
|
|
without_prefix = hex_value[2:] |
61
|
|
|
padded = without_prefix.zfill(2) |
62
|
|
|
|
63
|
|
|
if letter_case == LetterCase.Upper: |
64
|
|
|
padded = padded.upper() |
65
|
|
|
|
66
|
|
|
return padded |
67
|
|
|
|
68
|
|
|
def rgbs_to_hexes(rgbs): |
69
|
|
|
"""Convert a list of dec values into a list of hex values.""" |
70
|
|
|
assert 3 <= len(rgbs) <= 4 |
71
|
|
|
|
72
|
|
|
return [int_to_hex(rgb) for rgb in rgbs] |
73
|
|
|
|
74
|
|
|
def rgbs_to_string(rgbs, spacing=0): |
75
|
|
|
"""Convert RGBs into a string representation.""" |
76
|
|
|
joiner = ",".ljust(spacing + 1) |
77
|
|
|
|
78
|
|
|
# you cant join ints |
79
|
|
|
return joiner.join(str(x) for x in rgbs) |
80
|
|
|
|