-
Notifications
You must be signed in to change notification settings - Fork 1
/
bspcq
executable file
·380 lines (290 loc) · 10.9 KB
/
bspcq
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
#! /usr/bin/env python3.10
from argparse import ArgumentParser, Namespace
from json import loads
from os import linesep
from subprocess import run as run_sys
from typing import Any, Dict, List, Tuple
from rich import print
from rich.tree import Tree
def config() -> ArgumentParser:
argparser = ArgumentParser(
description="parses JSON output from 'bspc query' to provide a user\
friendly visual representation of the BSP tree. See 'man bspc' for\
more info. 'bspcq' can be used in a similar fashion to 'bspc\
query', for example: 'bspcq -N -n 123456', or 'bspcq -N' for all\
node BSP tree(s).",
)
argparser.add_argument(
"-m",
"--monitor",
nargs="*",
metavar="M",
help="query for monitor(s), given an identifier. See 'man bspc' for\
more information.",
)
argparser.add_argument(
"-d",
"--desktop",
nargs="*",
metavar="D",
help="query for desktop(s), given an identifier. See 'man bspc' for\
more information.",
)
argparser.add_argument(
"-n",
"--node",
"-w",
"--window",
nargs="*",
metavar="N",
help="query for node(s), or window(s), given an identifier. See 'man\
bspc' for more information.",
)
argparser.add_argument(
"-M",
"--monitors",
action="store_true",
help="exclusively print the monitor node(s) of the BSP tree - excludes\
all child nodes.",
)
argparser.add_argument(
"-D",
"--desktops",
action="store_true",
help="exclusively print the desktop node(s) of the BSP tree - excludes\
all child nodes.",
)
argparser.add_argument(
"-N",
"--nodes",
"-W",
"--windows",
action="store_true",
help="exclusively print the node/window node(s) of the BSP tree.",
)
argparser.add_argument(
"-j",
"--json",
nargs="?",
type=str,
metavar="J",
help="provide the data to be analyzed instead of letting 'bspcq' call\
'bspc query'.",
)
argparser.add_argument(
"-s",
"--simple",
action="store_true",
help="print a simplified view of the BSP tree.",
)
return argparser
def run() -> None:
args: Namespace = config().parse_args()
# When passed json, we'll just analyze it and give it back.
if args.json:
return print(analyze_bsp_tree(args.json, args.simple))
bsp_trees: List[Dict[str, Any]] = query(args)
# These args provide behaviour constraints - the user may define the domain
# that they are interested in, which means only information pertaining to
# that domain will be output.
if args.monitors:
return print_monitors(bsp_trees, args.simple)
if args.desktops:
return print_desktops(bsp_trees, args.simple)
if args.nodes:
return print_nodes(bsp_trees, args.node, args.desktop, args.simple)
for bsp_tree in bsp_trees:
full_tree = analyze_bsp_tree(bsp_tree, args.simple)
print(full_tree)
return
def query(args: Namespace) -> List[Dict[str, Any]]:
# Determine how to run `bspc query` - the user will be able to pass
# multiple optional arguments (`-n 123 -d 456`) but we will perform a
# `node` query in as there is an order of preference.
query: Tuple[str, List[Any]]
if args.monitor or args.desktop or args.node:
if args.node:
query = ("node", args.node)
elif args.desktop:
query = ("desktop", args.desktop)
else:
query = ("monitor", args.monitor)
return bspc_query(query[0], query[1])
else:
return bspc_query("all")
def print_monitors(bsp_trees: List[Dict[str, Any]], simple: bool) -> None:
for tree in bsp_trees:
print(analyze_monitor(tree, simple)[1])
def print_desktops(bsp_trees: List[Dict[str, Any]], simple: bool) -> None:
for tree in bsp_trees:
desktops = analyze_monitor(tree, simple)[0]
for desktop_tree in desktops:
print(analyze_desktop(desktop_tree, simple)[1])
def print_nodes(
bsp_trees: List[Dict[str, Any]],
only_nodes: bool,
with_desktops: bool,
simple: bool,
) -> None:
def analyze_and_print_nodes(tree: Dict[str, Any], simple: bool):
for node_tree in analyze_nodes(tree, simple)[1]:
print(node_tree)
def analyze_and_print_desktops(tree: Dict[str, Any], simple: bool):
nodes = analyze_desktop(tree, simple)[0]
if nodes is not None:
analyze_and_print_nodes(nodes, simple)
for tree in bsp_trees:
if only_nodes:
analyze_and_print_nodes(tree, simple)
elif with_desktops:
analyze_and_print_desktops(tree, simple)
else:
desktops = analyze_monitor(tree, simple)[0]
for desktop_tree in desktops:
analyze_and_print_desktops(desktop_tree, simple)
def bspc_query(
domain: str, identifiers: List[Any] = []
) -> List[Dict[str, Any]]:
cmd = ["bspc", "query"]
bsp_trees: List[Dict[str, Any]] = []
if domain == "all":
monitors_cmd = cmd.copy()
monitors_cmd.extend(["-M"])
monitors = run_cmd(monitors_cmd).split(linesep)
for monitor in monitors:
monitor_cmd = cmd.copy()
monitor_cmd.extend(["-T", "-m", f"{monitor}"])
bsp_trees.append(loads(run_cmd(monitor_cmd)))
else:
for identifier in identifiers:
cmd.extend(["-T", f"--{domain}", identifier])
try:
bsp_trees.append(loads(run_cmd(cmd)))
except Exception:
print("`" + " ".join(cmd) + "` returned no results.")
return bsp_trees
def run_cmd(cmd: List[str]) -> str:
return run_sys(cmd, capture_output=True).stdout.decode("utf-8").rstrip()
def analyze_bsp_tree(bsp_tree: Dict[str, Any], simple: bool) -> Tree:
# If `desktops` exists, we loop through each.
if bsp_tree.get("desktops"):
tree = analyze_monitor(bsp_tree, simple)[1]
desktop: Dict[str, Any]
for desktop in bsp_tree["desktops"]:
desktop_tree = tree.add(analyze_desktop(desktop, simple)[1])
# Absence of a `root` means the desktop is not occupied by any
# `node`s.
nodes: dict[str, Any] | None = desktop["root"]
if nodes is not None:
for node_tree in analyze_nodes(nodes, simple)[1]:
desktop_tree.add(node_tree)
# Otherwise, we're only dealing with a single desktop.
else:
tree = Tree(bsp_tree["name"]).add(analyze_desktop(bsp_tree, simple)[1])
# Absence of a `root` means the desktop is not occupied by any `node`s.
nodes: dict[str, Any] | None = bsp_tree["root"]
if nodes is not None:
for node_tree in analyze_nodes(nodes, simple)[1]:
tree.add(node_tree)
return tree
def analyze_monitor(
bsp_tree: Dict[str, Any], simple: bool
) -> Tuple[List[Dict[str, Any]], Tree]:
label = " ".join(
[
"[bold cyan]M[/bold cyan]:",
"[bold]{id}[/bold]".format(id=bsp_tree["id"]),
"{name}".format(name=bsp_tree["name"]),
]
)
temp = bsp_tree.copy()
temp["desktops"] = None
return (
bsp_tree["desktops"] if bsp_tree.get("desktops") else bsp_tree,
make_tree(label, temp, simple),
)
def analyze_desktop(
bsp_tree: Dict[str, Any], simple: bool
) -> Tuple[Dict[str, Any], Tree]:
label = " ".join(
[
"[bold green]D[/bold green]:",
"[bold]{id}[/bold]".format(id=bsp_tree["id"]),
"{name}".format(name=bsp_tree["name"]),
]
)
temp = bsp_tree.copy()
temp["root"] = None
return (bsp_tree["root"], make_tree(label, temp, simple))
def analyze_nodes(
bsp_tree: Dict[str, Any], simple: bool
) -> Tuple[List[Dict[str, Any]], List[Tree]]:
bsp_trees: List[Dict[str, Any]] = []
tree_list: List[Tree] = []
for node in traverse_nodes(bsp_tree, []):
# If a client exists, we've got an occupied node - if we don't, we've
# got a receptable.
client = node.get("client")
name = client["className"] if client else "receptacle"
label = " ".join(
[
"[bold yellow]N[/bold yellow]:",
"[bold]{id}[/bold]".format(id=node["id"]),
"{name}".format(name=name),
"[italic]{xtitle}[/italic]".format(xtitle=node["xtitle"]),
]
)
tree_list.append(make_tree(label, node, simple))
bsp_trees.append(node)
return (bsp_trees, tree_list)
def traverse_nodes(
bsp_tree: Dict[str, Any], nodes: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""`bspwm` is simple, but it isn't easy. -zyk
Probably the most complex piece of the puzzle - we repeatedly
`recurse_nodes` here, since in theory we can have an infinite number of
`node`s.
"""
# Absence of `firstChild` means there is only a single active `node` on the
# `desktop`, so we don't have to go fishing for children.
if bsp_tree["firstChild"] is None:
title = run_cmd(["xtitle", "{id}".format(id=bsp_tree["id"])])
bsp_tree["xtitle"] = title
nodes.append(bsp_tree)
elif bsp_tree["firstChild"].get("client"):
node_id = bsp_tree["firstChild"]["id"]
title = run_cmd(["xtitle", f"{node_id}"])
bsp_tree["firstChild"]["xtitle"] = title
nodes.append(bsp_tree["firstChild"])
# In the event that there is a `firstChild`, there will be a
# `secondChild`. A `secondChild` can have a `firstChild`, and so on.
traverse_nodes(bsp_tree["secondChild"], nodes)
else:
traverse_nodes(bsp_tree["firstChild"], nodes)
return nodes
def traverse_tree(iterable: List[Any] | Dict[str, Any], tree: Tree) -> Tree:
"""Recursively iterate over a List or Dict and populate a `Tree`."""
def format_val(val: Any) -> str:
return f"'[bold]{val}[/bold]'"
if type(iterable) is dict:
for key, val in iterable.items():
if val is None:
continue
elif type(val) is dict or type(val) is list:
if val.__len__() > 0:
traverse_tree(val, tree.add(f"[bold]{key}[/bold]"))
else:
tree.add(f"[italic]{key}[/italic] {format_val(val)}")
elif type(iterable) is list:
for el in iterable:
if el is None:
continue
elif type(el) is dict or type(el) is list:
if el.__len__() > 0:
traverse_tree(el, tree)
else:
tree.add(format_val(el))
return tree
def make_tree(label: str, bsp_tree: Dict[str, Any], simple: bool) -> Tree:
return Tree(label) if simple else traverse_tree(bsp_tree, Tree(label))
run()