-
Notifications
You must be signed in to change notification settings - Fork 0
/
dwmparser.py
538 lines (495 loc) · 23.4 KB
/
dwmparser.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python
from __future__ import print_function
import sys
import utils as u
import os
import subprocess
from dwmparams import *
import tabulate
from phyOS_simple_term_menu import TerminalMenu
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast
class c(int):
APPEARANCE = 0
BUTTONS = 1
KEYS = 2
RULES = 3
class DwmParse:
def __init__(self):
self.cparser = c_parser.CParser()
self.data_dir = u.set_dwm_data_dir()
self.cache_dir = u.set_dwm_cache_dir()
self.ast = ["", "", "", ""]
self.tabular_appearance = []
self.tabular_buttons = []
self.tabular_keys = []
self.tabular_rules = []
def build_dwm(self):
self.get_files("/appearance", "/keys", "/buttons", "/rules")
self.update()
self.save_config()
os.chdir(self.data_dir)
os.system("gcc -c dwm-conf.c -fPIC")
os.system("gcc -shared dwm-conf.o -o libdwm-conf.so")
os.system("pOS-powermenu restart")
def delete_attr(self, attr):
if attr == self.tabular_appearance:
t1 = tabulate.tabulate([[i] for i in attr[-1]], tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
attr[-1].pop(idx)
self.write_tmp_files()
else:
t1 = tabulate.tabulate(attr, tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
attr.pop(idx)
self.write_tmp_files()
def get_files(self, *args):
for f in args:
if f == "/appearance":
data = u.read_file("", self.data_dir + "/appearance")
self.ast[c.APPEARANCE] = self.cparser.parse(data)
elif f == "/buttons":
data = u.read_file("", self.data_dir + "/buttons")
self.ast[c.BUTTONS] = self.cparser.parse(data)
elif f == "/keys":
data = u.read_file("", self.data_dir + "/keys")
self.ast[c.KEYS] = self.cparser.parse(data)
elif f == "/rules":
data = u.read_file("", self.data_dir + "/rules")
self.ast[c.RULES] = self.cparser.parse(data)
def table_appearance(self):
if self.tabular_appearance:
return
for var in self.ast[c.APPEARANCE]:
if not isinstance(var.init, c_ast.InitList):
self.tabular_appearance.append([var.name, var.init.value])
else:
t = u.print_ast_to_c(var.init)
self.tabular_appearance.append(t.strip("\n").split(", "))
def table_keys(self):
if self.tabular_keys:
return
for var in self.ast[c.KEYS]:
if isinstance(var, c_ast.Typedef):
continue
for i in var.init.exprs:
t = u.print_ast_to_c(i)
params = t.strip("\n").split(", ", maxsplit=2)
if params[-1] in keys_dict:
params[-1] = keys_dict[params[-1]]
else:
params[-1] = self.parse_action(params[-1])
self.tabular_keys.append(params)
def table_buttons(self):
if self.tabular_buttons:
return
for var in self.ast[c.BUTTONS]:
if isinstance(var, c_ast.Typedef):
continue
for i in var.init.exprs:
t = u.print_ast_to_c(i)
params = t.strip("\n").split(", ", maxsplit=3)
if params[-1] in buttons_dict:
params[-1] = buttons_dict[params[-1]]
else:
params[-1] = self.parse_action(params[-1])
self.tabular_buttons.append(params)
def table_rules(self):
if self.tabular_rules:
return
for var in self.ast[c.RULES]:
if isinstance(var, c_ast.Typedef):
continue
for i in var.init.exprs:
t = u.print_ast_to_c(i)
params = t.strip("\n").split(", ")
self.tabular_rules.append(params)
def make_action(self, command):
if "TERM" in command:
command = command[4:].strip("()")
is_terminal = True
else:
is_terminal = False
cmd = 'spawn, SHCMD('
if is_terminal:
cmd += f'MAKETERM(TERMINAL, " -e {command}"))'
else:
cmd += f'"{command}")'
return cmd
def parse_action(self, command):
cmd = ""
if "MAKETERM" in command:
command = command.replace(" -e ", "").split('"')
cmd += "TERM(" + command[1] + ")"
else:
command = command.split('"')
cmd = command[1]
return cmd
def make_tables(self):
self.table_appearance()
self.table_buttons()
self.table_keys()
self.table_rules()
def which_table(self, arg, argval):
os.system("tput setaf 51")
if "app" in argval or argval == "font":
self.update_appearance()
self.table_appearance()
if arg == "show":
self.print_appearance()
elif arg == "change" and argval == "appr":
self.change_appearance_nonfont()
elif arg == "change" and argval == "font":
self.change_font(False)
elif arg == "add" and argval == "font":
self.change_font(True)
elif arg == "delete" and argval == "font":
self.delete_attr(self.tabular_appearance)
elif "key" in argval:
self.update_keys()
self.table_keys()
if arg == "show":
self.print_keys()
elif arg == "change":
self.change_key(False)
elif arg == "add":
self.change_key(True)
elif arg == "delete":
self.delete_attr(self.tabular_keys)
elif "button" in argval:
self.update_buttons()
self.table_buttons()
if arg == "show":
self.print_buttons()
elif arg == "change":
self.change_button(False)
elif arg == "add":
self.change_button(True)
elif arg == "delete":
self.delete_attr(self.tabular_buttons)
else:
self.update_rules()
self.table_rules()
if arg == "show":
self.print_rules()
elif arg == "change":
self.change_rule(False)
elif arg == "add":
self.change_rule(True)
elif arg == "delete":
self.delete_attr(self.tabular_rules)
def write_tmp_files(self):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
if self.tabular_appearance:
with open (self.cache_dir + "/appearance", "w", encoding = "utf-8") as a:
for data in self.tabular_appearance:
arr = ", ".join(data) + "\n"
if '"' in arr:
a.write("fonts, " + ", ".join(data) + "\n")
else:
a.write(", ".join(data) + "\n")
if self.tabular_keys:
with open (self.cache_dir + "/keys", "w", encoding = "utf-8") as a:
for data in self.tabular_keys:
a.write(", ".join(data) + "\n")
if self.tabular_buttons:
with open (self.cache_dir + "/buttons", "w", encoding = "utf-8") as a:
for data in self.tabular_buttons:
a.write(", ".join(data) + "\n")
if self.tabular_rules:
with open (self.cache_dir + "/rules", "w", encoding = "utf-8") as a:
for data in self.tabular_rules:
a.write(", ".join(data) + "\n")
def update_appearance(self):
a = open(self.cache_dir + "/appearance", "r", encoding = "utf-8")
for cur_attr in self.ast[c.APPEARANCE]:
line_val = a.readline().strip("\n").split(", ")
if len(line_val) <= 2:
cur_attr.init.value = line_val[1]
else:
cur_attr.init.exprs.clear()
for j in range(1, len(line_val)):
t = self.cparser.parse("const char *x = " + line_val[j] + ";")
cur_attr.init.exprs.append(t.ext[0].init)
a.close()
def update_keys(self):
for cur_attr in self.ast[c.KEYS]:
cur_attr.init.exprs.clear()
if isinstance(cur_attr, c_ast.Typedef):
continue
with open(self.cache_dir + "/keys", "r", encoding = "utf-8") as a:
for l in a:
arr = l.strip("\n").split(", ", maxsplit=2)
if arr[-1] in keys_dict.values():
arr[-1] = u.get_key_from_value(keys_dict, arr[-1])
else:
arr[-1] = self.make_action(arr[-1])
arr = ", ".join(arr)
line_val = "struct Key key = {" + arr + "};"
ast = self.cparser.parse(line_val)
cur_attr.init.exprs.append(ast.ext[0].init)
def update_buttons(self):
for cur_attr in self.ast[c.BUTTONS]:
cur_attr.init.exprs.clear()
if isinstance(cur_attr, c_ast.Typedef):
continue
with open(self.cache_dir + "/buttons", "r", encoding = "utf-8") as a:
for l in a:
arr = l.strip("\n").split(", ", maxsplit=3)
if arr[-1] in buttons_dict.values():
arr[-1] = u.get_key_from_value(buttons_dict, arr[-1])
else:
arr[-1] = self.make_action(arr[-1])
arr = ", ".join(arr)
line_val = "struct Button button = {" + arr + "};"
ast = self.cparser.parse(line_val)
cur_attr.init.exprs.append(ast.ext[0].init)
def update_rules(self):
for cur_attr in self.ast[c.RULES]:
cur_attr.init.exprs.clear()
if isinstance(cur_attr, c_ast.Typedef):
continue
with open(self.cache_dir + "/rules", "r", encoding = "utf-8") as a:
for l in a:
arr = l.strip("\n")
line_val = "struct Rule rule = {" + arr + "};"
ast = self.cparser.parse(line_val)
cur_attr.init.exprs.append(ast.ext[0].init)
def update(self):
self.update_appearance()
self.update_buttons()
self.update_keys()
self.update_rules()
def change_appearance_nonfont(self):
t1 = tabulate.tabulate(self.tabular_appearance[:-1], tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
os.system("tput setaf 51")
try:
inp = int(input(f"Set value for {self.tabular_appearance[idx][0]}: "))
if inp < 0:
raise ValueError
os.system("tput sgr0")
self.tabular_appearance[idx][1] = str(inp)
self.write_tmp_files()
except ValueError:
print("Please enter an integer number")
def change_button(self, isappend):
buttons = ["LeftClick", "RightClick", "MiddleClick", "WheelUp", "WheelDown"]
if isappend:
add_button = []
events = ["ClkStatusText", "ClkRootWin", "ClkClientWin", "ClkLtSymbol", "ClkTagBar"]
term_menu = TerminalMenu(events, title="Select event window:")
eventidx = term_menu.show()
add_button.append(events[eventidx])
new_button = input("Please enter the new modifier (Win, Alt, Shift, Control), you can add combinations with '|'.\nGive empty input for no modifier.\n")
new_button = "0" if new_button == "" else new_button
add_button.append(new_button)
term_menu = TerminalMenu(buttons)
new_button = buttons[term_menu.show()]
add_button.append(new_button)
events = ["ADD NEW ACTION (spawn a command)"]
events.extend(list(buttons_dict.values()))
term_menu = TerminalMenu(events, title="Select action:")
eventidx = term_menu.show()
if eventidx != 0:
add_button.append(events[eventidx])
else:
is_term = input("Will this command run on a terminal? [y|yes or n|no, empty input is no]\n")
if is_term != "y" and is_term != "" and is_term != "yes" and is_term != "n" and is_term != "no":
sys.stderr("Please input a valid argument.")
exit(1)
is_term = True if is_term == "y" or is_term == "yes" else False
command = input("Please enter your command.\n")
add_button.append(command if not is_term else "TERM(" + command + ")")
self.tabular_buttons.append(add_button)
self.write_tmp_files()
else:
t1 = tabulate.tabulate(self.tabular_buttons, tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
events = ["ClkStatusText", "ClkRootWin", "ClkClientWin", "ClkLtSymbol", "ClkTagBar"]
term_menu = TerminalMenu(events, title="Select event window:")
eventidx = term_menu.show()
self.tabular_buttons[idx][0] = events[eventidx]
new_button = input("Please enter the new modifier (Win, Alt, ShiftMask), you can add combinations with '|'.\nGive empty input for no modifier.\n")
new_button = "0" if new_button == "" else new_button
self.tabular_buttons[idx][1] = new_button
term_menu = TerminalMenu(buttons)
new_button = buttons[term_menu.show()]
self.tabular_buttons[idx][2] = new_button
self.write_tmp_files()
def change_font(self, isappend):
if isappend:
cur_fonts = [[f'{i} = {self.tabular_appearance[-1][i]}'] for i in range(len(self.tabular_appearance[-1]))]
os.system("tput setaf 51")
fonts = subprocess.check_output("fc-list : family style | sed '/\\,/d'", shell=True, text=True).strip("\n").split("\n")
term_menu = TerminalMenu(fonts, title="Please select a font:")
termidx = term_menu.show()
try:
size = int(input("Please set font size (int): "))
if size < 0:
raise ValueError
font = '"' + fonts[termidx] + f":size={size}" + '"'
self.tabular_appearance[-1].append(font)
print("Current fonts:")
print(tabulate.tabulate(cur_fonts, tablefmt="fancy_grid"))
idx = input("Please choose an index and press 'Enter' to add the new font. Empty input appends the font.\n")
if idx == "":
self.write_tmp_files()
return
idx = int(idx)
if idx < 0:
raise ValueError
else:
idx = idx if idx < len(self.tabular_appearance[-1]) else len(self.tabular_appearance[-1]) - 1
self.tabular_appearance[-1][-1], self.tabular_appearance[-1][idx] = \
self.tabular_appearance[-1][idx], self.tabular_appearance[-1][-1]
self.write_tmp_files()
except ValueError:
print("Please enter an integer greater than 0.")
else:
fonts = [[i] for i in self.tabular_appearance[-1]]
t2 = tabulate.tabulate(fonts, tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t2, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
os.system("tput setaf 51")
fonts = subprocess.check_output("fc-list : family style | sed '/\\,/d'", shell=True, text=True).strip("\n").split("\n")
term_menu = TerminalMenu(fonts, title="Please select a font:")
termidx = term_menu.show()
try:
size = int(input("Please set font size (int): "))
if size < 0:
raise ValueError
font = '"' + fonts[termidx] + f":size={size}" + '"'
self.tabular_appearance[len(self.tabular_appearance) - 1][idx] = font
self.write_tmp_files()
except ValueError:
print("Please enter an integer greater than 0.")
def change_key(self, isappend):
if isappend:
add_key = []
print("All keys must be prefixed with XK_[key].")
print("Example: XK_a for 'a'. Don't use capital letters.")
print("Use 'Shift' in modifier section for binding capital letters.")
new_key = input("Please enter the new modifier (Win, Alt, Shift, Control), you can add combinations with '|'.\nGive empty input for no modifier.\n")
new_key = "0" if new_key == "" else new_key
add_key.append(new_key)
new_key = input("Please enter the new key/keys.\n")
add_key.append(new_key)
events = ["ADD NEW ACTION (spawn a terminal command)"]
events.extend(list(keys_dict.values()))
term_menu = TerminalMenu(events, title="Select action:")
eventidx = term_menu.show()
if eventidx != 0:
add_key.append(events[eventidx])
else:
is_term = input("Will this command run on a terminal? [y|yes or n|no, empty input is no]\n")
if is_term != "y" and is_term != "" and is_term != "yes" and is_term != "n" and is_term != "no":
sys.stderr("Please input a valid argument.")
exit(1)
is_term = True if is_term == "y" or is_term == "yes" else False
command = input("Please enter your command.\n")
add_key.append(command if not is_term else "TERM(" + command + ")")
self.tabular_keys.append(add_key)
self.write_tmp_files()
else:
t1 = tabulate.tabulate(self.tabular_keys, tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
new_key = input("Please enter the new modifier (Win, Alt, ShiftMask), you can add combinations with '|'.\nGive empty input for no modifier.\n")
self.tabular_keys[idx][0] = new_key
new_key = input("Please enter the new key, you can add multiple keys with '|'.\n")
self.tabular_keys[idx][1] = new_key
self.write_tmp_files()
def change_rule(self, isappend):
if not isappend:
t1 = tabulate.tabulate(self.tabular_rules, tablefmt="fancy_grid").split("\n")
term_menu = TerminalMenu(t1, skip_empty_entries=True, cursor_index=1)
idx = term_menu.show()
idx //= 2
print("Please click a window to parse class name.")
class_name, instance = subprocess.check_output("xprop | grep 'WM_CLASS' | tr -d ',' | awk '{print $NF,$(NF-1)}'", shell=True, text=True).strip("\n ").split(" ")
new_rule = [class_name, instance, "NULL", "0", "0", "0", "0", "0", "0", "-1"]
print(class_name)
try:
tags = input("tagsmask: Input a number between 1-9 to force open it in the given tag number. 0 or enter for default.\n")
tags = 0 if tags == "" else int(tags)
if tags < 0 or tags > 9:
raise ValueError
new_rule[3] = f"1 << {tags - 1}"
isfloating = input("isfloating: Input '1' to open your application in floating mode. Enter or 0 for default.\n")
isfloating = 0 if isfloating == "" else int(isfloating)
if isfloating < 0 or isfloating > 1:
raise ValueError
new_rule[4] = str(isfloating)
isfloating = input("isterminal: Input '1' to run application in terminal. Enter or 0 for default.\n")
isfloating = 0 if isfloating == "" else int(isfloating)
if isfloating < 0 or isfloating > 1:
raise ValueError
new_rule[5] = str(isfloating)
isfloating = input("iscentered: Input '1' to position the application in the center of the screen. Enter or 0 for default.\n")
isfloating = 0 if isfloating == "" else int(isfloating)
if isfloating < 0 or isfloating > 1:
raise ValueError
new_rule[6] = str(isfloating)
isfloating = input("noswallow: Input '1' to prevent the application from swallowing. Enter or 0 for default.\n")
isfloating = 0 if isfloating == "" else int(isfloating)
if isfloating < 0 or isfloating > 1:
raise ValueError
new_rule[7] = str(isfloating)
isfloating = input("managedsize: Input '1' to allow dwm to set window size. Useful for floating windows if the base size is not sufficient.\nEnter or 0 for default.\n")
isfloating = 0 if isfloating == "" else int(isfloating)
if isfloating < 0 or isfloating > 1:
raise ValueError
new_rule[8] = str(isfloating)
print("Changing monitor will come soon.")
if isappend:
self.tabular_rules.append(new_rule)
else:
self.tabular_rules[idx] = new_rule
self.write_tmp_files()
except ValueError:
print("Please enter a valid number.")
def print_appearance(self):
t1 = tabulate.tabulate(self.tabular_appearance[:-1], tablefmt="fancy_grid").split("\n")
fonts = [[i] for i in self.tabular_appearance[-1]]
t2 = tabulate.tabulate(fonts, stralign="center", headers=["FONTS"], tablefmt="fancy_grid").split("\n")
min_start = min(len(t1), len(t2))
if len(t1) < len(t2):
t1, t2 = t2, t1
for c1, c2 in zip(t1, t2):
print(c1 + "\t" + c2)
for c in t1[min_start:]:
print(c)
def print_buttons(self):
h = ["CLICK WIN", "MODIFIERS", "BUTTON", "ACTION"]
print(tabulate.tabulate(self.tabular_buttons, headers=h, tablefmt="fancy_grid"))
def print_keys(self):
h = ["MODIFIERS", "KEY", "ACTION"]
print(tabulate.tabulate(self.tabular_keys, headers=h, tablefmt="fancy_grid"))
def print_rules(self):
h = ["CLASS", "INSTANCE", "TITLE", "TAGS", "ISFLOATING", "ISTERMINAL", "ISCENTERED", "NOSWALLOW", "MANAGEDSIZE", "MON"]
print(tabulate.tabulate(self.tabular_rules, headers=h, tablefmt="fancy_grid"))
def save_config(self):
a = self.data_dir + "/appearance"
k = self.data_dir + "/keys"
b = self.data_dir + "/buttons"
r = self.data_dir + "/rules"
with open(a, "w", encoding="utf-8") as f:
f.write(u.print_ast_to_c(self.ast[c.APPEARANCE]))
with open(k, "w", encoding="utf-8") as f:
f.write(u.print_ast_to_c(self.ast[c.KEYS]))
with open(b, "w", encoding="utf-8") as f:
f.write(u.print_ast_to_c(self.ast[c.BUTTONS]))
with open(r, "w", encoding="utf-8") as f:
f.write(u.print_ast_to_c(self.ast[c.RULES]))