-
Notifications
You must be signed in to change notification settings - Fork 0
/
i3_workspace_names.py
executable file
·353 lines (276 loc) · 10.9 KB
/
i3_workspace_names.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
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
#!/usr/bin/env python3
import i3ipc
import re
import json
import os
from xdg.BaseDirectory import xdg_config_home, xdg_cache_home, xdg_data_home
import argparse
from shutil import copyfile, copy, move
import requests
import subprocess
import traceback
PACKAGE_NAME = "i3-workspace-names"
class Settings:
CONFIG_DIR = xdg_config_home + "/" + PACKAGE_NAME
CONFIG_FILE = CONFIG_DIR + "/config.json"
def __init__(self, args):
self.config = args.config if args.config else Settings.CONFIG_FILE
self.apps = None
self.icons = None
self.strings = None
self.args = args
def hasConfig(self):
return os.path.isfile(self.config)
def load(self):
try:
with open(self.config) as j:
settings = json.load(j)
self.apps = settings['apps']
self.icons = settings['icon_replace']
self.strings = settings['string_replace']
except IOError:
traceback.print_exc()
exit(f"Failed to read config file from {self.config}")
def copy(self):
try:
dirname = os.path.dirname(self.config)
if not os.path.isdir(dirname):
os.makedirs(dirname)
copyfile("config.example.json", self.config)
print(f"Example config copied to {self.config}")
except Exception:
traceback.print_exc()
exit(f"Failed to create default config in {self.config}")
def get_application(self, name):
if name in self.apps:
return self.apps[name]
return None
class FontBuilder:
SOURCE_DIR = "/icons"
FONT_NAME = (PACKAGE_NAME + "-font").replace("-", "_")
FONT_DIR = xdg_data_home + "/fonts/"
COMMAND_FORMAT = "icon-font-generator {source}/*.svg --types ttf --css false --html false --name {font_name}" + \
" --out {target} --normalize true --center"
def __init__(self, cache, args):
self.cache = cache
self.args = args
self.target = cache.directory
self.source = args.build_source if args.build_source \
else Settings.CONFIG_DIR + FontBuilder.SOURCE_DIR
def build(self):
try:
command = FontBuilder.COMMAND_FORMAT.format(
font_name=FontBuilder.FONT_NAME,
target=self.target,
source=self.source
).split(" ")
result = subprocess.run(
command,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
print(result.stdout)
self.convert_json()
except subprocess.CalledProcessError:
traceback.print_exc()
exit(f"Failed to build font with command {command}")
def convert_json(self):
try:
json_file = self.target + "/" + FontBuilder.FONT_NAME + ".json"
data = None
with open(json_file, "r") as f:
data = json.load(f)
for icon in data:
data[icon] = chr(int(data[icon][1:], 16))
with open(json_file, "w") as f:
json.dump(data, f)
print("Successfully converted custom cache file")
except IOError:
traceback.print_exc()
exit(f"Failed to convert custom font json cache file")
def get_build_names(self):
file_types = ['json', 'ttf']
files = [FontBuilder.FONT_NAME + "." + ft for ft in file_types]
return files
def build_exists(self):
files = self.get_build_names()
for f in files:
if not os.path.isfile(self.target + "/" + f):
return False
return True
def clean(self):
names = self.get_build_names()
build_absolute = [self.target + "/" + b for b in names]
build_absolute.append(FontBuilder.FONT_DIR + "/" +
FontBuilder.FONT_NAME + ".ttf")
build_absolute.append(self.cache.directory + Cache.CUSTOM_CACHE)
try:
for build in build_absolute:
if os.path.isfile(build):
print(f"Removing {build}")
os.remove(build)
print("Finished build cleaning")
except IOError:
traceback.print_exc()
exit("Failed to clean build files")
def install(self):
try:
self.clean()
self.build()
if not os.path.isdir(FontBuilder.FONT_DIR):
os.makedirs(FontBuilder.FONT_DIR)
move(
self.target + "/" + FontBuilder.FONT_NAME + ".ttf",
FontBuilder.FONT_DIR
)
move(
self.target + "/" + FontBuilder.FONT_NAME + ".json",
self.cache.directory + Cache.CUSTOM_CACHE
)
print("Installed icon font for local user")
except IOError:
traceback.print_exc()
exit(f"Failed to install font to {FontBuilder.FONT_DIR}")
class Cache:
CACHE_DIR = xdg_cache_home + "/" + PACKAGE_NAME
ICON_CACHE = "/fa.json"
CUSTOM_CACHE = "/custom.json"
FONT_AWESOME_URL = 'https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/metadata/icons.json'
def __init__(self, cache_path):
self.directory = cache_path if cache_path else Cache.CACHE_DIR
self.icons = None
self.init_directory()
def init_directory(self):
try:
if not os.path.isdir(self.directory):
os.makedirs(self.directory)
except IOError:
traceback.print_exc()
exit(f"Failed to initialise cache directory at {self.directory}")
def refresh_icons(self, icon_path=None):
if icon_path is None:
icon_path = self.directory + Cache.ICON_CACHE
try:
r = requests.get(Cache.FONT_AWESOME_URL)
j = json.loads(r.text)
icons = {}
for i in j:
icons[i] = chr(int(j[i]['unicode'], 16))
with open(icon_path, 'w') as f:
json.dump(icons, f)
print(
f"Updated Font Awesome icon cache")
except requests.exceptions.RequestException:
traceback.print_exc()
exit(f"Failed to retrieve icons from {Cache.FONT_AWESOME_URL}")
except IOError:
traceback.print_exc()
exit(f"Failed to save icon cache to disk at {icon_path}")
def load_fa(self, icon_path):
if icon_path is None:
icon_path = self.directory + Cache.ICON_CACHE
if not os.path.isfile(icon_path):
self.refresh_icons(icon_path)
try:
with open(icon_path, "r") as f:
self.icons = json.load(f)
print("Loaded icons from disk")
except IOError:
traceback.print_exc()
exit(f"Failed to load icon cache file from {icon_path}")
def load_custom(self):
custom_path = self.directory + Cache.CUSTOM_CACHE
if os.path.isfile(custom_path):
try:
with open(custom_path, "r") as f:
self.custom = json.load(f)
print("Loaded custom icons from disk")
except IOError:
traceback.print_exc()
exit(f"Failed to load custom icon cache for {custom_path}")
class WorkspaceRenamer:
def __init__(self, cache, settings):
self.cache = cache
self.settings = settings
self.i3 = i3ipc.Connection()
# Subscribe to events
self.i3.on("window::move", self.rename)
self.i3.on("window::new", self.rename)
self.i3.on("window::title", self.rename)
self.i3.on("window::close", self.rename)
def run(self):
print("Started workspace renamer")
self.i3.main()
self.rename(self.i3, None) # Force an initial refresh
def replace(self, string):
for key, val in self.settings.icons.items():
pattern = re.compile(re.escape(key), re.IGNORECASE)
string = pattern.sub(self.cache.icons[val], string)
for i in string.split():
if i.lower() in self.cache.icons:
string = string.replace(i, self.cache.icons[i.lower()])
for key, val in self.settings.strings.items():
string = string.replace(key, val)
return string[:15]
def rename(self, i3, e):
for workspace in i3.get_tree().workspaces():
title = ""
for window in workspace.leaves():
if window.window_class in self.settings.apps:
icon_name = self.settings.apps[window.window_class]
if icon_name in self.cache.custom:
icon = self.cache.custom[icon_name]
elif icon_name in self.cache.icons:
icon = self.cache.icons[icon_name]
else:
icon = "N/A"
else:
icon = window.window_class + ' '
if self.settings.args.show_titles:
title += icon + ' ' + self.replace(window.name) + ' '
else:
title += icon + ' '
new_name = f"{workspace.num}"
if title:
new_name += f": {title}"
i3.command(f'rename workspace "{workspace.name}" to "{new_name}"')
def parse_arguments():
parser = argparse.ArgumentParser(
description='Dynamically change i3wm workspace names depending on windows')
parser.add_argument("-c", "--config",
help="Use a custom config file")
parser.add_argument("-x", "--cache",
help="Cache directory for icons")
parser.add_argument("-i", "--icons",
help="Use a custom icon cache file")
parser.add_argument("-u", "--update-icons",
help="Update icon list from FontAwesome", action="store_true")
parser.add_argument("-s", "--show-titles",
help="Hide window titles from workspace names", action="store_true")
parser.add_argument("-b", "--build-font",
help="Build icon font from SVGs", action="store_true")
parser.add_argument("--build-source",
help="Source directory with SVGs for font builder")
args = parser.parse_args()
return args
def main():
args = parse_arguments()
cache = Cache(args.cache)
settings = Settings(args)
builder = FontBuilder(cache, args)
if not settings.hasConfig():
settings.copy()
if args.update_icons:
cache.refresh_icons(args.icons)
elif args.build_font:
builder.install()
else:
cache.load_fa(args.icons)
cache.load_custom()
settings.load()
renamer = WorkspaceRenamer(cache, settings)
renamer.run()
if __name__ == "__main__":
main()