Repository navigation
Expand file tree
/
Copy pathexecutable_pywal-readable
More file actions
227 lines (202 loc) · 10.2 KB
/
Copy pathexecutable_pywal-readable
File metadata and controls
227 lines (202 loc) · 10.2 KB
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
#!/usr/bin/env python3
"""Run pywal with readable dark-terminal text before sequences and exports."""
import copy
import colorsys
import math
import hashlib
import shutil
import subprocess
import tempfile
import os
from pathlib import Path
import runpy
import re
import sys
# Reuse the repo's existing sRGB contrast math, also installed beside this script.
_here = Path(__file__).resolve().parent
_math = runpy.run_path(str(_here / ('executable_generate-i3-pywal-colors'
if (_here / 'executable_generate-i3-pywal-colors').exists()
else 'generate-i3-pywal-colors')))
contrast_ratio = _math['contrast_ratio']
mix = _math['mix']
hex_to_rgb = _math['hex_to_rgb']
relative_luminance = _math['relative_luminance']
def oklab(color: str) -> tuple:
"""Public-domain linear-sRGB transform: bottosson.github.io/posts/oklab/."""
rgb = [channel / 255 for channel in hex_to_rgb(color)]
r, g, b = [c / 12.92 if c <= .04045 else ((c + .055) / 1.055) ** 2.4 for c in rgb]
l = (.4122214708*r + .5363325363*g + .0514459929*b) ** (1/3)
m = (.2119034982*r + .6806995451*g + .1073969566*b) ** (1/3)
s = (.0883024619*r + .2817188376*g + .6299787005*b) ** (1/3)
return (.2104542553*l + .7936177850*m - .0040720468*s,
1.9779984951*l - 2.4285922050*m + .4505937099*s,
.0259040371*l + .7827717662*m - .8086757660*s)
def muted_color(lightness: float, chroma: float, hue: float) -> str:
"""OKLCH to sRGB; reduce chroma for gamut rather than clipping channels."""
for step in range(101):
c = chroma * (1 - step / 100)
a, b = c * math.cos(math.radians(hue)), c * math.sin(math.radians(hue))
l = (lightness + .3963377774*a + .2158037573*b)**3
m = (lightness - .1055613458*a - .0638541728*b)**3
s = (lightness - .0894841775*a - 1.291485548*b)**3
linear = (4.0767416621*l - 3.3077115913*m + .2309699292*s,
-1.2684380046*l + 2.6097574011*m - .3413193965*s,
-.0041960863*l - .7034186147*m + 1.707614701*s)
if all(0 <= value <= 1 for value in linear):
rgb = [12.92*v if v <= .0031308 else 1.055*v**(1/2.4)-.055 for v in linear]
return '#' + ''.join(f'{round(v*255):02X}' for v in rgb)
raise ValueError('Cannot map muted color into sRGB')
def comfortable_colors(bound: str, background: str) -> list:
"""Stable ANSI semantics with a restrained wallpaper hue influence."""
hue = colorsys.rgb_to_hls(*(c/255 for c in hex_to_rgb(background)))[0]
offset = 8 * math.sin(2 * math.pi * hue)
colors = []
for bright in (False, True):
for semantic_hue in (25, 140, 85, 255, 310, 200):
for step in range(101):
light = .75 + step*.001
normal = muted_color(light, .085, semantic_hue + offset)
if contrast_ratio(normal, bound) >= 4.55:
colors.append(muted_color(light + (.035 if bright else 0), .085, semantic_hue + offset))
break
else:
raise ValueError('Background leaves insufficient room for muted accents')
return colors
def repair_palette(palette: dict) -> None:
"""Validate first, then brighten text against 90%-opaque sRGB backgrounds."""
fixed = copy.deepcopy(palette)
for color in [*fixed['colors'].values(), fixed['special']['foreground'], fixed['special']['cursor']]:
hex_to_rgb(color)
background = fixed['special']['background']
hex_to_rgb(background)
bound = mix(background, '#ffffff', .1)
if contrast_ratio('#ffffff', bound) < 10:
# Only normalize unsupported backgrounds; retain room for colored text.
for step in range(1, 256):
candidate = mix(background, '#000000', step / 255)
candidate_bound = mix(candidate, '#ffffff', .1)
if contrast_ratio('#ffffff', candidate_bound) >= 10:
fixed['special']['background'] = candidate
bound = candidate_bound
break
fixed['special'].update(foreground='#D8DADF', cursor='#D8DADF')
for index, neutral in ((0, '#96989D'), (7, '#D8DADF'), (8, '#A4A6AB'), (15, '#E0E2E7')):
fixed['colors'][f'color{index}'] = neutral
slots = [(fixed['colors'], f'color{i}') for i in range(16)]
slots += [(fixed['special'], key) for key in ('foreground', 'cursor')]
for group, key in slots:
original = group[key]
hex_to_rgb(original)
target = 7 if key in ('foreground', 'cursor', 'color7') else 4.5
if relative_luminance(original) > relative_luminance(bound) and contrast_ratio(original, bound) >= target:
continue
# Mixing with white retains hue, reducing saturation only as needed.
for step in range(1, 256):
candidate = mix(original, '#ffffff', step / 255)
if relative_luminance(candidate) > relative_luminance(bound) and contrast_ratio(candidate, bound) >= target:
group[key] = candidate
break
accents = comfortable_colors(bound, fixed['special']['background'])
for key, color in zip([f'color{i}' for i in (*range(1, 7), *range(9, 15))], accents):
fixed['colors'][key] = color
palette.update(fixed)
def render_template(colors: dict, input_file: str, output_file: str | None = None) -> None:
"""Keep known upstream background roles separate from ANSI black text."""
from pywal import util
text = ''.join(util.read_file_raw(input_file))
name = Path(input_file).name
if name in ('colors-wal-dmenu.h', 'colors-wal-dwm.h', 'colors-wal-tabbed.h'):
text = text.replace('{color0}', '{background}')
elif name == 'colors-oomox':
for key in ('BG', 'MENU_BG', 'TXT_BG'):
text = text.replace(f'{key}={{color0.strip}}', f'{key}={{background.strip}}')
elif name == 'colors-wal-st.h':
text = text.replace('defaultbg = 0;', 'defaultbg = 256;')
util.save_file(text.format(**colors), output_file)
def sparse_colors(image: str, generate, backend) -> list:
"""Handle valid images with fewer than 16 colors without inventing hues."""
command = backend.has_im()
raw = backend.imagemagick(16, image, command)
if len(raw) <= 16:
complete = backend.imagemagick(256, image, command)
colors = [re.search(rb'#[0-9A-Fa-f]{6}', row).group().decode() for row in complete[1:]]
if 0 < len(colors) < 16:
return (colors * 16)[:16]
try:
return generate(image)
except SystemExit as exc:
if exc.code != 1 or not colors:
raise
return [colors[index*(len(colors)-1)//15] for index in range(16)]
return generate(image)
def decode_xcf(image: str) -> str:
"""Render an unsupported XCF with GIMP, preserving the source and profile."""
from pywal.settings import CACHE_DIR
gimp = shutil.which('gimp-console') or shutil.which('gimp')
if not gimp:
raise ValueError('This XCF requires GIMP; install GIMP or export its visible image to PNG')
source = Path(image)
digest = hashlib.sha256(source.read_bytes()).hexdigest()
output = Path(CACHE_DIR)/'decoded'/(digest+'.png')
if output.is_file():
return str(output)
output.parent.mkdir(parents=True, exist_ok=True)
def scheme_string(value):
return '"' + str(value).replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\r', '\\r') + '"'
with tempfile.TemporaryDirectory(prefix='pywal-gimp-') as temporary:
work = Path(temporary)
rendered = work/'visible.png'
src, dst = scheme_string(source), scheme_string(rendered)
script = (f'(let* ((image (car (gimp-file-load RUN-NONINTERACTIVE {src} {src}))) '
'(merged (car (gimp-image-merge-visible-layers image CLIP-TO-IMAGE)))) '
f'(file-png-save RUN-NONINTERACTIVE image merged {dst} {dst} 0 9 0 0 0 0 0)) (gimp-quit 0)')
env = {**os.environ, 'HOME': temporary, 'XDG_CONFIG_HOME': str(work/'config'),
'XDG_CACHE_HOME': str(work/'cache'), 'XDG_DATA_HOME': str(work/'data'),
'GIMP2_DIRECTORY': str(work/'gimp')}
result = subprocess.run([gimp, '-n', '-i', '--no-data', '--no-fonts',
'--batch-interpreter=plug-in-script-fu-eval', '-b', script],
env=env, capture_output=True, text=True, timeout=120)
if result.returncode or not rendered.is_file():
print(result.stdout + result.stderr, file=sys.stderr)
raise ValueError(f'GIMP could not render XCF: {source}')
with tempfile.NamedTemporaryFile(dir=output.parent, suffix='.png', delete=False) as staged:
staged_path = Path(staged.name)
try:
shutil.copyfile(rendered, staged_path)
staged_path.replace(output)
finally:
staged_path.unlink(missing_ok=True)
return str(output)
def main() -> int:
from pywal import __main__ as wal, export, sequences, colors
from pywal.backends import wal as backend
# pywal has no pre-export hook. Its CLI always sends sequences before export,
# even with -s; repair this shared boundary for image/cache/theme/-R paths.
send = sequences.send
get_colors = colors.get
def compatible_colors(image, *args, **kwargs):
try:
return get_colors(image, *args, **kwargs)
except subprocess.CalledProcessError:
if Path(image).suffix.lower() != '.xcf':
raise
return get_colors(decode_xcf(image), *args, **kwargs)
colors.get = compatible_colors
generate = backend.gen_colors
backend.gen_colors = lambda image: sparse_colors(image, generate, backend)
def send_readable(palette, *args, **kwargs):
repair_palette(palette)
return send(palette, *args, **kwargs)
sequences.send = send_readable
export.template = render_template
# Deprecated -r otherwise replays unchecked sequences before parse_args.
sys.argv[1:] = ['-R' if arg == '-r' else arg for arg in sys.argv[1:]]
try:
wal.main()
except (KeyError, ValueError) as exc:
icon = '' if os.environ.get('CLI_PLAIN') == '1' else '❌ '
print(f'{icon}Cannot apply readable pywal theme: {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())