forked from Alexhuszagh/BreezeStyleSheets
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.py
74 lines (62 loc) · 2.29 KB
/
helpers.py
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
import json
from pathlib import Path
HCT_THEME_COLOR: str = "b55162"
DARK_THEME_COLOR: str = "3daee9"
LIGHT_THEME_COLOR: str = "3daef3"
# Source: https://github.com/Alexhuszagh/BreezeStyleSheets/blob/main/configure.py#L82
def load_json_ignore_comments(path: Path) -> dict:
"""Load config.json file, ignoring comments //.
Source: https://github.com/Alexhuszagh/BreezeStyleSheets/blob/main/configure.py#L82
"""
with open(path) as f:
lines = f.read().splitlines()
lines = [i for i in lines if not i.strip().startswith("//")]
return json.loads("\n".join(lines))
def parse_color_field(color: str) -> str:
"""Parse color field in the format #rrggbb or rgba(r, g, b, a) to the format rrggbb.
:param color: #rrggbb (hexits) or rgba(r, g, b, a) (decimal)
:type color: str
:return: rrggbb
:rtype: str"""
if len(color) == 7:
return color[1:]
else:
color = color.replace("rgba(", "").replace(")", "")
channels: list[str] = color.split(",")
r, g, b = int(channels[0]), int(channels[1]), int(channels[2])
r, g, b = hex(r)[2:].zfill(2), hex(g)[2:].zfill(2), hex(b)[2:].zfill(2)
return r + g + b
def hex_color_times_ratio(hex_color: str, ratio: float) -> str:
"""Given 6-hexit color code rrggbb, multiply by ratio
and output a 6-hexit color code rrggbb.
:param hex_color: rrggbb
:type hex_color: str
:param ratio: 0.0 <= ratio <= 1.0
:type ratio: float
:return: hex_color * ratio
:rtype: str"""
if len(hex_color) != 6:
raise Exception("rrggbb hex_color")
if ratio < 0 or ratio > 1:
raise Exception("0 <= ratio <= 1, you inputted outside this range")
channels = bytes.fromhex(hex_color)
rv = str(
hex(
int(channels[0] * ratio) << 16
| int(channels[1] * ratio) << 8
| int(channels[2] * ratio)
)
)[2:]
if len(rv) < 6:
rv = "0" * (6 - len(rv)) + rv
return rv
def hex_color_to_dec(hex_color: str) -> tuple[int, int, int]:
"""
:param hex_color:
:type hex_color: str
:return: (r, g, b) in dec
:rtype: tuple[int, int, int]"""
if len(hex_color) != 6:
raise Exception("rrggbb hex_color")
channels = bytes.fromhex(hex_color)
return (channels[0], channels[1], channels[2])