-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbase16_shell_preview.py
executable file
·296 lines (237 loc) · 7.33 KB
/
base16_shell_preview.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
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
#!/usr/bin/env python3
import argparse
import curses
import functools
import os
import pathlib
import signal
import subprocess
import sys
__version__ = '1.0.0'
THEME_PATH = pathlib.Path('~/.base16_theme').expanduser()
SHELL = '/bin/sh'
NUM_COLORS = 22
class Theme:
def __init__(self, path):
self.path = pathlib.Path(path)
self.name = self.path.stem
prefix = 'base16-'
if self.name.startswith(prefix):
self.name = self.name[len(prefix):]
def apply(self):
subprocess.run([SHELL, self.path], check=True)
def install(self):
try:
THEME_PATH.unlink()
except FileNotFoundError:
pass
THEME_PATH.symlink_to(self.path)
hooks_dir = os.environ.get('BASE16_SHELL_HOOKS')
if hooks_dir is not None:
env = os.environ.copy()
env['BASE16_THEME'] = self.name
for path in pathlib.Path(hooks_dir).iterdir():
if path.is_file():
subprocess.run(
[path],
env=env,
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
check=True
)
@property
@functools.lru_cache()
def bg_color(self):
background_line = [
line
for line in self.path.read_text().split('\n')
if line.startswith('color00')
][0]
background_str = background_line.split('"')[1].replace('/', '')
return hex(int(background_str, 16))
class ScrollListWindow:
def __init__(self, data, lines, left_cols, right_cols):
self.data = data
self.lines = lines
self.left_cols = left_cols
self.right_cols = right_cols
self.offset = 0
self.selected = 0
self.left_window = curses.newwin(lines, left_cols)
self.right_window = curses.newwin(lines, right_cols, 0, self.left_cols)
def up(self):
self.index -= 1
self.render()
@property
def index(self):
return self.offset + self.selected
@index.setter
def index(self, index):
if index < 0:
index = 0
elif index >= len(self.data):
index = len(self.data) - 1
if index < (self.index):
diff = self.index - index
available = self.selected
self.selected -= min(diff, available)
elif index > (self.index):
diff = index - self.index
available = self.lines - 1 - self.selected
self.selected += min(diff, available)
self.offset = index - self.selected
def down(self):
self.index += 1
self.render()
def up_page(self):
self.selected = 0
self.index -= self.lines
self.render()
def down_page(self):
self.selected = self.lines - 1
self.index += self.lines
self.render()
def top(self):
self.index = 0
self.render()
def bottom(self):
self.index = len(self.data) - 1
self.render()
def render(self):
self._render_left()
self._render_right()
self.left_window.refresh()
self.right_window.refresh()
def _render_left(self):
end = self.offset + self.lines
line = 0
for i, value in enumerate(self.data):
if i < self.offset:
continue
elif i == end:
break
if line == self.selected:
self.value = value
attrs = curses.A_REVERSE
else:
attrs = 0
self.left_window.addstr(
line, 0, (self.left_cols - 1) * ' ', attrs)
self.left_window.addstr(
line, 0, self.format_left(value)[:self.left_cols-1],
attrs)
line += 1
def _render_right(self):
for i in range(self.lines):
curses.init_pair(i, i, -1)
text = f'color{i:02d} '
spaces = self.right_cols - len(text) - 1
self.right_window.addstr(i, len(text), spaces*' ',
curses.color_pair(i) + curses.A_REVERSE)
self.right_window.addstr(i, 0, text, curses.color_pair(i))
class ThemePreviewer(ScrollListWindow):
@staticmethod
def format_left(theme):
return theme.name
@staticmethod
def format_right(theme):
pass
def render(self):
super().render()
self.value.apply()
def run_curses_app(stdscr, scripts_dir, sort_bg):
stdscr.refresh()
stdscr.keypad(True)
curses.start_color()
curses.use_default_colors()
curses.curs_set(0)
curses.noecho()
sort_key = 'bg_color' if sort_bg else 'name'
sorted_themes = sorted(
[Theme(path)
for path in scripts_dir.iterdir()
if path.is_file()],
key=lambda x: (getattr(x, sort_key), x.name)
)
scroll_list_cols = 35
preview_cols = 42
total_cols = scroll_list_cols + preview_cols
win = ThemePreviewer(
sorted_themes,
NUM_COLORS,
scroll_list_cols,
preview_cols,
)
win.render()
movement_map = {
curses.KEY_DOWN: win.down,
curses.KEY_UP: win.up,
curses.KEY_PPAGE: win.up_page,
curses.KEY_NPAGE: win.down_page,
curses.KEY_HOME: win.top,
curses.KEY_END: win.bottom,
}
while True:
win.render()
c = stdscr.getch()
if c in movement_map:
movement_map[c]()
elif c == ord('q'):
end_run()
return
elif c == ord('\n'):
win.value.install()
end_run()
return
elif c == curses.KEY_RESIZE:
if curses.LINES < win.lines:
raise ValueError('Terminal has less than 22 lines.')
elif curses.COLS < total_cols:
raise ValueError(f'Terminal has less than {total_cols} cols.')
def end_run(*_):
curses.endwin()
if THEME_PATH.exists():
Theme(THEME_PATH).apply()
def _exit_signal_handler(*_):
end_run()
sys.exit()
def main():
parser = argparse.ArgumentParser(
'base16-shell-preview',
formatter_class=argparse.RawTextHelpFormatter,
description="""
keys:
up/down move 1
pgup/pgdown move page
home/end go to beginning/end
q quit
enter enable theme and quit
""")
parser.add_argument(
'--version',
action='version',
version=__version__
)
parser.add_argument(
'--sort-bg',
action='store_true',
help='sort themes by background (darkest to lightest)'
)
args = parser.parse_args()
for signalnum in [signal.SIGINT, signal.SIGTERM]:
signal.signal(signalnum, _exit_signal_handler)
base16_shell_dir = os.environ.get('BASE16_SHELL')
if base16_shell_dir is not None:
base16_shell_dir = pathlib.Path(base16_shell_dir)
else:
if THEME_PATH.is_symlink():
base16_shell_dir = THEME_PATH.resolve().parent.parent
else:
parser.error(
'please set the BASE16_SHELL environment variable '
'to the local repository path.'
)
curses.wrapper(
run_curses_app, base16_shell_dir.joinpath('scripts'), args.sort_bg)
if __name__ == '__main__':
main()